From e0eba8ce21af8a428333c75dc9d89bf3296162e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Sun, 29 Mar 2026 09:28:49 +0800 Subject: [PATCH] Chore: run clang-format ```bash find . -type f \( -name "*.c" -o -name "*.h" -o -name "*.cpp" -o -name "*.hpp" \) ! -path "src/3rdparty/*" -print0 | xargs -0 clang-format -i ``` --- src/common/FFPlatform.h | 12 +- src/common/FFcheckmacros.h | 24 +- src/common/FFlist.h | 88 +- src/common/FFstrbuf.h | 320 ++-- src/common/apple/cf_helpers.c | 173 +- src/common/apple/cf_helpers.h | 17 +- src/common/apple/smc_temps.c | 509 +++--- src/common/apple/smc_temps.h | 6 +- src/common/argType.h | 37 +- src/common/arrayUtils.h | 16 +- src/common/base64.h | 10 +- src/common/dbus.h | 19 +- src/common/debug.h | 24 +- src/common/ffdata.h | 16 +- src/common/font.h | 6 +- src/common/format.h | 3 +- src/common/haiku/version.cpp | 14 +- src/common/impl/FFPlatform.c | 41 +- src/common/impl/FFPlatform_unix.c | 340 ++-- src/common/impl/FFPlatform_windows.c | 247 ++- src/common/impl/FFlist.c | 18 +- src/common/impl/FFstrbuf.c | 609 ++++--- src/common/impl/base64.c | 92 +- src/common/impl/binary_apple.c | 175 +- src/common/impl/binary_linux.c | 70 +- src/common/impl/binary_windows.c | 41 +- src/common/impl/commandoption.c | 184 +-- src/common/impl/dbus.c | 153 +- src/common/impl/debug_windows.c | 18 +- src/common/impl/duration.c | 71 +- src/common/impl/edidHelper.c | 127 +- src/common/impl/font.c | 326 ++-- src/common/impl/format.c | 270 ++-- src/common/impl/frequency.c | 21 +- src/common/impl/init.c | 303 ++-- src/common/impl/io_unix.c | 218 ++- src/common/impl/io_windows.c | 283 ++-- src/common/impl/jsonconfig.c | 299 ++-- src/common/impl/kmod_apple.c | 3 +- src/common/impl/kmod_bsd.c | 3 +- src/common/impl/kmod_linux.c | 14 +- src/common/impl/kmod_nbsd.c | 25 +- src/common/impl/kmod_nosupport.c | 3 +- src/common/impl/kmod_sunos.c | 9 +- src/common/impl/kmod_windows.c | 15 +- src/common/impl/library.c | 129 +- src/common/impl/memrchr.c | 14 +- src/common/impl/netif.c | 10 +- src/common/impl/netif_apple.c | 135 +- src/common/impl/netif_bsd.c | 91 +- src/common/impl/netif_gnu.c | 17 +- src/common/impl/netif_haiku.c | 69 +- src/common/impl/netif_linux.c | 147 +- src/common/impl/netif_windows.c | 43 +- src/common/impl/networking_common.c | 72 +- src/common/impl/networking_linux.c | 340 ++-- src/common/impl/networking_windows.c | 182 +-- src/common/impl/option.c | 151 +- src/common/impl/parsing.c | 104 +- src/common/impl/path.c | 187 +-- src/common/impl/percent.c | 236 ++- src/common/impl/printing.c | 115 +- src/common/impl/processing_linux.c | 567 +++---- src/common/impl/processing_windows.c | 207 ++- src/common/impl/properties.c | 128 +- src/common/impl/settings.c | 300 ++-- src/common/impl/size.c | 20 +- src/common/impl/smbiosHelper.c | 343 ++-- src/common/impl/sysctl.c | 54 +- src/common/impl/temps.c | 109 +- src/common/impl/time.c | 62 +- src/common/impl/wcwidth.c | 3 +- src/common/io.h | 257 ++- src/common/jsonconfig.h | 16 +- src/common/library.h | 132 +- src/common/mallocHelper.h | 43 +- src/common/netif.h | 8 +- src/common/networking.h | 24 +- src/common/option.h | 33 +- src/common/parsing.h | 6 +- src/common/path.h | 13 +- src/common/percent.h | 6 +- src/common/printing.h | 3 +- src/common/processing.h | 30 +- src/common/properties.h | 37 +- src/common/settings.h | 8 +- src/common/smbiosHelper.h | 20 +- src/common/stringUtils.h | 71 +- src/common/textModifier.h | 2 +- src/common/thread.h | 188 ++- src/common/time.h | 83 +- src/common/unused.h | 8 +- src/common/wcwidth.h | 2 +- src/common/windows/com.cpp | 22 +- src/common/windows/com.hpp | 15 +- src/common/windows/getline.c | 10 +- src/common/windows/getline.h | 2 +- src/common/windows/nt.h | 366 ++--- src/common/windows/perflib_.h | 140 +- src/common/windows/registry.c | 248 ++- src/common/windows/registry.h | 70 +- src/common/windows/unicode.c | 18 +- src/common/windows/unicode.h | 42 +- src/common/windows/unicode.hpp | 15 +- src/common/windows/util.hpp | 10 +- src/common/windows/variant.cpp | 3 +- src/common/windows/variant.hpp | 127 +- src/common/windows/version.c | 51 +- src/common/windows/version.h | 1 - src/common/windows/wmi.cpp | 263 +-- src/common/windows/wmi.hpp | 62 +- src/detection/battery/battery.h | 3 +- src/detection/battery/battery_android.c | 105 +- src/detection/battery/battery_apple.c | 67 +- src/detection/battery/battery_bsd.c | 61 +- src/detection/battery/battery_haiku.c | 44 +- src/detection/battery/battery_linux.c | 142 +- src/detection/battery/battery_nbsd.c | 66 +- src/detection/battery/battery_nosupport.c | 3 +- src/detection/battery/battery_obsd.c | 27 +- src/detection/battery/battery_windows.c | 203 +-- src/detection/bios/bios.h | 3 +- src/detection/bios/bios_android.c | 9 +- src/detection/bios/bios_apple.c | 36 +- src/detection/bios/bios_bsd.c | 16 +- src/detection/bios/bios_linux.c | 15 +- src/detection/bios/bios_nbsd.c | 12 +- src/detection/bios/bios_nosupport.c | 3 +- src/detection/bios/bios_windows.c | 87 +- src/detection/bluetooth/bluetooth.h | 3 +- src/detection/bluetooth/bluetooth_bsd.c | 15 +- src/detection/bluetooth/bluetooth_haiku.cpp | 7 +- src/detection/bluetooth/bluetooth_linux.c | 141 +- src/detection/bluetooth/bluetooth_nosupport.c | 3 +- src/detection/bluetooth/bluetooth_windows.c | 77 +- src/detection/bluetooth/bluetooth_windows.cpp | 63 +- src/detection/bluetoothradio/bluetoothradio.c | 159 +- src/detection/bluetoothradio/bluetoothradio.h | 3 +- .../bluetoothradio/bluetoothradio_linux.c | 81 +- .../bluetoothradio/bluetoothradio_nosupport.c | 3 +- .../bluetoothradio/bluetoothradio_windows.c | 44 +- src/detection/board/board.h | 3 +- src/detection/board/board_android.c | 6 +- src/detection/board/board_apple.c | 20 +- src/detection/board/board_bsd.c | 3 +- src/detection/board/board_linux.c | 24 +- src/detection/board/board_nbsd.c | 15 +- src/detection/board/board_nosupport.c | 3 +- src/detection/board/board_windows.c | 32 +- src/detection/bootmgr/bootmgr.c | 34 +- src/detection/bootmgr/bootmgr.h | 3 +- src/detection/bootmgr/bootmgr_apple.c | 33 +- src/detection/bootmgr/bootmgr_bsd.c | 34 +- src/detection/bootmgr/bootmgr_linux.c | 17 +- src/detection/bootmgr/bootmgr_nosupport.c | 3 +- src/detection/bootmgr/bootmgr_windows.c | 44 +- src/detection/bootmgr/efi_helper.h | 6 +- src/detection/brightness/brightness.h | 3 +- src/detection/brightness/brightness_apple.c | 128 +- src/detection/brightness/brightness_bsd.c | 30 +- src/detection/brightness/brightness_linux.c | 124 +- src/detection/brightness/brightness_nbsd.c | 10 +- .../brightness/brightness_nosupport.c | 3 +- src/detection/brightness/brightness_obsd.c | 12 +- .../brightness/brightness_windows.cpp | 111 +- src/detection/btrfs/btrfs.h | 6 +- src/detection/btrfs/btrfs_linux.c | 145 +- src/detection/btrfs/btrfs_nosupport.c | 3 +- src/detection/camera/camera.h | 3 +- src/detection/camera/camera_android.c | 37 +- src/detection/camera/camera_linux.c | 82 +- src/detection/camera/camera_nosupport.c | 3 +- src/detection/camera/camera_windows.cpp | 104 +- src/detection/chassis/chassis.c | 117 +- src/detection/chassis/chassis.h | 3 +- src/detection/chassis/chassis_apple.c | 17 +- src/detection/chassis/chassis_bsd.c | 3 +- src/detection/chassis/chassis_linux.c | 26 +- src/detection/chassis/chassis_nbsd.c | 15 +- src/detection/chassis/chassis_nosupport.c | 3 +- src/detection/chassis/chassis_windows.c | 34 +- src/detection/command/command.c | 48 +- src/detection/cpu/cpu.c | 389 ++--- src/detection/cpu/cpu.h | 8 +- src/detection/cpu/cpu_apple.c | 116 +- src/detection/cpu/cpu_arm.h | 846 ++++++---- src/detection/cpu/cpu_bsd.c | 61 +- src/detection/cpu/cpu_haiku.c | 26 +- src/detection/cpu/cpu_linux.c | 896 ++++++----- src/detection/cpu/cpu_nbsd.c | 78 +- src/detection/cpu/cpu_nosupport.c | 3 +- src/detection/cpu/cpu_obsd.c | 70 +- src/detection/cpu/cpu_sunos.c | 96 +- src/detection/cpu/cpu_windows.c | 258 +-- src/detection/cpucache/cpucache.h | 20 +- src/detection/cpucache/cpucache_apple.c | 32 +- src/detection/cpucache/cpucache_linux.c | 87 +- src/detection/cpucache/cpucache_nosupport.c | 3 +- src/detection/cpucache/cpucache_shared.c | 66 +- src/detection/cpucache/cpucache_windows.c | 44 +- src/detection/cpuusage/cpuusage.c | 52 +- src/detection/cpuusage/cpuusage_apple.c | 20 +- src/detection/cpuusage/cpuusage_bsd.c | 32 +- src/detection/cpuusage/cpuusage_haiku.c | 12 +- src/detection/cpuusage/cpuusage_linux.c | 29 +- src/detection/cpuusage/cpuusage_nosupport.c | 3 +- src/detection/cpuusage/cpuusage_sunos.c | 18 +- src/detection/cpuusage/cpuusage_windows.c | 115 +- src/detection/cursor/cursor.h | 3 +- src/detection/cursor/cursor_linux.c | 70 +- src/detection/cursor/cursor_nosupport.c | 3 +- src/detection/cursor/cursor_windows.c | 14 +- src/detection/de/de_linux.c | 213 +-- src/detection/de/de_nosupport.c | 3 +- src/detection/disk/disk.c | 46 +- src/detection/disk/disk.h | 7 +- src/detection/disk/disk_bsd.c | 198 +-- src/detection/disk/disk_haiku.cpp | 55 +- src/detection/disk/disk_linux.c | 268 ++-- src/detection/disk/disk_nosupport.c | 3 +- src/detection/disk/disk_sunos.c | 104 +- src/detection/disk/disk_windows.c | 62 +- src/detection/diskio/diskio.c | 47 +- src/detection/diskio/diskio.h | 3 +- src/detection/diskio/diskio_apple.c | 27 +- src/detection/diskio/diskio_bsd.c | 80 +- src/detection/diskio/diskio_linux.c | 54 +- src/detection/diskio/diskio_nbsd.c | 15 +- src/detection/diskio/diskio_nosupport.c | 3 +- src/detection/diskio/diskio_obsd.c | 15 +- src/detection/diskio/diskio_sunos.c | 27 +- src/detection/diskio/diskio_windows.c | 70 +- src/detection/displayserver/displayserver.c | 12 +- src/detection/displayserver/displayserver.h | 30 +- .../displayserver/displayserver_android.c | 132 +- .../displayserver/displayserver_apple.c | 147 +- .../displayserver/displayserver_haiku.cpp | 28 +- .../displayserver/displayserver_windows.c | 148 +- src/detection/displayserver/linux/common.c | 16 +- .../displayserver/linux/displayserver_linux.c | 78 +- src/detection/displayserver/linux/drm.c | 312 ++-- .../linux/wayland/global-output.c | 94 +- .../kde-output-device-v2-client-protocol.h | 1426 ++++++++--------- .../wayland/kde-output-device-v2-protocol.c | 151 +- .../kde-output-order-v1-client-protocol.h | 51 +- .../wayland/kde-output-order-v1-protocol.c | 26 +- .../displayserver/linux/wayland/kde-output.c | 147 +- .../displayserver/linux/wayland/wayland.c | 221 ++- .../displayserver/linux/wayland/wayland.h | 30 +- ...t-management-unstable-v1-client-protocol.h | 980 ++++++----- ...r-output-management-unstable-v1-protocol.c | 173 +- .../xdg-output-unstable-v1-client-protocol.h | 292 ++-- .../wayland/xdg-output-unstable-v1-protocol.c | 50 +- .../displayserver/linux/wayland/zwlr-output.c | 107 +- src/detection/displayserver/linux/wmde.c | 396 ++--- src/detection/displayserver/linux/xcb.c | 212 ++- src/detection/displayserver/linux/xlib.c | 193 +-- src/detection/dns/dns_apple.c | 59 +- src/detection/dns/dns_linux.c | 88 +- src/detection/dns/dns_windows.c | 39 +- src/detection/editor/editor.c | 131 +- src/detection/editor/editor.h | 3 +- src/detection/font/font.c | 13 +- src/detection/font/font.h | 3 +- src/detection/font/font_haiku.cpp | 45 +- src/detection/font/font_linux.c | 18 +- src/detection/font/font_nosupport.c | 3 +- src/detection/font/font_windows.c | 55 +- src/detection/gamepad/gamepad.h | 3 +- src/detection/gamepad/gamepad_apple.c | 39 +- src/detection/gamepad/gamepad_bsd.c | 36 +- src/detection/gamepad/gamepad_haiku.cpp | 9 +- src/detection/gamepad/gamepad_linux.c | 56 +- src/detection/gamepad/gamepad_nosupport.c | 3 +- src/detection/gamepad/gamepad_windows.c | 193 +-- src/detection/gpu/adl.h | 14 +- src/detection/gpu/asahi_drm.h | 1366 ++++++++-------- src/detection/gpu/d3dkmthk.h | 421 +++-- src/detection/gpu/gpu.c | 124 +- src/detection/gpu/gpu.h | 23 +- src/detection/gpu/gpu_amd.c | 306 ++-- src/detection/gpu/gpu_android.c | 38 +- src/detection/gpu/gpu_apple.c | 153 +- src/detection/gpu/gpu_bsd.c | 176 +- src/detection/gpu/gpu_driver_specific.h | 68 +- src/detection/gpu/gpu_drm.c | 304 ++-- src/detection/gpu/gpu_gnu.c | 95 +- src/detection/gpu/gpu_haiku.c | 24 +- src/detection/gpu/gpu_intel.c | 151 +- src/detection/gpu/gpu_linux.c | 472 +++--- src/detection/gpu/gpu_mthreads.c | 145 +- src/detection/gpu/gpu_nbsd.c | 63 +- src/detection/gpu/gpu_nosupport.c | 3 +- src/detection/gpu/gpu_nvidia.c | 173 +- src/detection/gpu/gpu_obsd.c | 54 +- src/detection/gpu/gpu_pci.c | 218 +-- src/detection/gpu/gpu_sunos.c | 27 +- src/detection/gpu/gpu_windows.c | 303 ++-- src/detection/gpu/gpu_windows.cpp | 55 +- src/detection/gpu/gpu_wsl.c | 287 ++-- src/detection/gpu/igcl.h | 63 +- src/detection/gpu/intel_drm.h | 126 +- src/detection/gpu/mtml.h | 44 +- src/detection/gpu/nvapi.h | 15 +- src/detection/gpu/nvml.h | 10 +- src/detection/gtk_qt/gtk.c | 127 +- src/detection/gtk_qt/gtk_qt.h | 6 +- src/detection/gtk_qt/qt.c | 152 +- src/detection/host/host.h | 3 +- src/detection/host/host_android.c | 23 +- src/detection/host/host_apple.c | 44 +- src/detection/host/host_bsd.c | 7 +- src/detection/host/host_linux.c | 82 +- src/detection/host/host_mac.c | 585 +++++-- src/detection/host/host_nbsd.c | 18 +- src/detection/host/host_nosupport.c | 3 +- src/detection/host/host_obsd.c | 15 +- src/detection/host/host_windows.c | 38 +- src/detection/icons/icons.h | 4 +- src/detection/icons/icons_linux.c | 12 +- src/detection/icons/icons_nosupport.c | 3 +- src/detection/icons/icons_windows.c | 26 +- src/detection/initsystem/initsystem.h | 3 +- src/detection/initsystem/initsystem_haiku.c | 15 +- src/detection/initsystem/initsystem_linux.c | 107 +- .../initsystem/initsystem_nosupport.c | 3 +- src/detection/keyboard/keyboard.h | 3 +- src/detection/keyboard/keyboard_apple.c | 20 +- src/detection/keyboard/keyboard_bsd.c | 45 +- src/detection/keyboard/keyboard_haiku.cpp | 14 +- src/detection/keyboard/keyboard_linux.c | 61 +- src/detection/keyboard/keyboard_nosupport.c | 3 +- src/detection/keyboard/keyboard_windows.c | 50 +- src/detection/libc/libc.h | 3 +- src/detection/libc/libc_android.c | 15 +- src/detection/libc/libc_apple.c | 3 +- src/detection/libc/libc_bsd.c | 11 +- src/detection/libc/libc_linux.c | 13 +- src/detection/libc/libc_nosupport.c | 3 +- src/detection/libc/libc_windows.cpp | 35 +- src/detection/lm/lm.h | 3 +- src/detection/lm/lm_linux.c | 120 +- src/detection/lm/lm_nosupport.c | 3 +- src/detection/loadavg/loadavg_bsd.c | 19 +- src/detection/loadavg/loadavg_linux.c | 23 +- src/detection/loadavg/loadavg_nosupport.c | 3 +- src/detection/loadavg/loadavg_sunos.c | 3 +- src/detection/locale/locale_linux.c | 12 +- src/detection/locale/locale_windows.c | 8 +- src/detection/localip/localip.h | 26 +- src/detection/localip/localip_linux.c | 1213 +++++++------- src/detection/localip/localip_windows.c | 180 +-- src/detection/media/media.c | 18 +- src/detection/media/media.h | 5 +- src/detection/media/media_linux.c | 210 ++- src/detection/media/media_nosupport.c | 3 +- src/detection/media/media_windows.c | 22 +- src/detection/media/media_windows.dll.cpp | 67 +- src/detection/media/media_windows.dll.h | 6 +- src/detection/memory/memory.h | 3 +- src/detection/memory/memory_apple.c | 18 +- src/detection/memory/memory_bsd.c | 10 +- src/detection/memory/memory_haiku.c | 6 +- src/detection/memory/memory_linux.c | 31 +- src/detection/memory/memory_nbsd.c | 6 +- src/detection/memory/memory_nosupport.c | 3 +- src/detection/memory/memory_obsd.c | 6 +- src/detection/memory/memory_sunos.c | 3 +- src/detection/memory/memory_windows.c | 6 +- src/detection/mouse/mouse.h | 3 +- src/detection/mouse/mouse_apple.c | 20 +- src/detection/mouse/mouse_bsd.c | 33 +- src/detection/mouse/mouse_haiku.cpp | 14 +- src/detection/mouse/mouse_linux.c | 21 +- src/detection/mouse/mouse_nosupport.c | 3 +- src/detection/mouse/mouse_windows.c | 49 +- src/detection/netio/netio.c | 47 +- src/detection/netio/netio.h | 3 +- src/detection/netio/netio_apple.c | 23 +- src/detection/netio/netio_bsd.c | 25 +- src/detection/netio/netio_haiku.cpp | 22 +- src/detection/netio/netio_linux.c | 61 +- src/detection/netio/netio_nosupport.c | 3 +- src/detection/netio/netio_sunos.c | 33 +- src/detection/netio/netio_windows.c | 32 +- src/detection/opencl/opencl.c | 146 +- src/detection/opencl/opencl.h | 5 +- src/detection/opengl/opengl.h | 3 +- src/detection/opengl/opengl_apple.c | 43 +- src/detection/opengl/opengl_haiku.cpp | 25 +- src/detection/opengl/opengl_linux.c | 141 +- src/detection/opengl/opengl_shared.c | 103 +- src/detection/opengl/opengl_windows.c | 62 +- src/detection/os/os.c | 6 +- src/detection/os/os.h | 3 +- src/detection/os/os_android.c | 3 +- src/detection/os/os_haiku.c | 50 +- src/detection/os/os_linux.c | 253 ++- src/detection/os/os_nbsd.c | 3 +- src/detection/os/os_obsd.c | 3 +- src/detection/os/os_sunos.c | 6 +- src/detection/os/os_windows.c | 56 +- src/detection/packages/packages.c | 70 +- src/detection/packages/packages.h | 5 +- src/detection/packages/packages_apple.c | 39 +- src/detection/packages/packages_bsd.c | 15 +- src/detection/packages/packages_haiku.c | 6 +- src/detection/packages/packages_linux.c | 406 ++--- src/detection/packages/packages_nbsd.c | 6 +- src/detection/packages/packages_nix.c | 105 +- src/detection/packages/packages_nosupport.c | 3 +- src/detection/packages/packages_obsd.c | 6 +- src/detection/packages/packages_sunos.c | 15 +- src/detection/packages/packages_windows.c | 130 +- src/detection/physicaldisk/physicaldisk.h | 6 +- .../physicaldisk/physicaldisk_apple.c | 90 +- src/detection/physicaldisk/physicaldisk_bsd.c | 88 +- .../physicaldisk/physicaldisk_haiku.c | 49 +- .../physicaldisk/physicaldisk_linux.c | 120 +- .../physicaldisk/physicaldisk_nosupport.c | 3 +- .../physicaldisk/physicaldisk_sunos.c | 47 +- .../physicaldisk/physicaldisk_windows.c | 281 ++-- src/detection/physicalmemory/physicalmemory.c | 87 +- src/detection/physicalmemory/physicalmemory.h | 7 +- .../physicalmemory/physicalmemory_linux.c | 228 +-- .../physicalmemory/physicalmemory_nosupport.c | 3 +- src/detection/poweradapter/poweradapter.h | 3 +- .../poweradapter/poweradapter_apple.c | 18 +- .../poweradapter/poweradapter_linux.c | 54 +- .../poweradapter/poweradapter_nosupport.c | 3 +- src/detection/processes/processes_bsd.c | 14 +- src/detection/processes/processes_haiku.c | 6 +- src/detection/processes/processes_linux.c | 17 +- src/detection/processes/processes_nbsd.c | 8 +- src/detection/processes/processes_nosupport.c | 3 +- src/detection/processes/processes_obsd.c | 7 +- src/detection/processes/processes_windows.c | 23 +- src/detection/publicip/publicip.c | 57 +- src/detection/publicip/publicip.h | 3 +- src/detection/sound/audio_oss_sunos.h | 1239 +++++++------- src/detection/sound/sound.h | 3 +- src/detection/sound/sound_apple.c | 114 +- src/detection/sound/sound_bsd.c | 59 +- src/detection/sound/sound_haiku.cpp | 56 +- src/detection/sound/sound_linux.c | 75 +- src/detection/sound/sound_nbsd.c | 22 +- src/detection/sound/sound_nosupport.c | 3 +- src/detection/sound/sound_obsd.c | 65 +- src/detection/sound/sound_sunos.c | 67 +- src/detection/sound/sound_windows.cpp | 59 +- src/detection/swap/swap.h | 3 +- src/detection/swap/swap_apple.c | 6 +- src/detection/swap/swap_bsd.c | 41 +- src/detection/swap/swap_haiku.c | 12 +- src/detection/swap/swap_linux.c | 44 +- src/detection/swap/swap_nosupport.c | 3 +- src/detection/swap/swap_obsd.c | 20 +- src/detection/swap/swap_sunos.c | 12 +- src/detection/swap/swap_windows.c | 15 +- src/detection/terminalfont/terminalfont.c | 251 ++- src/detection/terminalfont/terminalfont.h | 3 +- .../terminalfont/terminalfont_android.c | 40 +- .../terminalfont/terminalfont_linux.c | 440 +++-- .../terminalfont/terminalfont_windows.c | 236 ++- src/detection/terminalshell/terminalshell.c | 821 +++++----- src/detection/terminalshell/terminalshell.h | 16 +- .../terminalshell/terminalshell_linux.c | 410 +++-- .../terminalshell/terminalshell_windows.c | 263 ++- src/detection/terminalsize/terminalsize.h | 3 +- .../terminalsize/terminalsize_linux.c | 17 +- .../terminalsize/terminalsize_windows.c | 23 +- src/detection/terminaltheme/terminaltheme.c | 105 +- src/detection/terminaltheme/terminaltheme.h | 6 +- src/detection/theme/theme.h | 3 +- src/detection/theme/theme_apple.c | 6 +- src/detection/theme/theme_linux.c | 37 +- src/detection/theme/theme_nosupport.c | 3 +- src/detection/theme/theme_windows.c | 24 +- src/detection/tpm/tpm.h | 3 +- src/detection/tpm/tpm_apple.c | 13 +- src/detection/tpm/tpm_bsd.c | 17 +- src/detection/tpm/tpm_linux.c | 18 +- src/detection/tpm/tpm_nosupport.c | 3 +- src/detection/tpm/tpm_windows.c | 66 +- src/detection/uptime/uptime.h | 3 +- src/detection/uptime/uptime_bsd.c | 23 +- src/detection/uptime/uptime_haiku.c | 3 +- src/detection/uptime/uptime_linux.c | 24 +- src/detection/uptime/uptime_sunos.c | 9 +- src/detection/uptime/uptime_windows.c | 3 +- src/detection/users/users.h | 3 +- src/detection/users/users_linux.c | 119 +- src/detection/users/users_nosupport.c | 3 +- src/detection/users/users_obsd.c | 25 +- src/detection/users/users_windows.c | 28 +- src/detection/version/version.c | 102 +- src/detection/version/version.h | 3 +- src/detection/vulkan/vulkan.c | 231 ++- src/detection/vulkan/vulkan.h | 5 +- src/detection/wallpaper/wallpaper_linux.c | 19 +- src/detection/wallpaper/wallpaper_nosupport.c | 3 +- src/detection/wallpaper/wallpaper_windows.c | 9 +- src/detection/weather/weather.c | 35 +- src/detection/wifi/wifi.h | 19 +- src/detection/wifi/wifi_android.c | 33 +- src/detection/wifi/wifi_bsd.c | 79 +- src/detection/wifi/wifi_linux.c | 359 ++--- src/detection/wifi/wifi_nbsd.c | 81 +- src/detection/wifi/wifi_nosupport.c | 3 +- src/detection/wifi/wifi_obsd.c | 28 +- src/detection/wifi/wifi_windows.c | 155 +- src/detection/wm/wm_linux.c | 240 ++- src/detection/wm/wm_nosupport.c | 6 +- src/detection/wm/wm_windows.c | 158 +- src/detection/wmtheme/wmtheme_linux.c | 150 +- src/detection/wmtheme/wmtheme_nosupport.c | 3 +- src/detection/wmtheme/wmtheme_windows.c | 217 ++- src/detection/zpool/libzfs_simplified.h | 16 +- src/detection/zpool/zpool.c | 75 +- src/detection/zpool/zpool.h | 3 +- src/fastfetch.c | 629 ++++---- src/fastfetch.h | 12 +- src/flashfetch.c | 5 +- src/logo/builtin.c | 377 ++--- src/logo/image/im6.c | 18 +- src/logo/image/im7.c | 23 +- src/logo/image/image.c | 792 +++++---- src/logo/image/image.h | 19 +- src/logo/logo.c | 623 ++++--- src/logo/logo.h | 15 +- src/modules/battery/battery.c | 190 +-- src/modules/battery/option.h | 9 +- src/modules/bios/bios.c | 78 +- src/modules/bios/option.h | 3 +- src/modules/bluetooth/bluetooth.c | 111 +- src/modules/bluetooth/option.h | 3 +- src/modules/bluetoothradio/bluetoothradio.c | 175 +- src/modules/bluetoothradio/option.h | 3 +- src/modules/board/board.c | 59 +- src/modules/board/option.h | 3 +- src/modules/bootmgr/bootmgr.c | 67 +- src/modules/bootmgr/option.h | 3 +- src/modules/break/break.c | 18 +- src/modules/break/option.h | 3 +- src/modules/brightness/brightness.c | 118 +- src/modules/brightness/option.h | 3 +- src/modules/btrfs/btrfs.c | 129 +- src/modules/btrfs/option.h | 3 +- src/modules/camera/camera.c | 80 +- src/modules/camera/option.h | 3 +- src/modules/chassis/chassis.c | 56 +- src/modules/chassis/option.h | 3 +- src/modules/colors/colors.c | 271 ++-- src/modules/colors/option.h | 12 +- src/modules/command/command.c | 111 +- src/modules/command/option.h | 3 +- src/modules/cpu/cpu.c | 165 +- src/modules/cpu/option.h | 3 +- src/modules/cpucache/cpucache.c | 151 +- src/modules/cpucache/option.h | 3 +- src/modules/cpuusage/cpuusage.c | 142 +- src/modules/cpuusage/option.h | 3 +- src/modules/cursor/cursor.c | 55 +- src/modules/cursor/option.h | 3 +- src/modules/custom/custom.c | 21 +- src/modules/custom/option.h | 3 +- src/modules/datetime/datetime.c | 130 +- src/modules/datetime/option.h | 3 +- src/modules/de/de.c | 52 +- src/modules/de/option.h | 3 +- src/modules/disk/disk.c | 340 ++-- src/modules/disk/option.h | 9 +- src/modules/diskio/diskio.c | 122 +- src/modules/diskio/option.h | 3 +- src/modules/display/display.c | 349 ++-- src/modules/display/option.h | 9 +- src/modules/dns/dns.c | 97 +- src/modules/dns/option.h | 3 +- src/modules/editor/editor.c | 64 +- src/modules/editor/option.h | 3 +- src/modules/font/font.c | 75 +- src/modules/font/option.h | 3 +- src/modules/gamepad/gamepad.c | 136 +- src/modules/gamepad/option.h | 3 +- src/modules/gpu/gpu.c | 366 +++-- src/modules/gpu/option.h | 13 +- src/modules/host/host.c | 70 +- src/modules/host/option.h | 3 +- src/modules/icons/icons.c | 60 +- src/modules/icons/option.h | 3 +- src/modules/initsystem/initsystem.c | 55 +- src/modules/initsystem/option.h | 3 +- src/modules/kernel/kernel.c | 48 +- src/modules/kernel/option.h | 3 +- src/modules/keyboard/keyboard.c | 106 +- src/modules/keyboard/option.h | 3 +- src/modules/lm/lm.c | 62 +- src/modules/lm/option.h | 3 +- src/modules/loadavg/loadavg.c | 111 +- src/modules/loadavg/option.h | 3 +- src/modules/locale/locale.c | 47 +- src/modules/locale/option.h | 3 +- src/modules/localip/localip.c | 398 +++-- src/modules/localip/option.h | 45 +- src/modules/logo/logo.c | 44 +- src/modules/logo/option.h | 3 +- src/modules/media/media.c | 137 +- src/modules/media/option.h | 3 +- src/modules/memory/memory.c | 77 +- src/modules/memory/option.h | 3 +- src/modules/modules.c | 27 +- src/modules/monitor/monitor.c | 100 +- src/modules/monitor/option.h | 3 +- src/modules/mouse/mouse.c | 109 +- src/modules/mouse/option.h | 3 +- src/modules/netio/netio.c | 149 +- src/modules/netio/option.h | 3 +- src/modules/opencl/opencl.c | 79 +- src/modules/opencl/option.h | 3 +- src/modules/opengl/opengl.c | 99 +- src/modules/opengl/option.h | 6 +- src/modules/os/option.h | 3 +- src/modules/os/os.c | 168 +- src/modules/packages/option.h | 6 +- src/modules/packages/packages.c | 350 ++-- src/modules/physicaldisk/option.h | 3 +- src/modules/physicaldisk/physicaldisk.c | 170 +- src/modules/physicalmemory/option.h | 3 +- src/modules/physicalmemory/physicalmemory.c | 121 +- src/modules/player/option.h | 3 +- src/modules/player/player.c | 94 +- src/modules/poweradapter/option.h | 3 +- src/modules/poweradapter/poweradapter.c | 73 +- src/modules/processes/option.h | 3 +- src/modules/processes/processes.c | 45 +- src/modules/publicip/option.h | 3 +- src/modules/publicip/publicip.c | 60 +- src/modules/separator/option.h | 3 +- src/modules/separator/separator.c | 122 +- src/modules/shell/option.h | 3 +- src/modules/shell/shell.c | 66 +- src/modules/sound/option.h | 6 +- src/modules/sound/sound.c | 171 +- src/modules/swap/option.h | 3 +- src/modules/swap/swap.c | 137 +- src/modules/terminal/option.h | 3 +- src/modules/terminal/terminal.c | 65 +- src/modules/terminalfont/option.h | 3 +- src/modules/terminalfont/terminalfont.c | 64 +- src/modules/terminalsize/option.h | 3 +- src/modules/terminalsize/terminalsize.c | 52 +- src/modules/terminaltheme/option.h | 3 +- src/modules/terminaltheme/terminaltheme.c | 60 +- src/modules/theme/option.h | 3 +- src/modules/theme/theme.c | 63 +- src/modules/title/option.h | 3 +- src/modules/title/title.c | 142 +- src/modules/tpm/option.h | 3 +- src/modules/tpm/tpm.c | 59 +- src/modules/uptime/option.h | 3 +- src/modules/uptime/uptime.c | 53 +- src/modules/users/option.h | 3 +- src/modules/users/users.c | 121 +- src/modules/version/option.h | 3 +- src/modules/version/version.c | 74 +- src/modules/vulkan/option.h | 3 +- src/modules/vulkan/vulkan.c | 92 +- src/modules/wallpaper/option.h | 3 +- src/modules/wallpaper/wallpaper.c | 61 +- src/modules/weather/option.h | 3 +- src/modules/weather/weather.c | 53 +- src/modules/wifi/option.h | 3 +- src/modules/wifi/wifi.c | 167 +- src/modules/wm/option.h | 3 +- src/modules/wm/wm.c | 78 +- src/modules/wmtheme/option.h | 3 +- src/modules/wmtheme/wmtheme.c | 46 +- src/modules/zpool/option.h | 3 +- src/modules/zpool/zpool.c | 139 +- src/options/display.c | 1003 ++++++------ src/options/display.h | 27 +- src/options/general.c | 142 +- src/options/general.h | 18 +- src/options/logo.c | 572 +++---- src/options/logo.h | 9 +- tests/color.c | 19 +- tests/duration.c | 11 +- tests/format.c | 151 +- tests/list.c | 64 +- tests/strbuf.c | 147 +- 690 files changed, 28093 insertions(+), 30062 deletions(-) diff --git a/src/common/FFPlatform.h b/src/common/FFPlatform.h index 75e81713c..cf8224dda 100644 --- a/src/common/FFPlatform.h +++ b/src/common/FFPlatform.h @@ -3,8 +3,7 @@ #include "common/FFstrbuf.h" #include "common/FFlist.h" -typedef struct FFPlatformSysinfo -{ +typedef struct FFPlatformSysinfo { FFstrbuf name; FFstrbuf release; FFstrbuf version; @@ -12,8 +11,7 @@ typedef struct FFPlatformSysinfo uint32_t pageSize; } FFPlatformSysinfo; -typedef struct FFPlatform -{ +typedef struct FFPlatform { FFstrbuf homeDir; // Trailing slash included FFstrbuf cacheDir; // Trailing slash included FFlist configDirs; // List of FFstrbuf, trailing slash included @@ -22,11 +20,11 @@ typedef struct FFPlatform FFstrbuf cwd; // Trailing slash included uint32_t pid; - #ifndef _WIN32 +#ifndef _WIN32 uint32_t uid; - #else +#else FFstrbuf sid; - #endif +#endif FFstrbuf userName; FFstrbuf fullUserName; FFstrbuf hostName; diff --git a/src/common/FFcheckmacros.h b/src/common/FFcheckmacros.h index 00d34b2d3..c4b9c3ebf 100644 --- a/src/common/FFcheckmacros.h +++ b/src/common/FFcheckmacros.h @@ -1,37 +1,37 @@ #pragma once #ifdef _MSC_VER - #include +# include #endif #if defined(__has_attribute) && __has_attribute(__warn_unused_result__) - #define FF_C_NODISCARD __attribute__((__warn_unused_result__)) +# define FF_C_NODISCARD __attribute__((__warn_unused_result__)) #elif defined(_MSC_VER) - #define FF_C_NODISCARD _Check_return_ +# define FF_C_NODISCARD _Check_return_ #else - #define FF_C_NODISCARD +# define FF_C_NODISCARD #endif #if defined(__has_attribute) && __has_attribute(__format__) - #define FF_C_PRINTF(formatStrIndex, argsStartIndex) __attribute__((__format__ (printf, formatStrIndex, argsStartIndex))) +# define FF_C_PRINTF(formatStrIndex, argsStartIndex) __attribute__((__format__(printf, formatStrIndex, argsStartIndex))) #else - #define FF_C_PRINTF(formatStrIndex, argsStartIndex) +# define FF_C_PRINTF(formatStrIndex, argsStartIndex) #endif #if defined(__has_attribute) && __has_attribute(__format__) - #define FF_C_SCANF(formatStrIndex, argsStartIndex) __attribute__((__format__ (scanf, formatStrIndex, argsStartIndex))) +# define FF_C_SCANF(formatStrIndex, argsStartIndex) __attribute__((__format__(scanf, formatStrIndex, argsStartIndex))) #else - #define FF_C_SCANF(formatStrIndex, argsStartIndex) +# define FF_C_SCANF(formatStrIndex, argsStartIndex) #endif #if defined(__has_attribute) && __has_attribute(__nonnull__) - #define FF_C_NONNULL(argIndex, ...) __attribute__((__nonnull__(argIndex, ##__VA_ARGS__))) +# define FF_C_NONNULL(argIndex, ...) __attribute__((__nonnull__(argIndex, ##__VA_ARGS__))) #else - #define FF_C_NONNULL(argIndex, ...) +# define FF_C_NONNULL(argIndex, ...) #endif #if defined(__has_attribute) && __has_attribute(__returns_nonnull__) - #define FF_C_RETURNS_NONNULL __attribute__((__returns_nonnull__)) +# define FF_C_RETURNS_NONNULL __attribute__((__returns_nonnull__)) #else - #define FF_C_RETURNS_NONNULL +# define FF_C_RETURNS_NONNULL #endif diff --git a/src/common/FFlist.h b/src/common/FFlist.h index ec7801212..9003609f2 100644 --- a/src/common/FFlist.h +++ b/src/common/FFlist.h @@ -9,8 +9,7 @@ #define FF_LIST_DEFAULT_ALLOC 16 -typedef struct FFlist -{ +typedef struct FFlist { uint8_t* data; uint32_t elementSize; uint32_t length; @@ -24,8 +23,7 @@ bool ffListShift(FFlist* list, void* result); // Removes the last element, and copy its value to `*result` bool ffListPop(FFlist* list, void* result); -static inline void ffListInit(FFlist* list, uint32_t elementSize) -{ +static inline void ffListInit(FFlist* list, uint32_t elementSize) { assert(elementSize > 0); list->elementSize = elementSize; list->capacity = 0; @@ -33,112 +31,102 @@ static inline void ffListInit(FFlist* list, uint32_t elementSize) list->data = NULL; } -static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capacity) -{ +static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capacity) { ffListInit(list, elementSize); list->capacity = capacity; - list->data = __builtin_expect(capacity == 0, 0) ? NULL : (uint8_t*) malloc((size_t)list->capacity * list->elementSize); + list->data = __builtin_expect(capacity == 0, 0) ? NULL : (uint8_t*) malloc((size_t) list->capacity * list->elementSize); } -static inline FFlist ffListCreate(uint32_t elementSize) -{ +static inline FFlist ffListCreate(uint32_t elementSize) { FFlist result; ffListInit(&result, elementSize); return result; } -static inline void* ffListGet(const FFlist* list, uint32_t index) -{ +static inline void* ffListGet(const FFlist* list, uint32_t index) { assert(list->capacity > index); return list->data + (index * list->elementSize); } -FF_C_NODISCARD static inline uint32_t ffListFirstIndexComp(const FFlist* list, void* compElement, bool(*compFunc)(const void*, const void*)) -{ - for(uint32_t i = 0; i < list->length; i++) - { - if(compFunc(ffListGet(list, i), compElement)) +FF_C_NODISCARD static inline uint32_t ffListFirstIndexComp(const FFlist* list, void* compElement, bool (*compFunc)(const void*, const void*)) { + for (uint32_t i = 0; i < list->length; i++) { + if (compFunc(ffListGet(list, i), compElement)) { return i; + } } return list->length; } -static inline bool ffListContains(const FFlist* list, void* compElement, bool(*compFunc)(const void*, const void*)) -{ +static inline bool ffListContains(const FFlist* list, void* compElement, bool (*compFunc)(const void*, const void*)) { return ffListFirstIndexComp(list, compElement, compFunc) != list->length; } -static inline void ffListSort(FFlist* list, int(*compar)(const void*, const void*)) -{ +static inline void ffListSort(FFlist* list, int (*compar)(const void*, const void*)) { qsort(list->data, list->length, list->elementSize, compar); } // Move the contents of `src` into `list`, and left `src` empty -static inline void ffListInitMove(FFlist* list, FFlist* src) -{ - if (src) - { +static inline void ffListInitMove(FFlist* list, FFlist* src) { + if (src) { list->elementSize = src->elementSize; list->capacity = src->capacity; list->length = src->length; list->data = src->data; ffListInit(src, list->elementSize); - } - else - { + } else { ffListInit(list, 0); } } -static inline void ffListDestroy(FFlist* list) -{ - if (!list->data) return; +static inline void ffListDestroy(FFlist* list) { + if (!list->data) { + return; + } - //Avoid free-after-use. These 3 assignments are cheap so don't remove them + // Avoid free-after-use. These 3 assignments are cheap so don't remove them list->capacity = list->length = 0; free(list->data); list->data = NULL; } -static inline void ffListClear(FFlist* list) -{ +static inline void ffListClear(FFlist* list) { list->length = 0; } -static inline void ffListReserve(FFlist* list, uint32_t newCapacity) -{ - if (__builtin_expect(newCapacity <= list->capacity, false)) +static inline void ffListReserve(FFlist* list, uint32_t newCapacity) { + if (__builtin_expect(newCapacity <= list->capacity, false)) { return; + } list->data = (uint8_t*) realloc(list->data, (size_t) newCapacity * list->elementSize); list->capacity = newCapacity; } -#define FF_LIST_FOR_EACH(itemType, itemVarName, listVar) \ - assert(sizeof(itemType) == (listVar).elementSize); \ - for(itemType* itemVarName = (itemType*)(listVar).data; \ - itemVarName - (itemType*)(listVar).data < (intptr_t)(listVar).length; \ +#define FF_LIST_FOR_EACH(itemType, itemVarName, listVar) \ + assert(sizeof(itemType) == (listVar).elementSize); \ + for (itemType* itemVarName = (itemType*) (listVar).data; \ + itemVarName - (itemType*) (listVar).data < (intptr_t) (listVar).length; \ ++itemVarName) #define FF_LIST_AUTO_DESTROY FFlist __attribute__((__cleanup__(ffListDestroy))) -#define FF_LIST_GET(itemType, listVar, index) \ - ({ \ +#define FF_LIST_GET(itemType, listVar, index) \ + ({ \ assert(sizeof(itemType) == (listVar).elementSize); \ - assert((listVar).capacity > (index)); \ - (itemType*)(listVar).data + (index); \ + assert((listVar).capacity > (index)); \ + (itemType*) (listVar).data + (index); \ }) -#define FF_LIST_ADD(itemType, listVar) \ - ({ \ +#define FF_LIST_ADD(itemType, listVar) \ + ({ \ assert(sizeof(itemType) == (listVar).elementSize); \ - (itemType*) ffListAdd(&(listVar)); \ + (itemType*) ffListAdd(&(listVar)); \ }) #define FF_LIST_FIRST(itemType, listVar) FF_LIST_GET(itemType, listVar, 0) -#define FF_LIST_LAST(itemType, listVar) \ - ({ \ - assert((listVar).length > 0); \ +#define FF_LIST_LAST(itemType, listVar) \ + ({ \ + assert((listVar).length > 0); \ FF_LIST_GET(itemType, listVar, ((listVar).length - 1)); \ }) diff --git a/src/common/FFstrbuf.h b/src/common/FFstrbuf.h index 80a817550..da9aba0d2 100644 --- a/src/common/FFstrbuf.h +++ b/src/common/FFstrbuf.h @@ -11,23 +11,22 @@ #include #ifdef FF_USE_SYSTEM_YYJSON - #include +# include #else - #include "3rdparty/yyjson/yyjson.h" +# include "3rdparty/yyjson/yyjson.h" #endif #ifdef _WIN32 - // #include - __stdcall char* StrStrIA(const char* lpFirst, const char* lpSrch); - #define strcasestr StrStrIA +// #include +__stdcall char* StrStrIA(const char* lpFirst, const char* lpSrch); +# define strcasestr StrStrIA #endif #define FASTFETCH_STRBUF_DEFAULT_ALLOC 32 // static string (allocated == 0), chars points to a string literal // dynamic string (allocated > 0), chars points to a heap allocated buffer -typedef struct FFstrbuf -{ +typedef struct FFstrbuf { uint32_t allocated; uint32_t length; char* chars; @@ -47,8 +46,9 @@ static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* _ void ffStrbufAppendC(FFstrbuf* strbuf, char c); void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c); void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value); -void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int(*transformFunc)(int)); -FF_C_PRINTF(2, 3) void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...); +void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transformFunc)(int)); +FF_C_PRINTF(2, 3) +void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...); void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments); const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until); @@ -61,7 +61,8 @@ void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c); // NOTE: Unlike ffStrbufAppend*, ffStrbufSet* functions may NOT reserve extra space void ffStrbufSet(FFstrbuf* strbuf, const FFstrbuf* value); void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value); -FF_C_PRINTF(2, 3) void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...); +FF_C_PRINTF(2, 3) +void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...); void ffStrbufTrimLeft(FFstrbuf* strbuf, char c); void ffStrbufTrimRight(FFstrbuf* strbuf, char c); @@ -126,16 +127,14 @@ void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf * * @return true if a line has been read, false if the end of the buffer has been reached. */ -static inline bool ffStrbufGetline(char** lineptr, size_t* n, FFstrbuf* buffer) -{ +static inline bool ffStrbufGetline(char** lineptr, size_t* n, FFstrbuf* buffer) { return ffStrbufGetdelim(lineptr, n, '\n', buffer); } /** * @brief Restore the end of a line that was modified by ffStrbufGetline. * @warning This function should be called before breaking an ffStrbufGetline loop if `buffer` will be used later. */ -static inline void ffStrbufGetlineRestore(char** lineptr, size_t* n, FFstrbuf* buffer) -{ +static inline void ffStrbufGetlineRestore(char** lineptr, size_t* n, FFstrbuf* buffer) { ffStrbufGetdelimRestore(lineptr, n, '\n', buffer); } bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf); @@ -152,60 +151,51 @@ void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value); // if `precision < 0`, let yyjson decide the precision void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool trailingZeros); -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateA(uint32_t allocate) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateA(uint32_t allocate) { FFstrbuf strbuf; ffStrbufInitA(&strbuf, allocate); return strbuf; } -static inline void ffStrbufInitCopy(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict src) -{ - if (src->allocated == 0) // static string +static inline void ffStrbufInitCopy(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict src) { + if (src->allocated == 0) { // static string *strbuf = *src; - else - { + } else { ffStrbufInitA(strbuf, src->allocated); ffStrbufAppend(strbuf, src); } } -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateCopy(const FFstrbuf* src) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateCopy(const FFstrbuf* src) { FFstrbuf strbuf; ffStrbufInitCopy(&strbuf, src); return strbuf; } // Move the content of `src` into `strbuf`, and left `src` empty -static inline void ffStrbufInitMove(FFstrbuf* strbuf, FFstrbuf* src) -{ - if (src) - { +static inline void ffStrbufInitMove(FFstrbuf* strbuf, FFstrbuf* src) { + if (src) { *strbuf = *src; ffStrbufInit(src); - } - else + } else { ffStrbufInit(strbuf); + } } -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateMove(FFstrbuf* src) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateMove(FFstrbuf* src) { FFstrbuf strbuf; ffStrbufInitMove(&strbuf, src); return strbuf; } -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateVF(const char* format, va_list arguments) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateVF(const char* format, va_list arguments) { FFstrbuf strbuf; ffStrbufInitVF(&strbuf, format, arguments); return strbuf; } FF_C_PRINTF(2, 3) -static inline void ffStrbufInitF(FFstrbuf* strbuf, const char* format, ...) -{ +static inline void ffStrbufInitF(FFstrbuf* strbuf, const char* format, ...) { va_list arguments; va_start(arguments, format); ffStrbufInitVF(strbuf, format, arguments); @@ -213,8 +203,7 @@ static inline void ffStrbufInitF(FFstrbuf* strbuf, const char* format, ...) } FF_C_PRINTF(1, 2) -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateF(const char* format, ...) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateF(const char* format, ...) { FFstrbuf strbuf; va_list arguments; @@ -225,50 +214,46 @@ FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateF(const char* format, ...) return strbuf; } -static inline void ffStrbufInitMoveS(FFstrbuf* strbuf, char* heapStr) -{ +static inline void ffStrbufInitMoveS(FFstrbuf* strbuf, char* heapStr) { ffStrbufInitMoveNS(strbuf, (uint32_t) strlen(heapStr), heapStr); } // Despite the name, this function resets strbuf to the initial/unallocated state -static inline void ffStrbufDestroy(FFstrbuf* strbuf) -{ - if(strbuf->allocated > 0) +static inline void ffStrbufDestroy(FFstrbuf* strbuf) { + if (strbuf->allocated > 0) { free(strbuf->chars); + } ffStrbufInit(strbuf); } -FF_C_NODISCARD static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) -{ +FF_C_NODISCARD static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) { assert(strbuf != NULL); - if(strbuf->allocated == 0) + if (strbuf->allocated == 0) { return 0; + } return strbuf->allocated - strbuf->length - 1; // - 1 for the null byte } -static inline void ffStrbufRecalculateLength(FFstrbuf* strbuf) -{ +static inline void ffStrbufRecalculateLength(FFstrbuf* strbuf) { strbuf->length = (uint32_t) strlen(strbuf->chars); } -static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) -{ +static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) { assert(strbuf != NULL); - if (value == NULL) + if (value == NULL) { ffStrbufClear(strbuf); - else + } else { ffStrbufSetNS(strbuf, (uint32_t) strlen(value), value); + } } -static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) -{ +static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) { assert(strbuf != NULL); - if (yyjson_is_str(jsonVal)) - { + if (yyjson_is_str(jsonVal)) { ffStrbufSetNS(strbuf, (uint32_t) unsafe_yyjson_get_len(jsonVal), unsafe_yyjson_get_str(jsonVal)); return true; } @@ -277,354 +262,305 @@ static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) return false; } -static inline void ffStrbufAppendS(FFstrbuf* strbuf, const char* value) -{ - if(value == NULL) +static inline void ffStrbufAppendS(FFstrbuf* strbuf, const char* value) { + if (value == NULL) { return; + } ffStrbufAppendNS(strbuf, (uint32_t) strlen(value), value); } -static inline bool ffStrbufAppendJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) -{ - if (yyjson_is_str(jsonVal)) - { +static inline bool ffStrbufAppendJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) { + if (yyjson_is_str(jsonVal)) { ffStrbufAppendNS(strbuf, (uint32_t) unsafe_yyjson_get_len(jsonVal), unsafe_yyjson_get_str(jsonVal)); return true; } return false; } -static inline void ffStrbufInit(FFstrbuf* strbuf) -{ +static inline void ffStrbufInit(FFstrbuf* strbuf) { extern char* CHAR_NULL_PTR; strbuf->allocated = strbuf->length = 0; strbuf->chars = CHAR_NULL_PTR; } -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreate(void) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreate(void) { FFstrbuf strbuf; ffStrbufInit(&strbuf); return strbuf; } -static inline void ffStrbufInitStatic(FFstrbuf* strbuf, const char* str) -{ +static inline void ffStrbufInitStatic(FFstrbuf* strbuf, const char* str) { ffStrbufInit(strbuf); - if (!str) return; + if (!str) { + return; + } strbuf->allocated = 0; strbuf->length = (uint32_t) strlen(str); strbuf->chars = (char*) str; } -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateStatic(const char* str) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateStatic(const char* str) { FFstrbuf strbuf; ffStrbufInitStatic(&strbuf, str); return strbuf; } -static inline void ffStrbufSetStatic(FFstrbuf* strbuf, const char* value) -{ - if(strbuf->allocated > 0) +static inline void ffStrbufSetStatic(FFstrbuf* strbuf, const char* value) { + if (strbuf->allocated > 0) { free(strbuf->chars); + } - if(value != NULL) + if (value != NULL) { ffStrbufInitStatic(strbuf, value); - else + } else { ffStrbufInit(strbuf); + } } -static inline void ffStrbufInitNS(FFstrbuf* strbuf, uint32_t length, const char* str) -{ +static inline void ffStrbufInitNS(FFstrbuf* strbuf, uint32_t length, const char* str) { ffStrbufInit(strbuf); ffStrbufAppendNS(strbuf, length, str); } -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateNS(uint32_t length, const char* str) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateNS(uint32_t length, const char* str) { FFstrbuf strbuf; ffStrbufInitNS(&strbuf, length, str); return strbuf; } -static inline bool ffStrbufInitJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) -{ +static inline bool ffStrbufInitJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) { ffStrbufInit(strbuf); return ffStrbufAppendJsonVal(strbuf, jsonVal); } -static inline void ffStrbufInitS(FFstrbuf* strbuf, const char* str) -{ +static inline void ffStrbufInitS(FFstrbuf* strbuf, const char* str) { ffStrbufInit(strbuf); ffStrbufAppendS(strbuf, str); } -FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateS(const char* str) -{ +FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateS(const char* str) { FFstrbuf strbuf; ffStrbufInitS(&strbuf, str); return strbuf; } -static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value) -{ +static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value) { assert(value != strbuf); - if(value == NULL) + if (value == NULL) { return; + } ffStrbufAppendNS(strbuf, value->length, value->chars); } -static inline void ffStrbufPrepend(FFstrbuf* strbuf, FFstrbuf* value) -{ - if(value == NULL) +static inline void ffStrbufPrepend(FFstrbuf* strbuf, FFstrbuf* value) { + if (value == NULL) { return; + } ffStrbufPrependNS(strbuf, value->length, value->chars); } -static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) -{ - if(value == NULL) +static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) { + if (value == NULL) { return; + } ffStrbufPrependNS(strbuf, (uint32_t) strlen(value), value); } -static inline FF_C_NODISCARD int ffStrbufComp(const FFstrbuf* strbuf, const FFstrbuf* comp) -{ +static inline FF_C_NODISCARD int ffStrbufComp(const FFstrbuf* strbuf, const FFstrbuf* comp) { uint32_t length = strbuf->length > comp->length ? comp->length : strbuf->length; return memcmp(strbuf->chars, comp->chars, length + 1); } -static inline FF_C_NODISCARD bool ffStrbufEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) -{ +static inline FF_C_NODISCARD bool ffStrbufEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) { return ffStrbufComp(strbuf, comp) == 0; } -static inline FF_C_NODISCARD int ffStrbufCompS(const FFstrbuf* strbuf, const char* comp) -{ +static inline FF_C_NODISCARD int ffStrbufCompS(const FFstrbuf* strbuf, const char* comp) { return strcmp(strbuf->chars, comp); } -static inline FF_C_NODISCARD bool ffStrbufEqualS(const FFstrbuf* strbuf, const char* comp) -{ +static inline FF_C_NODISCARD bool ffStrbufEqualS(const FFstrbuf* strbuf, const char* comp) { return ffStrbufCompS(strbuf, comp) == 0; } -static inline FF_C_NODISCARD int ffStrbufIgnCaseCompS(const FFstrbuf* strbuf, const char* comp) -{ +static inline FF_C_NODISCARD int ffStrbufIgnCaseCompS(const FFstrbuf* strbuf, const char* comp) { return strcasecmp(strbuf->chars, comp); } -static inline FF_C_NODISCARD bool ffStrbufIgnCaseEqualS(const FFstrbuf* strbuf, const char* comp) -{ +static inline FF_C_NODISCARD bool ffStrbufIgnCaseEqualS(const FFstrbuf* strbuf, const char* comp) { return ffStrbufIgnCaseCompS(strbuf, comp) == 0; } -static inline FF_C_NODISCARD int ffStrbufIgnCaseComp(const FFstrbuf* strbuf, const FFstrbuf* comp) -{ +static inline FF_C_NODISCARD int ffStrbufIgnCaseComp(const FFstrbuf* strbuf, const FFstrbuf* comp) { return ffStrbufIgnCaseCompS(strbuf, comp->chars); } -static inline FF_C_NODISCARD bool ffStrbufIgnCaseEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) -{ +static inline FF_C_NODISCARD bool ffStrbufIgnCaseEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) { return ffStrbufIgnCaseComp(strbuf, comp) == 0; } -static inline FF_C_NODISCARD bool ffStrbufContainC(const FFstrbuf* strbuf, char c) -{ +static inline FF_C_NODISCARD bool ffStrbufContainC(const FFstrbuf* strbuf, char c) { return memchr(strbuf->chars, c, strbuf->length) != NULL; } -static inline FF_C_NODISCARD bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) -{ +static inline FF_C_NODISCARD bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) { return strstr(strbuf->chars, str) != NULL; } -static inline FF_C_NODISCARD bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) -{ +static inline FF_C_NODISCARD bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) { return ffStrbufContainS(strbuf, str->chars); } -static inline FF_C_NODISCARD bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) -{ +static inline FF_C_NODISCARD bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) { return strcasestr(strbuf->chars, str) != NULL; } -static inline FF_C_NODISCARD bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) -{ +static inline FF_C_NODISCARD bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) { return ffStrbufContainIgnCaseS(strbuf, str->chars); } -static inline FF_C_NODISCARD uint32_t ffStrbufFirstIndexC(const FFstrbuf* strbuf, char c) -{ +static inline FF_C_NODISCARD uint32_t ffStrbufFirstIndexC(const FFstrbuf* strbuf, char c) { return ffStrbufNextIndexC(strbuf, 0, c); } -static inline FF_C_NODISCARD uint32_t ffStrbufFirstIndex(const FFstrbuf* strbuf, const FFstrbuf* searched) -{ +static inline FF_C_NODISCARD uint32_t ffStrbufFirstIndex(const FFstrbuf* strbuf, const FFstrbuf* searched) { return ffStrbufNextIndexS(strbuf, 0, searched->chars); } -static inline FF_C_NODISCARD uint32_t ffStrbufFirstIndexS(const FFstrbuf* strbuf, const char* str) -{ +static inline FF_C_NODISCARD uint32_t ffStrbufFirstIndexS(const FFstrbuf* strbuf, const char* str) { return ffStrbufNextIndexS(strbuf, 0, str); } -static inline FF_C_NODISCARD uint32_t ffStrbufLastIndexC(const FFstrbuf* strbuf, char c) -{ - if(strbuf->length == 0) +static inline FF_C_NODISCARD uint32_t ffStrbufLastIndexC(const FFstrbuf* strbuf, char c) { + if (strbuf->length == 0) { return 0; + } return ffStrbufPreviousIndexC(strbuf, strbuf->length - 1, c); } -static inline bool ffStrbufSubstrBeforeFirstC(FFstrbuf* strbuf, char c) -{ +static inline bool ffStrbufSubstrBeforeFirstC(FFstrbuf* strbuf, char c) { return ffStrbufSubstrBefore(strbuf, ffStrbufFirstIndexC(strbuf, c)); } -static inline bool ffStrbufSubstrBeforeLastC(FFstrbuf* strbuf, char c) -{ +static inline bool ffStrbufSubstrBeforeLastC(FFstrbuf* strbuf, char c) { return ffStrbufSubstrBefore(strbuf, ffStrbufLastIndexC(strbuf, c)); } -static inline FF_C_NODISCARD bool ffStrbufStartsWithC(const FFstrbuf* strbuf, char c) -{ +static inline FF_C_NODISCARD bool ffStrbufStartsWithC(const FFstrbuf* strbuf, char c) { return strbuf->chars[0] == c; } -static inline FF_C_NODISCARD bool ffStrbufStartsWithSN(const FFstrbuf* strbuf, const char* start, uint32_t length) -{ - if (length > strbuf->length) +static inline FF_C_NODISCARD bool ffStrbufStartsWithSN(const FFstrbuf* strbuf, const char* start, uint32_t length) { + if (length > strbuf->length) { return false; + } return memcmp(strbuf->chars, start, length) == 0; } -static inline FF_C_NODISCARD bool ffStrbufStartsWithS(const FFstrbuf* strbuf, const char* start) -{ +static inline FF_C_NODISCARD bool ffStrbufStartsWithS(const FFstrbuf* strbuf, const char* start) { return ffStrbufStartsWithSN(strbuf, start, (uint32_t) strlen(start)); } -static inline FF_C_NODISCARD bool ffStrbufStartsWith(const FFstrbuf* strbuf, const FFstrbuf* start) -{ +static inline FF_C_NODISCARD bool ffStrbufStartsWith(const FFstrbuf* strbuf, const FFstrbuf* start) { return ffStrbufStartsWithSN(strbuf, start->chars, start->length); } -static inline FF_C_NODISCARD bool ffStrbufStartsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t length, const char* start) -{ - if(length > strbuf->length) +static inline FF_C_NODISCARD bool ffStrbufStartsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t length, const char* start) { + if (length > strbuf->length) { return false; + } return strncasecmp(strbuf->chars, start, length) == 0; } -static inline FF_C_NODISCARD bool ffStrbufStartsWithIgnCaseS(const FFstrbuf* strbuf, const char* start) -{ +static inline FF_C_NODISCARD bool ffStrbufStartsWithIgnCaseS(const FFstrbuf* strbuf, const char* start) { return ffStrbufStartsWithIgnCaseNS(strbuf, (uint32_t) strlen(start), start); } -static inline FF_C_NODISCARD bool ffStrbufStartsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* start) -{ +static inline FF_C_NODISCARD bool ffStrbufStartsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* start) { return ffStrbufStartsWithIgnCaseNS(strbuf, start->length, start->chars); } -static inline FF_C_NODISCARD bool ffStrbufEndsWithC(const FFstrbuf* strbuf, char c) -{ - return strbuf->length == 0 ? false : - strbuf->chars[strbuf->length - 1] == c; +static inline FF_C_NODISCARD bool ffStrbufEndsWithC(const FFstrbuf* strbuf, char c) { + return strbuf->length == 0 ? false : strbuf->chars[strbuf->length - 1] == c; } -static inline FF_C_NODISCARD bool ffStrbufEndsWithNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) -{ - if(endLength > strbuf->length) +static inline FF_C_NODISCARD bool ffStrbufEndsWithNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) { + if (endLength > strbuf->length) { return false; + } return memcmp(strbuf->chars + strbuf->length - endLength, end, endLength) == 0; } -static inline FF_C_NODISCARD bool ffStrbufEndsWithS(const FFstrbuf* strbuf, const char* end) -{ +static inline FF_C_NODISCARD bool ffStrbufEndsWithS(const FFstrbuf* strbuf, const char* end) { return ffStrbufEndsWithNS(strbuf, (uint32_t) strlen(end), end); } -static inline FF_C_NODISCARD bool ffStrbufEndsWithFn(const FFstrbuf* strbuf, int (*const fn)(int)) -{ - return strbuf->length == 0 ? false : - fn(strbuf->chars[strbuf->length - 1]); +static inline FF_C_NODISCARD bool ffStrbufEndsWithFn(const FFstrbuf* strbuf, int (*const fn)(int)) { + return strbuf->length == 0 ? false : fn(strbuf->chars[strbuf->length - 1]); } -static inline FF_C_NODISCARD bool ffStrbufEndsWith(const FFstrbuf* strbuf, const FFstrbuf* end) -{ +static inline FF_C_NODISCARD bool ffStrbufEndsWith(const FFstrbuf* strbuf, const FFstrbuf* end) { return ffStrbufEndsWithNS(strbuf, end->length, end->chars); } -static inline FF_C_NODISCARD bool ffStrbufEndsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) -{ - if(endLength > strbuf->length) +static inline FF_C_NODISCARD bool ffStrbufEndsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) { + if (endLength > strbuf->length) { return false; + } return strcasecmp(strbuf->chars + strbuf->length - endLength, end) == 0; } -static inline FF_C_NODISCARD bool ffStrbufEndsWithIgnCaseS(const FFstrbuf* strbuf, const char* end) -{ +static inline FF_C_NODISCARD bool ffStrbufEndsWithIgnCaseS(const FFstrbuf* strbuf, const char* end) { return ffStrbufEndsWithIgnCaseNS(strbuf, (uint32_t) strlen(end), end); } -static inline FF_C_NODISCARD bool ffStrbufEndsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* end) -{ +static inline FF_C_NODISCARD bool ffStrbufEndsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* end) { return ffStrbufEndsWithIgnCaseNS(strbuf, end->length, end->chars); } -static inline void ffStrbufTrim(FFstrbuf* strbuf, char c) -{ +static inline void ffStrbufTrim(FFstrbuf* strbuf, char c) { ffStrbufTrimRight(strbuf, c); ffStrbufTrimLeft(strbuf, c); } -static inline void ffStrbufTrimSpace(FFstrbuf* strbuf) -{ +static inline void ffStrbufTrimSpace(FFstrbuf* strbuf) { ffStrbufTrimRightSpace(strbuf); ffStrbufTrimLeftSpace(strbuf); } -static inline bool ffStrbufMatchSeparatedS(const FFstrbuf* strbuf, const char* comp, char separator) -{ +static inline bool ffStrbufMatchSeparatedS(const FFstrbuf* strbuf, const char* comp, char separator) { return ffStrbufMatchSeparatedNS(strbuf, (uint32_t) strlen(comp), comp, separator); } -static inline bool ffStrbufMatchSeparated(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) -{ +static inline bool ffStrbufMatchSeparated(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) { return ffStrbufMatchSeparatedNS(strbuf, comp->length, comp->chars, separator); } -static inline bool ffStrbufMatchSeparatedIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) -{ +static inline bool ffStrbufMatchSeparatedIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) { return ffStrbufMatchSeparatedIgnCaseNS(strbuf, (uint32_t) strlen(comp), comp, separator); } -static inline bool ffStrbufMatchSeparatedIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) -{ +static inline bool ffStrbufMatchSeparatedIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) { return ffStrbufMatchSeparatedIgnCaseNS(strbuf, comp->length, comp->chars, separator); } -static inline bool ffStrbufSeparatedContainS(const FFstrbuf* strbuf, const char* comp, char separator) -{ +static inline bool ffStrbufSeparatedContainS(const FFstrbuf* strbuf, const char* comp, char separator) { return ffStrbufSeparatedContainNS(strbuf, (uint32_t) strlen(comp), comp, separator); } -static inline bool ffStrbufSeparatedContain(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) -{ +static inline bool ffStrbufSeparatedContain(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) { return ffStrbufSeparatedContainNS(strbuf, comp->length, comp->chars, separator); } -static inline bool ffStrbufSeparatedContainIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) -{ +static inline bool ffStrbufSeparatedContainIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) { return ffStrbufSeparatedContainIgnCaseNS(strbuf, (uint32_t) strlen(comp), comp, separator); } -static inline bool ffStrbufSeparatedContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) -{ +static inline bool ffStrbufSeparatedContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) { return ffStrbufSeparatedContainIgnCaseNS(strbuf, comp->length, comp->chars, separator); } diff --git a/src/common/apple/cf_helpers.c b/src/common/apple/cf_helpers.c index 8156d3779..e080f4dec 100644 --- a/src/common/apple/cf_helpers.c +++ b/src/common/apple/cf_helpers.c @@ -1,184 +1,183 @@ #include "cf_helpers.h" -const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result) -{ - if(CFGetTypeID(cf) == CFNumberGetTypeID()) - { - if(!CFNumberGetValue((CFNumberRef)cf, kCFNumberSInt64Type, result)) +const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result) { + if (CFGetTypeID(cf) == CFNumberGetTypeID()) { + if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt64Type, result)) { return "Number type is not SInt64"; + } return NULL; - } - else if(CFGetTypeID(cf) == CFDataGetTypeID()) - { - if(CFDataGetLength((CFDataRef)cf) != sizeof(int64_t)) + } else if (CFGetTypeID(cf) == CFDataGetTypeID()) { + if (CFDataGetLength((CFDataRef) cf) != sizeof(int64_t)) { return "Data length is not sizeof(int64_t)"; - CFDataGetBytes((CFDataRef)cf, CFRangeMake(0, sizeof(int64_t)), (uint8_t*)result); + } + CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(int64_t)), (uint8_t*) result); return NULL; } return "TypeID is neither 'CFNumber' nor 'CFData'"; } -const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result) -{ - if(CFGetTypeID(cf) == CFNumberGetTypeID()) - { - if(!CFNumberGetValue((CFNumberRef)cf, kCFNumberSInt32Type, result)) +const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result) { + if (CFGetTypeID(cf) == CFNumberGetTypeID()) { + if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt32Type, result)) { return "Number type is not SInt32"; + } return NULL; - } - else if(CFGetTypeID(cf) == CFDataGetTypeID()) - { - if(CFDataGetLength((CFDataRef)cf) != sizeof(int)) + } else if (CFGetTypeID(cf) == CFDataGetTypeID()) { + if (CFDataGetLength((CFDataRef) cf) != sizeof(int)) { return "Data length is not sizeof(int)"; - CFDataGetBytes((CFDataRef)cf, CFRangeMake(0, sizeof(int)), (uint8_t*)result); + } + CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(int)), (uint8_t*) result); return NULL; } return "TypeID is neither 'CFNumber' nor 'CFData'"; } -const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) -{ +const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) { ffStrbufClear(result); - if (!cf) + if (!cf) { return NULL; + } - if (CFGetTypeID(cf) == CFStringGetTypeID()) - { - CFStringRef cfStr = (CFStringRef)cf; + if (CFGetTypeID(cf) == CFStringGetTypeID()) { + CFStringRef cfStr = (CFStringRef) cf; const char* cstr = CFStringGetCStringPtr(cfStr, kCFStringEncodingUTF8); - if (cstr) + if (cstr) { ffStrbufSetS(result, cstr); - else - { + } else { uint32_t length = (uint32_t) CFStringGetLength(cfStr); - if (length == 0) + if (length == 0) { return NULL; + } ffStrbufEnsureFixedLengthFree(result, (uint32_t) CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8)); - if(!CFStringGetCString(cfStr, result->chars, result->allocated, kCFStringEncodingUTF8)) + if (!CFStringGetCString(cfStr, result->chars, result->allocated, kCFStringEncodingUTF8)) { return "CFStringGetCString() failed"; + } // CFStringGetCString ensures the buffer is NUL terminated // https://developer.apple.com/documentation/corefoundation/1542721-cfstringgetcstring - result->length = (uint32_t) strnlen(result->chars, (uint32_t)result->allocated); + result->length = (uint32_t) strnlen(result->chars, (uint32_t) result->allocated); } - } - else if (CFGetTypeID(cf) == CFDataGetTypeID()) - { - CFDataRef cfData = (CFDataRef)cf; - uint32_t length = (uint32_t)CFDataGetLength(cfData); - if (length == 0) + } else if (CFGetTypeID(cf) == CFDataGetTypeID()) { + CFDataRef cfData = (CFDataRef) cf; + uint32_t length = (uint32_t) CFDataGetLength(cfData); + if (length == 0) { return NULL; + } ffStrbufEnsureFixedLengthFree(result, length + 1); - CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*)result->chars); - result->length = (uint32_t)strnlen(result->chars, length); + CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars); + result->length = (uint32_t) strnlen(result->chars, length); result->chars[result->length] = '\0'; - } - else + } else { return "TypeID is neither 'CFString' nor 'CFData'"; + } return NULL; } -const char* ffCfDataGetDataAsString(CFTypeRef cf, FFstrbuf* result) -{ +const char* ffCfDataGetDataAsString(CFTypeRef cf, FFstrbuf* result) { ffStrbufClear(result); - if (!cf) + if (!cf) { return NULL; + } - if (CFGetTypeID(cf) == CFDataGetTypeID()) - { - CFDataRef cfData = (CFDataRef)cf; - uint32_t length = (uint32_t)CFDataGetLength(cfData); - if (length == 0) + if (CFGetTypeID(cf) == CFDataGetTypeID()) { + CFDataRef cfData = (CFDataRef) cf; + uint32_t length = (uint32_t) CFDataGetLength(cfData); + if (length == 0) { return NULL; + } ffStrbufEnsureFixedLengthFree(result, length + 1); - CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*)result->chars); + CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars); result->length = length; result->chars[result->length] = '\0'; - } - else + } else { return "TypeID is not 'CFData'"; + } return NULL; } -const char* ffCfDictGetString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) -{ - CFTypeRef cf = (CFTypeRef)CFDictionaryGetValue(dict, key); - if(cf == NULL) +const char* ffCfDictGetString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) { + CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); + if (cf == NULL) { return "CFDictionaryGetValue() failed"; + } return ffCfStrGetString(cf, result); } -const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) -{ - CFTypeRef cf = (CFTypeRef)CFDictionaryGetValue(dict, key); - if(cf == NULL) +const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) { + CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); + if (cf == NULL) { return "CFDictionaryGetValue() failed"; + } return ffCfDataGetDataAsString(cf, result); } -const char* ffCfDictGetBool(CFDictionaryRef dict, CFStringRef key, bool* result) -{ - CFBooleanRef cf = (CFBooleanRef)CFDictionaryGetValue(dict, key); - if(cf == NULL) +const char* ffCfDictGetBool(CFDictionaryRef dict, CFStringRef key, bool* result) { + CFBooleanRef cf = (CFBooleanRef) CFDictionaryGetValue(dict, key); + if (cf == NULL) { return "CFDictionaryGetValue() failed"; + } - if(CFGetTypeID(cf) != CFBooleanGetTypeID()) + if (CFGetTypeID(cf) != CFBooleanGetTypeID()) { return "TypeID is not 'CFBoolean'"; + } *result = CFBooleanGetValue(cf); return NULL; } -const char* ffCfDictGetInt(CFDictionaryRef dict, CFStringRef key, int* result) -{ - CFTypeRef cf = (CFTypeRef)CFDictionaryGetValue(dict, key); - if(cf == NULL) +const char* ffCfDictGetInt(CFDictionaryRef dict, CFStringRef key, int* result) { + CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); + if (cf == NULL) { return "CFDictionaryGetValue() failed"; + } return ffCfNumGetInt(cf, result); } -const char* ffCfDictGetInt64(CFDictionaryRef dict, CFStringRef key, int64_t* result) -{ - CFTypeRef cf = (CFTypeRef)CFDictionaryGetValue(dict, key); - if(cf == NULL) +const char* ffCfDictGetInt64(CFDictionaryRef dict, CFStringRef key, int64_t* result) { + CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); + if (cf == NULL) { return "CFDictionaryGetValue() failed"; + } return ffCfNumGetInt64(cf, result); } -const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offset, uint32_t size, uint8_t* result, uint32_t* length) -{ - CFTypeRef cf = (CFTypeRef)CFDictionaryGetValue(dict, key); - if(cf == NULL) +const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offset, uint32_t size, uint8_t* result, uint32_t* length) { + CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); + if (cf == NULL) { return "CFDictionaryGetValue() failed"; + } - if(CFGetTypeID(cf) != CFDataGetTypeID()) + if (CFGetTypeID(cf) != CFDataGetTypeID()) { return "TypeID is not 'CFData'"; + } - CFIndex trueLength = CFDataGetLength((CFDataRef)cf); + CFIndex trueLength = CFDataGetLength((CFDataRef) cf); - if(trueLength < offset + size) + if (trueLength < offset + size) { return "Data length is less than offset + size"; + } - if(length) + if (length) { *length = (uint32_t) trueLength; + } - CFDataGetBytes((CFDataRef)cf, CFRangeMake(offset, size), result); + CFDataGetBytes((CFDataRef) cf, CFRangeMake(offset, size), result); return NULL; } -const char* ffCfDictGetDict(CFDictionaryRef dict, CFStringRef key, CFDictionaryRef* result) -{ - CFDictionaryRef cf = (CFDictionaryRef)CFDictionaryGetValue(dict, key); - if (cf == NULL || CFGetTypeID(cf) != CFDictionaryGetTypeID()) +const char* ffCfDictGetDict(CFDictionaryRef dict, CFStringRef key, CFDictionaryRef* result) { + CFDictionaryRef cf = (CFDictionaryRef) CFDictionaryGetValue(dict, key); + if (cf == NULL || CFGetTypeID(cf) != CFDictionaryGetTypeID()) { return "TypeID is not 'CFDictionary'"; + } *result = cf; return NULL; diff --git a/src/common/apple/cf_helpers.h b/src/common/apple/cf_helpers.h index c41a397dc..181faa309 100644 --- a/src/common/apple/cf_helpers.h +++ b/src/common/apple/cf_helpers.h @@ -4,7 +4,7 @@ #include #include -//Return error info if failed, NULL otherwise +// Return error info if failed, NULL otherwise const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result); const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result); const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result); @@ -17,24 +17,23 @@ const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offs const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result); const char* ffCfDictGetDict(CFDictionaryRef dict, CFStringRef key, CFDictionaryRef* result); -static inline CFNumberRef ffCfCreateInt(int value) -{ +static inline CFNumberRef ffCfCreateInt(int value) { return CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &value); } -static inline void cfReleaseWrapper(void* type) -{ +static inline void cfReleaseWrapper(void* type) { assert(type); - if (*(CFTypeRef*) type) + if (*(CFTypeRef*) type) { CFRelease(*(CFTypeRef*) type); + } } #define FF_CFTYPE_AUTO_RELEASE __attribute__((__cleanup__(cfReleaseWrapper))) -static inline void wrapIoObjectRelease(io_object_t* service) -{ +static inline void wrapIoObjectRelease(io_object_t* service) { assert(service); - if (*service) + if (*service) { IOObjectRelease(*service); + } } #define FF_IOOBJECT_AUTO_RELEASE __attribute__((__cleanup__(wrapIoObjectRelease))) diff --git a/src/common/apple/smc_temps.c b/src/common/apple/smc_temps.c index 0a31a5052..4d0e64f89 100644 --- a/src/common/apple/smc_temps.c +++ b/src/common/apple/smc_temps.c @@ -60,66 +60,64 @@ typedef struct SmcBytes_t bytes; } SmcVal_t; -static uint32_t smcStrtoul(const char *str, int size, int base) -{ +static uint32_t smcStrtoul(const char* str, int size, int base) { uint32_t total = 0; - for (int i = 0; i < size; i++) - { - if (base == 16) - total += (uint32_t)(str[i] << (size - 1 - i) * 8); - else - total += (uint32_t)((unsigned char)(str[i]) << (size - 1 - i) * 8); + for (int i = 0; i < size; i++) { + if (base == 16) { + total += (uint32_t) (str[i] << (size - 1 - i) * 8); + } else { + total += (uint32_t) ((unsigned char) (str[i]) << (size - 1 - i) * 8); + } } return total; } -static void smcUltostr(char *str, uint32_t val) -{ - str[0] = (char)(val >> 24); - str[1] = (char)(val >> 16); - str[2] = (char)(val >> 8); - str[3] = (char)val; +static void smcUltostr(char* str, uint32_t val) { + str[0] = (char) (val >> 24); + str[1] = (char) (val >> 16); + str[2] = (char) (val >> 8); + str[3] = (char) val; str[4] = '\0'; } -static const char *smcCall(io_connect_t conn, uint32_t selector, SmcKeyData_t *inputStructure, SmcKeyData_t *outputStructure) -{ +static const char* smcCall(io_connect_t conn, uint32_t selector, SmcKeyData_t* inputStructure, SmcKeyData_t* outputStructure) { size_t size = sizeof(SmcKeyData_t); - if (IOConnectCallStructMethod(conn, selector, inputStructure, size, outputStructure, &size) != kIOReturnSuccess) + if (IOConnectCallStructMethod(conn, selector, inputStructure, size, outputStructure, &size) != kIOReturnSuccess) { return "IOConnectCallStructMethod(conn) failed"; + } return NULL; } // Provides key info, using a cache to dramatically improve the energy impact of smcFanControl -static const char *smcGetKeyInfo(io_connect_t conn, const uint32_t key, SmcKeyData_keyInfo_t *key_info) -{ +static const char* smcGetKeyInfo(io_connect_t conn, const uint32_t key, SmcKeyData_keyInfo_t* key_info) { SmcKeyData_t inputStructure = {0}; SmcKeyData_t outputStructure = {0}; inputStructure.key = key; inputStructure.data8 = kSmcCmdReadKeyInfo; - const char *error = smcCall(conn, kKernelIndexSmc, &inputStructure, &outputStructure); - if (error) + const char* error = smcCall(conn, kKernelIndexSmc, &inputStructure, &outputStructure); + if (error) { return error; + } *key_info = outputStructure.keyInfo; return NULL; } -static const char *smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcVal_t *val) -{ +static const char* smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcVal_t* val) { SmcKeyData_t inputStructure = {0}; SmcKeyData_t outputStructure = {0}; inputStructure.key = smcStrtoul(key, 4, 16); strcpy(val->key, key); - const char *error = smcGetKeyInfo(conn, inputStructure.key, &outputStructure.keyInfo); - if (error) + const char* error = smcGetKeyInfo(conn, inputStructure.key, &outputStructure.keyInfo); + if (error) { return error; + } val->dataSize = outputStructure.keyInfo.dataSize; smcUltostr(val->dataType, outputStructure.keyInfo.dataType); @@ -127,132 +125,147 @@ static const char *smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcV inputStructure.data8 = kSmcCmdReadBytes; error = smcCall(conn, kKernelIndexSmc, &inputStructure, &outputStructure); - if (error) + if (error) { return error; + } memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes)); return NULL; } -static const char *smcOpen(io_connect_t *conn) -{ +static const char* smcOpen(io_connect_t* conn) { FF_IOOBJECT_AUTO_RELEASE io_object_t device = IOServiceGetMatchingService(MACH_PORT_NULL, IOServiceMatching("AppleSMC")); - if (!device) + if (!device) { return "No SMC device found"; + } - if (IOServiceOpen(device, mach_task_self(), 0, conn) != kIOReturnSuccess) + if (IOServiceOpen(device, mach_task_self(), 0, conn) != kIOReturnSuccess) { return "IOServiceOpen() failed"; + } return NULL; } -static const char *smcReadValue(io_connect_t conn, const UInt32Char_t key, double *value) -{ +static const char* smcReadValue(io_connect_t conn, const UInt32Char_t key, double* value) { SmcVal_t val = {0}; const char* error = smcReadSmcVal(conn, key, &val); - if (error != NULL) + if (error != NULL) { return error; - if (val.dataSize == 0) + } + if (val.dataSize == 0) { return "Empty SMC result"; + } - switch (val.dataType[0]) - { + switch (val.dataType[0]) { case 'u': // unsigned integer types - if (val.dataType[1] == 'i') - { - switch (val.dataSize) - { - case 1: *value = *(uint8_t *)(val.bytes); break; - case 2: *value = ntohs(*(uint16_t *)(val.bytes)); break; - case 4: *value = ntohl(*(uint32_t *)(val.bytes)); break; - case 8: *value = (double) ntohll(*(uint64_t *)(val.bytes)); break; + if (val.dataType[1] == 'i') { + switch (val.dataSize) { + case 1: + *value = *(uint8_t*) (val.bytes); + break; + case 2: + *value = ntohs(*(uint16_t*) (val.bytes)); + break; + case 4: + *value = ntohl(*(uint32_t*) (val.bytes)); + break; + case 8: + *value = (double) ntohll(*(uint64_t*) (val.bytes)); + break; default: return "Unsupported SMC unsigned integer data size"; } - } - else + } else { return "Unsupported SMC unsigned data type"; + } break; case 'f': // floating point types - if (ffStrEquals(val.dataType, "flt ") && val.dataSize == 4) - *value = *(float *)(val.bytes); - else if (val.dataType[1] == 'p' && val.dataSize == 2) // fixed point types + if (ffStrEquals(val.dataType, "flt ") && val.dataSize == 4) { + *value = *(float*) (val.bytes); + } else if (val.dataType[1] == 'p' && val.dataSize == 2) // fixed point types { - if (ffStrEquals(val.dataType, "fp1f")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 32768.0; - else if (ffStrEquals(val.dataType, "fp4c")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 4096.0; - else if (ffStrEquals(val.dataType, "fp5b")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 2048.0; - else if (ffStrEquals(val.dataType, "fp6a")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 1024.0; - else if (ffStrEquals(val.dataType, "fp79")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 512.0; - else if (ffStrEquals(val.dataType, "fp88")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 256.0; - else if (ffStrEquals(val.dataType, "fpa6")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 64.0; - else if (ffStrEquals(val.dataType, "fpc4")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 16.0; - else if (ffStrEquals(val.dataType, "fpe2")) - *value = ntohs(*(uint16_t *)(val.bytes)) / 4.0; - else + if (ffStrEquals(val.dataType, "fp1f")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 32768.0; + } else if (ffStrEquals(val.dataType, "fp4c")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 4096.0; + } else if (ffStrEquals(val.dataType, "fp5b")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 2048.0; + } else if (ffStrEquals(val.dataType, "fp6a")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 1024.0; + } else if (ffStrEquals(val.dataType, "fp79")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 512.0; + } else if (ffStrEquals(val.dataType, "fp88")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 256.0; + } else if (ffStrEquals(val.dataType, "fpa6")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 64.0; + } else if (ffStrEquals(val.dataType, "fpc4")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 16.0; + } else if (ffStrEquals(val.dataType, "fpe2")) { + *value = ntohs(*(uint16_t*) (val.bytes)) / 4.0; + } else { return "Unsupported SMC floating point data type"; - } - else + } + } else { return "Unsupported SMC floating point data type"; + } break; case 's': // signed integer types - if (val.dataType[1] == 'i') - { - switch (val.dataSize) - { - case 1: *value = *(int8_t *)(val.bytes); break; - case 2: *value = ntohs(*(int16_t *)(val.bytes)); break; - case 4: *value = ntohl(*(int32_t *)(val.bytes)); break; - case 8: *value = (double)ntohll(*(int64_t *)(val.bytes)); break; - default: return "Unsupported SMC signed integer data size"; + if (val.dataType[1] == 'i') { + switch (val.dataSize) { + case 1: + *value = *(int8_t*) (val.bytes); + break; + case 2: + *value = ntohs(*(int16_t*) (val.bytes)); + break; + case 4: + *value = ntohl(*(int32_t*) (val.bytes)); + break; + case 8: + *value = (double) ntohll(*(int64_t*) (val.bytes)); + break; + default: + return "Unsupported SMC signed integer data size"; } - } - else if (val.dataType[1] == 'p' && val.dataSize == 2) // signed fixed point types + } else if (val.dataType[1] == 'p' && val.dataSize == 2) // signed fixed point types { - if (ffStrEquals(val.dataType, "sp1e")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 16384.0; - else if (ffStrEquals(val.dataType, "sp3c")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 4096.0; - else if (ffStrEquals(val.dataType, "sp4b")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 2048.0; - else if (ffStrEquals(val.dataType, "sp5a")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 1024.0; - else if (ffStrEquals(val.dataType, "sp69")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 512.0; - else if (ffStrEquals(val.dataType, "sp78")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 256.0; - else if (ffStrEquals(val.dataType, "sp87")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 128.0; - else if (ffStrEquals(val.dataType, "sp96")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 64.0; - else if (ffStrEquals(val.dataType, "spb4")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 16.0; - else if (ffStrEquals(val.dataType, "spf0")) - *value = (int16_t)ntohs(*(int16_t *)(val.bytes)) / 1.0; - else + if (ffStrEquals(val.dataType, "sp1e")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 16384.0; + } else if (ffStrEquals(val.dataType, "sp3c")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 4096.0; + } else if (ffStrEquals(val.dataType, "sp4b")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 2048.0; + } else if (ffStrEquals(val.dataType, "sp5a")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 1024.0; + } else if (ffStrEquals(val.dataType, "sp69")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 512.0; + } else if (ffStrEquals(val.dataType, "sp78")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 256.0; + } else if (ffStrEquals(val.dataType, "sp87")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 128.0; + } else if (ffStrEquals(val.dataType, "sp96")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 64.0; + } else if (ffStrEquals(val.dataType, "spb4")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 16.0; + } else if (ffStrEquals(val.dataType, "spf0")) { + *value = (int16_t) ntohs(*(int16_t*) (val.bytes)) / 1.0; + } else { return "Unsupported SMC signed integer data type"; - } - else + } + } else { return "Unsupported SMC signed data type"; + } break; case '{': // special types like pwm - if (ffStrEquals(val.dataType, "{pwm") && val.dataSize == 2) - { - *value = (double)ntohs(*(uint16_t *)(val.bytes)) * 100 / 65536.0; - } - else + if (ffStrEquals(val.dataType, "{pwm") && val.dataSize == 2) { + *value = (double) ntohs(*(uint16_t*) (val.bytes)) * 100 / 65536.0; + } else { return "Unsupported SMC special data type"; + } break; default: @@ -261,187 +274,191 @@ static const char *smcReadValue(io_connect_t conn, const UInt32Char_t key, doubl return NULL; } -static bool detectTemp(io_connect_t conn, const char* sensor, double* sum) -{ +static bool detectTemp(io_connect_t conn, const char* sensor, double* sum) { double temp = 0; const char* error = smcReadValue(conn, sensor, &temp); - if (error) return false; + if (error) { + return false; + } // https://github.com/exelban/stats/blob/14e29c4d60229c363cca9c9d25c30c87b7870830/Modules/Sensors/readers.swift#L124 - if (temp < 10 || temp > 120) return false; + if (temp < 10 || temp > 120) { + return false; + } *sum += temp; return true; } static io_connect_t conn; -const char* ffDetectSmcSpecificTemp(const char* sensor, double* result) -{ - if (!conn) - { - if (smcOpen(&conn) != NULL) +const char* ffDetectSmcSpecificTemp(const char* sensor, double* result) { + if (!conn) { + if (smcOpen(&conn) != NULL) { conn = (io_connect_t) -1; + } } - if (conn == (io_connect_t) -1) + if (conn == (io_connect_t) -1) { return "Could not open SMC connection"; + } - if (!detectTemp(conn, sensor, result)) + if (!detectTemp(conn, sensor, result)) { return "Could not read SMC temperature"; + } return NULL; } -const char* ffDetectSmcTemps(enum FFTempType type, double* result) -{ - if (!conn) - { - if (smcOpen(&conn) != NULL) +const char* ffDetectSmcTemps(enum FFTempType type, double* result) { + if (!conn) { + if (smcOpen(&conn) != NULL) { conn = (io_connect_t) -1; + } } - if (conn == (io_connect_t) -1) + if (conn == (io_connect_t) -1) { return "Could not open SMC connection"; + } uint32_t count = 0; *result = 0; // https://github.com/exelban/stats/blob/master/Modules/Sensors/values.swift - switch (type) - { - case FF_TEMP_CPU_X64: - count += detectTemp(conn, "TC0D", result); // CPU diode - count += detectTemp(conn, "TC0E", result); // CPU diode virtual - count += detectTemp(conn, "TC0F", result); // CPU diode filtered - count += detectTemp(conn, "TC0P", result); // CPU proximity - break; + switch (type) { + case FF_TEMP_CPU_X64: + count += detectTemp(conn, "TC0D", result); // CPU diode + count += detectTemp(conn, "TC0E", result); // CPU diode virtual + count += detectTemp(conn, "TC0F", result); // CPU diode filtered + count += detectTemp(conn, "TC0P", result); // CPU proximity + break; - case FF_TEMP_CPU_M1X: - count += detectTemp(conn, "Tp09", result); // CPU efficient core 1 - count += detectTemp(conn, "Tp0T", result); // CPU efficient core 2 + case FF_TEMP_CPU_M1X: + count += detectTemp(conn, "Tp09", result); // CPU efficient core 1 + count += detectTemp(conn, "Tp0T", result); // CPU efficient core 2 - count += detectTemp(conn, "Tp01", result); // CPU performance core 1 - count += detectTemp(conn, "Tp05", result); // CPU performance core 2 - count += detectTemp(conn, "Tp0D", result); // CPU performance core 3 - count += detectTemp(conn, "Tp0H", result); // CPU performance core 4 - count += detectTemp(conn, "Tp0L", result); // CPU performance core 5 - count += detectTemp(conn, "Tp0P", result); // CPU performance core 6 - count += detectTemp(conn, "Tp0X", result); // CPU performance core 7 - count += detectTemp(conn, "Tp0b", result); // CPU performance core 8 - break; + count += detectTemp(conn, "Tp01", result); // CPU performance core 1 + count += detectTemp(conn, "Tp05", result); // CPU performance core 2 + count += detectTemp(conn, "Tp0D", result); // CPU performance core 3 + count += detectTemp(conn, "Tp0H", result); // CPU performance core 4 + count += detectTemp(conn, "Tp0L", result); // CPU performance core 5 + count += detectTemp(conn, "Tp0P", result); // CPU performance core 6 + count += detectTemp(conn, "Tp0X", result); // CPU performance core 7 + count += detectTemp(conn, "Tp0b", result); // CPU performance core 8 + break; - case FF_TEMP_CPU_M2X: - count += detectTemp(conn, "Tp1h", result); // CPU efficiency core 1 - count += detectTemp(conn, "Tp1t", result); // CPU efficiency core 2 - count += detectTemp(conn, "Tp1p", result); // CPU efficiency core 3 - count += detectTemp(conn, "Tp1l", result); // CPU efficiency core 4 + case FF_TEMP_CPU_M2X: + count += detectTemp(conn, "Tp1h", result); // CPU efficiency core 1 + count += detectTemp(conn, "Tp1t", result); // CPU efficiency core 2 + count += detectTemp(conn, "Tp1p", result); // CPU efficiency core 3 + count += detectTemp(conn, "Tp1l", result); // CPU efficiency core 4 - count += detectTemp(conn, "Tp01", result); // CPU performance core 1 - count += detectTemp(conn, "Tp05", result); // CPU performance core 2 - count += detectTemp(conn, "Tp09", result); // CPU performance core 3 - count += detectTemp(conn, "Tp0D", result); // CPU performance core 4 - count += detectTemp(conn, "Tp0X", result); // CPU performance core 5 - count += detectTemp(conn, "Tp0b", result); // CPU performance core 6 - count += detectTemp(conn, "Tp0f", result); // CPU performance core 7 - count += detectTemp(conn, "Tp0j", result); // CPU performance core 8 - break; + count += detectTemp(conn, "Tp01", result); // CPU performance core 1 + count += detectTemp(conn, "Tp05", result); // CPU performance core 2 + count += detectTemp(conn, "Tp09", result); // CPU performance core 3 + count += detectTemp(conn, "Tp0D", result); // CPU performance core 4 + count += detectTemp(conn, "Tp0X", result); // CPU performance core 5 + count += detectTemp(conn, "Tp0b", result); // CPU performance core 6 + count += detectTemp(conn, "Tp0f", result); // CPU performance core 7 + count += detectTemp(conn, "Tp0j", result); // CPU performance core 8 + break; - case FF_TEMP_CPU_M3X: - count += detectTemp(conn, "Te05", result); // CPU efficiency core 1 - count += detectTemp(conn, "Te0L", result); // CPU efficiency core 2 - count += detectTemp(conn, "Te0P", result); // CPU efficiency core 3 - count += detectTemp(conn, "Te0S", result); // CPU efficiency core 4 - count += detectTemp(conn, "Tf04", result); // CPU performance core 1 - count += detectTemp(conn, "Tf09", result); // CPU performance core 2 - count += detectTemp(conn, "Tf0A", result); // CPU performance core 3 - count += detectTemp(conn, "Tf0B", result); // CPU performance core 4 - count += detectTemp(conn, "Tf0D", result); // CPU performance core 5 - count += detectTemp(conn, "Tf0E", result); // CPU performance core 6 - count += detectTemp(conn, "Tf44", result); // CPU performance core 7 - count += detectTemp(conn, "Tf49", result); // CPU performance core 8 - count += detectTemp(conn, "Tf4A", result); // CPU performance core 9 - count += detectTemp(conn, "Tf4B", result); // CPU performance core 10 - count += detectTemp(conn, "Tf4D", result); // CPU performance core 11 - count += detectTemp(conn, "Tf4E", result); // CPU performance core 12 - break; + case FF_TEMP_CPU_M3X: + count += detectTemp(conn, "Te05", result); // CPU efficiency core 1 + count += detectTemp(conn, "Te0L", result); // CPU efficiency core 2 + count += detectTemp(conn, "Te0P", result); // CPU efficiency core 3 + count += detectTemp(conn, "Te0S", result); // CPU efficiency core 4 + count += detectTemp(conn, "Tf04", result); // CPU performance core 1 + count += detectTemp(conn, "Tf09", result); // CPU performance core 2 + count += detectTemp(conn, "Tf0A", result); // CPU performance core 3 + count += detectTemp(conn, "Tf0B", result); // CPU performance core 4 + count += detectTemp(conn, "Tf0D", result); // CPU performance core 5 + count += detectTemp(conn, "Tf0E", result); // CPU performance core 6 + count += detectTemp(conn, "Tf44", result); // CPU performance core 7 + count += detectTemp(conn, "Tf49", result); // CPU performance core 8 + count += detectTemp(conn, "Tf4A", result); // CPU performance core 9 + count += detectTemp(conn, "Tf4B", result); // CPU performance core 10 + count += detectTemp(conn, "Tf4D", result); // CPU performance core 11 + count += detectTemp(conn, "Tf4E", result); // CPU performance core 12 + break; - case FF_TEMP_CPU_M4X: - count += detectTemp(conn, "Te05", result); // CPU efficiency core 1 - count += detectTemp(conn, "Te0S", result); // CPU efficiency core 2 - count += detectTemp(conn, "Te09", result); // CPU efficiency core 3 - count += detectTemp(conn, "Te0H", result); // CPU efficiency core 4 - count += detectTemp(conn, "Tp01", result); // CPU performance core 1 - count += detectTemp(conn, "Tp05", result); // CPU performance core 2 - count += detectTemp(conn, "Tp09", result); // CPU performance core 3 - count += detectTemp(conn, "Tp0D", result); // CPU performance core 4 - count += detectTemp(conn, "Tp0V", result); // CPU performance core 5 - count += detectTemp(conn, "Tp0Y", result); // CPU performance core 6 - count += detectTemp(conn, "Tp0b", result); // CPU performance core 7 - count += detectTemp(conn, "Tp0e", result); // CPU performance core 8 - break; + case FF_TEMP_CPU_M4X: + count += detectTemp(conn, "Te05", result); // CPU efficiency core 1 + count += detectTemp(conn, "Te0S", result); // CPU efficiency core 2 + count += detectTemp(conn, "Te09", result); // CPU efficiency core 3 + count += detectTemp(conn, "Te0H", result); // CPU efficiency core 4 + count += detectTemp(conn, "Tp01", result); // CPU performance core 1 + count += detectTemp(conn, "Tp05", result); // CPU performance core 2 + count += detectTemp(conn, "Tp09", result); // CPU performance core 3 + count += detectTemp(conn, "Tp0D", result); // CPU performance core 4 + count += detectTemp(conn, "Tp0V", result); // CPU performance core 5 + count += detectTemp(conn, "Tp0Y", result); // CPU performance core 6 + count += detectTemp(conn, "Tp0b", result); // CPU performance core 7 + count += detectTemp(conn, "Tp0e", result); // CPU performance core 8 + break; - case FF_TEMP_GPU_INTEL: - count += detectTemp(conn, "TCGC", result); // GPU Intel Graphics - goto gpu_unknown; + case FF_TEMP_GPU_INTEL: + count += detectTemp(conn, "TCGC", result); // GPU Intel Graphics + goto gpu_unknown; - case FF_TEMP_GPU_AMD: - count += detectTemp(conn, "TGDD", result); // GPU AMD Radeon - goto gpu_unknown; + case FF_TEMP_GPU_AMD: + count += detectTemp(conn, "TGDD", result); // GPU AMD Radeon + goto gpu_unknown; - case FF_TEMP_GPU_UNKNOWN: // Nvidia? - gpu_unknown: - count += detectTemp(conn, "TG0D", result); // GPU diode - count += detectTemp(conn, "TG0P", result); // GPU proximity - break; + case FF_TEMP_GPU_UNKNOWN: // Nvidia? + gpu_unknown: + count += detectTemp(conn, "TG0D", result); // GPU diode + count += detectTemp(conn, "TG0P", result); // GPU proximity + break; - case FF_TEMP_GPU_M1X: - count += detectTemp(conn, "Tg05", result); // GPU 1 - count += detectTemp(conn, "Tg0D", result); // GPU 2 - count += detectTemp(conn, "Tg0L", result); // GPU 3 - count += detectTemp(conn, "Tg0T", result); // GPU 4 - break; + case FF_TEMP_GPU_M1X: + count += detectTemp(conn, "Tg05", result); // GPU 1 + count += detectTemp(conn, "Tg0D", result); // GPU 2 + count += detectTemp(conn, "Tg0L", result); // GPU 3 + count += detectTemp(conn, "Tg0T", result); // GPU 4 + break; - case FF_TEMP_GPU_M2X: - count += detectTemp(conn, "Tg0f", result); // GPU 1 - count += detectTemp(conn, "Tg0j", result); // GPU 2 - break; + case FF_TEMP_GPU_M2X: + count += detectTemp(conn, "Tg0f", result); // GPU 1 + count += detectTemp(conn, "Tg0j", result); // GPU 2 + break; - case FF_TEMP_GPU_M3X: - count += detectTemp(conn, "Tf14", result); // GPU 1 - count += detectTemp(conn, "Tf18", result); // GPU 2 - count += detectTemp(conn, "Tf19", result); // GPU 3 - count += detectTemp(conn, "Tf1A", result); // GPU 4 - count += detectTemp(conn, "Tf24", result); // GPU 5 - count += detectTemp(conn, "Tf28", result); // GPU 6 - count += detectTemp(conn, "Tf29", result); // GPU 7 - count += detectTemp(conn, "Tf2A", result); // GPU 8 - break; + case FF_TEMP_GPU_M3X: + count += detectTemp(conn, "Tf14", result); // GPU 1 + count += detectTemp(conn, "Tf18", result); // GPU 2 + count += detectTemp(conn, "Tf19", result); // GPU 3 + count += detectTemp(conn, "Tf1A", result); // GPU 4 + count += detectTemp(conn, "Tf24", result); // GPU 5 + count += detectTemp(conn, "Tf28", result); // GPU 6 + count += detectTemp(conn, "Tf29", result); // GPU 7 + count += detectTemp(conn, "Tf2A", result); // GPU 8 + break; - case FF_TEMP_GPU_M4X: - count += detectTemp(conn, "Tg0G", result); // GPU 1 (Basic) - count += detectTemp(conn, "Tg0H", result); // GPU 2 (Basic) - count += detectTemp(conn, "Tg1U", result); // GPU 1 (Pro / Max) - count += detectTemp(conn, "Tg1k", result); // GPU 2 (Pro / Max) - count += detectTemp(conn, "Tg0K", result); // GPU 3 - count += detectTemp(conn, "Tg0L", result); // GPU 4 - count += detectTemp(conn, "Tg0d", result); // GPU 5 - count += detectTemp(conn, "Tg0e", result); // GPU 6 - count += detectTemp(conn, "Tg0j", result); // GPU 7 - count += detectTemp(conn, "Tg0k", result); // GPU 8 - break; + case FF_TEMP_GPU_M4X: + count += detectTemp(conn, "Tg0G", result); // GPU 1 (Basic) + count += detectTemp(conn, "Tg0H", result); // GPU 2 (Basic) + count += detectTemp(conn, "Tg1U", result); // GPU 1 (Pro / Max) + count += detectTemp(conn, "Tg1k", result); // GPU 2 (Pro / Max) + count += detectTemp(conn, "Tg0K", result); // GPU 3 + count += detectTemp(conn, "Tg0L", result); // GPU 4 + count += detectTemp(conn, "Tg0d", result); // GPU 5 + count += detectTemp(conn, "Tg0e", result); // GPU 6 + count += detectTemp(conn, "Tg0j", result); // GPU 7 + count += detectTemp(conn, "Tg0k", result); // GPU 8 + break; - case FF_TEMP_BATTERY: - count += detectTemp(conn, "TB1T", result); // Battery - count += detectTemp(conn, "TB2T", result); // Battery - break; + case FF_TEMP_BATTERY: + count += detectTemp(conn, "TB1T", result); // Battery + count += detectTemp(conn, "TB2T", result); // Battery + break; - case FF_TEMP_MEMORY: - count += detectTemp(conn, "Tm02", result); // Memory 1 - count += detectTemp(conn, "Tm06", result); // Memory 2 - count += detectTemp(conn, "Tm08", result); // Memory 3 - count += detectTemp(conn, "Tm09", result); // Memory 4 - break; + case FF_TEMP_MEMORY: + count += detectTemp(conn, "Tm02", result); // Memory 1 + count += detectTemp(conn, "Tm06", result); // Memory 2 + count += detectTemp(conn, "Tm08", result); // Memory 3 + count += detectTemp(conn, "Tm09", result); // Memory 4 + break; } - if (count == 0) + if (count == 0) { return "No temperatures detected"; + } *result /= count; diff --git a/src/common/apple/smc_temps.h b/src/common/apple/smc_temps.h index 031f7c2e1..6783bb95b 100644 --- a/src/common/apple/smc_temps.h +++ b/src/common/apple/smc_temps.h @@ -2,15 +2,13 @@ #include "fastfetch.h" -typedef struct FFTempValue -{ +typedef struct FFTempValue { FFstrbuf name; FFstrbuf deviceClass; double value; } FFTempValue; -enum FFTempType -{ +enum FFTempType { FF_TEMP_CPU_X64, FF_TEMP_CPU_M1X, FF_TEMP_CPU_M2X, diff --git a/src/common/argType.h b/src/common/argType.h index 481f9d225..ff8b6c4cd 100644 --- a/src/common/argType.h +++ b/src/common/argType.h @@ -5,14 +5,12 @@ // For ffRegReadValue(s) // If length is 0, data will be allocated with malloc() and must be freed by the caller // Otherwise, data must point to a buffer of at least length bytes, and the actual length of the data will be written to length. -typedef struct FFArgBuffer -{ +typedef struct FFArgBuffer { void* data; uint32_t length; } FFArgBuffer; -typedef enum __attribute__((__packed__)) FFArgType -{ +typedef enum __attribute__((__packed__)) FFArgType { FF_ARG_TYPE_NULL = 0, FF_ARG_TYPE_UINT, FF_ARG_TYPE_UINT64, @@ -28,18 +26,19 @@ typedef enum __attribute__((__packed__)) FFArgType FF_ARG_TYPE_BUFFER, } FFArgType; -#define FF_ARG(variable, var_name) { _Generic((variable), \ - uint32_t: FF_ARG_TYPE_UINT, \ - uint64_t: FF_ARG_TYPE_UINT64, \ - uint16_t: FF_ARG_TYPE_UINT16, \ - uint8_t: FF_ARG_TYPE_UINT8, \ - int32_t: FF_ARG_TYPE_INT, \ - char*: FF_ARG_TYPE_STRING, \ - const char*: FF_ARG_TYPE_STRING, \ - FFstrbuf: FF_ARG_TYPE_STRBUF, \ - float: FF_ARG_TYPE_FLOAT, \ - double: FF_ARG_TYPE_DOUBLE, \ - FFlist: FF_ARG_TYPE_LIST, \ - bool: FF_ARG_TYPE_BOOL, \ - FFArgBuffer: FF_ARG_TYPE_BUFFER \ - ), _Generic((variable), char*: (variable), const char*: (variable), default: &(variable) ), (var_name) } +#define FF_ARG(variable, var_name) {_Generic((variable), \ + uint32_t: FF_ARG_TYPE_UINT, \ + uint64_t: FF_ARG_TYPE_UINT64, \ + uint16_t: FF_ARG_TYPE_UINT16, \ + uint8_t: FF_ARG_TYPE_UINT8, \ + int32_t: FF_ARG_TYPE_INT, \ + char*: FF_ARG_TYPE_STRING, \ + const char*: FF_ARG_TYPE_STRING, \ + FFstrbuf: FF_ARG_TYPE_STRBUF, \ + float: FF_ARG_TYPE_FLOAT, \ + double: FF_ARG_TYPE_DOUBLE, \ + FFlist: FF_ARG_TYPE_LIST, \ + bool: FF_ARG_TYPE_BOOL, \ + FFArgBuffer: FF_ARG_TYPE_BUFFER), \ + _Generic((variable), char*: (variable), const char*: (variable), default: &(variable)), \ + (var_name)} diff --git a/src/common/arrayUtils.h b/src/common/arrayUtils.h index 83a49d6aa..e248cd29b 100644 --- a/src/common/arrayUtils.h +++ b/src/common/arrayUtils.h @@ -3,14 +3,14 @@ #include #ifdef __has_builtin - #if !__cplusplus && FF_SUPPORTS_COUNT_OF - #define ARRAY_SIZE(x) _Countof(x) - #elif __has_builtin(__is_array) - #define ARRAY_SIZE(x) ({ static_assert(__is_array(__typeof__(x)), "Must be an array"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) - #elif __has_builtin(__builtin_types_compatible_p) - #define ARRAY_SIZE(x) ({ static_assert(!__builtin_types_compatible_p(__typeof__(x), __typeof__(&*(x))), "Must not be a pointer"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) - #endif +# if !__cplusplus && FF_SUPPORTS_COUNT_OF +# define ARRAY_SIZE(x) _Countof(x) +# elif __has_builtin(__is_array) +# define ARRAY_SIZE(x) ({ static_assert(__is_array(__typeof__(x)), "Must be an array"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) +# elif __has_builtin(__builtin_types_compatible_p) +# define ARRAY_SIZE(x) ({ static_assert(!__builtin_types_compatible_p(__typeof__(x), __typeof__(&*(x))), "Must not be a pointer"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) +# endif #endif #ifndef ARRAY_SIZE - #define ARRAY_SIZE(x) ((uint32_t) (sizeof(x) / sizeof(*(x)))) +# define ARRAY_SIZE(x) ((uint32_t) (sizeof(x) / sizeof(*(x)))) #endif diff --git a/src/common/base64.h b/src/common/base64.h index 5dc8ee7c6..d17da5c70 100644 --- a/src/common/base64.h +++ b/src/common/base64.h @@ -2,9 +2,8 @@ #include "fastfetch.h" -void ffBase64EncodeRaw(uint32_t size, const char *str, uint32_t *out_size, char *output); -static inline FFstrbuf ffBase64EncodeStrbuf(const FFstrbuf* in) -{ +void ffBase64EncodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output); +static inline FFstrbuf ffBase64EncodeStrbuf(const FFstrbuf* in) { FFstrbuf out = ffStrbufCreateA(10 + in->length * 4 / 3); ffBase64EncodeRaw(in->length, in->chars, &out.length, out.chars); assert(out.length < out.allocated); @@ -12,9 +11,8 @@ static inline FFstrbuf ffBase64EncodeStrbuf(const FFstrbuf* in) return out; } -bool ffBase64DecodeRaw(uint32_t size, const char *str, uint32_t *out_size, char *output); -static inline FFstrbuf ffBase64DecodeStrbuf(const FFstrbuf* in) -{ +bool ffBase64DecodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output); +static inline FFstrbuf ffBase64DecodeStrbuf(const FFstrbuf* in) { FFstrbuf out = ffStrbufCreateA(10 + in->length * 3 / 4); ffBase64DecodeRaw(in->length, in->chars, &out.length, out.chars); assert(out.length < out.allocated); diff --git a/src/common/dbus.h b/src/common/dbus.h index cecd744cb..1bfd3a239 100644 --- a/src/common/dbus.h +++ b/src/common/dbus.h @@ -1,13 +1,12 @@ #pragma once #ifdef FF_HAVE_DBUS -#include +# include -#include "common/FFstrbuf.h" -#include "common/library.h" +# include "common/FFstrbuf.h" +# include "common/library.h" -typedef struct FFDBusLibrary -{ +typedef struct FFDBusLibrary { FF_LIBRARY_SYMBOL(dbus_bus_get) FF_LIBRARY_SYMBOL(dbus_message_new_method_call) FF_LIBRARY_SYMBOL(dbus_message_append_args) @@ -22,13 +21,12 @@ typedef struct FFDBusLibrary FF_LIBRARY_SYMBOL(dbus_connection_unref) } FFDBusLibrary; -typedef struct FFDBusData -{ +typedef struct FFDBusData { const FFDBusLibrary* lib; DBusConnection* connection; } FFDBusData; -const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data); //Returns an error message or NULL on success +const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data); // Returns an error message or NULL on success 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); @@ -39,11 +37,10 @@ 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); void ffDBusDestroyData(FFDBusData* data); -static inline DBusMessage* ffDBusGetAllProperties(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface) -{ +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, NULL); } -#define FF_DBUS_AUTO_DESTROY_DATA __attribute__((__cleanup__(ffDBusDestroyData))) +# define FF_DBUS_AUTO_DESTROY_DATA __attribute__((__cleanup__(ffDBusDestroyData))) #endif // FF_HAVE_DBUS diff --git a/src/common/debug.h b/src/common/debug.h index 412fc2cb1..70b0a82b3 100644 --- a/src/common/debug.h +++ b/src/common/debug.h @@ -3,27 +3,29 @@ #include "fastfetch.h" #include "common/time.h" -static inline const char* ffFindFileName(const char* file) -{ +static inline const char* ffFindFileName(const char* file) { const char* lastSlash = __builtin_strrchr(file, '/'); - #ifdef _WIN32 - if (lastSlash == NULL) +#ifdef _WIN32 + if (lastSlash == NULL) { lastSlash = __builtin_strrchr(file, '\\'); - #endif - if (lastSlash != NULL) + } +#endif + if (lastSlash != NULL) { return lastSlash + 1; + } return file; } #ifndef NDEBUG - #define FF_DEBUG_PRINT(file_, line_, format_, ...) \ - do { \ - if (instance.config.display.debugMode) \ +# define FF_DEBUG_PRINT(file_, line_, format_, ...) \ + do { \ + if (instance.config.display.debugMode) \ fprintf(stderr, "[%s%4d, %s] " format_ "\n", ffFindFileName(file_), line_, ffTimeToTimeStr(ffTimeGetNow()), ##__VA_ARGS__); \ } while (0) #else - #define FF_DEBUG_PRINT(file_, line_, format_, ...) \ - do { } while (0) +# define FF_DEBUG_PRINT(file_, line_, format_, ...) \ + do { \ + } while (0) #endif #define FF_DEBUG(format, ...) FF_DEBUG_PRINT(__FILE__, __LINE__, format, ##__VA_ARGS__) diff --git a/src/common/ffdata.h b/src/common/ffdata.h index 51b401ff3..65edfbb17 100644 --- a/src/common/ffdata.h +++ b/src/common/ffdata.h @@ -2,8 +2,7 @@ #include "common/FFstrbuf.h" -typedef enum __attribute__((__packed__)) FFDataResultDocType -{ +typedef enum __attribute__((__packed__)) FFDataResultDocType { FF_RESULT_DOC_TYPE_DEFAULT = 0, FF_RESULT_DOC_TYPE_JSON, FF_RESULT_DOC_TYPE_CONFIG, @@ -12,13 +11,12 @@ typedef enum __attribute__((__packed__)) FFDataResultDocType // FFdata aggregates configuration, generation parameters, and output state used by fastfetch. // It holds the parsed configuration document, a mutable JSON document for results, and related metadata. -typedef struct FFdata -{ - yyjson_doc* configDoc; // Parsed JSON configuration document - yyjson_mut_doc* resultDoc; // Mutable JSON document for storing results - FFstrbuf structure; // Custom output structure from command line - FFstrbuf structureDisabled; // Disabled modules in the output structure from command line - FFstrbuf genConfigPath; // Path to generate configuration file +typedef struct FFdata { + yyjson_doc* configDoc; // Parsed JSON configuration document + yyjson_mut_doc* resultDoc; // Mutable JSON document for storing results + FFstrbuf structure; // Custom output structure from command line + FFstrbuf structureDisabled; // Disabled modules in the output structure from command line + FFstrbuf genConfigPath; // Path to generate configuration file FFDataResultDocType docType; // Type of result document bool configLoaded; } FFdata; diff --git a/src/common/font.h b/src/common/font.h index e10817eec..f9d25e7fd 100644 --- a/src/common/font.h +++ b/src/common/font.h @@ -3,8 +3,7 @@ #include "common/FFstrbuf.h" #include "common/FFlist.h" -typedef struct FFfont -{ +typedef struct FFfont { FFstrbuf pretty; FFstrbuf name; FFstrbuf size; @@ -21,7 +20,6 @@ void ffFontInitMoveValues(FFfont* font, FFstrbuf* name, FFstrbuf* size, FFstrbuf void ffFontInitWithSpace(FFfont* font, const char* rawName); void ffFontDestroy(FFfont* font); -static inline void ffFontInitCopy(FFfont* font, const char* name) -{ +static inline void ffFontInitCopy(FFfont* font, const char* name) { ffFontInitValues(font, name, NULL); } diff --git a/src/common/format.h b/src/common/format.h index 3c7ada6ae..f47fc8612 100644 --- a/src/common/format.h +++ b/src/common/format.h @@ -2,8 +2,7 @@ #include "common/argType.h" -typedef struct FFformatarg -{ +typedef struct FFformatarg { FFArgType type; const void* value; const char* name; // argument name, must start with an alphabet diff --git a/src/common/haiku/version.cpp b/src/common/haiku/version.cpp index 8dcf672ee..f8e65c3d5 100644 --- a/src/common/haiku/version.cpp +++ b/src/common/haiku/version.cpp @@ -5,20 +5,22 @@ extern "C" { #include #include -bool ffGetFileVersion(const char* filePath, FFstrbuf* version) -{ +bool ffGetFileVersion(const char* filePath, FFstrbuf* version) { BFile f(filePath, B_READ_ONLY); - if (f.InitCheck() != B_OK) + if (f.InitCheck() != B_OK) { return false; + } BAppFileInfo fileInfo(&f); - if (f.InitCheck() != B_OK) + if (f.InitCheck() != B_OK) { return false; + } version_info info; - if (fileInfo.GetVersionInfo(&info, B_SYSTEM_VERSION_KIND) != B_OK) + if (fileInfo.GetVersionInfo(&info, B_SYSTEM_VERSION_KIND) != B_OK) { return false; + } - ffStrbufSetF(version, "%d.%d.%d", (int)info.major, (int)info.middle, (int)info.minor); + ffStrbufSetF(version, "%d.%d.%d", (int) info.major, (int) info.middle, (int) info.minor); return true; } diff --git a/src/common/impl/FFPlatform.c b/src/common/impl/FFPlatform.c index f84ab5878..532e46271 100644 --- a/src/common/impl/FFPlatform.c +++ b/src/common/impl/FFPlatform.c @@ -3,8 +3,7 @@ #include "common/io.h" #include "detection/version/version.h" -void ffPlatformInit(FFPlatform* platform) -{ +void ffPlatformInit(FFPlatform* platform) { ffStrbufInit(&platform->homeDir); ffStrbufInit(&platform->cacheDir); ffListInit(&platform->configDirs, sizeof(FFstrbuf)); @@ -17,9 +16,9 @@ void ffPlatformInit(FFPlatform* platform) ffStrbufInit(&platform->hostName); ffStrbufInit(&platform->userShell); - #ifdef _WIN32 +#ifdef _WIN32 ffStrbufInit(&platform->sid); - #endif +#endif FFPlatformSysinfo* info = &platform->sysinfo; @@ -30,24 +29,27 @@ void ffPlatformInit(FFPlatform* platform) ffPlatformInitImpl(platform); - if(info->name.length == 0) + if (info->name.length == 0) { ffStrbufSetStatic(&info->name, ffVersionResult.sysName); + } - if(info->architecture.length == 0) + if (info->architecture.length == 0) { ffStrbufSetStatic(&info->architecture, ffVersionResult.architecture); + } } -void ffPlatformDestroy(FFPlatform* platform) -{ +void ffPlatformDestroy(FFPlatform* platform) { ffStrbufDestroy(&platform->homeDir); ffStrbufDestroy(&platform->cacheDir); - FF_LIST_FOR_EACH(FFstrbuf, dir, platform->configDirs) + FF_LIST_FOR_EACH (FFstrbuf, dir, platform->configDirs) { ffStrbufDestroy(dir); + } ffListDestroy(&platform->configDirs); - FF_LIST_FOR_EACH(FFstrbuf, dir, platform->dataDirs) + FF_LIST_FOR_EACH (FFstrbuf, dir, platform->dataDirs) { ffStrbufDestroy(dir); + } ffListDestroy(&platform->dataDirs); ffStrbufDestroy(&platform->exePath); ffStrbufDestroy(&platform->cwd); @@ -57,9 +59,9 @@ void ffPlatformDestroy(FFPlatform* platform) ffStrbufDestroy(&platform->userShell); ffStrbufDestroy(&platform->fullUserName); - #ifdef _WIN32 +#ifdef _WIN32 ffStrbufDestroy(&platform->sid); - #endif +#endif FFPlatformSysinfo* info = &platform->sysinfo; ffStrbufDestroy(&info->architecture); @@ -68,23 +70,24 @@ void ffPlatformDestroy(FFPlatform* platform) ffStrbufDestroy(&info->version); } -void ffPlatformPathAddAbsolute(FFlist* dirs, const char* path) -{ - if (!ffPathExists(path, FF_PATHTYPE_DIRECTORY)) +void ffPlatformPathAddAbsolute(FFlist* dirs, const char* path) { + if (!ffPathExists(path, FF_PATHTYPE_DIRECTORY)) { return; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreateS(path); ffStrbufEnsureEndsWithC(&buffer, '/'); - if (!ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) + if (!ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) { ffStrbufInitMove((FFstrbuf*) ffListAdd(dirs), &buffer); + } } -void ffPlatformPathAddHome(FFlist* dirs, const FFPlatform* platform, const char* suffix) -{ +void ffPlatformPathAddHome(FFlist* dirs, const FFPlatform* platform, const char* suffix) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreateA(64); ffStrbufAppend(&buffer, &platform->homeDir); ffStrbufAppendS(&buffer, suffix); ffStrbufEnsureEndsWithC(&buffer, '/'); - if (ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY) && !ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) + if (ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY) && !ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) { ffStrbufInitMove((FFstrbuf*) ffListAdd(dirs), &buffer); + } } diff --git a/src/common/impl/FFPlatform_unix.c b/src/common/impl/FFPlatform_unix.c index c93c863bd..1a07b011e 100644 --- a/src/common/impl/FFPlatform_unix.c +++ b/src/common/impl/FFPlatform_unix.c @@ -12,167 +12,161 @@ #include #ifdef __APPLE__ - #include - #include +# include +# include #elif defined(__FreeBSD__) || defined(__NetBSD__) - #include +# include #elif defined(__OpenBSD__) - #include - #include - #include "common/path.h" +# include +# include +# include "common/path.h" #elif defined(__HAIKU__) - #include - #include +# include +# include #endif -static void getExePath(FFPlatform* platform) -{ +static void getExePath(FFPlatform* platform) { char exePath[PATH_MAX]; - #if defined(__linux__) || defined (__GNU__) - ssize_t exePathLen = readlink("/proc/self/exe", exePath, sizeof(exePath) - 1); - if (exePathLen >= 0) - exePath[exePathLen] = '\0'; - #elif defined(__APPLE__) - uint32_t exePathLen = sizeof(exePath); - if (_NSGetExecutablePath(exePath, &exePathLen) == 0) - exePathLen = (uint32_t) strlen(exePath); - else - exePathLen = 0; - #elif defined(__FreeBSD__) || defined(__NetBSD__) - size_t exePathLen = sizeof(exePath); - if(sysctl( - (int[]){CTL_KERN, - #ifdef __FreeBSD__ - KERN_PROC, KERN_PROC_PATHNAME, (pid_t) platform->pid - #else - KERN_PROC_ARGS, platform->pid, KERN_PROC_PATHNAME - #endif - }, 4, - exePath, &exePathLen, - NULL, 0 - ) < 0) - exePathLen = 0; - else - exePathLen--; // remove terminating NUL - #elif defined(__OpenBSD__) - // OpenBSD doesn't have a reliable way to get the executable path. - // Current implementation uses argv[0], which can be easily spoofed. - // See #2195 - size_t exePathLen = 0; - kvm_t* kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL); - if (kd) - { - int kpCount; - struct kinfo_proc* kp = kvm_getprocs(kd, KERN_PROC_PID, (pid_t) platform->pid, sizeof(*kp), &kpCount); - if (kp && kpCount == 1) - { - char** argv = kvm_getargv(kd, kp, 0); - if (argv && argv[0]) - { - char* arg0 = argv[0]; - if (arg0[0]) +#if defined(__linux__) || defined(__GNU__) + ssize_t exePathLen = readlink("/proc/self/exe", exePath, sizeof(exePath) - 1); + if (exePathLen >= 0) { + exePath[exePathLen] = '\0'; + } +#elif defined(__APPLE__) + uint32_t exePathLen = sizeof(exePath); + if (_NSGetExecutablePath(exePath, &exePathLen) == 0) { + exePathLen = (uint32_t) strlen(exePath); + } else { + exePathLen = 0; + } +#elif defined(__FreeBSD__) || defined(__NetBSD__) + size_t exePathLen = sizeof(exePath); + if (sysctl( + (int[]) {CTL_KERN, +# ifdef __FreeBSD__ + KERN_PROC, + KERN_PROC_PATHNAME, + (pid_t) platform->pid +# else + KERN_PROC_ARGS, + platform->pid, + KERN_PROC_PATHNAME +# endif + }, + 4, + exePath, + &exePathLen, + NULL, + 0) < 0) + exePathLen = 0; + else { + exePathLen--; // remove terminating NUL + } +#elif defined(__OpenBSD__) + // OpenBSD doesn't have a reliable way to get the executable path. + // Current implementation uses argv[0], which can be easily spoofed. + // See #2195 + size_t exePathLen = 0; + kvm_t* kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL); + if (kd) { + int kpCount; + struct kinfo_proc* kp = kvm_getprocs(kd, KERN_PROC_PID, (pid_t) platform->pid, sizeof(*kp), &kpCount); + if (kp && kpCount == 1) { + char** argv = kvm_getargv(kd, kp, 0); + if (argv && argv[0]) { + char* arg0 = argv[0]; + if (arg0[0]) { + if (strchr(arg0, '/') != NULL) // likely a path (absolute or relative) { - if (strchr(arg0, '/') != NULL) // likely a path (absolute or relative) - { - exePathLen = strlen(arg0); - if (exePathLen < ARRAY_SIZE(exePath)) - { - memcpy(exePath, arg0, exePathLen); - exePath[exePathLen] = '\0'; - } - else - exePathLen = 0; + exePathLen = strlen(arg0); + if (exePathLen < ARRAY_SIZE(exePath)) { + memcpy(exePath, arg0, exePathLen); + exePath[exePathLen] = '\0'; + } else { + exePathLen = 0; } - else - { - FF_STRBUF_AUTO_DESTROY tmpPath = ffStrbufCreate(); - if (ffFindExecutableInPath(arg0, &tmpPath) == NULL && tmpPath.length < ARRAY_SIZE(exePath)) - { - memcpy(exePath, tmpPath.chars, tmpPath.length + 1); - exePathLen = tmpPath.length; - } + } else { + FF_STRBUF_AUTO_DESTROY tmpPath = ffStrbufCreate(); + if (ffFindExecutableInPath(arg0, &tmpPath) == NULL && tmpPath.length < ARRAY_SIZE(exePath)) { + memcpy(exePath, tmpPath.chars, tmpPath.length + 1); + exePathLen = tmpPath.length; } + } - if (exePathLen > 0) - { - struct stat st; - if (stat(exePath, &st) == 0 && S_ISREG(st.st_mode)) - { - int cntp; - struct kinfo_file* kf = kvm_getfiles(kd, KERN_FILE_BYPID, platform->pid, sizeof(*kf), &cntp); - if (kf) - { - int i; - for (i = 0; i < cntp; i++) - { - if (kf[i].fd_fd == KERN_FILE_TEXT) - { - // KERN_FILE_TEXT is the executable file, not a shared library, and should be unique in the list. - if (st.st_dev != (dev_t)kf[i].va_fsid || st.st_ino != (ino_t)kf[i].va_fileid) - i = -1; - break; + if (exePathLen > 0) { + struct stat st; + if (stat(exePath, &st) == 0 && S_ISREG(st.st_mode)) { + int cntp; + struct kinfo_file* kf = kvm_getfiles(kd, KERN_FILE_BYPID, platform->pid, sizeof(*kf), &cntp); + if (kf) { + int i; + for (i = 0; i < cntp; i++) { + if (kf[i].fd_fd == KERN_FILE_TEXT) { + // KERN_FILE_TEXT is the executable file, not a shared library, and should be unique in the list. + if (st.st_dev != (dev_t) kf[i].va_fsid || st.st_ino != (ino_t) kf[i].va_fileid) { + i = -1; } + break; } - if (i < 0) - exePathLen = 0; } - else - { - // If we can't get the list of open files, we can't verify that the file is actually the executable - // Assume it is + if (i < 0) { + exePathLen = 0; } + } else { + // If we can't get the list of open files, we can't verify that the file is actually the executable + // Assume it is } - else - exePathLen = 0; + } else { + exePathLen = 0; } } } } - kvm_close(kd); } - #elif defined(__sun) - ssize_t exePathLen = readlink("/proc/self/path/a.out", exePath, sizeof(exePath) - 1); - if (exePathLen >= 0) - exePath[exePathLen] = '\0'; - #elif defined(__HAIKU__) - size_t exePathLen = 0; - image_info info; - int32 cookie = 0; + kvm_close(kd); + } +#elif defined(__sun) + ssize_t exePathLen = readlink("/proc/self/path/a.out", exePath, sizeof(exePath) - 1); + if (exePathLen >= 0) { + exePath[exePathLen] = '\0'; + } +#elif defined(__HAIKU__) + size_t exePathLen = 0; + image_info info; + int32 cookie = 0; - while (get_next_image_info(B_CURRENT_TEAM, &cookie, &info) == B_OK) { - if (info.type == B_APP_IMAGE) { - exePathLen = strlcpy(exePath, info.name, sizeof(exePath)); - break; - } + while (get_next_image_info(B_CURRENT_TEAM, &cookie, &info) == B_OK) { + if (info.type == B_APP_IMAGE) { + exePathLen = strlcpy(exePath, info.name, sizeof(exePath)); + break; } - #endif - if (exePathLen > 0) - { + } +#endif + if (exePathLen > 0) { ffStrbufEnsureFree(&platform->exePath, PATH_MAX); - if (realpath(exePath, platform->exePath.chars)) + if (realpath(exePath, platform->exePath.chars)) { ffStrbufRecalculateLength(&platform->exePath); - else + } else { ffStrbufSetNS(&platform->exePath, (uint32_t) exePathLen, exePath); + } } } -static void platformPathAddEnv(FFlist* dirs, const char* env) -{ +static void platformPathAddEnv(FFlist* dirs, const char* env) { const char* envValue = getenv(env); - if(!ffStrSet(envValue)) + if (!ffStrSet(envValue)) { return; + } FF_STRBUF_AUTO_DESTROY value = ffStrbufCreateA(64); ffStrbufAppendS(&value, envValue); uint32_t startIndex = 0; - while (startIndex < value.length) - { + while (startIndex < value.length) { uint32_t colonIndex = ffStrbufNextIndexC(&value, startIndex, ':'); value.chars[colonIndex] = '\0'; - if(!ffStrSet(value.chars + startIndex)) - { + if (!ffStrSet(value.chars + startIndex)) { startIndex = colonIndex + 1; continue; } @@ -183,61 +177,53 @@ static void platformPathAddEnv(FFlist* dirs, const char* env) } } -static void getHomeDir(FFPlatform* platform, const struct passwd* pwd) -{ +static void getHomeDir(FFPlatform* platform, const struct passwd* pwd) { const char* home = pwd ? pwd->pw_dir : getenv("HOME"); ffStrbufAppendS(&platform->homeDir, home); ffStrbufEnsureEndsWithC(&platform->homeDir, '/'); } -static void getCacheDir(FFPlatform* platform) -{ +static void getCacheDir(FFPlatform* platform) { const char* cache = getenv("XDG_CACHE_HOME"); - if(ffStrSet(cache)) - { + if (ffStrSet(cache)) { ffStrbufAppendS(&platform->cacheDir, cache); ffStrbufEnsureEndsWithC(&platform->cacheDir, '/'); - } - else - { + } else { ffStrbufAppend(&platform->cacheDir, &platform->homeDir); ffStrbufAppendS(&platform->cacheDir, ".cache/"); } } -static void getConfigDirs(FFPlatform* platform) -{ +static void getConfigDirs(FFPlatform* platform) { // Always make sure `${XDG_CONFIG_HOME:-$HOME/.config}` is the first entry platformPathAddEnv(&platform->configDirs, "XDG_CONFIG_HOME"); ffPlatformPathAddHome(&platform->configDirs, platform, ".config/"); - #if defined(__APPLE__) - ffPlatformPathAddHome(&platform->configDirs, platform, "Library/Preferences/"); - ffPlatformPathAddHome(&platform->configDirs, platform, "Library/Application Support/"); - #endif - #if defined(__HAIKU__) - ffPlatformPathAddHome(&platform->configDirs, platform, "config/settings/"); - #endif +#if defined(__APPLE__) + ffPlatformPathAddHome(&platform->configDirs, platform, "Library/Preferences/"); + ffPlatformPathAddHome(&platform->configDirs, platform, "Library/Application Support/"); +#endif +#if defined(__HAIKU__) + ffPlatformPathAddHome(&platform->configDirs, platform, "config/settings/"); +#endif ffPlatformPathAddHome(&platform->configDirs, platform, ""); platformPathAddEnv(&platform->configDirs, "XDG_CONFIG_DIRS"); - #if !defined(__APPLE__) - ffPlatformPathAddAbsolute(&platform->configDirs, FASTFETCH_TARGET_DIR_ETC "/xdg/"); - #endif +#if !defined(__APPLE__) + ffPlatformPathAddAbsolute(&platform->configDirs, FASTFETCH_TARGET_DIR_ETC "/xdg/"); +#endif ffPlatformPathAddAbsolute(&platform->configDirs, FASTFETCH_TARGET_DIR_ETC "/"); ffPlatformPathAddAbsolute(&platform->configDirs, FASTFETCH_TARGET_DIR_INSTALL_SYSCONF "/"); } -static void getDataDirs(FFPlatform* platform) -{ +static void getDataDirs(FFPlatform* platform) { platformPathAddEnv(&platform->dataDirs, "XDG_DATA_HOME"); ffPlatformPathAddHome(&platform->dataDirs, platform, ".local/share/"); // Add ${currentExePath}/../share - if (platform->exePath.length > 0) - { + if (platform->exePath.length > 0) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateCopy(&platform->exePath); ffStrbufSubstrBeforeLastC(&path, '/'); ffStrbufSubstrBeforeLastC(&path, '/'); @@ -245,9 +231,9 @@ static void getDataDirs(FFPlatform* platform) ffPlatformPathAddAbsolute(&platform->dataDirs, path.chars); } - #ifdef __APPLE__ - ffPlatformPathAddHome(&platform->dataDirs, platform, "Library/Application Support/"); - #endif +#ifdef __APPLE__ + ffPlatformPathAddHome(&platform->dataDirs, platform, "Library/Application Support/"); +#endif ffPlatformPathAddHome(&platform->dataDirs, platform, ""); platformPathAddEnv(&platform->dataDirs, "XDG_DATA_DIRS"); @@ -258,74 +244,66 @@ static void getDataDirs(FFPlatform* platform) ffPlatformPathAddAbsolute(&platform->dataDirs, FASTFETCH_TARGET_DIR_USR "/share/"); } -static void getUserName(FFPlatform* platform, const struct passwd* pwd) -{ - if (pwd) - { +static void getUserName(FFPlatform* platform, const struct passwd* pwd) { + if (pwd) { ffStrbufSetS(&platform->userName, pwd->pw_name); ffStrbufSetS(&platform->fullUserName, pwd->pw_gecos); ffStrbufTrimSpace(&platform->fullUserName); - } - else - { + } else { ffStrbufSetS(&platform->userName, getenv("USER")); } } -static void getHostName(FFPlatform* platform, const struct utsname* uts) -{ +static void getHostName(FFPlatform* platform, const struct utsname* uts) { ffStrbufAppendS(&platform->hostName, uts->nodename); } -static void getUserShell(FFPlatform* platform, const struct passwd* pwd) -{ +static void getUserShell(FFPlatform* platform, const struct passwd* pwd) { const char* shell = getenv("SHELL"); - if(!ffStrSet(shell) && pwd) + if (!ffStrSet(shell) && pwd) { shell = pwd->pw_shell; + } ffStrbufAppendS(&platform->userShell, shell); } -static void getSysinfo(FFPlatformSysinfo* info, const struct utsname* uts) -{ +static void getSysinfo(FFPlatformSysinfo* info, const struct utsname* uts) { ffStrbufAppendS(&info->name, uts->sysname); ffStrbufAppendS(&info->release, uts->release); ffStrbufAppendS(&info->version, uts->version); - #ifdef __HAIKU__ +#ifdef __HAIKU__ /* historical reason */ - if (ffStrEquals(uts->machine, "BePC")) + if (ffStrEquals(uts->machine, "BePC")) { ffStrbufSetStatic(&info->architecture, "i386"); - else - #endif - ffStrbufAppendS(&info->architecture, uts->machine); + } else +#endif + ffStrbufAppendS(&info->architecture, uts->machine); - #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__) +#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__) size_t length = sizeof(info->pageSize); - sysctl((int[]){ CTL_HW, HW_PAGESIZE }, 2, &info->pageSize, &length, NULL, 0); - #else + sysctl((int[]) {CTL_HW, HW_PAGESIZE}, 2, &info->pageSize, &length, NULL, 0); +#else info->pageSize = (uint32_t) sysconf(_SC_PAGESIZE); - #endif +#endif } -static void getCwd(FFPlatform* platform) -{ +static void getCwd(FFPlatform* platform) { char cwd[PATH_MAX]; - if (getcwd(cwd, sizeof(cwd)) != NULL) - { + if (getcwd(cwd, sizeof(cwd)) != NULL) { ffStrbufSetS(&platform->cwd, cwd); ffStrbufEnsureEndsWithC(&platform->cwd, '/'); } } -void ffPlatformInitImpl(FFPlatform* platform) -{ +void ffPlatformInitImpl(FFPlatform* platform) { platform->pid = (uint32_t) getpid(); platform->uid = getuid(); struct passwd* pwd = getpwuid(platform->uid); struct utsname uts; - if(uname(&uts) < 0) + if (uname(&uts) < 0) { memset(&uts, 0, sizeof(uts)); + } getExePath(platform); getCwd(platform); diff --git a/src/common/impl/FFPlatform_windows.c b/src/common/impl/FFPlatform_windows.c index 1dc377766..5490ca689 100644 --- a/src/common/impl/FFPlatform_windows.c +++ b/src/common/impl/FFPlatform_windows.c @@ -14,8 +14,7 @@ #define SECURITY_WIN32 1 // For secext.h #include -static void getExePath(FFPlatform* platform) -{ +static void getExePath(FFPlatform* platform) { wchar_t exePathW[MAX_PATH]; FF_AUTO_CLOSE_FD HANDLE hPath = CreateFileW( @@ -26,19 +25,17 @@ static void getExePath(FFPlatform* platform) OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (hPath != INVALID_HANDLE_VALUE) - { + if (hPath != INVALID_HANDLE_VALUE) { DWORD len = GetFinalPathNameByHandleW(hPath, exePathW, MAX_PATH, FILE_NAME_NORMALIZED); - if (len > 0 && len < MAX_PATH) - { + if (len > 0 && len < MAX_PATH) { ffStrbufSetNWS(&platform->exePath, len, exePathW); - if (ffStrbufStartsWithS(&platform->exePath, "\\\\?\\")) + if (ffStrbufStartsWithS(&platform->exePath, "\\\\?\\")) { ffStrbufSubstrAfter(&platform->exePath, 3); + } } } - if (platform->exePath.length == 0) - { + if (platform->exePath.length == 0) { PCUNICODE_STRING imagePathName = &ffGetPeb()->ProcessParameters->ImagePathName; ffStrbufSetNWS(&platform->exePath, imagePathName->Length / sizeof(wchar_t), imagePathName->Buffer); } @@ -46,17 +43,13 @@ static void getExePath(FFPlatform* platform) ffStrbufReplaceAllC(&platform->exePath, '\\', '/'); } -static void getHomeDir(FFPlatform* platform) -{ +static void getHomeDir(FFPlatform* platform) { PWSTR pPath = NULL; - if(SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &pPath))) - { + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &pPath))) { ffStrbufSetWS(&platform->homeDir, pPath); ffStrbufReplaceAllC(&platform->homeDir, '\\', '/'); ffStrbufEnsureEndsWithC(&platform->homeDir, '/'); - } - else - { + } else { ffStrbufSetS(&platform->homeDir, getenv("USERPROFILE")); ffStrbufReplaceAllC(&platform->homeDir, '\\', '/'); ffStrbufEnsureEndsWithC(&platform->homeDir, '/'); @@ -64,61 +57,54 @@ static void getHomeDir(FFPlatform* platform) CoTaskMemFree(pPath); } -static void getCacheDir(FFPlatform* platform) -{ +static void getCacheDir(FFPlatform* platform) { PWSTR pPath = NULL; - if(SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, NULL, &pPath))) - { + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, NULL, &pPath))) { ffStrbufSetWS(&platform->cacheDir, pPath); ffStrbufReplaceAllC(&platform->cacheDir, '\\', '/'); ffStrbufEnsureEndsWithC(&platform->cacheDir, '/'); - } - else - { + } else { ffStrbufAppend(&platform->cacheDir, &platform->homeDir); ffStrbufAppendS(&platform->cacheDir, "AppData/Local/"); } CoTaskMemFree(pPath); } -static void platformPathAddKnownFolder(FFlist* dirs, REFKNOWNFOLDERID folderId) -{ +static void platformPathAddKnownFolder(FFlist* dirs, REFKNOWNFOLDERID folderId) { PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT, NULL, &pPath))) - { + if (SUCCEEDED(SHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT, NULL, &pPath))) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreateWS(pPath); CoTaskMemFree(pPath); ffStrbufReplaceAllC(&buffer, '\\', '/'); ffStrbufEnsureEndsWithC(&buffer, '/'); - if (!ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) + if (!ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) { ffStrbufInitMove((FFstrbuf*) ffListAdd(dirs), &buffer); + } } } -static void platformPathAddEnvSuffix(FFlist* dirs, const char* env, const char* suffix) -{ +static void platformPathAddEnvSuffix(FFlist* dirs, const char* env, const char* suffix) { const char* value = getenv(env); - if(!ffStrSet(value)) + if (!ffStrSet(value)) { return; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreateA(64); ffStrbufAppendS(&buffer, value); ffStrbufReplaceAllC(&buffer, '\\', '/'); ffStrbufEnsureEndsWithC(&buffer, '/'); - if (suffix) - { + if (suffix) { ffStrbufAppendS(&buffer, suffix); ffStrbufEnsureEndsWithC(&buffer, '/'); } - if (ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY) && !ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) + if (ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY) && !ffListContains(dirs, &buffer, (void*) ffStrbufEqual)) { ffStrbufInitMove((FFstrbuf*) ffListAdd(dirs), &buffer); + } } -static void getConfigDirs(FFPlatform* platform) -{ - if(getenv("MSYSTEM")) - { +static void getConfigDirs(FFPlatform* platform) { + if (getenv("MSYSTEM")) { // We are in MSYS2 / Git Bash platformPathAddEnvSuffix(&platform->configDirs, "HOME", ".config/"); platformPathAddEnvSuffix(&platform->configDirs, "HOME", NULL); @@ -132,10 +118,8 @@ static void getConfigDirs(FFPlatform* platform) ffPlatformPathAddHome(&platform->configDirs, platform, ""); } -static void getDataDirs(FFPlatform* platform) -{ - if(getenv("MSYSTEM") && getenv("HOME")) - { +static void getDataDirs(FFPlatform* platform) { + if (getenv("MSYSTEM") && getenv("HOME")) { // We are in MSYS2 / Git Bash platformPathAddEnvSuffix(&platform->dataDirs, "HOME", ".local/share/"); platformPathAddEnvSuffix(&platform->dataDirs, "HOME", NULL); @@ -148,75 +132,77 @@ static void getDataDirs(FFPlatform* platform) ffPlatformPathAddHome(&platform->dataDirs, platform, ""); } -static void getUserName(FFPlatform* platform) -{ +static void getUserName(FFPlatform* platform) { wchar_t buffer[256]; DWORD size = ARRAY_SIZE(buffer); - if (GetUserNameExW(NameDisplay, buffer, &size)) + if (GetUserNameExW(NameDisplay, buffer, &size)) { ffStrbufSetWS(&platform->fullUserName, buffer); + } size = ARRAY_SIZE(buffer); - if (GetUserNameW(buffer, &size)) // GetUserNameExW(10002)? + if (GetUserNameW(buffer, &size)) { // GetUserNameExW(10002)? ffStrbufSetWS(&platform->userName, buffer); - else + } else { ffStrbufSetS(&platform->userName, getenv("USERNAME")); + } alignas(TOKEN_USER) char buf[SECURITY_MAX_SID_SIZE + sizeof(TOKEN_USER)]; - if (NT_SUCCESS(NtQueryInformationToken(NtCurrentProcessToken(), TokenUser, buf, sizeof(buf), &size))) - { + if (NT_SUCCESS(NtQueryInformationToken(NtCurrentProcessToken(), TokenUser, buf, sizeof(buf), &size))) { TOKEN_USER* tokenUser = (TOKEN_USER*) buf; - UNICODE_STRING sidString = { .Buffer = buffer, .Length = 0, .MaximumLength = sizeof(buffer) }; - if (NT_SUCCESS(RtlConvertSidToUnicodeString(&sidString, tokenUser->User.Sid, FALSE))) + UNICODE_STRING sidString = {.Buffer = buffer, .Length = 0, .MaximumLength = sizeof(buffer)}; + if (NT_SUCCESS(RtlConvertSidToUnicodeString(&sidString, tokenUser->User.Sid, FALSE))) { ffStrbufSetNWS(&platform->sid, sidString.Length / sizeof(wchar_t), sidString.Buffer); + } } } -static void getHostName(FFPlatform* platform) -{ +static void getHostName(FFPlatform* platform) { wchar_t buffer[256]; DWORD len = ARRAY_SIZE(buffer); - if (GetComputerNameExW(ComputerNameDnsHostname, buffer, &len) && len > 0) + if (GetComputerNameExW(ComputerNameDnsHostname, buffer, &len) && len > 0) { ffStrbufSetNWS(&platform->hostName, len, buffer); - else - { + } else { len = ARRAY_SIZE(buffer); - if (GetComputerNameExW(ComputerNameNetBIOS, buffer, &len) && len > 0) + if (GetComputerNameExW(ComputerNameNetBIOS, buffer, &len) && len > 0) { ffStrbufSetNWS(&platform->hostName, len, buffer); + } } } -static void getUserShell(FFPlatform* platform) -{ +static void getUserShell(FFPlatform* platform) { // Works in MSYS2 const char* userShell = getenv("SHELL"); - if (userShell) - { + if (userShell) { ffStrbufAppendS(&platform->userShell, userShell); ffStrbufReplaceAllC(&platform->userShell, '\\', '/'); } } -static const char* detectWine(void) -{ - const char * __cdecl wine_get_version(void); +static const char* detectWine(void) { + const char* __cdecl wine_get_version(void); void* hntdll = ffLibraryGetModule(L"ntdll.dll"); - if (!hntdll) return NULL; + if (!hntdll) { + return NULL; + } FF_LIBRARY_LOAD_SYMBOL_LAZY(hntdll, wine_get_version); - if (!ffwine_get_version) return NULL; + if (!ffwine_get_version) { + return NULL; + } return ffwine_get_version(); } -static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) -{ +static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) + if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) { return; + } uint32_t ubr = 0; ffRegReadValues(hKey, 2, (FFRegValueArg[]) { - FF_ARG(ubr, L"UBR"), - FF_ARG(info->version, L"BuildLabEx"), - }, NULL); + FF_ARG(ubr, L"UBR"), + FF_ARG(info->version, L"BuildLabEx"), + }, + NULL); PPEB_FULL peb = ffGetPeb(); @@ -228,87 +214,82 @@ static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) (unsigned) ubr); const char* wineVersion = detectWine(); - if (wineVersion) + if (wineVersion) { ffStrbufSetF(&info->name, "Wine_%s", wineVersion); - else + } else { ffStrbufSetStatic(&info->name, "WIN32_NT"); + } } -static void getSystemPageSize(FFPlatformSysinfo* info) -{ +static void getSystemPageSize(FFPlatformSysinfo* info) { SYSTEM_BASIC_INFORMATION sbi; - if (NT_SUCCESS(NtQuerySystemInformation(SystemBasicInformation, &sbi, sizeof(sbi), NULL))) + if (NT_SUCCESS(NtQuerySystemInformation(SystemBasicInformation, &sbi, sizeof(sbi), NULL))) { info->pageSize = sbi.PhysicalPageSize; - else + } else { info->pageSize = 4096; + } } -static void getSystemArchitecture(FFPlatformSysinfo* info) -{ +static void getSystemArchitecture(FFPlatformSysinfo* info) { SYSTEM_PROCESSOR_INFORMATION spi; - if (NT_SUCCESS(NtQuerySystemInformation(SystemProcessorInformation, &spi, sizeof(spi), NULL))) - { - switch (spi.ProcessorArchitecture) - { - case PROCESSOR_ARCHITECTURE_AMD64: - ffStrbufSetStatic(&info->architecture, "x86_64"); - break; - case PROCESSOR_ARCHITECTURE_IA64: - ffStrbufSetStatic(&info->architecture, "ia64"); - break; - case PROCESSOR_ARCHITECTURE_INTEL: - switch (spi.ProcessorLevel) - { - case 4: - ffStrbufSetStatic(&info->architecture, "i486"); - break; - case 5: - ffStrbufSetStatic(&info->architecture, "i586"); - break; - case 6: - ffStrbufSetStatic(&info->architecture, "i686"); - break; - default: - ffStrbufSetStatic(&info->architecture, "i386"); - break; - } - break; - case PROCESSOR_ARCHITECTURE_ARM64: - ffStrbufSetStatic(&info->architecture, "aarch64"); - break; - case PROCESSOR_ARCHITECTURE_ARM: - ffStrbufSetStatic(&info->architecture, "arm"); - break; - case PROCESSOR_ARCHITECTURE_PPC: - ffStrbufSetStatic(&info->architecture, "ppc"); - break; - case PROCESSOR_ARCHITECTURE_MIPS: - ffStrbufSetStatic(&info->architecture, "mips"); - break; - case PROCESSOR_ARCHITECTURE_ALPHA: - ffStrbufSetStatic(&info->architecture, "alpha"); - break; - case PROCESSOR_ARCHITECTURE_ALPHA64: - ffStrbufSetStatic(&info->architecture, "alpha64"); - break; - case PROCESSOR_ARCHITECTURE_UNKNOWN: - default: - ffStrbufSetStatic(&info->architecture, "unknown"); - break; + if (NT_SUCCESS(NtQuerySystemInformation(SystemProcessorInformation, &spi, sizeof(spi), NULL))) { + switch (spi.ProcessorArchitecture) { + case PROCESSOR_ARCHITECTURE_AMD64: + ffStrbufSetStatic(&info->architecture, "x86_64"); + break; + case PROCESSOR_ARCHITECTURE_IA64: + ffStrbufSetStatic(&info->architecture, "ia64"); + break; + case PROCESSOR_ARCHITECTURE_INTEL: + switch (spi.ProcessorLevel) { + case 4: + ffStrbufSetStatic(&info->architecture, "i486"); + break; + case 5: + ffStrbufSetStatic(&info->architecture, "i586"); + break; + case 6: + ffStrbufSetStatic(&info->architecture, "i686"); + break; + default: + ffStrbufSetStatic(&info->architecture, "i386"); + break; + } + break; + case PROCESSOR_ARCHITECTURE_ARM64: + ffStrbufSetStatic(&info->architecture, "aarch64"); + break; + case PROCESSOR_ARCHITECTURE_ARM: + ffStrbufSetStatic(&info->architecture, "arm"); + break; + case PROCESSOR_ARCHITECTURE_PPC: + ffStrbufSetStatic(&info->architecture, "ppc"); + break; + case PROCESSOR_ARCHITECTURE_MIPS: + ffStrbufSetStatic(&info->architecture, "mips"); + break; + case PROCESSOR_ARCHITECTURE_ALPHA: + ffStrbufSetStatic(&info->architecture, "alpha"); + break; + case PROCESSOR_ARCHITECTURE_ALPHA64: + ffStrbufSetStatic(&info->architecture, "alpha64"); + break; + case PROCESSOR_ARCHITECTURE_UNKNOWN: + default: + ffStrbufSetStatic(&info->architecture, "unknown"); + break; } } } -static void getCwd(FFPlatform* platform) -{ +static void getCwd(FFPlatform* platform) { PCURDIR cwd = &ffGetPeb()->ProcessParameters->CurrentDirectory; ffStrbufSetNWS(&platform->cwd, cwd->DosPath.Length / sizeof(WCHAR), cwd->DosPath.Buffer); ffStrbufReplaceAllC(&platform->cwd, '\\', '/'); ffStrbufEnsureEndsWithC(&platform->cwd, '/'); } -void ffPlatformInitImpl(FFPlatform* platform) -{ +void ffPlatformInitImpl(FFPlatform* platform) { platform->pid = (uint32_t) (uintptr_t) ffGetTeb()->ClientId.UniqueProcess; getExePath(platform); getCwd(platform); diff --git a/src/common/impl/FFlist.c b/src/common/impl/FFlist.c index f389ced41..3f98cd06f 100644 --- a/src/common/impl/FFlist.c +++ b/src/common/impl/FFlist.c @@ -3,19 +3,19 @@ #include #include -void* ffListAdd(FFlist* list) -{ - if(list->length == list->capacity) +void* ffListAdd(FFlist* list) { + if (list->length == list->capacity) { ffListReserve(list, list->capacity == 0 ? FF_LIST_DEFAULT_ALLOC : list->capacity * 2); + } ++list->length; return ffListGet(list, list->length - 1); } -bool ffListShift(FFlist* list, void* result) -{ - if(list->length == 0) +bool ffListShift(FFlist* list, void* result) { + if (list->length == 0) { return false; + } memcpy(result, list->data, list->elementSize); memmove(list->data, list->data + list->elementSize, (size_t) list->elementSize * (list->length - 1)); @@ -23,10 +23,10 @@ bool ffListShift(FFlist* list, void* result) return true; } -bool ffListPop(FFlist* list, void* result) -{ - if(list->length == 0) +bool ffListPop(FFlist* list, void* result) { + if (list->length == 0) { return false; + } memcpy(result, ffListGet(list, list->length - 1), list->elementSize); --list->length; diff --git a/src/common/impl/FFstrbuf.c b/src/common/impl/FFstrbuf.c index 5df26f7e0..aef8eef64 100644 --- a/src/common/impl/FFstrbuf.c +++ b/src/common/impl/FFstrbuf.c @@ -8,119 +8,120 @@ char* CHAR_NULL_PTR = ""; -void ffStrbufInitA(FFstrbuf* strbuf, uint32_t allocate) -{ +void ffStrbufInitA(FFstrbuf* strbuf, uint32_t allocate) { strbuf->allocated = allocate; - if(strbuf->allocated > 0) + if (strbuf->allocated > 0) { strbuf->chars = (char*) malloc(sizeof(char) * strbuf->allocated); + } - //This will set the length to zero and the null byte. + // This will set the length to zero and the null byte. ffStrbufClear(strbuf); } -void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) -{ +void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) { assert(format != NULL); char* buffer = NULL; int len = vasprintf(&buffer, format, arguments); assert(len >= 0); - ffStrbufInitMoveNS(strbuf, (uint32_t)len, buffer); + ffStrbufInitMoveNS(strbuf, (uint32_t) len, buffer); } // Takes ownership of `heapStr`. The caller must not free `heapStr` after calling this // function; the memory will be managed and freed via the associated FFstrbuf. -void ffStrbufInitMoveNS(FFstrbuf* strbuf, uint32_t length, char* heapStr) -{ +void ffStrbufInitMoveNS(FFstrbuf* strbuf, uint32_t length, char* heapStr) { assert(heapStr != NULL); strbuf->length = length; size_t allocSize = ffMallocUsableSize(heapStr); - if (allocSize == 0) + if (allocSize == 0) { allocSize = length + 1; - else if (allocSize > UINT32_MAX) + } else if (allocSize > UINT32_MAX) { allocSize = UINT32_MAX; + } strbuf->allocated = (uint32_t) allocSize; strbuf->chars = heapStr; } -void ffStrbufEnsureFree(FFstrbuf* strbuf, uint32_t free) -{ - if(ffStrbufGetFree(strbuf) >= free && !(strbuf->allocated == 0 && strbuf->length > 0)) +void ffStrbufEnsureFree(FFstrbuf* strbuf, uint32_t free) { + if (ffStrbufGetFree(strbuf) >= free && !(strbuf->allocated == 0 && strbuf->length > 0)) { return; + } uint32_t allocate = strbuf->allocated; - if(allocate < FASTFETCH_STRBUF_DEFAULT_ALLOC) + if (allocate < FASTFETCH_STRBUF_DEFAULT_ALLOC) { allocate = FASTFETCH_STRBUF_DEFAULT_ALLOC; - - while((strbuf->length + free + 1) > allocate) // + 1 for the null byte - allocate *= 2; - - if(strbuf->allocated == 0) - { - char* newbuf = malloc(sizeof(*strbuf->chars) * allocate); - if(strbuf->length == 0) - *newbuf = '\0'; - else - memcpy(newbuf, strbuf->chars, strbuf->length + 1); - strbuf->chars = newbuf; } - else + + while ((strbuf->length + free + 1) > allocate) { // + 1 for the null byte + allocate *= 2; + } + + if (strbuf->allocated == 0) { + char* newbuf = malloc(sizeof(*strbuf->chars) * allocate); + if (strbuf->length == 0) { + *newbuf = '\0'; + } else { + memcpy(newbuf, strbuf->chars, strbuf->length + 1); + } + strbuf->chars = newbuf; + } else { strbuf->chars = realloc(strbuf->chars, sizeof(*strbuf->chars) * allocate); + } strbuf->allocated = allocate; } // Ensure that at least `free` bytes are available in the buffer besides the current length // for an empty buffer, free + 1 length memory will be allocated(+1 for the NUL) -void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free) -{ +void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free) { uint32_t oldFree = ffStrbufGetFree(strbuf); - if (oldFree >= free && !(strbuf->allocated == 0 && strbuf->length > 0)) + if (oldFree >= free && !(strbuf->allocated == 0 && strbuf->length > 0)) { return; + } uint32_t newCap = strbuf->allocated + (free - oldFree); - if(strbuf->allocated == 0) - { + if (strbuf->allocated == 0) { newCap += strbuf->length + 1; char* newbuf = malloc(sizeof(*strbuf->chars) * newCap); - if(strbuf->length == 0) + if (strbuf->length == 0) { *newbuf = '\0'; - else + } else { memcpy(newbuf, strbuf->chars, strbuf->length + 1); + } strbuf->chars = newbuf; - } - else + } else { strbuf->chars = realloc(strbuf->chars, sizeof(*strbuf->chars) * newCap); + } strbuf->allocated = newCap; } -void ffStrbufClear(FFstrbuf* strbuf) -{ +void ffStrbufClear(FFstrbuf* strbuf) { assert(strbuf != NULL); - if(strbuf->allocated == 0) + if (strbuf->allocated == 0) { strbuf->chars = CHAR_NULL_PTR; - else + } else { strbuf->chars[0] = '\0'; + } strbuf->length = 0; } -void ffStrbufAppendC(FFstrbuf* strbuf, char c) -{ +void ffStrbufAppendC(FFstrbuf* strbuf, char c) { ffStrbufEnsureFree(strbuf, 1); strbuf->chars[strbuf->length++] = c; strbuf->chars[strbuf->length] = '\0'; } -void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) -{ - if (num == 0) return; +void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) { + if (num == 0) { + return; + } ffStrbufEnsureFree(strbuf, num); memset(&strbuf->chars[strbuf->length], c, num); @@ -128,10 +129,10 @@ void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) strbuf->chars[strbuf->length] = '\0'; } -void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) -{ - if(value == NULL || length == 0) +void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) { + if (value == NULL || length == 0) { return; + } ffStrbufEnsureFree(strbuf, length); memcpy(&strbuf->chars[strbuf->length], value, length); @@ -139,26 +140,25 @@ void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) strbuf->chars[strbuf->length] = '\0'; } -void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int(*transformFunc)(int)) -{ - if(value == NULL) +void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transformFunc)(int)) { + if (value == NULL) { return; + } - //Ensure capacity > 0 or the modification below will fail + // Ensure capacity > 0 or the modification below will fail uint32_t length = (uint32_t) strlen(value); - if(length == 0) + if (length == 0) { return; + } ffStrbufEnsureFree(strbuf, length); - for(uint32_t i = 0; value[i] != '\0'; i++) - { + for (uint32_t i = 0; value[i] != '\0'; i++) { strbuf->chars[strbuf->length++] = (char) transformFunc(value[i]); } strbuf->chars[strbuf->length] = '\0'; } -void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) -{ +void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) { assert(format != NULL); va_list copy; @@ -167,39 +167,39 @@ void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) uint32_t free = ffStrbufGetFree(strbuf); int written = vsnprintf(strbuf->chars + strbuf->length, strbuf->allocated > 0 ? free + 1 : 0, format, arguments); - if(written > 0 && (uint32_t) written > free) - { + if (written > 0 && (uint32_t) written > free) { ffStrbufEnsureFree(strbuf, (uint32_t) written); written = vsnprintf(strbuf->chars + strbuf->length, (uint32_t) written + 1, format, copy); } va_end(copy); - if(written > 0) + if (written > 0) { strbuf->length += (uint32_t) written; + } } -const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until) -{ - if(value == NULL) +const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until) { + if (value == NULL) { return NULL; + } const char* end = strchr(value, until); - if(end == NULL) + if (end == NULL) { ffStrbufAppendS(strbuf, value); - else + } else { ffStrbufAppendNS(strbuf, (uint32_t) (end - value), value); + } return end; } -void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) -{ +void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) { assert(format != NULL); va_list arguments; va_start(arguments, format); - if(strbuf->allocated == 0) { + if (strbuf->allocated == 0) { ffStrbufInitVF(strbuf, format, arguments); va_end(arguments); return; @@ -210,8 +210,7 @@ void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) va_end(arguments); } -void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) -{ +void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) { assert(format != NULL); va_list arguments; @@ -220,10 +219,10 @@ void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) va_end(arguments); } -void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value) -{ - if(value == NULL || length == 0) +void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value) { + if (value == NULL || length == 0) { return; + } ffStrbufEnsureFree(strbuf, length); memmove(strbuf->chars + length, strbuf->chars, strbuf->length + 1); // + 1 for the null byte @@ -231,30 +230,27 @@ void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value) strbuf->length += length; } -void ffStrbufPrependC(FFstrbuf* strbuf, char c) -{ +void ffStrbufPrependC(FFstrbuf* strbuf, char c) { ffStrbufEnsureFree(strbuf, 1); memmove(strbuf->chars + 1, strbuf->chars, strbuf->length + 1); // + 1 for the null byte strbuf->chars[0] = c; strbuf->length += 1; } -void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) -{ +void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) { assert(strbuf != NULL); - if (length == 0) - { + if (length == 0) { ffStrbufClear(strbuf); return; } assert(value != NULL); - if (strbuf->allocated < length + 1) - { - if (strbuf->allocated > 0) + if (strbuf->allocated < length + 1) { + if (strbuf->allocated > 0) { free(strbuf->chars); + } strbuf->allocated = length + 1; strbuf->chars = malloc(sizeof(char) * strbuf->allocated); } @@ -264,20 +260,17 @@ void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) strbuf->chars[length] = '\0'; } -void ffStrbufSet(FFstrbuf* strbuf, const FFstrbuf* value) -{ +void ffStrbufSet(FFstrbuf* strbuf, const FFstrbuf* value) { assert(value && value != strbuf); - if (value->length == 0) - { + if (value->length == 0) { ffStrbufClear(strbuf); return; } if (value->allocated == 0) // static string { - if (strbuf->allocated != 0) - { + if (strbuf->allocated != 0) { free(strbuf->chars); strbuf->allocated = 0; } @@ -288,21 +281,22 @@ void ffStrbufSet(FFstrbuf* strbuf, const FFstrbuf* value) ffStrbufSetNS(strbuf, value->length, value->chars); } -void ffStrbufTrimLeft(FFstrbuf* strbuf, char c) -{ - if(strbuf->length == 0) +void ffStrbufTrimLeft(FFstrbuf* strbuf, char c) { + if (strbuf->length == 0) { return; + } uint32_t index = 0; - while(index < strbuf->length && strbuf->chars[index] == c) + while (index < strbuf->length && strbuf->chars[index] == c) { ++index; + } - if(index == 0) + if (index == 0) { return; + } - if(strbuf->allocated == 0) - { - //static string + if (strbuf->allocated == 0) { + // static string strbuf->length -= index; strbuf->chars += index; return; @@ -313,21 +307,21 @@ void ffStrbufTrimLeft(FFstrbuf* strbuf, char c) strbuf->chars[strbuf->length] = '\0'; } -void ffStrbufTrimRight(FFstrbuf* strbuf, char c) -{ - if (strbuf->length == 0) +void ffStrbufTrimRight(FFstrbuf* strbuf, char c) { + if (strbuf->length == 0) { return; + } - if (!ffStrbufEndsWithC(strbuf, c)) + if (!ffStrbufEndsWithC(strbuf, c)) { return; + } - do + do { --strbuf->length; - while (ffStrbufEndsWithC(strbuf, c)); + } while (ffStrbufEndsWithC(strbuf, c)); - if (strbuf->allocated == 0) - { - //static string + if (strbuf->allocated == 0) { + // static string ffStrbufInitNS(strbuf, strbuf->length, strbuf->chars); return; } @@ -335,21 +329,22 @@ void ffStrbufTrimRight(FFstrbuf* strbuf, char c) strbuf->chars[strbuf->length] = '\0'; } -void ffStrbufTrimLeftSpace(FFstrbuf* strbuf) -{ - if(strbuf->length == 0) +void ffStrbufTrimLeftSpace(FFstrbuf* strbuf) { + if (strbuf->length == 0) { return; + } uint32_t index = 0; - while(index < strbuf->length && isspace(strbuf->chars[index])) + while (index < strbuf->length && isspace(strbuf->chars[index])) { ++index; + } - if(index == 0) + if (index == 0) { return; + } - if(strbuf->allocated == 0) - { - //static string + if (strbuf->allocated == 0) { + // static string strbuf->length -= index; strbuf->chars += index; return; @@ -360,21 +355,21 @@ void ffStrbufTrimLeftSpace(FFstrbuf* strbuf) strbuf->chars[strbuf->length] = '\0'; } -void ffStrbufTrimRightSpace(FFstrbuf* strbuf) -{ - if (strbuf->length == 0) +void ffStrbufTrimRightSpace(FFstrbuf* strbuf) { + if (strbuf->length == 0) { return; + } - if (!ffStrbufEndsWithFn(strbuf, isspace)) + if (!ffStrbufEndsWithFn(strbuf, isspace)) { return; + } - do + do { --strbuf->length; - while (ffStrbufEndsWithFn(strbuf, isspace)); + } while (ffStrbufEndsWithFn(strbuf, isspace)); - if (strbuf->allocated == 0) - { - //static string + if (strbuf->allocated == 0) { + // static string ffStrbufInitNS(strbuf, strbuf->length, strbuf->chars); return; } @@ -382,13 +377,12 @@ void ffStrbufTrimRightSpace(FFstrbuf* strbuf) strbuf->chars[strbuf->length] = '\0'; } -bool ffStrbufRemoveSubstr(FFstrbuf* strbuf, uint32_t startIndex, uint32_t endIndex) -{ - if(startIndex > strbuf->length || startIndex >= endIndex) +bool ffStrbufRemoveSubstr(FFstrbuf* strbuf, uint32_t startIndex, uint32_t endIndex) { + if (startIndex > strbuf->length || startIndex >= endIndex) { return false; + } - if(endIndex > strbuf->length) - { + if (endIndex > strbuf->length) { ffStrbufSubstrBefore(strbuf, startIndex); return true; } @@ -400,77 +394,73 @@ bool ffStrbufRemoveSubstr(FFstrbuf* strbuf, uint32_t startIndex, uint32_t endInd return true; } -void ffStrbufRemoveS(FFstrbuf* strbuf, const char* str) -{ +void ffStrbufRemoveS(FFstrbuf* strbuf, const char* str) { uint32_t stringLength = (uint32_t) strlen(str); - for(uint32_t i = ffStrbufNextIndexS(strbuf, 0, str); i < strbuf->length; i = ffStrbufNextIndexS(strbuf, i, str)) + for (uint32_t i = ffStrbufNextIndexS(strbuf, 0, str); i < strbuf->length; i = ffStrbufNextIndexS(strbuf, i, str)) { ffStrbufRemoveSubstr(strbuf, i, i + stringLength); + } } -void ffStrbufRemoveStrings(FFstrbuf* strbuf, uint32_t numStrings, const char* strings[]) -{ - for(uint32_t i = 0; i < numStrings; i++) +void ffStrbufRemoveStrings(FFstrbuf* strbuf, uint32_t numStrings, const char* strings[]) { + for (uint32_t i = 0; i < numStrings; i++) { ffStrbufRemoveS(strbuf, strings[i]); + } } -uint32_t ffStrbufNextIndexC(const FFstrbuf* strbuf, uint32_t start, char c) -{ +uint32_t ffStrbufNextIndexC(const FFstrbuf* strbuf, uint32_t start, char c) { assert(start <= strbuf->length); - const char* ptr = (const char*)memchr(strbuf->chars + start, c, strbuf->length - start); - return ptr ? (uint32_t)(ptr - strbuf->chars) : strbuf->length; + const char* ptr = (const char*) memchr(strbuf->chars + start, c, strbuf->length - start); + return ptr ? (uint32_t) (ptr - strbuf->chars) : strbuf->length; } -uint32_t ffStrbufNextIndexS(const FFstrbuf* strbuf, uint32_t start, const char* str) -{ +uint32_t ffStrbufNextIndexS(const FFstrbuf* strbuf, uint32_t start, const char* str) { assert(start <= strbuf->length); const char* ptr = strstr(strbuf->chars + start, str); - return ptr ? (uint32_t)(ptr - strbuf->chars) : strbuf->length; + return ptr ? (uint32_t) (ptr - strbuf->chars) : strbuf->length; } -uint32_t ffStrbufPreviousIndexC(const FFstrbuf* strbuf, uint32_t start, char c) -{ +uint32_t ffStrbufPreviousIndexC(const FFstrbuf* strbuf, uint32_t start, char c) { assert(start <= strbuf->length); - //We need to loop one higher than the actual index, because uint32_t is guaranteed to be >= 0, so this statement would always be true - for(uint32_t i = start + 1; i > 0; i--) - { - if(strbuf->chars[i - 1] == c) + // We need to loop one higher than the actual index, because uint32_t is guaranteed to be >= 0, so this statement would always be true + for (uint32_t i = start + 1; i > 0; i--) { + if (strbuf->chars[i - 1] == c) { return i - 1; + } } return strbuf->length; } -void ffStrbufReplaceAllC(FFstrbuf* strbuf, char find, char replace) -{ - if (strbuf->length == 0) +void ffStrbufReplaceAllC(FFstrbuf* strbuf, char find, char replace) { + if (strbuf->length == 0) { return; + } ffStrbufEnsureFree(strbuf, 0); for ( - char *current_pos = memchr(strbuf->chars, find, strbuf->length); + char* current_pos = memchr(strbuf->chars, find, strbuf->length); current_pos; current_pos = memchr( current_pos + 1, find, - strbuf->length - (uint32_t)(current_pos + 1 - strbuf->chars) - ) - ) + strbuf->length - (uint32_t) (current_pos + 1 - strbuf->chars))) { *current_pos = replace; + } } -bool ffStrbufSubstrBefore(FFstrbuf* strbuf, uint32_t index) -{ - if(strbuf->length <= index) +bool ffStrbufSubstrBefore(FFstrbuf* strbuf, uint32_t index) { + if (strbuf->length <= index) { return false; + } - if(strbuf->allocated == 0) - { - //static string - if (index < strbuf->length) + if (strbuf->allocated == 0) { + // static string + if (index < strbuf->length) { ffStrbufInitNS(strbuf, index, strbuf->chars); + } return true; } @@ -479,17 +469,14 @@ bool ffStrbufSubstrBefore(FFstrbuf* strbuf, uint32_t index) return true; } -bool ffStrbufSubstrAfter(FFstrbuf* strbuf, uint32_t index) -{ - if(index >= strbuf->length) - { +bool ffStrbufSubstrAfter(FFstrbuf* strbuf, uint32_t index) { + if (index >= strbuf->length) { ffStrbufClear(strbuf); return true; } - if(strbuf->allocated == 0) - { - //static string + if (strbuf->allocated == 0) { + // static string strbuf->length -= index + 1; strbuf->chars += index + 1; return true; @@ -501,48 +488,51 @@ bool ffStrbufSubstrAfter(FFstrbuf* strbuf, uint32_t index) return true; } -bool ffStrbufSubstrAfterFirstC(FFstrbuf* strbuf, char c) -{ +bool ffStrbufSubstrAfterFirstC(FFstrbuf* strbuf, char c) { uint32_t index = ffStrbufFirstIndexC(strbuf, c); - if(index >= strbuf->length) + if (index >= strbuf->length) { return false; + } ffStrbufSubstrAfter(strbuf, index); return true; } -bool ffStrbufSubstrAfterFirstS(FFstrbuf* strbuf, const char* str) -{ - if(*str == '\0') +bool ffStrbufSubstrAfterFirstS(FFstrbuf* strbuf, const char* str) { + if (*str == '\0') { return false; + } uint32_t index = ffStrbufFirstIndexS(strbuf, str) + (uint32_t) strlen(str) - 1; // -1, because firstIndexS is already pointing to str[0], we want to add only the remaining length - if(index >= strbuf->length) + if (index >= strbuf->length) { return false; + } ffStrbufSubstrAfter(strbuf, index); return true; } -bool ffStrbufSubstrAfterLastC(FFstrbuf* strbuf, char c) -{ +bool ffStrbufSubstrAfterLastC(FFstrbuf* strbuf, char c) { uint32_t index = ffStrbufLastIndexC(strbuf, c); - if(index >= strbuf->length) + if (index >= strbuf->length) { return false; + } ffStrbufSubstrAfter(strbuf, index); return true; } -bool ffStrbufSubstr(FFstrbuf* strbuf, uint32_t start, uint32_t end) -{ - if (__builtin_expect(start >= end, false)) - { +bool ffStrbufSubstr(FFstrbuf* strbuf, uint32_t start, uint32_t end) { + if (__builtin_expect(start >= end, false)) { ffStrbufClear(strbuf); return false; } - if (__builtin_expect(start == 0, false)) return ffStrbufSubstrBefore(strbuf, end); - if (__builtin_expect(end >= strbuf->length, false)) return ffStrbufSubstrAfter(strbuf, start - 1); + if (__builtin_expect(start == 0, false)) { + return ffStrbufSubstrBefore(strbuf, end); + } + if (__builtin_expect(end >= strbuf->length, false)) { + return ffStrbufSubstrAfter(strbuf, start - 1); + } uint32_t len = end - start; ffStrbufEnsureFixedLengthFree(strbuf, len); // In case of static string @@ -553,24 +543,20 @@ bool ffStrbufSubstr(FFstrbuf* strbuf, uint32_t start, uint32_t end) return true; } -uint32_t ffStrbufCountC(const FFstrbuf* strbuf, char c) -{ +uint32_t ffStrbufCountC(const FFstrbuf* strbuf, char c) { uint32_t result = 0; - for(uint32_t i = 0; i < strbuf->length; i++) - { - if(strbuf->chars[i] == c) + for (uint32_t i = 0; i < strbuf->length; i++) { + if (strbuf->chars[i] == c) { result++; + } } return result; } - -bool ffStrbufRemoveIgnCaseEndS(FFstrbuf* strbuf, const char* end) -{ +bool ffStrbufRemoveIgnCaseEndS(FFstrbuf* strbuf, const char* end) { uint32_t endLength = (uint32_t) strlen(end); - if(ffStrbufEndsWithIgnCaseNS(strbuf, endLength, end)) - { + if (ffStrbufEndsWithIgnCaseNS(strbuf, endLength, end)) { ffStrbufSubstrBefore(strbuf, strbuf->length - endLength); return true; } @@ -578,49 +564,43 @@ bool ffStrbufRemoveIgnCaseEndS(FFstrbuf* strbuf, const char* end) return false; } -bool ffStrbufEnsureEndsWithC(FFstrbuf* strbuf, char c) -{ - if(ffStrbufEndsWithC(strbuf, c)) +bool ffStrbufEnsureEndsWithC(FFstrbuf* strbuf, char c) { + if (ffStrbufEndsWithC(strbuf, c)) { return false; + } ffStrbufAppendC(strbuf, c); return true; } -void ffStrbufWriteTo(const FFstrbuf* strbuf, FILE* file) -{ +void ffStrbufWriteTo(const FFstrbuf* strbuf, FILE* file) { fwrite(strbuf->chars, sizeof(*strbuf->chars), strbuf->length, file); } -void ffStrbufPutTo(const FFstrbuf* strbuf, FILE* file) -{ +void ffStrbufPutTo(const FFstrbuf* strbuf, FILE* file) { ffStrbufWriteTo(strbuf, file); fputc('\n', file); } -double ffStrbufToDouble(const FFstrbuf* strbuf, double defaultValue) -{ +double ffStrbufToDouble(const FFstrbuf* strbuf, double defaultValue) { char* str_end; double result = strtod(strbuf->chars, &str_end); return str_end == strbuf->chars ? defaultValue : result; } -uint64_t ffStrbufToUInt(const FFstrbuf* strbuf, uint64_t defaultValue) -{ +uint64_t ffStrbufToUInt(const FFstrbuf* strbuf, uint64_t defaultValue) { char* str_end; unsigned long long result = strtoull(strbuf->chars, &str_end, 10); - return str_end == strbuf->chars ? defaultValue : (uint64_t)result; + return str_end == strbuf->chars ? defaultValue : (uint64_t) result; } -int64_t ffStrbufToSInt(const FFstrbuf* strbuf, int64_t defaultValue) -{ +int64_t ffStrbufToSInt(const FFstrbuf* strbuf, int64_t defaultValue) { char* str_end; long long result = strtoll(strbuf->chars, &str_end, 10); - return str_end == strbuf->chars ? defaultValue : (int64_t)result; + return str_end == strbuf->chars ? defaultValue : (int64_t) result; } -void ffStrbufAppendSInt(FFstrbuf* strbuf, int64_t value) -{ +void ffStrbufAppendSInt(FFstrbuf* strbuf, int64_t value) { ffStrbufEnsureFree(strbuf, 21); // Required by yyjson_write_number char* start = strbuf->chars + strbuf->length; @@ -630,11 +610,10 @@ void ffStrbufAppendSInt(FFstrbuf* strbuf, int64_t value) assert(end != NULL); - strbuf->length += (uint32_t)(end - start); + strbuf->length += (uint32_t) (end - start); } -void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value) -{ +void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value) { ffStrbufEnsureFree(strbuf, 21); // Required by yyjson_write_number char* start = strbuf->chars + strbuf->length; @@ -644,54 +623,49 @@ void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value) assert(end != NULL); - strbuf->length += (uint32_t)(end - start); + strbuf->length += (uint32_t) (end - start); } -void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool trailingZeros) -{ +void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool trailingZeros) { assert(precision <= 15); // yyjson_write_number supports up to 15 digits after the decimal point ffStrbufEnsureFree(strbuf, 40); // Required by yyjson_write_number char* start = strbuf->chars + strbuf->length; - if (precision == 0) + if (precision == 0) { value = round(value); + } yyjson_val val = {}; unsafe_yyjson_set_double(&val, value); - if (precision > 0) + if (precision > 0) { unsafe_yyjson_set_fp_to_fixed(&val, precision); + } // Write at most digits after the decimal point; doesn't append trailing zeros char* end = yyjson_write_number(&val, start); assert(end > start); - strbuf->length += (uint32_t)(end - start); + strbuf->length += (uint32_t) (end - start); - if (__builtin_expect(value > 1e21 || value < -1e21, false)) - { + if (__builtin_expect(value > 1e21 || value < -1e21, false)) { // If the value is too large, yyjson_write_number will write it in scientific notation return; } - if (trailingZeros) - { - if (precision > 1) - { - for (char* p = end - 1; *p != '.' && p > start; --p) + if (trailingZeros) { + if (precision > 1) { + for (char* p = end - 1; *p != '.' && p > start; --p) { --precision; - if (precision > 0) + } + if (precision > 0) { ffStrbufAppendNC(strbuf, (uint32_t) precision, '0'); - } - else if (precision == 0 || (precision < 0 && end[-1] == '0')) - { + } + } else if (precision == 0 || (precision < 0 && end[-1] == '0')) { goto removeDecimalPoint; } - } - else - { - if (end[-1] == '0') - { + } else { + if (end[-1] == '0') { removeDecimalPoint: // yyjson always appends ".0" to make it a float point number. We need to remove it strbuf->length -= 2; @@ -700,23 +674,25 @@ void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool } } -void ffStrbufUpperCase(FFstrbuf* strbuf) -{ - for (uint32_t i = 0; i < strbuf->length; ++i) +void ffStrbufUpperCase(FFstrbuf* strbuf) { + for (uint32_t i = 0; i < strbuf->length; ++i) { strbuf->chars[i] = (char) toupper(strbuf->chars[i]); + } } -void ffStrbufLowerCase(FFstrbuf* strbuf) -{ - for (uint32_t i = 0; i < strbuf->length; ++i) +void ffStrbufLowerCase(FFstrbuf* strbuf) { + for (uint32_t i = 0; i < strbuf->length; ++i) { strbuf->chars[i] = (char) tolower(strbuf->chars[i]); + } } -void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c) -{ - if(num == 0) return; - if (index >= strbuf->length) +void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c) { + if (num == 0) { + return; + } + if (index >= strbuf->length) { index = strbuf->length; + } ffStrbufEnsureFree(strbuf, num); memmove(strbuf->chars + index + num, strbuf->chars + index, strbuf->length - index + 1); @@ -724,66 +700,70 @@ void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c) strbuf->length += num; } -bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer) -{ +bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer) { assert(lineptr && n && buffer); assert(buffer->allocated > 0 || (buffer->allocated == 0 && buffer->length == 0)); assert(!*lineptr || (*lineptr >= buffer->chars && *lineptr <= buffer->chars + buffer->length)); const char* pBufferEnd = buffer->chars + buffer->length; - if (!*lineptr) + if (!*lineptr) { *lineptr = buffer->chars; - else - { + } else { *lineptr += *n; - if (*lineptr >= pBufferEnd) // non-empty last line + if (*lineptr >= pBufferEnd) { // non-empty last line return false; + } **lineptr = delimiter; ++*lineptr; } - if (*lineptr >= pBufferEnd) // empty last line + if (*lineptr >= pBufferEnd) { // empty last line return false; + } size_t remaining = (size_t) (pBufferEnd - *lineptr); char* ending = memchr(*lineptr, delimiter, remaining); - if (ending) - { + if (ending) { *n = (size_t) (ending - *lineptr); *ending = '\0'; - } - else + } else { *n = remaining; + } return true; } -void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer) -{ +void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer) { assert(buffer && lineptr && n); assert(buffer->allocated > 0 || (buffer->allocated == 0 && buffer->length == 0)); assert(!*lineptr || (*lineptr >= buffer->chars && *lineptr <= buffer->chars + buffer->length)); - if (!*lineptr) + if (!*lineptr) { return; + } *lineptr += *n; - if (*lineptr < buffer->chars + buffer->length) + if (*lineptr < buffer->chars + buffer->length) { **lineptr = delimiter; + } } -bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf) -{ - if (strbuf->allocated == 0) return false; // Doesn't work with static strings +bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf) { + if (strbuf->allocated == 0) { + return false; // Doesn't work with static strings + } bool changed = false; - for (uint32_t i = 0; i < strbuf->length; i++) - { - if (strbuf->chars[i] != ' ') continue; + for (uint32_t i = 0; i < strbuf->length; i++) { + if (strbuf->chars[i] != ' ') { + continue; + } i++; uint32_t j = i; for (; j < strbuf->length && strbuf->chars[j] == ' '; j++); - if (j == i) continue; + if (j == i) { + continue; + } memmove(&strbuf->chars[i], &strbuf->chars[j], strbuf->length - j + 1); strbuf->length -= j - i; changed = true; @@ -797,23 +777,25 @@ bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf) /// @param compLength The length of the separated string to check. /// @param comp The separated string to check. /// @param separator The separator character. -bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) -{ - if (strbuf->length == 0) +bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) { + if (strbuf->length == 0) { return true; + } - if (compLength == 0) + if (compLength == 0) { return false; + } - for (const char* p = comp; p < comp + compLength;) - { + for (const char* p = comp; p < comp + compLength;) { const char* colon = memchr(p, separator, compLength); - if (colon == NULL) + if (colon == NULL) { return strcmp(strbuf->chars, p) == 0; + } uint32_t substrLength = (uint32_t) (colon - p); - if (strbuf->length == substrLength && memcmp(strbuf->chars, p, substrLength) == 0) + if (strbuf->length == substrLength && memcmp(strbuf->chars, p, substrLength) == 0) { return true; + } p = colon + 1; } @@ -822,23 +804,25 @@ bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const } /// @brief Case insensitive version of ffStrbufMatchSeparatedNS. -bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) -{ - if (strbuf->length == 0) +bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) { + if (strbuf->length == 0) { return true; + } - if (compLength == 0) + if (compLength == 0) { return false; + } - for (const char* p = comp; p < comp + compLength;) - { + for (const char* p = comp; p < comp + compLength;) { const char* colon = memchr(p, separator, compLength); - if (colon == NULL) + if (colon == NULL) { return strcasecmp(strbuf->chars, p) == 0; + } uint32_t substrLength = (uint32_t) (colon - p); - if (strbuf->length == substrLength && strncasecmp(strbuf->chars, p, substrLength) == 0) + if (strbuf->length == substrLength && strncasecmp(strbuf->chars, p, substrLength) == 0) { return true; + } p = colon + 1; } @@ -846,31 +830,18 @@ bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength return false; } -int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint) -{ +int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint) { if (codepoint <= 0x7F) { - ffStrbufAppendC(strbuf, (char)codepoint); + ffStrbufAppendC(strbuf, (char) codepoint); return 1; } else if (codepoint <= 0x7FF) { - ffStrbufAppendNS(strbuf, 2, (char[]){ - (char) (0xC0 | (codepoint >> 6)), - (char) (0x80 | (codepoint & 0x3F)) - }); + ffStrbufAppendNS(strbuf, 2, (char[]) {(char) (0xC0 | (codepoint >> 6)), (char) (0x80 | (codepoint & 0x3F))}); return 2; } else if (codepoint <= 0xFFFF) { - ffStrbufAppendNS(strbuf, 3, (char[]){ - (char) (0xE0 | (codepoint >> 12)), - (char) (0x80 | ((codepoint >> 6) & 0x3F)), - (char) (0x80 | (codepoint & 0x3F)) - }); + ffStrbufAppendNS(strbuf, 3, (char[]) {(char) (0xE0 | (codepoint >> 12)), (char) (0x80 | ((codepoint >> 6) & 0x3F)), (char) (0x80 | (codepoint & 0x3F))}); return 3; } else if (codepoint <= 0x10FFFF) { - ffStrbufAppendNS(strbuf, 4, (char[]){ - (char) (0xF0 | (codepoint >> 18)), - (char) (0x80 | ((codepoint >> 12) & 0x3F)), - (char) (0x80 | ((codepoint >> 6) & 0x3F)), - (char) (0x80 | (codepoint & 0x3F)) - }); + ffStrbufAppendNS(strbuf, 4, (char[]) {(char) (0xF0 | (codepoint >> 18)), (char) (0x80 | ((codepoint >> 12) & 0x3F)), (char) (0x80 | ((codepoint >> 6) & 0x3F)), (char) (0x80 | (codepoint & 0x3F))}); return 4; } @@ -883,16 +854,15 @@ int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint) /// @param compLength The length of the separated string to check. /// @param comp The substring to check. /// @param separator The separator character. -bool ffStrbufSeparatedContainNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) -{ +bool ffStrbufSeparatedContainNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) { uint32_t startIndex = 0; - while(startIndex < strbuf->length) - { + while (startIndex < strbuf->length) { uint32_t colonIndex = ffStrbufNextIndexC(strbuf, startIndex, separator); uint32_t folderLength = colonIndex - startIndex; - if (folderLength == compLength && memcmp(strbuf->chars + startIndex, comp, compLength) == 0) + if (folderLength == compLength && memcmp(strbuf->chars + startIndex, comp, compLength) == 0) { return true; + } startIndex = colonIndex + 1; } @@ -900,16 +870,15 @@ bool ffStrbufSeparatedContainNS(const FFstrbuf* strbuf, uint32_t compLength, con return false; } -bool ffStrbufSeparatedContainIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) -{ +bool ffStrbufSeparatedContainIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) { uint32_t startIndex = 0; - while(startIndex < strbuf->length) - { + while (startIndex < strbuf->length) { uint32_t colonIndex = ffStrbufNextIndexC(strbuf, startIndex, separator); uint32_t folderLength = colonIndex - startIndex; - if (folderLength == compLength && strncasecmp(strbuf->chars + startIndex, comp, compLength) == 0) + if (folderLength == compLength && strncasecmp(strbuf->chars + startIndex, comp, compLength) == 0) { return true; + } startIndex = colonIndex + 1; } @@ -917,12 +886,12 @@ bool ffStrbufSeparatedContainIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLeng return false; } -bool ffStrbufDecodeHexEscapeSequences(FFstrbuf* strbuf) -{ +bool ffStrbufDecodeHexEscapeSequences(FFstrbuf* strbuf) { assert(strbuf); - if (strbuf->length < 4) + if (strbuf->length < 4) { return false; + } // Static string must be converted first. assert(strbuf->allocated > 0); @@ -931,18 +900,14 @@ bool ffStrbufDecodeHexEscapeSequences(FFstrbuf* strbuf) uint32_t read = 0; uint32_t write = 0; - while (read < strbuf->length) - { + while (read < strbuf->length) { if ( read + 3 < strbuf->length && strbuf->chars[read] == '\\' && - strbuf->chars[read + 1] == 'x' - ) - { + strbuf->chars[read + 1] == 'x') { int8_t hi = ffHexCharToInt(strbuf->chars[read + 2]); int8_t lo = ffHexCharToInt(strbuf->chars[read + 3]); - if (hi >= 0 && lo >= 0) - { + if (hi >= 0 && lo >= 0) { strbuf->chars[write++] = (char) ((hi << 4) | lo); read += 4; changed = true; diff --git a/src/common/impl/base64.c b/src/common/impl/base64.c index 0567b75ed..94f74f9e1 100644 --- a/src/common/impl/base64.c +++ b/src/common/impl/base64.c @@ -1,14 +1,12 @@ #include "common/base64.h" // https://github.com/kostya/benchmarks/blob/master/base64/test-nolib.c#L145 -void ffBase64EncodeRaw(uint32_t size, const char *str, uint32_t *out_size, char *output) -{ +void ffBase64EncodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output) { static const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - char *out = output; - const char *ends = str + (size - size % 3); - while (str != ends) - { - uint32_t n = __builtin_bswap32(*(uint32_t *)str); + char* out = output; + const char* ends = str + (size - size % 3); + while (str != ends) { + uint32_t n = __builtin_bswap32(*(uint32_t*) str); *out++ = chars[(n >> 26) & 63]; *out++ = chars[(n >> 20) & 63]; *out++ = chars[(n >> 14) & 63]; @@ -16,94 +14,94 @@ void ffBase64EncodeRaw(uint32_t size, const char *str, uint32_t *out_size, char str += 3; } - if (size % 3 == 1) - { - uint64_t n = (uint64_t)*str << 16; + if (size % 3 == 1) { + uint64_t n = (uint64_t) *str << 16; *out++ = chars[(n >> 18) & 63]; *out++ = chars[(n >> 12) & 63]; *out++ = '='; *out++ = '='; - } - else if (size % 3 == 2) - { - uint64_t n = (uint64_t)*str++ << 16; - n |= (uint64_t)*str << 8; + } else if (size % 3 == 2) { + uint64_t n = (uint64_t) *str++ << 16; + n |= (uint64_t) *str << 8; *out++ = chars[(n >> 18) & 63]; *out++ = chars[(n >> 12) & 63]; *out++ = chars[(n >> 6) & 63]; *out++ = '='; } *out = '\0'; - *out_size = (uint32_t)(out - output); + *out_size = (uint32_t) (out - output); } static uint8_t decode_table[256]; -void init_decode_table() -{ +void init_decode_table() { uint8_t ch = 0; - do - { + do { int32_t code = -1; - if (ch >= 'A' && ch <= 'Z') + if (ch >= 'A' && ch <= 'Z') { code = ch - 0x41; - if (ch >= 'a' && ch <= 'z') + } + if (ch >= 'a' && ch <= 'z') { code = ch - 0x47; - if (ch >= '0' && ch <= '9') + } + if (ch >= '0' && ch <= '9') { code = ch + 0x04; - if (ch == '+' || ch == '-') + } + if (ch == '+' || ch == '-') { code = 0x3E; - if (ch == '/' || ch == '_') + } + if (ch == '/' || ch == '_') { code = 0x3F; + } decode_table[ch] = (uint8_t) code; } while (ch++ < 0xFF); } #define next_char(x) uint8_t x = decode_table[(uint8_t) *str++]; -bool ffBase64DecodeRaw(uint32_t size, const char *str, uint32_t *out_size, char *output) -{ - if (*(uint64_t*) decode_table == 0) +bool ffBase64DecodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output) { + if (*(uint64_t*) decode_table == 0) { init_decode_table(); + } - char *out = output; - while (size > 0 && (str[size - 1] == '\n' || str[size - 1] == '\r' || str[size - 1] == '=')) + char* out = output; + while (size > 0 && (str[size - 1] == '\n' || str[size - 1] == '\r' || str[size - 1] == '=')) { size--; + } - const char *ends = str + size - 4; - while (true) - { - if (str > ends) + const char* ends = str + size - 4; + while (true) { + if (str > ends) { break; - while (*str == '\n' || *str == '\r') + } + while (*str == '\n' || *str == '\r') { str++; + } - if (str > ends) + if (str > ends) { break; + } next_char(a); next_char(b); next_char(c); next_char(d); - *out++ = (char)(a << 2 | b >> 4); - *out++ = (char)(b << 4 | c >> 2); - *out++ = (char)(c << 6 | d >> 0); + *out++ = (char) (a << 2 | b >> 4); + *out++ = (char) (b << 4 | c >> 2); + *out++ = (char) (c << 6 | d >> 0); } uint8_t mod = (uint8_t) (ends - str + 4) % 4; - if (mod == 2) - { + if (mod == 2) { next_char(a); next_char(b); - *out++ = (char)(a << 2 | b >> 4); - } - else if (mod == 3) - { + *out++ = (char) (a << 2 | b >> 4); + } else if (mod == 3) { next_char(a); next_char(b); next_char(c); - *out++ = (char)(a << 2 | b >> 4); - *out++ = (char)(b << 4 | c >> 2); + *out++ = (char) (a << 2 | b >> 4); + *out++ = (char) (b << 4 | c >> 2); } *out = '\0'; diff --git a/src/common/impl/binary_apple.c b/src/common/impl/binary_apple.c index dee65b6a6..8aefa874f 100644 --- a/src/common/impl/binary_apple.c +++ b/src/common/impl/binary_apple.c @@ -17,8 +17,7 @@ /** * Helper function to read data from a file at a specific offset */ -static inline bool readData(FILE *objFile, void *buf, size_t size, off_t offset) -{ +static inline bool readData(FILE* objFile, void* buf, size_t size, off_t offset) { fseek(objFile, offset, SEEK_SET); return fread(buf, 1, size, objFile) == size; } @@ -36,23 +35,29 @@ static inline bool readData(FILE *objFile, void *buf, size_t size, off_t offset) * * @return true to continue processing, false to stop */ -static bool handleMachSection(FILE *objFile, const char *name, off_t offset, size_t size, bool (*cb)(const char *str, uint32_t len, void *userdata), void *userdata, uint32_t minLength) -{ - if (!ffStrEquals(name, "__cstring")) return true; +static bool handleMachSection(FILE* objFile, const char* name, off_t offset, size_t size, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { + if (!ffStrEquals(name, "__cstring")) { + return true; + } FF_AUTO_FREE char* data = (char*) malloc(size); - if (!readData(objFile, data, size, offset)) + if (!readData(objFile, data, size, offset)) { return true; + } - for (size_t off = 0; off < size; ++off) - { + for (size_t off = 0; off < size; ++off) { const char* p = (const char*) data + off; - if (*p == '\0') continue; + if (*p == '\0') { + continue; + } uint32_t len = (uint32_t) strlen(p); - if (len < minLength) continue; - if (*p >= ' ' && *p <= '~') // Ignore control characters - { - if (!cb(p, len, userdata)) return false; + if (len < minLength) { + continue; + } + if (*p >= ' ' && *p <= '~') { // Ignore control characters + if (!cb(p, len, userdata)) { + return false; + } } off += len; } @@ -75,25 +80,23 @@ static bool handleMachSection(FILE *objFile, const char *name, off_t offset, siz * * @return NULL on success, error message on failure */ -static const char* dumpMachHeader(FILE *objFile, off_t offset, bool is_64, bool (*cb)(const char *str, uint32_t len, void *userdata), void *userdata, uint32_t minLength) -{ +static const char* dumpMachHeader(FILE* objFile, off_t offset, bool is_64, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { uint32_t ncmds; off_t loadCommandsOffset = offset; - if (is_64) - { + if (is_64) { struct mach_header_64 header; - if (!readData(objFile, &header, sizeof(header), offset)) + if (!readData(objFile, &header, sizeof(header), offset)) { return "read mach header failed"; + } ncmds = header.ncmds; loadCommandsOffset += sizeof(header); - } - else - { + } else { struct mach_header header; - if (!readData(objFile, &header, sizeof(header), offset)) + if (!readData(objFile, &header, sizeof(header), offset)) { return "read mach header failed"; + } ncmds = header.ncmds; loadCommandsOffset += sizeof(header); @@ -101,45 +104,50 @@ static const char* dumpMachHeader(FILE *objFile, off_t offset, bool is_64, bool off_t commandOffset = loadCommandsOffset; struct load_command cmd = {}; - for (uint32_t i = 0U; i < ncmds; i++, commandOffset += cmd.cmdsize) - { - if (!readData(objFile, &cmd, sizeof(cmd), commandOffset)) + for (uint32_t i = 0U; i < ncmds; i++, commandOffset += cmd.cmdsize) { + if (!readData(objFile, &cmd, sizeof(cmd), commandOffset)) { continue; - - if (cmd.cmd == LC_SEGMENT_64) - { - struct segment_command_64 segment; - if (!readData(objFile, &segment, sizeof(segment), commandOffset)) - continue; - - if (!ffStrEquals(segment.segname, "__TEXT")) continue; - - for (uint32_t j = 0U; j < segment.nsects; j++) - { - struct section_64 section; - if (!readData(objFile, §ion, sizeof(section), (off_t) ((size_t) commandOffset + sizeof(segment) + j * sizeof(section)))) - continue; - - if (!handleMachSection(objFile, section.sectname, section.offset, section.size, cb, userdata, minLength)) - return NULL; - } } - else if (cmd.cmd == LC_SEGMENT) - { - struct segment_command segment; - if (!readData(objFile, &segment, sizeof(segment), commandOffset)) + + if (cmd.cmd == LC_SEGMENT_64) { + struct segment_command_64 segment; + if (!readData(objFile, &segment, sizeof(segment), commandOffset)) { continue; + } - if (!ffStrEquals(segment.segname, "__TEXT")) continue; + if (!ffStrEquals(segment.segname, "__TEXT")) { + continue; + } - for (uint32_t j = 0; j < segment.nsects; j++) - { - struct section section; - if (!readData(objFile, §ion, sizeof(section), (off_t) ((size_t) commandOffset + sizeof(segment) + j * sizeof(section)))) + for (uint32_t j = 0U; j < segment.nsects; j++) { + struct section_64 section; + if (!readData(objFile, §ion, sizeof(section), (off_t) ((size_t) commandOffset + sizeof(segment) + j * sizeof(section)))) { continue; + } - if (!handleMachSection(objFile, section.sectname, section.offset, section.size, cb, userdata, minLength)) + if (!handleMachSection(objFile, section.sectname, section.offset, section.size, cb, userdata, minLength)) { return NULL; + } + } + } else if (cmd.cmd == LC_SEGMENT) { + struct segment_command segment; + if (!readData(objFile, &segment, sizeof(segment), commandOffset)) { + continue; + } + + if (!ffStrEquals(segment.segname, "__TEXT")) { + continue; + } + + for (uint32_t j = 0; j < segment.nsects; j++) { + struct section section; + if (!readData(objFile, §ion, sizeof(section), (off_t) ((size_t) commandOffset + sizeof(segment) + j * sizeof(section)))) { + continue; + } + + if (!handleMachSection(objFile, section.sectname, section.offset, section.size, cb, userdata, minLength)) { + return NULL; + } } } @@ -163,47 +171,49 @@ static const char* dumpMachHeader(FILE *objFile, off_t offset, bool is_64, bool * * @return NULL on success, error message on failure */ -static const char* dumpFatHeader(FILE *objFile, bool (*cb)(const char *str, uint32_t len, void *userdata), void *userdata, uint32_t minLength) -{ +static const char* dumpFatHeader(FILE* objFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { struct fat_header header; - if (!readData(objFile, &header, sizeof(header), 0)) + if (!readData(objFile, &header, sizeof(header), 0)) { return "read fat header failed"; + } bool needSwap = header.magic == FAT_CIGAM || header.magic == FAT_CIGAM_64; - if (needSwap) swap_fat_header(&header, NX_UnknownByteOrder); + if (needSwap) { + swap_fat_header(&header, NX_UnknownByteOrder); + } - for (uint32_t i = 0U; i < header.nfat_arch; i++) - { + for (uint32_t i = 0U; i < header.nfat_arch; i++) { off_t machHeaderOffset = 0; - if (header.magic == FAT_MAGIC) - { + if (header.magic == FAT_MAGIC) { struct fat_arch arch; - if (!readData(objFile, &arch, sizeof(arch), (off_t) (sizeof(header) + i * sizeof(arch)))) + if (!readData(objFile, &arch, sizeof(arch), (off_t) (sizeof(header) + i * sizeof(arch)))) { continue; + } - if (needSwap) + if (needSwap) { swap_fat_arch(&arch, 1, NX_UnknownByteOrder); - machHeaderOffset = (off_t)arch.offset; - } - else - { + } + machHeaderOffset = (off_t) arch.offset; + } else { struct fat_arch_64 arch; - if (!readData(objFile, &arch, sizeof(arch), (off_t) (sizeof(header) + i * sizeof(arch)))) + if (!readData(objFile, &arch, sizeof(arch), (off_t) (sizeof(header) + i * sizeof(arch)))) { continue; + } - if (needSwap) + if (needSwap) { swap_fat_arch_64(&arch, 1, NX_UnknownByteOrder); + } - machHeaderOffset = (off_t)arch.offset; + machHeaderOffset = (off_t) arch.offset; } uint32_t magic; - if (!readData(objFile, &magic, sizeof(magic), machHeaderOffset)) + if (!readData(objFile, &magic, sizeof(magic), machHeaderOffset)) { continue; + } - if (magic == MH_MAGIC_64 || magic == MH_MAGIC) - { + if (magic == MH_MAGIC_64 || magic == MH_MAGIC) { dumpMachHeader(objFile, machHeaderOffset, magic == MH_MAGIC_64, cb, userdata, minLength); return NULL; } @@ -219,26 +229,29 @@ static const char* dumpFatHeader(FILE *objFile, bool (*cb)(const char *str, uint * It locates the __cstring section in the __TEXT segment which contains * the string literals used in the program. */ -const char *ffBinaryExtractStrings(const char *machoFile, bool (*cb)(const char *str, uint32_t len, void *userdata), void *userdata, uint32_t minLength) -{ - FF_AUTO_CLOSE_FILE FILE *objFile = fopen(machoFile, "rb"); - if (objFile == NULL) +const char* ffBinaryExtractStrings(const char* machoFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { + FF_AUTO_CLOSE_FILE FILE* objFile = fopen(machoFile, "rb"); + if (objFile == NULL) { return "File could not be opened"; + } // Read the magic number to determine the type of binary uint32_t magic; - if (!readData(objFile, &magic, sizeof(magic), 0)) + if (!readData(objFile, &magic, sizeof(magic), 0)) { return "read magic number failed"; + } // Check for supported formats // MH_CIGAM and MH_CIGAM_64 seem to be no longer used, as `swap_mach_header` is marked as deprecated. // However FAT_CIGAM and FAT_CIGAM_64 are still used (/usr/bin/vim). - if (magic != MH_MAGIC && magic != MH_MAGIC_64 && magic != FAT_CIGAM && magic != FAT_CIGAM_64 && magic != FAT_MAGIC && magic != FAT_MAGIC_64) + if (magic != MH_MAGIC && magic != MH_MAGIC_64 && magic != FAT_CIGAM && magic != FAT_CIGAM_64 && magic != FAT_MAGIC && magic != FAT_MAGIC_64) { return "Unsupported format or big endian mach-o file"; + } // Process either a fat binary or a regular Mach-O binary - if (magic == FAT_MAGIC || magic == FAT_MAGIC_64 || magic == FAT_CIGAM || magic == FAT_CIGAM_64) + if (magic == FAT_MAGIC || magic == FAT_MAGIC_64 || magic == FAT_CIGAM || magic == FAT_CIGAM_64) { return dumpFatHeader(objFile, cb, userdata, minLength); - else + } else { return dumpMachHeader(objFile, 0, magic == MH_MAGIC_64, cb, userdata, minLength); + } } diff --git a/src/common/impl/binary_linux.c b/src/common/impl/binary_linux.c index d6ecf15b5..450b55981 100644 --- a/src/common/impl/binary_linux.c +++ b/src/common/impl/binary_linux.c @@ -2,12 +2,12 @@ #if defined(FF_HAVE_ELF) || defined(__sun) || (defined(__FreeBSD__) && !defined(__DragonFly__)) || defined(__OpenBSD__) || defined(__NetBSD__) -#include "common/io.h" -#include "common/library.h" -#include "common/stringUtils.h" +# include "common/io.h" +# include "common/library.h" +# include "common/stringUtils.h" -#include // #1254 -#include +# include // #1254 +# include /** * Structure to hold dynamically loaded libelf function pointers @@ -36,15 +36,15 @@ struct FFElfData { * * The function supports both 32-bit and 64-bit ELF formats. */ -const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) -{ +const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { // Initialize libelf if not already done - if (!elfData.inited) - { + if (!elfData.inited) { elfData.inited = true; FF_LIBRARY_LOAD_MESSAGE(libelf, "libelf" FF_LIBRARY_EXTENSION, 1); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_version) - if (elfData.ffelf_version(EV_CURRENT) == EV_NONE) return "elf_version() failed"; + if (elfData.ffelf_version(EV_CURRENT) == EV_NONE) { + return "elf_version() failed"; + } // Load all required libelf functions FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_begin) @@ -59,56 +59,69 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s libelf = NULL; } - if (elfData.ffelf_end == NULL) + if (elfData.ffelf_end == NULL) { return "load libelf failed"; + } // Open the ELF file FF_AUTO_CLOSE_FD int fd = open(elfFile, O_RDONLY | O_CLOEXEC); - if (fd < 0) return "open() failed"; + if (fd < 0) { + return "open() failed"; + } Elf* elf = elfData.ffelf_begin(fd, ELF_C_READ, NULL); - if (elf == NULL) return "elf_begin() failed"; + if (elf == NULL) { + return "elf_begin() failed"; + } // Get the section header string table index size_t shstrndx = 0; - if (elfData.ffelf_getshdrstrndx(elf, &shstrndx) < 0) - { + if (elfData.ffelf_getshdrstrndx(elf, &shstrndx) < 0) { elfData.ffelf_end(elf); return "elf_getshdrstrndx() failed"; } // Iterate through all sections, looking for .rodata which contains string literals Elf_Scn* scn = NULL; - while ((scn = elfData.ffelf_nextscn(elf, scn)) != NULL) - { + while ((scn = elfData.ffelf_nextscn(elf, scn)) != NULL) { // Try 64-bit section header first, then 32-bit if that fails Elf64_Shdr* shdr64 = elfData.ffelf64_getshdr(scn); Elf32_Shdr* shdr32 = NULL; - if (shdr64 == NULL) - { + if (shdr64 == NULL) { shdr32 = elfData.ffelf32_getshdr(scn); - if (shdr32 == NULL) continue; + if (shdr32 == NULL) { + continue; + } } // Get the section name and check if it's .rodata const char* name = elfData.ffelf_strptr(elf, shstrndx, shdr64 ? shdr64->sh_name : shdr32->sh_name); - if (name == NULL || !ffStrEquals(name, ".rodata")) continue; + if (name == NULL || !ffStrEquals(name, ".rodata")) { + continue; + } // Get the section data Elf_Data* data = elfData.ffelf_getdata(scn, NULL); - if (data == NULL) continue; + if (data == NULL) { + continue; + } // Scan the section for string literals - for (size_t off = 0; off < data->d_size; ++off) - { + for (size_t off = 0; off < data->d_size; ++off) { const char* p = (const char*) data->d_buf + off; - if (*p == '\0') continue; + if (*p == '\0') { + continue; + } uint32_t len = (uint32_t) strlen(p); - if (len < minLength) continue; + if (len < minLength) { + continue; + } // Only process printable ASCII characters if (*p >= ' ' && *p <= '~') // Ignore control characters { - if (!cb(p, len, userdata)) break; + if (!cb(p, len, userdata)) { + break; + } } off += len; } @@ -125,8 +138,7 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s /** * Fallback implementation when libelf is not available */ -const char* ffBinaryExtractStrings(const char* file, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) -{ +const char* ffBinaryExtractStrings(const char* file, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { FF_UNUSED(file, cb, userdata, minLength); return "Fastfetch was built without libelf support"; } diff --git a/src/common/impl/binary_windows.c b/src/common/impl/binary_windows.c index 39b9eab7f..9dc21e591 100644 --- a/src/common/impl/binary_windows.c +++ b/src/common/impl/binary_windows.c @@ -14,48 +14,51 @@ * (which typically contains string literals), and scans it for valid strings. * Each string found is passed to the callback function for processing. */ -const char* ffBinaryExtractStrings(const char *peFile, bool (*cb)(const char *str, uint32_t len, void *userdata), void *userdata, uint32_t minLength) -{ - FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileA(peFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) +const char* ffBinaryExtractStrings(const char* peFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { + FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileA(peFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { return "CreateFileA() failed"; + } FF_AUTO_CLOSE_FD HANDLE hSection = NULL; - if (!NT_SUCCESS(NtCreateSection(&hSection, SECTION_MAP_READ, NULL, NULL, PAGE_READONLY, SEC_COMMIT, hFile))) + if (!NT_SUCCESS(NtCreateSection(&hSection, SECTION_MAP_READ, NULL, NULL, PAGE_READONLY, SEC_COMMIT, hFile))) { return "NtCreateSection() failed"; + } PVOID base = NULL; SIZE_T viewSize = 0; - if (!NT_SUCCESS(NtMapViewOfSection(hSection, NtCurrentProcess(), &base, 0, 0, NULL, &viewSize, ViewUnmap, 0, PAGE_READONLY))) + if (!NT_SUCCESS(NtMapViewOfSection(hSection, NtCurrentProcess(), &base, 0, 0, NULL, &viewSize, ViewUnmap, 0, PAGE_READONLY))) { return "NtMapViewOfSection() failed"; + } PIMAGE_NT_HEADERS ntHeaders = RtlImageNtHeader(base); - if (!ntHeaders) - { + if (!ntHeaders) { NtUnmapViewOfSection(NtCurrentProcess(), base); return "RtlImageNtHeader() failed"; } PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(ntHeaders); - for (WORD i = 0; i < ntHeaders->FileHeader.NumberOfSections; ++i, ++section) - { + for (WORD i = 0; i < ntHeaders->FileHeader.NumberOfSections; ++i, ++section) { // Look for initialized data sections with the name ".rdata" which typically contains string literals - if ((section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) && ffStrEquals((const char*) section->Name, ".rdata")) - { - uint8_t *data = (uint8_t *) base + section->PointerToRawData; + if ((section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) && ffStrEquals((const char*) section->Name, ".rdata")) { + uint8_t* data = (uint8_t*) base + section->PointerToRawData; // Scan the section for string literals - for (size_t off = 0; off < section->SizeOfRawData; ++off) - { + for (size_t off = 0; off < section->SizeOfRawData; ++off) { const char* p = (const char*) data + off; - if (*p == '\0') continue; + if (*p == '\0') { + continue; + } uint32_t len = (uint32_t) strlen(p); - if (len < minLength) continue; + if (len < minLength) { + continue; + } // Only process printable ASCII characters if (*p >= ' ' && *p <= '~') // Ignore control characters { - if (!cb(p, len, userdata)) break; + if (!cb(p, len, userdata)) { + break; + } } off += len; } diff --git a/src/common/impl/commandoption.c b/src/common/impl/commandoption.c index 7bfc48999..9c920bb12 100644 --- a/src/common/impl/commandoption.c +++ b/src/common/impl/commandoption.c @@ -10,16 +10,17 @@ #include #include -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) - { +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 != 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); @@ -31,32 +32,25 @@ bool ffParseModuleOptions(const char* key, const char* value) FF_STRBUF_AUTO_DESTROY jsonKey = ffStrbufCreate(); bool flag = false; - for (const char* p = subKey; *p; ++p) - { - if (*p == '-') - { - if (flag) - { + 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)) - { + } 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) - { + if (flag) { flag = false; ffStrbufAppendC(&jsonKey, (char) toupper((unsigned char) *p)); - } - else + } else { ffStrbufAppendC(&jsonKey, *p); + } } } fprintf(stderr, "Error: Unsupported module option: %s\n", key); @@ -69,53 +63,49 @@ bool ffParseModuleOptions(const char* key, const char* value) return false; } -void ffPrepareCommandOption(FFdata* data) -{ +void ffPrepareCommandOption(FFdata* data) { char* moduleType = NULL; size_t moduleLen = 0; - while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) - { - #define FF_IF_MODULE_MATCH(moduleNameConstant) if (moduleLen == strlen(moduleNameConstant) \ - && ffStrEqualsIgnCase(moduleType, moduleNameConstant) \ - && !ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleNameConstant, ':')) + while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { +#define FF_IF_MODULE_MATCH(moduleNameConstant) if (moduleLen == strlen(moduleNameConstant) && ffStrEqualsIgnCase(moduleType, moduleNameConstant) && !ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleNameConstant, ':')) - switch (moduleType[0]) - { - case 'C': case 'c': + switch (moduleType[0]) { + case 'C': + case 'c': FF_IF_MODULE_MATCH(FF_CPUUSAGE_MODULE_NAME) - ffPrepareCPUUsage(); + ffPrepareCPUUsage(); break; - case 'D': case 'd': - FF_IF_MODULE_MATCH(FF_DISKIO_MODULE_NAME) - { + case 'D': + case 'd': + FF_IF_MODULE_MATCH(FF_DISKIO_MODULE_NAME) { __attribute__((__cleanup__(ffDestroyDiskIOOptions))) FFDiskIOOptions options; ffInitDiskIOOptions(&options); ffPrepareDiskIO(&options); } break; - case 'N': case 'n': - FF_IF_MODULE_MATCH(FF_NETIO_MODULE_NAME) - { + case 'N': + case 'n': + FF_IF_MODULE_MATCH(FF_NETIO_MODULE_NAME) { __attribute__((__cleanup__(ffDestroyNetIOOptions))) FFNetIOOptions options; ffInitNetIOOptions(&options); ffPrepareNetIO(&options); } break; - case 'P': case 'p': - FF_IF_MODULE_MATCH(FF_PUBLICIP_MODULE_NAME) - { + case 'P': + case 'p': + FF_IF_MODULE_MATCH(FF_PUBLICIP_MODULE_NAME) { __attribute__((__cleanup__(ffDestroyPublicIpOptions))) FFPublicIPOptions options; ffInitPublicIpOptions(&options); ffPreparePublicIp(&options); } break; - case 'W': case 'w': - FF_IF_MODULE_MATCH(FF_WEATHER_MODULE_NAME) - { + case 'W': + case 'w': + FF_IF_MODULE_MATCH(FF_WEATHER_MODULE_NAME) { __attribute__((__cleanup__(ffDestroyWeatherOptions))) FFWeatherOptions options; ffInitWeatherOptions(&options); ffPrepareWeather(&options); @@ -123,70 +113,65 @@ void ffPrepareCommandOption(FFdata* data) break; } - #undef FF_IF_MODULE_MATCH +#undef FF_IF_MODULE_MATCH } } -static void genJsonConfig(FFdata* data, FFModuleBaseInfo* baseInfo, void* options) -{ +static void genJsonConfig(FFdata* data, FFModuleBaseInfo* baseInfo, void* options) { yyjson_mut_doc* doc = data->resultDoc; yyjson_mut_val* modules = yyjson_mut_obj_get(doc->root, "modules"); - if (!modules) + if (!modules) { modules = yyjson_mut_obj_add_arr(doc, doc->root, "modules"); + } FF_STRBUF_AUTO_DESTROY type = ffStrbufCreateS(baseInfo->name); ffStrbufLowerCase(&type); - if (data->docType == FF_RESULT_DOC_TYPE_CONFIG_FULL) - { + if (data->docType == FF_RESULT_DOC_TYPE_CONFIG_FULL) { yyjson_mut_val* module = yyjson_mut_obj(doc); yyjson_mut_obj_add_strbuf(doc, module, "type", &type); - if (baseInfo->generateJsonConfig) + if (baseInfo->generateJsonConfig) { baseInfo->generateJsonConfig(options, doc, module); + } - if (yyjson_mut_obj_size(module) > 1) + if (yyjson_mut_obj_size(module) > 1) { yyjson_mut_arr_add_val(modules, module); - else + } else { yyjson_mut_arr_add_strbuf(doc, modules, &type); - } - else - { + } + } else { yyjson_mut_arr_add_strbuf(doc, modules, &type); } } -static void genJsonResult(FFdata* data, FFModuleBaseInfo* baseInfo, void* options) -{ +static void genJsonResult(FFdata* data, FFModuleBaseInfo* baseInfo, void* options) { yyjson_mut_doc* doc = data->resultDoc; 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) + if (baseInfo->generateJsonResult) { baseInfo->generateJsonResult(options, doc, module); - else + } else { yyjson_mut_obj_add_str(doc, module, "error", "Unsupported for JSON format"); + } } static void parseStructureCommand( FFdata* data, const char* line, - void (*fn)(FFdata*, FFModuleBaseInfo* baseInfo, void* options) -) -{ - if(ffCharIsEnglishAlphabet(line[0])) - { - for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(line[0]) - 'A']; *modules; ++modules) - { + void (*fn)(FFdata*, FFModuleBaseInfo* baseInfo, void* options)) { + if (ffCharIsEnglishAlphabet(line[0])) { + for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(line[0]) - 'A']; *modules; ++modules) { FFModuleBaseInfo* baseInfo = *modules; - if (ffStrEqualsIgnCase(line, baseInfo->name)) - { + if (ffStrEqualsIgnCase(line, baseInfo->name)) { uint8_t optionBuf[FF_OPTION_MAX_SIZE]; baseInfo->initOptions(optionBuf); - if (__builtin_expect(data->resultDoc != NULL, false)) + if (__builtin_expect(data->resultDoc != NULL, false)) { fn(data, baseInfo, optionBuf); - else + } else { baseInfo->printModule(optionBuf); + } baseInfo->destroyOptions(optionBuf); return; } @@ -196,61 +181,62 @@ static void parseStructureCommand( ffPrintError(line, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, ""); } -void ffPrintCommandOption(FFdata* data) -{ - //Parse the structure and call the modules +void ffPrintCommandOption(FFdata* data) { + // Parse the structure and call the modules int32_t thres = instance.config.display.stat; char* moduleType = NULL; size_t moduleLen = 0; - while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) - { - if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) + while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { + if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) { continue; + } double ms = 0; - if(thres >= 0) + if (thres >= 0) { ms = ffTimeGetTick(); + } parseStructureCommand(data, moduleType, genJsonResult); - if(thres >= 0) - { + if (thres >= 0) { ms = ffTimeGetTick() - ms; - if (data->resultDoc) - { + if (data->resultDoc) { yyjson_mut_val* moduleJson = yyjson_mut_arr_get_last(data->resultDoc->root); yyjson_mut_obj_add_real(data->resultDoc, moduleJson, "stat", ms); - } - else - { + } else { char str[64]; int len = snprintf(str, sizeof str, "%.3fms", ms); - if (thres > 0) - snprintf(str, sizeof str, "\e[%sm%.3fms\e[m", (ms <= thres ? FF_COLOR_FG_GREEN : ms <= 2 * thres ? FF_COLOR_FG_YELLOW : FF_COLOR_FG_RED), ms); + if (thres > 0) { + snprintf(str, sizeof str, "\e[%sm%.3fms\e[m", (ms <= thres ? FF_COLOR_FG_GREEN : ms <= 2 * thres ? FF_COLOR_FG_YELLOW + : FF_COLOR_FG_RED), + ms); + } printf("\e7\e[1A\e[9999999C\e[%dD%s\e8", len, str); // Save; Up 1; Right 9999999; Left ; Print ; Load } } - #if defined(_WIN32) - if (!data->resultDoc && !instance.config.display.noBuffer) fflush(stdout); - #endif +#if defined(_WIN32) + if (!data->resultDoc && !instance.config.display.noBuffer) { + fflush(stdout); + } +#endif } } -void ffMigrateCommandOptionToJsonc(FFdata* data) -{ - //If we don't have a custom structure, use the default one - if(data->structure.length == 0) +void ffMigrateCommandOptionToJsonc(FFdata* data) { + // If we don't have a custom structure, use the default one + if (data->structure.length == 0) { ffStrbufAppendS(&data->structure, FASTFETCH_DATATEXT_STRUCTURE); // Cannot use `ffStrbufSetStatic` here because we will modify the string + } char* moduleType = NULL; size_t moduleLen = 0; - while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) - { - if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) + while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { + if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) { continue; + } parseStructureCommand(data, moduleType, genJsonConfig); } diff --git a/src/common/impl/dbus.c b/src/common/impl/dbus.c index cf45700a9..4d4d44b58 100644 --- a/src/common/impl/dbus.c +++ b/src/common/impl/dbus.c @@ -2,11 +2,10 @@ #ifdef FF_HAVE_DBUS -#include "common/thread.h" -#include "common/stringUtils.h" +# include "common/thread.h" +# include "common/stringUtils.h" -static bool loadLibSymbols(FFDBusLibrary* lib) -{ +static bool loadLibSymbols(FFDBusLibrary* lib) { FF_LIBRARY_LOAD(dbus, false, "libdbus-1" FF_LIBRARY_EXTENSION, 4); FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_bus_get, false) FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_new_method_call, false) @@ -24,14 +23,12 @@ static bool loadLibSymbols(FFDBusLibrary* lib) return true; } -static const FFDBusLibrary* loadLib(void) -{ +static const FFDBusLibrary* loadLib(void) { static FFDBusLibrary lib; static bool loaded = false; static bool loadSuccess = false; - if(!loaded) - { + if (!loaded) { loaded = true; loadSuccess = loadLibSymbols(&lib); } @@ -39,199 +36,189 @@ static const FFDBusLibrary* loadLib(void) return loadSuccess ? &lib : NULL; } -const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data) -{ +const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data) { data->lib = loadLib(); - if(data->lib == NULL) + if (data->lib == NULL) { return "Failed to load DBus library"; + } data->connection = data->lib->ffdbus_bus_get(busType, NULL); - if(data->connection == NULL) + if (data->connection == NULL) { return "Failed to connect to DBus"; + } return NULL; } -void ffDBusDestroyData(FFDBusData* data) -{ - if (data->connection != NULL) - { +void ffDBusDestroyData(FFDBusData* data) { + if (data->connection != NULL) { data->lib->ffdbus_connection_unref(data->connection); data->connection = NULL; } } -bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result) -{ +bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result) { int argType = dbus->lib->ffdbus_message_iter_get_arg_type(iter); - if(argType == DBUS_TYPE_STRING || argType == DBUS_TYPE_OBJECT_PATH) - { + if (argType == DBUS_TYPE_STRING || argType == DBUS_TYPE_OBJECT_PATH) { const char* value = NULL; dbus->lib->ffdbus_message_iter_get_basic(iter, &value); - if(!ffStrSet(value)) + if (!ffStrSet(value)) { return false; + } ffStrbufAppendS(result, value); return true; } - if (argType == DBUS_TYPE_BYTE) - { + if (argType == DBUS_TYPE_BYTE) { uint8_t value; dbus->lib->ffdbus_message_iter_get_basic(iter, &value); ffStrbufAppendC(result, (char) value); return false; // Don't append a comma } - if(argType != DBUS_TYPE_VARIANT && argType != DBUS_TYPE_ARRAY) + if (argType != DBUS_TYPE_VARIANT && argType != DBUS_TYPE_ARRAY) { return false; + } DBusMessageIter subIter; dbus->lib->ffdbus_message_iter_recurse(iter, &subIter); - if(argType == DBUS_TYPE_VARIANT) + if (argType == DBUS_TYPE_VARIANT) { return ffDBusGetString(dbus, &subIter, result); + } - //At this point we have an array + // At this point we have an array bool foundAValue = false; - while(true) - { - if(ffDBusGetString(dbus, &subIter, result)) - { + while (true) { + if (ffDBusGetString(dbus, &subIter, result)) { foundAValue = true; ffStrbufAppendS(result, ", "); } - if(!dbus->lib->ffdbus_message_iter_next(&subIter)) + if (!dbus->lib->ffdbus_message_iter_next(&subIter)) { break; - else + } else { continue; + } } - if(foundAValue) + if (foundAValue) { ffStrbufSubstrBefore(result, result->length - 2); + } return foundAValue; } -bool ffDBusGetBool(FFDBusData* dbus, DBusMessageIter* iter, bool* result) -{ +bool ffDBusGetBool(FFDBusData* dbus, DBusMessageIter* iter, bool* result) { int argType = dbus->lib->ffdbus_message_iter_get_arg_type(iter); - if(argType == DBUS_TYPE_BOOLEAN) - { + if (argType == DBUS_TYPE_BOOLEAN) { dbus_bool_t value = 0; dbus->lib->ffdbus_message_iter_get_basic(iter, &value); *result = value != 0; return true; } - if(argType != DBUS_TYPE_VARIANT) + if (argType != DBUS_TYPE_VARIANT) { return false; + } DBusMessageIter subIter; dbus->lib->ffdbus_message_iter_recurse(iter, &subIter); return ffDBusGetBool(dbus, &subIter, result); } -bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint32_t* result) -{ +bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint32_t* result) { int argType = dbus->lib->ffdbus_message_iter_get_arg_type(iter); - if(argType == DBUS_TYPE_BYTE) - { + 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) - { + if (argType == DBUS_TYPE_UINT16) { uint16_t value = 0; dbus->lib->ffdbus_message_iter_get_basic(iter, &value); *result = value; return true; } - if(argType == DBUS_TYPE_UINT32) - { + if (argType == DBUS_TYPE_UINT32) { dbus->lib->ffdbus_message_iter_get_basic(iter, result); return true; } - if(argType != DBUS_TYPE_VARIANT) + if (argType != DBUS_TYPE_VARIANT) { return false; + } DBusMessageIter subIter; dbus->lib->ffdbus_message_iter_recurse(iter, &subIter); return ffDBusGetUint(dbus, &subIter, result); } -bool ffDBusGetInt(FFDBusData* dbus, DBusMessageIter* iter, int32_t* result) -{ +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) - { + 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) - { + if (argType == DBUS_TYPE_INT32) { dbus->lib->ffdbus_message_iter_get_basic(iter, result); return true; } - if(argType == DBUS_TYPE_BYTE) - { + 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) - { + 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) - { + if (argType == DBUS_TYPE_UINT32) { dbus->lib->ffdbus_message_iter_get_basic(iter, result); return true; } - if(argType != DBUS_TYPE_VARIANT) + 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* 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) + if (message == NULL) { return NULL; + } - if (arg1) - { - if (arg2) + if (arg1) { + if (arg2) { dbus->lib->ffdbus_message_append_args(message, DBUS_TYPE_STRING, &arg1, DBUS_TYPE_STRING, &arg2, DBUS_TYPE_INVALID); - else + } 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); @@ -241,15 +228,17 @@ DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const c return reply; } -DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property) -{ +DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property) { DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, "org.freedesktop.DBus.Properties", "Get"); - if(message == NULL) + if (message == NULL) { return NULL; + } dbus->lib->ffdbus_message_append_args(message, - DBUS_TYPE_STRING, &interface, - DBUS_TYPE_STRING, &property, + DBUS_TYPE_STRING, + &interface, + DBUS_TYPE_STRING, + &property, DBUS_TYPE_INVALID); DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, NULL); @@ -259,15 +248,14 @@ DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char return reply; } -bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, FFstrbuf* result) -{ +bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, FFstrbuf* result) { DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property); - if(reply == NULL) + if (reply == NULL) { return false; + } DBusMessageIter rootIterator; - if(!dbus->lib->ffdbus_message_iter_init(reply, &rootIterator)) - { + if (!dbus->lib->ffdbus_message_iter_init(reply, &rootIterator)) { dbus->lib->ffdbus_message_unref(reply); return false; } @@ -279,15 +267,14 @@ bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* return ret; } -bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, uint32_t* result) -{ +bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, uint32_t* result) { DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property); - if(reply == NULL) + if (reply == NULL) { return false; + } DBusMessageIter rootIterator; - if(!dbus->lib->ffdbus_message_iter_init(reply, &rootIterator)) - { + if (!dbus->lib->ffdbus_message_iter_init(reply, &rootIterator)) { dbus->lib->ffdbus_message_unref(reply); return false; } @@ -299,4 +286,4 @@ bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* ob return ret; } -#endif //FF_HAVE_DBUS +#endif // FF_HAVE_DBUS diff --git a/src/common/impl/debug_windows.c b/src/common/impl/debug_windows.c index bb827f99b..3789b7659 100644 --- a/src/common/impl/debug_windows.c +++ b/src/common/impl/debug_windows.c @@ -2,8 +2,7 @@ #include -const char* ffDebugWin32Error(DWORD errorCode) -{ +const char* ffDebugWin32Error(DWORD errorCode) { static char buffer[256]; DWORD len = FormatMessageA( @@ -28,23 +27,22 @@ const char* ffDebugWin32Error(DWORD errorCode) return buffer; } -const char* ffDebugNtStatus(NTSTATUS status) -{ +const char* ffDebugNtStatus(NTSTATUS status) { return ffDebugWin32Error(RtlNtStatusToDosError(status)); } -static inline DWORD HRESULTToWin32Error(HRESULT hr) -{ - if (SUCCEEDED(hr)) +static inline DWORD HRESULTToWin32Error(HRESULT hr) { + if (SUCCEEDED(hr)) { return ERROR_SUCCESS; + } - if (HRESULT_FACILITY(hr) == FACILITY_WIN32) + if (HRESULT_FACILITY(hr) == FACILITY_WIN32) { return HRESULT_CODE(hr); + } return ERROR_INTERNAL_ERROR; } -const char* ffDebugHResult(HRESULT hr) -{ +const char* ffDebugHResult(HRESULT hr) { return ffDebugWin32Error(HRESULTToWin32Error(hr)); } diff --git a/src/common/impl/duration.c b/src/common/impl/duration.c index a767ca386..a6a496548 100644 --- a/src/common/impl/duration.c +++ b/src/common/impl/duration.c @@ -1,25 +1,27 @@ #include "common/duration.h" -void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result) -{ +void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result) { const FFOptionsDisplay* options = &instance.config.display; bool spaceBeforeUnit = options->durationSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER; - if (totalSeconds < 60) - { + if (totalSeconds < 60) { ffStrbufAppendUInt(result, totalSeconds); - if (spaceBeforeUnit) ffStrbufAppendC(result, ' '); + if (spaceBeforeUnit) { + ffStrbufAppendC(result, ' '); + } ffStrbufAppendS(result, options->durationAbbreviation ? "sec" : "second"); - if (totalSeconds != 1) + if (totalSeconds != 1) { ffStrbufAppendC(result, 's'); + } return; } uint32_t seconds = (uint32_t) (totalSeconds % 60); totalSeconds /= 60; - if (seconds >= 30) + if (seconds >= 30) { totalSeconds++; + } uint32_t minutes = (uint32_t) (totalSeconds % 60); totalSeconds /= 60; @@ -27,56 +29,59 @@ void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result) totalSeconds /= 24; uint32_t days = (uint32_t) totalSeconds; - if (days > 0) - { + if (days > 0) { ffStrbufAppendUInt(result, days); - if (spaceBeforeUnit) ffStrbufAppendC(result, ' '); - if (options->durationAbbreviation) - { + if (spaceBeforeUnit) { + ffStrbufAppendC(result, ' '); + } + if (options->durationAbbreviation) { ffStrbufAppendC(result, 'd'); - if (hours > 0 || minutes > 0) + if (hours > 0 || minutes > 0) { ffStrbufAppendC(result, ' '); - } - else - { + } + } else { ffStrbufAppendS(result, days == 1 ? "day" : "days"); - 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) { ffStrbufAppendUInt(result, hours); - if (spaceBeforeUnit) ffStrbufAppendC(result, ' '); - if (options->durationAbbreviation) - { + if (spaceBeforeUnit) { + ffStrbufAppendC(result, ' '); + } + if (options->durationAbbreviation) { ffStrbufAppendC(result, 'h'); - if (minutes > 0) + if (minutes > 0) { ffStrbufAppendC(result, ' '); - } - else - { + } + } else { ffStrbufAppendS(result, hours == 1 ? "hour" : "hours"); - if (minutes > 0) + if (minutes > 0) { ffStrbufAppendS(result, ", "); + } } } - if (minutes > 0) - { + if (minutes > 0) { ffStrbufAppendUInt(result, minutes); - if (spaceBeforeUnit) ffStrbufAppendC(result, ' '); - if (options->durationAbbreviation) + if (spaceBeforeUnit) { + ffStrbufAppendC(result, ' '); + } + if (options->durationAbbreviation) { ffStrbufAppendC(result, 'm'); - else + } else { ffStrbufAppendS(result, minutes == 1 ? "min" : "mins"); + } } } diff --git a/src/common/impl/edidHelper.c b/src/common/impl/edidHelper.c index 8cf387adc..b18f1b9eb 100644 --- a/src/common/impl/edidHelper.c +++ b/src/common/impl/edidHelper.c @@ -1,55 +1,39 @@ #include "common/edidHelper.h" -void ffEdidGetPhysicalResolution(const uint8_t edid[128], uint32_t* width, uint32_t* height) -{ +void ffEdidGetPhysicalResolution(const uint8_t edid[128], uint32_t* width, uint32_t* height) { const int dtd = 54; *width = (((uint32_t) edid[dtd + 4] >> 4) << 8) | edid[dtd + 2]; *height = (((uint32_t) edid[dtd + 7] >> 4) << 8) | edid[dtd + 5]; } -void ffEdidGetPreferredResolutionAndRefreshRate(const uint8_t edid[128], uint32_t* width, uint32_t* height, double* refreshRate) -{ - for (uint32_t i = 0x36; i < 0x7E; i += 0x12) - { // read through descriptor blocks... - if (edid[i] != 0x00 && edid[i + 1] != 0x00) - { // a dtd - uint32_t hactive = edid[i+2] + (uint32_t) ((edid[i + 4] & 0xf0) << 4); - uint32_t hblank = edid[i+3] + (uint32_t) ((edid[i + 4] & 0x0f) << 8); - uint32_t vactive = edid[i+5] + (uint32_t) ((edid[i + 7] & 0xf0) << 4); - uint32_t vblank = edid[i+6] + (uint32_t) ((edid[i + 7] & 0x0f) << 8); - uint32_t pixclk = ((uint32_t) edid[i+1] << 8) | (edid[i]); +void ffEdidGetPreferredResolutionAndRefreshRate(const uint8_t edid[128], uint32_t* width, uint32_t* height, double* refreshRate) { + for (uint32_t i = 0x36; i < 0x7E; i += 0x12) { // read through descriptor blocks... + if (edid[i] != 0x00 && edid[i + 1] != 0x00) { // a dtd + uint32_t hactive = edid[i + 2] + (uint32_t) ((edid[i + 4] & 0xf0) << 4); + uint32_t hblank = edid[i + 3] + (uint32_t) ((edid[i + 4] & 0x0f) << 8); + uint32_t vactive = edid[i + 5] + (uint32_t) ((edid[i + 7] & 0xf0) << 4); + uint32_t vblank = edid[i + 6] + (uint32_t) ((edid[i + 7] & 0x0f) << 8); + uint32_t pixclk = ((uint32_t) edid[i + 1] << 8) | (edid[i]); *width = hactive; *height = vactive; - *refreshRate = (double)pixclk * 10000 / (double)(hactive+hblank) / (double)(vactive+vblank); + *refreshRate = (double) pixclk * 10000 / (double) (hactive + hblank) / (double) (vactive + vblank); return; } } } -void ffEdidGetVendorAndModel(const uint8_t edid[128], FFstrbuf* result) -{ +void ffEdidGetVendorAndModel(const uint8_t edid[128], FFstrbuf* result) { // https://github.com/jinksong/read_edid/blob/master/parse-edid/parse-edid.c - ffStrbufAppendF(result, "%c%c%c%04X", - (char) (((uint32_t)edid[8] >> 2 & 0x1f) + 'A' - 1), - (char) (((((uint32_t)edid[8] & 0x3) << 3) | (((uint32_t)edid[9] & 0xe0) >> 5)) + 'A' - 1), - (char) (((uint32_t)edid[9] & 0x1f) + 'A' - 1), - (uint32_t) (edid[10] + (uint32_t) (edid[11] << 8)) - ); + ffStrbufAppendF(result, "%c%c%c%04X", (char) (((uint32_t) edid[8] >> 2 & 0x1f) + 'A' - 1), (char) (((((uint32_t) edid[8] & 0x3) << 3) | (((uint32_t) edid[9] & 0xe0) >> 5)) + 'A' - 1), (char) (((uint32_t) edid[9] & 0x1f) + 'A' - 1), (uint32_t) (edid[10] + (uint32_t) (edid[11] << 8))); } -bool ffEdidGetName(const uint8_t edid[128], FFstrbuf* name) -{ +bool ffEdidGetName(const uint8_t edid[128], FFstrbuf* name) { // https://github.com/jinksong/read_edid/blob/master/parse-edid/parse-edid.c - for (uint32_t i = 0x36; i < 0x7E; i += 0x12) - { // read through descriptor blocks... - if (edid[i] == 0x00) - { // not a timing descriptor - if (edid[i + 3] == 0xfc) - { // Model Name tag - for (uint32_t j = 0; j < 13; j++) - { - if (edid[i + 5 + j] == 0x0a) - { + for (uint32_t i = 0x36; i < 0x7E; i += 0x12) { // read through descriptor blocks... + if (edid[i] == 0x00) { // not a timing descriptor + if (edid[i + 3] == 0xfc) { // Model Name tag + for (uint32_t j = 0; j < 13; j++) { + if (edid[i + 5 + j] == 0x0a) { ffStrbufAppendNS(name, j, (const char*) &edid[i + 5]); return true; } @@ -63,8 +47,7 @@ bool ffEdidGetName(const uint8_t edid[128], FFstrbuf* name) return false; } -void ffEdidGetPhysicalSize(const uint8_t edid[128], uint32_t* width, uint32_t* height) -{ +void ffEdidGetPhysicalSize(const uint8_t edid[128], uint32_t* width, uint32_t* height) { // Detailed Timing Descriptors uint32_t dw = (((uint32_t) edid[68] & 0xF0) << 4) + edid[66]; uint32_t dh = (((uint32_t) edid[68] & 0x0F) << 8) + edid[67]; @@ -74,53 +57,54 @@ void ffEdidGetPhysicalSize(const uint8_t edid[128], uint32_t* width, uint32_t* h uint32_t bh = edid[22] * 10; // Some monitors report invalid data in DTD. See #1406 - if (abs((int)dw - (int)bw) < 10 && abs((int)dh - (int)bh) < 10) - { + if (abs((int) dw - (int) bw) < 10 && abs((int) dh - (int) bh) < 10) { *width = dw; *height = dh; - } - else - { + } else { *width = bw; *height = bh; } } -void ffEdidGetSerialAndManufactureDate(const uint8_t edid[128], uint32_t* serial, uint16_t* year, uint16_t* week) -{ - if (edid[17] > 0 && edid[17] < 0xFF) - { +void ffEdidGetSerialAndManufactureDate(const uint8_t edid[128], uint32_t* serial, uint16_t* year, uint16_t* week) { + if (edid[17] > 0 && edid[17] < 0xFF) { *year = (uint16_t) (edid[17] + 1990); *week = (uint16_t) edid[16]; - if (*week == 0xFF) *week = 0; - } - else + if (*week == 0xFF) { + *week = 0; + } + } else { *year = *week = 0; + } *serial = *(uint32_t*) &edid[12]; } -bool ffEdidGetHdrCompatible(const uint8_t* edid, uint32_t length) -{ - if (length <= 128) return false; - for (const uint8_t* cta = &edid[128]; cta < &edid[length]; cta += 128) - { +bool ffEdidGetHdrCompatible(const uint8_t* edid, uint32_t length) { + if (length <= 128) { + return false; + } + for (const uint8_t* cta = &edid[128]; cta < &edid[length]; cta += 128) { // https://en.wikipedia.org/wiki/Extended_Display_Identification_Data#CTA_EDID_Timing_Extension_Block - if (cta[0] != 0x02 /* CTA EDID */) continue; - if (cta[1] < 0x03 /* Version 3 */) continue; + if (cta[0] != 0x02 /* CTA EDID */) { + continue; + } + if (cta[1] < 0x03 /* Version 3 */) { + continue; + } const uint8_t offset = cta[2]; - if (offset <= 4) continue; - for (uint8_t i = 4; i < offset;) - { + if (offset <= 4) { + continue; + } + for (uint8_t i = 4; i < offset;) { uint8_t blkLen = cta[i] & 0x1f; - if (blkLen > 0) - { + if (blkLen > 0) { uint8_t blkTag = (cta[i] & 0xe0) >> 5; - if (blkTag == 0x07 /* Extended Block Type Tag */) - { + if (blkTag == 0x07 /* Extended Block Type Tag */) { uint8_t extendedTag = cta[i + 1]; - if (extendedTag == 6 /* HDR SMDB */ || extendedTag == 7 /* HDR DMDB */) + if (extendedTag == 6 /* HDR SMDB */ || extendedTag == 7 /* HDR DMDB */) { return true; + } } } i += (uint8_t) (blkLen + 1); @@ -129,15 +113,20 @@ bool ffEdidGetHdrCompatible(const uint8_t* edid, uint32_t length) return false; } -bool ffEdidIsValid(const uint8_t edid[128], uint32_t length) -{ - if (length < 128 || length % 128 != 0) return false; +bool ffEdidIsValid(const uint8_t edid[128], uint32_t length) { + if (length < 128 || length % 128 != 0) { + return false; + } - static const uint8_t edidHeader[] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 }; - if (memcmp(edid, edidHeader, sizeof(edidHeader)) != 0) return false; + static const uint8_t edidHeader[] = {0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00}; + if (memcmp(edid, edidHeader, sizeof(edidHeader)) != 0) { + return false; + } uint8_t sum = 0; - for (uint32_t i = 0; i < 128; i++) sum += edid[i]; + for (uint32_t i = 0; i < 128; i++) { + sum += edid[i]; + } return sum == 0; } diff --git a/src/common/impl/font.c b/src/common/impl/font.c index 7548ab2de..56f4a1316 100644 --- a/src/common/impl/font.c +++ b/src/common/impl/font.c @@ -7,8 +7,7 @@ #include #include -void ffFontInit(FFfont* font) -{ +void ffFontInit(FFfont* font) { // Ensure no memory allocates ffStrbufInit(&font->pretty); ffStrbufInit(&font->name); @@ -16,84 +15,90 @@ void ffFontInit(FFfont* font) ffListInit(&font->styles, sizeof(FFstrbuf)); } -static void strbufAppendNSExcludingC(FFstrbuf* strbuf, uint32_t length, const char* value, char exclude) -{ - if(value == NULL || length == 0) +static void strbufAppendNSExcludingC(FFstrbuf* strbuf, uint32_t length, const char* value, char exclude) { + if (value == NULL || length == 0) { return; + } ffStrbufEnsureFree(strbuf, length); - for(uint32_t i = 0; i < length; i++) - { - if(value[i] != exclude) - strbuf->chars[strbuf->length++] = value[i]; + for (uint32_t i = 0; i < length; i++) { + if (value[i] != exclude) { + strbuf->chars[strbuf->length++] = value[i]; + } } strbuf->chars[strbuf->length] = '\0'; } -static void fontInitPretty(FFfont* font) -{ +static void fontInitPretty(FFfont* font) { ffStrbufAppend(&font->pretty, &font->name); - if(font->size.length == 0 && font->styles.length == 0) + if (font->size.length == 0 && font->styles.length == 0) { return; - else if(font->pretty.length == 0) + } else if (font->pretty.length == 0) { ffStrbufAppendS(&font->pretty, "default"); + } ffStrbufAppendS(&font->pretty, " ("); - if(font->size.length > 0) - { + if (font->size.length > 0) { ffStrbufAppend(&font->pretty, &font->size); - if (!ffStrbufEndsWithS(&font->size, "pt") && !ffStrbufEndsWithS(&font->size, "px")) + if (!ffStrbufEndsWithS(&font->size, "pt") && !ffStrbufEndsWithS(&font->size, "px")) { ffStrbufAppendS(&font->pretty, "pt"); + } - if(font->styles.length > 0) + if (font->styles.length > 0) { ffStrbufAppendS(&font->pretty, ", "); + } } - for(uint32_t i = 0; i < font->styles.length; i++) - { + for (uint32_t i = 0; i < font->styles.length; i++) { ffStrbufAppend(&font->pretty, FF_LIST_GET(FFstrbuf, font->styles, i)); - if(i < font->styles.length - 1) + if (i < font->styles.length - 1) { ffStrbufAppendS(&font->pretty, ", "); + } } ffStrbufAppendC(&font->pretty, ')'); } -void ffFontInitQt(FFfont* font, const char* data) -{ +void ffFontInitQt(FFfont* font, const char* data) { ffFontInit(font); - //See https://doc.qt.io/qt-5/qfont.html#toString + // See https://doc.qt.io/qt-5/qfont.html#toString - //Family + // Family data = ffStrbufAppendSUntilC(&font->name, data, ','); ffStrbufTrim(&font->name, ' '); - if (!data) goto exit; + if (!data) { + goto exit; + } data++; - //Size + // Size data = ffStrbufAppendSUntilC(&font->size, data, ','); ffStrbufTrim(&font->size, ' '); - if (!data) goto exit; + if (!data) { + goto exit; + } data++; - //Style + // Style data = strrchr(data, ','); - if (!data) goto exit; + if (!data) { + goto exit; + } data++; - if (isalpha(*data)) - { - do - { + if (isalpha(*data)) { + do { FFstrbuf* style = (FFstrbuf*) ffListAdd(&font->styles); ffStrbufInit(style); data = ffStrbufAppendSUntilC(style, data, ' '); - if (data) data++; + if (data) { + data++; + } } while (data); } @@ -101,34 +106,37 @@ exit: fontInitPretty(font); } -static void fontPangoParseWord(const char** data, FFfont* font, FFstrbuf* alternativeBuffer) -{ - while(**data == ' ' || **data == '\t' || **data == ',') +static void fontPangoParseWord(const char** data, FFfont* font, FFstrbuf* alternativeBuffer) { + while (**data == ' ' || **data == '\t' || **data == ',') { ++(*data); + } const char* wordStart = *data; - while(**data != ' ' && **data != '\t' && **data != ',' && **data != '\0' && **data != '`' && **data != '\\') + while (**data != ' ' && **data != '\t' && **data != ',' && **data != '\0' && **data != '`' && **data != '\\') { ++(*data); + } uint32_t wordLength = (uint32_t) (*data - wordStart); - if(wordLength == 0) + if (wordLength == 0) { return; + } - if(**data == '\0' || **data == '`' || **data == '\\') - { + if (**data == '\0' || **data == '`' || **data == '\\') { ffStrbufAppendNS(&font->size, wordLength, wordStart); - if(ffStrbufEndsWithS(&font->size, "px")) + if (ffStrbufEndsWithS(&font->size, "px")) { ffStrbufSubstrBefore(&font->size, font->size.length - 2); + } double dummy; - if(sscanf(font->size.chars, "%lf", &dummy) == 1) + if (sscanf(font->size.chars, "%lf", &dummy) == 1) { return; + } ffStrbufClear(&font->size); } - if( + if ( ffStrStartsWithIgnCase(wordStart, "Ultra") || ffStrStartsWithIgnCase(wordStart, "Extra") || ffStrStartsWithIgnCase(wordStart, "Semi") || @@ -142,51 +150,47 @@ static void fontPangoParseWord(const char** data, FFfont* font, FFstrbuf* altern ffStrStartsWithIgnCase(wordStart, "Bold") || ffStrStartsWithIgnCase(wordStart, "Black") || ffStrStartsWithIgnCase(wordStart, "Condensed") || - ffStrStartsWithIgnCase(wordStart, "Expanded") - ) { - if(alternativeBuffer == NULL) - { + ffStrStartsWithIgnCase(wordStart, "Expanded")) { + if (alternativeBuffer == NULL) { alternativeBuffer = (FFstrbuf*) ffListAdd(&font->styles); ffStrbufInit(alternativeBuffer); } strbufAppendNSExcludingC(alternativeBuffer, wordLength, wordStart, '-'); - if( + if ( ffStrStartsWithIgnCase(wordStart, "Ultra ") || ffStrStartsWithIgnCase(wordStart, "Extra ") || ffStrStartsWithIgnCase(wordStart, "Semi ") || - ffStrStartsWithIgnCase(wordStart, "Demi ") - ) { + ffStrStartsWithIgnCase(wordStart, "Demi ")) { fontPangoParseWord(data, font, alternativeBuffer); } return; } - if(alternativeBuffer != NULL) - { + if (alternativeBuffer != NULL) { strbufAppendNSExcludingC(alternativeBuffer, wordLength, wordStart, '-'); return; } - if(font->name.length > 0) + if (font->name.length > 0) { ffStrbufAppendC(&font->name, ' '); + } ffStrbufAppendNS(&font->name, wordLength, wordStart); } -void ffFontInitPango(FFfont* font, const char* data) -{ +void ffFontInitPango(FFfont* font, const char* data) { ffFontInit(font); - while(*data != '\0' && *data != '`' && *data != '\\') + while (*data != '\0' && *data != '`' && *data != '\\') { fontPangoParseWord(&data, font, NULL); + } fontInitPretty(font); } -void ffFontInitValues(FFfont* font, const char* name, const char* size) -{ +void ffFontInitValues(FFfont* font, const char* name, const char* size) { ffFontInit(font); ffStrbufAppendS(&font->name, name); @@ -196,8 +200,7 @@ void ffFontInitValues(FFfont* font, const char* name, const char* size) fontInitPretty(font); } -void ffFontInitXlfd(FFfont* font, const char* xlfd) -{ +void ffFontInitXlfd(FFfont* font, const char* xlfd) { assert(xlfd && *xlfd); // https://en.wikipedia.org/wiki/X_logical_font_description @@ -205,80 +208,78 @@ void ffFontInitXlfd(FFfont* font, const char* xlfd) // XLFD: -foundry-family-weight-slant-setwidth-addstyle-pixelsize-pointsize-xres-yres-spacing-averagewidth-charsetregistry-charsetencoding // It often starts with '-', which would create an empty first field. Skip it to align indexes. - if(*xlfd == '-') + if (*xlfd == '-') { xlfd++; + } const char* pstart = xlfd; - for(int field = 0; field < 14; field++) - { + for (int field = 0; field < 14; field++) { const char* pend = strchr(pstart, '-'); - uint32_t length = pend ? (uint32_t)(pend - pstart) : (uint32_t) strlen(pstart); + uint32_t length = pend ? (uint32_t) (pend - pstart) : (uint32_t) strlen(pstart); - if(length > 0) - { - if(field == 1) // family + if (length > 0) { + if (field == 1) // family { ffStrbufAppendNS(&font->name, length, pstart); - } - else if(field == 7) // pointsize (decipoints, preferred) + } else if (field == 7) // pointsize (decipoints, preferred) { // parse positive integer from substring long deciPt = 0; bool ok = true; - for(uint32_t i = 0; i < length; i++) - { + for (uint32_t i = 0; i < length; i++) { char c = pstart[i]; - if(c < '0' || c > '9') { ok = false; break; } + if (c < '0' || c > '9') { + ok = false; + break; + } deciPt = deciPt * 10 + (c - '0'); } - if(ok && deciPt > 0) - { + if (ok && deciPt > 0) { ffStrbufClear(&font->size); char tmp[32]; - if(deciPt % 10 == 0) + if (deciPt % 10 == 0) { snprintf(tmp, sizeof(tmp), "%ldpt", deciPt / 10); - else + } else { snprintf(tmp, sizeof(tmp), "%ld.%ldpt", deciPt / 10, deciPt % 10); + } ffStrbufAppendS(&font->size, tmp); } - } - else if(field == 6) // pixelsize (fallback if pointsize missing/invalid) + } else if (field == 6) // pixelsize (fallback if pointsize missing/invalid) { - if(font->size.length == 0) - { + if (font->size.length == 0) { long px = 0; bool ok = true; - for(uint32_t i = 0; i < length; i++) - { + for (uint32_t i = 0; i < length; i++) { char c = pstart[i]; - if(c < '0' || c > '9') { ok = false; break; } + if (c < '0' || c > '9') { + ok = false; + break; + } px = px * 10 + (c - '0'); } - if(ok && px > 0) - { + if (ok && px > 0) { ffStrbufAppendNS(&font->size, length, pstart); ffStrbufAppendS(&font->size, "px"); } } - } - else if(field >= 2 && field <= 5) // weight/slant/setwidth/addstyle + } else if (field >= 2 && field <= 5) // weight/slant/setwidth/addstyle { // ignore "normal" (case-insensitive) - if(!(length == 6 && ffStrStartsWithIgnCase(pstart, "normal"))) - { + if (!(length == 6 && ffStrStartsWithIgnCase(pstart, "normal"))) { FFstrbuf* style = (FFstrbuf*) ffListAdd(&font->styles); ffStrbufInitNS(style, length, pstart); } } } - if(!pend) + if (!pend) { break; + } pstart = pend + 1; } @@ -286,8 +287,7 @@ void ffFontInitXlfd(FFfont* font, const char* xlfd) fontInitPretty(font); } -void ffFontInitXft(FFfont* font, const char* xft) -{ +void ffFontInitXft(FFfont* font, const char* xft) { assert(xft); // https://en.wikipedia.org/wiki/Xft @@ -302,26 +302,28 @@ void ffFontInitXft(FFfont* font, const char* xft) // 1) Parse "head" part before first ':' => usually "family[-size]" (may include commas) const char* p = xft; - while(*p == ' ' || *p == '\t') + while (*p == ' ' || *p == '\t') { ++p; + } const char* headStart = p; - while(*p != '\0' && *p != ':') + while (*p != '\0' && *p != ':') { ++p; + } const char* headEnd = p; // trim tail spaces - while(headEnd > headStart && (headEnd[-1] == ' ' || headEnd[-1] == '\t')) + while (headEnd > headStart && (headEnd[-1] == ' ' || headEnd[-1] == '\t')) { --headEnd; + } // If multiple families are listed, take the first one (up to comma) - for(const char* q = headStart; q < headEnd; ++q) - { - if(*q == ',') - { + for (const char* q = headStart; q < headEnd; ++q) { + if (*q == ',') { headEnd = q; - while(headEnd > headStart && (headEnd[-1] == ' ' || headEnd[-1] == '\t')) + while (headEnd > headStart && (headEnd[-1] == ' ' || headEnd[-1] == '\t')) { --headEnd; + } break; } } @@ -330,56 +332,51 @@ void ffFontInitXft(FFfont* font, const char* xft) const char* dashPos = NULL; const char* sizeStart = NULL; - for(const char* q = headEnd; q > headStart; ) - { + for (const char* q = headEnd; q > headStart;) { --q; - if(*q == '-' && (q + 1) < headEnd && ffCharIsDigit(q[1])) - { + if (*q == '-' && (q + 1) < headEnd && ffCharIsDigit(q[1])) { dashPos = q; sizeStart = q + 1; break; } } - if(dashPos) - { + if (dashPos) { bool ok = true; bool seenDigit = false; - for(const char* q = sizeStart; q < headEnd; ++q) - { - if(ffCharIsDigit(*q)) + for (const char* q = sizeStart; q < headEnd; ++q) { + if (ffCharIsDigit(*q)) { seenDigit = true; - else if(*q == '.') + } else if (*q == '.') { continue; - else - { + } else { ok = false; break; } } - if(ok && seenDigit) - { + if (ok && seenDigit) { const char* nameEnd = dashPos; - while(nameEnd > headStart && (nameEnd[-1] == ' ' || nameEnd[-1] == '\t')) + while (nameEnd > headStart && (nameEnd[-1] == ' ' || nameEnd[-1] == '\t')) { --nameEnd; + } - if(nameEnd > headStart) + if (nameEnd > headStart) { ffStrbufAppendNS(&font->name, (uint32_t) (nameEnd - headStart), headStart); + } - if(headEnd > sizeStart) + if (headEnd > sizeStart) { ffStrbufAppendNS(&font->size, (uint32_t) (headEnd - sizeStart), sizeStart); - } - else - { - if(headEnd > headStart) + } + } else { + if (headEnd > headStart) { ffStrbufAppendNS(&font->name, (uint32_t) (headEnd - headStart), headStart); + } } - } - else - { - if(headEnd > headStart) + } else { + if (headEnd > headStart) { ffStrbufAppendNS(&font->name, (uint32_t) (headEnd - headStart), headStart); + } } ffStrbufTrim(&font->name, ' '); @@ -387,28 +384,27 @@ void ffFontInitXft(FFfont* font, const char* xft) // 2) Parse key=value fields after ':' (Fontconfig-like). Fields separated by ':'. // Common keys: size, pixelsize, pointsize, style, weight, slant, width - while(*p == ':') - { + while (*p == ':') { ++p; // key const char* keyStart = p; - while(*p != '\0' && *p != '=' && *p != ':') + while (*p != '\0' && *p != '=' && *p != ':') { ++p; + } const char* keyEnd = p; - if(*p != '=') + if (*p != '=') { continue; // skip tokens without '=' + } ++p; // skip '=' // value (until next ':', allow backslash-escaping) FF_STRBUF_AUTO_DESTROY value = ffStrbufCreate(); - while(*p != '\0' && *p != ':') - { - if(*p == '\\' && p[1] != '\0') - { + while (*p != '\0' && *p != ':') { + if (*p == '\\' && p[1] != '\0') { ++p; ffStrbufAppendC(&value, *p); ++p; @@ -426,44 +422,36 @@ void ffFontInitXft(FFfont* font, const char* xft) // helper: set numeric size if not set yet const bool sizeEmpty = (font->size.length == 0); - if(value.length > 0) - { - if( + if (value.length > 0) { + if ( (keyLen == 4 && ffStrStartsWithIgnCase(keyStart, "size")) || - (keyLen == 9 && ffStrStartsWithIgnCase(keyStart, "pixelsize")) - ) - { - if(sizeEmpty && ffCharIsDigit(value.chars[0])) - { + (keyLen == 9 && ffStrStartsWithIgnCase(keyStart, "pixelsize"))) { + if (sizeEmpty && ffCharIsDigit(value.chars[0])) { ffStrbufAppend(&font->size, &value); ffStrbufAppendS(&font->size, keyLen == 4 ? "pt" : "px"); } - } - else if(keyLen == 5 && ffStrStartsWithIgnCase(keyStart, "style")) - { + } else if (keyLen == 5 && ffStrStartsWithIgnCase(keyStart, "style")) { // style may contain multiple words: "Bold Italic" const char* s = value.chars; - while(*s != '\0') - { - while(*s == ' ' || *s == '\t' || *s == ',') + while (*s != '\0') { + while (*s == ' ' || *s == '\t' || *s == ',') { ++s; + } const char* w = s; - while(*s != '\0' && *s != ' ' && *s != '\t' && *s != ',') + while (*s != '\0' && *s != ' ' && *s != '\t' && *s != ',') { ++s; + } - if(s > w) - { + if (s > w) { FFstrbuf* style = FF_LIST_ADD(FFstrbuf, font->styles); ffStrbufInitNS(style, (uint32_t) (s - w), w); } } - } - else if( + } else if ( (keyLen == 6 && ffStrStartsWithIgnCase(keyStart, "weight")) || (keyLen == 5 && ffStrStartsWithIgnCase(keyStart, "slant")) || - (keyLen == 5 && ffStrStartsWithIgnCase(keyStart, "width")) - ) { + (keyLen == 5 && ffStrStartsWithIgnCase(keyStart, "width"))) { // normalize: remove '-' to align with other parsers ("Semi-Bold" -> "SemiBold") FFstrbuf* style = FF_LIST_ADD(FFstrbuf, font->styles); ffStrbufInit(style); @@ -476,14 +464,16 @@ void ffFontInitXft(FFfont* font, const char* xft) fontInitPretty(font); } -void ffFontInitMoveValues(FFfont* font, FFstrbuf* name, FFstrbuf* size, FFstrbuf* style) -{ +void ffFontInitMoveValues(FFfont* font, FFstrbuf* name, FFstrbuf* size, FFstrbuf* style) { ffFontInit(font); - if (name) ffStrbufInitMove(&font->name, name); - if (size) ffStrbufInitMove(&font->size, size); - if (style) - { + if (name) { + ffStrbufInitMove(&font->name, name); + } + if (size) { + ffStrbufInitMove(&font->size, size); + } + if (style) { FFstrbuf* styleBuf = FF_LIST_ADD(FFstrbuf, font->styles); ffStrbufInitMove(styleBuf, style); } @@ -491,30 +481,28 @@ void ffFontInitMoveValues(FFfont* font, FFstrbuf* name, FFstrbuf* size, FFstrbuf fontInitPretty(font); } -void ffFontInitWithSpace(FFfont* font, const char* rawName) -{ +void ffFontInitWithSpace(FFfont* font, const char* rawName) { const char* pspace = strrchr(rawName, ' '); - if(pspace == NULL) - { + if (pspace == NULL) { ffFontInitCopy(font, rawName); return; } ffFontInit(font); - ffStrbufAppendNS(&font->name, (uint32_t)(pspace - rawName), rawName); + ffStrbufAppendNS(&font->name, (uint32_t) (pspace - rawName), rawName); ffStrbufAppendS(&font->size, pspace + 1); fontInitPretty(font); } -void ffFontDestroy(FFfont* font) -{ +void ffFontDestroy(FFfont* font) { ffStrbufDestroy(&font->pretty); ffStrbufDestroy(&font->name); ffStrbufDestroy(&font->size); - FF_LIST_FOR_EACH(FFstrbuf, str, font->styles) + FF_LIST_FOR_EACH (FFstrbuf, str, font->styles) { ffStrbufDestroy(str); + } ffListDestroy(&font->styles); } diff --git a/src/common/impl/format.c b/src/common/impl/format.c index 16b21c479..37e7db623 100644 --- a/src/common/impl/format.c +++ b/src/common/impl/format.c @@ -6,61 +6,58 @@ #include -void ffFormatAppendFormatArg(FFstrbuf* buffer, const FFformatarg* formatarg) -{ - switch(formatarg->type) - { +void ffFormatAppendFormatArg(FFstrbuf* buffer, const FFformatarg* formatarg) { + switch (formatarg->type) { case FF_ARG_TYPE_INT: - ffStrbufAppendSInt(buffer, *(int32_t*)formatarg->value); + ffStrbufAppendSInt(buffer, *(int32_t*) formatarg->value); break; case FF_ARG_TYPE_UINT: - ffStrbufAppendUInt(buffer, *(uint32_t*)formatarg->value); + ffStrbufAppendUInt(buffer, *(uint32_t*) formatarg->value); break; case FF_ARG_TYPE_UINT64: - ffStrbufAppendUInt(buffer, *(uint64_t*)formatarg->value); + ffStrbufAppendUInt(buffer, *(uint64_t*) formatarg->value); break; case FF_ARG_TYPE_UINT16: - ffStrbufAppendUInt(buffer, *(uint16_t*)formatarg->value); + ffStrbufAppendUInt(buffer, *(uint16_t*) formatarg->value); break; case FF_ARG_TYPE_UINT8: - ffStrbufAppendUInt(buffer, *(uint8_t*)formatarg->value); + ffStrbufAppendUInt(buffer, *(uint8_t*) formatarg->value); break; case FF_ARG_TYPE_STRING: - ffStrbufAppendS(buffer, (const char*)formatarg->value); + ffStrbufAppendS(buffer, (const char*) formatarg->value); break; case FF_ARG_TYPE_STRBUF: - ffStrbufAppend(buffer, (const FFstrbuf*)formatarg->value); + ffStrbufAppend(buffer, (const FFstrbuf*) formatarg->value); break; case FF_ARG_TYPE_FLOAT: - ffStrbufAppendDouble(buffer, *(float*)formatarg->value, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros != FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER); + ffStrbufAppendDouble(buffer, *(float*) formatarg->value, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros != FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER); break; case FF_ARG_TYPE_DOUBLE: - ffStrbufAppendDouble(buffer, *(double*)formatarg->value, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros != FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER); + ffStrbufAppendDouble(buffer, *(double*) formatarg->value, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros != FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER); break; case FF_ARG_TYPE_BOOL: - ffStrbufAppendS(buffer, *(bool*)formatarg->value ? "true" : "false"); + ffStrbufAppendS(buffer, *(bool*) formatarg->value ? "true" : "false"); break; - case FF_ARG_TYPE_LIST: - { + case FF_ARG_TYPE_LIST: { const FFlist* list = (const FFlist*) formatarg->value; - for(uint32_t i = 0; i < list->length; i++) - { + for (uint32_t i = 0; i < list->length; i++) { ffStrbufAppend(buffer, FF_LIST_GET(FFstrbuf, *list, i)); - if(i < list->length - 1) + if (i < list->length - 1) { ffStrbufAppendS(buffer, ", "); + } } break; } - case FF_ARG_TYPE_BUFFER: - { + case FF_ARG_TYPE_BUFFER: { // Placeholder for binary data, just print the size for now const FFArgBuffer* argBuffer = (const FFArgBuffer*) formatarg->value; ffStrbufAppendF(buffer, "buffer(%u bytes)", argBuffer->length); break; } default: - if(formatarg->type != FF_ARG_TYPE_NULL) + if (formatarg->type != FF_ARG_TYPE_NULL) { fprintf(stderr, "Error: format string \"%s\": argument is not implemented: %i\n", buffer->chars, formatarg->type); + } break; } } @@ -73,62 +70,48 @@ void ffFormatAppendFormatArg(FFstrbuf* buffer, const FFformatarg* formatarg) * @param placeholderValue the string to parse * @return uint32_t the parsed value */ -static uint32_t getArgumentIndex(const char* placeholderValue, uint32_t numArgs, const FFformatarg* arguments) -{ +static uint32_t getArgumentIndex(const char* placeholderValue, uint32_t numArgs, const FFformatarg* arguments) { char firstChar = placeholderValue[0]; - if (firstChar == '\0') + if (firstChar == '\0') { return 0; // use arg counter + } - if (firstChar >= '0' && firstChar <= '9') - { + if (firstChar >= '0' && firstChar <= '9') { char* pEnd = NULL; uint32_t result = (uint32_t) strtoul(placeholderValue, &pEnd, 10); - if (result > numArgs) + if (result > numArgs) { return UINT32_MAX; - if (*pEnd != '\0') + } + if (*pEnd != '\0') { return UINT32_MAX; + } return result; - } - else if (ffCharIsEnglishAlphabet(firstChar)) - { - for (uint32_t i = 0; i < numArgs; ++i) - { + } else if (ffCharIsEnglishAlphabet(firstChar)) { + for (uint32_t i = 0; i < numArgs; ++i) { const FFformatarg* arg = &arguments[i]; - if (arg->name && ffStrEqualsIgnCase(placeholderValue, arg->name)) + if (arg->name && ffStrEqualsIgnCase(placeholderValue, arg->name)) { return i + 1; + } } } return UINT32_MAX; } -static inline void appendInvalidPlaceholder(FFstrbuf* buffer, const char* start, const FFstrbuf* placeholderValue, uint32_t index, uint32_t formatStringLength) -{ +static inline void appendInvalidPlaceholder(FFstrbuf* buffer, const char* start, const FFstrbuf* placeholderValue, uint32_t index, uint32_t formatStringLength) { ffStrbufAppendS(buffer, start); ffStrbufAppend(buffer, placeholderValue); - if(index < formatStringLength) + if (index < formatStringLength) { ffStrbufAppendC(buffer, '}'); + } } -static inline bool formatArgSet(const FFformatarg* arg) -{ - return arg->value != NULL && ( - (arg->type == FF_ARG_TYPE_DOUBLE && *(double*)arg->value > 0.0) || - (arg->type == FF_ARG_TYPE_FLOAT && *(float*)arg->value > 0.0) || - (arg->type == FF_ARG_TYPE_INT && *(int*)arg->value > 0) || - (arg->type == FF_ARG_TYPE_STRBUF && ((FFstrbuf*)arg->value)->length > 0) || - (arg->type == FF_ARG_TYPE_STRING && ffStrSet((char*)arg->value)) || - (arg->type == FF_ARG_TYPE_UINT8 && *(uint8_t*)arg->value > 0) || - (arg->type == FF_ARG_TYPE_UINT16 && *(uint16_t*)arg->value > 0) || - (arg->type == FF_ARG_TYPE_UINT && *(uint32_t*)arg->value > 0) || - (arg->type == FF_ARG_TYPE_BOOL && *(bool*)arg->value) || - (arg->type == FF_ARG_TYPE_LIST && ((FFlist*)arg->value)->length > 0) - ); +static inline bool formatArgSet(const FFformatarg* arg) { + return arg->value != NULL && ((arg->type == FF_ARG_TYPE_DOUBLE && *(double*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_FLOAT && *(float*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_INT && *(int*) arg->value > 0) || (arg->type == FF_ARG_TYPE_STRBUF && ((FFstrbuf*) arg->value)->length > 0) || (arg->type == FF_ARG_TYPE_STRING && ffStrSet((char*) arg->value)) || (arg->type == FF_ARG_TYPE_UINT8 && *(uint8_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT16 && *(uint16_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT && *(uint32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_BOOL && *(bool*) arg->value) || (arg->type == FF_ARG_TYPE_LIST && ((FFlist*) arg->value)->length > 0)); } -void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t numArgs, const FFformatarg* arguments) -{ +void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t numArgs, const FFformatarg* arguments) { uint32_t argCounter = 0; uint32_t numOpenIfs = 0; @@ -136,11 +119,9 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n FF_STRBUF_AUTO_DESTROY placeholderValue = ffStrbufCreate(); - for(uint32_t i = 0; i < formatstr->length; ++i) - { + for (uint32_t i = 0; i < formatstr->length; ++i) { // if we don't have a placeholder start just copy the chars over to output buffer - if(formatstr->chars[i] != '{') - { + if (formatstr->chars[i] != '{') { ffStrbufAppendC(buffer, formatstr->chars[i]); continue; } @@ -149,8 +130,7 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n ++i; // double {{ elvaluates to a single { and doesn't count as start - if(formatstr->chars[i] == '{') - { + if (formatstr->chars[i] == '{') { ffStrbufAppendC(buffer, '{'); continue; } @@ -165,61 +145,58 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n char firstChar = placeholderValue.chars[0]; - if (placeholderValue.length == 1) - { + if (placeholderValue.length == 1) { // test if for stop, if so break the loop - if (firstChar == '-') + if (firstChar == '-') { break; + } // test for end of an if, if so do nothing - if (firstChar == '?') - { - if(numOpenIfs == 0) + if (firstChar == '?') { + if (numOpenIfs == 0) { appendInvalidPlaceholder(buffer, "{", &placeholderValue, i, formatstr->length); - else + } else { --numOpenIfs; + } continue; } // test for end of a not if, if so do nothing - if (firstChar == '/') - { - if(numOpenNotIfs == 0) + if (firstChar == '/') { + if (numOpenNotIfs == 0) { appendInvalidPlaceholder(buffer, "{", &placeholderValue, i, formatstr->length); - else + } else { --numOpenNotIfs; + } continue; } // test for end of a color, if so do nothing - if (firstChar == '#') - { - if (!instance.config.display.pipe) + if (firstChar == '#') { + if (!instance.config.display.pipe) { ffStrbufAppendS(buffer, FASTFETCH_TEXT_MODIFIER_RESET); + } continue; } } // test for if, if so evaluate it - if (firstChar == '?') - { + if (firstChar == '?') { ffStrbufSubstrAfter(&placeholderValue, 0); uint32_t index = getArgumentIndex(placeholderValue.chars, numArgs, arguments); // testing for an invalid index - if (index > numArgs || index < 1) - { + if (index > numArgs || index < 1) { appendInvalidPlaceholder(buffer, "{?", &placeholderValue, i, formatstr->length); continue; } // continue normally if an format arg is set and the value is > 0 - if (formatArgSet(&arguments[index - 1])) - { + if (formatArgSet(&arguments[index - 1])) { ++numOpenIfs; continue; } @@ -230,22 +207,19 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n } // test for not if, if so evaluate it - if (firstChar == '/') - { + if (firstChar == '/') { ffStrbufSubstrAfter(&placeholderValue, 0); uint32_t index = getArgumentIndex(placeholderValue.chars, numArgs, arguments); // testing for an invalid index - if (index > numArgs || index < 1) - { + if (index > numArgs || index < 1) { appendInvalidPlaceholder(buffer, "{/", &placeholderValue, i, formatstr->length); continue; } - //continue normally if an format arg is not set or the value is 0 - if (!formatArgSet(&arguments[index - 1])) - { + // continue normally if an format arg is not set or the value is 0 + if (!formatArgSet(&arguments[index - 1])) { ++numOpenNotIfs; continue; } @@ -255,11 +229,9 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n continue; } - //test for color, if so evaluate it - if (firstChar == '#') - { - if (!instance.config.display.pipe) - { + // test for color, if so evaluate it + if (firstChar == '#') { + if (!instance.config.display.pipe) { ffStrbufAppendS(buffer, "\e["); ffOptionParseColorNoClear(placeholderValue.chars + 1, buffer); ffStrbufAppendC(buffer, 'm'); @@ -267,29 +239,25 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n continue; } - //test for constant or env var, if so evaluate it - if (firstChar == '$') - { + // test for constant or env var, if so evaluate it + if (firstChar == '$') { char* pend = NULL; int32_t indexSigned = (int32_t) strtol(placeholderValue.chars + 1, &pend, 10); - if (pend == placeholderValue.chars + 1) - { + if (pend == placeholderValue.chars + 1) { // treat placeholder as an environment variable char* envValue = getenv(placeholderValue.chars + 1); - if (envValue) + if (envValue) { ffStrbufAppendS(buffer, envValue); - else + } else { appendInvalidPlaceholder(buffer, "{", &placeholderValue, i, formatstr->length); - } - else - { + } + } else { // treat placeholder as a constant uint32_t index = (uint32_t) (indexSigned < 0 ? (int32_t) instance.config.display.constants.length + indexSigned : indexSigned - 1); - if (*pend != '\0' || instance.config.display.constants.length <= index) + if (*pend != '\0' || instance.config.display.constants.length <= index) { appendInvalidPlaceholder(buffer, "{", &placeholderValue, i, formatstr->length); - else - { + } else { FFstrbuf* item = FF_LIST_GET(FFstrbuf, instance.config.display.constants, index); ffStrbufAppend(buffer, item); } @@ -299,115 +267,104 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n char* pSep = placeholderValue.chars; char cSep = '\0'; - while (*pSep && *pSep != ':' && *pSep != '<' && *pSep != '>' && *pSep != '~') + while (*pSep && *pSep != ':' && *pSep != '<' && *pSep != '>' && *pSep != '~') { ++pSep; - if (*pSep) - { + } + if (*pSep) { cSep = *pSep; *pSep = '\0'; - } - else - { + } else { pSep = NULL; } uint32_t index = getArgumentIndex(placeholderValue.chars, numArgs, arguments); // test for invalid index - if (index == 0) + if (index == 0) { index = ++argCounter; + } - if (index > numArgs) - { - if (pSep) *pSep = cSep; + if (index > numArgs) { + if (pSep) { + *pSep = cSep; + } appendInvalidPlaceholder(buffer, "{", &placeholderValue, i, formatstr->length); continue; } - if (!cSep) + if (!cSep) { ffFormatAppendFormatArg(buffer, &arguments[index - 1]); - else if (cSep == '~') - { + } else if (cSep == '~') { FF_STRBUF_AUTO_DESTROY tempString = ffStrbufCreate(); ffFormatAppendFormatArg(&tempString, &arguments[index - 1]); char* pEnd = NULL; int32_t start = (int32_t) strtol(pSep + 1, &pEnd, 10); - if (start < 0) + if (start < 0) { start = (int32_t) tempString.length + start; - if (start >= 0 && (uint32_t) start < tempString.length) - { - if (*pEnd == '\0') + } + if (start >= 0 && (uint32_t) start < tempString.length) { + if (*pEnd == '\0') { ffStrbufAppendNS(buffer, tempString.length - (uint32_t) start, &tempString.chars[start]); - else if (*pEnd == ',') - { + } else if (*pEnd == ',') { int32_t end = (int32_t) strtol(pEnd + 1, &pEnd, 10); - if (!*pEnd) - { - if (end < 0) + if (!*pEnd) { + if (end < 0) { end = (int32_t) tempString.length + end; - if ((uint32_t) end > tempString.length) + } + if ((uint32_t) end > tempString.length) { end = (int32_t) tempString.length; - if (end > start) + } + if (end > start) { ffStrbufAppendNS(buffer, (uint32_t) (end - start), &tempString.chars[start]); + } } } } - if (*pEnd) - { + if (*pEnd) { *pSep = cSep; appendInvalidPlaceholder(buffer, "{", &placeholderValue, i, formatstr->length); continue; } - } - else - { + } else { char* pEnd = NULL; int32_t truncLength = (int32_t) strtol(pSep + 1, &pEnd, 10); - if (*pEnd != '\0') - { + if (*pEnd != '\0') { *pSep = cSep; appendInvalidPlaceholder(buffer, "{", &placeholderValue, i, formatstr->length); continue; } bool ellipsis = false; - if (truncLength < 0) - { + if (truncLength < 0) { ellipsis = true; truncLength = -truncLength; } FF_STRBUF_AUTO_DESTROY tempString = ffStrbufCreate(); ffFormatAppendFormatArg(&tempString, &arguments[index - 1]); - if (tempString.length == (uint32_t) truncLength) + if (tempString.length == (uint32_t) truncLength) { ffStrbufAppend(buffer, &tempString); - else if (tempString.length > (uint32_t) truncLength) - { - if (cSep == ':') - { + } else if (tempString.length > (uint32_t) truncLength) { + if (cSep == ':') { ffStrbufSubstrBefore(&tempString, (uint32_t) truncLength); ffStrbufTrimRightSpace(&tempString); + } else { + ffStrbufSubstrBefore(&tempString, (uint32_t) (!ellipsis ? truncLength : truncLength - 1)); } - else - ffStrbufSubstrBefore(&tempString, (uint32_t) (!ellipsis? truncLength : truncLength - 1)); ffStrbufAppend(buffer, &tempString); - if (ellipsis) + if (ellipsis) { ffStrbufAppendS(buffer, "…"); - } - else if (cSep == ':') + } + } else if (cSep == ':') { ffStrbufAppend(buffer, &tempString); - else - { - if (cSep == '<') - { + } else { + if (cSep == '<') { ffStrbufAppend(buffer, &tempString); ffStrbufAppendNC(buffer, (uint32_t) truncLength - tempString.length, ' '); - } - else - { + } else { ffStrbufAppendNC(buffer, (uint32_t) truncLength - tempString.length, ' '); ffStrbufAppend(buffer, &tempString); } @@ -415,6 +372,7 @@ void ffParseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint32_t n } } - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { ffStrbufAppendS(buffer, FASTFETCH_TEXT_MODIFIER_RESET); + } } diff --git a/src/common/impl/frequency.c b/src/common/impl/frequency.c index 3e5185be4..4838df803 100644 --- a/src/common/impl/frequency.c +++ b/src/common/impl/frequency.c @@ -1,24 +1,25 @@ #include "common/frequency.h" -bool ffFreqAppendNum(uint32_t mhz, FFstrbuf* result) -{ - if (mhz == 0) +bool ffFreqAppendNum(uint32_t mhz, FFstrbuf* result) { + if (mhz == 0) { return false; + } const FFOptionsDisplay* options = &instance.config.display; bool spaceBeforeUnit = options->freqSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER; int8_t ndigits = options->freqNdigits; - if (ndigits >= 0) - { + if (ndigits >= 0) { ffStrbufAppendDouble(result, mhz / 1000., ndigits, true); - if (spaceBeforeUnit) ffStrbufAppendC(result, ' '); + if (spaceBeforeUnit) { + ffStrbufAppendC(result, ' '); + } ffStrbufAppendS(result, "GHz"); - } - else - { + } else { ffStrbufAppendUInt(result, mhz); - if (spaceBeforeUnit) ffStrbufAppendC(result, ' '); + if (spaceBeforeUnit) { + ffStrbufAppendC(result, ' '); + } ffStrbufAppendS(result, "MHz"); } return true; diff --git a/src/common/impl/init.c b/src/common/impl/init.c index 18c250d33..d38937021 100644 --- a/src/common/impl/init.c +++ b/src/common/impl/init.c @@ -11,16 +11,15 @@ #include #include #ifdef _WIN32 - #include - #include "common/windows/unicode.h" +# include +# include "common/windows/unicode.h" #else - #include +# include #endif FFinstance instance; // Global singleton -static void initState(FFstate* state) -{ +static void initState(FFstate* state) { state->logoWidth = 0; state->logoHeight = 0; state->keysHeight = 0; @@ -33,27 +32,26 @@ static void initState(FFstate* state) { // don't enable bright color if the terminal is in light mode FFTerminalThemeResult result; - if (ffDetectTerminalTheme(&result, true /* forceEnv for performance */) && !result.bg.dark) + if (ffDetectTerminalTheme(&result, true /* forceEnv for performance */) && !result.bg.dark) { state->terminalLightTheme = true; + } } } -static void defaultConfig(void) -{ +static void defaultConfig(void) { ffOptionsInitLogo(&instance.config.logo); ffOptionsInitGeneral(&instance.config.general); ffOptionsInitDisplay(&instance.config.display); } -void ffInitInstance(void) -{ - #ifdef _WIN32 - // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setlocale-wsetlocale?source=recommendat> - setlocale(LC_ALL, ".UTF8"); - #else - // Never use `setlocale(LC_ALL, "")` - setlocale(LC_TIME, ""); - #endif +void ffInitInstance(void) { +#ifdef _WIN32 + // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setlocale-wsetlocale?source=recommendat> + setlocale(LC_ALL, ".UTF8"); +#else + // Never use `setlocale(LC_ALL, "")` + setlocale(LC_TIME, ""); +#endif defaultConfig(); initState(&instance.state); @@ -65,62 +63,66 @@ static volatile bool ffHideCursor = true; static volatile UINT oldCp = CP_UTF8; #endif -static void resetConsole(void) -{ - if(ffDisableLinewrap) +static void resetConsole(void) { + if (ffDisableLinewrap) { fputs("\033[?7h", stdout); + } - if(ffHideCursor) + if (ffHideCursor) { fputs("\033[?25h", stdout); + } - if(instance.state.dynamicInterval > 0) + if (instance.state.dynamicInterval > 0) { fputs("\033[?1049l", stdout); // Disable alternate buffer + } - #if defined(_WIN32) - fflush(stdout); +#if defined(_WIN32) + fflush(stdout); - if(oldCp != CP_UTF8) - SetConsoleOutputCP(oldCp); - #endif + if (oldCp != CP_UTF8) { + SetConsoleOutputCP(oldCp); + } +#endif } #ifdef _WIN32 -BOOL WINAPI consoleHandler(FF_MAYBE_UNUSED DWORD signal) -{ +BOOL WINAPI consoleHandler(FF_MAYBE_UNUSED DWORD signal) { resetConsole(); exit(0); } #else -static void exitSignalHandler(FF_MAYBE_UNUSED int signal) -{ +static void exitSignalHandler(FF_MAYBE_UNUSED int signal) { resetConsole(); exit(0); } #endif -void ffStart(void) -{ +void ffStart(void) { ffDisableLinewrap = instance.config.display.disableLinewrap && !instance.config.display.pipe; ffHideCursor = instance.config.display.hideCursor && !instance.config.display.pipe; - #ifdef _WIN32 +#ifdef _WIN32 SetErrorMode(SEM_FAILCRITICALERRORS); - if (instance.config.display.noBuffer) + if (instance.config.display.noBuffer) { setvbuf(stdout, NULL, _IONBF, 0); - else + } else { setvbuf(stdout, NULL, _IOFBF, 4096); + } SetConsoleCtrlHandler(consoleHandler, TRUE); HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); DWORD mode = 0; - if (GetConsoleMode(hStdout, &mode)) - { + if (GetConsoleMode(hStdout, &mode)) { SetConsoleMode(hStdout, mode | ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING); oldCp = GetConsoleOutputCP(); - if (oldCp != CP_UTF8) SetConsoleOutputCP(CP_UTF8); + if (oldCp != CP_UTF8) { + SetConsoleOutputCP(CP_UTF8); + } } - #else - if (instance.config.display.noBuffer) setvbuf(stdout, NULL, _IONBF, 0); - struct sigaction action = { .sa_handler = exitSignalHandler }; +#else + if (instance.config.display.noBuffer) { + setvbuf(stdout, NULL, _IONBF, 0); + } + struct sigaction action = {.sa_handler = exitSignalHandler}; sigaction(SIGINT, &action, NULL); sigaction(SIGTERM, &action, NULL); sigaction(SIGQUIT, &action, NULL); @@ -128,142 +130,139 @@ void ffStart(void) sigemptyset(&newmask); sigaddset(&newmask, SIGCHLD); sigprocmask(SIG_BLOCK, &newmask, NULL); - #endif +#endif - //reset everything to default before we start printing - if(!instance.config.display.pipe) + // reset everything to default before we start printing + if (!instance.config.display.pipe) { fputs(FASTFETCH_TEXT_MODIFIER_RESET, stdout); + } - if(ffHideCursor) + if (ffHideCursor) { fputs("\033[?25l", stdout); + } - if(ffDisableLinewrap) + if (ffDisableLinewrap) { fputs("\033[?7l", stdout); + } - if(instance.state.dynamicInterval > 0) - { + if (instance.state.dynamicInterval > 0) { fputs("\033[?1049h\033[H", stdout); // Enable alternate buffer fflush(stdout); } } -void ffFinish(void) -{ +void ffFinish(void) { resetConsole(); } -static void destroyConfig(void) -{ +static void destroyConfig(void) { ffOptionsDestroyLogo(&instance.config.logo); ffOptionsDestroyGeneral(&instance.config.general); ffOptionsDestroyDisplay(&instance.config.display); } -static void destroyState(void) -{ +static void destroyState(void) { ffPlatformDestroy(&instance.state.platform); } -void ffDestroyInstance(void) -{ +void ffDestroyInstance(void) { destroyConfig(); destroyState(); } -//Must be in a file compiled with the libfastfetch target, because the FF_HAVE* macros are not defined for the executable targets -void ffListFeatures(void) -{ +// Must be in a file compiled with the libfastfetch target, because the FF_HAVE* macros are not defined for the executable targets +void ffListFeatures(void) { fputs( - #if FF_HAVE_THREADS - "threads\n" - #endif - #if FF_HAVE_VULKAN - "vulkan\n" - #endif - #if FF_HAVE_WAYLAND - "wayland\n" - #endif - #if FF_HAVE_XCB_RANDR - "xcb-randr\n" - #endif - #if FF_HAVE_XRANDR - "xrandr\n" - #endif - #if FF_HAVE_DRM - "drm\n" - #endif - #if FF_HAVE_DRM_AMDGPU - "drm_amdgpu\n" - #endif - #if FF_HAVE_GIO - "gio\n" - #endif - #if FF_HAVE_DCONF - "dconf\n" - #endif - #if FF_HAVE_DBUS - "dbus\n" - #endif - #if FF_HAVE_IMAGEMAGICK7 - "imagemagick7\n" - #endif - #if FF_HAVE_IMAGEMAGICK6 - "imagemagick6\n" - #endif - #if FF_HAVE_CHAFA - "chafa\n" - #endif - #if FF_HAVE_ZLIB - "zlib\n" - #endif - #if FF_HAVE_SQLITE3 - "sqlite3\n" - #endif - #if FF_HAVE_RPM - "rpm\n" - #endif - #if FF_HAVE_EGL - "egl\n" - #endif - #if FF_HAVE_GLX - "glx\n" - #endif - #if FF_HAVE_OPENCL - "opencl\n" - #endif - #if FF_HAVE_FREETYPE - "freetype\n" - #endif - #if FF_HAVE_PULSE - "libpulse\n" - #endif - #if FF_HAVE_DDCUTIL - "libddcutil\n" - #endif - #if FF_HAVE_ELF || __sun || (__FreeBSD__ && !__DragonFly__) || __OpenBSD__ || __NetBSD__ - "libelf\n" - #endif - #if FF_HAVE_LIBZFS - "libzfs\n" - #endif - #if FF_USE_SYSTEM_YYJSON - "System yyjson\n" - #endif - #if FF_HAVE_LINUX_VIDEODEV2 - "linux/videodev2\n" - #endif - #if FF_HAVE_LINUX_WIRELESS - "linux/wireless\n" - #endif - #if FF_HAVE_EMBEDDED_PCIIDS - "Embedded pciids\n" - #endif - #if FF_WIN81_COMPAT - "Windows 8.1 Compatibility\n" - #endif - #if FF_APPLE_MEMSIZE_USABLE - "Apple memsize_usable\n" - #endif - "" - , stdout); +#if FF_HAVE_THREADS + "threads\n" +#endif +#if FF_HAVE_VULKAN + "vulkan\n" +#endif +#if FF_HAVE_WAYLAND + "wayland\n" +#endif +#if FF_HAVE_XCB_RANDR + "xcb-randr\n" +#endif +#if FF_HAVE_XRANDR + "xrandr\n" +#endif +#if FF_HAVE_DRM + "drm\n" +#endif +#if FF_HAVE_DRM_AMDGPU + "drm_amdgpu\n" +#endif +#if FF_HAVE_GIO + "gio\n" +#endif +#if FF_HAVE_DCONF + "dconf\n" +#endif +#if FF_HAVE_DBUS + "dbus\n" +#endif +#if FF_HAVE_IMAGEMAGICK7 + "imagemagick7\n" +#endif +#if FF_HAVE_IMAGEMAGICK6 + "imagemagick6\n" +#endif +#if FF_HAVE_CHAFA + "chafa\n" +#endif +#if FF_HAVE_ZLIB + "zlib\n" +#endif +#if FF_HAVE_SQLITE3 + "sqlite3\n" +#endif +#if FF_HAVE_RPM + "rpm\n" +#endif +#if FF_HAVE_EGL + "egl\n" +#endif +#if FF_HAVE_GLX + "glx\n" +#endif +#if FF_HAVE_OPENCL + "opencl\n" +#endif +#if FF_HAVE_FREETYPE + "freetype\n" +#endif +#if FF_HAVE_PULSE + "libpulse\n" +#endif +#if FF_HAVE_DDCUTIL + "libddcutil\n" +#endif +#if FF_HAVE_ELF || __sun || (__FreeBSD__ && !__DragonFly__) || __OpenBSD__ || __NetBSD__ + "libelf\n" +#endif +#if FF_HAVE_LIBZFS + "libzfs\n" +#endif +#if FF_USE_SYSTEM_YYJSON + "System yyjson\n" +#endif +#if FF_HAVE_LINUX_VIDEODEV2 + "linux/videodev2\n" +#endif +#if FF_HAVE_LINUX_WIRELESS + "linux/wireless\n" +#endif +#if FF_HAVE_EMBEDDED_PCIIDS + "Embedded pciids\n" +#endif +#if FF_WIN81_COMPAT + "Windows 8.1 Compatibility\n" +#endif +#if FF_APPLE_MEMSIZE_USABLE + "Apple memsize_usable\n" +#endif + "", + stdout); } diff --git a/src/common/impl/io_unix.c b/src/common/impl/io_unix.c index 12c07d716..30dcb970a 100644 --- a/src/common/impl/io_unix.c +++ b/src/common/impl/io_unix.c @@ -8,181 +8,177 @@ #include #include #ifndef __APPLE__ -#include +# include #else -#include +# include #endif #if FF_HAVE_WORDEXP - #include +# include #else - #include +# include #endif -static void createSubfolders(const char* fileName) -{ +static void createSubfolders(const char* fileName) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); - const char *token = NULL; - while((token = strchr(fileName, '/')) != NULL) - { - ffStrbufAppendNS(&path, (uint32_t)(token - fileName + 1), fileName); + const char* token = NULL; + while ((token = strchr(fileName, '/')) != NULL) { + ffStrbufAppendNS(&path, (uint32_t) (token - fileName + 1), fileName); mkdir(path.chars, S_IRWXU | S_IRGRP | S_IROTH); fileName = token + 1; } } -bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) -{ +bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) { int openFlagsModes = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC; mode_t openFlagsRights = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int FF_AUTO_CLOSE_FD fd = open(fileName, openFlagsModes, openFlagsRights); - if(fd == -1) - { - if (errno == ENOENT) - { + if (fd == -1) { + if (errno == ENOENT) { createSubfolders(fileName); fd = open(fileName, openFlagsModes, openFlagsRights); - if(fd == -1) + if (fd == -1) { return false; - } - else + } + } else { return false; + } } return write(fd, data, dataSize) > 0; } -static inline void readWithLength(int fd, FFstrbuf* buffer, uint32_t length) -{ +static inline void readWithLength(int fd, FFstrbuf* buffer, uint32_t length) { ffStrbufEnsureFixedLengthFree(buffer, length); ssize_t bytesRead = 0; - while( - length > 0 && (bytesRead = read(fd, buffer->chars + buffer->length, length)) > 0 - ) { + while ( + length > 0 && (bytesRead = read(fd, buffer->chars + buffer->length, length)) > 0) { buffer->length += (uint32_t) bytesRead; length -= (uint32_t) bytesRead; } } -static inline void readUntilEOF(int fd, FFstrbuf* buffer) -{ +static inline void readUntilEOF(int fd, FFstrbuf* buffer) { ffStrbufEnsureFree(buffer, 31); uint32_t available = ffStrbufGetFree(buffer); ssize_t bytesRead = 0; - while( - (bytesRead = read(fd, buffer->chars + buffer->length, available)) > 0 - ) { + while ( + (bytesRead = read(fd, buffer->chars + buffer->length, available)) > 0) { buffer->length += (uint32_t) bytesRead; - if((uint32_t) bytesRead == available) + if ((uint32_t) bytesRead == available) { ffStrbufEnsureFree(buffer, buffer->allocated - 1); // Doubles capacity every round. -1 for the null byte. + } available = ffStrbufGetFree(buffer); } } -bool ffAppendFDBuffer(int fd, FFstrbuf* buffer) -{ +bool ffAppendFDBuffer(int fd, FFstrbuf* buffer) { struct stat fileInfo; - if(fstat(fd, &fileInfo) != 0) + if (fstat(fd, &fileInfo) != 0) { return false; + } - if (fileInfo.st_size > 0) - readWithLength(fd, buffer, (uint32_t)fileInfo.st_size); - else + if (fileInfo.st_size > 0) { + readWithLength(fd, buffer, (uint32_t) fileInfo.st_size); + } else { readUntilEOF(fd, buffer); + } buffer->chars[buffer->length] = '\0'; return buffer->length > 0; } -bool ffPathExpandEnv(const char* in, FFstrbuf* out) -{ +bool ffPathExpandEnv(const char* in, FFstrbuf* out) { bool result = false; - #if FF_HAVE_WORDEXP +#if FF_HAVE_WORDEXP wordexp_t exp; - if (wordexp(in, &exp, 0) != 0) // WARN: 0 = no safety flags; command substitution allowed + if (wordexp(in, &exp, 0) != 0) { // WARN: 0 = no safety flags; command substitution allowed return false; + } - if (exp.we_wordc >= 1) - { + if (exp.we_wordc >= 1) { result = true; ffStrbufSetS(out, exp.we_wordv[exp.we_wordc > 1 ? ffTimeGetNow() % exp.we_wordc : 0]); } wordfree(&exp); - #else +#else glob_t gb; if (glob(in, GLOB_NOSORT - #ifdef GLOB_TILDE - | GLOB_TILDE - #endif - #ifdef GLOB_BRACE - | GLOB_BRACE - #endif - , NULL, &gb) != 0) +# ifdef GLOB_TILDE + | GLOB_TILDE +# endif +# ifdef GLOB_BRACE + | GLOB_BRACE +# endif + , + NULL, + &gb) != 0) return false; - if (gb.gl_pathc >= 1) - { + if (gb.gl_pathc >= 1) { result = true; ffStrbufSetS(out, gb.gl_pathv[gb.gl_pathc > 1 ? ffTimeGetNow() % (unsigned) gb.gl_pathc : 0]); } globfree(&gb); - #endif +#endif return result; } static int ftty = -1; static struct termios oldTerm; -void restoreTerm(void) -{ +void restoreTerm(void) { tcsetattr(ftty, TCSAFLUSH, &oldTerm); } -const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) -{ - if (ftty < 0) - { +const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) { + if (ftty < 0) { ftty = open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC); - if (ftty < 0) + if (ftty < 0) { return "open(\"/dev/tty\", O_RDWR | O_NOCTTY | O_CLOEXEC) failed"; + } - if(tcgetattr(ftty, &oldTerm) == -1) + if (tcgetattr(ftty, &oldTerm) == -1) { return "tcgetattr(STDIN_FILENO, &oldTerm) failed"; + } struct termios newTerm = oldTerm; newTerm.c_lflag &= (tcflag_t) ~(ICANON | ECHO); - if(tcsetattr(ftty, TCSAFLUSH, &newTerm) == -1) + if (tcsetattr(ftty, TCSAFLUSH, &newTerm) == -1) { return "tcsetattr(STDIN_FILENO, TCSAFLUSH, &newTerm)"; + } atexit(restoreTerm); } ffWriteFDData(ftty, strlen(request), request); - //Give the terminal some time to respond - #ifndef __APPLE__ - if(poll(&(struct pollfd) { .fd = ftty, .events = POLLIN }, 1, FF_IO_TERM_RESP_WAIT_MS) <= 0) +// Give the terminal some time to respond +#ifndef __APPLE__ + if (poll(&(struct pollfd) {.fd = ftty, .events = POLLIN}, 1, FF_IO_TERM_RESP_WAIT_MS) <= 0) { return "poll(/dev/tty) timeout or failed"; - #else + } +#else { // On macOS, poll(/dev/tty) always returns immediately // See also https://nathancraddock.com/blog/macos-dev-tty-polling/ fd_set rd; FD_ZERO(&rd); FD_SET(ftty, &rd); - if(select(ftty + 1, &rd, NULL, NULL, &(struct timeval) { .tv_sec = FF_IO_TERM_RESP_WAIT_MS / 1000, .tv_usec = (FF_IO_TERM_RESP_WAIT_MS % 1000) * 1000 }) <= 0) + if (select(ftty + 1, &rd, NULL, NULL, &(struct timeval) {.tv_sec = FF_IO_TERM_RESP_WAIT_MS / 1000, .tv_usec = (FF_IO_TERM_RESP_WAIT_MS % 1000) * 1000}) <= 0) { return "select(/dev/tty) timeout or failed"; + } } - #endif +#endif char buffer[1024]; size_t bytesRead = 0; @@ -190,12 +186,10 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* va_list args; va_start(args, format); - while (true) - { + while (true) { ssize_t nRead = read(ftty, buffer + bytesRead, sizeof(buffer) - bytesRead - 1); - if (nRead <= 0) - { + if (nRead <= 0) { va_end(args); return "read(STDIN_FILENO, buffer, sizeof(buffer) - 1) failed"; } @@ -208,13 +202,13 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* int ret = vsscanf(buffer, format, cargs); va_end(cargs); - if (ret <= 0) - { + if (ret <= 0) { va_end(args); return "vsscanf(buffer, format, args) failed"; } - if (ret >= nParams) + if (ret >= nParams) { break; + } } va_end(args); @@ -222,22 +216,22 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* return NULL; } -bool ffSuppressIO(bool suppress) -{ - #ifndef NDEBUG - if (instance.config.display.debugMode) +bool ffSuppressIO(bool suppress) { +#ifndef NDEBUG + if (instance.config.display.debugMode) { return false; - #endif + } +#endif static bool init = false; static int origOut = -1; static int origErr = -1; static int nullFile = -1; - if(!init) - { - if(!suppress) + if (!init) { + if (!suppress) { return true; + } origOut = dup(STDOUT_FILENO); origErr = dup(STDERR_FILENO); @@ -245,8 +239,9 @@ bool ffSuppressIO(bool suppress) init = true; } - if(nullFile == -1) + if (nullFile == -1) { return false; + } fflush(stdout); fflush(stderr); @@ -256,47 +251,48 @@ bool ffSuppressIO(bool suppress) return true; } -void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) -{ +void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) { FF_AUTO_CLOSE_FD int dfd = open(folder->chars, O_RDONLY | O_CLOEXEC); - if (dfd < 0) + if (dfd < 0) { return; + } DIR* dir = fdopendir(dfd); - if(dir == NULL) + if (dir == NULL) { return; + } uint32_t folderLength = folder->length; - if(pretty && folderName != NULL) - { - for(uint8_t i = 0; i < indentation - 1; i++) + if (pretty && folderName != NULL) { + for (uint8_t i = 0; i < indentation - 1; i++) { fputs(" | ", stdout); + } printf("%s/\n", folderName); } struct dirent* entry; - while((entry = readdir(dir)) != NULL) - { - if(entry->d_name[0] == '.') // skip hidden files + while ((entry = readdir(dir)) != NULL) { + if (entry->d_name[0] == '.') { // skip hidden files continue; + } bool isDir = false; #if !defined(__sun) && !defined(__HAIKU__) - if(entry->d_type != DT_UNKNOWN && entry->d_type != DT_LNK) + if (entry->d_type != DT_UNKNOWN && entry->d_type != DT_LNK) { isDir = entry->d_type == DT_DIR; - else + } else #endif { struct stat stbuf; - if (fstatat(dfd, entry->d_name, &stbuf, 0) < 0) + if (fstatat(dfd, entry->d_name, &stbuf, 0) < 0) { isDir = false; - else + } else { isDir = S_ISDIR(stbuf.st_mode); + } } - if (isDir) - { + if (isDir) { ffStrbufAppendS(folder, entry->d_name); ffStrbufAppendC(folder, '/'); listFilesRecursively(baseLength, folder, (uint8_t) (indentation + 1), entry->d_name, pretty); @@ -304,13 +300,11 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta continue; } - if (pretty) - { - for(uint8_t i = 0; i < indentation; i++) + if (pretty) { + for (uint8_t i = 0; i < indentation; i++) { fputs(" | ", stdout); - } - else - { + } + } else { fputs(folder->chars + baseLength, stdout); } @@ -320,23 +314,21 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta closedir(dir); } -void ffListFilesRecursively(const char* path, bool pretty) -{ +void ffListFilesRecursively(const char* path, bool pretty) { FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path); ffStrbufEnsureEndsWithC(&folder, '/'); listFilesRecursively(folder.length, &folder, 0, NULL, pretty); } -FFNativeFD ffGetNullFD(void) -{ +FFNativeFD ffGetNullFD(void) { static FFNativeFD hNullFile = -1; - if (hNullFile != -1) + if (hNullFile != -1) { return hNullFile; + } hNullFile = open("/dev/null", O_WRONLY | O_CLOEXEC); return hNullFile; } -bool ffRemoveFile(const char* fileName) -{ +bool ffRemoveFile(const char* fileName) { return unlink(fileName) == 0; } diff --git a/src/common/impl/io_windows.c b/src/common/impl/io_windows.c index 3ca229c90..9b6ef383e 100644 --- a/src/common/impl/io_windows.c +++ b/src/common/impl/io_windows.c @@ -6,15 +6,13 @@ #include -static bool createSubfolders(wchar_t* fileName) -{ +static bool createSubfolders(wchar_t* fileName) { HANDLE hRoot = ffGetPeb()->ProcessParameters->CurrentDirectory.Handle; bool closeRoot = false; wchar_t* ptr = fileName; // Absolute drive path: C:\... - if (ffCharIsEnglishAlphabet((char)ptr[0]) && ptr[1] == L':' && ptr[2] == L'\\') - { + if (ffCharIsEnglishAlphabet((char) ptr[0]) && ptr[1] == L':' && ptr[2] == L'\\') { wchar_t saved = ptr[3]; ptr[3] = L'\0'; @@ -25,26 +23,27 @@ static bool createSubfolders(wchar_t* fileName) NULL, OPEN_EXISTING, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, - NULL - ); + NULL); ptr[3] = saved; - if (hRoot == INVALID_HANDLE_VALUE) + if (hRoot == INVALID_HANDLE_VALUE) { return false; + } closeRoot = true; ptr += 3; // skip "C:\" } // UNC path: \\server\share\... - else if (ptr[0] == L'\\' && ptr[1] == L'\\') - { + else if (ptr[0] == L'\\' && ptr[1] == L'\\') { wchar_t* serverEnd = wcschr(ptr + 2, L'\\'); - if (serverEnd == NULL) + if (serverEnd == NULL) { return false; + } wchar_t* shareEnd = wcschr(serverEnd + 1, L'\\'); - if (shareEnd == NULL) + if (shareEnd == NULL) { return true; // no parent subfolder exists before file name + } wchar_t saved = *shareEnd; *shareEnd = L'\0'; @@ -56,21 +55,20 @@ static bool createSubfolders(wchar_t* fileName) NULL, OPEN_EXISTING, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, - NULL - ); + NULL); *shareEnd = saved; - if (hRoot == INVALID_HANDLE_VALUE) + if (hRoot == INVALID_HANDLE_VALUE) { return false; + } closeRoot = true; ptr = shareEnd + 1; // first component under share } // Rooted path on current drive: \foo\bar - else if (ptr[0] == L'\\') - { + else if (ptr[0] == L'\\') { UNICODE_STRING* dosPath = &ffGetPeb()->ProcessParameters->CurrentDirectory.DosPath; - wchar_t driveRoot[] = { dosPath->Buffer[0], L':', L'\\', L'\0' }; + wchar_t driveRoot[] = {dosPath->Buffer[0], L':', L'\\', L'\0'}; hRoot = CreateFileW( driveRoot, FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE, @@ -78,23 +76,22 @@ static bool createSubfolders(wchar_t* fileName) NULL, OPEN_EXISTING, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, - NULL - ); - if (hRoot == INVALID_HANDLE_VALUE) + NULL); + if (hRoot == INVALID_HANDLE_VALUE) { return false; + } closeRoot = true; ptr++; // skip leading '\' } - while (true) - { + while (true) { wchar_t* token = wcschr(ptr, L'\\'); - if (token == NULL) + if (token == NULL) { break; + } // Skip empty path segments caused by duplicated '\' - if (token == ptr) - { + if (token == ptr) { ptr = token + 1; continue; } @@ -110,8 +107,8 @@ static bool createSubfolders(wchar_t* fileName) .RootDirectory = hRoot, .ObjectName = &(UNICODE_STRING) { .Buffer = ptr, - .Length = (USHORT)((USHORT)(token - ptr) * sizeof(wchar_t)), - .MaximumLength = (USHORT)((USHORT)(token - ptr) * sizeof(wchar_t)), + .Length = (USHORT) ((USHORT) (token - ptr) * sizeof(wchar_t)), + .MaximumLength = (USHORT) ((USHORT) (token - ptr) * sizeof(wchar_t)), }, .Attributes = OBJ_CASE_INSENSITIVE, }, @@ -122,155 +119,153 @@ static bool createSubfolders(wchar_t* fileName) FILE_OPEN_IF, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, - 0 - ); + 0); - if (!NT_SUCCESS(status)) - { - if (closeRoot && hRoot != INVALID_HANDLE_VALUE) + if (!NT_SUCCESS(status)) { + if (closeRoot && hRoot != INVALID_HANDLE_VALUE) { NtClose(hRoot); + } return false; } - if (closeRoot && hRoot != INVALID_HANDLE_VALUE) + if (closeRoot && hRoot != INVALID_HANDLE_VALUE) { NtClose(hRoot); + } hRoot = hNew; closeRoot = true; ptr = token + 1; } - if (closeRoot && hRoot != INVALID_HANDLE_VALUE) + if (closeRoot && hRoot != INVALID_HANDLE_VALUE) { NtClose(hRoot); + } return true; } -bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) -{ +bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) { wchar_t fileNameW[MAX_PATH]; ULONG len = 0; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &len, fileName, (ULONG)strlen(fileName) + 1))) + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &len, fileName, (ULONG) strlen(fileName) + 1))) { return false; + } - for (ULONG i = 0; i < len / sizeof(wchar_t); ++i) - { - if (fileNameW[i] == L'/') + for (ULONG i = 0; i < len / sizeof(wchar_t); ++i) { + if (fileNameW[i] == L'/') { fileNameW[i] = L'\\'; + } } HANDLE FF_AUTO_CLOSE_FD handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (handle == INVALID_HANDLE_VALUE) - { - if (GetLastError() == ERROR_PATH_NOT_FOUND) - { - if (!createSubfolders(fileNameW)) + if (handle == INVALID_HANDLE_VALUE) { + if (GetLastError() == ERROR_PATH_NOT_FOUND) { + if (!createSubfolders(fileNameW)) { return false; + } handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (handle == INVALID_HANDLE_VALUE) + if (handle == INVALID_HANDLE_VALUE) { return false; - } - else + } + } else { return false; + } } DWORD written; - return !!WriteFile(handle, data, (DWORD)dataSize, &written, NULL); + return !!WriteFile(handle, data, (DWORD) dataSize, &written, NULL); } -static inline void readWithLength(HANDLE handle, FFstrbuf* buffer, uint32_t length) -{ +static inline void readWithLength(HANDLE handle, FFstrbuf* buffer, uint32_t length) { ffStrbufEnsureFree(buffer, length); DWORD bytesRead = 0; - while( + while ( length > 0 && ReadFile(handle, buffer->chars + buffer->length, length, &bytesRead, NULL) != FALSE && - bytesRead > 0 - ) { + bytesRead > 0) { buffer->length += (uint32_t) bytesRead; length -= (uint32_t) bytesRead; } } -static inline void readUntilEOF(HANDLE handle, FFstrbuf* buffer) -{ +static inline void readUntilEOF(HANDLE handle, FFstrbuf* buffer) { ffStrbufEnsureFree(buffer, 31); uint32_t available = ffStrbufGetFree(buffer); DWORD bytesRead = 0; - while( + while ( ReadFile(handle, buffer->chars + buffer->length, available, &bytesRead, NULL) != FALSE && - bytesRead > 0 - ) { + bytesRead > 0) { buffer->length += (uint32_t) bytesRead; - if((uint32_t) bytesRead == available) + if ((uint32_t) bytesRead == available) { ffStrbufEnsureFree(buffer, buffer->allocated - 1); // Doubles capacity every round. -1 for the null byte. + } available = ffStrbufGetFree(buffer); } } -bool ffAppendFDBuffer(HANDLE handle, FFstrbuf* buffer) -{ +bool ffAppendFDBuffer(HANDLE handle, FFstrbuf* buffer) { FILE_STANDARD_INFORMATION fileInfo; IO_STATUS_BLOCK iosb; - if(!NT_SUCCESS(NtQueryInformationFile(handle, &iosb, &fileInfo, sizeof(fileInfo), FileStandardInformation))) + if (!NT_SUCCESS(NtQueryInformationFile(handle, &iosb, &fileInfo, sizeof(fileInfo), FileStandardInformation))) { fileInfo.EndOfFile.QuadPart = 0; + } - if (fileInfo.EndOfFile.QuadPart > 0) - readWithLength(handle, buffer, (uint32_t)fileInfo.EndOfFile.QuadPart); - else + if (fileInfo.EndOfFile.QuadPart > 0) { + readWithLength(handle, buffer, (uint32_t) fileInfo.EndOfFile.QuadPart); + } else { readUntilEOF(handle, buffer); + } buffer->chars[buffer->length] = '\0'; return buffer->length > 0; } -HANDLE openatW(HANDLE dfd, const wchar_t* fileName, uint16_t fileNameLen, bool directory) -{ +HANDLE openatW(HANDLE dfd, const wchar_t* fileName, uint16_t fileNameLen, bool directory) { assert(fileNameLen <= 0x7FFF); HANDLE hFile; IO_STATUS_BLOCK iosb = {}; - if(!NT_SUCCESS(NtOpenFile(&hFile, - (directory ? FILE_LIST_DIRECTORY | FILE_TRAVERSE : FILE_READ_DATA | FILE_READ_EA) | FILE_READ_ATTRIBUTES | SYNCHRONIZE, &(OBJECT_ATTRIBUTES) { - .Length = sizeof(OBJECT_ATTRIBUTES), - .RootDirectory = dfd, - .ObjectName = &(UNICODE_STRING) { - .Buffer = (PWSTR) fileName, - .Length = fileNameLen * (USHORT) sizeof(wchar_t), - .MaximumLength = (fileNameLen + 1) * (USHORT) sizeof(wchar_t), + if (!NT_SUCCESS(NtOpenFile(&hFile, + (directory ? FILE_LIST_DIRECTORY | FILE_TRAVERSE : FILE_READ_DATA | FILE_READ_EA) | FILE_READ_ATTRIBUTES | SYNCHRONIZE, + &(OBJECT_ATTRIBUTES) { + .Length = sizeof(OBJECT_ATTRIBUTES), + .RootDirectory = dfd, + .ObjectName = &(UNICODE_STRING) { + .Buffer = (PWSTR) fileName, + .Length = fileNameLen * (USHORT) sizeof(wchar_t), + .MaximumLength = (fileNameLen + 1) * (USHORT) sizeof(wchar_t), + }, + .Attributes = OBJ_CASE_INSENSITIVE, }, - .Attributes = OBJ_CASE_INSENSITIVE, - }, - &iosb, - FILE_SHARE_READ | (directory ? FILE_SHARE_WRITE | FILE_SHARE_DELETE : 0), - FILE_SYNCHRONOUS_IO_NONALERT | (directory ? FILE_DIRECTORY_FILE : FILE_NON_DIRECTORY_FILE) - ))) + &iosb, + FILE_SHARE_READ | (directory ? FILE_SHARE_WRITE | FILE_SHARE_DELETE : 0), + FILE_SYNCHRONOUS_IO_NONALERT | (directory ? FILE_DIRECTORY_FILE : FILE_NON_DIRECTORY_FILE)))) { return INVALID_HANDLE_VALUE; + } return hFile; } -HANDLE openat(HANDLE dfd, const char* fileName, int oflag) -{ +HANDLE openat(HANDLE dfd, const char* fileName, int oflag) { wchar_t fileNameW[MAX_PATH]; ULONG len; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &len, fileName, (ULONG)strlen(fileName) + 1))) + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &len, fileName, (ULONG) strlen(fileName) + 1))) { return INVALID_HANDLE_VALUE; + } // Implies `fileNameW[len] = L'\0';` and `len` includes the null terminator len /= sizeof(wchar_t); // convert from bytes to characters - for (uint32_t i = 0; i < len - 1; ++i) - { - if (fileNameW[i] == L'/') + for (uint32_t i = 0; i < len - 1; ++i) { + if (fileNameW[i] == L'/') { fileNameW[i] = L'\\'; + } } - return openatW(dfd, fileNameW, (uint16_t)(len - 1), !!(oflag & O_DIRECTORY)); + return openatW(dfd, fileNameW, (uint16_t) (len - 1), !!(oflag & O_DIRECTORY)); } -bool ffPathExpandEnv(const char* in, FFstrbuf* out) -{ +bool ffPathExpandEnv(const char* in, FFstrbuf* out) { if (in[0] == '~') { if ((in[1] == '/' || in[1] == '\\' || in[1] == '\0') && !ffStrContainsC(in, '%')) { ffStrbufSet(out, &instance.state.platform.homeDir); @@ -281,24 +276,26 @@ bool ffPathExpandEnv(const char* in, FFstrbuf* out) wchar_t pathInW[MAX_PATH], pathOutW[MAX_PATH]; ULONG len = (ULONG) strlen(in); - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(pathInW, (ULONG) sizeof(pathInW), &len, in, len))) + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(pathInW, (ULONG) sizeof(pathInW), &len, in, len))) { return false; + } len /= sizeof(wchar_t); // convert from bytes to characters size_t outLen; // in characters, including null terminator - if (!NT_SUCCESS(RtlExpandEnvironmentStrings(NULL, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) + if (!NT_SUCCESS(RtlExpandEnvironmentStrings(NULL, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) { return false; + } ffStrbufSetNWS(out, (uint32_t) outLen - 1, pathOutW); return true; } -bool ffSuppressIO(bool suppress) -{ - #ifndef NDEBUG - if (instance.config.display.debugMode) +bool ffSuppressIO(bool suppress) { +#ifndef NDEBUG + if (instance.config.display.debugMode) { return false; - #endif + } +#endif static bool init = false; static HANDLE hOrigOut = INVALID_HANDLE_VALUE; @@ -308,10 +305,10 @@ bool ffSuppressIO(bool suppress) static int fOrigErr = -1; static int fNullFile = -1; - if (!init) - { - if(!suppress) + if (!init) { + if (!suppress) { return true; + } hOrigOut = GetStdHandle(STD_OUTPUT_HANDLE); hOrigErr = GetStdHandle(STD_ERROR_HANDLE); @@ -321,8 +318,9 @@ bool ffSuppressIO(bool suppress) init = true; } - if (hNullFile == INVALID_HANDLE_VALUE || fNullFile == -1) + if (hNullFile == INVALID_HANDLE_VALUE || fNullFile == -1) { return false; + } fflush(stdout); fflush(stderr); @@ -335,14 +333,13 @@ bool ffSuppressIO(bool suppress) return true; } -void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) -{ +void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) { uint32_t folderLength = folder->length; - if(pretty && folderName != NULL) - { - for(uint8_t i = 0; i < indentation - 1; i++) + if (pretty && folderName != NULL) { + for (uint8_t i = 0; i < indentation - 1; i++) { fputs(" | ", stdout); + } printf("%s/\n", folderName); } @@ -350,15 +347,15 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta WIN32_FIND_DATAA entry; HANDLE hFind = FindFirstFileA(folder->chars, &entry); ffStrbufTrimRight(folder, '*'); - if(hFind == INVALID_HANDLE_VALUE) + if (hFind == INVALID_HANDLE_VALUE) { return; + } - do - { - if (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - { - if(ffStrEquals(entry.cFileName, ".") || ffStrEquals(entry.cFileName, "..")) + do { + if (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + if (ffStrEquals(entry.cFileName, ".") || ffStrEquals(entry.cFileName, "..")) { continue; + } ffStrbufSubstrBefore(folder, folderLength); ffStrbufAppendS(folder, entry.cFileName); @@ -368,13 +365,11 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta continue; } - if (pretty) - { - for(uint8_t i = 0; i < indentation; i++) + if (pretty) { + for (uint8_t i = 0; i < indentation; i++) { fputs(" | ", stdout); - } - else - { + } + } else { fputs(folder->chars + baseLength, stdout); } @@ -383,20 +378,17 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta FindClose(hFind); } -void ffListFilesRecursively(const char* path, bool pretty) -{ +void ffListFilesRecursively(const char* path, bool pretty) { FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path); ffStrbufEnsureEndsWithC(&folder, '/'); listFilesRecursively(folder.length, &folder, 0, NULL, pretty); } -const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) -{ +const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) { HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); FF_AUTO_CLOSE_FD HANDLE hConin = INVALID_HANDLE_VALUE; DWORD inputMode; - if (!GetConsoleMode(hInput, &inputMode)) - { + if (!GetConsoleMode(hInput, &inputMode)) { hConin = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL); hInput = hConin; } @@ -409,18 +401,15 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); FF_AUTO_CLOSE_FD HANDLE hConout = INVALID_HANDLE_VALUE; DWORD outputMode; - if (!GetConsoleMode(hOutput, &outputMode)) - { + if (!GetConsoleMode(hOutput, &outputMode)) { hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL); hOutput = hConout; } WriteFile(hOutput, request, (DWORD) strlen(request), &bytes, NULL); } - while (true) - { - if (NtWaitForSingleObject(hInput, FALSE, &(LARGE_INTEGER) { .QuadPart = (int64_t) FF_IO_TERM_RESP_WAIT_MS * -10000 }) != STATUS_WAIT_0) - { + while (true) { + if (NtWaitForSingleObject(hInput, FALSE, &(LARGE_INTEGER) {.QuadPart = (int64_t) FF_IO_TERM_RESP_WAIT_MS * -10000}) != STATUS_WAIT_0) { SetConsoleMode(hInput, inputMode); return "NtWaitForSingleObject() failed or timeout"; } @@ -428,17 +417,18 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* // Ignore all unexpected input events INPUT_RECORD record; DWORD len = 0; - if (!PeekConsoleInputW(hInput, &record, 1, &len)) + if (!PeekConsoleInputW(hInput, &record, 1, &len)) { break; + } if ( record.EventType == KEY_EVENT && record.Event.KeyEvent.uChar.UnicodeChar != L'\r' && - record.Event.KeyEvent.uChar.UnicodeChar != L'\n' - ) + record.Event.KeyEvent.uChar.UnicodeChar != L'\n') { break; - else + } else { ReadConsoleInputW(hInput, &record, 1, &len); + } } va_list args; @@ -447,11 +437,9 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* char buffer[1024]; uint32_t bytesRead = 0; - while (true) - { + while (true) { DWORD bytes = 0; - if (!ReadFile(hInput, buffer, sizeof(buffer) - 1, &bytes, NULL) || bytes == 0) - { + if (!ReadFile(hInput, buffer, sizeof(buffer) - 1, &bytes, NULL) || bytes == 0) { va_end(args); return "ReadFile() failed"; } @@ -464,13 +452,13 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* int ret = vsscanf(buffer, format, cargs); va_end(cargs); - if (ret <= 0) - { + if (ret <= 0) { va_end(args); return "vsscanf(buffer, format, args) failed"; } - if (ret >= nParams) + if (ret >= nParams) { break; + } } SetConsoleMode(hInput, inputMode); @@ -480,11 +468,11 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* return NULL; } -FFNativeFD ffGetNullFD(void) -{ +FFNativeFD ffGetNullFD(void) { static FFNativeFD hNullFile = INVALID_HANDLE_VALUE; - if (hNullFile != INVALID_HANDLE_VALUE) + if (hNullFile != INVALID_HANDLE_VALUE) { return hNullFile; + } hNullFile = CreateFileW( L"NUL", GENERIC_READ | GENERIC_WRITE, @@ -492,7 +480,7 @@ FFNativeFD ffGetNullFD(void) 0, OPEN_EXISTING, 0, - &(SECURITY_ATTRIBUTES){ + &(SECURITY_ATTRIBUTES) { .nLength = sizeof(SECURITY_ATTRIBUTES), .lpSecurityDescriptor = NULL, .bInheritHandle = TRUE, @@ -500,7 +488,6 @@ FFNativeFD ffGetNullFD(void) return hNullFile; } -bool ffRemoveFile(const char* fileName) -{ +bool ffRemoveFile(const char* fileName) { return DeleteFileA(fileName) != FALSE; } diff --git a/src/common/impl/jsonconfig.c b/src/common/impl/jsonconfig.c index 5e5effb08..5071b8801 100644 --- a/src/common/impl/jsonconfig.c +++ b/src/common/impl/jsonconfig.c @@ -12,135 +12,117 @@ #include #include -bool ffJsonConfigParseModuleArgs(yyjson_val* key, yyjson_val* val, FFModuleArgs* moduleArgs) -{ - if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) +bool ffJsonConfigParseModuleArgs(yyjson_val* key, yyjson_val* val, FFModuleArgs* moduleArgs) { + if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) { return true; + } - if (unsafe_yyjson_equals_str(key, "key")) - { + if (unsafe_yyjson_equals_str(key, "key")) { ffStrbufSetJsonVal(&moduleArgs->key, val); return true; - } - else if (unsafe_yyjson_equals_str(key, "format")) - { + } else if (unsafe_yyjson_equals_str(key, "format")) { ffStrbufSetJsonVal(&moduleArgs->outputFormat, val); return true; - } - else if (unsafe_yyjson_equals_str(key, "outputColor")) - { + } else if (unsafe_yyjson_equals_str(key, "outputColor")) { ffOptionParseColor(yyjson_get_str(val), &moduleArgs->outputColor); return true; - } - else if (unsafe_yyjson_equals_str(key, "keyColor")) - { + } else if (unsafe_yyjson_equals_str(key, "keyColor")) { ffOptionParseColor(yyjson_get_str(val), &moduleArgs->keyColor); return true; - } - else if (unsafe_yyjson_equals_str(key, "keyWidth")) - { + } else if (unsafe_yyjson_equals_str(key, "keyWidth")) { moduleArgs->keyWidth = (uint32_t) yyjson_get_uint(val); return true; - } - else if (unsafe_yyjson_equals_str(key, "keyIcon")) - { + } else if (unsafe_yyjson_equals_str(key, "keyIcon")) { ffStrbufSetJsonVal(&moduleArgs->keyIcon, val); return true; } return false; } -void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* moduleArgs) -{ - if (moduleArgs->key.length > 0) +void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* moduleArgs) { + if (moduleArgs->key.length > 0) { yyjson_mut_obj_add_strbuf(doc, module, "key", &moduleArgs->key); - if (moduleArgs->outputFormat.length > 0) + } + if (moduleArgs->outputFormat.length > 0) { yyjson_mut_obj_add_strbuf(doc, module, "format", &moduleArgs->outputFormat); - if (moduleArgs->outputColor.length > 0) + } + if (moduleArgs->outputColor.length > 0) { yyjson_mut_obj_add_strbuf(doc, module, "outputColor", &moduleArgs->outputColor); - if (moduleArgs->keyColor.length > 0) + } + if (moduleArgs->keyColor.length > 0) { yyjson_mut_obj_add_strbuf(doc, module, "keyColor", &moduleArgs->keyColor); - if (moduleArgs->keyWidth > 0) + } + if (moduleArgs->keyWidth > 0) { yyjson_mut_obj_add_uint(doc, module, "keyWidth", moduleArgs->keyWidth); - if (moduleArgs->keyIcon.length > 0) + } + if (moduleArgs->keyIcon.length > 0) { yyjson_mut_obj_add_strbuf(doc, module, "keyIcon", &moduleArgs->keyIcon); + } } -const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair pairs[]) -{ - if (yyjson_is_int(val)) - { +const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair pairs[]) { + if (yyjson_is_int(val)) { int intVal = yyjson_get_int(val); - for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) - { - if (intVal == pPair->value) - { + for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) { + if (intVal == pPair->value) { *result = pPair->value; return NULL; } } return "Invalid enum integer"; - } - else if (yyjson_is_str(val)) - { + } else if (yyjson_is_str(val)) { const char* strVal = yyjson_get_str(val); - for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) - { - if (ffStrEqualsIgnCase(strVal, pPair->key)) - { + for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) { + if (ffStrEqualsIgnCase(strVal, pPair->key)) { *result = pPair->value; return NULL; } } return "Invalid enum string"; - } - else + } else { return "Invalid enum value type; must be a string or integer"; + } } -static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_mut_doc* jsonDoc) -{ - if(!ffCharIsEnglishAlphabet(type[0])) return false; +static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_mut_doc* jsonDoc) { + if (!ffCharIsEnglishAlphabet(type[0])) { + return false; + } - for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(type[0]) - 'A']; *modules; ++modules) - { + for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(type[0]) - 'A']; *modules; ++modules) { FFModuleBaseInfo* baseInfo = *modules; - if (ffStrEqualsIgnCase(type, baseInfo->name)) - { + if (ffStrEqualsIgnCase(type, baseInfo->name)) { uint8_t optionBuf[FF_OPTION_MAX_SIZE]; baseInfo->initOptions(optionBuf); - if (jsonVal) baseInfo->parseJsonObject(optionBuf, jsonVal); + if (jsonVal) { + baseInfo->parseJsonObject(optionBuf, jsonVal); + } bool succeeded; - if (jsonDoc) - { + 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) + if (baseInfo->generateJsonResult) { succeeded = baseInfo->generateJsonResult(optionBuf, jsonDoc, module); - else - { + } else { yyjson_mut_obj_add_str(jsonDoc, module, "error", "Unsupported for JSON format"); succeeded = false; } - } - else + } else { succeeded = baseInfo->printModule(optionBuf); + } baseInfo->destroyOptions(optionBuf); return succeeded; } } - if (jsonDoc) - { + 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 - { + } else { FFModuleArgs moduleArgs; ffOptionInitModuleArg(&moduleArgs, ""); ffPrintError(type, 0, &moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown module type"); @@ -149,61 +131,71 @@ static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_ return false; } -static void prepareModuleJsonObject(const char* type, yyjson_val* module) -{ - switch (type[0]) - { - case 'b': case 'B': { - if (ffStrEqualsIgnCase(type, FF_CPUUSAGE_MODULE_NAME)) +static void prepareModuleJsonObject(const char* type, yyjson_val* module) { + switch (type[0]) { + case 'b': + case 'B': { + if (ffStrEqualsIgnCase(type, FF_CPUUSAGE_MODULE_NAME)) { ffPrepareCPUUsage(); + } break; } - case 'c': case 'C': { - if (ffStrEqualsIgnCase(type, FF_COMMAND_MODULE_NAME)) - { + case 'c': + case 'C': { + if (ffStrEqualsIgnCase(type, FF_COMMAND_MODULE_NAME)) { __attribute__((__cleanup__(ffDestroyCommandOptions))) FFCommandOptions options; ffInitCommandOptions(&options); - if (module) ffCommandModuleInfo.parseJsonObject(&options, module); + if (module) { + ffCommandModuleInfo.parseJsonObject(&options, module); + } ffPrepareCommand(&options); } break; } - case 'd': case 'D': { - if (ffStrEqualsIgnCase(type, FF_DISKIO_MODULE_NAME)) - { + case 'd': + case 'D': { + if (ffStrEqualsIgnCase(type, FF_DISKIO_MODULE_NAME)) { __attribute__((__cleanup__(ffDestroyDiskIOOptions))) FFDiskIOOptions options; ffInitDiskIOOptions(&options); - if (module) ffDiskIOModuleInfo.parseJsonObject(&options, module); + if (module) { + ffDiskIOModuleInfo.parseJsonObject(&options, module); + } ffPrepareDiskIO(&options); } break; } - case 'n': case 'N': { - if (ffStrEqualsIgnCase(type, FF_NETIO_MODULE_NAME)) - { + case 'n': + case 'N': { + if (ffStrEqualsIgnCase(type, FF_NETIO_MODULE_NAME)) { __attribute__((__cleanup__(ffDestroyNetIOOptions))) FFNetIOOptions options; ffInitNetIOOptions(&options); - if (module) ffNetIOModuleInfo.parseJsonObject(&options, module); + if (module) { + ffNetIOModuleInfo.parseJsonObject(&options, module); + } ffPrepareNetIO(&options); } break; } - case 'p': case 'P': { - if (ffStrEqualsIgnCase(type, FF_PUBLICIP_MODULE_NAME)) - { + case 'p': + case 'P': { + if (ffStrEqualsIgnCase(type, FF_PUBLICIP_MODULE_NAME)) { __attribute__((__cleanup__(ffDestroyPublicIpOptions))) FFPublicIPOptions options; ffInitPublicIpOptions(&options); - if (module) ffPublicIPModuleInfo.parseJsonObject(&options, module); + if (module) { + ffPublicIPModuleInfo.parseJsonObject(&options, module); + } ffPreparePublicIp(&options); } break; } - case 'w': case 'W': { - if (ffStrEqualsIgnCase(type, FF_WEATHER_MODULE_NAME)) - { + case 'w': + case 'W': { + if (ffStrEqualsIgnCase(type, FF_WEATHER_MODULE_NAME)) { __attribute__((__cleanup__(ffDestroyWeatherOptions))) FFWeatherOptions options; ffInitWeatherOptions(&options); - if (module) ffWeatherModuleInfo.parseJsonObject(&options, module); + if (module) { + ffWeatherModuleInfo.parseJsonObject(&options, module); + } ffPrepareWeather(&options); } break; @@ -211,141 +203,154 @@ static void prepareModuleJsonObject(const char* type, yyjson_val* module) } } -static bool matchesJsonArray(const char* str, yyjson_val* val) -{ +static bool matchesJsonArray(const char* str, yyjson_val* val) { assert(val); - if (unsafe_yyjson_is_str(val)) + if (unsafe_yyjson_is_str(val)) { return ffStrEqualsIgnCase(str, unsafe_yyjson_get_str(val)); + } - if (!unsafe_yyjson_is_arr(val)) return false; + if (!unsafe_yyjson_is_arr(val)) { + return false; + } size_t idx, max; yyjson_val* item; - yyjson_arr_foreach(val, idx, max, item) - { - if (yyjson_is_str(item) && ffStrEqualsIgnCase(str, unsafe_yyjson_get_str(item))) + yyjson_arr_foreach (val, idx, max, item) { + if (yyjson_is_str(item) && ffStrEqualsIgnCase(str, unsafe_yyjson_get_str(item))) { return true; + } } return false; } -static const char* printJsonConfig(FFdata* data, bool prepare) -{ +static const char* printJsonConfig(FFdata* data, bool prepare) { yyjson_mut_doc* jsonDoc = data->resultDoc; yyjson_val* const root = yyjson_doc_get_root(data->configDoc); assert(root); - if (!yyjson_is_obj(root)) + if (!yyjson_is_obj(root)) { return "Invalid JSON config format. Root value must be an object"; + } yyjson_val* modules = yyjson_obj_get(root, "modules"); - if (!modules) return NULL; - if (!yyjson_is_arr(modules)) return "Property 'modules' must be an array of strings or objects"; + 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; - yyjson_arr_foreach(modules, idx, max, item) - { + yyjson_arr_foreach (modules, idx, max, item) { double ms = 0; - if(!prepare && thres >= 0) + if (!prepare && thres >= 0) { ms = ffTimeGetTick(); + } yyjson_val* module = item; const char* type = yyjson_get_str(module); - if (type) + if (type) { module = NULL; - else if (yyjson_is_obj(module)) - { + } else if (yyjson_is_obj(module)) { yyjson_val* conditions = yyjson_obj_get(module, "condition"); - if (conditions) - { - if (!yyjson_is_obj(conditions)) + if (conditions) { + if (!yyjson_is_obj(conditions)) { return "Property 'conditions' must be an object"; + } yyjson_val* system = yyjson_obj_get(conditions, "system"); - if (system && !matchesJsonArray(ffVersionResult.sysName, system)) + if (system && !matchesJsonArray(ffVersionResult.sysName, system)) { continue; + } system = yyjson_obj_get(conditions, "!system"); - if (system && matchesJsonArray(ffVersionResult.sysName, system)) + if (system && matchesJsonArray(ffVersionResult.sysName, system)) { continue; + } yyjson_val* arch = yyjson_obj_get(conditions, "arch"); - if (arch && !matchesJsonArray(ffVersionResult.architecture, arch)) + if (arch && !matchesJsonArray(ffVersionResult.architecture, arch)) { continue; + } arch = yyjson_obj_get(conditions, "!arch"); - if (arch && matchesJsonArray(ffVersionResult.architecture, 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)) + 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)) + } + if (succeeded != unsafe_yyjson_get_bool(previousSucceeded)) { continue; + } } } type = yyjson_get_str(yyjson_obj_get(module, "type")); - if (!type) return "module object must contain a \"type\" key ( case sensitive )"; - if (yyjson_obj_size(module) == 1) // contains only Property type + if (!type) { + return "module object must contain a \"type\" key ( case sensitive )"; + } + if (yyjson_obj_size(module) == 1) { // contains only Property type module = NULL; - } - else + } + } else { return "modules must be an array of strings or objects"; + } - if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, type, ':')) + if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, type, ':')) { continue; + } - if(prepare) + if (prepare) { prepareModuleJsonObject(type, module); - else + } else { succeeded = parseModuleJsonObject(type, module, jsonDoc); + } - if(!prepare && thres >= 0) - { + if (!prepare && thres >= 0) { ms = ffTimeGetTick() - ms; - if (jsonDoc) - { + if (jsonDoc) { yyjson_mut_val* moduleJson = yyjson_mut_arr_get_last(jsonDoc->root); yyjson_mut_obj_add_real(jsonDoc, moduleJson, "stat", ms); - } - else - { + } else { char str[64]; int len = snprintf(str, sizeof str, "%.3fms", ms); - if (thres > 0) - snprintf(str, sizeof str, "\e[%sm%.3fms\e[m", (ms <= thres ? FF_COLOR_FG_GREEN : ms <= 2 * thres ? FF_COLOR_FG_YELLOW : FF_COLOR_FG_RED), ms); + if (thres > 0) { + snprintf(str, sizeof str, "\e[%sm%.3fms\e[m", (ms <= thres ? FF_COLOR_FG_GREEN : ms <= 2 * thres ? FF_COLOR_FG_YELLOW + : FF_COLOR_FG_RED), + ms); + } printf("\e7\e[1A\e[9999999C\e[%dD%s\e8", len, str); // Save; Up 1; Right 9999999; Left ; Print ; Load } } - #if defined(_WIN32) - if (!instance.config.display.noBuffer && !jsonDoc) fflush(stdout); - #endif +#if defined(_WIN32) + if (!instance.config.display.noBuffer && !jsonDoc) { + fflush(stdout); + } +#endif } return NULL; } -void ffPrintJsonConfig(FFdata* data, bool prepare) -{ +void ffPrintJsonConfig(FFdata* data, bool prepare) { yyjson_mut_doc* jsonDoc = data->resultDoc; const char* error = printJsonConfig(data, prepare); - if (error) - { - if (jsonDoc) - { + if (error) { + if (jsonDoc) { yyjson_mut_val* obj = yyjson_mut_obj(jsonDoc); yyjson_mut_obj_add_str(jsonDoc, obj, "error", error); yyjson_mut_doc_set_root(jsonDoc, obj); - } - else + } else { ffPrintError("JsonConfig", 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "%s", error); + } } } diff --git a/src/common/impl/kmod_apple.c b/src/common/impl/kmod_apple.c index eb28faee6..82edc4946 100644 --- a/src/common/impl/kmod_apple.c +++ b/src/common/impl/kmod_apple.c @@ -3,8 +3,7 @@ #include #include -bool ffKmodLoaded(const char* modName) -{ +bool ffKmodLoaded(const char* modName) { FF_CFTYPE_AUTO_RELEASE CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, modName, kCFStringEncodingUTF8); FF_CFTYPE_AUTO_RELEASE CFArrayRef identifiers = CFArrayCreate(kCFAllocatorDefault, (const void**) &name, 1, &kCFTypeArrayCallBacks); FF_CFTYPE_AUTO_RELEASE CFArrayRef keys = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL); diff --git a/src/common/impl/kmod_bsd.c b/src/common/impl/kmod_bsd.c index 99ebafda7..996d4abbd 100644 --- a/src/common/impl/kmod_bsd.c +++ b/src/common/impl/kmod_bsd.c @@ -2,7 +2,6 @@ #include #include -bool ffKmodLoaded(const char* modName) -{ +bool ffKmodLoaded(const char* modName) { return modfind(modName) >= 0; } diff --git a/src/common/impl/kmod_linux.c b/src/common/impl/kmod_linux.c index 940093b5d..204ab3585 100644 --- a/src/common/impl/kmod_linux.c +++ b/src/common/impl/kmod_linux.c @@ -1,19 +1,21 @@ #include "common/kmod.h" #include "common/io.h" -bool ffKmodLoaded(const char* modName) -{ +bool ffKmodLoaded(const char* modName) { static FFstrbuf modules; - if (modules.chars == NULL) - { + if (modules.chars == NULL) { ffStrbufInitS(&modules, "\n"); ffAppendFileBuffer("/proc/modules", &modules); } - if (modules.length == 0) return false; + if (modules.length == 0) { + return false; + } uint32_t len = (uint32_t) strlen(modName); - if (len > 250) return false; + if (len > 250) { + return false; + } char temp[256]; temp[0] = '\n'; diff --git a/src/common/impl/kmod_nbsd.c b/src/common/impl/kmod_nbsd.c index f4e78eed8..e96b0ae0d 100644 --- a/src/common/impl/kmod_nbsd.c +++ b/src/common/impl/kmod_nbsd.c @@ -4,39 +4,36 @@ #include #include -typedef struct __attribute__((__packed__)) FFNbsdModList -{ +typedef struct __attribute__((__packed__)) FFNbsdModList { int len; modstat_t mods[]; } FFNbsdModList; -bool ffKmodLoaded(const char* modName) -{ +bool ffKmodLoaded(const char* modName) { static FFNbsdModList* list = NULL; - if (list == NULL) - { + if (list == NULL) { struct iovec iov = {}; - for (size_t len = 8192;; len = iov.iov_len) - { + for (size_t len = 8192;; len = iov.iov_len) { iov.iov_len = len; iov.iov_base = realloc(iov.iov_base, len); - if (modctl(MODCTL_STAT, &iov) < 0) - { + if (modctl(MODCTL_STAT, &iov) < 0) { free(iov.iov_base); return true; // ignore errors } - if (len >= iov.iov_len) break; + if (len >= iov.iov_len) { + break; + } } list = (FFNbsdModList*) iov.iov_base; } - for (int i = 0; i < list->len; i++) - { - if (ffStrEquals(list->mods[i].ms_name, modName)) + for (int i = 0; i < list->len; i++) { + if (ffStrEquals(list->mods[i].ms_name, modName)) { return true; + } } return false; diff --git a/src/common/impl/kmod_nosupport.c b/src/common/impl/kmod_nosupport.c index 1ae3b0b33..bca89ee34 100644 --- a/src/common/impl/kmod_nosupport.c +++ b/src/common/impl/kmod_nosupport.c @@ -1,6 +1,5 @@ #include "common/kmod.h" -bool ffKmodLoaded(FF_MAYBE_UNUSED const char* modName) -{ +bool ffKmodLoaded(FF_MAYBE_UNUSED const char* modName) { return true; // Don't generate kernel module related errors } diff --git a/src/common/impl/kmod_sunos.c b/src/common/impl/kmod_sunos.c index e6c403c82..de0020670 100644 --- a/src/common/impl/kmod_sunos.c +++ b/src/common/impl/kmod_sunos.c @@ -4,20 +4,19 @@ #include #include -bool ffKmodLoaded(const char* modName) -{ +bool ffKmodLoaded(const char* modName) { struct modinfo modinfo = { .mi_id = -1, .mi_nextid = -1, .mi_info = MI_INFO_ALL, }; - for (int id = -1; modctl(MODINFO, id, &modinfo) == 0; id = modinfo.mi_id) - { + for (int id = -1; modctl(MODINFO, id, &modinfo) == 0; id = modinfo.mi_id) { modinfo.mi_name[MODMAXNAMELEN - 1] = '\0'; - if (ffStrEquals(modinfo.mi_name, modName)) + if (ffStrEquals(modinfo.mi_name, modName)) { return true; + } } return !(errno == EINVAL || errno == ENOENT); diff --git a/src/common/impl/kmod_windows.c b/src/common/impl/kmod_windows.c index 3eb275760..b8db05210 100644 --- a/src/common/impl/kmod_windows.c +++ b/src/common/impl/kmod_windows.c @@ -3,24 +3,25 @@ #include "common/mallocHelper.h" #include "common/stringUtils.h" -bool ffKmodLoaded(const char* modName) -{ +bool ffKmodLoaded(const char* modName) { ULONG bufferSize = 0; NtQuerySystemInformation(SystemModuleInformation, NULL, 0, &bufferSize); - if (bufferSize == 0) + if (bufferSize == 0) { return true; // ignore errors + } FF_AUTO_FREE RTL_PROCESS_MODULES* buffer = malloc(bufferSize); - if (!NT_SUCCESS(NtQuerySystemInformation(SystemModuleInformation, buffer, bufferSize, &bufferSize))) + if (!NT_SUCCESS(NtQuerySystemInformation(SystemModuleInformation, buffer, bufferSize, &bufferSize))) { return true; // ignore errors + } - for (ULONG i = 0; i < buffer->NumberOfModules; i++) - { + for (ULONG i = 0; i < buffer->NumberOfModules; i++) { const char* name = (const char*) buffer->Modules[i].FullPathName + buffer->Modules[i].OffsetToFileName; - if (ffStrEqualsIgnCase(name, modName)) + if (ffStrEqualsIgnCase(name, modName)) { return true; + } } return false; diff --git a/src/common/impl/library.c b/src/common/impl/library.c index ee3626b45..39842f476 100644 --- a/src/common/impl/library.c +++ b/src/common/impl/library.c @@ -2,91 +2,91 @@ #include "common/library.h" #if _WIN32 -#include "common/debug.h" -#include "common/windows/nt.h" -#include -#include +# include "common/debug.h" +# include "common/windows/nt.h" +# include +# include #endif #ifndef FF_DISABLE_DLOPEN -#include +# include -//Clang doesn't define __SANITIZE_ADDRESS__ but defines __has_feature(address_sanitizer) -#if !defined(__SANITIZE_ADDRESS__) && defined(__has_feature) - #if __has_feature(address_sanitizer) - #define __SANITIZE_ADDRESS__ - #endif -#endif +// Clang doesn't define __SANITIZE_ADDRESS__ but defines __has_feature(address_sanitizer) +# if !defined(__SANITIZE_ADDRESS__) && defined(__has_feature) +# if __has_feature(address_sanitizer) +# define __SANITIZE_ADDRESS__ +# endif +# endif -#ifndef FF_DLOPEN_FLAGS - #ifdef __SANITIZE_ADDRESS__ - #define FF_DLOPEN_FLAGS RTLD_LAZY | RTLD_NODELETE - #else - #define FF_DLOPEN_FLAGS RTLD_LAZY - #endif -#endif +# ifndef FF_DLOPEN_FLAGS +# ifdef __SANITIZE_ADDRESS__ +# define FF_DLOPEN_FLAGS RTLD_LAZY | RTLD_NODELETE +# else +# define FF_DLOPEN_FLAGS RTLD_LAZY +# endif +# endif -static void* libraryLoad(const char* path, int maxVersion) -{ +static void* libraryLoad(const char* path, int maxVersion) { void* result = dlopen(path, FF_DLOPEN_FLAGS); - #ifdef _WIN32 +# ifdef _WIN32 // libX.dll.1 never exists on Windows, while libX-1.dll may exist FF_UNUSED(maxVersion) - if(result != NULL) + if (result != NULL) { return result; + } uint32_t pathLen = ffStrbufLastIndexC(&instance.state.platform.exePath, '/'); - if (pathLen == instance.state.platform.exePath.length) + if (pathLen == instance.state.platform.exePath.length) { return result; + } char absPath[MAX_PATH * 2]; strcpy(mempcpy(absPath, instance.state.platform.exePath.chars, pathLen + 1), path); return dlopen(absPath, FF_DLOPEN_FLAGS); - #else +# else - if(result != NULL || maxVersion < 0) + if (result != NULL || maxVersion < 0) { return result; + } FF_STRBUF_AUTO_DESTROY pathbuf = ffStrbufCreateA(64); ffStrbufAppendS(&pathbuf, path); ffStrbufAppendC(&pathbuf, '.'); - for(int i = maxVersion; i >= 0; --i) - { + for (int i = maxVersion; i >= 0; --i) { uint32_t originalLength = pathbuf.length; ffStrbufAppendSInt(&pathbuf, i); result = dlopen(pathbuf.chars, FF_DLOPEN_FLAGS); - if(result != NULL) + if (result != NULL) { break; + } ffStrbufSubstrBefore(&pathbuf, originalLength); } - #endif +# endif return result; } -void* ffLibraryLoad(const char* path, int maxVersion, ...) -{ +void* ffLibraryLoad(const char* path, int maxVersion, ...) { void* result = libraryLoad(path, maxVersion); - if (!result) - { + if (!result) { va_list defaultNames; va_start(defaultNames, maxVersion); - do - { + do { const char* pathRest = va_arg(defaultNames, const char*); - if(pathRest == NULL) + if (pathRest == NULL) { break; + } int maxVersionRest = va_arg(defaultNames, int); result = libraryLoad(pathRest, maxVersionRest); @@ -102,27 +102,25 @@ void* ffLibraryLoad(const char* path, int maxVersion, ...) #if _WIN32 -void* dlopen(const char* path, FF_MAYBE_UNUSED int mode) -{ +void* dlopen(const char* path, FF_MAYBE_UNUSED int mode) { wchar_t pathW[MAX_PATH + 1]; ULONG pathWBytes = 0; - NTSTATUS status = RtlUTF8ToUnicodeN(pathW, sizeof(pathW), &pathWBytes, path, (uint32_t)strlen(path) + 1); - if (!NT_SUCCESS(status)) - { + NTSTATUS status = RtlUTF8ToUnicodeN(pathW, sizeof(pathW), &pathWBytes, path, (uint32_t) strlen(path) + 1); + if (!NT_SUCCESS(status)) { FF_DEBUG("RtlUTF8ToUnicodeN failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status)); return NULL; } PVOID module = NULL; status = LdrLoadDll(NULL, NULL, &(UNICODE_STRING) { - .Length = (USHORT) pathWBytes - sizeof(wchar_t), // Exclude null terminator - .MaximumLength = (USHORT) pathWBytes, - .Buffer = pathW, - }, &module); + .Length = (USHORT) pathWBytes - sizeof(wchar_t), // Exclude null terminator + .MaximumLength = (USHORT) pathWBytes, + .Buffer = pathW, + }, + &module); - if (!NT_SUCCESS(status)) - { + if (!NT_SUCCESS(status)) { FF_DEBUG("LdrLoadDll failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status)); return NULL; } @@ -130,47 +128,44 @@ void* dlopen(const char* path, FF_MAYBE_UNUSED int mode) return module; } -int dlclose(void* handle) -{ +int dlclose(void* handle) { NTSTATUS status = LdrUnloadDll(handle); - if (!NT_SUCCESS(status)) - { + if (!NT_SUCCESS(status)) { FF_DEBUG("LdrUnloadDll failed for handle %p with status 0x%08lX: %s", handle, status, ffDebugNtStatus(status)); return -1; } return 0; } -void* dlsym(void* handle, const char* symbol) -{ +void* dlsym(void* handle, const char* symbol) { void* address; USHORT symbolBytes = (USHORT) strlen(symbol) + 1; NTSTATUS status = LdrGetProcedureAddress(handle, &(ANSI_STRING) { - .Length = symbolBytes - sizeof(char), - .MaximumLength = symbolBytes, - .Buffer = (char*) symbol, - }, 0, &address); - if (!NT_SUCCESS(status)) - { + .Length = symbolBytes - sizeof(char), + .MaximumLength = symbolBytes, + .Buffer = (char*) symbol, + }, + 0, + &address); + if (!NT_SUCCESS(status)) { FF_DEBUG("LdrGetProcedureAddress failed for symbol %s with status 0x%08lX: %s", symbol, status, ffDebugNtStatus(status)); return NULL; } return address; } -void* ffLibraryGetModule(const wchar_t* libraryFileName) -{ +void* ffLibraryGetModule(const wchar_t* libraryFileName) { assert(libraryFileName != NULL && "Use \"ffGetPeb()->ImageBaseAddress\" instead"); void* module = NULL; USHORT libraryFileNameBytes = (USHORT) (wcslen(libraryFileName) * sizeof(wchar_t)) + sizeof(wchar_t); NTSTATUS status = LdrGetDllHandle(NULL, NULL, &(UNICODE_STRING) { - .Length = libraryFileNameBytes - sizeof(wchar_t), - .MaximumLength = libraryFileNameBytes, - .Buffer = (wchar_t*) libraryFileName, - }, &module); - if (!NT_SUCCESS(status)) - { + .Length = libraryFileNameBytes - sizeof(wchar_t), + .MaximumLength = libraryFileNameBytes, + .Buffer = (wchar_t*) libraryFileName, + }, + &module); + if (!NT_SUCCESS(status)) { FF_DEBUG("LdrGetDllHandle failed for library %ls with status 0x%08lX: %s", libraryFileName, status, ffDebugNtStatus(status)); return NULL; } diff --git a/src/common/impl/memrchr.c b/src/common/impl/memrchr.c index 730a3ae3a..aaf97e604 100644 --- a/src/common/impl/memrchr.c +++ b/src/common/impl/memrchr.c @@ -2,17 +2,19 @@ #include #include -void* memrchr(const void* s, int c, size_t n) -{ - if (n == 0) return NULL; +void* memrchr(const void* s, int c, size_t n) { + if (n == 0) { + return NULL; + } const uint8_t uc = (uint8_t) c; const uint8_t* p = (const uint8_t*) s + n; - while (n--) - { - if (*--p == uc) return (void*) p; + while (n--) { + if (*--p == uc) { + return (void*) p; + } } return NULL; diff --git a/src/common/impl/netif.c b/src/common/impl/netif.c index 708399bfa..9f9ca5b8a 100644 --- a/src/common/impl/netif.c +++ b/src/common/impl/netif.c @@ -1,12 +1,11 @@ #include "common/netif.h" #ifndef _WIN32 - #include - #include +# include +# include #endif -const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV4(void) -{ +const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV4(void) { static FFNetifDefaultRouteResult result; if (result.status == FF_NETIF_UNINITIALIZED) { result.status = ffNetifGetDefaultRouteImplV4(&result) ? FF_NETIF_OK : FF_NETIF_INVALID; @@ -14,8 +13,7 @@ const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV4(void) return &result; } -const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV6(void) -{ +const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV6(void) { static FFNetifDefaultRouteResult result; if (result.status == FF_NETIF_UNINITIALIZED) { result.status = ffNetifGetDefaultRouteImplV6(&result) ? FF_NETIF_OK : FF_NETIF_INVALID; diff --git a/src/common/impl/netif_apple.c b/src/common/impl/netif_apple.c index 346ce8937..9f7e05e88 100644 --- a/src/common/impl/netif_apple.c +++ b/src/common/impl/netif_apple.c @@ -8,68 +8,66 @@ #include #include -#define ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n)) +#define ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n)) #if __APPLE__ - // https://github.com/apple-oss-distributions/network_cmds/blob/8f38231438e6a4d16ef8015e97e12c2c05105644/rtsol.tproj/if.c#L243 - #define ROUNDUP(a) ROUNDUP2((a), sizeof(uint32_t)) +// https://github.com/apple-oss-distributions/network_cmds/blob/8f38231438e6a4d16ef8015e97e12c2c05105644/rtsol.tproj/if.c#L243 +# define ROUNDUP(a) ROUNDUP2((a), sizeof(uint32_t)) #elif __sun - // https://github.com/illumos/illumos-gate/blob/95b8c88950fa7b19af46bc63230137cf96b0bff7/usr/src/cmd/cmd-inet/usr.sbin/route.c#L339 - #define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) +// https://github.com/illumos/illumos-gate/blob/95b8c88950fa7b19af46bc63230137cf96b0bff7/usr/src/cmd/cmd-inet/usr.sbin/route.c#L339 +# define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) #else - #error unknown platform +# error unknown platform #endif -static struct sockaddr * -get_rt_address(struct rt_msghdr *rtm, int desired) -{ - struct sockaddr *sa = (struct sockaddr *)(rtm + 1); +static struct sockaddr* +get_rt_address(struct rt_msghdr* rtm, int desired) { + struct sockaddr* sa = (struct sockaddr*) (rtm + 1); - for (int i = 0; i < RTAX_MAX; i++) - { - if (rtm->rtm_addrs & (1 << i)) - { - if ((1 << i) == desired) + for (int i = 0; i < RTAX_MAX; i++) { + if (rtm->rtm_addrs & (1 << i)) { + if ((1 << i) == desired) { return sa; + } - #ifndef __sun +#ifndef __sun uint32_t salen = sa->sa_len; - #else +#else uint32_t salen; // https://github.com/illumos/illumos-gate/blob/95b8c88950fa7b19af46bc63230137cf96b0bff7/usr/src/cmd/cmd-inet/usr.sbin/route.c#L2941 switch (sa->sa_family) { - case AF_INET: - salen = sizeof (struct sockaddr_in); - break; - case AF_LINK: - salen = sizeof (struct sockaddr_dl); - break; - case AF_INET6: - salen = sizeof (struct sockaddr_in6); - break; - default: - salen = sizeof (struct sockaddr); - break; + case AF_INET: + salen = sizeof(struct sockaddr_in); + break; + case AF_LINK: + salen = sizeof(struct sockaddr_dl); + break; + case AF_INET6: + salen = sizeof(struct sockaddr_in6); + break; + default: + salen = sizeof(struct sockaddr); + break; } - #endif - sa = (struct sockaddr *)(ROUNDUP(salen) + (char *)sa); +#endif + sa = (struct sockaddr*) (ROUNDUP(salen) + (char*) sa); } } return NULL; } -bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) -{ - //https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104 +bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { + // https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104 FF_AUTO_CLOSE_FD int pfRoute = socket(PF_ROUTE, SOCK_RAW, AF_INET); - if (pfRoute < 0) + if (pfRoute < 0) { return false; + } { struct timeval timeout = {1, 0}; - setsockopt(pfRoute, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); - setsockopt(pfRoute, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)); + setsockopt(pfRoute, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof(timeout)); + setsockopt(pfRoute, SOL_SOCKET, SO_SNDTIMEO, (char*) &timeout, sizeof(timeout)); } uint32_t pid = instance.state.platform.pid; @@ -90,38 +88,38 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) }, .dst = { .sin_family = AF_INET, - #ifndef __sun +#ifndef __sun .sin_len = sizeof(rtmsg.dst), - #endif +#endif }, }; - if (send(pfRoute, &rtmsg, rtmsg.hdr.rtm_msglen, 0) != rtmsg.hdr.rtm_msglen) + if (send(pfRoute, &rtmsg, rtmsg.hdr.rtm_msglen, 0) != rtmsg.hdr.rtm_msglen) { return false; + } - while (recv(pfRoute, &rtmsg, sizeof(rtmsg), 0) > 0 && !(rtmsg.hdr.rtm_seq == 1 && rtmsg.hdr.rtm_pid == (pid_t) pid)) - ; + while (recv(pfRoute, &rtmsg, sizeof(rtmsg), 0) > 0 && !(rtmsg.hdr.rtm_seq == 1 && rtmsg.hdr.rtm_pid == (pid_t) pid)); - #ifndef __sun // On Solaris, the RTF_GATEWAY flag is not set for default routes for some reason +#ifndef __sun // On Solaris, the RTF_GATEWAY flag is not set for default routes for some reason if ((rtmsg.hdr.rtm_flags & (RTF_UP | RTF_GATEWAY)) == (RTF_UP | RTF_GATEWAY)) - #endif +#endif { - struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(&rtmsg.hdr, RTA_IFP); + struct sockaddr_dl* sdl = (struct sockaddr_dl*) get_rt_address(&rtmsg.hdr, RTA_IFP); if (sdl - #ifndef __sun +#ifndef __sun && sdl->sdl_len - #endif - ) - { +#endif + ) { assert(sdl->sdl_nlen <= IF_NAMESIZE); memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen); result->ifName[sdl->sdl_nlen] = '\0'; result->ifIndex = sdl->sdl_index; // Get the preferred source address - struct sockaddr_in* src = (struct sockaddr_in*)get_rt_address(&rtmsg.hdr, RTA_IFA); - if (src && src->sin_family == AF_INET) + struct sockaddr_in* src = (struct sockaddr_in*) get_rt_address(&rtmsg.hdr, RTA_IFA); + if (src && src->sin_family == AF_INET) { result->preferredSourceAddrV4 = src->sin_addr.s_addr; + } return true; } @@ -131,18 +129,18 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) return false; } -bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) -{ - //https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104 +bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { + // https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104 FF_AUTO_CLOSE_FD int pfRoute = socket(PF_ROUTE, SOCK_RAW, AF_INET6); - if (pfRoute < 0) + if (pfRoute < 0) { return false; + } { struct timeval timeout = {1, 0}; - setsockopt(pfRoute, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); - setsockopt(pfRoute, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)); + setsockopt(pfRoute, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof(timeout)); + setsockopt(pfRoute, SOL_SOCKET, SO_SNDTIMEO, (char*) &timeout, sizeof(timeout)); } uint32_t pid = instance.state.platform.pid; @@ -163,29 +161,28 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) }, .dst = { .sin6_family = AF_INET6, - #ifndef __sun +#ifndef __sun .sin6_len = sizeof(rtmsg.dst), - #endif +#endif }, }; - if (send(pfRoute, &rtmsg, rtmsg.hdr.rtm_msglen, 0) != rtmsg.hdr.rtm_msglen) + if (send(pfRoute, &rtmsg, rtmsg.hdr.rtm_msglen, 0) != rtmsg.hdr.rtm_msglen) { return false; + } - while (recv(pfRoute, &rtmsg, sizeof(rtmsg), 0) > 0 && !(rtmsg.hdr.rtm_seq == 2 && rtmsg.hdr.rtm_pid == (pid_t) pid)) - ; + while (recv(pfRoute, &rtmsg, sizeof(rtmsg), 0) > 0 && !(rtmsg.hdr.rtm_seq == 2 && rtmsg.hdr.rtm_pid == (pid_t) pid)); - #ifndef __sun // On Solaris, the RTF_GATEWAY flag is not set for default routes for some reason +#ifndef __sun // On Solaris, the RTF_GATEWAY flag is not set for default routes for some reason if ((rtmsg.hdr.rtm_flags & (RTF_UP | RTF_GATEWAY)) == (RTF_UP | RTF_GATEWAY)) - #endif +#endif { - struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(&rtmsg.hdr, RTA_IFP); + struct sockaddr_dl* sdl = (struct sockaddr_dl*) get_rt_address(&rtmsg.hdr, RTA_IFP); if (sdl - #ifndef __sun +#ifndef __sun && sdl->sdl_len - #endif - ) - { +#endif + ) { assert(sdl->sdl_nlen <= IF_NAMESIZE); memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen); result->ifName[sdl->sdl_nlen] = '\0'; diff --git a/src/common/impl/netif_bsd.c b/src/common/impl/netif_bsd.c index a5b240c00..8e2b5674e 100644 --- a/src/common/impl/netif_bsd.c +++ b/src/common/impl/netif_bsd.c @@ -9,75 +9,72 @@ #include #include -#define ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n)) +#define ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n)) #if __DragonFly__ - // https://github.com/DragonFlyBSD/DragonFlyBSD/blob/cf0aa2f1e47a3f0a6055fe427563cb3f3e627064/sys/net/route.h#L315C9-L315C19 - #define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) +// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/cf0aa2f1e47a3f0a6055fe427563cb3f3e627064/sys/net/route.h#L315C9-L315C19 +# define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) #elif __FreeBSD__ - // https://github.com/freebsd/freebsd-src/blob/e4c0ecba44b20ebb2e4d80978c2cb6d16b730cb9/sys/net/route.h#L368C9-L368C16 - #define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) +// https://github.com/freebsd/freebsd-src/blob/e4c0ecba44b20ebb2e4d80978c2cb6d16b730cb9/sys/net/route.h#L368C9-L368C16 +# define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) #elif __NetBSD__ - // https://github.com/NetBSD/src/blob/29beb637d057520c0ed37ac2cde966f7cc0cadf4/sys/net/route.h#L330 - #define ROUNDUP(a) ROUNDUP2((a), sizeof(uint64_t)) +// https://github.com/NetBSD/src/blob/29beb637d057520c0ed37ac2cde966f7cc0cadf4/sys/net/route.h#L330 +# define ROUNDUP(a) ROUNDUP2((a), sizeof(uint64_t)) #elif __OpenBSD__ - // https://github.com/openbsd/src/blob/ca647cfa4ec3ccb8360714bc0ebc32a394f7fb6a/regress/sys/netinet/bindconnect/bindconnect.c#L250 - #define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) +// https://github.com/openbsd/src/blob/ca647cfa4ec3ccb8360714bc0ebc32a394f7fb6a/regress/sys/netinet/bindconnect/bindconnect.c#L250 +# define ROUNDUP(a) ROUNDUP2((a), sizeof(long)) #else - #error unknown platform +# error unknown platform #endif -static struct sockaddr * -get_rt_address(struct rt_msghdr *rtm, int desired) -{ - struct sockaddr *sa = (struct sockaddr *)(rtm + 1); +static struct sockaddr* +get_rt_address(struct rt_msghdr* rtm, int desired) { + struct sockaddr* sa = (struct sockaddr*) (rtm + 1); - for (int i = 0; i < RTAX_MAX; i++) - { - if (rtm->rtm_addrs & (1 << i)) - { - if ((1 << i) == desired) + for (int i = 0; i < RTAX_MAX; i++) { + if (rtm->rtm_addrs & (1 << i)) { + if ((1 << i) == desired) { return sa; - sa = (struct sockaddr *)(ROUNDUP(sa->sa_len) + (char *)sa); + } + sa = (struct sockaddr*) (ROUNDUP(sa->sa_len) + (char*) sa); } } return NULL; } -bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { int mib[6] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY}; size_t needed; - if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) + if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) { return false; + } FF_AUTO_FREE char* buf = malloc(needed); - if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) + if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { return false; + } char* lim = buf + needed; struct rt_msghdr* rtm; - for (char* next = buf; next < lim; next += rtm->rtm_msglen) - { - rtm = (struct rt_msghdr *)next; - struct sockaddr* sa = (struct sockaddr *)(rtm + 1); + for (char* next = buf; next < lim; next += rtm->rtm_msglen) { + rtm = (struct rt_msghdr*) next; + struct sockaddr* sa = (struct sockaddr*) (rtm + 1); - if ((rtm->rtm_flags & RTF_GATEWAY) && !(rtm->rtm_flags & RTF_REJECT) && (sa->sa_family == AF_INET)) - { - struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(rtm, RTA_IFP); - if (sdl && sdl->sdl_family == AF_LINK) - { + if ((rtm->rtm_flags & RTF_GATEWAY) && !(rtm->rtm_flags & RTF_REJECT) && (sa->sa_family == AF_INET)) { + struct sockaddr_dl* sdl = (struct sockaddr_dl*) get_rt_address(rtm, RTA_IFP); + if (sdl && sdl->sdl_family == AF_LINK) { assert(sdl->sdl_nlen <= IF_NAMESIZE); memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen); result->ifName[sdl->sdl_nlen] = '\0'; result->ifIndex = sdl->sdl_index; // Get the preferred source address - struct sockaddr_in* src = (struct sockaddr_in*)get_rt_address(rtm, RTA_IFA); - if (src && src->sin_family == AF_INET) + struct sockaddr_in* src = (struct sockaddr_in*) get_rt_address(rtm, RTA_IFA); + if (src && src->sin_family == AF_INET) { result->preferredSourceAddrV4 = src->sin_addr.s_addr; + } return true; } @@ -86,31 +83,29 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) return false; } -bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { int mib[6] = {CTL_NET, PF_ROUTE, 0, AF_INET6, NET_RT_FLAGS, RTF_GATEWAY}; size_t needed; - if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) + if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) { return false; + } FF_AUTO_FREE char* buf = malloc(needed); - if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) + if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { return false; + } char* lim = buf + needed; struct rt_msghdr* rtm; - for (char* next = buf; next < lim; next += rtm->rtm_msglen) - { - rtm = (struct rt_msghdr *)next; - struct sockaddr* sa = (struct sockaddr *)(rtm + 1); + for (char* next = buf; next < lim; next += rtm->rtm_msglen) { + rtm = (struct rt_msghdr*) next; + struct sockaddr* sa = (struct sockaddr*) (rtm + 1); - if ((rtm->rtm_flags & RTF_GATEWAY) && !(rtm->rtm_flags & RTF_REJECT) && (sa->sa_family == AF_INET6)) - { - struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(rtm, RTA_IFP); - if (sdl && sdl->sdl_family == AF_LINK) - { + if ((rtm->rtm_flags & RTF_GATEWAY) && !(rtm->rtm_flags & RTF_REJECT) && (sa->sa_family == AF_INET6)) { + struct sockaddr_dl* sdl = (struct sockaddr_dl*) get_rt_address(rtm, RTA_IFP); + if (sdl && sdl->sdl_family == AF_LINK) { assert(sdl->sdl_nlen <= IF_NAMESIZE); memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen); result->ifName[sdl->sdl_nlen] = '\0'; diff --git a/src/common/impl/netif_gnu.c b/src/common/impl/netif_gnu.c index 219bbebab..d2cf5d009 100644 --- a/src/common/impl/netif_gnu.c +++ b/src/common/impl/netif_gnu.c @@ -7,18 +7,20 @@ #define FF_STR_INDIR(x) #x #define FF_STR(x) FF_STR_INDIR(x) -bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { FILE* FF_AUTO_CLOSE_FILE netRoute = fopen("/proc/route", "r"); - if (!netRoute) return false; + 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; + 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; @@ -27,8 +29,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) return false; } -bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { // TODO: AF_INET6 FF_UNUSED(result); return false; diff --git a/src/common/impl/netif_haiku.c b/src/common/impl/netif_haiku.c index faa3ee876..f04183a1f 100644 --- a/src/common/impl/netif_haiku.c +++ b/src/common/impl/netif_haiku.c @@ -11,85 +11,95 @@ // loosely based on Haiku's src/bin/network/route/route.cpp -bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { FF_AUTO_CLOSE_FD int pfRoute = socket(AF_INET, SOCK_RAW, AF_INET); - if (pfRoute < 0) + if (pfRoute < 0) { return false; + } struct ifconf config; config.ifc_len = sizeof(config.ifc_value); - if (ioctl(pfRoute, SIOCGRTSIZE, &config, sizeof(struct ifconf)) < 0) + if (ioctl(pfRoute, SIOCGRTSIZE, &config, sizeof(struct ifconf)) < 0) { return false; + } int size = config.ifc_value; - if (size <= 0) + if (size <= 0) { return false; + } - FF_AUTO_FREE void *buffer = malloc((size_t) size); + FF_AUTO_FREE void* buffer = malloc((size_t) size); if (buffer == NULL) { return false; } config.ifc_len = size; config.ifc_buf = buffer; - if (ioctl(pfRoute, SIOCGRTTABLE, &config, sizeof(struct ifconf)) < 0) + if (ioctl(pfRoute, SIOCGRTTABLE, &config, sizeof(struct ifconf)) < 0) { return false; + } - struct ifreq *interface = (struct ifreq*)buffer; - struct ifreq *end = (struct ifreq*)((uint8_t*)buffer + size); + struct ifreq* interface = (struct ifreq*) buffer; + struct ifreq* end = (struct ifreq*) ((uint8_t*) buffer + size); while (interface < end) { if (interface->ifr_route.flags & RTF_DEFAULT) { // interface->ifr_metric? strlcpy(result->ifName, interface->ifr_name, IF_NAMESIZE); result->ifIndex = if_nametoindex(interface->ifr_name); - if (interface->ifr_route.source) - result->preferredSourceAddrV4 = ((struct sockaddr_in*)interface->ifr_route.source)->sin_addr.s_addr; + if (interface->ifr_route.source) { + result->preferredSourceAddrV4 = ((struct sockaddr_in*) interface->ifr_route.source)->sin_addr.s_addr; + } return true; } size_t addressSize = 0; - if (interface->ifr_route.destination != NULL) + if (interface->ifr_route.destination != NULL) { addressSize += interface->ifr_route.destination->sa_len; - if (interface->ifr_route.mask != NULL) + } + if (interface->ifr_route.mask != NULL) { addressSize += interface->ifr_route.mask->sa_len; - if (interface->ifr_route.gateway != NULL) + } + if (interface->ifr_route.gateway != NULL) { addressSize += interface->ifr_route.gateway->sa_len; + } - interface = (struct ifreq*)((addr_t)interface + IF_NAMESIZE + sizeof(struct route_entry) + addressSize); + interface = (struct ifreq*) ((addr_t) interface + IF_NAMESIZE + sizeof(struct route_entry) + addressSize); } return false; } -bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { FF_AUTO_CLOSE_FD int pfRoute = socket(AF_INET, SOCK_RAW, AF_INET6); - if (pfRoute < 0) + if (pfRoute < 0) { return false; + } struct ifconf config; config.ifc_len = sizeof(config.ifc_value); - if (ioctl(pfRoute, SIOCGRTSIZE, &config, sizeof(struct ifconf)) < 0) + if (ioctl(pfRoute, SIOCGRTSIZE, &config, sizeof(struct ifconf)) < 0) { return false; + } int size = config.ifc_value; - if (size <= 0) + if (size <= 0) { return false; + } - FF_AUTO_FREE void *buffer = malloc((size_t) size); + FF_AUTO_FREE void* buffer = malloc((size_t) size); if (buffer == NULL) { return false; } config.ifc_len = size; config.ifc_buf = buffer; - if (ioctl(pfRoute, SIOCGRTTABLE, &config, sizeof(struct ifconf)) < 0) + if (ioctl(pfRoute, SIOCGRTTABLE, &config, sizeof(struct ifconf)) < 0) { return false; + } - struct ifreq *interface = (struct ifreq*)buffer; - struct ifreq *end = (struct ifreq*)((uint8_t*)buffer + size); + struct ifreq* interface = (struct ifreq*) buffer; + struct ifreq* end = (struct ifreq*) ((uint8_t*) buffer + size); while (interface < end) { if (interface->ifr_route.flags & RTF_DEFAULT) { @@ -99,14 +109,17 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) } size_t addressSize = 0; - if (interface->ifr_route.destination != NULL) + if (interface->ifr_route.destination != NULL) { addressSize += interface->ifr_route.destination->sa_len; - if (interface->ifr_route.mask != NULL) + } + if (interface->ifr_route.mask != NULL) { addressSize += interface->ifr_route.mask->sa_len; - if (interface->ifr_route.gateway != NULL) + } + if (interface->ifr_route.gateway != NULL) { addressSize += interface->ifr_route.gateway->sa_len; + } - interface = (struct ifreq*)((addr_t)interface + IF_NAMESIZE + sizeof(struct route_entry) + addressSize); + interface = (struct ifreq*) ((addr_t) interface + IF_NAMESIZE + sizeof(struct route_entry) + addressSize); } return false; } diff --git a/src/common/impl/netif_linux.c b/src/common/impl/netif_linux.c index 092d919fb..eafacdcb0 100644 --- a/src/common/impl/netif_linux.c +++ b/src/common/impl/netif_linux.c @@ -7,13 +7,11 @@ #include #include -bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) -{ +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) - { + if (sock_fd < 0) { FF_DEBUG("Failed to create netlink socket: %s", strerror(errno)); return false; } @@ -25,11 +23,11 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) // Bind socket struct sockaddr_nl addr = { .nl_family = AF_NETLINK, - .nl_pid = 0, // Let kernel choose PID - .nl_groups = 0, // No multicast groups + .nl_pid = 0, // Let kernel choose PID + .nl_groups = 0, // No multicast groups }; - if (bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { + if (bind(sock_fd, (struct sockaddr*) &addr, sizeof(addr)) < 0) { FF_DEBUG("Failed to bind socket: %s", strerror(errno)); return false; } @@ -52,8 +50,8 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) // Route message .rtm = { .rtm_family = AF_INET, - .rtm_dst_len = 0, // Match all destinations - .rtm_src_len = 0, // Match all sources + .rtm_dst_len = 0, // Match all destinations + .rtm_src_len = 0, // Match all sources .rtm_tos = 0, .rtm_table = RT_TABLE_UNSPEC, .rtm_protocol = RTPROT_UNSPEC, @@ -71,12 +69,11 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) struct sockaddr_nl dest_addr = { .nl_family = AF_NETLINK, - .nl_pid = 0, // Kernel - .nl_groups = 0, // No multicast groups + .nl_pid = 0, // Kernel + .nl_groups = 0, // No multicast groups }; - ssize_t sent = sendto(sock_fd, &req, sizeof(req), 0, - (struct sockaddr*)&dest_addr, sizeof(dest_addr)); + ssize_t sent = sendto(sock_fd, &req, sizeof(req), 0, (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)); @@ -91,17 +88,15 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) uint32_t minMetric = UINT32_MAX; FF_MAYBE_UNUSED int routeCount = 0; - while (true) - { - ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0, - (struct sockaddr*)&src_addr, &src_addr_len); + 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)) { + if (received >= (ssize_t) sizeof(buffer)) { FF_DEBUG("Received truncated message: received %zd, bufsize %zu", received, sizeof(buffer)); return false; } @@ -117,20 +112,19 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) uint32_t prefsrc; } entry; - for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer; + 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) + nlh = NLMSG_NEXT(nlh, received)) { + if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid) { continue; - if (nlh->nlmsg_type == NLMSG_DONE) - { + } + 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)); + FF_DEBUG("Netlink reports error: %s", strerror(-((struct nlmsgerr*) NLMSG_DATA(nlh))->error)); continue; } @@ -140,7 +134,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) } routeCount++; - struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh); + 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; @@ -158,44 +152,47 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) } FF_DEBUG("Processing IPv4 default route candidate #%d", routeCount); - entry = (__typeof__(entry)) { }; // Default to zero metric (no RTA_PRIORITY found) + 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)) + 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); + 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; + 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; + 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)); + FF_DEBUG("Found preferred source: %s", inet_ntoa(*(struct in_addr*) &rta_data)); break; } } - if (entry.ifindex == 0 || entry.metric >= minMetric) - { + if (entry.ifindex == 0 || entry.metric >= minMetric) { next: FF_DEBUG("Skipping route: ifindex=%u, metric=%u", entry.ifindex, entry.metric); continue; @@ -204,8 +201,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) 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) - { + if (minMetric == 0) { FF_DEBUG("Found zero metric route, stopping further processing"); break; // Stop processing if we found a zero metric route } @@ -213,8 +209,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) } exit: - if (minMetric < UINT32_MAX) - { + 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; @@ -223,13 +218,11 @@ exit: return false; } -bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) -{ +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) - { + if (sock_fd < 0) { FF_DEBUG("Failed to create netlink socket: %s", strerror(errno)); return false; } @@ -241,11 +234,11 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) // Bind socket struct sockaddr_nl addr = { .nl_family = AF_NETLINK, - .nl_pid = 0, // Let kernel choose PID - .nl_groups = 0, // No multicast groups + .nl_pid = 0, // Let kernel choose PID + .nl_groups = 0, // No multicast groups }; - if (bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { + if (bind(sock_fd, (struct sockaddr*) &addr, sizeof(addr)) < 0) { FF_DEBUG("Failed to bind socket: %s", strerror(errno)); return false; } @@ -267,9 +260,9 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) }, // Route message .rtm = { - .rtm_family = AF_INET6, // IPv6 instead of IPv4 - .rtm_dst_len = 0, // Match all destinations - .rtm_src_len = 0, // Match all sources + .rtm_family = AF_INET6, // IPv6 instead of IPv4 + .rtm_dst_len = 0, // Match all destinations + .rtm_src_len = 0, // Match all sources .rtm_tos = 0, .rtm_table = RT_TABLE_UNSPEC, .rtm_protocol = RTPROT_UNSPEC, @@ -287,12 +280,11 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) struct sockaddr_nl dest_addr = { .nl_family = AF_NETLINK, - .nl_pid = 0, // Kernel - .nl_groups = 0, // No multicast groups + .nl_pid = 0, // Kernel + .nl_groups = 0, // No multicast groups }; - ssize_t sent = sendto(sock_fd, &req, sizeof(req), 0, - (struct sockaddr*)&dest_addr, sizeof(dest_addr)); + ssize_t sent = sendto(sock_fd, &req, sizeof(req), 0, (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)); @@ -307,17 +299,15 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) uint32_t minMetric = UINT32_MAX; FF_MAYBE_UNUSED int routeCount = 0; - while (true) - { - ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0, - (struct sockaddr*)&src_addr, &src_addr_len); + 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)) { + if (received >= (ssize_t) sizeof(buffer)) { FF_DEBUG("Received truncated message: received %zd, bufsize %zu", received, sizeof(buffer)); return false; } @@ -332,20 +322,19 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) uint32_t ifindex; } entry; - for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer; + 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) + nlh = NLMSG_NEXT(nlh, received)) { + if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid) { continue; - if (nlh->nlmsg_type == NLMSG_DONE) - { + } + 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)); + FF_DEBUG("Netlink reports error: %s", strerror(-((struct nlmsgerr*) NLMSG_DATA(nlh))->error)); continue; } @@ -355,7 +344,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) } routeCount++; - struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh); + 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; @@ -373,14 +362,13 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) } FF_DEBUG("Processing IPv6 default route candidate #%d", routeCount); - entry = (__typeof__(entry)) { }; // Default to zero metric (no RTA_PRIORITY found) + 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)) - { + rta = RTA_NEXT(rta, rtm_len)) { switch (rta->rta_type) { case RTA_DST: if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) { @@ -398,7 +386,9 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) 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; + 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))); } @@ -407,15 +397,16 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) 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; + if (metric >= minMetric) { + goto next; + } entry.metric = metric; } break; } } - if (entry.ifindex == 0 || entry.metric >= minMetric) - { + if (entry.ifindex == 0 || entry.metric >= minMetric) { next: FF_DEBUG("Skipping route: ifindex=%u, metric=%u", entry.ifindex, entry.metric); continue; @@ -424,8 +415,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) result->ifIndex = entry.ifindex; FF_DEBUG("Updated best route: ifindex=%u, metric=%u", entry.ifindex, entry.metric); - if (minMetric == 0) - { + if (minMetric == 0) { FF_DEBUG("Found zero metric route, stopping further processing"); break; // Stop processing if we found a zero metric route } @@ -433,8 +423,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) } exit: - if (minMetric < UINT32_MAX) - { + 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; diff --git a/src/common/impl/netif_windows.c b/src/common/impl/netif_windows.c index a78bbfba0..702c249e6 100644 --- a/src/common/impl/netif_windows.c +++ b/src/common/impl/netif_windows.c @@ -4,29 +4,26 @@ #include // AF_INET6, IN6_IS_ADDR_UNSPECIFIED #include -bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL; - if (!NETIO_SUCCESS(GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable))) + if (!NETIO_SUCCESS(GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable))) { return false; + } bool foundDefault = false; uint32_t smallestMetric = UINT32_MAX; - for (ULONG i = 0; i < pIpForwardTable->NumEntries; ++i) - { + for (ULONG i = 0; i < pIpForwardTable->NumEntries; ++i) { MIB_IPFORWARD_ROW2* row = &pIpForwardTable->Table[i]; if (row->DestinationPrefix.PrefixLength == 0 && row->DestinationPrefix.Prefix.Ipv4.sin_family == AF_INET && - row->DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr == 0) - { + row->DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr == 0) { MIB_IF_ROW2 ifRow = { .InterfaceIndex = row->InterfaceIndex, }; - if (NETIO_SUCCESS(GetIfEntry2(&ifRow)) && ifRow.OperStatus == IfOperStatusUp) - { + if (NETIO_SUCCESS(GetIfEntry2(&ifRow)) && ifRow.OperStatus == IfOperStatusUp) { MIB_IPINTERFACE_ROW ipInterfaceRow = { .Family = AF_INET, .InterfaceIndex = row->InterfaceIndex, @@ -34,11 +31,11 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) uint32_t realMetric = row->Metric /* Metric offset */; - if (NETIO_SUCCESS(GetIpInterfaceEntry(&ipInterfaceRow))) + if (NETIO_SUCCESS(GetIpInterfaceEntry(&ipInterfaceRow))) { realMetric += ipInterfaceRow.Metric /* Interface metric */; + } - if (realMetric < smallestMetric) - { + if (realMetric < smallestMetric) { smallestMetric = realMetric; result->ifIndex = row->InterfaceIndex; foundDefault = true; @@ -53,30 +50,26 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) return foundDefault; } - -bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) -{ +bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL; - if (!NETIO_SUCCESS(GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable))) + if (!NETIO_SUCCESS(GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable))) { return false; + } bool foundDefault = false; uint32_t smallestMetric = UINT32_MAX; - for (ULONG i = 0; i < pIpForwardTable->NumEntries; ++i) - { + for (ULONG i = 0; i < pIpForwardTable->NumEntries; ++i) { MIB_IPFORWARD_ROW2* row = &pIpForwardTable->Table[i]; if (row->DestinationPrefix.PrefixLength == 0 && row->DestinationPrefix.Prefix.Ipv6.sin6_family == AF_INET6 && - IN6_IS_ADDR_UNSPECIFIED(&row->DestinationPrefix.Prefix.Ipv6.sin6_addr)) - { + IN6_IS_ADDR_UNSPECIFIED(&row->DestinationPrefix.Prefix.Ipv6.sin6_addr)) { MIB_IF_ROW2 ifRow = { .InterfaceIndex = row->InterfaceIndex, }; - if (NETIO_SUCCESS(GetIfEntry2(&ifRow)) && ifRow.OperStatus == IfOperStatusUp) - { + if (NETIO_SUCCESS(GetIfEntry2(&ifRow)) && ifRow.OperStatus == IfOperStatusUp) { MIB_IPINTERFACE_ROW ipInterfaceRow = { .Family = AF_INET6, .InterfaceIndex = row->InterfaceIndex, @@ -84,11 +77,11 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) uint32_t realMetric = row->Metric /* Metric offset */; - if (NETIO_SUCCESS(GetIpInterfaceEntry(&ipInterfaceRow))) + if (NETIO_SUCCESS(GetIpInterfaceEntry(&ipInterfaceRow))) { realMetric += ipInterfaceRow.Metric /* Interface metric */; + } - if (realMetric < smallestMetric) - { + if (realMetric < smallestMetric) { smallestMetric = realMetric; result->ifIndex = row->InterfaceIndex; foundDefault = true; diff --git a/src/common/impl/networking_common.c b/src/common/impl/networking_common.c index 939f2e627..543f87623 100644 --- a/src/common/impl/networking_common.c +++ b/src/common/impl/networking_common.c @@ -5,10 +5,9 @@ #include "common/debug.h" #ifdef FF_HAVE_ZLIB -#include +# include -struct FFZlibLibrary -{ +struct FFZlibLibrary { FF_LIBRARY_SYMBOL(inflateInit2_) FF_LIBRARY_SYMBOL(inflate) FF_LIBRARY_SYMBOL(inflateEnd) @@ -16,18 +15,17 @@ struct FFZlibLibrary bool inited; } zlibData; -const char* ffNetworkingLoadZlibLibrary(void) -{ - if (!zlibData.inited) - { +const char* ffNetworkingLoadZlibLibrary(void) { + if (!zlibData.inited) { zlibData.inited = true; FF_LIBRARY_LOAD_MESSAGE(zlib, - #ifdef _WIN32 - "zlib1" - #else - "libz" - #endif - FF_LIBRARY_EXTENSION, 2) +# ifdef _WIN32 + "zlib1" +# else + "libz" +# endif + FF_LIBRARY_EXTENSION, + 2) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateInit2_) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflate) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateEnd) @@ -37,16 +35,16 @@ const char* ffNetworkingLoadZlibLibrary(void) } // Try to pre-read gzip header to determine uncompressed size -static uint32_t guessGzipOutputSize(const void* data, uint32_t dataSize) -{ +static uint32_t guessGzipOutputSize(const void* data, uint32_t dataSize) { // gzip file format: http://www.zlib.org/rfc-gzip.html - if (dataSize < 10 || ((const uint8_t*)data)[0] != 0x1f || ((const uint8_t*)data)[1] != 0x8b) + if (dataSize < 10 || ((const uint8_t*) data)[0] != 0x1f || ((const uint8_t*) data)[1] != 0x8b) { return 0; + } // Uncompressed size in gzip format is stored in the last 4 bytes, but only valid if data is less than 4GB if (dataSize > 18) { // Get ISIZE value from the end of file (little endian) - const uint8_t* tail = (const uint8_t*)data + dataSize - 4; + const uint8_t* tail = (const uint8_t*) data + dataSize - 4; uint32_t uncompressedSize = (uint32_t) tail[0] | ((uint32_t) tail[1] << 8u) | ((uint32_t) tail[2] << 16u) | ((uint32_t) tail[3] << 24u); // For valid gzip files, this value is the length of the uncompressed data modulo 2^32 @@ -65,8 +63,7 @@ static uint32_t guessGzipOutputSize(const void* data, uint32_t dataSize) } // Decompress gzip content -bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) -{ +bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) { assert(headerEnd != NULL && *headerEnd == '\r'); // Calculate header size @@ -96,7 +93,7 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) uint32_t compressedSize = buffer->length - headerSize - 4; // Check if content is actually in gzip format (gzip header magic is 0x1f 0x8b) - if (compressedSize < 2 || (uint8_t)bodyStart[0] != 0x1f || (uint8_t)bodyStart[1] != 0x8b) { + if (compressedSize < 2 || (uint8_t) bodyStart[0] != 0x1f || (uint8_t) bodyStart[1] != 0x8b) { FF_DEBUG("Content is not valid gzip format, skipping decompression"); return false; } @@ -113,14 +110,14 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) .zalloc = Z_NULL, .zfree = Z_NULL, .opaque = Z_NULL, - .avail_in = (uInt)compressedSize, - .next_in = (Bytef*)bodyStart, - .avail_out = (uInt)ffStrbufGetFree(&decompressedBuffer), - .next_out = (Bytef*)decompressedBuffer.chars, + .avail_in = (uInt) compressedSize, + .next_in = (Bytef*) bodyStart, + .avail_out = (uInt) ffStrbufGetFree(&decompressedBuffer), + .next_out = (Bytef*) decompressedBuffer.chars, }; // Initialize decompression engine - if (zlibData.ffinflateInit2_(&zs, 16 + MAX_WBITS, ZLIB_VERSION, (int)sizeof(z_stream)) != Z_OK) { + if (zlibData.ffinflateInit2_(&zs, 16 + MAX_WBITS, ZLIB_VERSION, (int) sizeof(z_stream)) != Z_OK) { FF_DEBUG("Failed to initialize decompression engine"); return false; } @@ -130,20 +127,19 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) int result = zlibData.ffinflate(&zs, Z_FINISH); // If output buffer is insufficient, try to extend buffer - while (result == Z_BUF_ERROR || (result != Z_STREAM_END && zs.avail_out == 0)) - { + while (result == Z_BUF_ERROR || (result != Z_STREAM_END && zs.avail_out == 0)) { FF_DEBUG("Output buffer insufficient, trying to extend"); // Save already decompressed data amount - uint32_t alreadyDecompressed = (uint32_t)(availableOut - zs.avail_out); + uint32_t alreadyDecompressed = (uint32_t) (availableOut - zs.avail_out); decompressedBuffer.length += alreadyDecompressed; decompressedBuffer.chars[decompressedBuffer.length] = '\0'; ffStrbufEnsureFree(&decompressedBuffer, decompressedBuffer.length / 2); // Set output parameters to point to new buffer - zs.avail_out = (uInt)ffStrbufGetFree(&decompressedBuffer); - zs.next_out = (Bytef*)(decompressedBuffer.chars + decompressedBuffer.length); + zs.avail_out = (uInt) ffStrbufGetFree(&decompressedBuffer); + zs.next_out = (Bytef*) (decompressedBuffer.chars + decompressedBuffer.length); availableOut = zs.avail_out; // Decompress again @@ -153,7 +149,7 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) zlibData.ffinflateEnd(&zs); // Calculate decompressed size - uint32_t decompressedSize = (uint32_t)(availableOut - zs.avail_out); + uint32_t decompressedSize = (uint32_t) (availableOut - zs.avail_out); decompressedBuffer.length += decompressedSize; decompressedBuffer.chars[decompressedBuffer.length] = '\0'; FF_DEBUG("Successfully decompressed %u bytes compressed data to %u bytes", compressedSize, decompressedBuffer.length); @@ -163,19 +159,13 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) char* line = NULL; size_t len = 0; - while (ffStrbufGetline(&line, &len, buffer)) - { - if (ffStrStartsWithIgnCase(line, "Content-Encoding:")) - { + while (ffStrbufGetline(&line, &len, buffer)) { + if (ffStrStartsWithIgnCase(line, "Content-Encoding:")) { continue; - } - else if (ffStrStartsWithIgnCase(line, "Content-Length:")) - { + } else if (ffStrStartsWithIgnCase(line, "Content-Length:")) { ffStrbufAppendF(&newBuffer, "Content-Length: %u\r\n", decompressedBuffer.length); continue; - } - else if (line[0] == '\r') - { + } else if (line[0] == '\r') { ffStrbufAppendS(&newBuffer, "\r\n"); ffStrbufGetlineRestore(&line, &len, buffer); break; diff --git a/src/common/impl/networking_linux.c b/src/common/impl/networking_linux.c index cd9ab16ef..4e7cd9e31 100644 --- a/src/common/impl/networking_linux.c +++ b/src/common/impl/networking_linux.c @@ -16,132 +16,137 @@ #include #include -static const char* tryNonThreadingFastPath(FFNetworkingState* state) -{ - #if defined(TCP_FASTOPEN) || __APPLE__ +static const char* tryNonThreadingFastPath(FFNetworkingState* state) { +#if defined(TCP_FASTOPEN) || __APPLE__ - if (!state->tfo) - { - #if __linux__ || __GNU__ - // Linux doesn't support sendto() on unconnected sockets - FF_DEBUG("TCP Fast Open disabled, skipping"); - return "TCP Fast Open disabled"; - #endif - } - else - { - FF_DEBUG("Attempting to use TCP Fast Open to connect"); + if (!state->tfo) { +# if __linux__ || __GNU__ + // Linux doesn't support sendto() on unconnected sockets + FF_DEBUG("TCP Fast Open disabled, skipping"); + return "TCP Fast Open disabled"; +# endif + } else { + FF_DEBUG("Attempting to use TCP Fast Open to connect"); - #ifndef __APPLE__ // On macOS, TCP_FASTOPEN doesn't seem to be needed - // Set TCP Fast Open - int flag = 1; - if (setsockopt(state->sockfd, IPPROTO_TCP, - #ifdef __APPLE__ +# ifndef __APPLE__ // On macOS, TCP_FASTOPEN doesn't seem to be needed + // Set TCP Fast Open + int flag = 1; + if (setsockopt(state->sockfd, IPPROTO_TCP, +# ifdef __APPLE__ // https://github.com/rust-lang/libc/pull/3135 0x218 // TCP_FASTOPEN_FORCE_ENABLE - #else +# else TCP_FASTOPEN - #endif - , &flag, sizeof(flag)) != 0) { - FF_DEBUG("Failed to set TCP_FASTOPEN option: %s", strerror(errno)); - return "setsockopt(TCP_FASTOPEN) failed"; - } else { - #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"); - #else - FF_DEBUG("Successfully set TCP_FASTOPEN option"); - #endif - } - #endif +# endif + , + &flag, + sizeof(flag)) != 0) { + FF_DEBUG("Failed to set TCP_FASTOPEN option: %s", strerror(errno)); + return "setsockopt(TCP_FASTOPEN) failed"; + } else { +# 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"); +# else + FF_DEBUG("Successfully set TCP_FASTOPEN option"); +# endif } +# endif + } - #ifndef __APPLE__ - FF_DEBUG("Using sendto() + MSG_DONTWAIT to send %u bytes of data", state->command.length); - ssize_t sent = sendto(state->sockfd, - state->command.chars, - state->command.length, - #ifdef MSG_FASTOPEN - MSG_FASTOPEN | - #endif - #ifdef MSG_NOSIGNAL - MSG_NOSIGNAL | - #endif - MSG_DONTWAIT, - state->addr->ai_addr, - state->addr->ai_addrlen); - #else - if (fcntl(state->sockfd, F_SETFL, O_NONBLOCK) == -1) { - FF_DEBUG("fcntl(F_SETFL) failed: %s", strerror(errno)); - return "fcntl(F_SETFL) failed"; - } - FF_DEBUG("Using connectx() to send %u bytes of data", state->command.length); - // Use connectx to establish connection and send data in one call - size_t sent; - if (connectx(state->sockfd, +# ifndef __APPLE__ + FF_DEBUG("Using sendto() + MSG_DONTWAIT to send %u bytes of data", state->command.length); + ssize_t sent = sendto(state->sockfd, + state->command.chars, + state->command.length, +# ifdef MSG_FASTOPEN + MSG_FASTOPEN | +# endif +# ifdef MSG_NOSIGNAL + MSG_NOSIGNAL | +# endif + MSG_DONTWAIT, + state->addr->ai_addr, + state->addr->ai_addrlen); +# else + if (fcntl(state->sockfd, F_SETFL, O_NONBLOCK) == -1) { + FF_DEBUG("fcntl(F_SETFL) failed: %s", strerror(errno)); + return "fcntl(F_SETFL) failed"; + } + FF_DEBUG("Using connectx() to send %u bytes of data", state->command.length); + // Use connectx to establish connection and send data in one call + size_t sent; + if (connectx(state->sockfd, &(sa_endpoints_t) { .sae_dstaddr = state->addr->ai_addr, .sae_dstaddrlen = state->addr->ai_addrlen, }, - SAE_ASSOCID_ANY, state->tfo ? CONNECT_DATA_IDEMPOTENT : 0, + SAE_ASSOCID_ANY, + state->tfo ? CONNECT_DATA_IDEMPOTENT : 0, &(struct iovec) { .iov_base = state->command.chars, .iov_len = state->command.length, - }, 1, &sent, NULL) != 0) sent = 0; - if (fcntl(state->sockfd, F_SETFL, 0) == -1) { - FF_DEBUG("fcntl(F_SETFL) failed: %s", strerror(errno)); - return "fcntl(F_SETFL) failed"; - } - #endif - if (sent > 0 || (errno == EAGAIN || errno == EWOULDBLOCK - #ifdef __APPLE__ - // On macOS EINPROGRESS means the connection cannot be completed immediately - // On Linux, it means the TFO cookie is not available locally - || errno == EINPROGRESS - #endif - )) - { - FF_DEBUG( - #ifdef __APPLE__ - "connectx()" - #else - "sendto()" - #endif - " %s (sent=%zd, %s)", errno == 0 ? "succeeded" : "was in progress", sent, strerror(errno)); - freeaddrinfo(state->addr); - state->addr = NULL; - ffStrbufDestroy(&state->command); - return NULL; - } - + }, + 1, + &sent, + NULL) != 0) { + sent = 0; + } + if (fcntl(state->sockfd, F_SETFL, 0) == -1) { + FF_DEBUG("fcntl(F_SETFL) failed: %s", strerror(errno)); + return "fcntl(F_SETFL) failed"; + } +# endif + if (sent > 0 || (errno == EAGAIN || errno == EWOULDBLOCK +# ifdef __APPLE__ + // On macOS EINPROGRESS means the connection cannot be completed immediately + // On Linux, it means the TFO cookie is not available locally + || errno == EINPROGRESS +# endif + )) { FF_DEBUG( - #ifdef __APPLE__ +# ifdef __APPLE__ "connectx()" - #else +# else "sendto()" - #endif - " failed: %s", strerror(errno)); - #ifdef __APPLE__ - return "connectx() failed"; - #else - return "sendto() failed"; - #endif - #else - FF_UNUSED(state); - return "TFO support is not available"; - #endif +# endif + " %s (sent=%zd, %s)", + errno == 0 ? "succeeded" : "was in progress", + sent, + strerror(errno)); + freeaddrinfo(state->addr); + state->addr = NULL; + ffStrbufDestroy(&state->command); + return NULL; + } + + FF_DEBUG( +# ifdef __APPLE__ + "connectx()" +# else + "sendto()" +# endif + " failed: %s", + strerror(errno)); +# ifdef __APPLE__ + return "connectx() failed"; +# else + return "sendto() failed"; +# endif +#else + FF_UNUSED(state); + return "TFO support is not available"; +#endif } // Traditional connect and send function -static const char* connectAndSend(FFNetworkingState* state) -{ +static const char* connectAndSend(FFNetworkingState* state) { const char* ret = NULL; FF_DEBUG("Using traditional connection method to connect"); FF_DEBUG("Attempting connect() to server..."); - if(connect(state->sockfd, state->addr->ai_addr, state->addr->ai_addrlen) == -1) - { + if (connect(state->sockfd, state->addr->ai_addr, state->addr->ai_addrlen) == -1) { FF_DEBUG("connect() failed: %s", strerror(errno)); ret = "connect() failed"; goto error; @@ -149,8 +154,7 @@ static const char* connectAndSend(FFNetworkingState* state) FF_DEBUG("connect() succeeded"); FF_DEBUG("Attempting to send %u bytes of data...", state->command.length); - if(send(state->sockfd, state->command.chars, state->command.length, 0) < 0) - { + if (send(state->sockfd, state->command.chars, state->command.length, 0) < 0) { FF_DEBUG("send() failed: %s", strerror(errno)); ret = "send() failed"; goto error; @@ -176,8 +180,7 @@ exit: FF_THREAD_ENTRY_DECL_WRAPPER(connectAndSend, FFNetworkingState*); // Parallel DNS resolution and socket creation -static const char* initNetworkingState(FFNetworkingState* state, const char* host, const char* path, const char* headers) -{ +static const char* initNetworkingState(FFNetworkingState* state, const char* host, const char* path, const char* headers) { FF_DEBUG("Initializing network connection state: host=%s, path=%s", host, path); // Initialize command and host information @@ -197,25 +200,23 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos ffStrbufAppendS(&state->command, headers); ffStrbufAppendS(&state->command, "\r\n"); - #ifdef FF_HAVE_THREADS +#ifdef FF_HAVE_THREADS state->thread = 0; FF_DEBUG("Thread ID initialized to 0"); - #endif +#endif const char* ret = NULL; struct addrinfo hints = { .ai_family = state->ipv6 ? AF_INET6 : AF_INET, .ai_socktype = SOCK_STREAM, - .ai_flags = AI_NUMERICSERV - }; + .ai_flags = AI_NUMERICSERV}; FF_DEBUG("Resolving address: %s (%s)", host, state->ipv6 ? "IPv6" : "IPv4"); // Use AI_NUMERICSERV flag to indicate the service is a numeric port, reducing parsing time int gaiRes = getaddrinfo(host, "80", &hints, &state->addr); - if(gaiRes != 0) - { + if (gaiRes != 0) { FF_DEBUG("getaddrinfo() failed: %s (res=%d)", gai_strerror(gaiRes), gaiRes); ret = "getaddrinfo() failed"; goto error; @@ -224,8 +225,7 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos FF_DEBUG("Creating socket"); state->sockfd = socket(state->addr->ai_family, state->addr->ai_socktype, state->addr->ai_protocol); - if(state->sockfd == -1) - { + if (state->sockfd == -1) { FF_DEBUG("socket() failed: %s", strerror(errno)); ret = "socket() failed"; goto error; @@ -233,57 +233,56 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos FF_DEBUG("Socket creation successful: fd=%d", state->sockfd); int flag = 1; - #ifdef TCP_NODELAY +#ifdef TCP_NODELAY // Disable Nagle's algorithm to reduce small packet transmission delay if (setsockopt(state->sockfd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)) != 0) { FF_DEBUG("Failed to set TCP_NODELAY: %s", strerror(errno)); } else { FF_DEBUG("Successfully disabled Nagle's algorithm"); } - #endif +#endif - #ifdef TCP_QUICKACK +#ifdef TCP_QUICKACK // Set TCP_QUICKACK option to avoid delayed acknowledgments if (setsockopt(state->sockfd, IPPROTO_TCP, TCP_QUICKACK, &flag, sizeof(flag)) != 0) { FF_DEBUG("Failed to set TCP_QUICKACK: %s", strerror(errno)); } else { FF_DEBUG("Successfully enabled TCP quick acknowledgment"); } - #endif +#endif - if (state->timeout > 0) - { + if (state->timeout > 0) { FF_DEBUG("Setting connection timeout: %u ms", state->timeout); FF_MAYBE_UNUSED uint32_t sec = state->timeout / 1000; - if (sec == 0) sec = 1; + if (sec == 0) { + sec = 1; + } - #ifdef TCP_CONNECTIONTIMEOUT +#ifdef TCP_CONNECTIONTIMEOUT FF_DEBUG("Using TCP_CONNECTIONTIMEOUT: %u seconds", sec); setsockopt(state->sockfd, IPPROTO_TCP, TCP_CONNECTIONTIMEOUT, &sec, sizeof(sec)); - #elif defined(TCP_KEEPINIT) +#elif defined(TCP_KEEPINIT) FF_DEBUG("Using TCP_KEEPINIT: %u seconds", sec); setsockopt(state->sockfd, IPPROTO_TCP, TCP_KEEPINIT, &sec, sizeof(sec)); - #elif defined(TCP_USER_TIMEOUT) +#elif defined(TCP_USER_TIMEOUT) FF_DEBUG("Using TCP_USER_TIMEOUT: %u milliseconds", state->timeout); setsockopt(state->sockfd, IPPROTO_TCP, TCP_USER_TIMEOUT, &state->timeout, sizeof(state->timeout)); - #else +#else FF_DEBUG("Current platform does not support TCP connection timeout"); - #endif +#endif } return NULL; error: FF_DEBUG("Error occurred during initialization"); - if (state->addr != NULL) - { + if (state->addr != NULL) { FF_DEBUG("Releasing address information"); freeaddrinfo(state->addr); state->addr = NULL; } - if (state->sockfd > 0) - { + if (state->sockfd > 0) { FF_DEBUG("Closing socket: fd=%d", state->sockfd); close(state->sockfd); state->sockfd = -1; @@ -291,31 +290,26 @@ error: return ret; } -const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) -{ +const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) { FF_DEBUG("Preparing to send HTTP request: host=%s, path=%s", host, path); - if (state->compression) - { + if (state->compression) { FF_DEBUG("Compression enabled, checking if zlib is available"); - #ifdef FF_HAVE_ZLIB +#ifdef FF_HAVE_ZLIB const char* zlibError = ffNetworkingLoadZlibLibrary(); // Only enable compression if zlib library is successfully loaded - if (zlibError == NULL) - { + if (zlibError == NULL) { FF_DEBUG("Successfully loaded zlib library, compression enabled"); } else { FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError); state->compression = false; } - #else +#else FF_DEBUG("zlib not supported at build time, compression disabled"); state->compression = false; - #endif - } - else - { +#endif + } else { FF_DEBUG("Compression disabled"); } @@ -333,33 +327,30 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho } FF_DEBUG("TryNonThreadingFastPath() failed: %s, trying traditional connection", tfoResult); - #ifdef FF_HAVE_THREADS - if (instance.config.general.multithreading) - { +#ifdef FF_HAVE_THREADS + if (instance.config.general.multithreading) { FF_DEBUG("Multithreading mode enabled, creating connection thread"); state->thread = ffThreadCreate(connectAndSendThreadMain, state); if (state->thread) { - FF_DEBUG("Thread creation successful: thread=%p", (void*)(uintptr_t)state->thread); + FF_DEBUG("Thread creation successful: thread=%p", (void*) (uintptr_t) state->thread); return NULL; } FF_DEBUG("Thread creation failed"); } else { FF_DEBUG("Multithreading mode disabled, connecting in main thread"); } - #endif +#endif return connectAndSend(state); } -const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer) -{ +const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer) { assert(buffer->allocated > 0); FF_DEBUG("Preparing to receive HTTP response"); uint32_t timeout = state->timeout; - #ifdef FF_HAVE_THREADS - if (state->thread) - { +#ifdef FF_HAVE_THREADS + if (state->thread) { FF_DEBUG("Connection thread is running, waiting for it to complete (timeout=%u ms)", timeout); if (!ffThreadJoin(state->thread, timeout)) { FF_DEBUG("Thread join failed or timed out"); @@ -368,10 +359,9 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf FF_DEBUG("Thread completed successfully"); state->thread = 0; } - #endif +#endif - if(state->sockfd == -1) - { + if (state->sockfd == -1) { FF_DEBUG("Invalid socket, HTTP request might have failed"); return "ffNetworkingSendHttpRequest() failed"; } @@ -380,24 +370,22 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf int rcvbuf = 65536; // 64KB setsockopt(state->sockfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)); - #ifdef __APPLE__ +#ifdef __APPLE__ // poll for the socket to be readable. // Because of the non-blocking connectx() call, the connection might not be established yet FF_DEBUG("Using poll() to check if socket is readable"); { int pollRes = poll(&(struct pollfd) { - .fd = state->sockfd, - .events = POLLIN - }, 1, timeout > 0 ? (int) timeout : -1); - if (pollRes == 0) - { + .fd = state->sockfd, + .events = POLLIN}, + 1, + timeout > 0 ? (int) timeout : -1); + if (pollRes == 0) { FF_DEBUG("poll() timed out after %u ms", timeout); close(state->sockfd); state->sockfd = -1; return "poll() timeout"; - } - else if (pollRes == -1) - { + } else if (pollRes == -1) { FF_DEBUG("poll() failed: %s", strerror(errno)); close(state->sockfd); state->sockfd = -1; @@ -405,19 +393,17 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf } } FF_DEBUG("Socket is readable, proceeding to receive data"); - #else - if(timeout > 0) - { +#else + if (timeout > 0) { FF_DEBUG("Setting receive timeout: %u ms", timeout); struct timeval timev; timev.tv_sec = timeout / 1000; - timev.tv_usec = (__typeof__(timev.tv_usec)) ((timeout % 1000) * 1000); //milliseconds to microseconds + timev.tv_usec = (__typeof__(timev.tv_usec)) ((timeout % 1000) * 1000); // milliseconds to microseconds setsockopt(state->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timev, sizeof(timev)); } - #endif +#endif - if (shutdown(state->sockfd, SHUT_WR) == -1) - { + if (shutdown(state->sockfd, SHUT_WR) == -1) { FF_DEBUG("Failed to shutdown socket send: %s", strerror(errno)); // Not a critical error, continue anyway } @@ -429,7 +415,9 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf do { FF_DEBUG("Data reception loop #%d, current buffer size: %u, available space: %u", - ++recvCount, buffer->length, ffStrbufGetFree(buffer)); + ++recvCount, + buffer->length, + ffStrbufGetFree(buffer)); // We set `Connection: close`, so the server will close the connection when done. // Thus we can use MSG_WAITALL to wait until the buffer is full or the connection is closed. @@ -453,7 +441,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf if (headerEnd == 0) { char* pHeaderEnd = memmem(buffer->chars, buffer->length, "\r\n\r\n", 4); if (pHeaderEnd) { - headerEnd = (uint32_t)(pHeaderEnd - buffer->chars); + headerEnd = (uint32_t) (pHeaderEnd - buffer->chars); FF_DEBUG("Found HTTP header end marker, position: %u", headerEnd); // Check for Content-Length header to pre-allocate enough memory @@ -496,8 +484,8 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf return "Invalid response"; } - // If compression was used, try to decompress - #ifdef FF_HAVE_ZLIB +// If compression was used, try to decompress +#ifdef FF_HAVE_ZLIB if (state->compression) { FF_DEBUG("Content received, checking if compressed"); if (!ffNetworkingDecompressGzip(buffer, buffer->chars + headerEnd)) { @@ -507,7 +495,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf FF_DEBUG("Decompression successful or no decompression needed, total length after decompression: %u bytes", buffer->length); } } - #endif +#endif return NULL; } diff --git a/src/common/impl/networking_windows.c b/src/common/impl/networking_windows.c index 620087492..ad7553ff0 100644 --- a/src/common/impl/networking_windows.c +++ b/src/common/impl/networking_windows.c @@ -1,7 +1,7 @@ #include #include -//Must be included after +// Must be included after #include "fastfetch.h" #include "common/networking.h" #include "common/stringUtils.h" @@ -9,23 +9,22 @@ static LPFN_CONNECTEX ConnectEx; -static const char* initWsaData(WSADATA* wsaData) -{ +static const char* initWsaData(WSADATA* wsaData) { FF_DEBUG("Initializing WinSock"); - if(WSAStartup(MAKEWORD(2, 2), wsaData) != 0) { + if (WSAStartup(MAKEWORD(2, 2), wsaData) != 0) { FF_DEBUG("WSAStartup() failed"); return "WSAStartup() failed"; } - if(LOBYTE(wsaData->wVersion) != 2 || HIBYTE(wsaData->wVersion) != 2) { + if (LOBYTE(wsaData->wVersion) != 2 || HIBYTE(wsaData->wVersion) != 2) { FF_DEBUG("Invalid wsaData version found: %d.%d", LOBYTE(wsaData->wVersion), HIBYTE(wsaData->wVersion)); WSACleanup(); return "Invalid wsaData version found"; } - //Dummy socket needed for WSAIoctl + // Dummy socket needed for WSAIoctl SOCKET sockfd = WSASocketW(AF_INET, SOCK_STREAM, 0, NULL, 0, 0); - if(sockfd == INVALID_SOCKET) { + if (sockfd == INVALID_SOCKET) { FF_DEBUG("WSASocketW(AF_INET, SOCK_STREAM) failed"); WSACleanup(); return "WSASocketW(AF_INET, SOCK_STREAM) failed"; @@ -33,10 +32,7 @@ static const char* initWsaData(WSADATA* wsaData) DWORD dwBytes; GUID guid = WSAID_CONNECTEX; - if(WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, - &guid, sizeof(guid), - &ConnectEx, sizeof(ConnectEx), - &dwBytes, NULL, NULL) != 0) { + if (WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &ConnectEx, sizeof(ConnectEx), &dwBytes, NULL, NULL) != 0) { FF_DEBUG("WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER) failed"); closesocket(sockfd); WSACleanup(); @@ -49,45 +45,36 @@ static const char* initWsaData(WSADATA* wsaData) return NULL; } -const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) -{ +const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) { FF_DEBUG("Preparing to send HTTP request: host=%s, path=%s", host, path); - if (state->compression) - { - #ifdef FF_HAVE_ZLIB + if (state->compression) { +#ifdef FF_HAVE_ZLIB const char* zlibError = ffNetworkingLoadZlibLibrary(); // Only enable compression if zlib library is successfully loaded - if (zlibError == NULL) - { + if (zlibError == NULL) { FF_DEBUG("Successfully loaded zlib library, compression enabled"); } else { FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError); state->compression = false; } - #else +#else FF_DEBUG("zlib not supported at build time, compression disabled"); state->compression = false; - #endif - } - else - { +#endif + } else { FF_DEBUG("Compression disabled"); } static WSADATA wsaData; - if (wsaData.wVersion == 0) - { + if (wsaData.wVersion == 0) { const char* error = initWsaData(&wsaData); - if (error != NULL) - { + if (error != NULL) { wsaData.wVersion = (WORD) -1; FF_DEBUG("WinSock initialization failed: %s", error); return error; } - } - else if (wsaData.wVersion == (WORD) -1) - { + } else if (wsaData.wVersion == (WORD) -1) { FF_DEBUG("WinSock initialization previously failed"); return "initWsaData() failed before"; } @@ -100,54 +87,52 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho }; wchar_t hostW[256]; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(hostW, (ULONG) sizeof(hostW), NULL, host, (ULONG) strlen(host) + 1))) - { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(hostW, (ULONG) sizeof(hostW), NULL, host, (ULONG) strlen(host) + 1))) { FF_DEBUG("Failed to convert host to wide string: %s", host); return "Failed to convert host to wide string"; } FF_DEBUG("Resolving address: %s (%s)", host, state->ipv6 ? "IPv6" : "IPv4"); - if(GetAddrInfoW(hostW, L"80", &hints, &addr) != 0) - { + if (GetAddrInfoW(hostW, L"80", &hints, &addr) != 0) { FF_DEBUG("GetAddrInfoW() failed"); return "GetAddrInfoW() failed"; } state->sockfd = WSASocketW(addr->ai_family, addr->ai_socktype, addr->ai_protocol, NULL, 0, 0); - if(state->sockfd == INVALID_SOCKET) - { + if (state->sockfd == INVALID_SOCKET) { FF_DEBUG("WSASocketW() failed"); FreeAddrInfoW(addr); return "WSASocketW() failed"; } DWORD flag = 1; - #ifdef TCP_NODELAY +#ifdef TCP_NODELAY // Enable TCP_NODELAY to disable Nagle's algorithm - if (setsockopt(state->sockfd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(flag)) != 0) { + if (setsockopt(state->sockfd, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(flag)) != 0) { FF_DEBUG("Failed to set TCP_NODELAY: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); } else { FF_DEBUG("Successfully disabled Nagle's algorithm"); } - #endif +#endif // Set timeout if needed if (state->timeout > 0) { FF_DEBUG("Setting connection timeout: %u ms", state->timeout); - setsockopt(state->sockfd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&state->timeout, sizeof(state->timeout)); + setsockopt(state->sockfd, SOL_SOCKET, SO_SNDTIMEO, (const char*) &state->timeout, sizeof(state->timeout)); } - //ConnectEx requires the socket to be initially bound - if((state->ipv6 - ? bind(state->sockfd, (SOCKADDR *) &(struct sockaddr_in6) { - .sin6_family = AF_INET6, - .sin6_addr = in6addr_any, - }, sizeof(struct sockaddr_in6)) - : bind(state->sockfd, (SOCKADDR *) &(struct sockaddr_in) { - .sin_family = AF_INET, - .sin_addr.s_addr = INADDR_ANY, - }, sizeof(struct sockaddr_in))) != 0) - { + // ConnectEx requires the socket to be initially bound + if ((state->ipv6 + ? bind(state->sockfd, (SOCKADDR*) &(struct sockaddr_in6) { + .sin6_family = AF_INET6, + .sin6_addr = in6addr_any, + }, + sizeof(struct sockaddr_in6)) + : bind(state->sockfd, (SOCKADDR*) &(struct sockaddr_in) { + .sin_family = AF_INET, + .sin_addr.s_addr = INADDR_ANY, + }, + sizeof(struct sockaddr_in))) != 0) { FF_DEBUG("bind() failed: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); closesocket(state->sockfd); FreeAddrInfoW(addr); @@ -156,9 +141,8 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho } // Initialize overlapped structure with WSA event for asynchronous I/O - state->overlapped = (OVERLAPPED){ - .hEvent = WSACreateEvent() - }; + state->overlapped = (OVERLAPPED) { + .hEvent = WSACreateEvent()}; if (state->overlapped.hEvent == WSA_INVALID_EVENT) { FF_DEBUG("WSACreateEvent() failed"); @@ -185,49 +169,39 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho ffStrbufAppendS(&state->command, headers); ffStrbufAppendS(&state->command, "\r\n"); - #ifdef TCP_FASTOPEN - if (state->tfo) - { +#ifdef TCP_FASTOPEN + if (state->tfo) { // Set TCP Fast Open flag = 1; - if (setsockopt(state->sockfd, IPPROTO_TCP, TCP_FASTOPEN, (char*)&flag, sizeof(flag)) != 0) { + if (setsockopt(state->sockfd, IPPROTO_TCP, TCP_FASTOPEN, (char*) &flag, sizeof(flag)) != 0) { FF_DEBUG("Failed to set TCP_FASTOPEN option: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); } else { FF_DEBUG("Successfully set TCP_FASTOPEN option"); } - } - else - { + } else { FF_DEBUG("TCP Fast Open disabled"); } - #endif +#endif FF_DEBUG("Using ConnectEx to send %u bytes of data", state->command.length); DWORD sent = 0; - BOOL result = ConnectEx(state->sockfd, addr->ai_addr, (int)addr->ai_addrlen, - state->command.chars, state->command.length, &sent, &state->overlapped); + BOOL result = ConnectEx(state->sockfd, addr->ai_addr, (int) addr->ai_addrlen, state->command.chars, state->command.length, &sent, &state->overlapped); FreeAddrInfoW(addr); addr = NULL; - if(!result) - { - if (WSAGetLastError() != WSA_IO_PENDING) - { + if (!result) { + if (WSAGetLastError() != WSA_IO_PENDING) { FF_DEBUG("ConnectEx() failed: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); WSACloseEvent(state->overlapped.hEvent); closesocket(state->sockfd); state->sockfd = INVALID_SOCKET; ffStrbufDestroy(&state->command); return "ConnectEx() failed"; - } - else - { + } else { FF_DEBUG("ConnectEx() pending"); } - } - else - { + } else { FF_DEBUG("ConnectEx() succeeded, sent %u bytes of data", (unsigned) sent); } @@ -235,31 +209,28 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho return NULL; } -const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer) -{ +const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer) { assert(buffer->allocated > 0); FF_DEBUG("Preparing to receive HTTP response"); - if (state->sockfd == INVALID_SOCKET) - { + if (state->sockfd == INVALID_SOCKET) { FF_DEBUG("Invalid socket, HTTP request might have failed"); return "ffNetworkingSendHttpRequest() failed"; } uint32_t timeout = state->timeout; - if (timeout > 0) - { + if (timeout > 0) { FF_DEBUG("WSAWaitForMultipleEvents with timeout: %u ms", timeout); DWORD result = WSAWaitForMultipleEvents(1, &state->overlapped.hEvent, TRUE, timeout, FALSE); - if (result != WSA_WAIT_EVENT_0) - { + if (result != WSA_WAIT_EVENT_0) { if (result == WSA_WAIT_TIMEOUT) { FF_DEBUG("WSAWaitForMultipleEvents timed out"); } else { FF_DEBUG("WSAWaitForMultipleEvents failed: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); } - if (CancelIoEx((HANDLE) state->sockfd, &state->overlapped)) + if (CancelIoEx((HANDLE) state->sockfd, &state->overlapped)) { WSAWaitForMultipleEvents(1, &state->overlapped.hEvent, TRUE, 10, TRUE); + } WSACloseEvent(state->overlapped.hEvent); closesocket(state->sockfd); ffStrbufDestroy(&state->command); @@ -268,8 +239,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf } DWORD transfer, flags; - if (!WSAGetOverlappedResult(state->sockfd, &state->overlapped, &transfer, TRUE, &flags)) - { + if (!WSAGetOverlappedResult(state->sockfd, &state->overlapped, &transfer, TRUE, &flags)) { FF_DEBUG("WSAGetOverlappedResult failed: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); closesocket(state->sockfd); WSACloseEvent(state->overlapped.hEvent); @@ -281,28 +251,24 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf WSACloseEvent(state->overlapped.hEvent); state->overlapped.hEvent = NULL; - if (setsockopt(state->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0) != 0) - { + if (setsockopt(state->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0) != 0) { FF_DEBUG("Failed to update connect context: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); // Not a critical error, continue anyway } - if (shutdown(state->sockfd, SD_SEND) == SOCKET_ERROR) - { + if (shutdown(state->sockfd, SD_SEND) == SOCKET_ERROR) { FF_DEBUG("Failed to shutdown socket send: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); // Not a critical error, continue anyway } - if(timeout > 0) - { + if (timeout > 0) { FF_DEBUG("Setting receive timeout: %u ms", timeout); - setsockopt(state->sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); + setsockopt(state->sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*) &timeout, sizeof(timeout)); } // Set larger receive buffer for better performance int rcvbuf = 65536; // 64KB - if (setsockopt(state->sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&rcvbuf, sizeof(rcvbuf))) - { + if (setsockopt(state->sockfd, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvbuf, sizeof(rcvbuf))) { FF_DEBUG("Failed to set SO_RCVBUF: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); // Not a critical error, continue anyway } @@ -314,13 +280,20 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf do { FF_DEBUG("Data reception loop #%d, current buffer size: %u, available space: %u", - ++recvCount, buffer->length, ffStrbufGetFree(buffer)); + ++recvCount, + buffer->length, + ffStrbufGetFree(buffer)); DWORD received = 0, recvFlags = 0; int recvResult = WSARecv(state->sockfd, &(WSABUF) { - .buf = buffer->chars + buffer->length, - .len = (ULONG) ffStrbufGetFree(buffer), - }, 1, &received, &recvFlags, NULL, NULL); + .buf = buffer->chars + buffer->length, + .len = (ULONG) ffStrbufGetFree(buffer), + }, + 1, + &received, + &recvFlags, + NULL, + NULL); if (recvResult == SOCKET_ERROR || received == 0) { if (recvResult == 0 && received == 0) { @@ -340,7 +313,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf if (headerEnd == 0) { char* pHeaderEnd = strstr(buffer->chars, "\r\n\r\n"); if (pHeaderEnd) { - headerEnd = (uint32_t)(pHeaderEnd - buffer->chars); + headerEnd = (uint32_t) (pHeaderEnd - buffer->chars); FF_DEBUG("Found HTTP header end marker, position: %u", headerEnd); // Check for Content-Length header to pre-allocate enough memory @@ -358,7 +331,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf } } while (ffStrbufGetFree(buffer) > 0); - FF_DEBUG("Closing socket: fd=%u", (unsigned)state->sockfd); + FF_DEBUG("Closing socket: fd=%u", (unsigned) state->sockfd); closesocket(state->sockfd); state->sockfd = INVALID_SOCKET; @@ -378,14 +351,15 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf if (ffStrbufStartsWithS(buffer, "HTTP/1.0 200 OK\r\n")) { FF_DEBUG("Received valid HTTP 200 response, content length: %u bytes, total length: %u bytes", - contentLength, buffer->length); + contentLength, + buffer->length); } else { FF_DEBUG("Invalid response: %.40s...", buffer->chars); return "Invalid response"; } - // If compression was used, try to decompress - #ifdef FF_HAVE_ZLIB +// If compression was used, try to decompress +#ifdef FF_HAVE_ZLIB if (state->compression) { FF_DEBUG("Content received, checking if compressed"); if (!ffNetworkingDecompressGzip(buffer, buffer->chars + headerEnd)) { @@ -395,7 +369,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf FF_DEBUG("Decompression successful or no decompression needed, total length after decompression: %u bytes", buffer->length); } } - #endif +#endif return NULL; } diff --git a/src/common/impl/option.c b/src/common/impl/option.c index 63da17ef3..a6dc09673 100644 --- a/src/common/impl/option.c +++ b/src/common/impl/option.c @@ -4,34 +4,35 @@ #include "common/stringUtils.h" // Return start position of the inner key if the argument key belongs to the module specified, NULL otherwise -const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName) -{ +const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName) { const char* subKey = argumentKey; - if(!(subKey[0] == '-' && subKey[1] == '-')) + if (!(subKey[0] == '-' && subKey[1] == '-')) { return NULL; + } subKey += 2; - uint32_t moduleNameLen = (uint32_t)strlen(moduleName); - if(strncasecmp(subKey, moduleName, moduleNameLen) != 0) + uint32_t moduleNameLen = (uint32_t) strlen(moduleName); + if (strncasecmp(subKey, moduleName, moduleNameLen) != 0) { return NULL; + } subKey += moduleNameLen; - if(subKey[0] == '\0') + if (subKey[0] == '\0') { return subKey; + } - if(subKey[0] != '-') + if (subKey[0] != '-') { return NULL; + } subKey += 1; return subKey; } -void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer) -{ - if(value == NULL) - { +void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer) { + if (value == NULL) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(477); } @@ -39,18 +40,15 @@ void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* b ffStrbufSetS(buffer, value); } -uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) -{ - if(value == NULL) - { +uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) { + if (value == NULL) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(480); } char* end; uint32_t num = (uint32_t) strtoul(value, &end, 10); - if(*end != '\0') - { + if (*end != '\0') { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(479); } @@ -58,18 +56,15 @@ uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) return num; } -int32_t ffOptionParseInt32(const char* argumentKey, const char* value) -{ - if(value == NULL) - { +int32_t ffOptionParseInt32(const char* argumentKey, const char* value) { + if (value == NULL) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(480); } char* end; int32_t num = (int32_t) strtol(value, &end, 10); - if(*end != '\0') - { + if (*end != '\0') { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(479); } @@ -77,42 +72,38 @@ int32_t ffOptionParseInt32(const char* argumentKey, const char* value) return num; } -int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]) -{ - if(requestedKey == NULL) - { +int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]) { + if (requestedKey == NULL) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(476); } - for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) - { - if(ffStrEqualsIgnCase(requestedKey, pPair->key)) + for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) { + if (ffStrEqualsIgnCase(requestedKey, pPair->key)) { return pPair->value; + } } fprintf(stderr, "Error: unknown %s value: %s\n", argumentKey, requestedKey); exit(478); } -bool ffOptionParseBoolean(const char* str) -{ +bool ffOptionParseBoolean(const char* str) { return ( !ffStrSet(str) || ffStrEqualsIgnCase(str, "true") || - ffStrEqualsIgnCase(str, "yes") || - ffStrEqualsIgnCase(str, "on") || - ffStrEqualsIgnCase(str, "1") - ); + ffStrEqualsIgnCase(str, "yes") || + ffStrEqualsIgnCase(str, "on") || + ffStrEqualsIgnCase(str, "1")); } -void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) -{ - if (!value || value[0] == '\0') return; +void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) { + if (!value || value[0] == '\0') { + return; + } // If value is already an ANSI escape code, use it - if (value[0] == '\e' && value[1] == '[') - { + if (value[0] == '\e' && value[1] == '[') { ffStrbufAppendS(buffer, value + 2); ffStrbufTrimRight(buffer, 'm'); return; @@ -120,54 +111,28 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) ffStrbufEnsureFree(buffer, 63); - while(*value != '\0') - { - #define FF_APPEND_COLOR_CODE_COND(prefix, code) \ - if(ffStrStartsWithIgnCase(value, #prefix)) { ffStrbufAppendS(buffer, code); value += strlen(#prefix); continue; } - #define FF_APPEND_COLOR_PROP_COND(prefix, prop) \ - if(ffStrStartsWithIgnCase(value, #prefix)) { if (instance.config.display.prop.length) ffStrbufAppend(buffer, &instance.config.display.prop); else ffStrbufAppendS(buffer, FF_COLOR_FG_DEFAULT); value += strlen(#prefix); continue; } + while (*value != '\0') { +#define FF_APPEND_COLOR_CODE_COND(prefix, code) \ + if (ffStrStartsWithIgnCase(value, #prefix)) { \ + ffStrbufAppendS(buffer, code); \ + value += strlen(#prefix); \ + continue; \ + } +#define FF_APPEND_COLOR_PROP_COND(prefix, prop) \ + if (ffStrStartsWithIgnCase(value, #prefix)) { \ + if (instance.config.display.prop.length) ffStrbufAppend(buffer, &instance.config.display.prop); \ + else ffStrbufAppendS(buffer, FF_COLOR_FG_DEFAULT); \ + value += strlen(#prefix); \ + continue; \ + } - if (ffCharIsEnglishAlphabet(value[0])) - { + if (ffCharIsEnglishAlphabet(value[0])) { FF_APPEND_COLOR_CODE_COND(reset_, FF_COLOR_MODE_RESET) - else FF_APPEND_COLOR_CODE_COND(bold_, FF_COLOR_MODE_BOLD) - else FF_APPEND_COLOR_CODE_COND(bright_, FF_COLOR_MODE_BOLD) - else FF_APPEND_COLOR_CODE_COND(dim_, FF_COLOR_MODE_DIM) - else FF_APPEND_COLOR_CODE_COND(italic_, FF_COLOR_MODE_ITALIC) - else FF_APPEND_COLOR_CODE_COND(underline_, FF_COLOR_MODE_UNDERLINE) - else FF_APPEND_COLOR_CODE_COND(blink_, FF_COLOR_MODE_BLINK) - else FF_APPEND_COLOR_CODE_COND(inverse_, FF_COLOR_MODE_INVERSE) - else FF_APPEND_COLOR_CODE_COND(hidden_, FF_COLOR_MODE_HIDDEN) - else FF_APPEND_COLOR_CODE_COND(strike_, FF_COLOR_MODE_STRIKETHROUGH) - else FF_APPEND_COLOR_CODE_COND(black, FF_COLOR_FG_BLACK) - else FF_APPEND_COLOR_CODE_COND(red, FF_COLOR_FG_RED) - else FF_APPEND_COLOR_CODE_COND(green, FF_COLOR_FG_GREEN) - else FF_APPEND_COLOR_CODE_COND(yellow, FF_COLOR_FG_YELLOW) - else FF_APPEND_COLOR_CODE_COND(blue, FF_COLOR_FG_BLUE) - else FF_APPEND_COLOR_CODE_COND(magenta, FF_COLOR_FG_MAGENTA) - else FF_APPEND_COLOR_CODE_COND(cyan, FF_COLOR_FG_CYAN) - else FF_APPEND_COLOR_CODE_COND(white, FF_COLOR_FG_WHITE) - else FF_APPEND_COLOR_CODE_COND(default, FF_COLOR_FG_DEFAULT) - else FF_APPEND_COLOR_CODE_COND(light_black, FF_COLOR_FG_LIGHT_BLACK) - else FF_APPEND_COLOR_CODE_COND(light_red, FF_COLOR_FG_LIGHT_RED) - else FF_APPEND_COLOR_CODE_COND(light_green, FF_COLOR_FG_LIGHT_GREEN) - else FF_APPEND_COLOR_CODE_COND(light_yellow, FF_COLOR_FG_LIGHT_YELLOW) - else FF_APPEND_COLOR_CODE_COND(light_blue, FF_COLOR_FG_LIGHT_BLUE) - else FF_APPEND_COLOR_CODE_COND(light_magenta, FF_COLOR_FG_LIGHT_MAGENTA) - else FF_APPEND_COLOR_CODE_COND(light_cyan, FF_COLOR_FG_LIGHT_CYAN) - else FF_APPEND_COLOR_CODE_COND(light_white, FF_COLOR_FG_LIGHT_WHITE) - else FF_APPEND_COLOR_PROP_COND(keys, colorKeys) - else FF_APPEND_COLOR_PROP_COND(title, colorTitle) - else FF_APPEND_COLOR_PROP_COND(output, colorOutput) - else FF_APPEND_COLOR_PROP_COND(separator, colorSeparator) - else - { + else FF_APPEND_COLOR_CODE_COND(bold_, FF_COLOR_MODE_BOLD) else FF_APPEND_COLOR_CODE_COND(bright_, FF_COLOR_MODE_BOLD) else FF_APPEND_COLOR_CODE_COND(dim_, FF_COLOR_MODE_DIM) else FF_APPEND_COLOR_CODE_COND(italic_, FF_COLOR_MODE_ITALIC) else FF_APPEND_COLOR_CODE_COND(underline_, FF_COLOR_MODE_UNDERLINE) else FF_APPEND_COLOR_CODE_COND(blink_, FF_COLOR_MODE_BLINK) else FF_APPEND_COLOR_CODE_COND(inverse_, FF_COLOR_MODE_INVERSE) else FF_APPEND_COLOR_CODE_COND(hidden_, FF_COLOR_MODE_HIDDEN) else FF_APPEND_COLOR_CODE_COND(strike_, FF_COLOR_MODE_STRIKETHROUGH) else FF_APPEND_COLOR_CODE_COND(black, FF_COLOR_FG_BLACK) else FF_APPEND_COLOR_CODE_COND(red, FF_COLOR_FG_RED) else FF_APPEND_COLOR_CODE_COND(green, FF_COLOR_FG_GREEN) else FF_APPEND_COLOR_CODE_COND(yellow, FF_COLOR_FG_YELLOW) else FF_APPEND_COLOR_CODE_COND(blue, FF_COLOR_FG_BLUE) else FF_APPEND_COLOR_CODE_COND(magenta, FF_COLOR_FG_MAGENTA) else FF_APPEND_COLOR_CODE_COND(cyan, FF_COLOR_FG_CYAN) else FF_APPEND_COLOR_CODE_COND(white, FF_COLOR_FG_WHITE) else FF_APPEND_COLOR_CODE_COND(default, FF_COLOR_FG_DEFAULT) else FF_APPEND_COLOR_CODE_COND(light_black, FF_COLOR_FG_LIGHT_BLACK) else FF_APPEND_COLOR_CODE_COND(light_red, FF_COLOR_FG_LIGHT_RED) else FF_APPEND_COLOR_CODE_COND(light_green, FF_COLOR_FG_LIGHT_GREEN) else FF_APPEND_COLOR_CODE_COND(light_yellow, FF_COLOR_FG_LIGHT_YELLOW) else FF_APPEND_COLOR_CODE_COND(light_blue, FF_COLOR_FG_LIGHT_BLUE) else FF_APPEND_COLOR_CODE_COND(light_magenta, FF_COLOR_FG_LIGHT_MAGENTA) else FF_APPEND_COLOR_CODE_COND(light_cyan, FF_COLOR_FG_LIGHT_CYAN) else FF_APPEND_COLOR_CODE_COND(light_white, FF_COLOR_FG_LIGHT_WHITE) else FF_APPEND_COLOR_PROP_COND(keys, colorKeys) else FF_APPEND_COLOR_PROP_COND(title, colorTitle) else FF_APPEND_COLOR_PROP_COND(output, colorOutput) else FF_APPEND_COLOR_PROP_COND(separator, colorSeparator) else { fprintf(stderr, "Error: invalid color code found: %s\n", value); exit(479); } - } - else if (value[0] == '@') - { + } else if (value[0] == '@') { // Xterm 256 color ++value; char* pend = NULL; @@ -181,9 +146,7 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) ffStrbufAppendUInt(buffer, color); value = pend; continue; - } - else if (value[0] == '#') - { + } else if (value[0] == '#') { // RGB color ++value; char* pend = NULL; @@ -195,13 +158,11 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) if (pend - value > 6) { fprintf(stderr, "Error: RGB color code too long: %s\n", value); exit(479); - } - else if (pend - value == 3) { + } else if (pend - value == 3) { rgb = ((rgb & 0xF00) >> 8) * 0x110000 + - ((rgb & 0x0F0) >> 4) * 0x001100 + - ((rgb & 0x00F) >> 0) * 0x000011; - } - else if (pend - value != 6) { + ((rgb & 0x0F0) >> 4) * 0x001100 + + ((rgb & 0x00F) >> 0) * 0x000011; + } else if (pend - value != 6) { fprintf(stderr, "Error: invalid RGB color code length: %s\n", value); exit(479); } @@ -214,7 +175,7 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) ffStrbufAppendC(buffer, *value); ++value; - #undef FF_APPEND_COLOR_CODE_COND - #undef FF_APPEND_COLOR_PROP_COND +#undef FF_APPEND_COLOR_CODE_COND +#undef FF_APPEND_COLOR_PROP_COND } } diff --git a/src/common/impl/parsing.c b/src/common/impl/parsing.c index 668a28773..b6de9d648 100644 --- a/src/common/impl/parsing.c +++ b/src/common/impl/parsing.c @@ -4,94 +4,86 @@ #include #ifdef _WIN32 - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wformat" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wformat" #endif -void ffParseSemver(FFstrbuf* buffer, const FFstrbuf* major, const FFstrbuf* minor, const FFstrbuf* patch) -{ - if(major->length > 0) +void ffParseSemver(FFstrbuf* buffer, const FFstrbuf* major, const FFstrbuf* minor, const FFstrbuf* patch) { + if (major->length > 0) { ffStrbufAppend(buffer, major); - else if(minor->length > 0 || patch->length > 0) + } else if (minor->length > 0 || patch->length > 0) { ffStrbufAppendC(buffer, '1'); + } - if(minor->length == 0 && patch->length == 0) + if (minor->length == 0 && patch->length == 0) { return; + } ffStrbufAppendC(buffer, '.'); - if(minor->length > 0) + if (minor->length > 0) { ffStrbufAppend(buffer, minor); - else if(patch->length > 0) + } else if (patch->length > 0) { ffStrbufAppendC(buffer, '0'); + } - if(patch->length == 0) + if (patch->length == 0) { return; + } ffStrbufAppendC(buffer, '.'); ffStrbufAppend(buffer, patch); } -int8_t ffVersionCompare(const FFVersion* version1, const FFVersion* version2) -{ - if(version1->major != version2->major) +int8_t ffVersionCompare(const FFVersion* version1, const FFVersion* version2) { + if (version1->major != version2->major) { return version1->major > version2->major ? 1 : -1; + } - if(version1->minor != version2->minor) + if (version1->minor != version2->minor) { return version1->minor > version2->minor ? 1 : -1; + } - if(version1->patch != version2->patch) + if (version1->patch != version2->patch) { return version1->patch > version2->patch ? 1 : -1; + } return 0; } -void ffVersionToPretty(const FFVersion* version, FFstrbuf* pretty) -{ - if(version->major > 0 || version->minor > 0 || version->patch > 0) - { +void ffVersionToPretty(const FFVersion* version, FFstrbuf* pretty) { + if (version->major > 0 || version->minor > 0 || version->patch > 0) { ffStrbufAppendUInt(pretty, version->major); } - if(version->minor > 0 || version->patch > 0) - { + if (version->minor > 0 || version->patch > 0) { ffStrbufAppendC(pretty, '.'); ffStrbufAppendUInt(pretty, version->minor); } - if(version->patch > 0) - { + if (version->patch > 0) { ffStrbufAppendC(pretty, '.'); ffStrbufAppendUInt(pretty, version->patch); } } -void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, const FFstrbuf* gtk4) -{ - if(gtk2->length > 0 && gtk3->length > 0 && gtk4->length > 0) - { - if((ffStrbufIgnCaseEqual(gtk2, gtk3)) && (ffStrbufIgnCaseEqual(gtk2, gtk4))) - { +void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, const FFstrbuf* gtk4) { + if (gtk2->length > 0 && gtk3->length > 0 && gtk4->length > 0) { + if ((ffStrbufIgnCaseEqual(gtk2, gtk3)) && (ffStrbufIgnCaseEqual(gtk2, gtk4))) { ffStrbufAppend(buffer, gtk4); ffStrbufAppendS(buffer, " [GTK2/3/4]"); - } - else if(ffStrbufIgnCaseEqual(gtk2, gtk3)) - { + } else if (ffStrbufIgnCaseEqual(gtk2, gtk3)) { ffStrbufAppend(buffer, gtk3); ffStrbufAppendS(buffer, " [GTK2/3], "); ffStrbufAppend(buffer, gtk4); ffStrbufAppendS(buffer, " [GTK4]"); - } - else if(ffStrbufIgnCaseEqual(gtk3, gtk4)) - { + } else if (ffStrbufIgnCaseEqual(gtk3, gtk4)) { ffStrbufAppend(buffer, gtk2); ffStrbufAppendS(buffer, " [GTK2], "); ffStrbufAppend(buffer, gtk4); ffStrbufAppendS(buffer, " [GTK3/4]"); - } - else - { + } else { ffStrbufAppend(buffer, gtk2); ffStrbufAppendS(buffer, " [GTK2], "); ffStrbufAppend(buffer, gtk3); @@ -99,54 +91,38 @@ void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, co ffStrbufAppend(buffer, gtk4); ffStrbufAppendS(buffer, " [GTK4]"); } - } - else if(gtk2->length > 0 && gtk3->length > 0) - { - if(ffStrbufIgnCaseEqual(gtk2, gtk3)) - { + } else if (gtk2->length > 0 && gtk3->length > 0) { + if (ffStrbufIgnCaseEqual(gtk2, gtk3)) { ffStrbufAppend(buffer, gtk3); ffStrbufAppendS(buffer, " [GTK2/3]"); - } - else - { + } else { ffStrbufAppend(buffer, gtk2); ffStrbufAppendS(buffer, " [GTK2], "); ffStrbufAppend(buffer, gtk3); ffStrbufAppendS(buffer, " [GTK3]"); } - } - else if(gtk3->length > 0 && gtk4->length > 0) - { - if(ffStrbufIgnCaseEqual(gtk3, gtk4)) - { + } else if (gtk3->length > 0 && gtk4->length > 0) { + if (ffStrbufIgnCaseEqual(gtk3, gtk4)) { ffStrbufAppend(buffer, gtk4); ffStrbufAppendS(buffer, " [GTK3/4]"); - } - else - { + } else { ffStrbufAppend(buffer, gtk3); ffStrbufAppendS(buffer, " [GTK3], "); ffStrbufAppend(buffer, gtk4); ffStrbufAppendS(buffer, " [GTK4]"); } - } - else if(gtk2->length > 0) - { + } else if (gtk2->length > 0) { ffStrbufAppend(buffer, gtk2); ffStrbufAppendS(buffer, " [GTK2]"); - } - else if(gtk3->length > 0) - { + } else if (gtk3->length > 0) { ffStrbufAppend(buffer, gtk3); ffStrbufAppendS(buffer, " [GTK3]"); - } - else if(gtk4->length > 0) - { + } else if (gtk4->length > 0) { ffStrbufAppend(buffer, gtk4); ffStrbufAppendS(buffer, " [GTK4]"); } } #ifdef _WIN32 - #pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif diff --git a/src/common/impl/path.c b/src/common/impl/path.c index 2c01d2330..59c163651 100644 --- a/src/common/impl/path.c +++ b/src/common/impl/path.c @@ -3,44 +3,49 @@ #include "common/arrayUtils.h" #if !_WIN32 -const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) -{ +const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) { char* path = getenv("PATH"); - if(!path) + if (!path) { return "$PATH not set"; + } - #ifdef _WIN32 +# ifdef _WIN32 const bool appendExe = !ffStrEndsWithIgnCase(name, ".exe"); - #endif +# endif - for (char* token = path; *token; path = token + 1) - { + for (char* token = path; *token; path = token + 1) { token = strchr(path, - #ifdef _WIN32 - ';' - #else - ':' - #endif +# ifdef _WIN32 + ';' +# else + ':' +# endif ); - if (!token) token = path + strlen(path); + if (!token) { + token = path + strlen(path); + } - ffStrbufSetNS(result, (uint32_t)(token - path), path); + ffStrbufSetNS(result, (uint32_t) (token - path), path); ffStrbufEnsureEndsWithC(result, - #ifdef _WIN32 - '\\' - #else - '/' - #endif +# ifdef _WIN32 + '\\' +# else + '/' +# endif ); ffStrbufAppendS(result, name); - #ifdef _WIN32 - if (appendExe) ffStrbufAppendS(result, ".exe"); - if (!ffPathExists(result->chars, FF_PATHTYPE_FILE)) +# ifdef _WIN32 + if (appendExe) { + ffStrbufAppendS(result, ".exe"); + } + if (!ffPathExists(result->chars, FF_PATHTYPE_FILE)) { continue; - #else - if (access(result->chars, X_OK) != 0) + } +# else + if (access(result->chars, X_OK) != 0) { continue; - #endif + } +# endif return NULL; } @@ -48,17 +53,15 @@ const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) return "Executable not found"; } #else -#include -#include -#include -#include +# include +# include +# include +# include -const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) -{ +const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) { char buffer[MAX_PATH + 1]; DWORD length = SearchPathA(NULL, name, ".exe", sizeof(buffer), buffer, NULL); - if (length == 0) - { + if (length == 0) { ffStrbufClear(result); return "Executable not found"; } @@ -66,10 +69,8 @@ const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) return NULL; } -static inline int winerr2Errno(DWORD err) -{ - switch (err) - { +static inline int winerr2Errno(DWORD err) { + switch (err) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_INVALID_NAME: @@ -89,24 +90,20 @@ static inline int winerr2Errno(DWORD err) } } -char* frealpath(HANDLE hFile, char* resolved_name) -{ - if (__builtin_expect(hFile == INVALID_HANDLE_VALUE || !hFile, false)) - { +char* frealpath(HANDLE hFile, char* resolved_name) { + if (__builtin_expect(hFile == INVALID_HANDLE_VALUE || !hFile, false)) { errno = EINVAL; return NULL; } wchar_t resolvedNameW[MAX_PATH + 4]; /* +4 for "\\\\?\\" prefix */ - DWORD lenW = GetFinalPathNameByHandleW(hFile, resolvedNameW, (DWORD)ARRAY_SIZE(resolvedNameW), FILE_NAME_NORMALIZED); + DWORD lenW = GetFinalPathNameByHandleW(hFile, resolvedNameW, (DWORD) ARRAY_SIZE(resolvedNameW), FILE_NAME_NORMALIZED); - if (lenW == 0) - { + if (lenW == 0) { errno = winerr2Errno(GetLastError()); return NULL; } - if (lenW >= ARRAY_SIZE(resolvedNameW)) - { + if (lenW >= ARRAY_SIZE(resolvedNameW)) { errno = E2BIG; return NULL; } @@ -115,51 +112,41 @@ char* frealpath(HANDLE hFile, char* resolved_name) wchar_t* srcW = resolvedNameW; DWORD srcLenW = lenW; - if (srcLenW >= 8 && wcsncmp(resolvedNameW, L"\\\\?\\UNC\\", 8) == 0) - { + if (srcLenW >= 8 && wcsncmp(resolvedNameW, L"\\\\?\\UNC\\", 8) == 0) { /* Convert "\\?\UNC\server\share" to "\\server\share" */ srcW += 6; srcLenW -= 6; *srcW = L'\\'; - } - else if (srcLenW >= 4 && wcsncmp(resolvedNameW, L"\\\\?\\", 4) == 0) - { + } else if (srcLenW >= 4 && wcsncmp(resolvedNameW, L"\\\\?\\", 4) == 0) { srcW += 4; srcLenW -= 4; } - if (resolved_name) - { + if (resolved_name) { ULONG outBytes = 0; - if (!NT_SUCCESS(RtlUnicodeToUTF8N(resolved_name, MAX_PATH, &outBytes, srcW, (ULONG)(srcLenW * sizeof(wchar_t))))) - { + if (!NT_SUCCESS(RtlUnicodeToUTF8N(resolved_name, MAX_PATH, &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) { errno = E2BIG; return NULL; } - if (outBytes > MAX_PATH) - { + if (outBytes > MAX_PATH) { errno = E2BIG; return NULL; } return resolved_name; - } - else - { + } else { /* UTF-8 worst-case: up to 4 bytes per UTF-16 code unit */ char tmp[(MAX_PATH + 4) * 4]; ULONG outBytes = 0; - if (!NT_SUCCESS(RtlUnicodeToUTF8N(tmp, (ULONG)sizeof(tmp), &outBytes, srcW, (ULONG)(srcLenW * sizeof(wchar_t))))) - { + if (!NT_SUCCESS(RtlUnicodeToUTF8N(tmp, (ULONG) sizeof(tmp), &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) { errno = E2BIG; return NULL; } - resolved_name = (char*)malloc(outBytes); - if (!resolved_name) - { + resolved_name = (char*) malloc(outBytes); + if (!resolved_name) { errno = ENOMEM; return NULL; } @@ -171,10 +158,8 @@ char* frealpath(HANDLE hFile, char* resolved_name) return resolved_name; } -char* realpath(const char* __restrict file_name, char* __restrict resolved_name) -{ - if (!file_name) - { +char* realpath(const char* __restrict file_name, char* __restrict resolved_name) { + if (!file_name) { errno = EINVAL; return NULL; } @@ -182,8 +167,7 @@ char* realpath(const char* __restrict file_name, char* __restrict resolved_name) wchar_t fileNameW[MAX_PATH]; ULONG lenBytes = 0; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG)sizeof(fileNameW), &lenBytes, file_name, (ULONG)strlen(file_name) + 1))) - { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &lenBytes, file_name, (ULONG) strlen(file_name) + 1))) { errno = EINVAL; return NULL; } @@ -197,8 +181,7 @@ char* realpath(const char* __restrict file_name, char* __restrict resolved_name) FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (hFile == INVALID_HANDLE_VALUE) - { + if (hFile == INVALID_HANDLE_VALUE) { errno = winerr2Errno(GetLastError()); return NULL; } @@ -206,18 +189,15 @@ char* realpath(const char* __restrict file_name, char* __restrict resolved_name) return frealpath(hFile, resolved_name); } -ssize_t freadlink(HANDLE hFile, char* buf, size_t bufsiz) -{ - if (__builtin_expect(hFile == INVALID_HANDLE_VALUE || !buf || bufsiz == 0, false)) - { +ssize_t freadlink(HANDLE hFile, char* buf, size_t bufsiz) { + if (__builtin_expect(hFile == INVALID_HANDLE_VALUE || !buf || bufsiz == 0, false)) { errno = EINVAL; return -1; } alignas(REPARSE_DATA_BUFFER) BYTE reparseBuf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; DWORD bytesReturned = 0; - if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, reparseBuf, (DWORD) sizeof(reparseBuf), &bytesReturned, NULL)) - { + if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, reparseBuf, (DWORD) sizeof(reparseBuf), &bytesReturned, NULL)) { errno = winerr2Errno(GetLastError()); return -1; } @@ -226,59 +206,45 @@ ssize_t freadlink(HANDLE hFile, char* buf, size_t bufsiz) const wchar_t* targetW = NULL; USHORT targetBytes = 0; - if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) - { - if (rp->SymbolicLinkReparseBuffer.PrintNameLength > 0) - { + if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) { + if (rp->SymbolicLinkReparseBuffer.PrintNameLength > 0) { targetW = rp->SymbolicLinkReparseBuffer.PathBuffer + (rp->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(wchar_t)); targetBytes = rp->SymbolicLinkReparseBuffer.PrintNameLength; - } - else - { + } else { targetW = rp->SymbolicLinkReparseBuffer.PathBuffer + (rp->SymbolicLinkReparseBuffer.SubstituteNameOffset / sizeof(wchar_t)); targetBytes = rp->SymbolicLinkReparseBuffer.SubstituteNameLength; if (targetBytes >= 8 && - wcsncmp(targetW, L"\\??\\", 4) == 0) - { + wcsncmp(targetW, L"\\??\\", 4) == 0) { targetW += 4; targetBytes -= 8; } } - } - else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) - { - if (rp->MountPointReparseBuffer.PrintNameLength > 0) - { + } else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) { + if (rp->MountPointReparseBuffer.PrintNameLength > 0) { targetW = rp->MountPointReparseBuffer.PathBuffer + (rp->MountPointReparseBuffer.PrintNameOffset / sizeof(wchar_t)); targetBytes = rp->MountPointReparseBuffer.PrintNameLength; - } - else - { + } else { targetW = rp->MountPointReparseBuffer.PathBuffer + (rp->MountPointReparseBuffer.SubstituteNameOffset / sizeof(wchar_t)); targetBytes = rp->MountPointReparseBuffer.SubstituteNameLength; if (targetBytes >= 8 && - wcsncmp(targetW, L"\\??\\", 4) == 0) - { + wcsncmp(targetW, L"\\??\\", 4) == 0) { targetW += 4; targetBytes -= 8; } } - } - else - { + } else { errno = EINVAL; return -1; } ULONG outBytes = 0; - if (!NT_SUCCESS(RtlUnicodeToUTF8N(buf, (ULONG) bufsiz, &outBytes, targetW, targetBytes))) - { + if (!NT_SUCCESS(RtlUnicodeToUTF8N(buf, (ULONG) bufsiz, &outBytes, targetW, targetBytes))) { errno = E2BIG; return -1; } @@ -287,18 +253,15 @@ ssize_t freadlink(HANDLE hFile, char* buf, size_t bufsiz) return (ssize_t) outBytes; } -ssize_t readlink(const char* path, char* buf, size_t bufsiz) -{ - if (!path || !buf || bufsiz == 0) - { +ssize_t readlink(const char* path, char* buf, size_t bufsiz) { + if (!path || !buf || bufsiz == 0) { errno = EINVAL; return -1; } wchar_t pathW[MAX_PATH]; ULONG pathWBytes = 0; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(pathW, (ULONG) sizeof(pathW), &pathWBytes, path, (ULONG) strlen(path) + 1))) - { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(pathW, (ULONG) sizeof(pathW), &pathWBytes, path, (ULONG) strlen(path) + 1))) { errno = EINVAL; return -1; } @@ -310,11 +273,9 @@ ssize_t readlink(const char* path, char* buf, size_t bufsiz) NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, - NULL - ); + NULL); - if (hFile == INVALID_HANDLE_VALUE) - { + if (hFile == INVALID_HANDLE_VALUE) { errno = winerr2Errno(GetLastError()); return -1; } diff --git a/src/common/impl/percent.c b/src/common/impl/percent.c index a367bce57..ee0b8cf3f 100644 --- a/src/common/impl/percent.c +++ b/src/common/impl/percent.c @@ -6,44 +6,42 @@ #include "common/textModifier.h" #include "common/stringUtils.h" -static void appendOutputColor(FFstrbuf* buffer, const FFModuleArgs* module) -{ - if (module->outputColor.length) +static void appendOutputColor(FFstrbuf* buffer, const FFModuleArgs* module) { + if (module->outputColor.length) { ffStrbufAppendF(buffer, "\e[%sm", module->outputColor.chars); - else if (instance.config.display.colorOutput.length) + } else if (instance.config.display.colorOutput.length) { ffStrbufAppendF(buffer, "\e[%sm", instance.config.display.colorOutput.chars); + } } -const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFlags* result) -{ - if (yyjson_is_uint(jsonVal)) - { +const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFlags* result) { + if (yyjson_is_uint(jsonVal)) { *result = (FFPercentageTypeFlags) yyjson_get_uint(jsonVal); return NULL; } - if (yyjson_is_arr(jsonVal)) - { + if (yyjson_is_arr(jsonVal)) { FFPercentageTypeFlags flags = 0; yyjson_val* item; size_t idx, max; - yyjson_arr_foreach(jsonVal, idx, max, item) - { + yyjson_arr_foreach (jsonVal, idx, max, item) { const char* flag = yyjson_get_str(item); - if (!flag) + if (!flag) { return "Error: percent.type: invalid flag string"; - if (ffStrEqualsIgnCase(flag, "num")) + } + if (ffStrEqualsIgnCase(flag, "num")) { flags |= FF_PERCENTAGE_TYPE_NUM_BIT; - else if (ffStrEqualsIgnCase(flag, "bar")) + } else if (ffStrEqualsIgnCase(flag, "bar")) { flags |= FF_PERCENTAGE_TYPE_BAR_BIT; - else if (ffStrEqualsIgnCase(flag, "hide-others")) + } else if (ffStrEqualsIgnCase(flag, "hide-others")) { flags |= FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT; - else if (ffStrEqualsIgnCase(flag, "num-color")) + } else if (ffStrEqualsIgnCase(flag, "num-color")) { flags |= FF_PERCENTAGE_TYPE_NUM_COLOR_BIT; - else if (ffStrEqualsIgnCase(flag, "bar-monochrome")) + } else if (ffStrEqualsIgnCase(flag, "bar-monochrome")) { flags |= FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT; - else + } else { return "Error: percent.type: unknown flag string"; + } } *result = flags; @@ -53,8 +51,7 @@ const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFl return "Error: usage: percent.type must be a number or an array of strings"; } -void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, const FFModuleArgs* module) -{ +void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, const FFModuleArgs* module) { uint8_t green = config.green, yellow = config.yellow; assert(green <= 100 && yellow <= 100); @@ -65,30 +62,24 @@ void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConf uint8_t blocksPercent = (uint8_t) (percent / 100.0 * options->barWidth + 0.5); assert(blocksPercent <= options->barWidth); - if(!borderAsValue && options->barBorderLeft.length) - { - if(!options->pipe && options->barColorBorder.length > 0) + if (!borderAsValue && options->barBorderLeft.length) { + if (!options->pipe && options->barColorBorder.length > 0) { ffStrbufAppendF(buffer, "\e[%sm", options->barColorBorder.chars); + } ffStrbufAppend(buffer, &options->barBorderLeft); } - if (percent == -DBL_MAX) - { + if (percent == -DBL_MAX) { // Use total color for simplification - if(!options->pipe && options->barColorTotal.length > 0) + if (!options->pipe && options->barColorTotal.length > 0) { ffStrbufAppendS(buffer, "\e[" FF_COLOR_FG_LIGHT_BLACK "m"); - - for (uint8_t i = 0; i < options->barWidth; ++i) - { - ffStrbufAppend(buffer, borderAsValue && i == 0 - ? &options->barBorderLeft - : borderAsValue && i == options->barWidth - 1 - ? &options->barBorderRight - : &options->barCharTotal); } - } - else - { + + for (uint8_t i = 0; i < options->barWidth; ++i) { + ffStrbufAppend(buffer, borderAsValue && i == 0 ? &options->barBorderLeft : borderAsValue && i == options->barWidth - 1 ? &options->barBorderRight + : &options->barCharTotal); + } + } else { const char* colorGreen = options->percentColorGreen.chars; const char* colorYellow = options->percentColorYellow.chars; const char* colorRed = options->percentColorRed.chars; @@ -98,76 +89,70 @@ 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) - { + if (!options->pipe && options->barColorElapsed.length > 0 && monochrome) { const char* color = NULL; - if (!autoColorElapsed) + 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; + } 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 && !monochrome) - { + for (uint8_t i = 0; i < blocksPercent; ++i) { + if (!options->pipe && options->barColorElapsed.length > 0 && !monochrome) { 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) + if (i == section2Begin) { ffStrbufAppendF(buffer, "\e[%sm", (green > yellow ? colorGreen : colorRed)); - else if (i == section1Begin) + } else if (i == section1Begin) { ffStrbufAppendF(buffer, "\e[%sm", colorYellow); - else if (i == 0) + } else if (i == 0) { ffStrbufAppendF(buffer, "\e[%sm", (green <= yellow ? colorGreen : colorRed)); + } } - ffStrbufAppend(buffer, borderAsValue && i == 0 - ? &options->barBorderLeftElapsed - : borderAsValue && i == options->barWidth - 1 - ? &options->barBorderRightElapsed - : &options->barCharElapsed); + ffStrbufAppend(buffer, borderAsValue && i == 0 ? &options->barBorderLeftElapsed : borderAsValue && i == options->barWidth - 1 ? &options->barBorderRightElapsed + : &options->barCharElapsed); } - if (blocksPercent < options->barWidth) - { - if(!options->pipe && options->barColorTotal.length > 0) + if (blocksPercent < options->barWidth) { + if (!options->pipe && options->barColorTotal.length > 0) { ffStrbufAppendF(buffer, "\e[%sm", options->barColorTotal.chars); - for (uint8_t i = blocksPercent; i < options->barWidth; ++i) - { - ffStrbufAppend(buffer, borderAsValue && i == 0 - ? &options->barBorderLeft - : borderAsValue && i == options->barWidth - 1 - ? &options->barBorderRight - : &options->barCharTotal); + } + for (uint8_t i = blocksPercent; i < options->barWidth; ++i) { + ffStrbufAppend(buffer, borderAsValue && i == 0 ? &options->barBorderLeft : borderAsValue && i == options->barWidth - 1 ? &options->barBorderRight + : &options->barCharTotal); } } } - if(!borderAsValue && options->barBorderRight.length) - { - if(!options->pipe && options->barColorBorder.length > 0) + if (!borderAsValue && options->barBorderRight.length) { + if (!options->pipe && options->barColorBorder.length > 0) { ffStrbufAppendF(buffer, "\e[%sm", options->barColorBorder.chars); + } ffStrbufAppend(buffer, &options->barBorderRight); } - if(!options->pipe && (options->barColorElapsed.length > 0 || options->barColorTotal.length > 0 || options->barColorBorder.length > 0)) - { + if (!options->pipe && (options->barColorElapsed.length > 0 || options->barColorTotal.length > 0 || options->barColorBorder.length > 0)) { ffStrbufAppendS(buffer, FASTFETCH_TEXT_MODIFIER_RESET); appendOutputColor(buffer, module); } } -void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, bool parentheses, const FFModuleArgs* module) -{ +void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, bool parentheses, const FFModuleArgs* module) { uint8_t green = config.green, yellow = config.yellow; assert(green <= 100 && yellow <= 100); @@ -176,61 +161,57 @@ void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConf bool colored = !!(percentType & FF_PERCENTAGE_TYPE_NUM_COLOR_BIT); - if (parentheses) + if (parentheses) { ffStrbufAppendC(buffer, '('); + } - if (colored && !options->pipe) - { + if (colored && !options->pipe) { const char* colorGreen = options->percentColorGreen.chars; const char* colorYellow = options->percentColorYellow.chars; const char* colorRed = options->percentColorRed.chars; - if(percent == -DBL_MAX) + if (percent == -DBL_MAX) { ffStrbufAppendS(buffer, "\e[" FF_COLOR_FG_LIGHT_BLACK "m"); - else if(green <= yellow) - { - if (percent > yellow) + } else if (green <= yellow) { + if (percent > yellow) { ffStrbufAppendF(buffer, "\e[%sm", colorRed); - else if (percent > green) + } else if (percent > green) { ffStrbufAppendF(buffer, "\e[%sm", colorYellow); - else + } else { ffStrbufAppendF(buffer, "\e[%sm", colorGreen); - } - else - { - if (percent < yellow) + } + } else { + if (percent < yellow) { ffStrbufAppendF(buffer, "\e[%sm", colorRed); - else if (percent < green) + } else if (percent < green) { ffStrbufAppendF(buffer, "\e[%sm", colorYellow); - else + } else { ffStrbufAppendF(buffer, "\e[%sm", colorGreen); + } } } - ffStrbufAppendF(buffer, "%*.*f%s%%", options->percentWidth, options->percentNdigits, percent, - options->percentSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : ""); + ffStrbufAppendF(buffer, "%*.*f%s%%", options->percentWidth, options->percentNdigits, percent, options->percentSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : ""); - if (colored && !options->pipe) - { + if (colored && !options->pipe) { ffStrbufAppendS(buffer, FASTFETCH_TEXT_MODIFIER_RESET); appendOutputColor(buffer, module); } - if (parentheses) + if (parentheses) { ffStrbufAppendC(buffer, ')'); + } } -bool ffPercentParseCommandOptions(const char* key, const char* subkey, const char* value, FFPercentageModuleConfig* config) -{ - if (!ffStrStartsWithIgnCase(subkey, "percent-")) +bool ffPercentParseCommandOptions(const char* key, const char* subkey, const char* value, FFPercentageModuleConfig* config) { + if (!ffStrStartsWithIgnCase(subkey, "percent-")) { return false; + } subkey += strlen("percent-"); - if (ffStrEqualsIgnCase(subkey, "green")) - { + if (ffStrEqualsIgnCase(subkey, "green")) { uint32_t num = ffOptionParseUInt32(key, value); - if (num > 100) - { + if (num > 100) { fprintf(stderr, "Error: usage: %s must be between 0 and 100\n", key); exit(480); } @@ -238,11 +219,9 @@ bool ffPercentParseCommandOptions(const char* key, const char* subkey, const cha return true; } - if (ffStrEqualsIgnCase(subkey, "yellow")) - { + if (ffStrEqualsIgnCase(subkey, "yellow")) { uint32_t num = ffOptionParseUInt32(key, value); - if (num > 100) - { + if (num > 100) { fprintf(stderr, "Error: usage: %s must be between 0 and 100\n", key); exit(480); } @@ -250,8 +229,7 @@ bool ffPercentParseCommandOptions(const char* key, const char* subkey, const cha return true; } - if (ffStrEqualsIgnCase(subkey, "type")) - { + if (ffStrEqualsIgnCase(subkey, "type")) { config->type = (FFPercentageTypeFlags) ffOptionParseUInt32(key, value); return true; } @@ -259,25 +237,22 @@ bool ffPercentParseCommandOptions(const char* key, const char* subkey, const cha return false; } -bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageModuleConfig* config) -{ +bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageModuleConfig* config) { assert(key); - if (!unsafe_yyjson_equals_str(key, "percent")) + if (!unsafe_yyjson_equals_str(key, "percent")) { return false; + } - if (!yyjson_is_obj(value)) - { + if (!yyjson_is_obj(value)) { fprintf(stderr, "Error: usage: %s must be an object\n", unsafe_yyjson_get_str(key)); exit(480); } yyjson_val* greenVal = yyjson_obj_get(value, "green"); - if (greenVal) - { + if (greenVal) { int num = yyjson_get_int(greenVal); - if (num < 0 || num > 100) - { + if (num < 0 || num > 100) { fputs("Error: usage: percent.green must be between 0 and 100\n", stderr); exit(480); } @@ -285,11 +260,9 @@ bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageMo } yyjson_val* yellowVal = yyjson_obj_get(value, "yellow"); - if (yellowVal) - { + if (yellowVal) { int num = yyjson_get_int(yellowVal); - if (num < 0 || num > 100) - { + if (num < 0 || num > 100) { fputs("Error: usage: percent.yellow must be between 0 and 100\n", stderr); exit(480); } @@ -297,11 +270,9 @@ bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageMo } yyjson_val* typeVal = yyjson_obj_get(value, "type"); - if (typeVal) - { + if (typeVal) { const char* error = ffPercentParseTypeJsonConfig(typeVal, &config->type); - if (error) - { + if (error) { fputs(error, stderr); exit(480); } @@ -310,8 +281,7 @@ bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageMo return true; } -void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig config) -{ +void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig config) { yyjson_mut_val* percent = yyjson_mut_obj_add_obj(doc, module, "percent"); yyjson_mut_obj_add_uint(doc, percent, "green", config.green); yyjson_mut_obj_add_uint(doc, percent, "yellow", config.yellow); diff --git a/src/common/impl/printing.c b/src/common/impl/printing.c index efb9a2e90..c9f43c01c 100644 --- a/src/common/impl/printing.c +++ b/src/common/impl/printing.c @@ -3,145 +3,146 @@ #include "common/textModifier.h" #include "logo/logo.h" -void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType) -{ +void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType) { ffLogoPrintLine(); - //This is used by --set-keyless, in this case we want neither the module name nor the separator - if(moduleName == NULL) + // This is used by --set-keyless, in this case we want neither the module name nor the separator + if (moduleName == NULL) { return; + } - //This is used as a magic value for hiding keys - if (!(moduleArgs && ffStrbufEqualS(&moduleArgs->key, " ")) && instance.config.display.keyType != FF_MODULE_KEY_TYPE_NONE) - { + // This is used as a magic value for hiding keys + if (!(moduleArgs && ffStrbufEqualS(&moduleArgs->key, " ")) && instance.config.display.keyType != FF_MODULE_KEY_TYPE_NONE) { ffPrintCharTimes(' ', instance.config.display.keyPaddingLeft); - if(!instance.config.display.pipe) - { + if (!instance.config.display.pipe) { fputs(FASTFETCH_TEXT_MODIFIER_RESET, stdout); - if (instance.config.display.brightColor) + if (instance.config.display.brightColor) { fputs(FASTFETCH_TEXT_MODIFIER_BOLT, stdout); + } - if(moduleArgs && !(printType & FF_PRINT_TYPE_NO_CUSTOM_KEY_COLOR) && moduleArgs->keyColor.length > 0) + if (moduleArgs && !(printType & FF_PRINT_TYPE_NO_CUSTOM_KEY_COLOR) && moduleArgs->keyColor.length > 0) { ffPrintColor(&moduleArgs->keyColor); - else + } else { ffPrintColor(&instance.config.display.colorKeys); + } } - if (instance.config.display.keyType & FF_MODULE_KEY_TYPE_ICON && moduleArgs && moduleArgs->keyIcon.length > 0) + if (instance.config.display.keyType & FF_MODULE_KEY_TYPE_ICON && moduleArgs && moduleArgs->keyIcon.length > 0) { ffStrbufWriteTo(&moduleArgs->keyIcon, stdout); + } - if (instance.config.display.keyType & FF_MODULE_KEY_TYPE_STRING) - { + if (instance.config.display.keyType & FF_MODULE_KEY_TYPE_STRING) { ffPrintCharTimes(' ', instance.config.display.keyType >> FF_MODULE_KEY_TYPE_SPACE_SHIFT); - //NULL check is required for modules with custom keys, e.g. disk with the folder path - if((printType & FF_PRINT_TYPE_NO_CUSTOM_KEY) || !moduleArgs || moduleArgs->key.length == 0) - { + // NULL check is required for modules with custom keys, e.g. disk with the folder path + if ((printType & FF_PRINT_TYPE_NO_CUSTOM_KEY) || !moduleArgs || moduleArgs->key.length == 0) { fputs(moduleName, stdout); - if(moduleIndex > 0) + if (moduleIndex > 0) { printf(" %hhu", moduleIndex); - } - else - { + } + } else { FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); FF_PARSE_FORMAT_STRING_CHECKED(&key, &moduleArgs->key, ((FFformatarg[]) { - FF_ARG(moduleIndex, "index"), - FF_ARG(moduleArgs->keyIcon, "icon"), - })); + FF_ARG(moduleIndex, "index"), + FF_ARG(moduleArgs->keyIcon, "icon"), + })); ffStrbufWriteTo(&key, stdout); } } - if(!instance.config.display.pipe) - { + if (!instance.config.display.pipe) { fputs(FASTFETCH_TEXT_MODIFIER_RESET, stdout); ffPrintColor(&instance.config.display.colorSeparator); } ffStrbufWriteTo(&instance.config.display.keyValueSeparator, stdout); - if(!instance.config.display.pipe && instance.config.display.colorSeparator.length) + if (!instance.config.display.pipe && instance.config.display.colorSeparator.length) { fputs(FASTFETCH_TEXT_MODIFIER_RESET, stdout); + } - if (!(printType & FF_PRINT_TYPE_NO_CUSTOM_KEY_WIDTH)) - { + if (!(printType & FF_PRINT_TYPE_NO_CUSTOM_KEY_WIDTH)) { uint32_t keyWidth = moduleArgs && moduleArgs->keyWidth > 0 ? moduleArgs->keyWidth : instance.config.display.keyWidth; - if (keyWidth > 0) + if (keyWidth > 0) { printf("\e[%uG", (unsigned) (keyWidth + instance.state.logoWidth)); + } } } - if(!instance.config.display.pipe) - { + if (!instance.config.display.pipe) { fputs(FASTFETCH_TEXT_MODIFIER_RESET, stdout); - if (moduleArgs && moduleArgs->outputColor.length) + if (moduleArgs && moduleArgs->outputColor.length) { ffPrintColor(&moduleArgs->outputColor); - else if (instance.config.display.colorOutput.length) + } else if (instance.config.display.colorOutput.length) { ffPrintColor(&instance.config.display.colorOutput); + } } } -void ffPrintFormat(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, uint32_t numArgs, const FFformatarg* arguments) -{ +void ffPrintFormat(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, uint32_t numArgs, const FFformatarg* arguments) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (moduleArgs) + if (moduleArgs) { ffParseFormatString(&buffer, &moduleArgs->outputFormat, numArgs, arguments); - else + } else { ffStrbufAppendS(&buffer, "unknown"); + } ffPrintLogoAndKey(moduleName, moduleIndex, moduleArgs, printType); ffStrbufPutTo(&buffer, stdout); } -void ffPrintError(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, const char* message, ...) -{ - if(!instance.config.display.showErrors) +void ffPrintError(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, const char* message, ...) { + if (!instance.config.display.showErrors) { return; + } ffPrintLogoAndKey(moduleName, moduleIndex, moduleArgs, printType); - if(!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs(FASTFETCH_TEXT_MODIFIER_ERROR, stdout); + } va_list arguments; va_start(arguments, message); vprintf(message, arguments); va_end(arguments); - if(!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs(FASTFETCH_TEXT_MODIFIER_RESET, stdout); + } putchar('\n'); } -void ffPrintColor(const FFstrbuf* colorValue) -{ - //If the color is not set, this would reset in \033[m, which resets everything. - //So we only print it, if the main color is at least one char. - if(colorValue->length == 0) +void ffPrintColor(const FFstrbuf* colorValue) { + // If the color is not set, this would reset in \033[m, which resets everything. + // So we only print it, if the main color is at least one char. + if (colorValue->length == 0) { return; + } printf("\e[%sm", colorValue->chars); } -void ffPrintCharTimes(char c, uint32_t times) -{ - if(times == 0) +void ffPrintCharTimes(char c, uint32_t times) { + if (times == 0) { return; + } - if(times == 1) - { + if (times == 1) { putchar(c); return; } char str[32]; - memset(str, c, sizeof(str)); //2 instructions when compiling with AVX2 enabled - for(uint32_t i = sizeof(str); i <= times; i += (uint32_t)sizeof(str)) + memset(str, c, sizeof(str)); // 2 instructions when compiling with AVX2 enabled + for (uint32_t i = sizeof(str); i <= times; i += (uint32_t) sizeof(str)) { fwrite(str, 1, sizeof(str), stdout); + } uint32_t remaining = times % sizeof(str); - if(remaining > 0) + if (remaining > 0) { fwrite(str, 1, remaining, stdout); + } } diff --git a/src/common/impl/processing_linux.c b/src/common/impl/processing_linux.c index 472cec5a3..a24d3f6c0 100644 --- a/src/common/impl/processing_linux.c +++ b/src/common/impl/processing_linux.c @@ -13,28 +13,28 @@ #include #if !(__ANDROID__ || __OpenBSD__) - #include +# include #endif #if defined(__FreeBSD__) || defined(__APPLE__) - #include - #include - #include +# include +# include +# include #endif #if defined(__APPLE__) - #include +# include #elif defined(__sun) - #include +# include #elif defined(__OpenBSD__) - #include - #include - #include +# include +# include +# include #elif defined(__NetBSD__) - #include - #include +# include +# include #elif defined(__HAIKU__) - #include - #include +# include +# include #endif #ifndef environ @@ -43,31 +43,30 @@ extern char** environ; enum { FF_PIPE_BUFSIZ = 8192 }; -static inline int ffPipe2(int* fds, int flags) -{ - #ifndef FF_HAVE_PIPE2 - if(pipe(fds) == -1) - return -1; - fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL) | flags); - fcntl(fds[1], F_SETFL, fcntl(fds[1], F_GETFL) | flags); - return 0; - #else - return pipe2(fds, flags); - #endif +static inline int ffPipe2(int* fds, int flags) { +#ifndef FF_HAVE_PIPE2 + if (pipe(fds) == -1) { + return -1; + } + fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL) | flags); + fcntl(fds[1], F_SETFL, fcntl(fds[1], F_GETFL) | flags); + return 0; +#else + return pipe2(fds, flags); +#endif } - // Not thread-safe -const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle) -{ +const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle) { int pipes[2]; - if(ffPipe2(pipes, O_CLOEXEC) == -1) + if (ffPipe2(pipes, O_CLOEXEC) == -1) { return "pipe() failed"; + } pid_t childPid = -1; int nullFile = ffGetNullFD(); - #if !(__ANDROID__ || __OpenBSD__) +#if !(__ANDROID__ || __OpenBSD__) // NetBSD / Darwin: native syscall // Linux (glibc): clone3-execve @@ -83,33 +82,29 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* static char* oldLang = NULL; static int langIndex = -1; - if (langIndex >= 0) - { + if (langIndex >= 0) { // Found before if (oldLang) // oldLang was set only if it needed to be changed { - if (environ[langIndex] != oldLang) - { + if (environ[langIndex] != oldLang) { // environ is changed outside of this function langIndex = -1; - } - else + } else { environ[langIndex] = (char*) "LANG=C.UTF-8"; + } } } - if (langIndex < 0) - { - for (int i = 0; environ[i] != NULL; i++) - { - if (ffStrStartsWith(environ[i], "LANG=")) - { + if (langIndex < 0) { + for (int i = 0; environ[i] != NULL; i++) { + if (ffStrStartsWith(environ[i], "LANG=")) { langIndex = i; const char* langValue = environ[i] + 5; // Skip "LANG=" if (ffStrEqualsIgnCase(langValue, "C") || ffStrStartsWithIgnCase(environ[i], "C.") || ffStrEqualsIgnCase(langValue, "en_US") || - ffStrStartsWithIgnCase(langValue, "en_US.")) + ffStrStartsWithIgnCase(langValue, "en_US.")) { break; // No need to change LANG + } oldLang = environ[i]; environ[i] = (char*) "LANG=C.UTF-8"; // Set LANG to C.UTF-8 for consistent output break; @@ -119,33 +114,32 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* int ret = posix_spawnp(&childPid, argv[0], &file_actions, NULL, argv, environ); - if (oldLang) + if (oldLang) { environ[langIndex] = oldLang; + } posix_spawn_file_actions_destroy(&file_actions); - if (ret != 0) - { + if (ret != 0) { close(pipes[0]); close(pipes[1]); - if (ret == ENOENT) + if (ret == ENOENT) { return "command not found"; + } return "posix_spawnp() failed"; } - #else +#else // https://github.com/termux/termux-packages/issues/25369 childPid = fork(); - if(childPid == -1) - { + if (childPid == -1) { close(pipes[0]); close(pipes[1]); return "fork() failed"; } - if(childPid == 0) - { + if (childPid == 0) { // Child process dup2(pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO); dup2(nullFile, useStdErr ? STDOUT_FILENO : STDERR_FILENO); @@ -154,7 +148,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* _exit(127); } - #endif +#endif close(pipes[1]); outHandle->pid = childPid; @@ -162,8 +156,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* return NULL; } -const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) -{ +const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { assert(handle->pipeRead != -1); assert(handle->pid != -1); @@ -174,20 +167,15 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) handle->pid = -1; char str[FF_PIPE_BUFSIZ]; - for (;;) - { - if (timeout >= 0) - { - struct pollfd pollfd = { childPipeFd, POLLIN, 0 }; + for (;;) { + if (timeout >= 0) { + struct pollfd pollfd = {childPipeFd, POLLIN, 0}; int pollret = poll(&pollfd, 1, timeout); - if (pollret == 0) - { + if (pollret == 0) { kill(childPid, SIGTERM); waitpid(childPid, NULL, 0); return "poll(&pollfd, 1, timeout) timeout (try increasing --processing-timeout)"; - } - else if (pollret < 0 || (pollfd.revents & POLLERR)) - { + } else if (pollret < 0 || (pollfd.revents & POLLERR)) { kill(childPid, SIGTERM); waitpid(childPid, NULL, 0); return pollret < 0 @@ -197,63 +185,65 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) } ssize_t nRead = read(childPipeFd, str, FF_PIPE_BUFSIZ); - if (nRead > 0) + if (nRead > 0) { ffStrbufAppendNS(buffer, (uint32_t) nRead, str); - else if (nRead == 0) - { + } else if (nRead == 0) { int stat_loc = 0; - if (childPid > 0 && waitpid(childPid, &stat_loc, 0) == childPid) - { - if (!WIFEXITED(stat_loc)) + if (childPid > 0 && waitpid(childPid, &stat_loc, 0) == childPid) { + if (!WIFEXITED(stat_loc)) { return "child process exited abnormally"; - if (WEXITSTATUS(stat_loc) == 127) + } + if (WEXITSTATUS(stat_loc) == 127) { return "command not found"; + } // We only handle 127 as an error. See `getTerminalVersionUrxvt` in `terminalshell.c` return NULL; } return NULL; - } - else if (nRead < 0) + } else if (nRead < 0) { break; + } } return "read(childPipeFd, str, FF_PIPE_BUFSIZ) failed"; } -void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, const char** exeName, FFstrbuf* exePath) -{ +void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, const char** exeName, FFstrbuf* exePath) { assert(processName->length > 0); ffStrbufClear(exe); - if (exePath) ffStrbufClear(exePath); + if (exePath) { + ffStrbufClear(exePath); + } - #if defined(__linux__) || defined(__GNU__) +#if defined(__linux__) || defined(__GNU__) char filePath[64]; - snprintf(filePath, sizeof(filePath), "/proc/%d/cmdline", (int)pid); + snprintf(filePath, sizeof(filePath), "/proc/%d/cmdline", (int) pid); - if(ffReadFileBuffer(filePath, exe)) - { + if (ffReadFileBuffer(filePath, exe)) { const char* p = exe->chars; uint32_t len = (uint32_t) strlen(p); - if (len + 1 < exe->length) - { + if (len + 1 < exe->length) { const char* name = memrchr(p, '/', len); - if (name) name++; else name = p; + if (name) { + name++; + } else { + name = p; + } // For interpreters, try to find the real script path in the arguments if (ffStrStartsWith(name, "python") - #ifndef __ANDROID__ +# ifndef __ANDROID__ || ffStrEquals(name, "guile") // for shepherd - #endif - ) - { +# 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 + for (p = p + len + 1; *p && *p == '-'; p += strlen(p) + 1) { // Skip arguments assert(p - exe->chars < exe->allocated); - if (*p) - { + } + if (*p) { len = (uint32_t) strlen(p); memmove(exe->chars, p, len + 1); } @@ -262,12 +252,11 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons assert(len < exe->allocated); exe->length = len; - ffStrbufTrimLeft(exe, '-'); //Login shells start with a dash + ffStrbufTrimLeft(exe, '-'); // Login shells start with a dash } - if (exePath) - { - snprintf(filePath, sizeof(filePath), "/proc/%d/exe", (int)pid); + if (exePath) { + snprintf(filePath, sizeof(filePath), "/proc/%d/exe", (int) pid); char buf[PATH_MAX]; ssize_t length = readlink(filePath, buf, PATH_MAX - 1); if (length > 0) // doesn't contain trailing NUL @@ -275,64 +264,68 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons buf[length] = '\0'; // When the process is a deleted executable, the resolved path is like `/usr/bin/app (deleted)` // But we can still access the binary via `/proc/pid/exe`. See #2136 - if (ffPathExists(buf, FF_PATHTYPE_ANY)) - ffStrbufSetNS(exePath, (uint32_t)length, buf); + if (ffPathExists(buf, FF_PATHTYPE_ANY)) { + ffStrbufSetNS(exePath, (uint32_t) length, buf); + } } - if (exePath->length == 0) + if (exePath->length == 0) { ffStrbufSetS(exePath, filePath); + } } - #elif defined(__APPLE__) +#elif defined(__APPLE__) size_t len = 0; - int mibs[] = { CTL_KERN, KERN_PROCARGS2, pid }; - if (sysctl(mibs, ARRAY_SIZE(mibs), NULL, &len, NULL, 0) == 0) - {// try get arg0 - //don't know why if don't let len longer, proArgs2 and len will change during the following sysctl() in old MacOS version. + int mibs[] = {CTL_KERN, KERN_PROCARGS2, pid}; + if (sysctl(mibs, ARRAY_SIZE(mibs), NULL, &len, NULL, 0) == 0) { // try get arg0 + // don't know why if don't let len longer, proArgs2 and len will change during the following sysctl() in old MacOS version. len++; FF_AUTO_FREE char* const procArgs2 = malloc(len); - if (sysctl(mibs, ARRAY_SIZE(mibs), procArgs2, &len, NULL, 0) == 0) - { + if (sysctl(mibs, ARRAY_SIZE(mibs), procArgs2, &len, NULL, 0) == 0) { // https://gist.github.com/nonowarn/770696#file-getargv-c-L46 uint32_t argc = *(uint32_t*) procArgs2; const char* realExePath = procArgs2 + sizeof(argc); const char* arg0 = memchr(realExePath, '\0', len - (size_t) (realExePath - procArgs2)); - if (exePath) + if (exePath) { ffStrbufSetNS(exePath, (uint32_t) (arg0 - realExePath), realExePath); - - do arg0++; while (*arg0 == '\0'); - assert(arg0 < procArgs2 + len); - - if (argc > 1) - { - // #977 - const char* p = strrchr(arg0, '/'); - if (p) - p++; - else - p = arg0; - if (ffStrStartsWithIgnCase(p, "python")) // /opt/homebrew/Cellar/python@3.12/3.12.3/Frameworks/Python.framework/Versions/3.12/Resources/Python.app/Contents/MacOS/Python /Users/carter/.local/bin/xonsh - arg0 = p + strlen(p) + 1; } - if (*arg0 == '-') arg0++; // Login shells + do { + arg0++; + } while (*arg0 == '\0'); + assert(arg0 < procArgs2 + len); + + if (argc > 1) { + // #977 + const char* p = strrchr(arg0, '/'); + if (p) { + p++; + } else { + p = arg0; + } + if (ffStrStartsWithIgnCase(p, "python")) { // /opt/homebrew/Cellar/python@3.12/3.12.3/Frameworks/Python.framework/Versions/3.12/Resources/Python.app/Contents/MacOS/Python /Users/carter/.local/bin/xonsh + arg0 = p + strlen(p) + 1; + } + } + + if (*arg0 == '-') { + arg0++; // Login shells + } ffStrbufSetS(exe, arg0); } } - if (exePath || exe->length == 0) - { + if (exePath || exe->length == 0) { char buf[PROC_PIDPATHINFO_MAXSIZE]; int length = proc_pidpath(pid, buf, ARRAY_SIZE(buf)); - if (length > 0) - { - if (exe->length == 0) + if (length > 0) { + if (exe->length == 0) { ffStrbufSetNS(exe, (uint32_t) length, buf); - if (exePath) - { + } + if (exePath) { // We don't use exec_path above as exePath because it's a relative path and can be different // from the actual executable being run (for example, when the original file is moved) ffStrbufSetNS(exePath, (uint32_t) length, buf); @@ -340,142 +333,159 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons } } - #elif defined(__FreeBSD__) || defined(__NetBSD__) +#elif defined(__FreeBSD__) || defined(__NetBSD__) size_t size = ARG_MAX; FF_AUTO_FREE char* args = malloc(size); static_assert(ARG_MAX > PATH_MAX, ""); - if(exePath && sysctl( - (int[]){CTL_KERN, - #if __FreeBSD__ - KERN_PROC, KERN_PROC_PATHNAME, pid - #else - KERN_PROC_ARGS, pid, KERN_PROC_PATHNAME - #endif - }, 4, - args, &size, - NULL, 0 - ) == 0) + if (exePath && sysctl((int[]) {CTL_KERN, +# if __FreeBSD__ + KERN_PROC, + KERN_PROC_PATHNAME, + pid +# else + KERN_PROC_ARGS, + pid, + KERN_PROC_PATHNAME +# endif + }, + 4, + args, + &size, + NULL, + 0) == 0) ffStrbufSetNS(exePath, (uint32_t) (size - 1), args); size = ARG_MAX; - if(sysctl( - (int[]){CTL_KERN, - #if __FreeBSD__ - KERN_PROC, KERN_PROC_ARGS, pid - #else - KERN_PROC_ARGS, pid, KERN_PROC_ARGV, - #endif - }, 4, - args, &size, - NULL, 0 - ) == 0) - { + if (sysctl( + (int[]) {CTL_KERN, +# if __FreeBSD__ + KERN_PROC, + KERN_PROC_ARGS, + pid +# else + KERN_PROC_ARGS, + pid, + KERN_PROC_ARGV, +# endif + }, + 4, + args, + &size, + NULL, + 0) == 0) { char* arg0 = args; size_t arg0Len = strlen(args); - if (size > arg0Len + 1) - { + if (size > arg0Len + 1) { char* p = (char*) memrchr(args, '/', arg0Len); - if (p) + if (p) { p++; - else + } else { p = arg0; + } if (ffStrStartsWith(p, "python")) // /usr/local/bin/python3.9 /home/carter/.local/bin/xonsh { arg0 += arg0Len + 1; } } - if (arg0[0] == '-') arg0++; + if (arg0[0] == '-') { + arg0++; + } ffStrbufSetS(exe, arg0); } - #elif defined(__sun) +#elif defined(__sun) char filePath[128]; snprintf(filePath, sizeof(filePath), "/proc/%d/psinfo", (int) pid); psinfo_t proc; - if (ffReadFileData(filePath, sizeof(proc), &proc) == sizeof(proc)) - { + if (ffReadFileData(filePath, sizeof(proc), &proc) == sizeof(proc)) { const char* args = proc.pr_psargs; - if (args[0] == '-') ++args; + if (args[0] == '-') { + ++args; + } const char* end = strchr(args, ' '); ffStrbufSetNS(exe, end ? (uint32_t) (end - args) : (uint32_t) strlen(args), args); } - if (exePath) - { + if (exePath) { snprintf(filePath, sizeof(filePath), "/proc/%d/path/a.out", (int) pid); char buf[PATH_MAX]; ssize_t length = readlink(filePath, buf, PATH_MAX - 1); if (length > 0) // doesn't contain trailing NUL { buf[length] = '\0'; - ffStrbufSetNS(exePath, (uint32_t)length, buf); + ffStrbufSetNS(exePath, (uint32_t) length, buf); } } - #elif defined(__OpenBSD__) +#elif defined(__OpenBSD__) kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); int count = 0; const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count); - if (proc) - { + if (proc) { char** argv = kvm_getargv(kd, proc, 0); - if (argv) - { + if (argv) { const char* arg0 = argv[0]; - if (arg0[0] == '-') arg0++; + if (arg0[0] == '-') { + arg0++; + } ffStrbufSetS(exe, arg0); } } kvm_close(kd); - #elif defined(__HAIKU__) +#elif defined(__HAIKU__) image_info info; int32 cookie = 0; - while (get_next_image_info(pid, &cookie, &info) == B_OK) - { - if (info.type != B_APP_IMAGE) continue; + while (get_next_image_info(pid, &cookie, &info) == B_OK) { + if (info.type != B_APP_IMAGE) { + continue; + } ffStrbufSetS(exe, info.name); - if (exePath) + if (exePath) { ffStrbufSet(exePath, exe); + } break; } - #endif +#endif - if(exe->length == 0) + if (exe->length == 0) { ffStrbufSet(exe, processName); + } assert(exe->length > 0); uint32_t lastSlashIndex = ffStrbufLastIndexC(exe, '/'); - if(lastSlashIndex < exe->length) + if (lastSlashIndex < exe->length) { *exeName = exe->chars + lastSlashIndex + 1; + } } -const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, int32_t* tty) -{ - if (pid <= 0) +const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, int32_t* tty) { + if (pid <= 0) { return "Invalid pid"; + } - #if defined(__linux__) || defined(__GNU__) +#if defined(__linux__) || defined(__GNU__) char procFilePath[64]; - #if __linux__ +# if __linux__ if (ppid || tty) - #endif +# endif { - snprintf(procFilePath, sizeof(procFilePath), "/proc/%d/stat", (int)pid); + 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) + if (nRead <= 8) { return "ffReadFileData(/proc/pid/stat, PROC_FILE_BUFFSIZ-1, buf) failed"; + } buf[nRead] = '\0'; // pid (comm) state ppid pgrp session tty const char* pState = NULL; @@ -483,175 +493,180 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i { // comm in `/proc/pid/stat` is not encoded, and may contain ' ', ')' or even `\n` const char* start = memchr(buf, '(', (size_t) nRead); - if (!start) + if (!start) { return "memchr(stat, '(') failed"; + } start++; const char* end = memrchr(start, ')', (size_t) nRead - (size_t) (start - buf)); - if (!end) + if (!end) { return "memrchr(stat, ')') failed"; + } ffStrbufSetNS(name, (uint32_t) (end - start), start); ffStrbufTrimRightSpace(name); - if (name->chars[0] == '\0') + if (name->chars[0] == '\0') { return "process name is empty"; + } pState = end + 2; // skip ") " } - #if !__linux__ +# if !__linux__ if (ppid || tty) - #endif +# endif { int ppid_, tty_; - if(sscanf(pState + 2, "%d %*d %*d %d", &ppid_, &tty_) < 2) + if (sscanf(pState + 2, "%d %*d %*d %d", &ppid_, &tty_) < 2) { return "sscanf(stat) failed"; + } - if (ppid) + if (ppid) { *ppid = (pid_t) ppid_; - if (tty) + } + if (tty) { *tty = tty_ & 0xFF; + } } } - #if __linux__ - else - { - snprintf(procFilePath, sizeof(procFilePath), "/proc/%d/comm", (int)pid); +# if __linux__ + else { + snprintf(procFilePath, sizeof(procFilePath), "/proc/%d/comm", (int) pid); ssize_t nRead = ffReadFileBuffer(procFilePath, name); - if(nRead <= 0) + if (nRead <= 0) { return "ffReadFileBuffer(/proc/pid/comm, name) failed"; + } ffStrbufTrimRightSpace(name); } - #endif +# endif - #elif defined(__APPLE__) +#elif defined(__APPLE__) struct kinfo_proc proc; size_t size = sizeof(proc); - if(sysctl( - (int[]){CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}, 4, - &proc, &size, - NULL, 0 - )) + if (sysctl( + (int[]) {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}, 4, &proc, &size, NULL, 0)) { return "sysctl(KERN_PROC_PID) failed"; + } - ffStrbufSetS(name, proc.kp_proc.p_comm); //trancated to 16 chars - if (ppid) - *ppid = (pid_t)proc.kp_eproc.e_ppid; - if (tty) - { + ffStrbufSetS(name, proc.kp_proc.p_comm); // trancated to 16 chars + if (ppid) { + *ppid = (pid_t) proc.kp_eproc.e_ppid; + } + if (tty) { *tty = ((proc.kp_eproc.e_tdev >> 24) & 0xFF) == 0x10 ? proc.kp_eproc.e_tdev & 0xFFFFFF : -1; } - #elif defined(__FreeBSD__) +#elif defined(__FreeBSD__) - #ifdef __DragonFly__ - #define ki_comm kp_comm - #define ki_ppid kp_ppid - #define ki_tdev kp_tdev - #define ki_flag kp_flags - #endif +# ifdef __DragonFly__ +# define ki_comm kp_comm +# define ki_ppid kp_ppid +# define ki_tdev kp_tdev +# define ki_flag kp_flags +# endif struct kinfo_proc proc; size_t size = sizeof(proc); - if(sysctl( - (int[]){CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}, 4, - &proc, &size, - NULL, 0 - )) + if (sysctl( + (int[]) {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}, 4, &proc, &size, NULL, 0)) { return "sysctl(KERN_PROC_PID) failed"; - - ffStrbufSetS(name, proc.ki_comm); - if (ppid) - *ppid = (pid_t)proc.ki_ppid; - if (tty) - { - if (proc.ki_tdev != NODEV && proc.ki_flag & P_CONTROLT) - { - const char* ttyName = devname(proc.ki_tdev, S_IFCHR); - if (ffStrStartsWith(ttyName, "pts/")) - *tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); - else - *tty = -1; - } - else - *tty = -1; } - #elif defined(__NetBSD__) + ffStrbufSetS(name, proc.ki_comm); + if (ppid) { + *ppid = (pid_t) proc.ki_ppid; + } + if (tty) { + if (proc.ki_tdev != NODEV && proc.ki_flag & P_CONTROLT) { + const char* ttyName = devname(proc.ki_tdev, S_IFCHR); + if (ffStrStartsWith(ttyName, "pts/")) { + *tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); + } else { + *tty = -1; + } + } else { + *tty = -1; + } + } + +#elif defined(__NetBSD__) struct kinfo_proc2 proc; size_t size = sizeof(proc); - if(sysctl( - (int[]){CTL_KERN, KERN_PROC2, KERN_PROC_PID, pid, sizeof(proc), 1}, 6, - &proc, &size, - NULL, 0 - ) != 0) + if (sysctl( + (int[]) {CTL_KERN, KERN_PROC2, KERN_PROC_PID, pid, sizeof(proc), 1}, 6, &proc, &size, NULL, 0) != 0) { return "sysctl(KERN_PROC_PID) failed"; - - ffStrbufSetS(name, proc.p_comm); - if (ppid) - *ppid = (pid_t)proc.p_ppid; - if (tty) - { - if (proc.p_flag & P_CONTROLT) - { - const char* ttyName = devname(proc.p_tdev, S_IFCHR); - if (ffStrStartsWith(ttyName, "pts/")) - *tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); - else - *tty = -1; - } - else - *tty = -1; } - #elif defined(__sun) + ffStrbufSetS(name, proc.p_comm); + if (ppid) { + *ppid = (pid_t) proc.p_ppid; + } + if (tty) { + if (proc.p_flag & P_CONTROLT) { + const char* ttyName = devname(proc.p_tdev, S_IFCHR); + if (ffStrStartsWith(ttyName, "pts/")) { + *tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); + } else { + *tty = -1; + } + } else { + *tty = -1; + } + } + +#elif defined(__sun) char path[128]; snprintf(path, sizeof(path), "/proc/%d/psinfo", (int) pid); psinfo_t proc; - if (ffReadFileData(path, sizeof(proc), &proc) != sizeof(proc)) + if (ffReadFileData(path, sizeof(proc), &proc) != sizeof(proc)) { return "ffReadFileData(psinfo) failed"; + } ffStrbufSetS(name, proc.pr_fname); - if (ppid) + if (ppid) { *ppid = proc.pr_ppid; - if (tty) + } + if (tty) { *tty = (int) proc.pr_ttydev; + } - #elif defined(__OpenBSD__) +#elif defined(__OpenBSD__) kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); int count = 0; const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count); - if (proc) - { + if (proc) { ffStrbufSetS(name, proc->p_comm); - if (ppid) + if (ppid) { *ppid = proc->p_ppid; - if (tty) + } + if (tty) { *tty = (int) proc->p_tdev; + } } kvm_close(kd); - if (!proc) + if (!proc) { return "kvm_getprocs() failed"; + } - #elif defined(__HAIKU__) +#elif defined(__HAIKU__) team_info info; - if (get_team_info(pid, &info) == B_OK) - { + if (get_team_info(pid, &info) == B_OK) { ffStrbufSetS(name, info.name); - if (ppid) + if (ppid) { *ppid = info.parent; + } } FF_UNUSED(tty); - #else +#else return "Unsupported platform"; - #endif +#endif return NULL; } diff --git a/src/common/impl/processing_windows.c b/src/common/impl/processing_windows.c index e78e4fa56..768c4cc5d 100644 --- a/src/common/impl/processing_windows.c +++ b/src/common/impl/processing_windows.c @@ -11,45 +11,44 @@ enum { FF_PIPE_BUFSIZ = 8192 }; -static void argvToCmdline(char* const argv[], FFstrbuf* result) -{ +static void argvToCmdline(char* const argv[], FFstrbuf* result) { // From https://gist.github.com/jin-x/cdd641d98887524b091fb1f82a68717d FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate(); - for (int i = 0; argv[i] != NULL; i++) - { + for (int i = 0; argv[i] != NULL; i++) { ffStrbufSetS(&temp, argv[i]); // Add slash (\) before double quotes (") and duplicate slashes before it for ( uint32_t pos = ffStrbufFirstIndexC(&temp, '"'), cnt; pos != temp.length; - pos = ffStrbufNextIndexC(&temp, pos + cnt * 2, '"') - ) { + pos = ffStrbufNextIndexC(&temp, pos + cnt * 2, '"')) { cnt = 1; while (pos > 0 && temp.chars[pos - 1] == '\\') { ++cnt, --pos; } ffStrbufInsertNC(&temp, pos, cnt, '\\'); } // Add quotes around string if whitespace chars are present (with slash duplicating at the end of string) - if (ffStrbufFirstIndexS(&temp, " \t") != temp.length) - { + if (ffStrbufFirstIndexS(&temp, " \t") != temp.length) { uint32_t pos = temp.length; uint32_t cnt = 0; while (pos > 0 && temp.chars[pos - 1] == '\\') { ++cnt, --pos; } - if (cnt > 0) ffStrbufAppendNC(&temp, cnt, '\\'); + if (cnt > 0) { + ffStrbufAppendNC(&temp, cnt, '\\'); + } ffStrbufPrependC(&temp, '"'); ffStrbufAppendC(&temp, '"'); } // Add space delimiter - if (i > 0) ffStrbufAppendC(result, ' '); + if (i > 0) { + ffStrbufAppendC(result, ' '); + } ffStrbufAppend(result, &temp); ffStrbufClear(&temp); } } -const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle) -{ +const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle) { const int32_t timeout = instance.config.general.processingTimeout; wchar_t pipeName[32]; @@ -64,39 +63,36 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* FF_PIPE_BUFSIZ, FF_PIPE_BUFSIZ, 0, - NULL - ); - if (hChildPipeRead == INVALID_HANDLE_VALUE) + NULL); + if (hChildPipeRead == INVALID_HANDLE_VALUE) { return "CreateNamedPipeW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed"; + } HANDLE hChildPipeWrite = CreateFileW( pipeName, GENERIC_WRITE, 0, - &(SECURITY_ATTRIBUTES){ + &(SECURITY_ATTRIBUTES) { .nLength = sizeof(SECURITY_ATTRIBUTES), .lpSecurityDescriptor = NULL, .bInheritHandle = TRUE, }, OPEN_EXISTING, 0, - NULL - ); - if (hChildPipeWrite == INVALID_HANDLE_VALUE) + NULL); + if (hChildPipeWrite == INVALID_HANDLE_VALUE) { return "CreateFileW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed"; + } PROCESS_INFORMATION piProcInfo = {}; STARTUPINFOW siStartInfo = { .cb = sizeof(siStartInfo), .dwFlags = STARTF_USESTDHANDLES, }; - if (useStdErr) - { + if (useStdErr) { siStartInfo.hStdOutput = ffGetNullFD(); siStartInfo.hStdError = hChildPipeWrite; - } - else - { + } else { siStartInfo.hStdOutput = hChildPipeWrite; siStartInfo.hStdError = ffGetNullFD(); } @@ -107,52 +103,51 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* argvToCmdline(argv, &buf); uint32_t cmdlineBytes = (buf.length + 1) * sizeof(wchar_t); cmdline = malloc(cmdlineBytes); - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(cmdline, cmdlineBytes, NULL, buf.chars, buf.length + 1))) + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(cmdline, cmdlineBytes, NULL, buf.chars, buf.length + 1))) { return "RtlUTF8ToUnicodeN() failed"; + } } BOOL success = CreateProcessW( - NULL, // application name - cmdline, // command line - NULL, // process security attributes - NULL, // primary thread security attributes - TRUE, // handles are inherited - 0, // creation flags - NULL, // use parent's environment - NULL, // use parent's current directory - &siStartInfo, // STARTUPINFO pointer - &piProcInfo // receives PROCESS_INFORMATION + NULL, // application name + cmdline, // command line + NULL, // process security attributes + NULL, // primary thread security attributes + TRUE, // handles are inherited + 0, // creation flags + NULL, // use parent's environment + NULL, // use parent's current directory + &siStartInfo, // STARTUPINFO pointer + &piProcInfo // receives PROCESS_INFORMATION ); NtClose(hChildPipeWrite); - if(!success) - { - if (GetLastError() == ERROR_FILE_NOT_FOUND) + if (!success) { + if (GetLastError() == ERROR_FILE_NOT_FOUND) { return "command not found"; + } return "CreateProcessW() failed"; } NtClose(piProcInfo.hThread); // we don't need the thread handle - outHandle->pid = piProcInfo.hProcess; - outHandle->pipeRead = hChildPipeRead; + outHandle->pid = piProcInfo.hProcess; + outHandle->pipeRead = hChildPipeRead; hChildPipeRead = INVALID_HANDLE_VALUE; // ownership transferred, don't close it return NULL; } -static void terminateChildProcess(HANDLE hProcess, HANDLE hChildPipeRead, HANDLE hReadEvent, IO_STATUS_BLOCK* piosb) -{ +static void terminateChildProcess(HANDLE hProcess, HANDLE hChildPipeRead, HANDLE hReadEvent, IO_STATUS_BLOCK* piosb) { IO_STATUS_BLOCK cancelIosb = {}; - if (NT_SUCCESS(NtCancelIoFileEx(hChildPipeRead, piosb, &cancelIosb))) - { - if (hReadEvent) - NtWaitForSingleObject(hReadEvent, FALSE, &(LARGE_INTEGER) { .QuadPart = -100000 }); // wait for cancellation to complete + if (NT_SUCCESS(NtCancelIoFileEx(hChildPipeRead, piosb, &cancelIosb))) { + if (hReadEvent) { + NtWaitForSingleObject(hReadEvent, FALSE, &(LARGE_INTEGER) {.QuadPart = -100000}); // wait for cancellation to complete + } } NtTerminateProcess(hProcess, 1); } -const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) -{ +const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { assert(handle->pipeRead != INVALID_HANDLE_VALUE); assert(handle->pid != INVALID_HANDLE_VALUE); @@ -163,14 +158,14 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) handle->pid = INVALID_HANDLE_VALUE; handle->pipeRead = INVALID_HANDLE_VALUE; - if (timeout >= 0 && !NT_SUCCESS(NtCreateEvent(&hReadEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE))) + if (timeout >= 0 && !NT_SUCCESS(NtCreateEvent(&hReadEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE))) { return "NtCreateEvent() failed"; + } char str[FF_PIPE_BUFSIZ]; uint32_t nRead = 0; IO_STATUS_BLOCK iosb = {}; - do - { + do { NTSTATUS status = NtReadFile( hChildPipeRead, hReadEvent, @@ -180,33 +175,29 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) str, (ULONG) sizeof(str), NULL, - NULL - ); - if (status == STATUS_PENDING) - { - switch (NtWaitForSingleObject(hReadEvent, FALSE, &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 })) - { - case STATUS_WAIT_0: - status = iosb.Status; - break; + NULL); + if (status == STATUS_PENDING) { + switch (NtWaitForSingleObject(hReadEvent, FALSE, &(LARGE_INTEGER) {.QuadPart = (int64_t) timeout * -10000})) { + case STATUS_WAIT_0: + status = iosb.Status; + break; - case STATUS_TIMEOUT: - { - terminateChildProcess(hProcess, hChildPipeRead, hReadEvent, &iosb); - return "NtReadFile(hChildPipeRead) timed out"; - } + case STATUS_TIMEOUT: { + terminateChildProcess(hProcess, hChildPipeRead, hReadEvent, &iosb); + return "NtReadFile(hChildPipeRead) timed out"; + } - default: - terminateChildProcess(hProcess, hChildPipeRead, hReadEvent, &iosb); - return "NtWaitForSingleObject(hReadEvent) failed"; + default: + terminateChildProcess(hProcess, hChildPipeRead, hReadEvent, &iosb); + return "NtWaitForSingleObject(hReadEvent) failed"; } } - if (status == STATUS_PIPE_BROKEN || status == STATUS_END_OF_FILE) + if (status == STATUS_PIPE_BROKEN || status == STATUS_END_OF_FILE) { goto exit; + } - if (!NT_SUCCESS(status)) - { + if (!NT_SUCCESS(status)) { terminateChildProcess(hProcess, hChildPipeRead, NULL, &iosb); return "NtReadFile(hChildPipeRead) failed"; } @@ -215,81 +206,75 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) ffStrbufAppendNS(buffer, nRead, str); } while (nRead > 0); -exit: - { - PROCESS_BASIC_INFORMATION info = {}; - ULONG size; - if(NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessBasicInformation, &info, sizeof(info), &size))) - { - assert(size == sizeof(info)); - if (info.ExitStatus != STILL_ACTIVE && info.ExitStatus != 0) - return "Child process exited with an error"; +exit: { + PROCESS_BASIC_INFORMATION info = {}; + ULONG size; + if (NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessBasicInformation, &info, sizeof(info), &size))) { + assert(size == sizeof(info)); + if (info.ExitStatus != STILL_ACTIVE && info.ExitStatus != 0) { + return "Child process exited with an error"; } - else - return "NtQueryInformationProcess(ProcessBasicInformation) failed"; + } else { + return "NtQueryInformationProcess(ProcessBasicInformation) failed"; } +} return NULL; } -bool ffProcessGetInfoWindows(uint32_t pid, uint32_t* ppid, FFstrbuf* pname, FFstrbuf* exe, const char** exeName, FFstrbuf* exePath, bool* gui) -{ +bool ffProcessGetInfoWindows(uint32_t pid, uint32_t* ppid, FFstrbuf* pname, FFstrbuf* exe, const char** exeName, FFstrbuf* exePath, bool* gui) { FF_AUTO_CLOSE_FD HANDLE hProcess = NtCurrentProcess(); - if(pid != 0) - { + if (pid != 0) { if (!NT_SUCCESS(NtOpenProcess(&hProcess, PROCESS_QUERY_LIMITED_INFORMATION, &(OBJECT_ATTRIBUTES) { - .Length = sizeof(OBJECT_ATTRIBUTES), - }, &(CLIENT_ID) { .UniqueProcess = (HANDLE)(uintptr_t) pid }))) + .Length = sizeof(OBJECT_ATTRIBUTES), + }, + &(CLIENT_ID) {.UniqueProcess = (HANDLE) (uintptr_t) pid}))) { return false; + } } - if(ppid) - { + if (ppid) { PROCESS_BASIC_INFORMATION info = {}; ULONG size; - if(NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessBasicInformation, &info, sizeof(info), &size))) - { + if (NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessBasicInformation, &info, sizeof(info), &size))) { assert(size == sizeof(info)); - *ppid = (uint32_t)info.InheritedFromUniqueProcessId; - } - else + *ppid = (uint32_t) info.InheritedFromUniqueProcessId; + } else { return false; + } } - if(exe) - { + if (exe) { // TODO: It's possible to query the command line with `NtQueryInformationProcess(60/*ProcessCommandLineInformation*/)` since Windows 8.1 alignas(UNICODE_STRING) uint8_t buffer[4096]; ULONG size; - if(NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageFileNameWin32, &buffer, sizeof(buffer), &size))) - { - UNICODE_STRING* imagePath = (UNICODE_STRING*)buffer; + if (NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageFileNameWin32, &buffer, sizeof(buffer), &size))) { + UNICODE_STRING* imagePath = (UNICODE_STRING*) buffer; ffStrbufSetNWS(exe, imagePath->Length / sizeof(wchar_t), imagePath->Buffer); - if (exePath) ffStrbufSet(exePath, exe); + if (exePath) { + ffStrbufSet(exePath, exe); + } - if (pname && exeName) - { + if (pname && exeName) { *exeName = exe->chars + ffStrbufLastIndexC(exe, '\\') + 1; ffStrbufSetS(pname, *exeName); } - } - else + } else { return false; + } } - if (gui) - { + if (gui) { SECTION_IMAGE_INFORMATION info = {}; ULONG size; - if(NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageInformation, &info, sizeof(info), &size))) - { + if (NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageInformation, &info, sizeof(info), &size))) { assert(size == sizeof(info)); *gui = info.SubSystemType == IMAGE_SUBSYSTEM_WINDOWS_GUI; - } - else + } else { return false; + } } return true; diff --git a/src/common/impl/properties.c b/src/common/impl/properties.c index 8b7859bdb..1e7427f30 100644 --- a/src/common/impl/properties.c +++ b/src/common/impl/properties.c @@ -6,61 +6,63 @@ #include #include #ifdef _WIN32 - #include "common/windows/getline.h" +# include "common/windows/getline.h" #endif -bool ffParsePropLinePointer(const char** line, const char* start, FFstrbuf* buffer) -{ - if(**line == '\0') +bool ffParsePropLinePointer(const char** line, const char* start, FFstrbuf* buffer) { + if (**line == '\0') { return false; + } - //Skip any amount of whitespace at the begin of line - while(**line == ' ' || **line == '\t') + // Skip any amount of whitespace at the begin of line + while (**line == ' ' || **line == '\t') { ++(*line); + } - while(*start != '\0') - { + while (*start != '\0') { // Any amount of whitespace in the format string matches any amount of whitespace in the line, even none - if(*start == ' ' || *start == '\t') - { - while(*start == ' ' || *start == '\t') + if (*start == ' ' || *start == '\t') { + while (*start == ' ' || *start == '\t') { ++start; + } - while(**line == ' ' || **line == '\t') + while (**line == ' ' || **line == '\t') { ++(*line); + } continue; } - //Line doesn't match start, skip it - if(tolower(**line) != tolower(*start) || **line == '\0') + // Line doesn't match start, skip it + if (tolower(**line) != tolower(*start) || **line == '\0') { return false; + } - //Line and start match, continue testing + // Line and start match, continue testing ++(*line); ++start; } char valueEnd = '\n'; - //Allow faster parsing of XML - if(*(*line - 1) == '>') + // Allow faster parsing of XML + if (*(*line - 1) == '>') { valueEnd = '<'; + } - //Skip any amount of whitespace at the begin of the value - while(**line == ' ' || **line == '\t') + // Skip any amount of whitespace at the begin of the value + while (**line == ' ' || **line == '\t') { ++(*line); + } - //Allow faster parsing of quotet values - if(**line == '"' || **line == '\'') - { + // Allow faster parsing of quotet values + if (**line == '"' || **line == '\'') { valueEnd = **line; ++(*line); } - //Copy the value to the buffer - while(**line != valueEnd && **line != '\n' && **line != '\0') - { + // Copy the value to the buffer + while (**line != valueEnd && **line != '\n' && **line != '\0') { ffStrbufAppendC(buffer, **line); ++(*line); } @@ -70,17 +72,17 @@ bool ffParsePropLinePointer(const char** line, const char* start, FFstrbuf* buff return true; } -bool ffParsePropLines(const char* lines, const char* start, FFstrbuf* buffer) -{ - while(!ffParsePropLinePointer(&lines, start, buffer)) - { - while(*lines != '\0' && *lines != '\n') +bool ffParsePropLines(const char* lines, const char* start, FFstrbuf* buffer) { + while (!ffParsePropLinePointer(&lines, start, buffer)) { + while (*lines != '\0' && *lines != '\n') { ++lines; + } - if(*lines == '\0') + if (*lines == '\0') { return false; + } - //Skip '\n' + // Skip '\n' ++lines; } @@ -91,81 +93,79 @@ bool ffParsePropLines(const char* lines, const char* start, FFstrbuf* buffer) // Buffers which already contain content are not overwritten // The last occurrence of start in the first file will be the one used -bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquery* queries) -{ +bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquery* queries) { FF_AUTO_CLOSE_FILE FILE* file = fopen(filename, "r"); - if (file == NULL) + if (file == NULL) { return false; + } bool valueStorage[32]; bool* unsetValues = valueStorage; - if (numQueries > ARRAY_SIZE(valueStorage)) + if (numQueries > ARRAY_SIZE(valueStorage)) { unsetValues = malloc(sizeof(bool) * numQueries); - - bool allSet = true; - for (uint32_t i = 0; i < numQueries; i++) - { - unsetValues[i] = queries[i].buffer->length == 0; - if (unsetValues[i]) - allSet = false; } - if (!allSet) - { + bool allSet = true; + for (uint32_t i = 0; i < numQueries; i++) { + unsetValues[i] = queries[i].buffer->length == 0; + if (unsetValues[i]) { + allSet = false; + } + } + + if (!allSet) { FF_AUTO_FREE char* line = NULL; size_t len = 0; - while (getline(&line, &len, file) != -1) - { - for(uint32_t i = 0; i < numQueries; i++) - { - if(!unsetValues[i]) + while (getline(&line, &len, file) != -1) { + for (uint32_t i = 0; i < numQueries; i++) { + if (!unsetValues[i]) { continue; + } uint32_t currentLength = queries[i].buffer->length; queries[i].buffer->length = 0; - if(!ffParsePropLine(line, queries[i].start, queries[i].buffer)) + if (!ffParsePropLine(line, queries[i].start, queries[i].buffer)) { queries[i].buffer->length = currentLength; + } } } } - if(unsetValues != valueStorage) + if (unsetValues != valueStorage) { free(unsetValues); + } return true; } -bool ffParsePropFileHomeValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) -{ +bool ffParsePropFileHomeValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) { FF_STRBUF_AUTO_DESTROY absolutePath = ffStrbufCreateF("%s/%s", instance.state.platform.homeDir.chars, relativeFile); return ffParsePropFileValues(absolutePath.chars, numQueries, queries); } -bool ffParsePropFileListValues(const FFlist* list, const char* relativeFile, uint32_t numQueries, FFpropquery* queries) -{ +bool ffParsePropFileListValues(const FFlist* list, const char* relativeFile, uint32_t numQueries, FFpropquery* queries) { bool foundAFile = false; - FF_LIST_FOR_EACH(FFstrbuf, dirPrefix, *list) - { + FF_LIST_FOR_EACH (FFstrbuf, dirPrefix, *list) { const uint32_t dirPrefixLength = dirPrefix->length; ffStrbufAppendS(dirPrefix, relativeFile); - if(ffParsePropFileValues(dirPrefix->chars, numQueries, queries)) + if (ffParsePropFileValues(dirPrefix->chars, numQueries, queries)) { foundAFile = true; + } ffStrbufSubstrBefore(dirPrefix, dirPrefixLength); bool allSet = true; - for(uint32_t k = 0; k < numQueries; k++) - { - if(queries[k].buffer->length == 0) - { + for (uint32_t k = 0; k < numQueries; k++) { + if (queries[k].buffer->length == 0) { allSet = false; break; } } - if(allSet) + if (allSet) { break; + } } return foundAFile; diff --git a/src/common/impl/settings.c b/src/common/impl/settings.c index acb42195b..911e1ff0f 100644 --- a/src/common/impl/settings.c +++ b/src/common/impl/settings.c @@ -7,39 +7,38 @@ #include #ifdef FF_HAVE_GIO -#include +# include -typedef struct GVariantGetters -{ +typedef struct GVariantGetters { FF_LIBRARY_SYMBOL(g_variant_dup_string) FF_LIBRARY_SYMBOL(g_variant_get_boolean) FF_LIBRARY_SYMBOL(g_variant_get_int32) FF_LIBRARY_SYMBOL(g_variant_unref) } GVariantGetters; -static FFvariant getGVariantValue(GVariant* variant, FFvarianttype type, const GVariantGetters* variantGetters) -{ +static FFvariant getGVariantValue(GVariant* variant, FFvarianttype type, const GVariantGetters* variantGetters) { FFvariant result; - if(variant == NULL) + if (variant == NULL) { result = FF_VARIANT_NULL; - else if(type == FF_VARIANT_TYPE_STRING) + } else if (type == FF_VARIANT_TYPE_STRING) { result = (FFvariant) {.strValue = variantGetters->ffg_variant_dup_string(variant, NULL)}; // Dup string, so that variant itself can be freed - else if(type == FF_VARIANT_TYPE_BOOL) + } else if (type == FF_VARIANT_TYPE_BOOL) { result = (FFvariant) {.boolValue = (bool) variantGetters->ffg_variant_get_boolean(variant), .boolValueSet = true}; - else if(type == FF_VARIANT_TYPE_INT) + } else if (type == FF_VARIANT_TYPE_INT) { result = (FFvariant) {.intValue = variantGetters->ffg_variant_get_int32(variant)}; - else + } else { result = FF_VARIANT_NULL; + } - if(variant) + if (variant) { variantGetters->ffg_variant_unref(variant); + } return result; } -typedef struct GSettingsData -{ +typedef struct GSettingsData { FF_LIBRARY_SYMBOL(g_settings_schema_source_lookup) FF_LIBRARY_SYMBOL(g_settings_schema_has_key) FF_LIBRARY_SYMBOL(g_settings_new_full) @@ -53,12 +52,10 @@ typedef struct GSettingsData bool inited; } GSettingsData; -static const GSettingsData* getGSettingsData(void) -{ +static const GSettingsData* getGSettingsData(void) { static GSettingsData data; - if (!data.inited) - { + if (!data.inited) { data.inited = true; FF_LIBRARY_LOAD(libgsettings, NULL, "libgio-2.0" FF_LIBRARY_EXTENSION, 1); FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_lookup, NULL) @@ -75,56 +72,61 @@ static const GSettingsData* getGSettingsData(void) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_unref, NULL); data.schemaSource = data.ffg_settings_schema_source_get_default(); - if (data.schemaSource) + if (data.schemaSource) { libgsettings = NULL; + } } - if(!data.schemaSource) + if (!data.schemaSource) { return NULL; + } return &data; } -FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type) -{ +FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type) { const GSettingsData* data = getGSettingsData(); - if(data == NULL) + if (data == NULL) { return FF_VARIANT_NULL; + } GSettingsSchema* schema = data->ffg_settings_schema_source_lookup(data->schemaSource, schemaName, true); - if(schema == NULL) + if (schema == NULL) { return FF_VARIANT_NULL; + } - if(data->ffg_settings_schema_has_key(schema, key) == false) + if (data->ffg_settings_schema_has_key(schema, key) == false) { return FF_VARIANT_NULL; + } GSettings* settings = data->ffg_settings_new_full(schema, NULL, path); - if(settings == NULL) + if (settings == NULL) { return FF_VARIANT_NULL; + } GVariant* variant = data->ffg_settings_get_value(settings, key); - if(variant != NULL) + if (variant != NULL) { return getGVariantValue(variant, type, &data->variantGetters); + } variant = data->ffg_settings_get_user_value(settings, key); - if(variant != NULL) + if (variant != NULL) { return getGVariantValue(variant, type, &data->variantGetters); + } variant = data->ffg_settings_get_default_value(settings, key); return getGVariantValue(variant, type, &data->variantGetters); } -#else //FF_HAVE_GIO -FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type) -{ +#else // FF_HAVE_GIO +FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type) { FF_UNUSED(schemaName, path, key, type) return FF_VARIANT_NULL; } -#endif //FF_HAVE_GIO +#endif // FF_HAVE_GIO #ifdef FF_HAVE_DCONF -#include +# include -typedef struct DConfData -{ +typedef struct DConfData { FF_LIBRARY_SYMBOL(dconf_client_read_full) FF_LIBRARY_SYMBOL(dconf_client_new) GVariantGetters variantGetters; @@ -133,12 +135,10 @@ typedef struct DConfData bool inited; } DConfData; -static const DConfData* getDConfData(void) -{ +static const DConfData* getDConfData(void) { static DConfData data; - if (!data.inited) - { + if (!data.inited) { data.inited = true; FF_LIBRARY_LOAD(libdconf, NULL, "libdconf" FF_LIBRARY_EXTENSION, 2); @@ -150,127 +150,124 @@ static const DConfData* getDConfData(void) FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_unref, NULL) data.client = data.ffdconf_client_new(); - if (data.client) + if (data.client) { libdconf = NULL; + } } - if(!data.client) + if (!data.client) { return NULL; + } return &data; } -FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type) -{ +FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type) { const DConfData* data = getDConfData(); - if(data == NULL) + if (data == NULL) { return FF_VARIANT_NULL; + } GVariant* variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_FLAGS_NONE, NULL); - if(variant != NULL) + if (variant != NULL) { return getGVariantValue(variant, type, &data->variantGetters); + } variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_USER_VALUE, NULL); - if(variant != NULL) + if (variant != NULL) { return getGVariantValue(variant, type, &data->variantGetters); + } variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_DEFAULT_VALUE, NULL); return getGVariantValue(variant, type, &data->variantGetters); } -#else //FF_HAVE_DCONF -FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type) -{ +#else // FF_HAVE_DCONF +FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type) { FF_UNUSED(key, type) return FF_VARIANT_NULL; } -#endif //FF_HAVE_DCONF +#endif // FF_HAVE_DCONF -FFvariant ffSettingsGetGnome(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); - if( + if ( (type == FF_VARIANT_TYPE_BOOL && gsettings.boolValueSet) || - (type != FF_VARIANT_TYPE_BOOL && gsettings.strValue != NULL) - ) return gsettings; + (type != FF_VARIANT_TYPE_BOOL && gsettings.strValue != NULL)) { + return gsettings; + } return ffSettingsGetDConf(dconfKey, type); } #ifdef FF_HAVE_DBUS -#include "common/dbus.h" +# include "common/dbus.h" -FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type) -{ +FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type) { FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; - if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) + if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { return FF_VARIANT_NULL; + } DBusMessage* reply = ffDBusGetMethodReply(&dbus, "org.xfce.Xfconf", "/org/xfce/Xfconf", "org.xfce.Xfconf", "GetProperty", channelName, propertyName); - if(!reply) + if (!reply) { return FF_VARIANT_NULL; + } DBusMessageIter rootIterator; - if(!dbus.lib->ffdbus_message_iter_init(reply, &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) - { + if (type == FF_VARIANT_TYPE_INT) { int32_t value; - if (ffDBusGetInt(&dbus, &rootIterator, &value)) - { + if (ffDBusGetInt(&dbus, &rootIterator, &value)) { dbus.lib->ffdbus_message_unref(reply); - return (FFvariant) { .intValue = value }; + return (FFvariant) {.intValue = value}; } return FF_VARIANT_NULL; } - if(type == FF_VARIANT_TYPE_STRING) - { + if (type == FF_VARIANT_TYPE_STRING) { FFstrbuf value = ffStrbufCreate(); - if (ffDBusGetString(&dbus, &rootIterator, &value)) - { + if (ffDBusGetString(&dbus, &rootIterator, &value)) { dbus.lib->ffdbus_message_unref(reply); - return (FFvariant) { .strValue = value.chars }; // Leaks value.chars + return (FFvariant) {.strValue = value.chars}; // Leaks value.chars } return FF_VARIANT_NULL; } - if(type == FF_VARIANT_TYPE_BOOL) - { + if (type == FF_VARIANT_TYPE_BOOL) { bool value; - if (ffDBusGetBool(&dbus, &rootIterator, &value)) - { + if (ffDBusGetBool(&dbus, &rootIterator, &value)) { dbus.lib->ffdbus_message_unref(reply); - return (FFvariant) { .boolValue = value, .boolValueSet = true }; + return (FFvariant) {.boolValue = value, .boolValueSet = true}; } } return FF_VARIANT_NULL; } -#define FF_DBUS_ITER_CONTINUE(dbus, iterator) \ - { \ - if(!(dbus).lib->ffdbus_message_iter_next(iterator)) \ - break; \ - continue; \ +# 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) { + FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; + if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { + return FF_VARIANT_NULL; } -FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb) -{ - FF_DBUS_AUTO_DESTROY_DATA 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) + if (!reply) { return FF_VARIANT_NULL; + } DBusMessageIter rootIterator; - if(!dbus.lib->ffdbus_message_iter_init(reply, &rootIterator)) - { + if (!dbus.lib->ffdbus_message_iter_init(reply, &rootIterator)) { dbus.lib->ffdbus_message_unref(reply); return FF_VARIANT_NULL; } @@ -278,10 +275,10 @@ FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* pro 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) + 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); @@ -289,38 +286,34 @@ FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* pro const char* key; dbus.lib->ffdbus_message_iter_get_basic(&dictIterator, &key); - if (cb(data, key)) FF_DBUS_ITER_CONTINUE(dbus, &arrayIterator) + if (cb(data, key)) { + FF_DBUS_ITER_CONTINUE(dbus, &arrayIterator) + } dbus.lib->ffdbus_message_iter_next(&dictIterator); - if(type == FF_VARIANT_TYPE_INT) - { + if (type == FF_VARIANT_TYPE_INT) { int32_t value; - if (ffDBusGetInt(&dbus, &dictIterator, &value)) - { + if (ffDBusGetInt(&dbus, &dictIterator, &value)) { dbus.lib->ffdbus_message_unref(reply); - return (FFvariant) { .intValue = value }; + return (FFvariant) {.intValue = value}; } return FF_VARIANT_NULL; } - if(type == FF_VARIANT_TYPE_STRING) - { + if (type == FF_VARIANT_TYPE_STRING) { FFstrbuf value = ffStrbufCreate(); - if (ffDBusGetString(&dbus, &dictIterator, &value)) - { + if (ffDBusGetString(&dbus, &dictIterator, &value)) { dbus.lib->ffdbus_message_unref(reply); - return (FFvariant) { .strValue = value.chars }; // Leaks value.chars + return (FFvariant) {.strValue = value.chars}; // Leaks value.chars } return FF_VARIANT_NULL; } - if(type == FF_VARIANT_TYPE_BOOL) - { + if (type == FF_VARIANT_TYPE_BOOL) { bool value; - if (ffDBusGetBool(&dbus, &dictIterator, &value)) - { + if (ffDBusGetBool(&dbus, &dictIterator, &value)) { dbus.lib->ffdbus_message_unref(reply); - return (FFvariant) { .boolValue = value, .boolValueSet = true }; + return (FFvariant) {.boolValue = value, .boolValueSet = true}; } } @@ -329,24 +322,21 @@ FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* pro return FF_VARIANT_NULL; } -#else //FF_HAVE_DBUS -FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type) -{ +#else // FF_HAVE_DBUS +FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type) { FF_UNUSED(channelName, propertyName, type) return FF_VARIANT_NULL; } -FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb) -{ +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 +#endif // FF_HAVE_DBUS #ifdef FF_HAVE_SQLITE3 -#include +# include -typedef struct SQLiteData -{ +typedef struct SQLiteData { FF_LIBRARY_SYMBOL(sqlite3_open_v2) FF_LIBRARY_SYMBOL(sqlite3_prepare_v2) FF_LIBRARY_SYMBOL(sqlite3_step) @@ -359,12 +349,10 @@ typedef struct SQLiteData bool inited; } SQLiteData; -static const SQLiteData* getSQLiteData(void) -{ +static const SQLiteData* getSQLiteData(void) { static SQLiteData data; - if (!data.inited) - { + if (!data.inited) { data.inited = true; FF_LIBRARY_LOAD(libsqlite, NULL, "libsqlite3" FF_LIBRARY_EXTENSION, 1); FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_open_v2, NULL) @@ -378,34 +366,35 @@ static const SQLiteData* getSQLiteData(void) libsqlite = NULL; } - if (!data.ffsqlite3_close) + if (!data.ffsqlite3_close) { return NULL; + } return &data; } -int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) -{ - if(!ffPathExists(dbPath, FF_PATHTYPE_FILE)) +int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) { + if (!ffPathExists(dbPath, FF_PATHTYPE_FILE)) { return 0; + } const SQLiteData* data = getSQLiteData(); - if(data == NULL) + if (data == NULL) { return 0; + } sqlite3* db; - if(data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) + if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { return 0; + } sqlite3_stmt* stmt; - if(data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) - { + if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) { data->ffsqlite3_close(db); return 0; } - if(data->ffsqlite3_step(stmt) != SQLITE_ROW || data->ffsqlite3_data_count(stmt) < 1) - { + if (data->ffsqlite3_step(stmt) != SQLITE_ROW || data->ffsqlite3_data_count(stmt) < 1) { data->ffsqlite3_finalize(stmt); data->ffsqlite3_close(db); return 0; @@ -419,71 +408,72 @@ int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) return result; } -bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf* result) -{ - if(!ffPathExists(dbPath, FF_PATHTYPE_FILE)) +bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf* result) { + if (!ffPathExists(dbPath, FF_PATHTYPE_FILE)) { return false; + } const SQLiteData* data = getSQLiteData(); - if(data == NULL) + if (data == NULL) { return false; + } sqlite3* db; - if(data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) + if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { return false; + } sqlite3_stmt* stmt; - if(data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) - { + if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) { data->ffsqlite3_close(db); return false; } - if(data->ffsqlite3_step(stmt) != SQLITE_ROW || data->ffsqlite3_data_count(stmt) < 1) - { + if (data->ffsqlite3_step(stmt) != SQLITE_ROW || data->ffsqlite3_data_count(stmt) < 1) { data->ffsqlite3_finalize(stmt); data->ffsqlite3_close(db); return false; } - ffStrbufSetS(result, (const char *) data->ffsqlite3_column_text(stmt, 0)); + ffStrbufSetS(result, (const char*) data->ffsqlite3_column_text(stmt, 0)); data->ffsqlite3_finalize(stmt); data->ffsqlite3_close(db); return true; } -#else //FF_HAVE_SQLITE3 -int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) -{ +#else // FF_HAVE_SQLITE3 +int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) { FF_UNUSED(dbPath, query) return 0; } -bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf* result) -{ +bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf* result) { FF_UNUSED(dbPath, query, result) return false; } -#endif //FF_HAVE_SQLITE3 +#endif // FF_HAVE_SQLITE3 #ifdef __ANDROID__ -#include +# include bool ffSettingsGetAndroidProperty(const char* propName, FFstrbuf* result) { ffStrbufEnsureFree(result, PROP_VALUE_MAX); int len = __system_property_get(propName, result->chars + result->length); - if (len <= 0) return false; + if (len <= 0) { + return false; + } result->length += (uint32_t) len; result->chars[result->length] = '\0'; return true; } #elif defined(__FreeBSD__) -#include -bool ffSettingsGetFreeBSDKenv(const char* propName, FFstrbuf* result) -{ - //https://wiki.ghostbsd.org/index.php/Kenv +# include +bool ffSettingsGetFreeBSDKenv(const char* propName, FFstrbuf* result) { + // https://wiki.ghostbsd.org/index.php/Kenv ffStrbufEnsureFree(result, KENV_MVALLEN); int len = kenv(KENV_GET, propName, result->chars + result->length, KENV_MVALLEN); - if (len <= 1) return false; // number of bytes copied, including NUL terminator + if (len <= 1) { + return false; // number of bytes copied, including NUL terminator + } result->length += (uint32_t) len - 1; return true; } diff --git a/src/common/impl/size.c b/src/common/impl/size.c index 89e7e0551..789c0f6a5 100644 --- a/src/common/impl/size.c +++ b/src/common/impl/size.c @@ -2,32 +2,30 @@ #include -static void appendNum(FFstrbuf* result, uint64_t bytes, uint32_t base, const char** prefixes) -{ +static void appendNum(FFstrbuf* result, uint64_t bytes, uint32_t base, const char** prefixes) { const FFOptionsDisplay* options = &instance.config.display; double size = (double) bytes; uint8_t counter = 0; - while(size >= base && counter < options->sizeMaxPrefix && prefixes[counter + 1]) - { + while (size >= base && counter < options->sizeMaxPrefix && prefixes[counter + 1]) { size /= base; counter++; } - if (counter == 0) + if (counter == 0) { ffStrbufAppendUInt(result, bytes); - else + } else { ffStrbufAppendDouble(result, size, (int8_t) options->sizeNdigits, true); - if (options->sizeSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER) + } + if (options->sizeSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER) { ffStrbufAppendC(result, ' '); + } ffStrbufAppendS(result, prefixes[counter]); } -void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result) -{ +void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result) { const FFOptionsDisplay* options = &instance.config.display; - switch (options->sizeBinaryPrefix) - { + switch (options->sizeBinaryPrefix) { case FF_SIZE_BINARY_PREFIX_TYPE_IEC: appendNum(result, bytes, 1024, (const char*[]) {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", NULL}); break; diff --git a/src/common/impl/smbiosHelper.c b/src/common/impl/smbiosHelper.c index a41638ccb..aaaaf32a4 100644 --- a/src/common/impl/smbiosHelper.c +++ b/src/common/impl/smbiosHelper.c @@ -4,11 +4,9 @@ #include "common/mallocHelper.h" #include "common/debug.h" -bool ffIsSmbiosValueSet(FFstrbuf* value) -{ +bool ffIsSmbiosValueSet(FFstrbuf* value) { ffStrbufTrimRightSpace(value); - return - value->length > 0 && + return value->length > 0 && !ffStrbufStartsWithIgnCaseS(value, "To be filled") && !ffStrbufStartsWithIgnCaseS(value, "To be set") && !ffStrbufStartsWithIgnCaseS(value, "OEM") && @@ -36,43 +34,36 @@ bool ffIsSmbiosValueSet(FFstrbuf* value) !ffStrbufIgnCaseEqualS(value, "Standard") && ({ // Some SMBIOS implementations use "0x0000" to indicate an unset value, even for strings. bool zero = ffStrbufStartsWithS(value, "0x0"); - if (zero) - { - for (size_t i = 2; i < value->length; i++) - { + if (zero) { + for (size_t i = 2; i < value->length; i++) { char c = value->chars[i]; - if (c != '0') - { + if (c != '0') { zero = false; break; } } } !zero; - }) - ; + }); } static bool smbiosTableInitialized = false; static FFSmbiosHeaderTable smbiosTable; -const FFSmbiosHeader* ffSmbiosNextEntry(const FFSmbiosHeader* header) -{ +const FFSmbiosHeader* ffSmbiosNextEntry(const FFSmbiosHeader* header) { const char* p = ((const char*) header) + header->Length; - if (*p) - { - do + if (*p) { + do { p += strlen(p) + 1; - while (*p); + } while (*p); + } else { // The terminator is always double 0 even if there is no string + p++; } - else // The terminator is always double 0 even if there is no string - p ++; return (const FFSmbiosHeader*) (p + 1); } -static bool parseSmbiosTable(const uint8_t* data, uint32_t length) -{ +static bool parseSmbiosTable(const uint8_t* data, uint32_t length) { const FFSmbiosHeader* endOfTable = NULL; FF_DEBUG("Parsing SMBIOS table structures with length %u bytes", length); @@ -80,52 +71,49 @@ static bool parseSmbiosTable(const uint8_t* data, uint32_t length) for ( const FFSmbiosHeader* header = (const FFSmbiosHeader*) data; (const uint8_t*) header + sizeof(FFSmbiosHeader) < (const uint8_t*) data + length; - header = ffSmbiosNextEntry(header) - ) - { + header = ffSmbiosNextEntry(header)) { ++totalCount; endOfTable = header; // This doesn't verify the entire structure (e.g. string section can still be truncated), // but at least ensures the formatted section is valid and prevents infinite loops // when the table is severely malformed. - if (__builtin_expect((const uint8_t*) header + header->Length > (const uint8_t*) data + length, false)) - { + if (__builtin_expect((const uint8_t*) header + header->Length > (const uint8_t*) data + length, false)) { FF_DEBUG("Truncated SMBIOS structure at offset 0x%lx: length %u is too small", - (unsigned long)((const uint8_t*) header - data), header->Length); + (unsigned long) ((const uint8_t*) header - data), + header->Length); break; } - if (header->Type < FF_SMBIOS_TYPE_END_OF_TABLE) - { - if (!smbiosTable[header->Type]) - { + if (header->Type < FF_SMBIOS_TYPE_END_OF_TABLE) { + if (!smbiosTable[header->Type]) { smbiosTable[header->Type] = header; FF_DEBUG("Found SMBIOS structure type %u, handle 0x%04X, length %u", - header->Type, header->Handle, header->Length); + header->Type, + header->Handle, + header->Length); structureCount++; - } - else - { + } else { FF_DEBUG("Duplicate SMBIOS structure type %u, handle 0x%04X, length %u", - header->Type, header->Handle, header->Length); + header->Type, + header->Handle, + header->Length); } - } - else if (header->Type == FF_SMBIOS_TYPE_END_OF_TABLE) - { + } else if (header->Type == FF_SMBIOS_TYPE_END_OF_TABLE) { FF_DEBUG("Reached SMBIOS end of type %u, handle 0x%04X, length %u", - header->Type, header->Handle, header->Length); + header->Type, + header->Handle, + header->Length); break; - } - else - { + } else { FF_DEBUG("Found custom SMBIOS structure type %u, handle 0x%04X, length %u; ignoring", - header->Type, header->Handle, header->Length); + header->Type, + header->Handle, + header->Length); } } - if (!endOfTable) - { + if (!endOfTable) { FF_DEBUG("No SMBIOS structures found in table"); return false; } @@ -140,60 +128,58 @@ static bool parseSmbiosTable(const uint8_t* data, uint32_t length) } #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__sun) || defined(__HAIKU__) || defined(__OpenBSD__) || defined(__GNU__) -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include -#ifdef __linux__ - #include "common/properties.h" -#elif defined(__FreeBSD__) - #include "common/settings.h" - #define loff_t off_t // FreeBSD doesn't have loff_t -#elif defined(__sun) - #define loff_t off_t -#elif defined(__NetBSD__) - #include "common/sysctl.h" - #define loff_t off_t -#endif +# ifdef __linux__ +# include "common/properties.h" +# elif defined(__FreeBSD__) +# include "common/settings.h" +# define loff_t off_t // FreeBSD doesn't have loff_t +# elif defined(__sun) +# define loff_t off_t +# elif defined(__NetBSD__) +# include "common/sysctl.h" +# define loff_t off_t +# endif -#ifdef __linux__ -bool ffGetSmbiosValue(const char* devicesPath, const char* classPath, FFstrbuf* buffer) -{ +# ifdef __linux__ +bool ffGetSmbiosValue(const char* devicesPath, const char* classPath, FFstrbuf* buffer) { // /sys/class/dmi/id/* are all pseudo-files with very small content // so reading the whole file at once is efficient ffStrbufEnsureFixedLengthFree(buffer, 127); ssize_t len = ffReadFileData(devicesPath, buffer->allocated - 1, buffer->chars); - if (len > 0) - { + if (len > 0) { assert(len < buffer->allocated); buffer->chars[len] = '\0'; buffer->length = (uint32_t) len; ffStrbufTrimRightSpace(buffer); - if(ffIsSmbiosValueSet(buffer)) + if (ffIsSmbiosValueSet(buffer)) { return true; + } } len = ffReadFileData(classPath, buffer->allocated - 1, buffer->chars); - if (len > 0) - { + if (len > 0) { assert(len < buffer->allocated); buffer->chars[len] = '\0'; buffer->length = (uint32_t) len; ffStrbufTrimRightSpace(buffer); - if(ffIsSmbiosValueSet(buffer)) + if (ffIsSmbiosValueSet(buffer)) { return true; + } } ffStrbufClear(buffer); return false; } -#endif +# endif -typedef struct FFSmbios20EntryPoint -{ +typedef struct FFSmbios20EntryPoint { uint8_t AnchorString[4]; uint8_t EntryPointStructureChecksum; uint8_t EntryPointLength; @@ -212,8 +198,7 @@ typedef struct FFSmbios20EntryPoint static_assert(offsetof(FFSmbios20EntryPoint, SmbiosBcdRevision) == 0x1E, "FFSmbios20EntryPoint: Wrong struct alignment"); -typedef struct FFSmbios30EntryPoint -{ +typedef struct FFSmbios30EntryPoint { uint8_t AnchorString[5]; uint8_t EntryPointStructureChecksum; uint8_t EntryPointLength; @@ -229,38 +214,35 @@ typedef struct FFSmbios30EntryPoint static_assert(offsetof(FFSmbios30EntryPoint, StructureTableAddress) == 0x10, "FFSmbios30EntryPoint: Wrong struct alignment"); -typedef union FFSmbiosEntryPoint -{ +typedef union FFSmbiosEntryPoint { FFSmbios20EntryPoint Smbios20; FFSmbios30EntryPoint Smbios30; } FFSmbiosEntryPoint; -const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() -{ +const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { static FFstrbuf buffer; - if (!smbiosTableInitialized) - { + if (!smbiosTableInitialized) { smbiosTableInitialized = true; FF_DEBUG("Initializing SMBIOS buffer"); ffStrbufInit(&buffer); - #if !__HAIKU__ && !__OpenBSD__ && !__DragonFly__ && !__GNU__ - #ifdef __linux__ +# if !__HAIKU__ && !__OpenBSD__ && !__DragonFly__ && !__GNU__ +# ifdef __linux__ FF_DEBUG("Using Linux implementation - trying /sys/firmware/dmi/tables/DMI"); if (!ffAppendFileBuffer("/sys/firmware/dmi/tables/DMI", &buffer)) - #endif +# endif { - #if !defined(__sun) && !defined(__NetBSD__) +# if !defined(__sun) && !defined(__NetBSD__) FF_DEBUG("Using memory-mapped implementation"); FF_STRBUF_AUTO_DESTROY strEntryAddress = ffStrbufCreate(); - #ifdef __FreeBSD__ +# ifdef __FreeBSD__ FF_DEBUG("Using FreeBSD kenv implementation"); if (!ffSettingsGetFreeBSDKenv("hint.smbios.0.mem", &strEntryAddress)) { FF_DEBUG("Failed to get SMBIOS address from FreeBSD kenv"); return NULL; } FF_DEBUG("Got SMBIOS address from kenv: %s", strEntryAddress.chars); - #elif defined(__linux__) +# elif defined(__linux__) { FF_DEBUG("Using Linux EFI systab implementation"); FF_STRBUF_AUTO_DESTROY systab = ffStrbufCreate(); @@ -275,14 +257,14 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() } FF_DEBUG("Found SMBIOS entry in systab: %s", strEntryAddress.chars); } - #endif +# endif loff_t entryAddress = (loff_t) strtol(strEntryAddress.chars, NULL, 16); if (entryAddress == 0) { FF_DEBUG("Invalid SMBIOS entry address: 0"); return NULL; } - FF_DEBUG("Parsed SMBIOS entry address: 0x%lx", (unsigned long)entryAddress); + FF_DEBUG("Parsed SMBIOS entry address: 0x%lx", (unsigned long) entryAddress); FF_AUTO_CLOSE_FD int fd = open("/dev/mem", O_RDONLY | O_CLOEXEC); if (fd < 0) { @@ -293,9 +275,9 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() FFSmbiosEntryPoint entryPoint; FF_DEBUG("Attempting to read %zu bytes from physical address 0x%lx", - sizeof(entryPoint), (unsigned long)entryAddress); - if (pread(fd, &entryPoint, sizeof(entryPoint), entryAddress) < 0x10) - { + sizeof(entryPoint), + (unsigned long) entryAddress); + if (pread(fd, &entryPoint, sizeof(entryPoint), entryAddress) < 0x10) { FF_DEBUG("pread failed, trying mmap"); // `pread /dev/mem` returns EFAULT in FreeBSD // https://stackoverflow.com/questions/69372330/how-to-read-dev-mem-using-read @@ -310,14 +292,14 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() } else { FF_DEBUG("Successfully read entry point data via pread"); } - #else +# else // Sun or NetBSD FF_DEBUG("Using %s specific implementation", - #ifdef __NetBSD__ +# ifdef __NetBSD__ "NetBSD" - #else +# else "SunOS" - #endif +# endif ); FF_AUTO_CLOSE_FD int fd = open("/dev/smbios", O_RDONLY | O_CLOEXEC); @@ -328,80 +310,79 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() FF_DEBUG("/dev/smbios opened successfully with fd=%d", fd); FFSmbiosEntryPoint entryPoint; - #ifdef __NetBSD__ +# ifdef __NetBSD__ off_t addr = (off_t) ffSysctlGetInt64("machdep.smbios", 0); if (addr == 0) { FF_DEBUG("Failed to get SMBIOS address from sysctl"); return NULL; } - FF_DEBUG("Got SMBIOS address from sysctl: 0x%lx", (unsigned long)addr); + FF_DEBUG("Got SMBIOS address from sysctl: 0x%lx", (unsigned long) addr); if (pread(fd, &entryPoint, sizeof(entryPoint), addr) < 1) { FF_DEBUG("Failed to read SMBIOS entry point: %s", strerror(errno)); return NULL; } FF_DEBUG("Successfully read SMBIOS entry point"); - #else +# else FF_DEBUG("Reading SMBIOS entry point from /dev/smbios"); if (ffReadFDData(fd, sizeof(entryPoint), &entryPoint) < 1) { FF_DEBUG("Failed to read SMBIOS entry point: %s", strerror(errno)); return NULL; } FF_DEBUG("Successfully read SMBIOS entry point"); - #endif - #endif +# endif +# endif uint32_t tableLength = 0; loff_t tableAddress = 0; - if (memcmp(entryPoint.Smbios20.AnchorString, "_SM_", sizeof(entryPoint.Smbios20.AnchorString)) == 0) - { + if (memcmp(entryPoint.Smbios20.AnchorString, "_SM_", sizeof(entryPoint.Smbios20.AnchorString)) == 0) { FF_DEBUG("Found SMBIOS 2.0 entry point"); if (entryPoint.Smbios20.EntryPointLength != sizeof(entryPoint.Smbios20)) { FF_DEBUG("Invalid SMBIOS 2.0 entry point length: %u (expected %zu)", - entryPoint.Smbios20.EntryPointLength, sizeof(entryPoint.Smbios20)); + entryPoint.Smbios20.EntryPointLength, + sizeof(entryPoint.Smbios20)); return NULL; } tableLength = entryPoint.Smbios20.StructureTableLength; tableAddress = (loff_t) entryPoint.Smbios20.StructureTableAddress; FF_DEBUG("SMBIOS 2.0: tableLength=0x%x, tableAddress=0x%lx, version=%u.%u", - tableLength, (unsigned long)tableAddress, - entryPoint.Smbios20.SmbiosMajorVersion, entryPoint.Smbios20.SmbiosMinorVersion); - } - else if (memcmp(entryPoint.Smbios30.AnchorString, "_SM3_", sizeof(entryPoint.Smbios30.AnchorString)) == 0) - { + tableLength, + (unsigned long) tableAddress, + entryPoint.Smbios20.SmbiosMajorVersion, + entryPoint.Smbios20.SmbiosMinorVersion); + } else if (memcmp(entryPoint.Smbios30.AnchorString, "_SM3_", sizeof(entryPoint.Smbios30.AnchorString)) == 0) { FF_DEBUG("Found SMBIOS 3.0 entry point"); if (entryPoint.Smbios30.EntryPointLength != sizeof(entryPoint.Smbios30)) { FF_DEBUG("Invalid SMBIOS 3.0 entry point length: %u (expected %zu)", - entryPoint.Smbios30.EntryPointLength, sizeof(entryPoint.Smbios30)); + entryPoint.Smbios30.EntryPointLength, + sizeof(entryPoint.Smbios30)); return NULL; } tableLength = entryPoint.Smbios30.StructureTableMaximumSize; tableAddress = (loff_t) entryPoint.Smbios30.StructureTableAddress; FF_DEBUG("SMBIOS 3.0: tableLength=0x%x, tableAddress=0x%lx, version=%u.%u.%u", - tableLength, (unsigned long)tableAddress, - entryPoint.Smbios30.SmbiosMajorVersion, entryPoint.Smbios30.SmbiosMinorVersion, entryPoint.Smbios30.SmbiosDocrev); - } - else { + tableLength, + (unsigned long) tableAddress, + entryPoint.Smbios30.SmbiosMajorVersion, + entryPoint.Smbios30.SmbiosMinorVersion, + entryPoint.Smbios30.SmbiosDocrev); + } else { FF_DEBUG("Unknown SMBIOS entry point format"); return NULL; } ffStrbufEnsureFixedLengthFree(&buffer, tableLength); - FF_DEBUG("Attempting to read SMBIOS table data: %u bytes at 0x%lx", tableLength, (unsigned long)tableAddress); - if (pread(fd, buffer.chars, tableLength, tableAddress) == (ssize_t) tableLength) - { + FF_DEBUG("Attempting to read SMBIOS table data: %u bytes at 0x%lx", tableLength, (unsigned long) tableAddress); + if (pread(fd, buffer.chars, tableLength, tableAddress) == (ssize_t) tableLength) { buffer.length = tableLength; buffer.chars[buffer.length] = '\0'; FF_DEBUG("Successfully read SMBIOS table data: %u bytes", tableLength); - } - else - { + } else { FF_DEBUG("pread failed, trying mmap"); // entryPoint.StructureTableAddress must be page aligned. // Unaligned physical memory access results in all kinds of crashes. void* p = mmap(NULL, tableLength, PROT_READ, MAP_SHARED, fd, tableAddress); - if (p == MAP_FAILED) - { + if (p == MAP_FAILED) { FF_DEBUG("mmap failed: %s", strerror(errno)); ffStrbufDestroy(&buffer); // free buffer and reset state return NULL; @@ -411,25 +392,26 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() FF_DEBUG("Successfully read SMBIOS table data via mmap: %u bytes", tableLength); } } - #else +# else { FF_DEBUG("Using %s implementation", - #if __HAIKU__ +# if __HAIKU__ "Haiku" - #else +# else "OpenBSD" - #endif +# endif ); uint32_t tableLength = 0; off_t tableAddress = 0; FF_AUTO_CLOSE_FD int fd = open( - #if __HAIKU__ +# if __HAIKU__ "/dev/misc/mem" - #else +# else "/dev/mem" // kern.securelevel must be -1 - #endif - , O_RDONLY | O_CLOEXEC); +# endif + , + O_RDONLY | O_CLOEXEC); if (fd < 0) { FF_DEBUG("Failed to open memory device: %s", strerror(errno)); return NULL; @@ -448,37 +430,40 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() } FF_DEBUG("Successfully read 0x10000 bytes from physical address 0xF0000"); - for (off_t offset = 0; offset <= 0xffe0; offset += 0x10) - { - FFSmbiosEntryPoint* p = (void*)(smBiosBase + offset); - if (memcmp(p, "_SM3_", sizeof(p->Smbios30.AnchorString)) == 0) - { - FF_DEBUG("Found SMBIOS 3.0 entry point at offset 0x%lx", (unsigned long)offset); + for (off_t offset = 0; offset <= 0xffe0; offset += 0x10) { + FFSmbiosEntryPoint* p = (void*) (smBiosBase + offset); + if (memcmp(p, "_SM3_", sizeof(p->Smbios30.AnchorString)) == 0) { + FF_DEBUG("Found SMBIOS 3.0 entry point at offset 0x%lx", (unsigned long) offset); if (p->Smbios30.EntryPointLength != sizeof(p->Smbios30)) { FF_DEBUG("Invalid SMBIOS 3.0 entry point length: %u (expected %zu)", - p->Smbios30.EntryPointLength, sizeof(p->Smbios30)); + p->Smbios30.EntryPointLength, + sizeof(p->Smbios30)); return NULL; } tableLength = p->Smbios30.StructureTableMaximumSize; tableAddress = (off_t) p->Smbios30.StructureTableAddress; FF_DEBUG("SMBIOS 3.0: tableLength=0x%x, tableAddress=0x%lx, version=%u.%u.%u", - tableLength, (unsigned long)tableAddress, - p->Smbios30.SmbiosMajorVersion, p->Smbios30.SmbiosMinorVersion, p->Smbios30.SmbiosDocrev); + tableLength, + (unsigned long) tableAddress, + p->Smbios30.SmbiosMajorVersion, + p->Smbios30.SmbiosMinorVersion, + p->Smbios30.SmbiosDocrev); break; - } - else if (memcmp(p, "_SM_", sizeof(p->Smbios20.AnchorString)) == 0) - { - FF_DEBUG("Found SMBIOS 2.0 entry point at offset 0x%lx", (unsigned long)offset); + } else if (memcmp(p, "_SM_", sizeof(p->Smbios20.AnchorString)) == 0) { + FF_DEBUG("Found SMBIOS 2.0 entry point at offset 0x%lx", (unsigned long) offset); if (p->Smbios20.EntryPointLength != sizeof(p->Smbios20)) { FF_DEBUG("Invalid SMBIOS 2.0 entry point length: %u (expected %zu)", - p->Smbios20.EntryPointLength, sizeof(p->Smbios20)); + p->Smbios20.EntryPointLength, + sizeof(p->Smbios20)); return NULL; } tableLength = p->Smbios20.StructureTableLength; tableAddress = (off_t) p->Smbios20.StructureTableAddress; FF_DEBUG("SMBIOS 2.0: tableLength=0x%x, tableAddress=0x%lx, version=%u.%u", - tableLength, (unsigned long)tableAddress, - p->Smbios20.SmbiosMajorVersion, p->Smbios20.SmbiosMinorVersion); + tableLength, + (unsigned long) tableAddress, + p->Smbios20.SmbiosMajorVersion, + p->Smbios20.SmbiosMinorVersion); break; } } @@ -488,22 +473,21 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() } ffStrbufEnsureFixedLengthFree(&buffer, tableLength); - FF_DEBUG("Attempting to read SMBIOS table data: %u bytes at 0x%lx", tableLength, (unsigned long)tableAddress); - if (pread(fd, buffer.chars, tableLength, tableAddress) == tableLength) - { + FF_DEBUG("Attempting to read SMBIOS table data: %u bytes at 0x%lx", tableLength, (unsigned long) tableAddress); + if (pread(fd, buffer.chars, tableLength, tableAddress) == tableLength) { buffer.length = tableLength; buffer.chars[buffer.length] = '\0'; FF_DEBUG("Successfully read SMBIOS table data: %u bytes", tableLength); - } - else { + } else { FF_DEBUG("Failed to read SMBIOS table data: %s", strerror(errno)); return NULL; } } - #endif +# endif - if (!parseSmbiosTable((const uint8_t*) buffer.chars, buffer.length)) + if (!parseSmbiosTable((const uint8_t*) buffer.chars, buffer.length)) { ffStrbufClear(&buffer); + } } if (buffer.length == 0) { @@ -514,12 +498,11 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() return &smbiosTable; } #elif defined(_WIN32) -#include "common/windows/nt.h" +# include "common/windows/nt.h" -#pragma GCC diagnostic ignored "-Wmultichar" +# pragma GCC diagnostic ignored "-Wmultichar" -typedef struct FFRawSmbiosData -{ +typedef struct FFRawSmbiosData { uint8_t Used20CallingMethod; uint8_t SMBIOSMajorVersion; uint8_t SMBIOSMinorVersion; @@ -528,12 +511,10 @@ typedef struct FFRawSmbiosData uint8_t SMBIOSTableData[]; } FFRawSmbiosData; -const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() -{ +const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { static SYSTEM_FIRMWARE_TABLE_INFORMATION* buffer; - if (!smbiosTableInitialized) - { + if (!smbiosTableInitialized) { smbiosTableInitialized = true; FF_DEBUG("Initializing Windows SMBIOS buffer"); @@ -550,7 +531,8 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() } if (bufSize != sfti.TableBufferLength + (ULONG) sizeof(sfti)) { FF_DEBUG("Firmware table size mismatch: NtQuerySystemInformation returned %lu but expected %lu", - bufSize, sfti.TableBufferLength + (ULONG) sizeof(sfti)); + bufSize, + sfti.TableBufferLength + (ULONG) sizeof(sfti)); return NULL; } FF_DEBUG("Firmware table size: %lu bytes", bufSize); @@ -559,8 +541,7 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() *buffer = sfti; FF_DEBUG("Allocated buffer for SMBIOS data"); - if (!NT_SUCCESS(NtQuerySystemInformation(SystemFirmwareTableInformation, buffer, bufSize, &bufSize))) - { + if (!NT_SUCCESS(NtQuerySystemInformation(SystemFirmwareTableInformation, buffer, bufSize, &bufSize))) { FF_DEBUG("NtQuerySystemInformation(SystemFirmwareTableInformation) failed"); free(buffer); buffer = NULL; @@ -569,10 +550,11 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() FFRawSmbiosData* rawData = (FFRawSmbiosData*) buffer->TableBuffer; FF_DEBUG("Successfully retrieved SMBIOS data: version %u.%u, length %u bytes", - rawData->SMBIOSMajorVersion, rawData->SMBIOSMinorVersion, rawData->Length); + rawData->SMBIOSMajorVersion, + rawData->SMBIOSMinorVersion, + rawData->Length); - if (!parseSmbiosTable(rawData->SMBIOSTableData, rawData->Length)) - { + if (!parseSmbiosTable(rawData->SMBIOSTableData, rawData->Length)) { free(buffer); buffer = NULL; return NULL; @@ -586,34 +568,29 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() return &smbiosTable; } #elif defined(__APPLE__) -#include "common/apple/cf_helpers.h" +# include "common/apple/cf_helpers.h" -const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() -{ +const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { static CFDataRef smbiosDataBuffer; - if (!smbiosTableInitialized) - { + if (!smbiosTableInitialized) { smbiosTableInitialized = true; FF_DEBUG("Initializing SMBIOS buffer on Apple platform"); FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t registryEntry = IOServiceGetMatchingService(MACH_PORT_NULL, IOServiceMatching("AppleSMBIOS")); - if (!registryEntry) - { + if (!registryEntry) { FF_DEBUG("IOServiceGetMatchingService() failed to find AppleSMBIOS"); return NULL; } FF_DEBUG("AppleSMBIOS service found, retrieving SMBIOS data"); smbiosDataBuffer = IORegistryEntryCreateCFProperty(registryEntry, CFSTR("SMBIOS"), kCFAllocatorDefault, kNilOptions); - if (!smbiosDataBuffer) - { + if (!smbiosDataBuffer) { FF_DEBUG("IORegistryEntryCreateCFProperty() failed to get SMBIOS data"); return NULL; } - if (CFGetTypeID(smbiosDataBuffer) != CFDataGetTypeID()) - { + if (CFGetTypeID(smbiosDataBuffer) != CFDataGetTypeID()) { FF_DEBUG("Unexpected SMBIOS data type: expected CFData"); CFRelease(smbiosDataBuffer); smbiosDataBuffer = NULL; @@ -621,16 +598,14 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() } FF_DEBUG("Successfully retrieved SMBIOS data: %lu bytes", CFDataGetLength(smbiosDataBuffer)); - if (!parseSmbiosTable((const uint8_t*) CFDataGetBytePtr(smbiosDataBuffer), (uint32_t) CFDataGetLength(smbiosDataBuffer))) - { + if (!parseSmbiosTable((const uint8_t*) CFDataGetBytePtr(smbiosDataBuffer), (uint32_t) CFDataGetLength(smbiosDataBuffer))) { CFRelease(smbiosDataBuffer); smbiosDataBuffer = NULL; return NULL; } } - if (!smbiosDataBuffer) - { + if (!smbiosDataBuffer) { FF_DEBUG("No valid SMBIOS data available"); return NULL; } diff --git a/src/common/impl/sysctl.c b/src/common/impl/sysctl.c index 9b1c52d11..62ba31c0d 100644 --- a/src/common/impl/sysctl.c +++ b/src/common/impl/sysctl.c @@ -3,86 +3,88 @@ #include #ifdef __OpenBSD__ -const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result) -{ +const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result) { size_t neededLength; - if (sysctl((int[]) {mib1, mib2}, 2, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) //neededLength is 1 for empty strings, because of the null terminator + if (sysctl((int[]) {mib1, mib2}, 2, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator return "sysctlbyname() failed"; + } ffStrbufEnsureFree(result, (uint32_t) neededLength - 1); - if (sysctl((int[]) {mib1, mib2}, 2, result->chars + result->length, &neededLength, NULL, 0) == 0) + if (sysctl((int[]) {mib1, mib2}, 2, result->chars + result->length, &neededLength, NULL, 0) == 0) { result->length += (uint32_t) neededLength - 1; + } result->chars[result->length] = '\0'; return NULL; } -int ffSysctlGetInt(int mib1, int mib2, int defaultValue) -{ +int ffSysctlGetInt(int mib1, int mib2, int defaultValue) { int result; size_t neededLength = sizeof(result); - if (sysctl((int[]) {mib1, mib2}, 2, &result, &neededLength, NULL, 0) != 0) + if (sysctl((int[]) {mib1, mib2}, 2, &result, &neededLength, NULL, 0) != 0) { return defaultValue; + } return result; } -int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) -{ +int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) { int64_t result; size_t neededLength = sizeof(result); - if(sysctl((int[]) {mib1, mib2}, 2, &result, &neededLength, NULL, 0) != 0) + if (sysctl((int[]) {mib1, mib2}, 2, &result, &neededLength, NULL, 0) != 0) { return defaultValue; + } return result; } #else -const char* ffSysctlGetString(const char* propName, FFstrbuf* result) -{ +const char* ffSysctlGetString(const char* propName, FFstrbuf* result) { size_t neededLength; - if(sysctlbyname(propName, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) //neededLength is 1 for empty strings, because of the null terminator + if (sysctlbyname(propName, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator return "sysctlbyname() failed"; + } ffStrbufEnsureFree(result, (uint32_t) neededLength - 1); - if(sysctlbyname(propName, result->chars + result->length, &neededLength, NULL, 0) == 0) + if (sysctlbyname(propName, result->chars + result->length, &neededLength, NULL, 0) == 0) { result->length += (uint32_t) neededLength - 1; + } result->chars[result->length] = '\0'; return NULL; } -int ffSysctlGetInt(const char* propName, int defaultValue) -{ +int ffSysctlGetInt(const char* propName, int defaultValue) { int result; size_t neededLength = sizeof(result); - if(sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) + if (sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) { return defaultValue; + } return result; } -int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) -{ +int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) { int64_t result; size_t neededLength = sizeof(result); - if(sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) + if (sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) { return defaultValue; + } return result; } #endif // OpenBSD -void* ffSysctlGetData(int* request, u_int requestLength, size_t* resultLength) -{ - if(sysctl(request, requestLength, NULL, resultLength, NULL, 0) != 0) +void* ffSysctlGetData(int* request, u_int requestLength, size_t* resultLength) { + if (sysctl(request, requestLength, NULL, resultLength, NULL, 0) != 0) { return NULL; + } void* data = malloc(*resultLength); - if(data == NULL) + if (data == NULL) { return NULL; + } - if(sysctl(request, requestLength, data, resultLength, NULL, 0) != 0) - { + if (sysctl(request, requestLength, data, resultLength, NULL, 0) != 0) { free(data); return NULL; } diff --git a/src/common/impl/temps.c b/src/common/impl/temps.c index 29d705aa4..7bb2a6665 100644 --- a/src/common/impl/temps.c +++ b/src/common/impl/temps.c @@ -3,10 +3,10 @@ #include "common/textModifier.h" #include "common/stringUtils.h" -void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig config, const FFModuleArgs* module) -{ - if (celsius == -DBL_MAX) // ignores invalid value +void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig config, const FFModuleArgs* module) { + if (celsius == -DBL_MAX) { // ignores invalid value return; + } const FFOptionsDisplay* options = &instance.config.display; const char* colorGreen = options->tempColorGreen.chars; @@ -15,76 +15,68 @@ void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig confi uint8_t green = config.green, yellow = config.yellow; - if (!options->pipe) - { - if(green <= yellow) - { - if (celsius > yellow) + if (!options->pipe) { + if (green <= yellow) { + if (celsius > yellow) { ffStrbufAppendF(buffer, "\e[%sm", colorRed); - else if (celsius > green) + } else if (celsius > green) { ffStrbufAppendF(buffer, "\e[%sm", colorYellow); - else + } else { ffStrbufAppendF(buffer, "\e[%sm", colorGreen); - } - else - { - if (celsius < yellow) + } + } else { + if (celsius < yellow) { ffStrbufAppendF(buffer, "\e[%sm", colorRed); - else if (celsius < green) + } else if (celsius < green) { ffStrbufAppendF(buffer, "\e[%sm", colorYellow); - else + } else { ffStrbufAppendF(buffer, "\e[%sm", colorGreen); + } } } - switch (options->tempUnit) - { + switch (options->tempUnit) { case FF_TEMPERATURE_UNIT_DEFAULT: case FF_TEMPERATURE_UNIT_CELSIUS: - ffStrbufAppendF(buffer, "%.*f%s°C", options->tempNdigits, celsius, - options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : ""); + ffStrbufAppendF(buffer, "%.*f%s°C", options->tempNdigits, celsius, options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : ""); break; case FF_TEMPERATURE_UNIT_FAHRENHEIT: - ffStrbufAppendF(buffer, "%.*f%s°F", options->tempNdigits, celsius * 1.8 + 32, - options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : ""); + ffStrbufAppendF(buffer, "%.*f%s°F", options->tempNdigits, celsius * 1.8 + 32, options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : ""); break; case FF_TEMPERATURE_UNIT_KELVIN: - ffStrbufAppendF(buffer, "%.*f%sK", options->tempNdigits, celsius + 273.15, - options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " "); + ffStrbufAppendF(buffer, "%.*f%sK", options->tempNdigits, celsius + 273.15, options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " "); break; } - if (!options->pipe) - { + if (!options->pipe) { ffStrbufAppendS(buffer, FASTFETCH_TEXT_MODIFIER_RESET); - if (module->outputColor.length) + if (module->outputColor.length) { ffStrbufAppendF(buffer, "\e[%sm", module->outputColor.chars); - else if (instance.config.display.colorOutput.length) + } else if (instance.config.display.colorOutput.length) { ffStrbufAppendF(buffer, "\e[%sm", instance.config.display.colorOutput.chars); + } } } -bool ffTempsParseCommandOptions(const char* key, const char* subkey, const char* value, bool* useTemp, FFColorRangeConfig* config) -{ - if (!ffStrStartsWithIgnCase(subkey, "temp")) +bool ffTempsParseCommandOptions(const char* key, const char* subkey, const char* value, bool* useTemp, FFColorRangeConfig* config) { + if (!ffStrStartsWithIgnCase(subkey, "temp")) { return false; + } - if (subkey[strlen("temp")] == '\0') - { + if (subkey[strlen("temp")] == '\0') { *useTemp = ffOptionParseBoolean(value); return true; } - if (subkey[strlen("temp")] != '-') + if (subkey[strlen("temp")] != '-') { return false; + } subkey += strlen("temp-"); - if (ffStrEqualsIgnCase(subkey, "green")) - { + if (ffStrEqualsIgnCase(subkey, "green")) { uint32_t num = ffOptionParseUInt32(key, value); - if (num > 100) - { + if (num > 100) { fprintf(stderr, "Error: usage: %s must be between 0 and 100\n", key); exit(480); } @@ -92,11 +84,9 @@ bool ffTempsParseCommandOptions(const char* key, const char* subkey, const char* return true; } - if (ffStrEqualsIgnCase(subkey, "yellow")) - { + if (ffStrEqualsIgnCase(subkey, "yellow")) { uint32_t num = ffOptionParseUInt32(key, value); - if (num > 100) - { + if (num > 100) { fprintf(stderr, "Error: usage: %s must be between 0 and 100\n", key); exit(480); } @@ -107,27 +97,24 @@ bool ffTempsParseCommandOptions(const char* key, const char* subkey, const char* return false; } -bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, FFColorRangeConfig* config) -{ +bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, FFColorRangeConfig* config) { assert(key); - if (!unsafe_yyjson_equals_str(key, "temp")) + if (!unsafe_yyjson_equals_str(key, "temp")) { return false; + } - if (yyjson_is_bool(value)) - { + if (yyjson_is_bool(value)) { *useTemp = yyjson_get_bool(value); return true; } - if (yyjson_is_null(value)) - { + if (yyjson_is_null(value)) { *useTemp = false; return true; } - if (!yyjson_is_obj(value)) - { + if (!yyjson_is_obj(value)) { fprintf(stderr, "Error: usage: %s must be an object or a boolean\n", unsafe_yyjson_get_str(key)); exit(480); } @@ -135,11 +122,9 @@ bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, F *useTemp = true; yyjson_val* greenVal = yyjson_obj_get(value, "green"); - if (greenVal) - { + if (greenVal) { int num = yyjson_get_int(greenVal); - if (num < 0 || num > 100) - { + if (num < 0 || num > 100) { fputs("Error: usage: temp.green must be between 0 and 100\n", stderr); exit(480); } @@ -147,11 +132,9 @@ bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, F } yyjson_val* yellowVal = yyjson_obj_get(value, "yellow"); - if (yellowVal) - { + if (yellowVal) { int num = yyjson_get_int(yellowVal); - if (num < 0 || num > 100) - { + if (num < 0 || num > 100) { fputs("Error: usage: temp.yellow must be between 0 and 100\n", stderr); exit(480); } @@ -161,12 +144,10 @@ bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, F return true; } -void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, bool temp, FFColorRangeConfig config) -{ - if (!temp) +void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, bool temp, FFColorRangeConfig config) { + if (!temp) { yyjson_mut_obj_add_bool(doc, module, "temp", false); - else - { + } else { yyjson_mut_val* temp = yyjson_mut_obj_add_obj(doc, module, "temp"); yyjson_mut_obj_add_uint(doc, temp, "green", config.green); yyjson_mut_obj_add_uint(doc, temp, "yellow", config.yellow); diff --git a/src/common/impl/time.c b/src/common/impl/time.c index a991cb560..3de9bb1f1 100644 --- a/src/common/impl/time.c +++ b/src/common/impl/time.c @@ -5,13 +5,14 @@ char ffTimeInternalBuffer[64]; // Reduce memory usage and prevent redundant allocations #ifdef _WIN32 - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wformat" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wformat" #endif -const char* ffTimeToFullStr(uint64_t msec) -{ - if (msec == 0) return ""; +const char* ffTimeToFullStr(uint64_t msec) { + if (msec == 0) { + return ""; + } time_t tsec = (time_t) (msec / 1000); const struct tm* tm = localtime(&tsec); @@ -22,18 +23,20 @@ const char* ffTimeToFullStr(uint64_t msec) return ffTimeInternalBuffer; } -const char* ffTimeToShortStr(uint64_t msec) -{ - if (msec == 0) return ""; +const char* ffTimeToShortStr(uint64_t msec) { + if (msec == 0) { + return ""; + } time_t tsec = (time_t) (msec / 1000); strftime(ffTimeInternalBuffer, ARRAY_SIZE(ffTimeInternalBuffer), "%F %T", localtime(&tsec)); return ffTimeInternalBuffer; } -const char* ffTimeToTimeStr(uint64_t msec) -{ - if (msec == 0) return ""; +const char* ffTimeToTimeStr(uint64_t msec) { + if (msec == 0) { + return ""; + } time_t tsec = (time_t) (msec / 1000); uint32_t len = (uint32_t) strftime(ffTimeInternalBuffer, ARRAY_SIZE(ffTimeInternalBuffer), "%T", localtime(&tsec)); @@ -42,34 +45,35 @@ const char* ffTimeToTimeStr(uint64_t msec) } #ifdef _WIN32 - #pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif -FFTimeGetAgeResult ffTimeGetAge(uint64_t birthMs, uint64_t nowMs) -{ +FFTimeGetAgeResult ffTimeGetAge(uint64_t birthMs, uint64_t nowMs) { FFTimeGetAgeResult result = {}; - if (__builtin_expect(birthMs == 0 || nowMs < birthMs, 0)) + if (__builtin_expect(birthMs == 0 || nowMs < birthMs, 0)) { return result; + } time_t birth_s = (time_t) (birthMs / 1000); struct tm birth_tm; - #ifdef _WIN32 +#ifdef _WIN32 localtime_s(&birth_tm, &birth_s); - #else +#else localtime_r(&birth_s, &birth_tm); - #endif +#endif time_t now_s = (time_t) (nowMs / 1000); struct tm now_tm; - #ifdef _WIN32 +#ifdef _WIN32 localtime_s(&now_tm, &now_s); - #else +#else localtime_r(&now_s, &now_tm); - #endif +#endif result.years = (uint32_t) (now_tm.tm_year - birth_tm.tm_year); - if (now_tm.tm_yday < birth_tm.tm_yday) + if (now_tm.tm_yday < birth_tm.tm_yday) { result.years--; + } birth_tm.tm_year += (int) result.years; birth_s = mktime(&birth_tm); @@ -83,13 +87,11 @@ FFTimeGetAgeResult ffTimeGetAge(uint64_t birthMs, uint64_t nowMs) } #ifdef _WIN32 - double ffQpcMultiplier; +double ffQpcMultiplier; - __attribute__((constructor)) - static void ffTimeInitQpcMultiplier(void) - { - LARGE_INTEGER frequency; - RtlQueryPerformanceFrequency(&frequency); - ffQpcMultiplier = 1000. / (double) frequency.QuadPart; - } +__attribute__((constructor)) static void ffTimeInitQpcMultiplier(void) { + LARGE_INTEGER frequency; + RtlQueryPerformanceFrequency(&frequency); + ffQpcMultiplier = 1000. / (double) frequency.QuadPart; +} #endif diff --git a/src/common/impl/wcwidth.c b/src/common/impl/wcwidth.c index 5cad57ef6..5b4a1adc9 100644 --- a/src/common/impl/wcwidth.c +++ b/src/common/impl/wcwidth.c @@ -1,8 +1,7 @@ #include "common/wcwidth.h" #include "3rdparty/widecharwidth/widechar_width_c.h" -int mk_wcwidth(uint32_t wc) -{ +int mk_wcwidth(uint32_t wc) { // // We render U+1F6E1 (🛡) with a width of 2, // // but widechar_width says it has a width of 1 because Unicode classifies it as "neutral". // // diff --git a/src/common/io.h b/src/common/io.h index 2d2851f00..02d4dd3de 100644 --- a/src/common/io.h +++ b/src/common/io.h @@ -4,94 +4,89 @@ #include "common/FFlist.h" #ifdef _WIN32 - #include - #include - #include - #include "common/windows/nt.h" - typedef HANDLE FFNativeFD; - #define FF_INVALID_FD INVALID_HANDLE_VALUE +# include +# include +# include +# include "common/windows/nt.h" +typedef HANDLE FFNativeFD; +# define FF_INVALID_FD INVALID_HANDLE_VALUE #else - #include - #include - #include - #include - #include - #include - typedef int FFNativeFD; - #define FF_INVALID_FD (-1) - // procfs's file can be changed between read calls such as /proc/meminfo and /proc/uptime. - // one safe way to read correct data is reading the whole file in a single read syscall - #define PROC_FILE_BUFFSIZ (32 * 1024) +# include +# include +# include +# include +# include +# include +typedef int FFNativeFD; +# define FF_INVALID_FD (-1) +// procfs's file can be changed between read calls such as /proc/meminfo and /proc/uptime. +// one safe way to read correct data is reading the whole file in a single read syscall +# define PROC_FILE_BUFFSIZ (32 * 1024) #endif #ifdef _WIN32 - #ifndef O_CLOEXEC - #define O_CLOEXEC 0 - #endif - #ifndef O_RDONLY - #define O_RDONLY 0 - #endif - #ifndef O_DIRECTORY - #define O_DIRECTORY 0200000 - #endif +# ifndef O_CLOEXEC +# define O_CLOEXEC 0 +# endif +# ifndef O_RDONLY +# define O_RDONLY 0 +# endif +# ifndef O_DIRECTORY +# define O_DIRECTORY 0200000 +# endif // Only O_RDONLY is supported HANDLE openat(HANDLE dfd, const char* fileName, int oflag); HANDLE openatW(HANDLE dfd, const wchar_t* fileName, uint16_t fileNameLen, bool directory); #endif - -static inline bool ffIsValidNativeFD(FFNativeFD fd) -{ - #ifndef _WIN32 - return fd >= 0; - #else - // https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443 - return fd != INVALID_HANDLE_VALUE && fd != NULL; - #endif +static inline bool ffIsValidNativeFD(FFNativeFD fd) { +#ifndef _WIN32 + return fd >= 0; +#else + // https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443 + return fd != INVALID_HANDLE_VALUE && fd != NULL; +#endif } FF_C_NONNULL(1) -static inline bool wrapClose(FFNativeFD* pfd) -{ +static inline bool wrapClose(FFNativeFD* pfd) { assert(pfd); - if (!ffIsValidNativeFD(*pfd)) + if (!ffIsValidNativeFD(*pfd)) { return false; + } - #ifndef _WIN32 - close(*pfd); - #else - NtClose(*pfd); - #endif +#ifndef _WIN32 + close(*pfd); +#else + NtClose(*pfd); +#endif return true; } #define FF_AUTO_CLOSE_FD __attribute__((__cleanup__(wrapClose))) -static inline FFNativeFD FFUnixFD2NativeFD(int unixfd) -{ - #ifndef _WIN32 - return unixfd; - #else - return (FFNativeFD) _get_osfhandle(unixfd); - #endif +static inline FFNativeFD FFUnixFD2NativeFD(int unixfd) { +#ifndef _WIN32 + return unixfd; +#else + return (FFNativeFD) _get_osfhandle(unixfd); +#endif } FF_C_NONNULL(3) -static inline bool ffWriteFDData(FFNativeFD fd, size_t dataSize, const void* data) -{ - #ifndef _WIN32 - return write(fd, data, dataSize) != -1; - #else - DWORD written; - return WriteFile(fd, data, (DWORD) dataSize, &written, NULL) && written == dataSize; - #endif +static inline bool ffWriteFDData(FFNativeFD fd, size_t dataSize, const void* data) { +#ifndef _WIN32 + return write(fd, data, dataSize) != -1; +#else + DWORD written; + return WriteFile(fd, data, (DWORD) dataSize, &written, NULL) && written == dataSize; +#endif } FF_C_NONNULL(2) -static inline bool ffWriteFDBuffer(FFNativeFD fd, const FFstrbuf* content) -{ +static inline bool ffWriteFDBuffer(FFNativeFD fd, const FFstrbuf* content) { return ffWriteFDData(fd, content->length, content->chars); } @@ -99,103 +94,98 @@ FF_C_NONNULL(1, 3) bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data); FF_C_NONNULL(1, 2) -static inline bool ffWriteFileBuffer(const char* fileName, const FFstrbuf* buffer) -{ +static inline bool ffWriteFileBuffer(const char* fileName, const FFstrbuf* buffer) { return ffWriteFileData(fileName, buffer->length, buffer->chars); } FF_C_NONNULL(3) -static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSize, void* data) -{ - #ifndef _WIN32 - return read(fd, data, dataSize); - #else - DWORD bytesRead; - if(!ReadFile(fd, data, (DWORD)dataSize, &bytesRead, NULL)) - return -1; +static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSize, void* data) { +#ifndef _WIN32 + return read(fd, data, dataSize); +#else + DWORD bytesRead; + if (!ReadFile(fd, data, (DWORD) dataSize, &bytesRead, NULL)) { + return -1; + } - return (ssize_t)bytesRead; - #endif + return (ssize_t) bytesRead; +#endif } FF_C_NONNULL(2) bool ffAppendFDBuffer(FFNativeFD fd, FFstrbuf* buffer); FF_C_NONNULL(1, 3) -static inline ssize_t ffReadFileData(const char* fileName, size_t dataSize, void* data) -{ +static inline ssize_t ffReadFileData(const char* fileName, size_t dataSize, void* data) { FFNativeFD FF_AUTO_CLOSE_FD fd = - #ifndef _WIN32 +#ifndef _WIN32 open(fileName, O_RDONLY | O_CLOEXEC); - #else +#else CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - #endif +#endif - if (!ffIsValidNativeFD(fd)) + if (!ffIsValidNativeFD(fd)) { return -1; + } return ffReadFDData(fd, dataSize, data); } FF_C_NONNULL(2, 4) -static inline ssize_t ffReadFileDataRelative(FFNativeFD dfd, const char* fileName, size_t dataSize, void* data) -{ +static inline ssize_t ffReadFileDataRelative(FFNativeFD dfd, const char* fileName, size_t dataSize, void* data) { FFNativeFD FF_AUTO_CLOSE_FD fd = openat(dfd, fileName, O_RDONLY | O_CLOEXEC); - if (!ffIsValidNativeFD(fd)) + if (!ffIsValidNativeFD(fd)) { return -1; + } return ffReadFDData(fd, dataSize, data); } FF_C_NONNULL(1, 2) -static inline bool ffAppendFileBuffer(const char* fileName, FFstrbuf* buffer) -{ +static inline bool ffAppendFileBuffer(const char* fileName, FFstrbuf* buffer) { FFNativeFD FF_AUTO_CLOSE_FD fd = - #ifndef _WIN32 +#ifndef _WIN32 open(fileName, O_RDONLY | O_CLOEXEC); - #else +#else CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - #endif +#endif - if (!ffIsValidNativeFD(fd)) + if (!ffIsValidNativeFD(fd)) { return false; + } return ffAppendFDBuffer(fd, buffer); } FF_C_NONNULL(2, 3) -static inline bool ffAppendFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) -{ +static inline bool ffAppendFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) { FFNativeFD FF_AUTO_CLOSE_FD fd = openat(dfd, fileName, O_RDONLY | O_CLOEXEC); - if (!ffIsValidNativeFD(fd)) + if (!ffIsValidNativeFD(fd)) { return false; + } return ffAppendFDBuffer(fd, buffer); } FF_C_NONNULL(2) -static inline bool ffReadFDBuffer(FFNativeFD fd, FFstrbuf* buffer) -{ +static inline bool ffReadFDBuffer(FFNativeFD fd, FFstrbuf* buffer) { ffStrbufClear(buffer); return ffAppendFDBuffer(fd, buffer); } FF_C_NONNULL(1, 2) -static inline bool ffReadFileBuffer(const char* fileName, FFstrbuf* buffer) -{ +static inline bool ffReadFileBuffer(const char* fileName, FFstrbuf* buffer) { ffStrbufClear(buffer); return ffAppendFileBuffer(fileName, buffer); } FF_C_NONNULL(2, 3) -static inline bool ffReadFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) -{ +static inline bool ffReadFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) { ffStrbufClear(buffer); return ffAppendFileBufferRelative(dfd, fileName, buffer); } -typedef enum __attribute__((__packed__)) FFPathType -{ +typedef enum __attribute__((__packed__)) FFPathType { FF_PATHTYPE_FILE = 1 << 0, FF_PATHTYPE_DIRECTORY = 1 << 1, FF_PATHTYPE_ANY = FF_PATHTYPE_FILE | FF_PATHTYPE_DIRECTORY, @@ -203,48 +193,51 @@ typedef enum __attribute__((__packed__)) FFPathType } FFPathType; FF_C_NONNULL(1) -static inline bool ffPathExists(const char* path, FFPathType pathType) -{ - #ifdef _WIN32 +static inline bool ffPathExists(const char* path, FFPathType pathType) { +#ifdef _WIN32 wchar_t wPath[MAX_PATH]; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(wPath, (ULONG) sizeof(wPath), NULL, path, (ULONG)strlen(path) + 1))) + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(wPath, (ULONG) sizeof(wPath), NULL, path, (ULONG) strlen(path) + 1))) { return false; + } DWORD attr = GetFileAttributesW(wPath); - if(attr == INVALID_FILE_ATTRIBUTES) + if (attr == INVALID_FILE_ATTRIBUTES) { return false; + } - if(pathType & FF_PATHTYPE_FILE && !(attr & FILE_ATTRIBUTE_DIRECTORY)) + if (pathType & FF_PATHTYPE_FILE && !(attr & FILE_ATTRIBUTE_DIRECTORY)) { return true; + } - if(pathType & FF_PATHTYPE_DIRECTORY && (attr & FILE_ATTRIBUTE_DIRECTORY)) + if (pathType & FF_PATHTYPE_DIRECTORY && (attr & FILE_ATTRIBUTE_DIRECTORY)) { return true; + } - #else +#else - if (pathType == FF_PATHTYPE_ANY) - { + if (pathType == FF_PATHTYPE_ANY) { // Zero overhead return access(path, F_OK) == 0; - } - else - { + } else { struct stat fileStat; - if(stat(path, &fileStat) != 0) + if (stat(path, &fileStat) != 0) { return false; + } unsigned int mode = fileStat.st_mode & S_IFMT; - if(pathType & FF_PATHTYPE_FILE && mode != S_IFDIR) + if (pathType & FF_PATHTYPE_FILE && mode != S_IFDIR) { return true; + } - if(pathType & FF_PATHTYPE_DIRECTORY && mode == S_IFDIR) + if (pathType & FF_PATHTYPE_DIRECTORY && mode == S_IFDIR) { return true; + } } - #endif +#endif return false; } @@ -261,9 +254,10 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* // Not thread safe! bool ffSuppressIO(bool suppress); -static inline void ffUnsuppressIO(bool* suppressed) -{ - if (!*suppressed) return; +static inline void ffUnsuppressIO(bool* suppressed) { + if (!*suppressed) { + return; + } ffSuppressIO(false); *suppressed = false; } @@ -273,11 +267,11 @@ static inline void ffUnsuppressIO(bool* suppressed) void ffListFilesRecursively(const char* path, bool pretty); FF_C_NONNULL(1) -static inline bool wrapFclose(FILE** pfile) -{ +static inline bool wrapFclose(FILE** pfile) { assert(pfile); - if (!*pfile) + if (!*pfile) { return false; + } fclose(*pfile); return true; } @@ -285,20 +279,20 @@ static inline bool wrapFclose(FILE** pfile) FF_C_NONNULL(1) #ifndef _WIN32 -static inline bool wrapClosedir(DIR** pdir) -{ +static inline bool wrapClosedir(DIR** pdir) { assert(pdir); - if (!*pdir) + if (!*pdir) { return false; + } closedir(*pdir); return true; } #else -static inline bool wrapClosedir(HANDLE* pdir) -{ +static inline bool wrapClosedir(HANDLE* pdir) { assert(pdir); - if (!*pdir) + if (!*pdir) { return false; + } FindClose(*pdir); return true; } @@ -306,16 +300,15 @@ static inline bool wrapClosedir(HANDLE* pdir) #define FF_AUTO_CLOSE_DIR __attribute__((__cleanup__(wrapClosedir))) FF_C_NONNULL(1, 2, 3) -static inline bool ffSearchUserConfigFile(const FFlist* configDirs, const char* fileSubpath, FFstrbuf* result) -{ +static inline bool ffSearchUserConfigFile(const FFlist* configDirs, const char* fileSubpath, FFstrbuf* result) { // configDirs is a list of FFstrbufs include the trailing slash - FF_LIST_FOR_EACH(FFstrbuf, dir, *configDirs) - { + FF_LIST_FOR_EACH (FFstrbuf, dir, *configDirs) { ffStrbufClear(result); ffStrbufAppend(result, dir); ffStrbufAppendS(result, fileSubpath); - if (ffPathExists(result->chars, FF_PATHTYPE_FILE)) + if (ffPathExists(result->chars, FF_PATHTYPE_FILE)) { return true; + } } return false; diff --git a/src/common/jsonconfig.h b/src/common/jsonconfig.h index 55f9ab5f8..a78aafd16 100644 --- a/src/common/jsonconfig.h +++ b/src/common/jsonconfig.h @@ -6,20 +6,20 @@ bool ffJsonConfigParseModuleArgs(yyjson_val* key, yyjson_val* val, FFModuleArgs* moduleArgs); const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair pairs[]); -yyjson_api_inline yyjson_mut_val* yyjson_mut_strbuf(yyjson_mut_doc *doc, const FFstrbuf* buf) { +yyjson_api_inline yyjson_mut_val* yyjson_mut_strbuf(yyjson_mut_doc* doc, const FFstrbuf* buf) { return yyjson_mut_strncpy(doc, buf->chars, buf->length); } -yyjson_api_inline bool yyjson_mut_obj_add_strbuf(yyjson_mut_doc *doc, - yyjson_mut_val *obj, - const char *_key, - const FFstrbuf* buf) { +yyjson_api_inline bool yyjson_mut_obj_add_strbuf(yyjson_mut_doc* doc, + yyjson_mut_val* obj, + const char* _key, + const FFstrbuf* buf) { return yyjson_mut_obj_add_strncpy(doc, obj, _key, buf->chars, buf->length); } -yyjson_api_inline bool yyjson_mut_arr_add_strbuf(yyjson_mut_doc *doc, - yyjson_mut_val *obj, - const FFstrbuf* buf) { +yyjson_api_inline bool yyjson_mut_arr_add_strbuf(yyjson_mut_doc* doc, + yyjson_mut_val* obj, + const FFstrbuf* buf) { return yyjson_mut_arr_add_strncpy(doc, obj, buf->chars, buf->length); } diff --git a/src/common/library.h b/src/common/library.h index 9c4ee7282..cbe7802b8 100644 --- a/src/common/library.h +++ b/src/common/library.h @@ -5,103 +5,103 @@ #ifndef FF_DISABLE_DLOPEN -#if defined(_WIN32) - #define FF_DLOPEN_FLAGS 0 - FF_C_NODISCARD void* dlopen(const char* path, int mode); - FF_C_NODISCARD void* dlsym(void* handle, const char* symbol); - int dlclose(void* handle); -#else - #include -#endif +# if defined(_WIN32) +# define FF_DLOPEN_FLAGS 0 +FF_C_NODISCARD void* dlopen(const char* path, int mode); +FF_C_NODISCARD void* dlsym(void* handle, const char* symbol); +int dlclose(void* handle); +# else +# include +# endif -#ifdef _WIN32 - #define FF_LIBRARY_EXTENSION ".dll" -#elif defined(__APPLE__) - #define FF_LIBRARY_EXTENSION ".dylib" -#else - #define FF_LIBRARY_EXTENSION ".so" -#endif +# ifdef _WIN32 +# define FF_LIBRARY_EXTENSION ".dll" +# elif defined(__APPLE__) +# define FF_LIBRARY_EXTENSION ".dylib" +# else +# define FF_LIBRARY_EXTENSION ".so" +# endif -static inline void ffLibraryUnload(void** handle) -{ +static inline void ffLibraryUnload(void** handle) { assert(handle); - if (*handle) + if (*handle) { dlclose(*handle); + } } -#if __cplusplus -#define __auto_type auto -#endif +# if __cplusplus +# define __auto_type auto +# endif -#define FF_LIBRARY_SYMBOL(symbolName) \ - __typeof__(&symbolName) ff ## symbolName; +# define FF_LIBRARY_SYMBOL(symbolName) \ + __typeof__(&symbolName) ff##symbolName; -#define FF_LIBRARY_LOAD(libraryObjectName, returnValue, ...) \ - void* __attribute__((__cleanup__(ffLibraryUnload))) libraryObjectName = ffLibraryLoad(__VA_ARGS__, NULL);\ - if(libraryObjectName == NULL) \ - return returnValue; +# define FF_LIBRARY_LOAD(libraryObjectName, returnValue, ...) \ + void* __attribute__((__cleanup__(ffLibraryUnload))) libraryObjectName = ffLibraryLoad(__VA_ARGS__, NULL); \ + if (libraryObjectName == NULL) \ + return returnValue; -#define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ - FF_LIBRARY_LOAD(libraryObjectName, "dlopen(" libraryFileName ") failed", libraryFileName, maxVersion, ##__VA_ARGS__) +# define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ + FF_LIBRARY_LOAD(libraryObjectName, "dlopen(" libraryFileName ") failed", libraryFileName, maxVersion, ##__VA_ARGS__) -#define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \ - symbolMapping = (__typeof__(&symbolName)) dlsym(library, #symbolName); \ - if(symbolMapping == NULL) \ - return returnValue; +# define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \ + symbolMapping = (__typeof__(&symbolName)) dlsym(library, #symbolName); \ + if (symbolMapping == NULL) \ + return returnValue; -#define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \ - __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff ## symbolName, symbolName, returnValue); +# define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \ + __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, returnValue); -#define FF_LIBRARY_LOAD_SYMBOL_LAZY(library, symbolName) \ - __auto_type ff ## symbolName = (__typeof__(&symbolName)) dlsym(library, #symbolName); +# define FF_LIBRARY_LOAD_SYMBOL_LAZY(library, symbolName) \ + __auto_type ff##symbolName = (__typeof__(&symbolName)) dlsym(library, #symbolName); -#define FF_LIBRARY_LOAD_SYMBOL_MESSAGE(library, symbolName) \ - __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff ## symbolName, symbolName, "dlsym " #symbolName " failed"); +# define FF_LIBRARY_LOAD_SYMBOL_MESSAGE(library, symbolName) \ + __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, "dlsym " #symbolName " failed"); -#define FF_LIBRARY_LOAD_SYMBOL_VAR(library, varName, symbolName, returnValue) \ - FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff ## symbolName, symbolName, returnValue); +# define FF_LIBRARY_LOAD_SYMBOL_VAR(library, varName, symbolName, returnValue) \ + FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, returnValue); -#define FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(library, varName, symbolName) \ - FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff ## symbolName, symbolName, "dlsym " #symbolName " failed"); +# define FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(library, varName, symbolName) \ + FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, "dlsym " #symbolName " failed"); -#define FF_LIBRARY_LOAD_SYMBOL_PTR(library, varName, symbolName, returnValue) \ - FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName)->ff ## symbolName, symbolName, returnValue); +# define FF_LIBRARY_LOAD_SYMBOL_PTR(library, varName, symbolName, returnValue) \ + FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName)->ff##symbolName, symbolName, returnValue); void* ffLibraryLoad(const char* path, int maxVersion, ...); #else -#define FF_LIBRARY_EXTENSION "" +# define FF_LIBRARY_EXTENSION "" -#define FF_LIBRARY_SYMBOL(symbolName) \ - __typeof__(&symbolName) ff ## symbolName; +# define FF_LIBRARY_SYMBOL(symbolName) \ + __typeof__(&symbolName) ff##symbolName; -#define FF_LIBRARY_LOAD(libraryObjectName, returnValue, ...) \ - FF_MAYBE_UNUSED void* libraryObjectName = NULL; // Placeholder +# define FF_LIBRARY_LOAD(libraryObjectName, returnValue, ...) \ + FF_MAYBE_UNUSED void* libraryObjectName = NULL; // Placeholder -#define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ - FF_LIBRARY_LOAD(libraryObjectName, , libraryFileName, maxVersion, ##__VA_ARGS__) +# define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ + FF_LIBRARY_LOAD(libraryObjectName, , libraryFileName, maxVersion, ##__VA_ARGS__) -#define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \ - symbolMapping = (__typeof__(&symbolName)) &symbolName; +# define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \ + symbolMapping = (__typeof__(&symbolName)) &symbolName; -#define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \ - FF_MAYBE_UNUSED __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff ## symbolName, symbolName, returnValue); +# define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \ + FF_MAYBE_UNUSED __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, returnValue); -#define FF_LIBRARY_LOAD_SYMBOL_LAZY(library, symbolName) \ - FF_MAYBE_UNUSED __auto_type ff ## symbolName = (__typeof__(&symbolName)) &symbolName; +# define FF_LIBRARY_LOAD_SYMBOL_LAZY(library, symbolName) \ + FF_MAYBE_UNUSED __auto_type ff##symbolName = (__typeof__(&symbolName)) &symbolName; -#define FF_LIBRARY_LOAD_SYMBOL_MESSAGE(library, symbolName) \ - FF_MAYBE_UNUSED __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff ## symbolName, symbolName, "dlsym " #symbolName " failed"); +# define FF_LIBRARY_LOAD_SYMBOL_MESSAGE(library, symbolName) \ + FF_MAYBE_UNUSED __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, "dlsym " #symbolName " failed"); -#define FF_LIBRARY_LOAD_SYMBOL_VAR(library, varName, symbolName, returnValue) \ - FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff ## symbolName, symbolName, returnValue); +# define FF_LIBRARY_LOAD_SYMBOL_VAR(library, varName, symbolName, returnValue) \ + FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, returnValue); -#define FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(library, varName, symbolName) \ - FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff ## symbolName, symbolName, "dlsym " #symbolName " failed"); +# define FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(library, varName, symbolName) \ + FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, "dlsym " #symbolName " failed"); -#define FF_LIBRARY_LOAD_SYMBOL_PTR(library, varName, symbolName, returnValue) \ - FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName)->ff ## symbolName, symbolName, returnValue); +# define FF_LIBRARY_LOAD_SYMBOL_PTR(library, varName, symbolName, returnValue) \ + FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName)->ff##symbolName, symbolName, returnValue); #endif diff --git a/src/common/mallocHelper.h b/src/common/mallocHelper.h index a36423d69..215cf3d78 100644 --- a/src/common/mallocHelper.h +++ b/src/common/mallocHelper.h @@ -4,36 +4,35 @@ #include #if FF_HAVE_MALLOC_USABLE_SIZE || FF_HAVE_MSVC_MSIZE - #if __has_include() - #include - #else - #include // For DragonFly BSD - #endif +# if __has_include() +# include +# else +# include // For DragonFly BSD +# endif #elif FF_HAVE_MALLOC_SIZE - #include +# include #endif -static inline void ffWrapFree(const void* pPtr) -{ +static inline void ffWrapFree(const void* pPtr) { assert(pPtr); - if(*(void**)pPtr) - free(*(void**)pPtr); + if (*(void**) pPtr) { + free(*(void**) pPtr); + } } #define FF_AUTO_FREE __attribute__((__cleanup__(ffWrapFree))) // ptr MUST be a malloc'ed pointer -static inline size_t ffMallocUsableSize(const void* ptr) -{ +static inline size_t ffMallocUsableSize(const void* ptr) { assert(ptr); - #if FF_HAVE_MALLOC_USABLE_SIZE - return malloc_usable_size((void*) ptr); - #elif FF_HAVE_MALLOC_SIZE - return malloc_size((void*) ptr); - #elif FF_HAVE_MSVC_MSIZE - return _msize((void*) ptr); - #else - (void) ptr; - return 0; // Not supported - #endif +#if FF_HAVE_MALLOC_USABLE_SIZE + return malloc_usable_size((void*) ptr); +#elif FF_HAVE_MALLOC_SIZE + return malloc_size((void*) ptr); +#elif FF_HAVE_MSVC_MSIZE + return _msize((void*) ptr); +#else + (void) ptr; + return 0; // Not supported +#endif } diff --git a/src/common/netif.h b/src/common/netif.h index 99a1a69a0..3449145b5 100644 --- a/src/common/netif.h +++ b/src/common/netif.h @@ -3,8 +3,8 @@ #include "fastfetch.h" #ifndef _WIN32 - #include - #include +# include +# include #endif typedef enum __attribute__((__packed__)) FFNetifDefaultRouteResultStatus { @@ -16,10 +16,10 @@ typedef enum __attribute__((__packed__)) FFNetifDefaultRouteResultStatus { typedef struct FFNetifDefaultRouteResult { uint32_t ifIndex; - #ifndef _WIN32 +#ifndef _WIN32 char ifName[IF_NAMESIZE + 1]; uint32_t preferredSourceAddrV4; - #endif +#endif enum FFNetifDefaultRouteResultStatus status; } FFNetifDefaultRouteResult; diff --git a/src/common/networking.h b/src/common/networking.h index 91428b705..d4efb62ca 100644 --- a/src/common/networking.h +++ b/src/common/networking.h @@ -4,29 +4,29 @@ #include "common/FFstrbuf.h" #ifdef _WIN32 - #include +# include #endif struct addrinfo; typedef struct FFNetworkingState { - #ifdef _WIN32 - uintptr_t sockfd; - OVERLAPPED overlapped; - #else - int sockfd; - struct addrinfo* addr; +#ifdef _WIN32 + uintptr_t sockfd; + OVERLAPPED overlapped; +#else + int sockfd; + struct addrinfo* addr; - #ifdef FF_HAVE_THREADS - FFThreadType thread; - #endif - #endif +# ifdef FF_HAVE_THREADS + FFThreadType thread; +# endif +#endif FFstrbuf command; uint32_t timeout; bool ipv6; bool compression; // if true, HTTP content compression will be enabled if supported - bool tfo; // if true, TCP Fast Open will be attempted first, and fallback to traditional connection if it fails + bool tfo; // if true, TCP Fast Open will be attempted first, and fallback to traditional connection if it fails } FFNetworkingState; const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers); diff --git a/src/common/option.h b/src/common/option.h index 00a082361..76f6620fa 100644 --- a/src/common/option.h +++ b/src/common/option.h @@ -6,23 +6,20 @@ struct yyjson_val; struct yyjson_mut_doc; struct yyjson_mut_val; -typedef struct FFModuleFormatArg -{ +typedef struct FFModuleFormatArg { const char* desc; const char* name; } FFModuleFormatArg; -typedef struct FFModuleFormatArgList -{ +typedef struct FFModuleFormatArgList { FFModuleFormatArg* args; uint32_t count; } FFModuleFormatArgList; -#define FF_FORMAT_ARG_LIST(list) { .args = list, .count = sizeof(list) / sizeof(FFModuleFormatArg) } +#define FF_FORMAT_ARG_LIST(list) {.args = list, .count = sizeof(list) / sizeof(FFModuleFormatArg)} // Must be the first field of FFModuleOptions -typedef struct FFModuleBaseInfo -{ +typedef struct FFModuleBaseInfo { const char* name; const char* description; // A dirty polymorphic implementation in C. @@ -32,15 +29,14 @@ typedef struct FFModuleBaseInfo void (*initOptions)(void* options); void (*destroyOptions)(void* options); - void (*parseJsonObject)(void* options, struct yyjson_val *module); - bool (*printModule)(void* options); // true on success + void (*parseJsonObject)(void* options, struct yyjson_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; -typedef enum __attribute__((__packed__)) FFModuleKeyType -{ +typedef enum __attribute__((__packed__)) FFModuleKeyType { FF_MODULE_KEY_TYPE_NONE = 0, FF_MODULE_KEY_TYPE_STRING = 1 << 0, FF_MODULE_KEY_TYPE_ICON = 1 << 1, @@ -54,8 +50,7 @@ typedef enum __attribute__((__packed__)) FFModuleKeyType FF_MODULE_KEY_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFModuleKeyType; -typedef struct FFModuleArgs -{ +typedef struct FFModuleArgs { FFstrbuf key; FFstrbuf keyColor; FFstrbuf keyIcon; @@ -64,8 +59,7 @@ typedef struct FFModuleArgs uint32_t keyWidth; } FFModuleArgs; -typedef struct FFKeyValuePair -{ +typedef struct FFKeyValuePair { const char* key; int value; } FFKeyValuePair; @@ -77,14 +71,12 @@ FF_C_NODISCARD int32_t ffOptionParseInt32(const char* argumentKey, const char* v FF_C_NODISCARD int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]); FF_C_NODISCARD bool ffOptionParseBoolean(const char* str); void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer); -static inline void ffOptionParseColor(const char* value, FFstrbuf* buffer) -{ +static inline void ffOptionParseColor(const char* value, FFstrbuf* buffer) { ffStrbufClear(buffer); ffOptionParseColorNoClear(value, buffer); } -static inline void ffOptionInitModuleArg(FFModuleArgs* args, const char* icon) -{ +static inline void ffOptionInitModuleArg(FFModuleArgs* args, const char* icon) { ffStrbufInit(&args->key); ffStrbufInit(&args->keyColor); ffStrbufInitStatic(&args->keyIcon, icon); @@ -93,8 +85,7 @@ static inline void ffOptionInitModuleArg(FFModuleArgs* args, const char* icon) args->keyWidth = 0; } -static inline void ffOptionDestroyModuleArg(FFModuleArgs* args) -{ +static inline void ffOptionDestroyModuleArg(FFModuleArgs* args) { ffStrbufDestroy(&args->key); ffStrbufDestroy(&args->keyColor); ffStrbufDestroy(&args->keyIcon); diff --git a/src/common/parsing.h b/src/common/parsing.h index f870fd185..17097722f 100644 --- a/src/common/parsing.h +++ b/src/common/parsing.h @@ -4,15 +4,13 @@ #include -typedef struct FFVersion -{ +typedef struct FFVersion { uint32_t major; uint32_t minor; uint32_t patch; } FFVersion; -typedef struct FFColorRangeConfig -{ +typedef struct FFColorRangeConfig { uint8_t green; uint8_t yellow; } FFColorRangeConfig; diff --git a/src/common/path.h b/src/common/path.h index 73680034c..79d181df2 100644 --- a/src/common/path.h +++ b/src/common/path.h @@ -4,19 +4,18 @@ #include "common/stringUtils.h" const char* ffFindExecutableInPath(const char* name, FFstrbuf* result); -static inline bool ffIsAbsolutePath(const char* path) -{ - #ifdef _WIN32 +static inline bool ffIsAbsolutePath(const char* path) { +#ifdef _WIN32 return (ffCharIsEnglishAlphabet(path[0]) && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) // drive letter path - || (path[0] == '\\' && path[1] == '\\'); // UNC path - #else + || (path[0] == '\\' && path[1] == '\\'); // UNC path +#else return path[0] == '/'; - #endif +#endif } #if _WIN32 char* frealpath(void* __restrict hFile, char* __restrict resolved_name /*MAX_PATH*/); -char* realpath(const char* __restrict file_name, char* __restrict resolved_name /*MAX_PATH*/); +char* realpath(const char* __restrict file_name, char* __restrict resolved_name /*MAX_PATH*/); ssize_t freadlink(void* hFile, char* buf, size_t bufsiz); ssize_t readlink(const char* path, char* buf, size_t bufsiz); #endif diff --git a/src/common/percent.h b/src/common/percent.h index 4ce3c2f0b..5cd4c9c00 100644 --- a/src/common/percent.h +++ b/src/common/percent.h @@ -4,8 +4,7 @@ #include "common/parsing.h" #include "common/option.h" -typedef enum __attribute__((__packed__)) FFPercentageTypeFlags -{ +typedef enum __attribute__((__packed__)) FFPercentageTypeFlags { FF_PERCENTAGE_TYPE_NONE = 0, FF_PERCENTAGE_TYPE_NUM_BIT = 1 << 0, FF_PERCENTAGE_TYPE_BAR_BIT = 1 << 1, @@ -16,8 +15,7 @@ typedef enum __attribute__((__packed__)) FFPercentageTypeFlags } FFPercentageTypeFlags; static_assert(sizeof(FFPercentageTypeFlags) == 1, ""); -typedef struct FFPercentageModuleConfig -{ +typedef struct FFPercentageModuleConfig { uint8_t green; uint8_t yellow; FFPercentageTypeFlags type; diff --git a/src/common/printing.h b/src/common/printing.h index 1ee79d540..9cc99b1b2 100644 --- a/src/common/printing.h +++ b/src/common/printing.h @@ -16,6 +16,7 @@ void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModu void ffPrintFormat(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, uint32_t numArgs, const FFformatarg* arguments); #define FF_PRINT_FORMAT_CHECKED(moduleName, moduleIndex, moduleArgs, printType, arguments) \ ffPrintFormat((moduleName), (moduleIndex), (moduleArgs), (printType), (sizeof(arguments) / sizeof(*arguments)), (arguments)); -FF_C_PRINTF(5, 6) void ffPrintError(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, const char* message, ...); +FF_C_PRINTF(5, 6) +void ffPrintError(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, const char* message, ...); void ffPrintColor(const FFstrbuf* colorValue); void ffPrintCharTimes(char c, uint32_t times); diff --git a/src/common/processing.h b/src/common/processing.h index c62235ca2..5c347675a 100644 --- a/src/common/processing.h +++ b/src/common/processing.h @@ -3,43 +3,47 @@ #include "common/FFstrbuf.h" #ifndef _WIN32 -#include // pid_t +# include // pid_t #endif typedef struct FFProcessHandle { - #if _WIN32 - void* pid; // HANDLE +#if _WIN32 + void* pid; // HANDLE void* pipeRead; // HANDLE - #else +#else pid_t pid; int pipeRead; - #endif +#endif } FFProcessHandle; const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle); const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer); // Destroys handle internally -static inline const char* ffProcessAppendStdOut(FFstrbuf* buffer, char* const argv[]) -{ +static inline const char* ffProcessAppendStdOut(FFstrbuf* buffer, char* const argv[]) { FFProcessHandle handle; const char* error = ffProcessSpawn(argv, false, &handle); - if (error) return error; + if (error) { + return error; + } error = ffProcessReadOutput(&handle, buffer); - if (!error) + if (!error) { ffStrbufTrimRightSpace(buffer); + } return error; } -static inline const char* ffProcessAppendStdErr(FFstrbuf* buffer, char* const argv[]) -{ +static inline const char* ffProcessAppendStdErr(FFstrbuf* buffer, char* const argv[]) { FFProcessHandle handle; const char* error = ffProcessSpawn(argv, true, &handle); - if (error) return error; + if (error) { + return error; + } error = ffProcessReadOutput(&handle, buffer); - if (!error) + if (!error) { ffStrbufTrimRightSpace(buffer); + } return error; } diff --git a/src/common/properties.h b/src/common/properties.h index 9cc9ff34f..319854886 100644 --- a/src/common/properties.h +++ b/src/common/properties.h @@ -2,8 +2,7 @@ #include "fastfetch.h" -typedef struct FFpropquery -{ +typedef struct FFpropquery { const char* start; FFstrbuf* buffer; } FFpropquery; @@ -15,42 +14,34 @@ bool ffParsePropFileListValues(const FFlist* list, const char* relativeFile, uin bool ffParsePropLinePointer(const char** line, const char* start, FFstrbuf* buffer); -static inline bool ffParsePropLine(const char* line, const char* start, FFstrbuf* buffer) -{ +static inline bool ffParsePropLine(const char* line, const char* start, FFstrbuf* buffer) { return ffParsePropLinePointer(&line, start, buffer); } -static inline bool ffParsePropFile(const char* filename, const char* start, FFstrbuf* buffer) -{ - return ffParsePropFileValues(filename, 1, (FFpropquery[]){{start, buffer}}); +static inline bool ffParsePropFile(const char* filename, const char* start, FFstrbuf* buffer) { + return ffParsePropFileValues(filename, 1, (FFpropquery[]) {{start, buffer}}); } -static inline bool ffParsePropFileHome(const char* relativeFile, const char* start, FFstrbuf* buffer) -{ - return ffParsePropFileHomeValues(relativeFile, 1, (FFpropquery[]){{start, buffer}}); +static inline bool ffParsePropFileHome(const char* relativeFile, const char* start, FFstrbuf* buffer) { + return ffParsePropFileHomeValues(relativeFile, 1, (FFpropquery[]) {{start, buffer}}); } -static inline bool ffParsePropFileList(const FFlist* list, const char* relativeFile, const char* start, FFstrbuf* buffer) -{ - return ffParsePropFileListValues(list, relativeFile, 1, (FFpropquery[]){{start, buffer}}); +static inline bool ffParsePropFileList(const FFlist* list, const char* relativeFile, const char* start, FFstrbuf* buffer) { + return ffParsePropFileListValues(list, relativeFile, 1, (FFpropquery[]) {{start, buffer}}); } -static inline bool ffParsePropFileConfigValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) -{ +static inline bool ffParsePropFileConfigValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) { return ffParsePropFileListValues(&instance.state.platform.configDirs, relativeFile, numQueries, queries); } -static inline bool ffParsePropFileConfig(const char* relativeFile, const char* start, FFstrbuf* buffer) -{ - return ffParsePropFileConfigValues(relativeFile, 1, (FFpropquery[]){{start, buffer}}); +static inline bool ffParsePropFileConfig(const char* relativeFile, const char* start, FFstrbuf* buffer) { + return ffParsePropFileConfigValues(relativeFile, 1, (FFpropquery[]) {{start, buffer}}); } -static inline bool ffParsePropFileDataValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) -{ +static inline bool ffParsePropFileDataValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) { return ffParsePropFileListValues(&instance.state.platform.dataDirs, relativeFile, numQueries, queries); } -static inline bool ffParsePropFileData(const char* relativeFile, const char* start, FFstrbuf* buffer) -{ - return ffParsePropFileDataValues(relativeFile, 1, (FFpropquery[]){{start, buffer}}); +static inline bool ffParsePropFileData(const char* relativeFile, const char* start, FFstrbuf* buffer) { + return ffParsePropFileDataValues(relativeFile, 1, (FFpropquery[]) {{start, buffer}}); } diff --git a/src/common/settings.h b/src/common/settings.h index 86fd66313..32419b9c1 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -2,15 +2,13 @@ #include "fastfetch.h" -typedef enum __attribute__((__packed__)) FFvarianttype -{ +typedef enum __attribute__((__packed__)) FFvarianttype { FF_VARIANT_TYPE_STRING, FF_VARIANT_TYPE_BOOL, FF_VARIANT_TYPE_INT } FFvarianttype; -typedef union FFvariant -{ +typedef union FFvariant { const char* strValue; int32_t intValue; struct @@ -20,7 +18,7 @@ typedef union FFvariant }; } FFvariant; -#define FF_VARIANT_NULL ((FFvariant){.strValue = NULL}) +#define FF_VARIANT_NULL ((FFvariant) {.strValue = NULL}) FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type); FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type); diff --git a/src/common/smbiosHelper.h b/src/common/smbiosHelper.h index d4d62c5f0..057e5e45b 100644 --- a/src/common/smbiosHelper.h +++ b/src/common/smbiosHelper.h @@ -3,10 +3,10 @@ #include "common/FFstrbuf.h" bool ffIsSmbiosValueSet(FFstrbuf* value); -static inline void ffCleanUpSmbiosValue(FFstrbuf* value) -{ - if (!ffIsSmbiosValueSet(value)) +static inline void ffCleanUpSmbiosValue(FFstrbuf* value) { + if (!ffIsSmbiosValueSet(value)) { ffStrbufClear(value); + } } // https://github.com/KunYi/DumpSMBIOS @@ -20,7 +20,7 @@ typedef enum __attribute__((__packed__)) FFSmbiosType // : uint8_t FF_SMBIOS_TYPE_SYSTEM_ENCLOSURE = 3, FF_SMBIOS_TYPE_PROCESSOR_INFO = 4, FF_SMBIOS_TYPE_MEMORY_CONTROLLER_INFO = 5, // obsolete - FF_SMBIOS_TYPE_MEMORY_MODULE_INFO = 6, // obsolete + FF_SMBIOS_TYPE_MEMORY_MODULE_INFO = 6, // obsolete FF_SMBIOS_TYPE_CACHE_INFO = 7, FF_SMBIOS_TYPE_PORT_CONNECTOR_INFO = 8, FF_SMBIOS_TYPE_SYSTEM_SLOTS = 9, @@ -68,8 +68,7 @@ typedef enum __attribute__((__packed__)) FFSmbiosType // : uint8_t } FFSmbiosType; static_assert(sizeof(FFSmbiosType) == 1, "FFSmbiosType should be 1 byte"); -typedef struct FFSmbiosHeader -{ +typedef struct FFSmbiosHeader { // Type of SMBIOS structure. Do NOT test `Type == FF_SMBIOS_END_OF_TABLE` to determine the end of the table, // as malformed tables may be missing the end-of-table marker. // **Use FFSmbiosHeaderTable[FF_SMBIOS_TYPE_END_OF_TABLE] pointer instead.** @@ -83,12 +82,13 @@ typedef struct FFSmbiosHeader } __attribute__((__packed__)) FFSmbiosHeader; static_assert(sizeof(FFSmbiosHeader) == 4, "FFSmbiosHeader should be 4 bytes"); -static inline const char* ffSmbiosLocateString(const char* start, uint8_t index /* start from 1 */) -{ - if (index == 0 || *start == '\0') +static inline const char* ffSmbiosLocateString(const char* start, uint8_t index /* start from 1 */) { + if (index == 0 || *start == '\0') { return NULL; - while (--index) + } + while (--index) { start += strlen(start) + 1; + } return start; } diff --git a/src/common/stringUtils.h b/src/common/stringUtils.h index 3afbe6ec3..34e5cc832 100644 --- a/src/common/stringUtils.h +++ b/src/common/stringUtils.h @@ -5,102 +5,93 @@ #include #include -static inline bool ffStrSet(const char* str) -{ - if(str == NULL) +static inline bool ffStrSet(const char* str) { + if (str == NULL) { return false; + } - while(isspace(*str)) + while (isspace(*str)) { str++; + } return *str != '\0'; } - -static inline bool ffStrStartsWithIgnCase(const char* str, const char* compareTo) -{ +static inline bool ffStrStartsWithIgnCase(const char* str, const char* compareTo) { return strncasecmp(str, compareTo, strlen(compareTo)) == 0; } -static inline bool ffStrEqualsIgnCase(const char* str, const char* compareTo) -{ +static inline bool ffStrEqualsIgnCase(const char* str, const char* compareTo) { return strcasecmp(str, compareTo) == 0; } -static inline bool ffStrStartsWith(const char* str, const char* compareTo) -{ +static inline bool ffStrStartsWith(const char* str, const char* compareTo) { return strncmp(str, compareTo, strlen(compareTo)) == 0; } -static inline bool ffStrEndsWith(const char* str, const char* compareTo) -{ +static inline bool ffStrEndsWith(const char* str, const char* compareTo) { size_t strLength = strlen(str); size_t compareToLength = strlen(compareTo); - if (strLength < compareToLength) + if (strLength < compareToLength) { return false; + } return memcmp(str + strLength - compareToLength, compareTo, compareToLength) == 0; } -static inline bool ffStrEndsWithIgnCase(const char* str, const char* compareTo) -{ +static inline bool ffStrEndsWithIgnCase(const char* str, const char* compareTo) { size_t strLength = strlen(str); size_t compareToLength = strlen(compareTo); - if (strLength < compareToLength) + if (strLength < compareToLength) { return false; + } return strncasecmp(str + strLength - compareToLength, compareTo, compareToLength) == 0; } -static inline bool ffStrEquals(const char* str, const char* compareTo) -{ +static inline bool ffStrEquals(const char* str, const char* compareTo) { return strcmp(str, compareTo) == 0; } -static inline bool ffStrContains(const char* str, const char* compareTo) -{ +static inline bool ffStrContains(const char* str, const char* compareTo) { return strstr(str, compareTo) != NULL; } -static inline bool ffStrContainsIgnCase(const char* str, const char* compareTo) -{ +static inline bool ffStrContainsIgnCase(const char* str, const char* compareTo) { return strcasestr(str, compareTo) != NULL; } -static inline bool ffStrContainsC(const char* str, char compareTo) -{ +static inline bool ffStrContainsC(const char* str, char compareTo) { return strchr(str, compareTo) != NULL; } -static inline bool ffCharIsEnglishAlphabet(char c) -{ +static inline bool ffCharIsEnglishAlphabet(char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } -static inline bool ffCharIsDigit(char c) -{ +static inline bool ffCharIsDigit(char c) { return '0' <= c && c <= '9'; } -static inline bool ffCharIsHexDigit(char c) -{ +static inline bool ffCharIsHexDigit(char c) { return ffCharIsDigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'); } -static inline int8_t ffHexCharToInt(char c) -{ - if (ffCharIsDigit(c)) +static inline int8_t ffHexCharToInt(char c) { + if (ffCharIsDigit(c)) { return (int8_t) (c - '0'); - else if ('a' <= c && c <= 'f') + } else if ('a' <= c && c <= 'f') { return (int8_t) (c - 'a' + 10); - else if ('A' <= c && c <= 'F') + } else if ('A' <= c && c <= 'F') { return (int8_t) (c - 'A' + 10); - else + } else { return -1; + } } // Copies at most (dstBufSiz - 1) bytes from src to dst; dst is always null-terminated -static inline char* ffStrCopy(char* __restrict__ dst, const char* __restrict__ src, size_t dstBufSiz) -{ - if (__builtin_expect(dst == NULL, false) || dstBufSiz == 0) return dst; +static inline char* ffStrCopy(char* __restrict__ dst, const char* __restrict__ src, size_t dstBufSiz) { + if (__builtin_expect(dst == NULL, false) || dstBufSiz == 0) { + return dst; + } size_t len = strnlen(src, dstBufSiz - 1); memcpy(dst, src, len); diff --git a/src/common/textModifier.h b/src/common/textModifier.h index dbc4338cd..77d6e5595 100644 --- a/src/common/textModifier.h +++ b/src/common/textModifier.h @@ -1,5 +1,5 @@ #pragma once -#define FASTFETCH_TEXT_MODIFIER_BOLT "\033[1m" +#define FASTFETCH_TEXT_MODIFIER_BOLT "\033[1m" #define FASTFETCH_TEXT_MODIFIER_ERROR "\033[1;31m" #define FASTFETCH_TEXT_MODIFIER_RESET "\033[m" diff --git a/src/common/thread.h b/src/common/thread.h index dbe0da108..bc4f1ee91 100644 --- a/src/common/thread.h +++ b/src/common/thread.h @@ -3,87 +3,115 @@ #include "fastfetch.h" #ifdef FF_HAVE_THREADS - #if defined(_WIN32) - #include - #include - #include - #include - #define FF_THREAD_MUTEX_INITIALIZER SRWLOCK_INIT - typedef SRWLOCK FFThreadMutex; - typedef HANDLE FFThreadType; - static inline void ffThreadMutexLock(FFThreadMutex* mutex) { AcquireSRWLockExclusive(mutex); } - static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) { ReleaseSRWLockExclusive(mutex); } - static inline FFThreadType ffThreadCreate(unsigned (__stdcall* func)(void*), void* data) { - return (FFThreadType)_beginthreadex(NULL, 0, func, data, 0, NULL); - } - #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) static __stdcall unsigned fn ## ThreadMain (void* data) { fn((paramType)data); return 0; } - #define FF_THREAD_ENTRY_DECL_WRAPPER_NOPARAM(fn) static __stdcall unsigned fn ## ThreadMain () { fn(); return 0; } - static inline void ffThreadDetach(FFThreadType thread) { NtClose(thread); } - static inline bool ffThreadJoin(FFThreadType thread, uint32_t timeout) - { - if (NtWaitForSingleObject(thread, FALSE, timeout == 0 ? NULL : &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 }) != STATUS_WAIT_0) - { - TerminateThread(thread, (DWORD) -1); - NtClose(thread); +# if defined(_WIN32) +# include +# include +# include +# include +# define FF_THREAD_MUTEX_INITIALIZER SRWLOCK_INIT +typedef SRWLOCK FFThreadMutex; +typedef HANDLE FFThreadType; +static inline void ffThreadMutexLock(FFThreadMutex* mutex) { + AcquireSRWLockExclusive(mutex); +} +static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) { + ReleaseSRWLockExclusive(mutex); +} +static inline FFThreadType ffThreadCreate(unsigned(__stdcall* func)(void*), void* data) { + return (FFThreadType) _beginthreadex(NULL, 0, func, data, 0, NULL); +} +# define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \ + static __stdcall unsigned fn##ThreadMain(void* data) { \ + fn((paramType) data); \ + return 0; \ + } +# define FF_THREAD_ENTRY_DECL_WRAPPER_NOPARAM(fn) \ + static __stdcall unsigned fn##ThreadMain() { \ + fn(); \ + return 0; \ + } +static inline void ffThreadDetach(FFThreadType thread) { + NtClose(thread); +} +static inline bool ffThreadJoin(FFThreadType thread, uint32_t timeout) { + if (NtWaitForSingleObject(thread, FALSE, timeout == 0 ? NULL : &(LARGE_INTEGER) {.QuadPart = (int64_t) timeout * -10000}) != STATUS_WAIT_0) { + TerminateThread(thread, (DWORD) -1); + NtClose(thread); + return false; + } + NtClose(thread); + return true; +} +# else +# include +# include +# if FF_HAVE_PTHREAD_NP +# include +# endif +typedef pthread_t FFThreadType; +# if __APPLE__ +# include +# define FF_THREAD_MUTEX_INITIALIZER OS_UNFAIR_LOCK_INIT +typedef os_unfair_lock FFThreadMutex; +static inline void ffThreadMutexLock(os_unfair_lock* mutex) { + os_unfair_lock_lock(mutex); +} +static inline void ffThreadMutexUnlock(os_unfair_lock* mutex) { + os_unfair_lock_unlock(mutex); +} +# else +# define FF_THREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER +typedef pthread_mutex_t FFThreadMutex; +static inline void ffThreadMutexLock(FFThreadMutex* mutex) { + pthread_mutex_lock(mutex); +} +static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) { + pthread_mutex_unlock(mutex); +} +# endif +static inline FFThreadType ffThreadCreate(void* (*func)(void*), void* data) { + FFThreadType newThread = 0; + pthread_create(&newThread, NULL, func, data); + return newThread; +} +# define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \ + static void* fn##ThreadMain(void* data) { \ + fn((paramType) data); \ + return NULL; \ + } +# define FF_THREAD_ENTRY_DECL_WRAPPER_NOPARAM(fn) \ + static void* fn##ThreadMain() { \ + fn(); \ + return NULL; \ + } +static inline void ffThreadDetach(FFThreadType thread) { + pthread_detach(thread); +} +static inline bool ffThreadJoin(FFThreadType thread, FF_MAYBE_UNUSED uint32_t timeout) { +# if HAVE_TIMEDJOIN_NP + if (timeout > 0) { + struct timespec ts; + if (clock_gettime(CLOCK_REALTIME, &ts) == 0) { + ts.tv_sec += timeout / 1000; + ts.tv_nsec += (timeout % 1000) * 1000000; + if (pthread_timedjoin_np(thread, NULL, &ts) != 0) { + pthread_kill(thread, SIGTERM); return false; } - NtClose(thread); return true; } - #else - #include - #include - #if FF_HAVE_PTHREAD_NP - #include - #endif - typedef pthread_t FFThreadType; - #if __APPLE__ - #include - #define FF_THREAD_MUTEX_INITIALIZER OS_UNFAIR_LOCK_INIT - typedef os_unfair_lock FFThreadMutex; - static inline void ffThreadMutexLock(os_unfair_lock* mutex) { os_unfair_lock_lock(mutex); } - static inline void ffThreadMutexUnlock(os_unfair_lock* mutex) { os_unfair_lock_unlock(mutex); } - #else - #define FF_THREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER - typedef pthread_mutex_t FFThreadMutex; - static inline void ffThreadMutexLock(FFThreadMutex* mutex) { pthread_mutex_lock(mutex); } - static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) { pthread_mutex_unlock(mutex); } - #endif - static inline FFThreadType ffThreadCreate(void* (* func)(void*), void* data) { - FFThreadType newThread = 0; - pthread_create(&newThread, NULL, func, data); - return newThread; - } - #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) static void* fn ## ThreadMain (void* data) { fn((paramType)data); return NULL; } - #define FF_THREAD_ENTRY_DECL_WRAPPER_NOPARAM(fn) static void* fn ## ThreadMain () { fn(); return NULL; } - static inline void ffThreadDetach(FFThreadType thread) { pthread_detach(thread); } - static inline bool ffThreadJoin(FFThreadType thread, FF_MAYBE_UNUSED uint32_t timeout) - { - #if HAVE_TIMEDJOIN_NP - if (timeout > 0) - { - struct timespec ts; - if (clock_gettime(CLOCK_REALTIME, &ts) == 0) - { - ts.tv_sec += timeout / 1000; - ts.tv_nsec += (timeout % 1000) * 1000000; - if (pthread_timedjoin_np(thread, NULL, &ts) != 0) - { - pthread_kill(thread, SIGTERM); - return false; - } - return true; - } - } - #endif - pthread_join(thread, NULL); - return true; - } - #endif -#else //FF_HAVE_THREADS - #define FF_THREAD_MUTEX_INITIALIZER 0 - typedef char FFThreadMutex; - static inline void ffThreadMutexLock(FFThreadMutex* mutex) { FF_UNUSED(mutex) } - static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) { FF_UNUSED(mutex) } - #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) -#endif //FF_HAVE_THREADS + } +# endif + pthread_join(thread, NULL); + return true; +} +# endif +#else // FF_HAVE_THREADS +# define FF_THREAD_MUTEX_INITIALIZER 0 +typedef char FFThreadMutex; +static inline void ffThreadMutexLock(FFThreadMutex* mutex) { + FF_UNUSED(mutex) +} +static inline void ffThreadMutexUnlock(FFThreadMutex* mutex){FF_UNUSED(mutex)} +# define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) +#endif // FF_HAVE_THREADS diff --git a/src/common/time.h b/src/common/time.h index 0156a9c72..af950802b 100644 --- a/src/common/time.h +++ b/src/common/time.h @@ -4,64 +4,62 @@ #include #include #ifdef _WIN32 - #include - #include "common/windows/nt.h" - #include +# include +# include "common/windows/nt.h" +# include #elif defined(__HAIKU__) - #include +# include #endif #include "common/arrayUtils.h" -static inline double ffTimeGetTick(void) //In msec +static inline double ffTimeGetTick(void) // In msec { - #ifdef _WIN32 - extern double ffQpcMultiplier; - LARGE_INTEGER start; - RtlQueryPerformanceCounter(&start); - return (double) start.QuadPart * ffQpcMultiplier; - #elif defined(__HAIKU__) - return (double) system_time() / 1000.; - #else - struct timespec timeNow; - clock_gettime(CLOCK_MONOTONIC, &timeNow); - return (double) timeNow.tv_sec * 1000. + (double) timeNow.tv_nsec / 1000000.; - #endif +#ifdef _WIN32 + extern double ffQpcMultiplier; + LARGE_INTEGER start; + RtlQueryPerformanceCounter(&start); + return (double) start.QuadPart * ffQpcMultiplier; +#elif defined(__HAIKU__) + return (double) system_time() / 1000.; +#else + struct timespec timeNow; + clock_gettime(CLOCK_MONOTONIC, &timeNow); + return (double) timeNow.tv_sec * 1000. + (double) timeNow.tv_nsec / 1000000.; +#endif } #if _WIN32 -static inline uint64_t ffFileTimeToUnixMs(uint64_t value) -{ - if (__builtin_expect(__builtin_usubll_overflow(value, 116444736000000000ull, &value), false)) +static inline uint64_t ffFileTimeToUnixMs(uint64_t value) { + if (__builtin_expect(__builtin_usubll_overflow(value, 116444736000000000ull, &value), false)) { return 0; + } return value / 10000ull; } #endif -static inline uint64_t ffTimeGetNow(void) -{ - #ifdef _WIN32 - uint64_t timeNow = ffKSystemTimeToUInt64(&SharedUserData->SystemTime); - return ffFileTimeToUnixMs((uint64_t) timeNow); - #elif defined(__HAIKU__) - return (uint64_t) real_time_clock_usecs() / 1000u; - #else - struct timespec timeNow; - clock_gettime(CLOCK_REALTIME, &timeNow); - return (uint64_t)(((uint64_t) timeNow.tv_sec * 1000u) + ((uint64_t) timeNow.tv_nsec / 1000000u)); - #endif +static inline uint64_t ffTimeGetNow(void) { +#ifdef _WIN32 + uint64_t timeNow = ffKSystemTimeToUInt64(&SharedUserData->SystemTime); + return ffFileTimeToUnixMs((uint64_t) timeNow); +#elif defined(__HAIKU__) + return (uint64_t) real_time_clock_usecs() / 1000u; +#else + struct timespec timeNow; + clock_gettime(CLOCK_REALTIME, &timeNow); + return (uint64_t) (((uint64_t) timeNow.tv_sec * 1000u) + ((uint64_t) timeNow.tv_nsec / 1000000u)); +#endif } // Returns true if not interrupted -static inline bool ffTimeSleep(uint32_t msec) -{ - #ifdef _WIN32 - LARGE_INTEGER interval; - interval.QuadPart = -(int64_t) msec * 10000; // Relative time in 100-nanosecond intervals - return NT_SUCCESS(NtDelayExecution(TRUE, &interval)); - #else - return nanosleep(&(struct timespec){ msec / 1000, (long) (msec % 1000) * 1000000 }, NULL) == 0; - #endif +static inline bool ffTimeSleep(uint32_t msec) { +#ifdef _WIN32 + LARGE_INTEGER interval; + interval.QuadPart = -(int64_t) msec * 10000; // Relative time in 100-nanosecond intervals + return NT_SUCCESS(NtDelayExecution(TRUE, &interval)); +#else + return nanosleep(&(struct timespec) {msec / 1000, (long) (msec % 1000) * 1000000}, NULL) == 0; +#endif } // Not thread-safe @@ -73,8 +71,7 @@ const char* ffTimeToShortStr(uint64_t msec); // Not thread-safe const char* ffTimeToTimeStr(uint64_t msec); -typedef struct FFTimeGetAgeResult -{ +typedef struct FFTimeGetAgeResult { uint32_t years; uint32_t daysOfYear; double yearsFraction; diff --git a/src/common/unused.h b/src/common/unused.h index 937ac9bf9..78d85800f 100644 --- a/src/common/unused.h +++ b/src/common/unused.h @@ -1,9 +1,11 @@ #pragma once -static inline void ffUnused(int dummy, ...) { (void) dummy; } +static inline void ffUnused(int dummy, ...) { + (void) dummy; +} #define FF_UNUSED(...) ffUnused(0, __VA_ARGS__); #if defined(__GNUC__) || defined(__clang__) - #define FF_MAYBE_UNUSED __attribute__ ((__unused__)) +# define FF_MAYBE_UNUSED __attribute__((__unused__)) #else - #define FF_MAYBE_UNUSED +# define FF_MAYBE_UNUSED #endif diff --git a/src/common/wcwidth.h b/src/common/wcwidth.h index 1f972b6a0..9f65aab47 100644 --- a/src/common/wcwidth.h +++ b/src/common/wcwidth.h @@ -3,7 +3,7 @@ #include #ifdef FF_HAVE_WCWIDTH -#include +# include // Should be char32_t but it's not defined on macOS static_assert(sizeof(wchar_t) == sizeof(uint32_t), "wcwidth implementation requires wchar_t to be 32 bits"); diff --git a/src/common/windows/com.cpp b/src/common/windows/com.cpp index 47da8e319..4ad067b8d 100644 --- a/src/common/windows/com.cpp +++ b/src/common/windows/com.cpp @@ -3,18 +3,17 @@ #include -//https://learn.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer -//https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/computer-system-hardware-classes -static void CoUninitializeWrap(void) -{ +// https://learn.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer +// https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/computer-system-hardware-classes +static void CoUninitializeWrap(void) { CoUninitialize(); } -static const char* doInitCom() -{ +static const char* doInitCom() { // Initialize COM - if (FAILED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) + if (FAILED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) { return "CoInitializeEx() failed"; + } // Set general COM security levels @@ -30,8 +29,7 @@ static const char* doInitCom() NULL // Reserved ); - if (FAILED(hRes) && hRes != RPC_E_TOO_LATE /* Has been set by a random dll */) - { + if (FAILED(hRes) && hRes != RPC_E_TOO_LATE /* Has been set by a random dll */) { CoUninitialize(); return "CoInitializeSecurity() failed"; } @@ -40,10 +38,10 @@ static const char* doInitCom() return NULL; } -const char* ffInitCom(void) -{ +const char* ffInitCom(void) { static const char* error = ""; - if (error && error[0] == '\0') + if (error && error[0] == '\0') { error = doInitCom(); + } return error; } diff --git a/src/common/windows/com.hpp b/src/common/windows/com.hpp index 3714d79dc..a9cbcecb6 100644 --- a/src/common/windows/com.hpp +++ b/src/common/windows/com.hpp @@ -2,19 +2,20 @@ #ifdef __cplusplus -#include +# include const char* ffInitCom(void); -static inline void ffReleaseComObject(void* ppUnknown) -{ +static inline void ffReleaseComObject(void* ppUnknown) { IUnknown* pUnknown = *(IUnknown**) ppUnknown; - if (pUnknown) pUnknown->Release(); + if (pUnknown) { + pUnknown->Release(); + } } -#define FF_AUTO_RELEASE_COM_OBJECT __attribute__((__cleanup__(ffReleaseComObject))) +# define FF_AUTO_RELEASE_COM_OBJECT __attribute__((__cleanup__(ffReleaseComObject))) #else - // Win32 COM headers requires C++ compiler - #error Must be included in C++ source file +// Win32 COM headers requires C++ compiler +# error Must be included in C++ source file #endif diff --git a/src/common/windows/getline.c b/src/common/windows/getline.c index cb1760f78..3d43d55f3 100644 --- a/src/common/windows/getline.c +++ b/src/common/windows/getline.c @@ -3,7 +3,7 @@ #include #include -ssize_t getline(char **lineptr, size_t *n, FILE *stream) { +ssize_t getline(char** lineptr, size_t* n, FILE* stream) { ssize_t pos = -1; int c; @@ -28,13 +28,13 @@ ssize_t getline(char **lineptr, size_t *n, FILE *stream) { } pos = 0; - while(c != EOF) { - if ((size_t)(pos + 1) >= *n) { + while (c != EOF) { + if ((size_t) (pos + 1) >= *n) { size_t new_size = *n + (*n >> 2); if (new_size < 128) { new_size = 128; } - char *new_ptr = realloc(*lineptr, new_size); + char* new_ptr = realloc(*lineptr, new_size); if (new_ptr == NULL) { pos = -1; goto exit; @@ -43,7 +43,7 @@ ssize_t getline(char **lineptr, size_t *n, FILE *stream) { *lineptr = new_ptr; } - ((char *)(*lineptr))[pos ++] = (char)c; + ((char*) (*lineptr))[pos++] = (char) c; if (c == '\n') { break; } diff --git a/src/common/windows/getline.h b/src/common/windows/getline.h index 0c0e9ec70..49ba5db20 100644 --- a/src/common/windows/getline.h +++ b/src/common/windows/getline.h @@ -3,4 +3,4 @@ #include #include -ssize_t getline(char **lineptr, size_t *n, FILE *stream); +ssize_t getline(char** lineptr, size_t* n, FILE* stream); diff --git a/src/common/windows/nt.h b/src/common/windows/nt.h index 3cc63a223..ecbc8da91 100644 --- a/src/common/windows/nt.h +++ b/src/common/windows/nt.h @@ -30,10 +30,8 @@ NTSYSAPI NTSTATUS NTAPI NtPowerInformation( OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength); - NTSYSAPI NTSTATUS NTAPI RtlGetVersion( - _Inout_ PRTL_OSVERSIONINFOW lpVersionInformation -); + _Inout_ PRTL_OSVERSIONINFOW lpVersionInformation); NTSYSAPI NTSTATUS NTAPI NtQueryDirectoryFile( IN HANDLE FileHandle, @@ -49,29 +47,26 @@ NTSYSAPI NTSTATUS NTAPI NtQueryDirectoryFile( IN BOOLEAN RestartScan); // https://ntdoc.m417z.com/process_devicemap_information_ex -typedef struct _PROCESS_DEVICEMAP_INFORMATION_EX -{ - union - { +typedef struct _PROCESS_DEVICEMAP_INFORMATION_EX { + union { struct { HANDLE DirectoryHandle; // A handle to a directory object that can be set as the new device map for the process. This handle must have DIRECTORY_TRAVERSE access. } Set; struct { - ULONG DriveMap; // A bitmask that indicates which drive letters are currently in use in the process's device map. - UCHAR DriveType[32]; // A value that indicates the type of each drive (e.g., local disk, network drive, etc.). // DRIVE_* WinBase.h + ULONG DriveMap; // A bitmask that indicates which drive letters are currently in use in the process's device map. + UCHAR DriveType[32]; // A value that indicates the type of each drive (e.g., local disk, network drive, etc.). // DRIVE_* WinBase.h } Query; }; ULONG Flags; // PROCESS_LUID_DOSDEVICES_ONLY } PROCESS_DEVICEMAP_INFORMATION_EX, *PPROCESS_DEVICEMAP_INFORMATION_EX; #ifndef NtCurrentProcess -#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1) +# define NtCurrentProcess() ((HANDLE) (LONG_PTR) - 1) #endif -typedef struct _CURDIR -{ +typedef struct _CURDIR { UNICODE_STRING DosPath; HANDLE Handle; } CURDIR, *PCURDIR; @@ -81,15 +76,13 @@ NTSYSAPI PIMAGE_NT_HEADERS NTAPI RtlImageNtHeader(IN PVOID BaseOfImage); /** * The SECTION_IMAGE_INFORMATION structure contains detailed information about an image section. */ -typedef struct _SECTION_IMAGE_INFORMATION -{ - PVOID TransferAddress; // The address of the image entry point function. - ULONG ZeroBits; // The number of high-order address bits that must be zero in the image base address. - SIZE_T MaximumStackSize; // The maximum stack size of threads from the PE file header. - SIZE_T CommittedStackSize; // The initial stack size of threads from the PE file header. - ULONG SubSystemType; // The image subsystem from the PE file header (e.g., Windows GUI, Windows CUI, POSIX). - union - { +typedef struct _SECTION_IMAGE_INFORMATION { + PVOID TransferAddress; // The address of the image entry point function. + ULONG ZeroBits; // The number of high-order address bits that must be zero in the image base address. + SIZE_T MaximumStackSize; // The maximum stack size of threads from the PE file header. + SIZE_T CommittedStackSize; // The initial stack size of threads from the PE file header. + ULONG SubSystemType; // The image subsystem from the PE file header (e.g., Windows GUI, Windows CUI, POSIX). + union { struct { USHORT SubSystemMinorVersion; @@ -97,8 +90,7 @@ typedef struct _SECTION_IMAGE_INFORMATION }; ULONG SubSystemVersion; }; - union - { + union { struct { USHORT MajorOperatingSystemVersion; @@ -106,35 +98,32 @@ typedef struct _SECTION_IMAGE_INFORMATION }; ULONG OperatingSystemVersion; }; - USHORT ImageCharacteristics; // The image characteristics from the PE file header. - USHORT DllCharacteristics; // The DLL characteristics flags (e.g., ASLR, NX compatibility). - USHORT Machine; // The image architecture (e.g., x86, x64, ARM). - BOOLEAN ImageContainsCode; // The image contains native executable code. - union - { + USHORT ImageCharacteristics; // The image characteristics from the PE file header. + USHORT DllCharacteristics; // The DLL characteristics flags (e.g., ASLR, NX compatibility). + USHORT Machine; // The image architecture (e.g., x86, x64, ARM). + BOOLEAN ImageContainsCode; // The image contains native executable code. + union { UCHAR ImageFlags; struct { - UCHAR ComPlusNativeReady : 1; // The image contains precompiled .NET assembly generated by NGEN (Native Image Generator). - UCHAR ComPlusILOnly : 1; // the image contains only Microsoft Intermediate Language (IL) assembly. - UCHAR ImageDynamicallyRelocated : 1; // The image was mapped using a random base address rather than the preferred base address. - UCHAR ImageMappedFlat : 1; // The image was mapped using a single contiguous region, rather than separate regions for each section. - UCHAR BaseBelow4gb : 1; // The image was mapped using a base address below the 4 GB boundary. - UCHAR ComPlusPrefer32bit : 1; // The image prefers to run as a 32-bit process, even on a 64-bit system. + UCHAR ComPlusNativeReady : 1; // The image contains precompiled .NET assembly generated by NGEN (Native Image Generator). + UCHAR ComPlusILOnly : 1; // the image contains only Microsoft Intermediate Language (IL) assembly. + UCHAR ImageDynamicallyRelocated : 1; // The image was mapped using a random base address rather than the preferred base address. + UCHAR ImageMappedFlat : 1; // The image was mapped using a single contiguous region, rather than separate regions for each section. + UCHAR BaseBelow4gb : 1; // The image was mapped using a base address below the 4 GB boundary. + UCHAR ComPlusPrefer32bit : 1; // The image prefers to run as a 32-bit process, even on a 64-bit system. UCHAR Reserved : 2; }; }; - ULONG LoaderFlags; // Reserved by ntdll.dll for the Windows loader. - ULONG ImageFileSize; // The size of the image, in bytes, including all headers. - ULONG CheckSum; // The image file checksum, from the PE optional header. + ULONG LoaderFlags; // Reserved by ntdll.dll for the Windows loader. + ULONG ImageFileSize; // The size of the image, in bytes, including all headers. + ULONG CheckSum; // The image file checksum, from the PE optional header. } SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION; -typedef struct _SYSTEM_BOOT_ENVIRONMENT_INFORMATION -{ +typedef struct _SYSTEM_BOOT_ENVIRONMENT_INFORMATION { GUID BootIdentifier; FIRMWARE_TYPE FirmwareType; - union - { + union { ULONGLONG BootFlags; struct { @@ -146,15 +135,14 @@ typedef struct _SYSTEM_BOOT_ENVIRONMENT_INFORMATION ULONGLONG DbgSystemHiveReplace : 1; ULONGLONG DbgMeasuredLaunchSmmProtections : 1; ULONGLONG DbgMeasuredLaunchSmmLevel : 7; // 20H1 - ULONGLONG DbgBugCheckRecovery : 1; // 24H2 + ULONGLONG DbgBugCheckRecovery : 1; // 24H2 ULONGLONG DbgFASR : 1; ULONGLONG DbgUseCachedBcd : 1; }; }; } SYSTEM_BOOT_ENVIRONMENT_INFORMATION; -typedef struct _RTL_PROCESS_MODULE_INFORMATION -{ +typedef struct _RTL_PROCESS_MODULE_INFORMATION { PVOID Section; PVOID MappedBase; PVOID ImageBase; @@ -167,8 +155,7 @@ typedef struct _RTL_PROCESS_MODULE_INFORMATION UCHAR FullPathName[256]; } RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION; -typedef struct _RTL_PROCESS_MODULES -{ +typedef struct _RTL_PROCESS_MODULES { ULONG NumberOfModules; _Field_size_(NumberOfModules) RTL_PROCESS_MODULE_INFORMATION Modules[1]; } RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES; @@ -184,8 +171,7 @@ NTSTATUS NTAPI NtQuerySystemEnvironmentValueEx( NTSTATUS NTAPI RtlGUIDFromString(IN PCUNICODE_STRING GuidString, OUT GUID* Guid); NTSTATUS NTAPI RtlStringFromGUIDEx(IN GUID* Guid, OUT PCUNICODE_STRING GuidString, _In_ BOOLEAN AllocateGuidString); -typedef struct _SYSTEM_SECUREBOOT_INFORMATION -{ +typedef struct _SYSTEM_SECUREBOOT_INFORMATION { BOOLEAN SecureBootEnabled; BOOLEAN SecureBootCapable; } SYSTEM_SECUREBOOT_INFORMATION, *PSYSTEM_SECUREBOOT_INFORMATION; @@ -196,18 +182,15 @@ NTSTATUS NTAPI NtQuerySystemInformationEx( _In_ ULONG InputBufferLength, _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation, _In_ ULONG SystemInformationLength, - _Out_opt_ PULONG ReturnLength -); + _Out_opt_ PULONG ReturnLength); -typedef enum _SYSTEM_FIRMWARE_TABLE_ACTION -{ +typedef enum _SYSTEM_FIRMWARE_TABLE_ACTION { SystemFirmwareTableEnumerate, SystemFirmwareTableGet, SystemFirmwareTableMax } SYSTEM_FIRMWARE_TABLE_ACTION; -typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION -{ +typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION { ULONG ProviderSignature; // (same as the GetSystemFirmwareTable function) SYSTEM_FIRMWARE_TABLE_ACTION Action; ULONG TableID; @@ -220,8 +203,7 @@ NTSYSAPI NTSTATUS NTAPI NtDelayExecution(_In_ BOOLEAN Alertable, _In_ PLARGE_INT /** * The KSYSTEM_TIME structure represents interrupt time, system time, and time zone bias. */ -typedef struct _KSYSTEM_TIME -{ +typedef struct _KSYSTEM_TIME { ULONG LowPart; LONG High1Time; LONG High2Time; @@ -240,8 +222,7 @@ typedef struct _KSYSTEM_TIME * \remarks NEC98x86 represents the NEC PC-98 architecture, * supported only on very early Windows releases. */ -typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE -{ +typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE { StandardDesign, NEC98x86, EndAlternatives @@ -252,8 +233,7 @@ typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE * * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-kuser_shared_data */ -typedef struct _KUSER_SHARED_DATA -{ +typedef struct _KUSER_SHARED_DATA { // // Current low 32-bit of tick count and tick count multiplier. // @@ -344,14 +324,13 @@ typedef struct _KUSER_SHARED_DATA // This value controls Application Compatibility (AppCompat) switchback processing. // - union - { + union { ULONG AppCompatFlag; struct { - ULONG SwitchbackEnabled : 1; // Basic switchback processing - ULONG ExtendedHeuristics : 1; // Extended switchback heuristics - ULONG TelemetryFallback : 1; // Telemetry-driven fallback + ULONG SwitchbackEnabled : 1; // Basic switchback processing + ULONG ExtendedHeuristics : 1; // Extended switchback heuristics + ULONG TelemetryFallback : 1; // Telemetry-driven fallback ULONG Reserved : 29; } AppCompatFlags; }; @@ -435,13 +414,12 @@ typedef struct _KUSER_SHARED_DATA BOOLEAN ProcessorFeatures[PROCESSOR_FEATURE_MAX]; - // // Reserved fields - do not use. // ULONG MaximumUserModeAddressDeprecated; // Deprecated, use SystemBasicInformation instead. - ULONG SystemRangeStartDeprecated; // Deprecated, use SystemRangeStartInformation instead. + ULONG SystemRangeStartDeprecated; // Deprecated, use SystemRangeStartInformation instead. // // Time slippage while in debugger. @@ -489,8 +467,7 @@ typedef struct _KUSER_SHARED_DATA // Mitigation policies. // - union - { + union { UCHAR MitigationPolicies; struct { @@ -562,8 +539,7 @@ typedef struct _KUSER_SHARED_DATA // Virtualization flags. // - union - { + union { UCHAR VirtualizationFlags; #if defined(_ARM64_) @@ -580,7 +556,6 @@ typedef struct _KUSER_SHARED_DATA }; #endif - }; // @@ -598,8 +573,7 @@ typedef struct _KUSER_SHARED_DATA // API for an accurate result // - union - { + union { ULONG SharedDataFlags; struct { @@ -608,20 +582,20 @@ typedef struct _KUSER_SHARED_DATA // Use the bit definitions instead. // - ULONG DbgErrorPortPresent : 1; - ULONG DbgElevationEnabled : 1; - ULONG DbgVirtEnabled : 1; + ULONG DbgErrorPortPresent : 1; + ULONG DbgElevationEnabled : 1; + ULONG DbgVirtEnabled : 1; ULONG DbgInstallerDetectEnabled : 1; - ULONG DbgLkgEnabled : 1; - ULONG DbgDynProcessorEnabled : 1; - ULONG DbgConsoleBrokerEnabled : 1; - ULONG DbgSecureBootEnabled : 1; - ULONG DbgMultiSessionSku : 1; + ULONG DbgLkgEnabled : 1; + ULONG DbgDynProcessorEnabled : 1; + ULONG DbgConsoleBrokerEnabled : 1; + ULONG DbgSecureBootEnabled : 1; + ULONG DbgMultiSessionSku : 1; ULONG DbgMultiUsersInSessionSku : 1; ULONG DbgStateSeparationEnabled : 1; - ULONG DbgSplitTokenEnabled : 1; - ULONG DbgShadowAdminEnabled : 1; - ULONG SpareBits : 19; + ULONG DbgSplitTokenEnabled : 1; + ULONG DbgShadowAdminEnabled : 1; + ULONG SpareBits : 19; }; }; @@ -630,63 +604,57 @@ typedef struct _KUSER_SHARED_DATA #define SharedUserData ((const KUSER_SHARED_DATA*) 0x7FFE0000UL) -static inline uint64_t ffKSystemTimeToUInt64(const volatile KSYSTEM_TIME* pTime) -{ - #if _WIN64 +static inline uint64_t ffKSystemTimeToUInt64(const volatile KSYSTEM_TIME* pTime) { +#if _WIN64 // This is safe even if pTime is not 8-byte aligned // See https://learn.microsoft.com/en-us/windows/win32/winprog64/fault-alignments return *(const volatile uint64_t*) pTime; - #else +#else uint32_t low, high1, high2; do { high1 = pTime->High1Time; - low = pTime->LowPart; + low = pTime->LowPart; high2 = pTime->High2Time; } while (high1 != high2); return ((uint64_t) high1 << 32) | low; - #endif +#endif } -static inline bool ffIsWindows10OrGreater() -{ - #if FF_WIN81_COMPAT +static inline bool ffIsWindows10OrGreater() { +#if FF_WIN81_COMPAT return SharedUserData->NtMajorVersion >= 10; - #else +#else return true; - #endif +#endif } -static inline bool ffIsWindows11OrGreater() -{ +static inline bool ffIsWindows11OrGreater() { return ffIsWindows10OrGreater() && SharedUserData->NtBuildNumber >= 22000; } NTSYSAPI NTSTATUS NTAPI NtOpenProcessToken( _In_ HANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, - _Out_ PHANDLE TokenHandle -); + _Out_ PHANDLE TokenHandle); NTSYSAPI NTSTATUS NTAPI NtAdjustPrivilegesToken( _In_ HANDLE TokenHandle, _In_ BOOLEAN DisableAllPrivileges, _In_opt_ PTOKEN_PRIVILEGES NewState, _In_ ULONG BufferLength, _Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_PRIVILEGES PreviousState, - _Out_opt_ PULONG ReturnLength -); + _Out_opt_ PULONG ReturnLength); NTSYSAPI NTSTATUS NTAPI NtQueryInformationToken( _In_ HANDLE TokenHandle, _In_ TOKEN_INFORMATION_CLASS TokenInformationClass, _Out_writes_bytes_to_opt_(TokenInformationLength, *ReturnLength) PVOID TokenInformation, _In_ ULONG TokenInformationLength, - _Out_ PULONG ReturnLength -); -#define NtCurrentProcessToken() ((HANDLE)(LONG_PTR)-4) // for NtQueryInformationToken only; Windows 8+ + _Out_ PULONG ReturnLength); +#define NtCurrentProcessToken() ((HANDLE) (LONG_PTR) - 4) // for NtQueryInformationToken only; Windows 8+ NTSYSAPI NTSTATUS NTAPI NtReadFile( _In_ HANDLE FileHandle, @@ -697,49 +665,42 @@ NTSYSAPI NTSTATUS NTAPI NtReadFile( _Out_writes_bytes_(Length) PVOID Buffer, _In_ ULONG Length, _In_opt_ PLARGE_INTEGER ByteOffset, - _In_opt_ PULONG Key -); + _In_opt_ PULONG Key); NTSYSAPI NTSTATUS NTAPI NtCreateEvent( _Out_ PHANDLE EventHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ EVENT_TYPE EventType, - _In_ BOOLEAN InitialState -); + _In_ BOOLEAN InitialState); NTSYSAPI NTSTATUS NTAPI NtQueryAttributesFile( _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, - _Out_ PFILE_BASIC_INFORMATION FileInformation -); + _Out_ PFILE_BASIC_INFORMATION FileInformation); NTSYSAPI NTSTATUS NTAPI RtlUnicodeToUTF8N( _Out_writes_bytes_to_(UTF8StringMaxByteCount, *UTF8StringActualByteCount) PCHAR UTF8StringDestination, _In_ ULONG UTF8StringMaxByteCount, _Out_opt_ PULONG UTF8StringActualByteCount, _In_reads_bytes_(UnicodeStringByteCount) PCWCH UnicodeStringSource, - _In_ ULONG UnicodeStringByteCount -); + _In_ ULONG UnicodeStringByteCount); NTSYSAPI NTSTATUS NTAPI RtlUTF8ToUnicodeN( _Out_writes_bytes_to_(UnicodeStringMaxByteCount, *UnicodeStringActualByteCount) PWSTR UnicodeStringDestination, _In_ ULONG UnicodeStringMaxByteCount, _Out_opt_ PULONG UnicodeStringActualByteCount, _In_reads_bytes_(UTF8StringByteCount) PCCH UTF8StringSource, - _In_ ULONG UTF8StringByteCount -); + _In_ ULONG UTF8StringByteCount); #define RTL_MAX_DRIVE_LETTERS 32 -typedef struct _RTL_DRIVE_LETTER_CURDIR -{ +typedef struct _RTL_DRIVE_LETTER_CURDIR { USHORT Flags; USHORT Length; ULONG TimeStamp; STRING DosPath; } RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR; -typedef struct _RTL_USER_PROCESS_PARAMETERS_FULL -{ +typedef struct _RTL_USER_PROCESS_PARAMETERS_FULL { ULONG MaximumLength; ULONG Length; @@ -794,8 +755,7 @@ typedef struct CPTABLEINFO* PCPTABLEINFO; typedef struct NLSTABLEINFO* PNLSTABLEINFO; typedef struct GDI_HANDLE_ENTRY* PGDI_HANDLE_ENTRY; -typedef struct _PEB_FULL -{ +typedef struct _PEB_FULL { // // The process was cloned with an inherited address space. // @@ -811,19 +771,18 @@ typedef struct _PEB_FULL // BOOLEAN BeingDebugged; - union - { + union { BOOLEAN BitField; struct { - BOOLEAN ImageUsesLargePages : 1; // The process uses large image regions (4 MB). - BOOLEAN IsProtectedProcess : 1; // The process is a protected process. - BOOLEAN IsImageDynamicallyRelocated : 1; // The process image base address was relocated. - BOOLEAN SkipPatchingUser32Forwarders : 1; // The process skipped forwarders for User32.dll functions. 1 for 64-bit, 0 for 32-bit. - BOOLEAN IsPackagedProcess : 1; // The process is a packaged store process (APPX/MSIX). - BOOLEAN IsAppContainerProcess : 1; // The process has an AppContainer token. - BOOLEAN IsProtectedProcessLight : 1; // The process is a protected process (light). - BOOLEAN IsLongPathAwareProcess : 1; // The process is long path aware. + BOOLEAN ImageUsesLargePages : 1; // The process uses large image regions (4 MB). + BOOLEAN IsProtectedProcess : 1; // The process is a protected process. + BOOLEAN IsImageDynamicallyRelocated : 1; // The process image base address was relocated. + BOOLEAN SkipPatchingUser32Forwarders : 1; // The process skipped forwarders for User32.dll functions. 1 for 64-bit, 0 for 32-bit. + BOOLEAN IsPackagedProcess : 1; // The process is a packaged store process (APPX/MSIX). + BOOLEAN IsAppContainerProcess : 1; // The process has an AppContainer token. + BOOLEAN IsProtectedProcessLight : 1; // The process is a protected process (light). + BOOLEAN IsLongPathAwareProcess : 1; // The process is long path aware. }; }; @@ -875,19 +834,18 @@ typedef struct _PEB_FULL // // Cross process flags. // - union - { + union { ULONG CrossProcessFlags; struct { - ULONG ProcessInJob : 1; // The process is part of a job. - ULONG ProcessInitializing : 1; // The process is initializing. - ULONG ProcessUsingVEH : 1; // The process is using VEH. - ULONG ProcessUsingVCH : 1; // The process is using VCH. - ULONG ProcessUsingFTH : 1; // The process is using FTH. - ULONG ProcessPreviouslyThrottled : 1; // The process was previously throttled. - ULONG ProcessCurrentlyThrottled : 1; // The process is currently throttled. - ULONG ProcessImagesHotPatched : 1; // The process images are hot patched. // RS5 + ULONG ProcessInJob : 1; // The process is part of a job. + ULONG ProcessInitializing : 1; // The process is initializing. + ULONG ProcessUsingVEH : 1; // The process is using VEH. + ULONG ProcessUsingVCH : 1; // The process is using VCH. + ULONG ProcessUsingFTH : 1; // The process is using FTH. + ULONG ProcessPreviouslyThrottled : 1; // The process was previously throttled. + ULONG ProcessCurrentlyThrottled : 1; // The process is currently throttled. + ULONG ProcessImagesHotPatched : 1; // The process images are hot patched. // RS5 ULONG ReservedBits0 : 24; }; }; @@ -895,8 +853,7 @@ typedef struct _PEB_FULL // // User32 KERNEL_CALLBACK_TABLE (ntuser.h) // - union - { + union { PKERNEL_CALLBACK_TABLE KernelCallbackTable; PVOID UserSharedInfoPtr; }; @@ -969,8 +926,7 @@ typedef struct _PEB_FULL // // Global flags for the system. // - union - { + union { ULONG NtGlobalFlag; struct { @@ -1115,8 +1071,7 @@ typedef struct _PEB_FULL // ... } PEB_FULL, *PPEB_FULL; -typedef struct _TEB_FULL -{ +typedef struct _TEB_FULL { // // Thread Information Block (TIB) contains the thread's stack, base and limit addresses, the current stack pointer, and the exception list. // @@ -1188,13 +1143,11 @@ typedef struct _TEB_FULL LCID CurrentLocale; } TEB_FULL, *PTEB_FULL; -static inline PTEB_FULL ffGetTeb() -{ +static inline PTEB_FULL ffGetTeb() { return (PTEB_FULL) NtCurrentTeb(); } -static inline PPEB_FULL ffGetPeb() -{ +static inline PPEB_FULL ffGetPeb() { return ffGetTeb()->ProcessEnvironmentBlock; } @@ -1204,23 +1157,20 @@ NTSYSAPI NTSTATUS NTAPI RtlExpandEnvironmentStrings( _In_ SIZE_T SourceLength, _Out_writes_(DestinationLength) PWSTR Destination, _In_ SIZE_T DestinationLength, - _Out_opt_ PSIZE_T ReturnLength -); + _Out_opt_ PSIZE_T ReturnLength); NTSYSAPI NTSTATUS NTAPI NtOpenKey( _Out_ PHANDLE KeyHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes -); + _In_ POBJECT_ATTRIBUTES ObjectAttributes); -typedef enum _KEY_VALUE_INFORMATION_CLASS -{ - KeyValueBasicInformation, // KEY_VALUE_BASIC_INFORMATION - KeyValueFullInformation, // KEY_VALUE_FULL_INFORMATION - KeyValuePartialInformation, // KEY_VALUE_PARTIAL_INFORMATION - KeyValueFullInformationAlign64, // KEY_VALUE_FULL_INFORMATION_ALIGN64 - KeyValuePartialInformationAlign64, // KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 - KeyValueLayerInformation, // KEY_VALUE_LAYER_INFORMATION +typedef enum _KEY_VALUE_INFORMATION_CLASS { + KeyValueBasicInformation, // KEY_VALUE_BASIC_INFORMATION + KeyValueFullInformation, // KEY_VALUE_FULL_INFORMATION + KeyValuePartialInformation, // KEY_VALUE_PARTIAL_INFORMATION + KeyValueFullInformationAlign64, // KEY_VALUE_FULL_INFORMATION_ALIGN64 + KeyValuePartialInformationAlign64, // KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 + KeyValueLayerInformation, // KEY_VALUE_LAYER_INFORMATION MaxKeyValueInfoClass } KEY_VALUE_INFORMATION_CLASS; @@ -1230,34 +1180,30 @@ NTSYSAPI NTSTATUS NTAPI NtQueryValueKey( _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyValueInformation, _In_ ULONG Length, - _Out_ PULONG ResultLength -); + _Out_ PULONG ResultLength); NTSYSAPI NTSTATUS NTAPI RtlOpenCurrentUser( _In_ ACCESS_MASK DesiredAccess, - _Out_ PHANDLE CurrentUserKey -); + _Out_ PHANDLE CurrentUserKey); -typedef struct _KEY_VALUE_PARTIAL_INFORMATION -{ +typedef struct _KEY_VALUE_PARTIAL_INFORMATION { ULONG TitleIndex; ULONG Type; ULONG DataLength; _Field_size_bytes_(DataLength) UCHAR Data[]; } KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION; -typedef enum _KEY_INFORMATION_CLASS -{ - KeyBasicInformation, // KEY_BASIC_INFORMATION - KeyNodeInformation, // KEY_NODE_INFORMATION - KeyFullInformation, // KEY_FULL_INFORMATION - KeyNameInformation, // KEY_NAME_INFORMATION - KeyCachedInformation, // KEY_CACHED_INFORMATION - KeyFlagsInformation, // KEY_FLAGS_INFORMATION +typedef enum _KEY_INFORMATION_CLASS { + KeyBasicInformation, // KEY_BASIC_INFORMATION + KeyNodeInformation, // KEY_NODE_INFORMATION + KeyFullInformation, // KEY_FULL_INFORMATION + KeyNameInformation, // KEY_NAME_INFORMATION + KeyCachedInformation, // KEY_CACHED_INFORMATION + KeyFlagsInformation, // KEY_FLAGS_INFORMATION KeyVirtualizationInformation, // KEY_VIRTUALIZATION_INFORMATION - KeyHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION - KeyTrustInformation, // KEY_TRUST_INFORMATION - KeyLayerInformation, // KEY_LAYER_INFORMATION + KeyHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION + KeyTrustInformation, // KEY_TRUST_INFORMATION + KeyLayerInformation, // KEY_LAYER_INFORMATION MaxKeyInfoClass } KEY_INFORMATION_CLASS; @@ -1267,19 +1213,16 @@ NTSYSAPI NTSTATUS NTAPI NtEnumerateKey( _In_ KEY_INFORMATION_CLASS KeyInformationClass, _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyInformation, _In_ ULONG Length, - _Out_ PULONG ResultLength -); + _Out_ PULONG ResultLength); -typedef struct _KEY_BASIC_INFORMATION -{ - LARGE_INTEGER LastWriteTime; // Number of 100-nanosecond intervals since this key or any of its values changed. - ULONG TitleIndex; // Reserved // A legacy field originally intended for use with localization such as an index of a resource table. - ULONG NameLength; // The size, in bytes, of the key name string in the Name array. - _Field_size_bytes_(NameLength) WCHAR Name[]; // The name of the registry key. This string is not null-terminated. +typedef struct _KEY_BASIC_INFORMATION { + LARGE_INTEGER LastWriteTime; // Number of 100-nanosecond intervals since this key or any of its values changed. + ULONG TitleIndex; // Reserved // A legacy field originally intended for use with localization such as an index of a resource table. + ULONG NameLength; // The size, in bytes, of the key name string in the Name array. + _Field_size_bytes_(NameLength) WCHAR Name[]; // The name of the registry key. This string is not null-terminated. } KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION; -typedef struct _KEY_FULL_INFORMATION -{ +typedef struct _KEY_FULL_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG ClassOffset; @@ -1298,40 +1241,34 @@ NTSYSAPI NTSTATUS NTAPI NtQueryKey( _In_ KEY_INFORMATION_CLASS KeyInformationClass, _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyInformation, _In_ ULONG Length, - _Out_ PULONG ResultLength -); + _Out_ PULONG ResultLength); NTSYSAPI NTSTATUS NTAPI NtOpenProcess( _Out_ PHANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, - _In_opt_ PCLIENT_ID ClientId -); + _In_opt_ PCLIENT_ID ClientId); NTSYSAPI NTSTATUS NTAPI LdrLoadDll( _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, _In_ PCUNICODE_STRING DllName, - _Out_ PVOID *DllHandle -); + _Out_ PVOID* DllHandle); NTSYSAPI NTSTATUS NTAPI LdrUnloadDll( - _In_ PVOID DllHandle -); + _In_ PVOID DllHandle); NTSYSAPI NTSTATUS NTAPI LdrGetDllHandle( _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, _In_ PCUNICODE_STRING DllName, - _Out_ PVOID *DllHandle -); + _Out_ PVOID* DllHandle); NTSYSAPI NTSTATUS NTAPI LdrGetProcedureAddress( _In_ PVOID DllHandle, _In_opt_ PCANSI_STRING ProcedureName, _In_opt_ ULONG ProcedureNumber, - _Out_ PVOID *ProcedureAddress -); + _Out_ PVOID* ProcedureAddress); typedef enum _SECTION_INHERIT { ViewShare = 1, @@ -1345,42 +1282,35 @@ NTSYSAPI NTSTATUS NTAPI NtCreateSection( _In_opt_ PLARGE_INTEGER MaximumSize, _In_ ULONG SectionPageProtection, _In_ ULONG AllocationAttributes, - _In_opt_ HANDLE FileHandle -); + _In_opt_ HANDLE FileHandle); NTSYSAPI NTSTATUS NTAPI NtMapViewOfSection( _In_ HANDLE SectionHandle, _In_ HANDLE ProcessHandle, - _Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID *BaseAddress, + _Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID* BaseAddress, _In_ ULONG_PTR ZeroBits, _In_ SIZE_T CommitSize, _Inout_opt_ PLARGE_INTEGER SectionOffset, _Inout_ PSIZE_T ViewSize, _In_ SECTION_INHERIT InheritDisposition, _In_ ULONG AllocationType, - _In_ ULONG PageProtection -); + _In_ ULONG PageProtection); NTSYSAPI NTSTATUS NTAPI NtUnmapViewOfSection( _In_ HANDLE ProcessHandle, - _In_opt_ PVOID BaseAddress -); + _In_opt_ PVOID BaseAddress); NTSYSAPI LOGICAL NTAPI RtlQueryPerformanceCounter( - _Out_ PLARGE_INTEGER PerformanceCounter -); + _Out_ PLARGE_INTEGER PerformanceCounter); NTSYSAPI LOGICAL NTAPI RtlQueryPerformanceFrequency( - _Out_ PLARGE_INTEGER PerformanceFrequency -); + _Out_ PLARGE_INTEGER PerformanceFrequency); NTSYSAPI NTSTATUS NTAPI NtCancelIoFileEx( _In_ HANDLE FileHandle, _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel, - _Out_ PIO_STATUS_BLOCK IoStatusBlock -); + _Out_ PIO_STATUS_BLOCK IoStatusBlock); NTSYSAPI NTSTATUS NTAPI NtTerminateProcess( _In_opt_ HANDLE ProcessHandle, - _In_ NTSTATUS ExitStatus -); + _In_ NTSTATUS ExitStatus); diff --git a/src/common/windows/perflib_.h b/src/common/windows/perflib_.h index 0d261b963..f30ed541c 100644 --- a/src/common/windows/perflib_.h +++ b/src/common/windows/perflib_.h @@ -5,10 +5,10 @@ // Missing from of MinGW-w64 SDK -#define PERF_WILDCARD_COUNTER 0xFFFFFFFF -#define PERF_WILDCARD_INSTANCE L"*" +#define PERF_WILDCARD_COUNTER 0xFFFFFFFF +#define PERF_WILDCARD_INSTANCE L"*" #define PERF_AGGREGATE_INSTANCE L"_Total" -#define PERF_MAX_INSTANCE_NAME 1024 +#define PERF_MAX_INSTANCE_NAME 1024 typedef struct _PERF_INSTANCE_HEADER { ULONG Size; // = sizeof(PERF_INSTANCE_HEADER) + sizeof(InstanceName) + sizeof(Padding) @@ -19,28 +19,28 @@ typedef struct _PERF_INSTANCE_HEADER { } PERF_INSTANCE_HEADER, *PPERF_INSTANCE_HEADER; typedef struct _PERF_COUNTER_IDENTIFIER { - GUID CounterSetGuid; // The GUID of the counterset. - ULONG Status; // Win32 error code indicating success/failure of the add/delete operation. - ULONG Size; // sizeof(PERF_COUNTER_IDENTIFIER) + sizeof(InstanceName) + sizeof(Padding) - ULONG CounterId; // CounterId, or PERF_WILDCARD_COUNTER for all counters. - ULONG InstanceId; // InstanceId, or 0xFFFFFFFF to not filter on instance ID. - ULONG Index; // Set by PerfQueryCounterInfo to the position in which the corresponding counter data is returned. - ULONG Reserved; // Reserved. + GUID CounterSetGuid; // The GUID of the counterset. + ULONG Status; // Win32 error code indicating success/failure of the add/delete operation. + ULONG Size; // sizeof(PERF_COUNTER_IDENTIFIER) + sizeof(InstanceName) + sizeof(Padding) + ULONG CounterId; // CounterId, or PERF_WILDCARD_COUNTER for all counters. + ULONG InstanceId; // InstanceId, or 0xFFFFFFFF to not filter on instance ID. + ULONG Index; // Set by PerfQueryCounterInfo to the position in which the corresponding counter data is returned. + ULONG Reserved; // Reserved. // Followed by: // WCHAR InstanceName[]; // WCHAR Padding[]; -} PERF_COUNTER_IDENTIFIER, * PPERF_COUNTER_IDENTIFIER; +} PERF_COUNTER_IDENTIFIER, *PPERF_COUNTER_IDENTIFIER; typedef struct _PERF_DATA_HEADER { - ULONG dwTotalSize; // = sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER blocks...) - ULONG dwNumCounters; // The number of PERF_COUNTER_HEADER blocks. - LONGLONG PerfTimeStamp; // Timestamp from a high-resolution clock. - LONGLONG PerfTime100NSec; // The number of 100 nanosecond intervals since January 1, 1601, in Coordinated Universal Time (UTC). - LONGLONG PerfFreq; // The frequency of a high-resolution clock. - SYSTEMTIME SystemTime; // The time at which data is collected on the provider side. + ULONG dwTotalSize; // = sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER blocks...) + ULONG dwNumCounters; // The number of PERF_COUNTER_HEADER blocks. + LONGLONG PerfTimeStamp; // Timestamp from a high-resolution clock. + LONGLONG PerfTime100NSec; // The number of 100 nanosecond intervals since January 1, 1601, in Coordinated Universal Time (UTC). + LONGLONG PerfFreq; // The frequency of a high-resolution clock. + SYSTEMTIME SystemTime; // The time at which data is collected on the provider side. // Followed by: // PERF_COUNTER_HEADER blocks...; -} PERF_DATA_HEADER, * PPERF_DATA_HEADER; +} PERF_DATA_HEADER, *PPERF_DATA_HEADER; typedef enum _PerfCounterDataType { PERF_ERROR_RETURN = 0, /* An error occurred when the performance counter value was queried. */ @@ -51,90 +51,84 @@ typedef enum _PerfCounterDataType { } PerfCounterDataType; typedef struct _PERF_COUNTER_HEADER { - ULONG dwStatus; // Win32 error code indicating success/failure of the query operation. + ULONG dwStatus; // Win32 error code indicating success/failure of the query operation. PerfCounterDataType dwType; // Result type - error, single/single, multi/single, single/multi, multi/multi. - ULONG dwSize; // = sizeof(PERF_COUNTER_HEADER) + sizeof(Additional data) - ULONG Reserved; // Reserved. + ULONG dwSize; // = sizeof(PERF_COUNTER_HEADER) + sizeof(Additional data) + ULONG Reserved; // Reserved. // Followed by additional data: // If dwType == PERF_ERROR_RETURN: nothing. // If dwType == PERF_SINGLE_COUNTER: PERF_COUNTER_DATA block. // If dwType == PERF_MULTIPLE_COUNTERS: PERF_MULTI_COUNTERS block + PERF_COUNTER_DATA blocks. // If dwType == PERF_MULTIPLE_INSTANCES: PERF_MULTI_INSTANCES block. // If dwType == PERF_COUNTERSET: PERF_MULTI_COUNTERS block + PERF_MULTI_INSTANCES block. -} PERF_COUNTER_HEADER, * PPERF_COUNTER_HEADER; +} PERF_COUNTER_HEADER, *PPERF_COUNTER_HEADER; typedef struct _PERF_MULTI_INSTANCES { - ULONG dwTotalSize; // = sizeof(PERF_MULTI_INSTANCES) + sizeof(instance data blocks...) - ULONG dwInstances; // Number of instance data blocks. + ULONG dwTotalSize; // = sizeof(PERF_MULTI_INSTANCES) + sizeof(instance data blocks...) + ULONG dwInstances; // Number of instance data blocks. // Followed by: // Instance data blocks...; -} PERF_MULTI_INSTANCES, * PPERF_MULTI_INSTANCES; +} PERF_MULTI_INSTANCES, *PPERF_MULTI_INSTANCES; typedef struct _PERF_MULTI_COUNTERS { - ULONG dwSize; // sizeof(PERF_MULTI_COUNTERS) + sizeof(CounterIds) - ULONG dwCounters; // Number of counter ids. + ULONG dwSize; // sizeof(PERF_MULTI_COUNTERS) + sizeof(CounterIds) + ULONG dwCounters; // Number of counter ids. // Followed by: // DWORD CounterIds[dwCounters]; -} PERF_MULTI_COUNTERS, * PPERF_MULTI_COUNTERS; +} PERF_MULTI_COUNTERS, *PPERF_MULTI_COUNTERS; typedef struct _PERF_COUNTER_DATA { - ULONG dwDataSize; // Size of the counter data, in bytes. - ULONG dwSize; // = sizeof(PERF_COUNTER_DATA) + sizeof(Data) + sizeof(Padding) + ULONG dwDataSize; // Size of the counter data, in bytes. + ULONG dwSize; // = sizeof(PERF_COUNTER_DATA) + sizeof(Data) + sizeof(Padding) // Followed by: // BYTE Data[dwDataSize]; // BYTE Padding[]; -} PERF_COUNTER_DATA, * PPERF_COUNTER_DATA; +} PERF_COUNTER_DATA, *PPERF_COUNTER_DATA; _Success_(return == ERROR_SUCCESS) -ULONG -WINAPI -PerfEnumerateCounterSetInstances( - _In_opt_z_ LPCWSTR szMachine, - _In_ LPCGUID pCounterSetId, - _Out_opt_bytecap_post_bytecount_(cbInstances, *pcbInstancesActual) PPERF_INSTANCE_HEADER pInstances, - DWORD cbInstances, - _Out_ LPDWORD pcbInstancesActual - ); + ULONG + WINAPI + PerfEnumerateCounterSetInstances( + _In_opt_z_ LPCWSTR szMachine, + _In_ LPCGUID pCounterSetId, + _Out_opt_bytecap_post_bytecount_(cbInstances, *pcbInstancesActual) PPERF_INSTANCE_HEADER pInstances, + DWORD cbInstances, + _Out_ LPDWORD pcbInstancesActual); _Success_(return == ERROR_SUCCESS) -ULONG -WINAPI -PerfOpenQueryHandle( - _In_opt_z_ LPCWSTR szMachine, - _Out_ HANDLE * phQuery - ); + ULONG + WINAPI + PerfOpenQueryHandle( + _In_opt_z_ LPCWSTR szMachine, + _Out_ HANDLE* phQuery); _Success_(return == ERROR_SUCCESS) -ULONG -WINAPI -PerfCloseQueryHandle( - _In_ HANDLE hQuery - ); + ULONG + WINAPI + PerfCloseQueryHandle( + _In_ HANDLE hQuery); _Success_(return == ERROR_SUCCESS) -ULONG -WINAPI -PerfAddCounters( - _In_ HANDLE hQuery, - _Inout_bytecount_(cbCounters) PPERF_COUNTER_IDENTIFIER pCounters, - DWORD cbCounters - ); + ULONG + WINAPI + PerfAddCounters( + _In_ HANDLE hQuery, + _Inout_bytecount_(cbCounters) PPERF_COUNTER_IDENTIFIER pCounters, + DWORD cbCounters); _Success_(return == ERROR_SUCCESS) -ULONG -WINAPI -PerfDeleteCounters( - _In_ HANDLE hQuery, - _Inout_bytecount_(cbCounters) PPERF_COUNTER_IDENTIFIER pCounters, - DWORD cbCounters - ); + ULONG + WINAPI + PerfDeleteCounters( + _In_ HANDLE hQuery, + _Inout_bytecount_(cbCounters) PPERF_COUNTER_IDENTIFIER pCounters, + DWORD cbCounters); _Success_(return == ERROR_SUCCESS) -ULONG -WINAPI -PerfQueryCounterData( - _In_ HANDLE hQuery, - _Out_opt_bytecap_post_bytecount_(cbCounterBlock, *pcbCounterBlockActual) PPERF_DATA_HEADER pCounterBlock, - DWORD cbCounterBlock, - _Out_ LPDWORD pcbCounterBlockActual - ); + ULONG + WINAPI + PerfQueryCounterData( + _In_ HANDLE hQuery, + _Out_opt_bytecap_post_bytecount_(cbCounterBlock, *pcbCounterBlockActual) PPERF_DATA_HEADER pCounterBlock, + DWORD cbCounterBlock, + _Out_ LPDWORD pcbCounterBlockActual); diff --git a/src/common/windows/registry.c b/src/common/windows/registry.c index a8c020492..30cd68ce6 100644 --- a/src/common/windows/registry.c +++ b/src/common/windows/registry.c @@ -9,9 +9,9 @@ static HANDLE hRootKeys[8 /*(uintptr_t) HKEY_CURRENT_USER_LOCAL_SETTINGS - (uintptr_t) HKEY_CLASSES_ROOT + 1*/]; -static const char* hKey2Str(HANDLE hRootKey) -{ - #define HKEY_CASE(compareKey) if(hRootKey == hRootKeys[(uintptr_t)compareKey - (uintptr_t)HKEY_CLASSES_ROOT]) return #compareKey; +static const char* hKey2Str(HANDLE hRootKey) { +#define HKEY_CASE(compareKey) \ + if (hRootKey == hRootKeys[(uintptr_t) compareKey - (uintptr_t) HKEY_CLASSES_ROOT]) return #compareKey; HKEY_CASE(HKEY_CLASSES_ROOT) HKEY_CASE(HKEY_CURRENT_USER) HKEY_CASE(HKEY_LOCAL_MACHINE) @@ -20,31 +20,27 @@ static const char* hKey2Str(HANDLE hRootKey) HKEY_CASE(HKEY_CURRENT_CONFIG) HKEY_CASE(HKEY_DYN_DATA) HKEY_CASE(HKEY_CURRENT_USER_LOCAL_SETTINGS) - #undef HKEY_CASE +#undef HKEY_CASE return "UNKNOWN"; } -HANDLE ffRegGetRootKeyHandle(HKEY hKey) -{ +HANDLE ffRegGetRootKeyHandle(HKEY hKey) { assert(hKey); assert((uintptr_t) hKey >= (uintptr_t) HKEY_CLASSES_ROOT && (uintptr_t) hKey <= (uintptr_t) HKEY_CURRENT_USER_LOCAL_SETTINGS); - FF_DEBUG("Getting root key handle for HKEY %08llx", (uint64_t)(uintptr_t) hKey); + FF_DEBUG("Getting root key handle for HKEY %08llx", (uint64_t) (uintptr_t) hKey); HANDLE result = hRootKeys[(uintptr_t) hKey - (uintptr_t) HKEY_CLASSES_ROOT]; - if (result) - { + if (result) { FF_DEBUG("Found cached root key handle for %s -> %p", hKey2Str(result), result); return result; } - switch ((uintptr_t) hKey) - { + switch ((uintptr_t) hKey) { case (uintptr_t) HKEY_CURRENT_USER: { NTSTATUS status = RtlOpenCurrentUser(KEY_READ, &result); - if (!NT_SUCCESS(status)) - { + if (!NT_SUCCESS(status)) { FF_DEBUG("RtlOpenCurrentUser() failed: %s", ffDebugNtStatus(status)); return NULL; } @@ -54,13 +50,12 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) case (uintptr_t) HKEY_LOCAL_MACHINE: { UNICODE_STRING path = RTL_CONSTANT_STRING(L"\\Registry\\Machine"); NTSTATUS status = NtOpenKey(&result, KEY_READ, &(OBJECT_ATTRIBUTES) { - .Length = sizeof(OBJECT_ATTRIBUTES), - .RootDirectory = NULL, - .ObjectName = &path, - .Attributes = OBJ_CASE_INSENSITIVE, - }); - if (!NT_SUCCESS(status)) - { + .Length = sizeof(OBJECT_ATTRIBUTES), + .RootDirectory = NULL, + .ObjectName = &path, + .Attributes = OBJ_CASE_INSENSITIVE, + }); + if (!NT_SUCCESS(status)) { FF_DEBUG("NtOpenKey(%ls) failed: %s (0x%08lx)", path.Buffer, ffDebugNtStatus(status), status); return NULL; } @@ -77,8 +72,7 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) return result; } -bool ffRegOpenSubkeyForRead(HANDLE hKey, const wchar_t* subKeyW, HANDLE* result, FFstrbuf* error) -{ +bool ffRegOpenSubkeyForRead(HANDLE hKey, const wchar_t* subKeyW, HANDLE* result, FFstrbuf* error) { assert(hKey); assert(subKeyW); assert(result); @@ -87,18 +81,16 @@ bool ffRegOpenSubkeyForRead(HANDLE hKey, const wchar_t* subKeyW, HANDLE* result, USHORT subKeyLen = (USHORT) (wcslen(subKeyW) * sizeof(wchar_t)); if (!NT_SUCCESS(NtOpenKey(result, KEY_READ, &(OBJECT_ATTRIBUTES) { - .Length = sizeof(OBJECT_ATTRIBUTES), - .RootDirectory = hKey, - .ObjectName = &(UNICODE_STRING) { - .Length = subKeyLen, - .MaximumLength = subKeyLen + (USHORT) sizeof(wchar_t), - .Buffer = (wchar_t*) subKeyW, - }, - }))) - { + .Length = sizeof(OBJECT_ATTRIBUTES), + .RootDirectory = hKey, + .ObjectName = &(UNICODE_STRING) { + .Length = subKeyLen, + .MaximumLength = subKeyLen + (USHORT) sizeof(wchar_t), + .Buffer = (wchar_t*) subKeyW, + }, + }))) { FF_DEBUG("NtOpenKey(%s\\) failed", hKey2Str(hKey)); - if (error) - { + if (error) { FF_STRBUF_AUTO_DESTROY subKeyA = ffStrbufCreateWS(subKeyW); ffStrbufAppendF(error, "NtOpenKey(%s\\%s) failed", hKey2Str(hKey), subKeyA.chars); } @@ -108,24 +100,22 @@ bool ffRegOpenSubkeyForRead(HANDLE hKey, const wchar_t* subKeyW, HANDLE* result, return true; } -static bool processRegValue(const FFRegValueArg* arg, const ULONG regType, const void* regData, ULONG regDataLen, FFstrbuf* error) -{ - switch (arg->type) - { - case FF_ARG_TYPE_STRBUF: - { - if (regType != REG_SZ && regType != REG_EXPAND_SZ) +static bool processRegValue(const FFRegValueArg* arg, const ULONG regType, const void* regData, ULONG regDataLen, FFstrbuf* error) { + switch (arg->type) { + case FF_ARG_TYPE_STRBUF: { + if (regType != REG_SZ && regType != REG_EXPAND_SZ) { goto type_mismatch; + } FFstrbuf* strbuf = (FFstrbuf*) arg->value; uint32_t strLen = regDataLen / sizeof(wchar_t); - if (strLen == 0) + if (strLen == 0) { ffStrbufClear(strbuf); - else - { + } else { const wchar_t* ws = (const wchar_t*) regData; - if (ws[strLen - 1] == L'\0') + if (ws[strLen - 1] == L'\0') { --strLen; + } ffStrbufSetNWS(strbuf, strLen, ws); } break; @@ -135,59 +125,61 @@ static bool processRegValue(const FFRegValueArg* arg, const ULONG regType, const case FF_ARG_TYPE_UINT64: case FF_ARG_TYPE_UINT16: case FF_ARG_TYPE_UINT8: - case FF_ARG_TYPE_BOOL: - { + case FF_ARG_TYPE_BOOL: { uint64_t value = 0; - if (regType == REG_DWORD) - { - if (regDataLen < sizeof(uint32_t)) + if (regType == REG_DWORD) { + if (regDataLen < sizeof(uint32_t)) { goto type_mismatch; + } value = *(uint32_t*) regData; - } - else if (regType == REG_QWORD) - { - if (regDataLen < sizeof(uint64_t)) + } else if (regType == REG_QWORD) { + if (regDataLen < sizeof(uint64_t)) { goto type_mismatch; + } value = *(uint64_t*) regData; - } - else + } else { goto type_mismatch; + } - if (arg->type == FF_ARG_TYPE_UINT) *(uint32_t*) arg->value = (uint32_t) value; - else if (arg->type == FF_ARG_TYPE_UINT64) *(uint64_t*) arg->value = (uint64_t) value; - else if (arg->type == FF_ARG_TYPE_UINT16) *(uint16_t*) arg->value = (uint16_t) value; - else if (arg->type == FF_ARG_TYPE_UINT8) *(uint8_t*) arg->value = (uint8_t) value; - else if (arg->type == FF_ARG_TYPE_BOOL) *(bool*) arg->value = value != 0; + if (arg->type == FF_ARG_TYPE_UINT) { + *(uint32_t*) arg->value = (uint32_t) value; + } else if (arg->type == FF_ARG_TYPE_UINT64) { + *(uint64_t*) arg->value = (uint64_t) value; + } else if (arg->type == FF_ARG_TYPE_UINT16) { + *(uint16_t*) arg->value = (uint16_t) value; + } else if (arg->type == FF_ARG_TYPE_UINT8) { + *(uint8_t*) arg->value = (uint8_t) value; + } else if (arg->type == FF_ARG_TYPE_BOOL) { + *(bool*) arg->value = value != 0; + } break; } - case FF_ARG_TYPE_FLOAT: - { - if (regDataLen < sizeof(float)) + case FF_ARG_TYPE_FLOAT: { + if (regDataLen < sizeof(float)) { goto type_mismatch; + } *(float*) arg->value = *(float*) regData; break; } - case FF_ARG_TYPE_DOUBLE: - { - if (regDataLen < sizeof(double)) + case FF_ARG_TYPE_DOUBLE: { + if (regDataLen < sizeof(double)) { goto type_mismatch; + } *(double*) arg->value = *(double*) regData; break; } - case FF_ARG_TYPE_LIST: - { - if (regType != REG_MULTI_SZ) + case FF_ARG_TYPE_LIST: { + if (regType != REG_MULTI_SZ) { goto type_mismatch; + } FFlist* list = (FFlist*) arg->value; - if (list->elementSize != sizeof(FFstrbuf)) - { - if (error) - { + if (list->elementSize != sizeof(FFstrbuf)) { + if (error) { FF_STRBUF_AUTO_DESTROY nameA = arg->name ? ffStrbufCreateWS(arg->name) : ffStrbufCreateStatic("(default)"); ffStrbufAppendF(error, "ffRegReadValues(%s) type mismatch: expected list of strbuf for REG_MULTI_SZ", nameA.chars); } @@ -199,9 +191,7 @@ static bool processRegValue(const FFRegValueArg* arg, const ULONG regType, const for ( const wchar_t* ptr = (const wchar_t*) regData; (const uint8_t*) ptr < (const uint8_t*) regData + regDataLen && *ptr; - ptr++ - ) - { + ptr++) { uint32_t strLen = (uint32_t) wcsnlen(ptr, regDataLen / sizeof(wchar_t) - (size_t) (ptr - (const wchar_t*) regData)); ffStrbufInitNWS(FF_LIST_ADD(FFstrbuf, *list), strLen, ptr); ptr += strLen; @@ -209,20 +199,16 @@ static bool processRegValue(const FFRegValueArg* arg, const ULONG regType, const break; } - case FF_ARG_TYPE_BUFFER: - { - if (regType != REG_BINARY) + case FF_ARG_TYPE_BUFFER: { + if (regType != REG_BINARY) { goto type_mismatch; + } FFArgBuffer* buffer = (FFArgBuffer*) arg->value; - if (buffer->length == 0) - { + if (buffer->length == 0) { buffer->data = malloc(regDataLen); - } - else if (buffer->length < regDataLen) - { - if (error) - { + } else if (buffer->length < regDataLen) { + if (error) { FF_STRBUF_AUTO_DESTROY nameA = arg->name ? ffStrbufCreateWS(arg->name) : ffStrbufCreateStatic("(default)"); ffStrbufAppendF(error, "ffRegReadValues(%s) buffer too small (%u): expected %u", nameA.chars, (unsigned) buffer->length, (unsigned) regDataLen); } @@ -237,8 +223,7 @@ static bool processRegValue(const FFRegValueArg* arg, const ULONG regType, const case FF_ARG_TYPE_STRING: case FF_ARG_TYPE_NULL: default: - if (error) - { + if (error) { FF_STRBUF_AUTO_DESTROY nameA = arg->name ? ffStrbufCreateWS(arg->name) : ffStrbufCreateStatic("(default)"); ffStrbufAppendF(error, "processRegValue(%s) unsupported FFArgType %u", nameA.chars, (unsigned) arg->type); } @@ -249,18 +234,18 @@ static bool processRegValue(const FFRegValueArg* arg, const ULONG regType, const type_mismatch: FF_DEBUG("ffRegReadValues(%ls) type mismatch: regType=%u, argType=%u, dataLen=%u", - arg->name ?: L"(default)", (unsigned) regType, (unsigned) arg->type, (unsigned) regDataLen); - if (error) - { + arg->name ?: L"(default)", + (unsigned) regType, + (unsigned) arg->type, + (unsigned) regDataLen); + if (error) { FF_STRBUF_AUTO_DESTROY nameA = arg->name ? ffStrbufCreateWS(arg->name) : ffStrbufCreateStatic("(default)"); - ffStrbufAppendF(error, "ffRegReadValues(%s) type mismatch: regType=%u, argType=%u, dataLen=%u", - nameA.chars, (unsigned) regType, (unsigned) arg->type, (unsigned) regDataLen); + ffStrbufAppendF(error, "ffRegReadValues(%s) type mismatch: regType=%u, argType=%u, dataLen=%u", nameA.chars, (unsigned) regType, (unsigned) arg->type, (unsigned) regDataLen); } return false; } -bool ffRegReadValue(HANDLE hKey, const FFRegValueArg* arg, FFstrbuf* error) -{ +bool ffRegReadValue(HANDLE hKey, const FFRegValueArg* arg, FFstrbuf* error) { UNICODE_STRING* valueNameU = &(UNICODE_STRING) { .Length = arg->name ? (USHORT) (wcslen(arg->name) * sizeof(wchar_t)) : 0 /*(default)*/, .MaximumLength = 0, @@ -272,14 +257,13 @@ bool ffRegReadValue(HANDLE hKey, const FFRegValueArg* arg, FFstrbuf* error) KEY_VALUE_PARTIAL_INFORMATION* buffer = (KEY_VALUE_PARTIAL_INFORMATION*) &staticBuffer; DWORD bufSize = sizeof(staticBuffer); - if (NT_SUCCESS(NtQueryValueKey(hKey, valueNameU, KeyValuePartialInformation, buffer, bufSize, &bufSize))) + if (NT_SUCCESS(NtQueryValueKey(hKey, valueNameU, KeyValuePartialInformation, buffer, bufSize, &bufSize))) { goto process_value; + } - if (bufSize == 0) - { + if (bufSize == 0) { FF_DEBUG("NtQueryValueKey(%p, %ls) failed (bufSize=0)", hKey, arg->name ?: L"(default)"); - if (error) - { + if (error) { FF_STRBUF_AUTO_DESTROY valueNameA = arg->name ? ffStrbufCreateWS(arg->name) : ffStrbufCreateStatic("(default)"); ffStrbufAppendF(error, "NtQueryValueKey(%p, %s) failed", hKey, valueNameA.chars); } @@ -289,11 +273,9 @@ bool ffRegReadValue(HANDLE hKey, const FFRegValueArg* arg, FFstrbuf* error) dynamicBuffer = (uint8_t*) malloc(bufSize); buffer = (KEY_VALUE_PARTIAL_INFORMATION*) dynamicBuffer; - if (!NT_SUCCESS(NtQueryValueKey(hKey, valueNameU, KeyValuePartialInformation, buffer, bufSize, &bufSize))) - { + if (!NT_SUCCESS(NtQueryValueKey(hKey, valueNameU, KeyValuePartialInformation, buffer, bufSize, &bufSize))) { FF_DEBUG("NtQueryValueKey(%p, %ls, buffer=%u) failed", hKey, arg->name ?: L"(default)", (unsigned) bufSize); - if (error) - { + if (error) { FF_STRBUF_AUTO_DESTROY valueNameA = arg->name ? ffStrbufCreateWS(arg->name) : ffStrbufCreateStatic("(default)"); ffStrbufAppendF(error, "NtQueryValueKey(%p, %s, buffer) failed", hKey, valueNameA.chars); } @@ -305,22 +287,22 @@ process_value: return processRegValue(arg, buffer->Type, buffer->Data, buffer->DataLength, error); } -bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFstrbuf* error) -{ - if (__builtin_expect(argc == 0, false)) +bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFstrbuf* error) { + if (__builtin_expect(argc == 0, false)) { return true; + } assert(argv); FF_AUTO_FREE UNICODE_STRING* names = (UNICODE_STRING*) calloc(argc, sizeof(*names)); FF_AUTO_FREE KEY_VALUE_ENTRY* entries = (KEY_VALUE_ENTRY*) calloc(argc, sizeof(*entries)); - for (uint32_t i = 0; i < argc; ++i) - { - if (__builtin_expect(!argv[i].value, false)) - { + for (uint32_t i = 0; i < argc; ++i) { + if (__builtin_expect(!argv[i].value, false)) { FF_DEBUG("ffRegReadValues(argv[%u].value) is NULL", (unsigned) i); - if (error) ffStrbufAppendF(error, "ffRegReadValues(argv[%u].pVar) is NULL", (unsigned) i); + if (error) { + ffStrbufAppendF(error, "ffRegReadValues(argv[%u].pVar) is NULL", (unsigned) i); + } return false; } @@ -333,54 +315,51 @@ bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFs } ULONG bufferSize = argc * 128; - if (bufferSize < 512) + if (bufferSize < 512) { bufferSize = 512; + } FF_AUTO_FREE uint8_t* buffer = NULL; - while (true) - { + while (true) { buffer = (uint8_t*) realloc(buffer, bufferSize); ULONG writtenSize = bufferSize; ULONG requiredSize = 0; NTSTATUS status = NtQueryMultipleValueKey(hKey, entries, argc, buffer, &writtenSize, &requiredSize); - if (!NT_SUCCESS(status)) - { + if (!NT_SUCCESS(status)) { // Buffer too small: docs guarantee requiredSize is returned when provided. - if (requiredSize > bufferSize) - { + if (requiredSize > bufferSize) { FF_DEBUG("NtQueryMultipleValueKey(%p) resize buffer: %u -> %u", hKey, (unsigned) bufferSize, (unsigned) requiredSize); bufferSize = requiredSize; continue; } FF_DEBUG("NtQueryMultipleValueKey(%p, argc=%u) failed, status=0x%08X", hKey, (unsigned) argc, (unsigned) status); - if (error) - ffStrbufAppendF(error, "NtQueryMultipleValueKey(%p, argc=%u) failed, status=0x%08X", - hKey, (unsigned) argc, (unsigned) status); + if (error) { + ffStrbufAppendF(error, "NtQueryMultipleValueKey(%p, argc=%u) failed, status=0x%08X", hKey, (unsigned) argc, (unsigned) status); + } return false; } break; } - for (uint32_t i = 0; i < argc; ++i) - { + for (uint32_t i = 0; i < argc; ++i) { const FFRegValueArg* arg = &argv[i]; const KEY_VALUE_ENTRY* entry = &entries[i]; FF_DEBUG("Read value[%u] from %p: type=%u, len=%u", (unsigned) i, hKey, (unsigned) entry->Type, (unsigned) entry->DataLength); - if (!processRegValue(arg, entry->Type, buffer + entry->DataOffset, entry->DataLength, error)) + if (!processRegValue(arg, entry->Type, buffer + entry->DataOffset, entry->DataLength, error)) { return false; + } } return true; } -bool ffRegGetSubKey(HANDLE hKey, uint32_t index, FFstrbuf* result, FFstrbuf* error) -{ +bool ffRegGetSubKey(HANDLE hKey, uint32_t index, FFstrbuf* result, FFstrbuf* error) { assert(hKey); assert(result); @@ -388,11 +367,11 @@ bool ffRegGetSubKey(HANDLE hKey, uint32_t index, FFstrbuf* result, FFstrbuf* err ULONG bufSize = (ULONG) sizeof(buffer); KEY_BASIC_INFORMATION* keyInfo = (KEY_BASIC_INFORMATION*) buffer; - if (!NT_SUCCESS(NtEnumerateKey(hKey, index, KeyBasicInformation, keyInfo, bufSize, &bufSize))) - { + if (!NT_SUCCESS(NtEnumerateKey(hKey, index, KeyBasicInformation, keyInfo, bufSize, &bufSize))) { FF_DEBUG("NtEnumerateKey(hKey=%p, index=%u) failed", hKey, (unsigned) index); - if (error) + if (error) { ffStrbufAppendF(error, "NtEnumerateKey(hKey=%p, %u, keyInfo) failed", hKey, (unsigned) index); + } return false; } @@ -400,8 +379,7 @@ bool ffRegGetSubKey(HANDLE hKey, uint32_t index, FFstrbuf* result, FFstrbuf* err return true; } -bool ffRegGetNSubKeys(HANDLE hKey, uint32_t* result, FFstrbuf* error) -{ +bool ffRegGetNSubKeys(HANDLE hKey, uint32_t* result, FFstrbuf* error) { assert(hKey); assert(result); @@ -409,11 +387,11 @@ bool ffRegGetNSubKeys(HANDLE hKey, uint32_t* result, FFstrbuf* error) ULONG bufSize = sizeof(buffer); KEY_FULL_INFORMATION* keyInfo = (KEY_FULL_INFORMATION*) buffer; - if (!NT_SUCCESS(NtQueryKey(hKey, KeyFullInformation, keyInfo, bufSize, &bufSize))) - { + if (!NT_SUCCESS(NtQueryKey(hKey, KeyFullInformation, keyInfo, bufSize, &bufSize))) { FF_DEBUG("NtQueryKey(hKey=%p, KeyFullInformation) failed", hKey); - if (error) + if (error) { ffStrbufAppendF(error, "NtQueryKey(hKey=%p, KeyFullInformation, keyInfo) failed", hKey); + } return false; } diff --git a/src/common/windows/registry.h b/src/common/windows/registry.h index b056dd3b6..14910057b 100644 --- a/src/common/windows/registry.h +++ b/src/common/windows/registry.h @@ -5,18 +5,17 @@ #include "common/io.h" #ifndef HKEY_CURRENT_USER -#define HKEY_CLASSES_ROOT ((HKEY) (ULONG_PTR)((LONG)0x80000000)) -#define HKEY_CURRENT_USER ((HKEY) (ULONG_PTR)((LONG)0x80000001)) -#define HKEY_LOCAL_MACHINE ((HKEY) (ULONG_PTR)((LONG)0x80000002)) -#define HKEY_USERS ((HKEY) (ULONG_PTR)((LONG)0x80000003)) -#define HKEY_PERFORMANCE_DATA ((HKEY) (ULONG_PTR)((LONG)0x80000004)) -#define HKEY_CURRENT_CONFIG ((HKEY) (ULONG_PTR)((LONG)0x80000005)) -#define HKEY_DYN_DATA ((HKEY) (ULONG_PTR)((LONG)0x80000006)) -#define HKEY_CURRENT_USER_LOCAL_SETTINGS ((HKEY) (ULONG_PTR)((LONG)0x80000007)) +# define HKEY_CLASSES_ROOT ((HKEY) (ULONG_PTR) ((LONG) 0x80000000)) +# define HKEY_CURRENT_USER ((HKEY) (ULONG_PTR) ((LONG) 0x80000001)) +# define HKEY_LOCAL_MACHINE ((HKEY) (ULONG_PTR) ((LONG) 0x80000002)) +# define HKEY_USERS ((HKEY) (ULONG_PTR) ((LONG) 0x80000003)) +# define HKEY_PERFORMANCE_DATA ((HKEY) (ULONG_PTR) ((LONG) 0x80000004)) +# define HKEY_CURRENT_CONFIG ((HKEY) (ULONG_PTR) ((LONG) 0x80000005)) +# define HKEY_DYN_DATA ((HKEY) (ULONG_PTR) ((LONG) 0x80000006)) +# define HKEY_CURRENT_USER_LOCAL_SETTINGS ((HKEY) (ULONG_PTR) ((LONG) 0x80000007)) #endif -typedef struct FFRegValueArg -{ +typedef struct FFRegValueArg { FFArgType type; const void* value; const wchar_t* name; @@ -29,40 +28,39 @@ bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFs bool ffRegGetSubKey(HANDLE hKey, uint32_t index, FFstrbuf* result, FFstrbuf* error); bool ffRegGetNSubKeys(HANDLE hKey, uint32_t* result, FFstrbuf* error); -static inline bool ffRegOpenKeyForRead(HKEY hRootKey, const wchar_t* subKeyW, HANDLE* result, FFstrbuf* error) -{ +static inline bool ffRegOpenKeyForRead(HKEY hRootKey, const wchar_t* subKeyW, HANDLE* result, FFstrbuf* error) { return ffRegOpenSubkeyForRead(ffRegGetRootKeyHandle(hRootKey), subKeyW, result, error); } -static inline bool ffRegReadStrbuf(HANDLE hKey, const wchar_t* valueNameW, FFstrbuf* result, FFstrbuf* error) -{ +static inline bool ffRegReadStrbuf(HANDLE hKey, const wchar_t* valueNameW, FFstrbuf* result, FFstrbuf* error) { return ffRegReadValue(hKey, &(FFRegValueArg) { - .type = FF_ARG_TYPE_STRBUF, - .value = result, - .name = valueNameW, - }, error); + .type = FF_ARG_TYPE_STRBUF, + .value = result, + .name = valueNameW, + }, + error); } -static inline bool ffRegReadUint(HANDLE hKey, const wchar_t* valueNameW, uint32_t* result, FFstrbuf* error) -{ +static inline bool ffRegReadUint(HANDLE hKey, const wchar_t* valueNameW, uint32_t* result, FFstrbuf* error) { return ffRegReadValue(hKey, &(FFRegValueArg) { - .type = FF_ARG_TYPE_UINT, - .value = result, - .name = valueNameW, - }, error); + .type = FF_ARG_TYPE_UINT, + .value = result, + .name = valueNameW, + }, + error); } -static inline bool ffRegReadUint64(HANDLE hKey, const wchar_t* valueNameW, uint64_t* result, FFstrbuf* error) -{ +static inline bool ffRegReadUint64(HANDLE hKey, const wchar_t* valueNameW, uint64_t* result, FFstrbuf* error) { return ffRegReadValue(hKey, &(FFRegValueArg) { - .type = FF_ARG_TYPE_UINT64, - .value = result, - .name = valueNameW, - }, error); + .type = FF_ARG_TYPE_UINT64, + .value = result, + .name = valueNameW, + }, + error); } -static inline bool ffRegReadData(HANDLE hKey, const wchar_t* valueNameW, FFArgBuffer* buffer, FFstrbuf* error) -{ +static inline bool ffRegReadData(HANDLE hKey, const wchar_t* valueNameW, FFArgBuffer* buffer, FFstrbuf* error) { return ffRegReadValue(hKey, &(FFRegValueArg) { - .type = FF_ARG_TYPE_BUFFER, - .value = buffer, - .name = valueNameW, - }, error); + .type = FF_ARG_TYPE_BUFFER, + .value = buffer, + .name = valueNameW, + }, + error); } diff --git a/src/common/windows/unicode.c b/src/common/windows/unicode.c index 24aa3d564..06008ba42 100644 --- a/src/common/windows/unicode.c +++ b/src/common/windows/unicode.c @@ -2,10 +2,8 @@ #include "common/windows/nt.h" -void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) -{ - if(!length) - { +void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) { + if (!length) { ffStrbufClear(result); return; } @@ -13,8 +11,7 @@ void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) ULONG size_needed = 0; NTSTATUS status = RtlUnicodeToUTF8N(NULL, 0, &size_needed, source, length * sizeof(wchar_t)); - if (size_needed == 0) - { + if (size_needed == 0) { ffStrbufSetF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status); return; } @@ -26,16 +23,15 @@ void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) result->chars[size_needed] = '\0'; } -void ffStrbufAppendNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) -{ - if(!length) +void ffStrbufAppendNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) { + if (!length) { return; + } ULONG size_needed = 0; NTSTATUS status = RtlUnicodeToUTF8N(NULL, 0, &size_needed, source, length * sizeof(wchar_t)); - if (size_needed == 0) - { + if (size_needed == 0) { ffStrbufAppendF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status); return; } diff --git a/src/common/windows/unicode.h b/src/common/windows/unicode.h index 8a3162432..f58b425e5 100644 --- a/src/common/windows/unicode.h +++ b/src/common/windows/unicode.h @@ -6,39 +6,41 @@ void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source); void ffStrbufAppendNWS(FFstrbuf* result, uint32_t length, const wchar_t* source); -static inline void ffStrbufSetWS(FFstrbuf* result, const wchar_t* source) -{ - if (!source) return ffStrbufClear(result); - return ffStrbufSetNWS(result, (uint32_t)wcslen(source), source); +static inline void ffStrbufSetWS(FFstrbuf* result, const wchar_t* source) { + if (!source) { + return ffStrbufClear(result); + } + return ffStrbufSetNWS(result, (uint32_t) wcslen(source), source); } -static inline void ffStrbufAppendWS(FFstrbuf* result, const wchar_t* source) -{ - if (!source) return; - return ffStrbufAppendNWS(result, (uint32_t)wcslen(source), source); +static inline void ffStrbufAppendWS(FFstrbuf* result, const wchar_t* source) { + if (!source) { + return; + } + return ffStrbufAppendNWS(result, (uint32_t) wcslen(source), source); } -static inline void ffStrbufInitNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) -{ +static inline void ffStrbufInitNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) { ffStrbufInit(result); return ffStrbufSetNWS(result, length, source); } -static inline void ffStrbufInitWS(FFstrbuf* result, const wchar_t* source) -{ - if (!source) return ffStrbufInit(result); - return ffStrbufInitNWS(result, (uint32_t)wcslen(source), source); +static inline void ffStrbufInitWS(FFstrbuf* result, const wchar_t* source) { + if (!source) { + return ffStrbufInit(result); + } + return ffStrbufInitNWS(result, (uint32_t) wcslen(source), source); } -static inline FFstrbuf ffStrbufCreateNWS(uint32_t length, const wchar_t* source) -{ +static inline FFstrbuf ffStrbufCreateNWS(uint32_t length, const wchar_t* source) { FFstrbuf result; ffStrbufInitNWS(&result, length, source); return result; } -static inline FFstrbuf ffStrbufCreateWS(const wchar_t* source) -{ - if (!source) return ffStrbufCreate(); - return ffStrbufCreateNWS((uint32_t)wcslen(source), source); +static inline FFstrbuf ffStrbufCreateWS(const wchar_t* source) { + if (!source) { + return ffStrbufCreate(); + } + return ffStrbufCreateNWS((uint32_t) wcslen(source), source); } diff --git a/src/common/windows/unicode.hpp b/src/common/windows/unicode.hpp index 418a206df..b2b534dbe 100644 --- a/src/common/windows/unicode.hpp +++ b/src/common/windows/unicode.hpp @@ -3,28 +3,25 @@ #ifdef __cplusplus extern "C" { -#include "unicode.h" +# include "unicode.h" } -#include +# include -static inline void ffStrbufInitWSV(FFstrbuf* result, const std::wstring_view source) -{ +static inline void ffStrbufInitWSV(FFstrbuf* result, const std::wstring_view source) { return ffStrbufInitNWS(result, (uint32_t) source.size(), source.data()); } -static inline FFstrbuf ffStrbufCreateWSV(const std::wstring_view source) -{ +static inline FFstrbuf ffStrbufCreateWSV(const std::wstring_view source) { return ffStrbufCreateNWS((uint32_t) source.size(), source.data()); } -static inline void ffStrbufSetWSV(FFstrbuf* result, const std::wstring_view source) -{ +static inline void ffStrbufSetWSV(FFstrbuf* result, const std::wstring_view source) { return ffStrbufSetNWS(result, (uint32_t) source.size(), source.data()); } #else - #error Must be included in C++ source file +# error Must be included in C++ source file #endif diff --git a/src/common/windows/util.hpp b/src/common/windows/util.hpp index 9891d638c..939f6bb45 100644 --- a/src/common/windows/util.hpp +++ b/src/common/windows/util.hpp @@ -6,14 +6,16 @@ template struct on_scope_exit { static_assert(std::is_nothrow_move_constructible::value, - "Fn must be nothrow move constructible"); + "Fn must be nothrow move constructible"); - explicit on_scope_exit(Fn &&fn) noexcept + explicit on_scope_exit(Fn&& fn) noexcept : _fn(std::move(fn)) {}; on_scope_exit(const on_scope_exit&) = delete; on_scope_exit& operator=(const on_scope_exit&) = delete; - ~on_scope_exit() noexcept { this->_fn(); } + ~on_scope_exit() noexcept { + this->_fn(); + } -private: + private: Fn _fn; }; diff --git a/src/common/windows/variant.cpp b/src/common/windows/variant.cpp index fa3b9a0e5..d5610d308 100644 --- a/src/common/windows/variant.cpp +++ b/src/common/windows/variant.cpp @@ -2,8 +2,7 @@ #include -FFWmiVariant::FFWmiVariant(std::initializer_list strings): FFWmiVariant() -{ +FFWmiVariant::FFWmiVariant(std::initializer_list strings) : FFWmiVariant() { SAFEARRAYBOUND bound = { .cElements = (ULONG) strings.size(), .lLbound = 0, diff --git a/src/common/windows/variant.hpp b/src/common/windows/variant.hpp index b2e68cfa8..afa1317ba 100644 --- a/src/common/windows/variant.hpp +++ b/src/common/windows/variant.hpp @@ -7,8 +7,7 @@ #include template -struct FFBaseVariant: TVariant -{ +struct FFBaseVariant : TVariant { bool hasValue() { return this->vt != VT_EMPTY; } @@ -17,8 +16,8 @@ struct FFBaseVariant: TVariant return this->hasValue(); } - template T get() - { + template + T get() { // boolean if constexpr (std::is_same_v) { assert(this->vt == VT_BOOL); @@ -29,16 +28,13 @@ struct FFBaseVariant: TVariant else if constexpr (std::is_same_v) { assert(this->vt == VT_I1); return this->cVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_I2); return this->iVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_I4 || this->vt == VT_INT); return this->intVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_I8); return this->llVal; } @@ -47,16 +43,13 @@ struct FFBaseVariant: TVariant else if constexpr (std::is_same_v) { assert(this->vt == VT_UI1); return this->bVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_UI2); return this->uiVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_UI4 || this->vt == VT_UINT); return this->uintVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_UI8); return this->ullVal; } @@ -65,8 +58,7 @@ struct FFBaseVariant: TVariant else if constexpr (std::is_same_v) { assert(this->vt == VT_R4); return this->fltVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_R8); return this->dblVal; } @@ -75,95 +67,98 @@ struct FFBaseVariant: TVariant else if constexpr (std::is_same_v) { assert(this->vt == VT_LPSTR); return this->pcVal; - } - else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { assert(this->vt == VT_BSTR || this->vt == VT_LPWSTR); - if (this->vt == VT_LPWSTR) + if (this->vt == VT_LPWSTR) { return this->bstrVal; - else - return { this->bstrVal, SysStringLen(this->bstrVal) }; + } else { + return {this->bstrVal, SysStringLen(this->bstrVal)}; + } } // array signed else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_I1); - return std::make_pair((int8_t*)this->parray->pvData, this->parray->cDims); - } - else if constexpr (std::is_same_v>) { + return std::make_pair((int8_t*) this->parray->pvData, this->parray->cDims); + } else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_I2); - return std::make_pair((int16_t*)this->parray->pvData, this->parray->cDims); - } - else if constexpr (std::is_same_v>) { + return std::make_pair((int16_t*) this->parray->pvData, this->parray->cDims); + } else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_I4); - return std::make_pair((int32_t*)this->parray->pvData, this->parray->cDims); - } - else if constexpr (std::is_same_v>) { + return std::make_pair((int32_t*) this->parray->pvData, this->parray->cDims); + } else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_I8); - return std::make_pair((int64_t*)this->parray->pvData, this->parray->cDims); + return std::make_pair((int64_t*) this->parray->pvData, this->parray->cDims); } // array unsigned else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_UI1); - return std::make_pair((uint8_t*)this->parray->pvData, this->parray->cDims); - } - else if constexpr (std::is_same_v>) { + return std::make_pair((uint8_t*) this->parray->pvData, this->parray->cDims); + } else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_UI2); - return std::make_pair((uint16_t*)this->parray->pvData, this->parray->cDims); - } - else if constexpr (std::is_same_v>) { + return std::make_pair((uint16_t*) this->parray->pvData, this->parray->cDims); + } else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_UI4); - return std::make_pair((uint32_t*)this->parray->pvData, this->parray->cDims); - } - else if constexpr (std::is_same_v>) { + return std::make_pair((uint32_t*) this->parray->pvData, this->parray->cDims); + } else if constexpr (std::is_same_v>) { assert(this->vt & VT_ARRAY); assert((this->vt & ~VT_ARRAY) == VT_UI8); - return std::make_pair((uint64_t*)this->parray->pvData, this->parray->cDims); - } - else { + return std::make_pair((uint64_t*) this->parray->pvData, this->parray->cDims); + } else { assert(false && "unsupported type"); __builtin_unreachable(); } } }; -struct FFWmiVariant: FFBaseVariant -{ +struct FFWmiVariant : FFBaseVariant { FFWmiVariant(const FFWmiVariant&) = delete; FFWmiVariant(FFWmiVariant&&); // don't define it to enforce NRVO optimization - explicit FFWmiVariant() { VariantInit(this); } + explicit FFWmiVariant() { + VariantInit(this); + } explicit FFWmiVariant(std::initializer_list strings); - ~FFWmiVariant() { VariantClear(this); } + ~FFWmiVariant() { + VariantClear(this); + } }; static_assert(sizeof(FFWmiVariant) == sizeof(VARIANT), ""); -struct FFPropVariant: FFBaseVariant -{ +struct FFPropVariant : FFBaseVariant { FFPropVariant(const FFPropVariant&) = delete; FFPropVariant(FFPropVariant&&); // don't define it to enforce NRVO optimization - explicit FFPropVariant() { PropVariantInit(this); } - ~FFPropVariant() { PropVariantClear(this); } + explicit FFPropVariant() { + PropVariantInit(this); + } + ~FFPropVariant() { + PropVariantClear(this); + } }; static_assert(sizeof(FFPropVariant) == sizeof(PROPVARIANT), ""); -namespace -{ - // Provide our bstr_t to avoid libstdc++ dependency - struct bstr_t - { - explicit bstr_t(const wchar_t* str) noexcept: _bstr(SysAllocString(str)) {} - ~bstr_t(void) noexcept { SysFreeString(_bstr); } - explicit operator const wchar_t*(void) const noexcept { return _bstr; } - operator BSTR(void) const noexcept { return _bstr; } +namespace { +// Provide our bstr_t to avoid libstdc++ dependency +struct bstr_t { + explicit bstr_t(const wchar_t* str) noexcept : _bstr(SysAllocString(str)) {} + ~bstr_t(void) noexcept { + SysFreeString(_bstr); + } + explicit operator const wchar_t*(void) const noexcept { + return _bstr; + } + operator BSTR(void) const noexcept { + return _bstr; + } - private: - BSTR _bstr; - }; -} + private: + BSTR _bstr; +}; +} // namespace diff --git a/src/common/windows/version.c b/src/common/windows/version.c index df00e29a2..6b4c589fe 100644 --- a/src/common/windows/version.c +++ b/src/common/windows/version.c @@ -5,53 +5,46 @@ #include -bool ffGetFileVersion(const wchar_t* filePath, const wchar_t* stringName, FFstrbuf* version) -{ +bool ffGetFileVersion(const wchar_t* filePath, const wchar_t* stringName, FFstrbuf* version) { FF_DEBUG("ffGetFileVersion: enter filePath=%ls stringName=%ls", filePath, stringName); DWORD handle; DWORD size = GetFileVersionInfoSizeW(filePath, &handle); - if (size == 0) - { + if (size == 0) { DWORD err = GetLastError(); FF_DEBUG("GetFileVersionInfoSizeW failed: err=%lu (%s)", - (unsigned long) err, ffDebugWin32Error(err)); + (unsigned long) err, + ffDebugWin32Error(err)); return false; } FF_DEBUG("GetFileVersionInfoSizeW ok: size=%lu handle=%lu", - (unsigned long) size, (unsigned long) handle); + (unsigned long) size, + (unsigned long) handle); FF_AUTO_FREE void* versionData = malloc(size); - if (!versionData) - { + if (!versionData) { FF_DEBUG("malloc failed: size=%lu", (unsigned long) size); return false; } - if (!GetFileVersionInfoW(filePath, handle, size, versionData)) - { + if (!GetFileVersionInfoW(filePath, handle, size, versionData)) { DWORD err = GetLastError(); FF_DEBUG("GetFileVersionInfoW failed: err=%lu (%s)", - (unsigned long) err, ffDebugWin32Error(err)); + (unsigned long) err, + ffDebugWin32Error(err)); return false; } FF_DEBUG("GetFileVersionInfoW ok"); - if (!stringName) - { + if (!stringName) { VS_FIXEDFILEINFO* verInfo; UINT len; if (VerQueryValueW(versionData, L"\\", (void**) &verInfo, &len) && len && - verInfo->dwSignature == 0xFEEF04BD) - { - ffStrbufSetF(version, "%u.%u.%u.%u", - (unsigned) ((verInfo->dwProductVersionMS >> 16) & 0xffff), - (unsigned) ((verInfo->dwProductVersionMS >> 0) & 0xffff), - (unsigned) ((verInfo->dwProductVersionLS >> 16) & 0xffff), - (unsigned) ((verInfo->dwProductVersionLS >> 0) & 0xffff)); + verInfo->dwSignature == 0xFEEF04BD) { + ffStrbufSetF(version, "%u.%u.%u.%u", (unsigned) ((verInfo->dwProductVersionMS >> 16) & 0xffff), (unsigned) ((verInfo->dwProductVersionMS >> 0) & 0xffff), (unsigned) ((verInfo->dwProductVersionLS >> 16) & 0xffff), (unsigned) ((verInfo->dwProductVersionLS >> 0) & 0xffff)); FF_DEBUG("fixed version resolved: %s", version->chars); return true; } @@ -60,30 +53,28 @@ bool ffGetFileVersion(const wchar_t* filePath, const wchar_t* stringName, FFstrb return false; } - struct { WORD language; WORD codePage; }* translations; + struct { + WORD language; + WORD codePage; + }* translations; UINT translationsLen; if (VerQueryValueW(versionData, L"\\VarFileInfo\\Translation", (void**) &translations, &translationsLen) && - translationsLen >= sizeof(*translations)) - { + translationsLen >= sizeof(*translations)) { wchar_t subBlock[128]; - snwprintf(subBlock, ARRAY_SIZE(subBlock), L"\\StringFileInfo\\%04x%04x\\%ls", - translations[0].language, translations[0].codePage, stringName); + snwprintf(subBlock, ARRAY_SIZE(subBlock), L"\\StringFileInfo\\%04x%04x\\%ls", translations[0].language, translations[0].codePage, stringName); FF_DEBUG("query version string with translation: %ls", subBlock); wchar_t* value; UINT valueLen; // Number of characters, including null terminator - if (VerQueryValueW(versionData, subBlock, (void**) &value, &valueLen) && valueLen > 0) - { + if (VerQueryValueW(versionData, subBlock, (void**) &value, &valueLen) && valueLen > 0) { ffStrbufSetNWS(version, valueLen - 1, value); FF_DEBUG("version string resolved (translation fallback): %s", version->chars); return true; } FF_DEBUG("translation fallback query failed"); - } - else - { + } else { FF_DEBUG("no translation table found in version resource"); } diff --git a/src/common/windows/version.h b/src/common/windows/version.h index 73e7cc1e5..457c0534a 100644 --- a/src/common/windows/version.h +++ b/src/common/windows/version.h @@ -1,6 +1,5 @@ #include "fastfetch.h" - /** * @brief Retrieves a specific version string for a Windows file. * diff --git a/src/common/windows/wmi.cpp b/src/common/windows/wmi.cpp index 74dbb3f19..381bf5922 100644 --- a/src/common/windows/wmi.cpp +++ b/src/common/windows/wmi.cpp @@ -6,8 +6,7 @@ #include #include -static const char* doInitService(const wchar_t* networkResource, IWbemServices** result) -{ +static const char* doInitService(const wchar_t* networkResource, IWbemServices** result) { HRESULT hres; // Obtain the initial locator to WMI @@ -19,8 +18,9 @@ static const char* doInitService(const wchar_t* networkResource, IWbemServices** IID_IWbemLocator, (LPVOID*) &pLoc); - if (FAILED(hres)) + if (FAILED(hres)) { return "Failed to create IWbemLocator object"; + } // Connect to WMI through the IWbemLocator::ConnectServer method IWbemServices* pSvc = nullptr; @@ -29,47 +29,46 @@ static const char* doInitService(const wchar_t* networkResource, IWbemServices** // the current user and obtain pointer pSvc // to make IWbemServices calls. hres = pLoc->ConnectServer( - bstr_t(networkResource), // Object path of WMI namespace - nullptr, // User name. nullptr = current user - nullptr, // User password. nullptr = current - 0, // Locale. nullptr indicates current - 0, // Security flags. - 0, // Authority (for example, Kerberos) - 0, // Context object - &pSvc // pointer to IWbemServices proxy + bstr_t(networkResource), // Object path of WMI namespace + nullptr, // User name. nullptr = current user + nullptr, // User password. nullptr = current + 0, // Locale. nullptr indicates current + 0, // Security flags. + 0, // Authority (for example, Kerberos) + 0, // Context object + &pSvc // pointer to IWbemServices proxy ); pLoc->Release(); pLoc = nullptr; - if (FAILED(hres)) + if (FAILED(hres)) { return "Could not connect WMI server"; + } *result = pSvc; return NULL; } -FFWmiQuery::FFWmiQuery(const wchar_t* queryStr, FFstrbuf* error, FFWmiNamespace wmiNs) -{ +FFWmiQuery::FFWmiQuery(const wchar_t* queryStr, FFstrbuf* error, FFWmiNamespace wmiNs) { const char* errStr; - if ((errStr = ffInitCom())) - { - if (error) + if ((errStr = ffInitCom())) { + if (error) { ffStrbufSetS(error, errStr); + } return; } static IWbemServices* contexts[(int) FFWmiNamespace::LAST]; - IWbemServices* context = contexts[(int)wmiNs]; - if (!context) - { - if ((errStr = doInitService(wmiNs == FFWmiNamespace::CIMV2 ? L"ROOT\\CIMV2" : L"ROOT\\WMI", &context))) - { - if (error) + IWbemServices* context = contexts[(int) wmiNs]; + if (!context) { + if ((errStr = doInitService(wmiNs == FFWmiNamespace::CIMV2 ? L"ROOT\\CIMV2" : L"ROOT\\WMI", &context))) { + if (error) { ffStrbufSetS(error, errStr); + } return; } - contexts[(int)wmiNs] = context; + contexts[(int) wmiNs] = context; } this->pService = context; @@ -82,44 +81,37 @@ FFWmiQuery::FFWmiQuery(const wchar_t* queryStr, FFstrbuf* error, FFWmiNamespace nullptr, &this->pEnumerator); - if (FAILED(hres)) - { - if(error) + if (FAILED(hres)) { + if (error) { ffStrbufAppendF(error, "Query for '%ls' failed. Error code = 0x%lX", queryStr, hres); + } } } -bool FFWmiRecord::getString(const wchar_t* key, FFstrbuf* strbuf) -{ +bool FFWmiRecord::getString(const wchar_t* key, FFstrbuf* strbuf) { bool result = true; FFWmiVariant vtProp; CIMTYPE type; - if(FAILED(obj->Get(key, 0, &vtProp, &type, nullptr)) || vtProp.vt != VT_BSTR) - { + if (FAILED(obj->Get(key, 0, &vtProp, &type, nullptr)) || vtProp.vt != VT_BSTR) { result = false; - } - else - { - switch(vtProp.vt) - { + } else { + switch (vtProp.vt) { case VT_BSTR: - if(type == CIM_DATETIME) - { - FF_AUTO_RELEASE_COM_OBJECT ISWbemDateTime *pDateTime = nullptr; + if (type == CIM_DATETIME) { + FF_AUTO_RELEASE_COM_OBJECT ISWbemDateTime* pDateTime = nullptr; BSTR dateStr; - if(FAILED(CoCreateInstance(__uuidof(SWbemDateTime), 0, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDateTime)))) + if (FAILED(CoCreateInstance(__uuidof(SWbemDateTime), 0, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDateTime)))) { result = false; - else if(FAILED(pDateTime->put_Value(vtProp.bstrVal))) + } else if (FAILED(pDateTime->put_Value(vtProp.bstrVal))) { result = false; - else if(FAILED(pDateTime->GetFileTime(VARIANT_TRUE, &dateStr))) + } else if (FAILED(pDateTime->GetFileTime(VARIANT_TRUE, &dateStr))) { result = false; - else + } else { ffStrbufSetNWS(strbuf, SysStringLen(dateStr), dateStr); - } - else - { + } + } else { ffStrbufSetNWS(strbuf, SysStringLen(vtProp.bstrVal), vtProp.bstrVal); } break; @@ -137,100 +129,155 @@ bool FFWmiRecord::getString(const wchar_t* key, FFstrbuf* strbuf) return result; } -bool FFWmiRecord::getSigned(const wchar_t* key, int64_t* integer) -{ +bool FFWmiRecord::getSigned(const wchar_t* key, int64_t* integer) { bool result = true; FFWmiVariant vtProp; CIMTYPE type; - if(FAILED(obj->Get(key, 0, &vtProp, &type, nullptr))) - { + if (FAILED(obj->Get(key, 0, &vtProp, &type, nullptr))) { result = false; - } - else - { - switch(vtProp.vt) - { - case VT_BSTR: *integer = wcstoll(vtProp.bstrVal, nullptr, 10); break; - case VT_I1: *integer = vtProp.cVal; break; - case VT_I2: *integer = vtProp.iVal; break; + } else { + switch (vtProp.vt) { + case VT_BSTR: + *integer = wcstoll(vtProp.bstrVal, nullptr, 10); + break; + case VT_I1: + *integer = vtProp.cVal; + break; + case VT_I2: + *integer = vtProp.iVal; + break; case VT_INT: - case VT_I4: *integer = vtProp.intVal; break; - case VT_I8: *integer = vtProp.llVal; break; - case VT_UI1: *integer = (int64_t)vtProp.bVal; break; - case VT_UI2: *integer = (int64_t)vtProp.uiVal; break; + case VT_I4: + *integer = vtProp.intVal; + break; + case VT_I8: + *integer = vtProp.llVal; + break; + case VT_UI1: + *integer = (int64_t) vtProp.bVal; + break; + case VT_UI2: + *integer = (int64_t) vtProp.uiVal; + break; case VT_UINT: - case VT_UI4: *integer = (int64_t)vtProp.uintVal; break; - case VT_UI8: *integer = (int64_t)vtProp.ullVal; break; - case VT_BOOL: *integer = vtProp.boolVal != VARIANT_FALSE; break; - default: *integer = 0; result = false; + case VT_UI4: + *integer = (int64_t) vtProp.uintVal; + break; + case VT_UI8: + *integer = (int64_t) vtProp.ullVal; + break; + case VT_BOOL: + *integer = vtProp.boolVal != VARIANT_FALSE; + break; + default: + *integer = 0; + result = false; } } return result; } -bool FFWmiRecord::getUnsigned(const wchar_t* key, uint64_t* integer) -{ +bool FFWmiRecord::getUnsigned(const wchar_t* key, uint64_t* integer) { bool result = true; FFWmiVariant vtProp; - if(FAILED(obj->Get(key, 0, &vtProp, nullptr, nullptr))) - { + if (FAILED(obj->Get(key, 0, &vtProp, nullptr, nullptr))) { result = false; - } - else - { - switch(vtProp.vt) - { - case VT_BSTR: *integer = wcstoull(vtProp.bstrVal, nullptr, 10); break; - case VT_I1: *integer = (uint64_t)vtProp.cVal; break; - case VT_I2: *integer = (uint64_t)vtProp.iVal; break; + } else { + switch (vtProp.vt) { + case VT_BSTR: + *integer = wcstoull(vtProp.bstrVal, nullptr, 10); + break; + case VT_I1: + *integer = (uint64_t) vtProp.cVal; + break; + case VT_I2: + *integer = (uint64_t) vtProp.iVal; + break; case VT_INT: - case VT_I4: *integer = (uint64_t)vtProp.intVal; break; - case VT_I8: *integer = (uint64_t)vtProp.llVal; break; - case VT_UI1: *integer = vtProp.bVal; break; - case VT_UI2: *integer = vtProp.uiVal; break; + case VT_I4: + *integer = (uint64_t) vtProp.intVal; + break; + case VT_I8: + *integer = (uint64_t) vtProp.llVal; + break; + case VT_UI1: + *integer = vtProp.bVal; + break; + case VT_UI2: + *integer = vtProp.uiVal; + break; case VT_UINT: - case VT_UI4: *integer = vtProp.uintVal; break; - case VT_UI8: *integer = vtProp.ullVal; break; - case VT_BOOL: *integer = vtProp.boolVal != VARIANT_FALSE; break; - default: *integer = 0; result = false; + case VT_UI4: + *integer = vtProp.uintVal; + break; + case VT_UI8: + *integer = vtProp.ullVal; + break; + case VT_BOOL: + *integer = vtProp.boolVal != VARIANT_FALSE; + break; + default: + *integer = 0; + result = false; } } return result; } -bool FFWmiRecord::getReal(const wchar_t* key, double* real) -{ +bool FFWmiRecord::getReal(const wchar_t* key, double* real) { bool result = true; FFWmiVariant vtProp; - if(FAILED(obj->Get(key, 0, &vtProp, nullptr, nullptr))) - { + if (FAILED(obj->Get(key, 0, &vtProp, nullptr, nullptr))) { result = false; - } - else - { - switch(vtProp.vt) - { - case VT_BSTR: *real = wcstod(vtProp.bstrVal, nullptr); break; - case VT_I1: *real = vtProp.cVal; break; - case VT_I2: *real = vtProp.iVal; break; + } else { + switch (vtProp.vt) { + case VT_BSTR: + *real = wcstod(vtProp.bstrVal, nullptr); + break; + case VT_I1: + *real = vtProp.cVal; + break; + case VT_I2: + *real = vtProp.iVal; + break; case VT_INT: - case VT_I4: *real = vtProp.intVal; break; - case VT_I8: *real = (double)vtProp.llVal; break; - case VT_UI1: *real = vtProp.bVal; break; - case VT_UI2: *real = vtProp.uiVal; break; + case VT_I4: + *real = vtProp.intVal; + break; + case VT_I8: + *real = (double) vtProp.llVal; + break; + case VT_UI1: + *real = vtProp.bVal; + break; + case VT_UI2: + *real = vtProp.uiVal; + break; case VT_UINT: - case VT_UI4: *real = vtProp.uintVal; break; - case VT_UI8: *real = (double)vtProp.ullVal; break; - case VT_R4: *real = vtProp.fltVal; break; - case VT_R8: *real = vtProp.dblVal; break; - case VT_BOOL: *real = vtProp.boolVal != VARIANT_FALSE; break; - default: *real = -DBL_MAX; result = false; + case VT_UI4: + *real = vtProp.uintVal; + break; + case VT_UI8: + *real = (double) vtProp.ullVal; + break; + case VT_R4: + *real = vtProp.fltVal; + break; + case VT_R8: + *real = vtProp.dblVal; + break; + case VT_BOOL: + *real = vtProp.boolVal != VARIANT_FALSE; + break; + default: + *real = -DBL_MAX; + result = false; } } return result; diff --git a/src/common/windows/wmi.hpp b/src/common/windows/wmi.hpp index a72a72dcc..d620ab927 100644 --- a/src/common/windows/wmi.hpp +++ b/src/common/windows/wmi.hpp @@ -3,13 +3,13 @@ #ifdef __cplusplus extern "C" { - #include "fastfetch.h" +# include "fastfetch.h" } -#include -#include +# include +# include -#include "variant.hpp" +# include "variant.hpp" enum class FFWmiNamespace { CIMV2, @@ -17,17 +17,26 @@ enum class FFWmiNamespace { LAST, }; -struct FFWmiRecord -{ +struct FFWmiRecord { IWbemClassObject* obj = nullptr; - explicit FFWmiRecord(IWbemClassObject* obj): obj(obj) {}; + explicit FFWmiRecord(IWbemClassObject* obj) : obj(obj) {}; FFWmiRecord(const FFWmiRecord&) = delete; - FFWmiRecord(FFWmiRecord&& other) { *this = (FFWmiRecord&&)other; } - ~FFWmiRecord() { if(obj) obj->Release(); } - explicit operator bool() { return !!obj; } - FFWmiRecord& operator =(FFWmiRecord&& other) { - if(obj) obj->Release(); + FFWmiRecord(FFWmiRecord&& other) { + *this = (FFWmiRecord&&) other; + } + ~FFWmiRecord() { + if (obj) { + obj->Release(); + } + } + explicit operator bool() { + return !!obj; + } + FFWmiRecord& operator=(FFWmiRecord&& other) { + if (obj) { + obj->Release(); + } obj = other.obj; other.obj = nullptr; return *this; @@ -44,20 +53,29 @@ struct FFWmiRecord } }; -struct FFWmiQuery -{ +struct FFWmiQuery { IWbemServices* pService = nullptr; IEnumWbemClassObject* pEnumerator = nullptr; FFWmiQuery(const wchar_t* queryStr, FFstrbuf* error = nullptr, FFWmiNamespace wmiNs = FFWmiNamespace::CIMV2); - explicit FFWmiQuery(IEnumWbemClassObject* pEnumerator): pEnumerator(pEnumerator) {} + explicit FFWmiQuery(IEnumWbemClassObject* pEnumerator) : pEnumerator(pEnumerator) {} FFWmiQuery(const FFWmiQuery& other) = delete; - FFWmiQuery(FFWmiQuery&& other) { *this = (FFWmiQuery&&)other; } - ~FFWmiQuery() { if(pEnumerator) pEnumerator->Release(); } + FFWmiQuery(FFWmiQuery&& other) { + *this = (FFWmiQuery&&) other; + } + ~FFWmiQuery() { + if (pEnumerator) { + pEnumerator->Release(); + } + } - explicit operator bool() { return !!pEnumerator; } - FFWmiQuery& operator =(FFWmiQuery&& other) { - if(pEnumerator) pEnumerator->Release(); + explicit operator bool() { + return !!pEnumerator; + } + FFWmiQuery& operator=(FFWmiQuery&& other) { + if (pEnumerator) { + pEnumerator->Release(); + } pEnumerator = other.pEnumerator; other.pEnumerator = nullptr; return *this; @@ -74,6 +92,6 @@ struct FFWmiQuery }; #else - // Win32 COM headers requires C++ compiler - #error Must be included in C++ source file +// Win32 COM headers requires C++ compiler +# error Must be included in C++ source file #endif //__cplusplus diff --git a/src/detection/battery/battery.h b/src/detection/battery/battery.h index ddeb7c6e7..cc4bd1793 100644 --- a/src/detection/battery/battery.h +++ b/src/detection/battery/battery.h @@ -5,8 +5,7 @@ #define FF_BATTERY_TEMP_UNSET (-DBL_MAX) -typedef struct FFBatteryResult -{ +typedef struct FFBatteryResult { FFstrbuf manufacturer; FFstrbuf manufactureDate; FFstrbuf modelName; diff --git a/src/detection/battery/battery_android.c b/src/detection/battery/battery_android.c index 9425dbd19..7a4e8150a 100644 --- a/src/detection/battery/battery_android.c +++ b/src/detection/battery/battery_android.c @@ -7,31 +7,29 @@ #define FF_TERMUX_API_PATH FASTFETCH_TARGET_DIR_ROOT "/libexec/termux-api" #define FF_TERMUX_API_PARAM "BatteryStatus" -static inline void wrapYyjsonFree(yyjson_doc** doc) -{ +static inline void wrapYyjsonFree(yyjson_doc** doc) { assert(doc); - if (*doc) + if (*doc) { yyjson_doc_free(*doc); + } } -static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) -{ +static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if(ffProcessAppendStdOut(&buffer, (char* const[]){ - FF_TERMUX_API_PATH, - FF_TERMUX_API_PARAM, - NULL - })) + if (ffProcessAppendStdOut(&buffer, (char* const[]) {FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, NULL})) { return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed"; + } yyjson_doc* __attribute__((__cleanup__(wrapYyjsonFree))) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, NULL, NULL); - if (!doc) + if (!doc) { return "Failed to parse battery info"; + } yyjson_val* root = yyjson_doc_get_root(doc); - if (!yyjson_is_obj(root)) + if (!yyjson_is_obj(root)) { return "Battery info result is not a JSON object"; + } FFBatteryResult* battery = ffListAdd(results); battery->temperature = FF_BATTERY_TEMP_UNSET; @@ -46,50 +44,54 @@ static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) battery->capacity = yyjson_get_num(yyjson_obj_get(root, "percentage")); const char* acStatus = yyjson_get_str(yyjson_obj_get(root, "plugged")); - if (acStatus) - { - if (ffStrEquals(acStatus, "PLUGGED_AC")) + if (acStatus) { + if (ffStrEquals(acStatus, "PLUGGED_AC")) { ffStrbufAppendS(&battery->status, "AC Connected, "); - else if (ffStrEquals(acStatus, "PLUGGED_USB")) + } else if (ffStrEquals(acStatus, "PLUGGED_USB")) { ffStrbufAppendS(&battery->status, "USB Connected, "); - else if (ffStrEquals(acStatus, "PLUGGED_WIRELESS")) + } else if (ffStrEquals(acStatus, "PLUGGED_WIRELESS")) { ffStrbufAppendS(&battery->status, "Wireless Connected, "); + } } const char* status = yyjson_get_str(yyjson_obj_get(root, "status")); - if (status) - { - if (ffStrEquals(status, "CHARGING")) + if (status) { + if (ffStrEquals(status, "CHARGING")) { ffStrbufAppendS(&battery->status, "Charging"); - else if (ffStrEquals(status, "DISCHARGING")) + } else if (ffStrEquals(status, "DISCHARGING")) { ffStrbufAppendS(&battery->status, "Discharging"); + } } ffStrbufTrimRight(&battery->status, ' '); ffStrbufTrimRight(&battery->status, ','); - if(options->temp) + if (options->temp) { battery->temperature = yyjson_get_num(yyjson_obj_get(root, "temperature")); + } return NULL; } -static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) -{ +static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buf, (char* []) { - "/system/bin/dumpsys", - "battery", - NULL, - }) != NULL || buf.length == 0) + if (ffProcessAppendStdOut(&buf, (char*[]) { + "/system/bin/dumpsys", + "battery", + NULL, + }) != NULL || + buf.length == 0) { return "Executing `/system/bin/dumpsys battery` failed"; // Only works in `adb shell`, or when rooted + } - if (!ffStrbufStartsWithS(&buf, "Current Battery Service state:\n")) + if (!ffStrbufStartsWithS(&buf, "Current Battery Service state:\n")) { return "Invalid `/system/bin/dumpsys battery` result"; + } const char* start = buf.chars + strlen("Current Battery Service state:\n"); FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate(); - if (!ffParsePropLines(start, "present: ", &temp) || !ffStrbufEqualS(&temp, "true")) + if (!ffParsePropLines(start, "present: ", &temp) || !ffStrbufEqualS(&temp, "true")) { return NULL; + } ffStrbufClear(&temp); FFBatteryResult* battery = ffListAdd(results); @@ -104,45 +106,50 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) ffStrbufInit(&battery->serial); ffStrbufInit(&battery->manufactureDate); - if (ffParsePropLines(start, "AC powered: ", &temp) && ffStrbufEqualS(&temp, "true")) + if (ffParsePropLines(start, "AC powered: ", &temp) && ffStrbufEqualS(&temp, "true")) { ffStrbufAppendS(&battery->status, "AC powered"); + } ffStrbufClear(&temp); - if (ffParsePropLines(start, "USB powered: ", &temp) && ffStrbufEqualS(&temp, "true")) - { - if (battery->status.length) ffStrbufAppendS(&battery->status, ", "); + if (ffParsePropLines(start, "USB powered: ", &temp) && ffStrbufEqualS(&temp, "true")) { + if (battery->status.length) { + ffStrbufAppendS(&battery->status, ", "); + } ffStrbufAppendS(&battery->status, "USB powered"); } ffStrbufClear(&temp); - if (ffParsePropLines(start, "Wireless powered: ", &temp) && ffStrbufEqualS(&temp, "true")) - { - if (battery->status.length) ffStrbufAppendS(&battery->status, ", "); + if (ffParsePropLines(start, "Wireless powered: ", &temp) && ffStrbufEqualS(&temp, "true")) { + if (battery->status.length) { + ffStrbufAppendS(&battery->status, ", "); + } ffStrbufAppendS(&battery->status, "Wireless powered"); } ffStrbufClear(&temp); { double level = 0, scale = 0; - if (ffParsePropLines(start, "level: ", &temp)) + if (ffParsePropLines(start, "level: ", &temp)) { level = ffStrbufToDouble(&temp, -DBL_MAX); + } ffStrbufClear(&temp); - if (ffParsePropLines(start, "scale: ", &temp)) + if (ffParsePropLines(start, "scale: ", &temp)) { scale = ffStrbufToDouble(&temp, -DBL_MAX); + } ffStrbufClear(&temp); - if (level > 0 && scale > 0) + if (level > 0 && scale > 0) { battery->capacity = level * 100 / scale; + } } - if(options->temp) - { - if (ffParsePropLines(start, "temperature: ", &temp)) - { + if (options->temp) { + if (ffParsePropLines(start, "temperature: ", &temp)) { battery->temperature = ffStrbufToDouble(&temp, FF_BATTERY_TEMP_UNSET); - if (battery->temperature != 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); } @@ -152,10 +159,10 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) return NULL; } -const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) -{ +const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { const char* error = parseTermuxApi(options, results); - if (error && parseDumpsys(options, results) == NULL) + if (error && parseDumpsys(options, results) == NULL) { return NULL; + } return error; } diff --git a/src/detection/battery/battery_apple.c b/src/detection/battery/battery_apple.c index d4935de2f..a6da4612f 100644 --- a/src/detection/battery/battery_apple.c +++ b/src/detection/battery/battery_apple.c @@ -6,27 +6,29 @@ #include #include -const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) -{ +const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { FF_IOOBJECT_AUTO_RELEASE io_iterator_t iterator = IO_OBJECT_NULL; - if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("AppleSmartBattery"), &iterator) != kIOReturnSuccess) + if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("AppleSmartBattery"), &iterator) != kIOReturnSuccess) { return "IOServiceGetMatchingServices() failed"; + } io_registry_entry_t registryEntry; - while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) - { + while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryBattery = registryEntry; FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef properties = NULL; - if (IORegistryEntryCreateCFProperties(entryBattery, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) + if (IORegistryEntryCreateCFProperties(entryBattery, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { continue; + } int currentCapacity, maxCapacity; - if (ffCfDictGetInt(properties, CFSTR(kIOPMPSMaxCapacityKey), &maxCapacity) != NULL || maxCapacity <= 0) + if (ffCfDictGetInt(properties, CFSTR(kIOPMPSMaxCapacityKey), &maxCapacity) != NULL || maxCapacity <= 0) { continue; + } - if (ffCfDictGetInt(properties, CFSTR(kIOPMPSCurrentCapacityKey), ¤tCapacity) != NULL || currentCapacity <= 0) + if (ffCfDictGetInt(properties, CFSTR(kIOPMPSCurrentCapacityKey), ¤tCapacity) != NULL || currentCapacity <= 0) { continue; + } bool boolValue; @@ -44,13 +46,14 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) ffCfDictGetString(properties, CFSTR(kIOPMPSSerialKey), &battery->serial); ffCfDictGetString(properties, CFSTR(kIOPMPSManufacturerKey), &battery->manufacturer); - if (!ffCfDictGetBool(properties, CFSTR("built-in"), &boolValue) && boolValue) - { - if (!battery->manufacturer.length) + if (!ffCfDictGetBool(properties, CFSTR("built-in"), &boolValue) && boolValue) { + if (!battery->manufacturer.length) { ffStrbufAppendS(&battery->manufacturer, "Apple Inc."); + } ffStrbufAppendS(&battery->technology, "Lithium"); - if (!battery->modelName.length) + if (!battery->modelName.length) { ffStrbufAppendS(&battery->modelName, "Built-in"); + } } int32_t cycleCount = 0; @@ -58,43 +61,39 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) battery->cycleCount = cycleCount < 0 ? 0 : (uint32_t) cycleCount; battery->timeRemaining = -1; - if (ffCfDictGetBool(properties, CFSTR(kIOPMPSExternalConnectedKey), &boolValue) == NULL) - { - if (boolValue) + if (ffCfDictGetBool(properties, CFSTR(kIOPMPSExternalConnectedKey), &boolValue) == NULL) { + if (boolValue) { ffStrbufAppendS(&battery->status, "AC connected, "); - else - { + } else { ffStrbufAppendS(&battery->status, "Discharging, "); ffCfDictGetInt(properties, CFSTR("AvgTimeToEmpty"), &battery->timeRemaining); // in minutes - if (battery->timeRemaining < 0 || battery->timeRemaining >= 0xFFFF) + if (battery->timeRemaining < 0 || battery->timeRemaining >= 0xFFFF) { battery->timeRemaining = -1; - else + } else { battery->timeRemaining *= 60; + } } } - if (ffCfDictGetBool(properties, CFSTR(kIOPMPSIsChargingKey), &boolValue) == NULL && boolValue) + if (ffCfDictGetBool(properties, CFSTR(kIOPMPSIsChargingKey), &boolValue) == NULL && boolValue) { ffStrbufAppendS(&battery->status, "Charging, "); - if (ffCfDictGetBool(properties, CFSTR(kIOPMPSAtCriticalLevelKey), &boolValue) == NULL && boolValue) + } + if (ffCfDictGetBool(properties, CFSTR(kIOPMPSAtCriticalLevelKey), &boolValue) == NULL && boolValue) { ffStrbufAppendS(&battery->status, "Critical, "); + } ffStrbufTrimRight(&battery->status, ' '); ffStrbufTrimRight(&battery->status, ','); int sbdsManufactureDate = 0; - if (ffCfDictGetInt(properties, CFSTR(kIOPMPSManufactureDateKey), &sbdsManufactureDate) == NULL) - { + if (ffCfDictGetInt(properties, CFSTR(kIOPMPSManufactureDateKey), &sbdsManufactureDate) == NULL) { int day = sbdsManufactureDate & 0b11111; int month = (sbdsManufactureDate >> 5) & 0b1111; int year = (sbdsManufactureDate >> 9) + 1800; ffStrbufSetF(&battery->manufactureDate, "%.4d-%.2d-%.2d", year, month, day); - } - else - { + } else { CFDictionaryRef batteryData; - if (ffCfDictGetDict(properties, CFSTR("BatteryData"), &batteryData) == NULL) - { + if (ffCfDictGetDict(properties, CFSTR("BatteryData"), &batteryData) == NULL) { char manufactureDate[sizeof(uint64_t)]; - if (ffCfDictGetInt64(batteryData, CFSTR(kIOPMPSManufactureDateKey), (int64_t*) manufactureDate) == NULL) - { + if (ffCfDictGetInt64(batteryData, CFSTR(kIOPMPSManufactureDateKey), (int64_t*) manufactureDate) == NULL) { // https://github.com/AsahiLinux/linux/blob/b5c05cbffb0488c7618106926d522cc3b43d93d5/drivers/power/supply/macsmc_power.c#L410-L419 int year = (manufactureDate[0] - '0') * 10 + (manufactureDate[1] - '0') + 2000 - 8; int month = (manufactureDate[2] - '0') * 10 + (manufactureDate[3] - '0'); @@ -104,13 +103,13 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) } } - if (options->temp) - { + if (options->temp) { int64_t temp; - if (!ffCfDictGetInt64(properties, CFSTR(kIOPMPSBatteryTemperatureKey), &temp)) + if (!ffCfDictGetInt64(properties, CFSTR(kIOPMPSBatteryTemperatureKey), &temp)) { battery->temperature = (double) temp / 10 - 273.15; - else + } else { ffDetectSmcTemps(FF_TEMP_BATTERY, &battery->temperature); + } } } diff --git a/src/detection/battery/battery_bsd.c b/src/detection/battery/battery_bsd.c index d8ccd97f6..a3701a320 100644 --- a/src/detection/battery/battery_bsd.c +++ b/src/detection/battery/battery_bsd.c @@ -8,29 +8,31 @@ #include #include -const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) -{ - //https://www.freebsd.org/cgi/man.cgi?acpi_battery(4) - //https://gitlab.xfce.org/panel-plugins/xfce4-battery-plugin/-/blob/master/panel-plugin/libacpi.c +const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) { + // https://www.freebsd.org/cgi/man.cgi?acpi_battery(4) + // https://gitlab.xfce.org/panel-plugins/xfce4-battery-plugin/-/blob/master/panel-plugin/libacpi.c int units = ffSysctlGetInt("hw.acpi.battery.units", -100); - if (units < 0) + if (units < 0) { return "sysctlbyname(\"hw.acpi.battery.units\") failed"; + } - if(units == 0) + if (units == 0) { return NULL; + } FF_AUTO_CLOSE_FD int acpifd = open("/dev/acpi", O_RDONLY | O_CLOEXEC); - if(acpifd < 0) + if (acpifd < 0) { return "open(\"/dev/acpi\", O_RDONLY | O_CLOEXEC) failed"; + } - for(int i = 0; i < units; ++i) - { + for (int i = 0; i < units; ++i) { union acpi_battery_ioctl_arg battio; battio.unit = i; - if(ioctl(acpifd, ACPIIO_BATT_GET_BATTINFO, &battio) < 0 || (battio.battinfo.state == ACPI_BATT_STAT_NOT_PRESENT)) + if (ioctl(acpifd, ACPIIO_BATT_GET_BATTINFO, &battio) < 0 || (battio.battinfo.state == ACPI_BATT_STAT_NOT_PRESENT)) { continue; + } FFBatteryResult* battery = ffListAdd(results); battery->temperature = FF_BATTERY_TEMP_UNSET; @@ -42,54 +44,49 @@ const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* r ffStrbufInit(&battery->serial); ffStrbufInit(&battery->manufactureDate); battery->timeRemaining = -1; - if (battio.battinfo.min > 0) + if (battio.battinfo.min > 0) { battery->timeRemaining = battio.battinfo.min * 60; - battery->capacity = battio.battinfo.cap; - if(battio.battinfo.state == ACPI_BATT_STAT_INVALID) - { - ffStrbufAppendS(&battery->status, "Unknown, "); } - else - { - if(battio.battinfo.state & ACPI_BATT_STAT_DISCHARG) + battery->capacity = battio.battinfo.cap; + if (battio.battinfo.state == ACPI_BATT_STAT_INVALID) { + ffStrbufAppendS(&battery->status, "Unknown, "); + } else { + if (battio.battinfo.state & ACPI_BATT_STAT_DISCHARG) { ffStrbufAppendS(&battery->status, "Discharging, "); - else if(battio.battinfo.state & ACPI_BATT_STAT_CHARGING) + } else if (battio.battinfo.state & ACPI_BATT_STAT_CHARGING) { ffStrbufAppendS(&battery->status, "Charging, "); - if(battio.battinfo.state & ACPI_BATT_STAT_CRITICAL) + } + if (battio.battinfo.state & ACPI_BATT_STAT_CRITICAL) { ffStrbufAppendS(&battery->status, "Critical, "); + } } int acadStatus; - if (ioctl(acpifd, ACPIIO_ACAD_GET_STATUS, &acadStatus) >= 0 && acadStatus) - { + if (ioctl(acpifd, ACPIIO_ACAD_GET_STATUS, &acadStatus) >= 0 && acadStatus) { ffStrbufAppendS(&battery->status, "AC Connected"); - } - else - { + } else { ffStrbufTrimRight(&battery->status, ' '); ffStrbufTrimRight(&battery->status, ','); } - #ifdef ACPIIO_BATT_GET_BIX +#ifdef ACPIIO_BATT_GET_BIX battio.unit = i; - if (ioctl(acpifd, ACPIIO_BATT_GET_BIX, &battio) >= 0) - { + if (ioctl(acpifd, ACPIIO_BATT_GET_BIX, &battio) >= 0) { ffStrbufAppendS(&battery->manufacturer, battio.bix.oeminfo); ffStrbufAppendS(&battery->modelName, battio.bix.model); ffStrbufAppendS(&battery->technology, battio.bix.type); ffStrbufAppendS(&battery->serial, battio.bix.serial); battery->cycleCount = battio.bix.cycles; } - #elif defined(ACPIIO_BATT_GET_BIF) +#elif defined(ACPIIO_BATT_GET_BIF) battio.unit = i; - if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) >= 0) - { + if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) >= 0) { ffStrbufAppendS(&battery->manufacturer, battio.bif.oeminfo); ffStrbufAppendS(&battery->modelName, battio.bif.model); ffStrbufAppendS(&battery->technology, battio.bif.type); ffStrbufAppendS(&battery->serial, battio.bif.serial); } - #endif +#endif } return NULL; } diff --git a/src/detection/battery/battery_haiku.c b/src/detection/battery/battery_haiku.c index 54d5978ee..82d6bec1d 100644 --- a/src/detection/battery/battery_haiku.c +++ b/src/detection/battery/battery_haiku.c @@ -6,22 +6,26 @@ #include #include -const char* parseBattery(int dfd, const char* battId, FFlist* results) -{ +const char* parseBattery(int dfd, const char* battId, FFlist* results) { FF_AUTO_CLOSE_FD int fd = openat(dfd, battId, O_RDWR); - if (fd < 0) return "openat() failed"; + if (fd < 0) { + return "openat() failed"; + } acpi_battery_info basic = {}; - if (ioctl(fd, GET_BATTERY_INFO, &basic, sizeof(basic)) != 0) + if (ioctl(fd, GET_BATTERY_INFO, &basic, sizeof(basic)) != 0) { return "ioctl(GET_BATTERY_INFO) failed"; + } acpi_extended_battery_info extended = {}; - if (ioctl(fd, GET_EXTENDED_BATTERY_INFO, &extended, sizeof(extended)) != 0) + if (ioctl(fd, GET_EXTENDED_BATTERY_INFO, &extended, sizeof(extended)) != 0) { return "ioctl(GET_EXTENDED_BATTERY_INFO) failed"; + } - if (extended.last_full_charge == (uint32)-1) + if (extended.last_full_charge == (uint32) -1) { return "Skipped"; + } - FFBatteryResult* battery = (FFBatteryResult*)ffListAdd(results); + FFBatteryResult* battery = (FFBatteryResult*) ffListAdd(results); ffStrbufInitS(&battery->modelName, extended.model_number); ffStrbufInitS(&battery->manufacturer, extended.oem_info); ffStrbufInit(&battery->manufactureDate); @@ -33,29 +37,35 @@ const char* parseBattery(int dfd, const char* battId, FFlist* results) battery->timeRemaining = -1; battery->capacity = (double) basic.capacity * 100. / (double) extended.last_full_charge; - if (basic.state & BATTERY_DISCHARGING) + if (basic.state & BATTERY_DISCHARGING) { ffStrbufAppendS(&battery->status, "Discharging, "); - if (basic.state & BATTERY_CHARGING) + } + if (basic.state & BATTERY_CHARGING) { ffStrbufAppendS(&battery->status, "Charging, "); - if (basic.state & BATTERY_CRITICAL_STATE) + } + if (basic.state & BATTERY_CRITICAL_STATE) { ffStrbufAppendS(&battery->status, "Critical, "); - if (basic.state & BATTERY_NOT_CHARGING) + } + if (basic.state & BATTERY_NOT_CHARGING) { ffStrbufAppendS(&battery->status, "AC Connected, "); + } ffStrbufTrimRight(&battery->status, ' '); ffStrbufTrimRight(&battery->status, ','); return NULL; } -const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) -{ +const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) { FF_AUTO_CLOSE_DIR DIR* dir = opendir("/dev/power/acpi_battery/"); - if (!dir) return "opendir(/dev/power/acpi_battery) failed"; + if (!dir) { + return "opendir(/dev/power/acpi_battery) failed"; + } struct dirent* entry; - while ((entry = readdir(dir))) - { - if (entry->d_name[0] == '.') continue; + while ((entry = readdir(dir))) { + if (entry->d_name[0] == '.') { + continue; + } parseBattery(dirfd(dir), entry->d_name, results); } diff --git a/src/detection/battery/battery_linux.c b/src/detection/battery/battery_linux.c index d750dc61e..fa8bb1bab 100644 --- a/src/detection/battery/battery_linux.c +++ b/src/detection/battery/battery_linux.c @@ -8,142 +8,143 @@ // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-power -static bool checkAc(const char* id, FFstrbuf* tmpBuffer) -{ - if (ffStrStartsWith(id, "BAT")) +static bool checkAc(const char* id, FFstrbuf* tmpBuffer) { + if (ffStrStartsWith(id, "BAT")) { ffStrbufSetS(tmpBuffer, "/sys/class/power_supply/ADP1/online"); - else if (ffStrStartsWith(id, "macsmc-battery")) + } else if (ffStrStartsWith(id, "macsmc-battery")) { ffStrbufSetS(tmpBuffer, "/sys/class/power_supply/macsmc-ac/online"); - else + } else { ffStrbufClear(tmpBuffer); + } char online = '\0'; return ffReadFileData(tmpBuffer->chars, 1, &online) == 1 && online == '1'; } -static void parseBattery(int dfd, const char* id, FFBatteryOptions* options, FFlist* results) -{ +static void parseBattery(int dfd, const char* id, FFBatteryOptions* options, FFlist* results) { FF_STRBUF_AUTO_DESTROY tmpBuffer = ffStrbufCreate(); // type must exist and be "Battery" - if (!ffReadFileBufferRelative(dfd, "type", &tmpBuffer)) + if (!ffReadFileBufferRelative(dfd, "type", &tmpBuffer)) { return; + } ffStrbufTrimRightSpace(&tmpBuffer); - if(!ffStrbufIgnCaseEqualS(&tmpBuffer, "Battery")) + if (!ffStrbufIgnCaseEqualS(&tmpBuffer, "Battery")) { return; + } // scope may not exist or must not be "Device" - if (ffReadFileBufferRelative(dfd, "scope", &tmpBuffer)) + if (ffReadFileBufferRelative(dfd, "scope", &tmpBuffer)) { ffStrbufTrimRightSpace(&tmpBuffer); + } - if(ffStrbufIgnCaseEqualS(&tmpBuffer, "Device")) + if (ffStrbufIgnCaseEqualS(&tmpBuffer, "Device")) { return; + } // capacity must exist and be not empty // This is expensive in my laptop - if (!ffReadFileBufferRelative(dfd, "capacity", &tmpBuffer)) + if (!ffReadFileBufferRelative(dfd, "capacity", &tmpBuffer)) { return; + } FFBatteryResult* result = ffListAdd(results); result->capacity = ffStrbufToDouble(&tmpBuffer, 0); - //At this point, we have a battery. Try to get as much values as possible. + // At this point, we have a battery. Try to get as much values as possible. ffStrbufInit(&result->manufacturer); - if (ffReadFileBufferRelative(dfd, "manufacturer", &result->manufacturer)) + if (ffReadFileBufferRelative(dfd, "manufacturer", &result->manufacturer)) { ffStrbufTrimRightSpace(&result->manufacturer); - else if (ffStrEquals(id, "macsmc-battery")) // asahi + } else if (ffStrEquals(id, "macsmc-battery")) { // asahi ffStrbufSetStatic(&result->manufacturer, "Apple Inc."); + } ffStrbufInit(&result->modelName); - if (ffReadFileBufferRelative(dfd, "model_name", &result->modelName)) + if (ffReadFileBufferRelative(dfd, "model_name", &result->modelName)) { ffStrbufTrimRightSpace(&result->modelName); + } ffStrbufInit(&result->technology); - if (ffReadFileBufferRelative(dfd, "technology", &result->technology)) + if (ffReadFileBufferRelative(dfd, "technology", &result->technology)) { ffStrbufTrimRightSpace(&result->technology); + } ffStrbufInit(&result->status); - if (ffReadFileBufferRelative(dfd, "status", &result->status)) + if (ffReadFileBufferRelative(dfd, "status", &result->status)) { ffStrbufTrimRightSpace(&result->status); + } // Unknown, Charging, Discharging, Not charging, Full result->timeRemaining = -1; - if (ffStrbufEqualS(&result->status, "Discharging")) - { - if (ffReadFileBufferRelative(dfd, "time_to_empty_now", &tmpBuffer)) + if (ffStrbufEqualS(&result->status, "Discharging")) { + if (ffReadFileBufferRelative(dfd, "time_to_empty_now", &tmpBuffer)) { result->timeRemaining = (int32_t) ffStrbufToSInt(&tmpBuffer, 0); - else - { - if (ffReadFileBufferRelative(dfd, "charge_now", &tmpBuffer)) - { + } else { + if (ffReadFileBufferRelative(dfd, "charge_now", &tmpBuffer)) { int64_t chargeNow = ffStrbufToSInt(&tmpBuffer, 0); - if (chargeNow > 0) - { - if (ffReadFileBufferRelative(dfd, "current_now", &tmpBuffer)) - { + if (chargeNow > 0) { + if (ffReadFileBufferRelative(dfd, "current_now", &tmpBuffer)) { int64_t currentNow = ffStrbufToSInt(&tmpBuffer, INT64_MIN); - if (currentNow < 0) currentNow = -currentNow; - if (currentNow > 0) + if (currentNow < 0) { + currentNow = -currentNow; + } + if (currentNow > 0) { result->timeRemaining = (int32_t) ((chargeNow * 3600) / currentNow); + } } } } } - if (checkAc(id, &tmpBuffer)) + if (checkAc(id, &tmpBuffer)) { ffStrbufAppendS(&result->status, ", AC Connected"); - } - else if (ffStrbufEqualS(&result->status, "Not charging") || ffStrbufEqualS(&result->status, "Full")) + } + } else if (ffStrbufEqualS(&result->status, "Not charging") || ffStrbufEqualS(&result->status, "Full")) { ffStrbufSetStatic(&result->status, "AC Connected"); - else if (ffStrbufEqualS(&result->status, "Charging")) + } else if (ffStrbufEqualS(&result->status, "Charging")) { ffStrbufAppendS(&result->status, ", AC Connected"); - else if (ffStrbufEqualS(&result->status, "Unknown")) - { + } else if (ffStrbufEqualS(&result->status, "Unknown")) { ffStrbufClear(&result->status); - if (checkAc(id, &tmpBuffer)) + if (checkAc(id, &tmpBuffer)) { ffStrbufAppendS(&result->status, "AC Connected"); + } } - if (ffReadFileBufferRelative(dfd, "capacity_level", &tmpBuffer)) - { + if (ffReadFileBufferRelative(dfd, "capacity_level", &tmpBuffer)) { ffStrbufTrimRightSpace(&tmpBuffer); - if (ffStrbufEqualS(&tmpBuffer, "Critical")) - { - if (result->status.length) + if (ffStrbufEqualS(&tmpBuffer, "Critical")) { + if (result->status.length) { ffStrbufAppendS(&result->status, ", Critical"); - else + } else { ffStrbufSetStatic(&result->status, "Critical"); + } } } ffStrbufInit(&result->serial); - if (ffReadFileBufferRelative(dfd, "serial_number", &result->serial)) + if (ffReadFileBufferRelative(dfd, "serial_number", &result->serial)) { ffStrbufTrimRightSpace(&result->serial); + } - if (ffReadFileBufferRelative(dfd, "cycle_count", &tmpBuffer)) - { + if (ffReadFileBufferRelative(dfd, "cycle_count", &tmpBuffer)) { int64_t cycleCount = ffStrbufToSInt(&tmpBuffer, 0); result->cycleCount = cycleCount < 0 || cycleCount > UINT32_MAX ? 0 : (uint32_t) cycleCount; } ffStrbufInit(&result->manufactureDate); - if (ffReadFileBufferRelative(dfd, "manufacture_year", &tmpBuffer)) - { + if (ffReadFileBufferRelative(dfd, "manufacture_year", &tmpBuffer)) { int year = (int) ffStrbufToSInt(&tmpBuffer, 0); - if (year > 0) - { - if (ffReadFileBufferRelative(dfd, "manufacture_month", &tmpBuffer)) - { + if (year > 0) { + if (ffReadFileBufferRelative(dfd, "manufacture_month", &tmpBuffer)) { int month = (int) ffStrbufToSInt(&tmpBuffer, 0); - if (month > 0) - { - if (ffReadFileBufferRelative(dfd, "manufacture_day", &tmpBuffer)) - { + if (month > 0) { + if (ffReadFileBufferRelative(dfd, "manufacture_day", &tmpBuffer)) { int day = (int) ffStrbufToSInt(&tmpBuffer, 0); - if (day > 0) + if (day > 0) { ffStrbufSetF(&result->manufactureDate, "%.4d-%.2d-%.2d", year, month, day); + } } } } @@ -151,31 +152,32 @@ static void parseBattery(int dfd, const char* id, FFBatteryOptions* options, FFl } result->temperature = FF_BATTERY_TEMP_UNSET; - if (options->temp) - { - if (ffReadFileBufferRelative(dfd, "temp", &tmpBuffer)) - { + if (options->temp) { + if (ffReadFileBufferRelative(dfd, "temp", &tmpBuffer)) { result->temperature = ffStrbufToDouble(&tmpBuffer, FF_BATTERY_TEMP_UNSET); - if (result->temperature != FF_BATTERY_TEMP_UNSET) + if (result->temperature != FF_BATTERY_TEMP_UNSET) { result->temperature /= 10; + } } } } -const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) -{ +const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/power_supply/"); - if(dirp == NULL) + if (dirp == NULL) { return "opendir(\"/sys/class/power_supply/\") == NULL"; + } struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } FF_AUTO_CLOSE_FD int dfd = openat(dirfd(dirp), entry->d_name, O_RDONLY | O_CLOEXEC | O_PATH | O_DIRECTORY); - if (dfd > 0) parseBattery(dfd, entry->d_name, options, results); + if (dfd > 0) { + parseBattery(dfd, entry->d_name, options, results); + } } return NULL; diff --git a/src/detection/battery/battery_nbsd.c b/src/detection/battery/battery_nbsd.c index 37ef64966..1c37f93fa 100644 --- a/src/detection/battery/battery_nbsd.c +++ b/src/detection/battery/battery_nbsd.c @@ -14,67 +14,66 @@ #include #include -const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) -{ +const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) { FF_AUTO_CLOSE_FD int fd = open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC); - if (fd < 0) return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed"; + if (fd < 0) { + return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed"; + } prop_dictionary_t root = NULL; - if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) + if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) { return "prop_dictionary_recv_ioctl(ENVSYS_GETDICTIONARY) failed"; + } bool acConnected = false; { prop_array_t acad = prop_dictionary_get(root, "acpiacad0"); - if (acad) - { + if (acad) { prop_dictionary_t dict = prop_array_get(acad, 0); prop_dictionary_get_uint8(dict, "cur-value", (uint8_t*) &acConnected); } } prop_object_iterator_t itKey = prop_dictionary_iterator(root); - for (prop_dictionary_keysym_t key; (key = prop_object_iterator_next(itKey)) != NULL; ) - { - if (!ffStrStartsWith(prop_dictionary_keysym_value(key), "acpibat")) continue; + for (prop_dictionary_keysym_t key; (key = prop_object_iterator_next(itKey)) != NULL;) { + if (!ffStrStartsWith(prop_dictionary_keysym_value(key), "acpibat")) { + continue; + } prop_array_t bat = prop_dictionary_get_keysym(root, key); uint32_t max = 0, curr = 0, dischargeRate = 0; bool charging = false, critical = false; prop_object_iterator_t iter = prop_array_iterator(bat); - for (prop_dictionary_t dict; (dict = prop_object_iterator_next(iter)) != NULL;) - { - if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) + for (prop_dictionary_t dict; (dict = prop_object_iterator_next(iter)) != NULL;) { + if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) { continue; + } const char* desc = NULL; - if (!prop_dictionary_get_string(dict, "description", &desc)) + if (!prop_dictionary_get_string(dict, "description", &desc)) { continue; + } - if (ffStrEquals(desc, "present")) - { + if (ffStrEquals(desc, "present")) { int value = 0; - if (prop_dictionary_get_int(dict, "cur-value", &value) && value == 0) + if (prop_dictionary_get_int(dict, "cur-value", &value) && value == 0) { continue; - } - else if (ffStrEquals(desc, "charging")) - { + } + } else if (ffStrEquals(desc, "charging")) { prop_dictionary_get_uint8(dict, "cur-value", (uint8_t*) &charging); - } - else if (ffStrEquals(desc, "charge")) - { + } else if (ffStrEquals(desc, "charge")) { prop_dictionary_get_uint32(dict, "max-value", &max); prop_dictionary_get_uint32(dict, "cur-value", &curr); const char* state = NULL; - if (prop_dictionary_get_string(dict, "state", &state) && ffStrEquals(state, "critical")) + if (prop_dictionary_get_string(dict, "state", &state) && ffStrEquals(state, "critical")) { critical = true; - } - else if (ffStrEquals(desc, "discharge rate")) + } + } else if (ffStrEquals(desc, "discharge rate")) { prop_dictionary_get_uint(dict, "cur-value", &dischargeRate); + } } - if (max > 0) - { + if (max > 0) { FFBatteryResult* battery = ffListAdd(results); battery->temperature = FF_BATTERY_TEMP_UNSET; battery->cycleCount = 0; @@ -87,17 +86,18 @@ const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* r battery->timeRemaining = -1; battery->capacity = (double) curr / (double) max * 100.; - if (charging) + if (charging) { ffStrbufAppendS(&battery->status, "Charging, "); - else if (dischargeRate) - { + } else if (dischargeRate) { ffStrbufAppendS(&battery->status, "Discharging, "); - battery->timeRemaining = (int32_t)((double)curr / dischargeRate * 3600); + battery->timeRemaining = (int32_t) ((double) curr / dischargeRate * 3600); } - if (critical) + if (critical) { ffStrbufAppendS(&battery->status, "Critical, "); - if (acConnected) + } + if (acConnected) { ffStrbufAppendS(&battery->status, "AC Connected"); + } ffStrbufTrimRight(&battery->status, ' '); ffStrbufTrimRight(&battery->status, ','); } diff --git a/src/detection/battery/battery_nosupport.c b/src/detection/battery/battery_nosupport.c index 02f084748..efd0f736f 100644 --- a/src/detection/battery/battery_nosupport.c +++ b/src/detection/battery/battery_nosupport.c @@ -1,8 +1,7 @@ #include "fastfetch.h" #include "battery.h" -const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) -{ +const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { FF_UNUSED(options, results) return "Not supported on this platform"; } diff --git a/src/detection/battery/battery_obsd.c b/src/detection/battery/battery_obsd.c index 2cd5c9e4a..e051caf82 100644 --- a/src/detection/battery/battery_obsd.c +++ b/src/detection/battery/battery_obsd.c @@ -6,19 +6,22 @@ #include #include -const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* result) -{ +const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* result) { FF_AUTO_CLOSE_FD int devfd = open("/dev/apm", O_RDONLY | O_CLOEXEC); - if (devfd < 0) return "open(dev/apm, O_RDONLY | O_CLOEXEC) failed"; + if (devfd < 0) { + return "open(dev/apm, O_RDONLY | O_CLOEXEC) failed"; + } struct apm_power_info info = {}; - if (ioctl(devfd, APM_IOC_GETPOWER, &info) < 0) + if (ioctl(devfd, APM_IOC_GETPOWER, &info) < 0) { return "ioctl(APM_IOC_GETPOWER) failed"; + } - if (info.battery_state == APM_BATTERY_ABSENT) + if (info.battery_state == APM_BATTERY_ABSENT) { return NULL; + } FFBatteryResult* battery = (FFBatteryResult*) ffListAdd(result); battery->temperature = FF_BATTERY_TEMP_UNSET; @@ -32,19 +35,19 @@ const char* ffDetectBattery(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* r ffStrbufInit(&battery->serial); ffStrbufInit(&battery->manufactureDate); - if (info.ac_state == APM_AC_ON) + if (info.ac_state == APM_AC_ON) { ffStrbufAppendS(&battery->status, "AC Connected"); - else if (info.ac_state == APM_AC_BACKUP) + } else if (info.ac_state == APM_AC_BACKUP) { ffStrbufAppendS(&battery->status, "Backup In Use"); - else if (info.ac_state == APM_AC_OFF) - { + } else if (info.ac_state == APM_AC_OFF) { battery->timeRemaining = (int) info.minutes_left * 60; ffStrbufAppendS(&battery->status, "Discharging"); } - if (info.battery_state == APM_BATT_CRITICAL || info.battery_state == APM_BATT_CHARGING) - { - if (battery->status.length) ffStrbufAppendS(&battery->status, ", "); + if (info.battery_state == APM_BATT_CRITICAL || info.battery_state == APM_BATT_CHARGING) { + if (battery->status.length) { + ffStrbufAppendS(&battery->status, ", "); + } ffStrbufAppendS(&battery->status, info.battery_state == APM_BATT_CRITICAL ? "Critical" : "Charging"); } diff --git a/src/detection/battery/battery_windows.c b/src/detection/battery/battery_windows.c index 319688511..308e73e18 100644 --- a/src/detection/battery/battery_windows.c +++ b/src/detection/battery/battery_windows.c @@ -12,129 +12,145 @@ #include #include -static const char* detectWithCmApi(FFBatteryOptions* options, FFlist* results) -{ - //https://learn.microsoft.com/en-us/windows-hardware/drivers/install/using-device-interfaces +static const char* detectWithCmApi(FFBatteryOptions* options, FFlist* results) { + // https://learn.microsoft.com/en-us/windows-hardware/drivers/install/using-device-interfaces ULONG cchDeviceInterfaces = 0; - CONFIGRET cr = CM_Get_Device_Interface_List_SizeW(&cchDeviceInterfaces, (LPGUID)&GUID_DEVCLASS_BATTERY, NULL, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); - if (cr != CR_SUCCESS) + CONFIGRET cr = CM_Get_Device_Interface_List_SizeW(&cchDeviceInterfaces, (LPGUID) &GUID_DEVCLASS_BATTERY, NULL, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + if (cr != CR_SUCCESS) { return "CM_Get_Device_Interface_List_SizeW() failed"; + } - if (cchDeviceInterfaces <= 1) + if (cchDeviceInterfaces <= 1) { return NULL; // Not found + } - wchar_t* FF_AUTO_FREE mszDeviceInterfaces = (wchar_t*)malloc(cchDeviceInterfaces * sizeof(wchar_t)); - cr = CM_Get_Device_Interface_ListW((LPGUID)&GUID_DEVCLASS_BATTERY, NULL, mszDeviceInterfaces, cchDeviceInterfaces, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); - if (cr != CR_SUCCESS) + wchar_t* FF_AUTO_FREE mszDeviceInterfaces = (wchar_t*) malloc(cchDeviceInterfaces * sizeof(wchar_t)); + cr = CM_Get_Device_Interface_ListW((LPGUID) &GUID_DEVCLASS_BATTERY, NULL, mszDeviceInterfaces, cchDeviceInterfaces, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + if (cr != CR_SUCCESS) { return "CM_Get_Device_Interface_ListW() failed"; + } - for (const wchar_t* pDeviceInterface = mszDeviceInterfaces; *pDeviceInterface; pDeviceInterface += wcslen(pDeviceInterface) + 1) - { + for (const wchar_t* pDeviceInterface = mszDeviceInterfaces; *pDeviceInterface; pDeviceInterface += wcslen(pDeviceInterface) + 1) { HANDLE FF_AUTO_CLOSE_FD hBattery = CreateFileW(pDeviceInterface, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if(hBattery == INVALID_HANDLE_VALUE) + if (hBattery == INVALID_HANDLE_VALUE) { continue; + } - BATTERY_QUERY_INFORMATION bqi = { .InformationLevel = BatteryInformation }; + BATTERY_QUERY_INFORMATION bqi = {.InformationLevel = BatteryInformation}; DWORD dwWait = 0; DWORD dwOut; - if(!DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_TAG, &dwWait, sizeof(dwWait), &bqi.BatteryTag, sizeof(bqi.BatteryTag), &dwOut, NULL) && bqi.BatteryTag) + if (!DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_TAG, &dwWait, sizeof(dwWait), &bqi.BatteryTag, sizeof(bqi.BatteryTag), &dwOut, NULL) && bqi.BatteryTag) { continue; + } BATTERY_INFORMATION bi = {0}; - if(!DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &bi, sizeof(bi), &dwOut, NULL)) + if (!DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &bi, sizeof(bi), &dwOut, NULL)) { continue; + } - if(!(bi.Capabilities & BATTERY_SYSTEM_BATTERY)) + if (!(bi.Capabilities & BATTERY_SYSTEM_BATTERY)) { continue; + } - FFBatteryResult* battery = (FFBatteryResult*)ffListAdd(results); + FFBatteryResult* battery = (FFBatteryResult*) ffListAdd(results); - if(memcmp(bi.Chemistry, "PbAc", 4) == 0) + if (memcmp(bi.Chemistry, "PbAc", 4) == 0) { ffStrbufInitStatic(&battery->technology, "Lead Acid"); - else if(memcmp(bi.Chemistry, "LION", 4) == 0 || memcmp(bi.Chemistry, "Li-I", 4) == 0) + } else if (memcmp(bi.Chemistry, "LION", 4) == 0 || memcmp(bi.Chemistry, "Li-I", 4) == 0) { ffStrbufInitStatic(&battery->technology, "Lithium Ion"); - else if(memcmp(bi.Chemistry, "NiCd", 4) == 0) + } else if (memcmp(bi.Chemistry, "NiCd", 4) == 0) { ffStrbufInitStatic(&battery->technology, "Nickel Cadmium"); - else if(memcmp(bi.Chemistry, "NiMH", 4) == 0) + } else if (memcmp(bi.Chemistry, "NiMH", 4) == 0) { ffStrbufInitStatic(&battery->technology, "Nickel Metal Hydride"); - else if(memcmp(bi.Chemistry, "NiZn", 4) == 0) + } else if (memcmp(bi.Chemistry, "NiZn", 4) == 0) { ffStrbufInitStatic(&battery->technology, "Nickel Zinc"); - else if(memcmp(bi.Chemistry, "RAM\0", 4) == 0) + } else if (memcmp(bi.Chemistry, "RAM\0", 4) == 0) { ffStrbufInitStatic(&battery->technology, "Rechargeable Alkaline-Manganese"); - else + } else { ffStrbufInitStatic(&battery->technology, "Unknown"); + } { ffStrbufInit(&battery->modelName); bqi.InformationLevel = BatteryDeviceName; wchar_t name[64]; - if(DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), name, sizeof(name), &dwOut, NULL)) + if (DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), name, sizeof(name), &dwOut, NULL)) { ffStrbufSetWS(&battery->modelName, name); + } } { ffStrbufInit(&battery->manufacturer); bqi.InformationLevel = BatteryManufactureName; wchar_t name[64]; - if(DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), name, sizeof(name), &dwOut, NULL)) + if (DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), name, sizeof(name), &dwOut, NULL)) { ffStrbufSetWS(&battery->manufacturer, name); + } } { ffStrbufInit(&battery->manufactureDate); bqi.InformationLevel = BatteryManufactureDate; BATTERY_MANUFACTURE_DATE date; - if(DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &date, sizeof(date), &dwOut, NULL)) + if (DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &date, sizeof(date), &dwOut, NULL)) { ffStrbufSetF(&battery->manufactureDate, "%.4d-%.2d-%.2d", date.Year < 1000 ? date.Year + 1900 : date.Year, date.Month, date.Day); + } } { ffStrbufInit(&battery->serial); bqi.InformationLevel = BatterySerialNumber; wchar_t name[64]; - if(DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), name, sizeof(name), &dwOut, NULL)) + if (DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), name, sizeof(name), &dwOut, NULL)) { ffStrbufSetWS(&battery->serial, name); + } } battery->cycleCount = bi.CycleCount; battery->temperature = FF_BATTERY_TEMP_UNSET; - if(options->temp) - { + if (options->temp) { bqi.InformationLevel = BatteryTemperature; ULONG temp; - if(DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &temp, sizeof(temp), &dwOut, NULL)) + if (DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &temp, sizeof(temp), &dwOut, NULL)) { battery->temperature = temp / 10.0 - 273.15; + } } { bqi.InformationLevel = BatteryEstimatedTime; ULONG time; - if(DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &time, sizeof(time), &dwOut, NULL)) + if (DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, &bqi, sizeof(bqi), &time, sizeof(time), &dwOut, NULL)) { battery->timeRemaining = time == BATTERY_UNKNOWN_TIME ? -1 : (int32_t) time; + } } { BATTERY_STATUS bs; - BATTERY_WAIT_STATUS bws = { .BatteryTag = bqi.BatteryTag }; - if(DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_STATUS, &bws, sizeof(bws), &bs, sizeof(bs), &dwOut, NULL) && bs.Capacity != BATTERY_UNKNOWN_CAPACITY && bi.FullChargedCapacity != 0) + BATTERY_WAIT_STATUS bws = {.BatteryTag = bqi.BatteryTag}; + if (DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_STATUS, &bws, sizeof(bws), &bs, sizeof(bs), &dwOut, NULL) && bs.Capacity != BATTERY_UNKNOWN_CAPACITY && bi.FullChargedCapacity != 0) { battery->capacity = bs.Capacity * 100.0 / bi.FullChargedCapacity; - else + } else { battery->capacity = 0; + } ffStrbufInit(&battery->status); - if(bs.PowerState & BATTERY_POWER_ON_LINE) + if (bs.PowerState & BATTERY_POWER_ON_LINE) { ffStrbufAppendS(&battery->status, "AC Connected, "); - if(bs.PowerState & BATTERY_DISCHARGING) + } + if (bs.PowerState & BATTERY_DISCHARGING) { ffStrbufAppendS(&battery->status, "Discharging, "); - if(bs.PowerState & BATTERY_CHARGING) + } + if (bs.PowerState & BATTERY_CHARGING) { ffStrbufAppendS(&battery->status, "Charging, "); - if(bs.PowerState & BATTERY_CRITICAL) + } + if (bs.PowerState & BATTERY_CRITICAL) { ffStrbufAppendS(&battery->status, "Critical, "); + } ffStrbufTrimRight(&battery->status, ' '); ffStrbufTrimRight(&battery->status, ','); } @@ -142,42 +158,42 @@ static const char* detectWithCmApi(FFBatteryOptions* options, FFlist* results) return NULL; } -typedef struct FFSmbiosPortableBattery -{ +typedef struct FFSmbiosPortableBattery { FFSmbiosHeader Header; // 2.1+ - uint8_t Location; // string - uint8_t Manufacturer; // string - uint8_t ManufactureDate; // string - uint8_t SerialNumber; // string - uint8_t DeviceName; // string - uint8_t DeviceChemistry; // enum - uint16_t DesignCapacity; // varies - uint16_t DesignVoltage; // varies - uint8_t SbdsVersionNumber; // string + uint8_t Location; // string + uint8_t Manufacturer; // string + uint8_t ManufactureDate; // string + uint8_t SerialNumber; // string + uint8_t DeviceName; // string + uint8_t DeviceChemistry; // enum + uint16_t DesignCapacity; // varies + uint16_t DesignVoltage; // varies + uint8_t SbdsVersionNumber; // string uint8_t MaximumErrorInBatteryData; // varies // 2.2+ - uint16_t SbdsSerialNumber; // varies - uint16_t SbdsManufactureDate; // varies - uint8_t SbdsDeviceChemistry; // string + uint16_t SbdsSerialNumber; // varies + uint16_t SbdsManufactureDate; // varies + uint8_t SbdsDeviceChemistry; // string uint8_t DesignCapacityMultiplier; // varies - uint16_t OEMSpecific; // varies + uint16_t OEMSpecific; // varies } __attribute__((__packed__)) FFSmbiosPortableBattery; static_assert(offsetof(FFSmbiosPortableBattery, OEMSpecific) == 0x16, "FFSmbiosPortableBattery: Wrong struct alignment"); -static const char* detectBySmbios(FFBatteryResult* battery) -{ +static const char* detectBySmbios(FFBatteryResult* battery) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosPortableBattery* data = (const FFSmbiosPortableBattery*) (*smbiosTable)[FF_SMBIOS_TYPE_PORTABLE_BATTERY]; - if (!data) + if (!data) { return "Portable battery section is not found in SMBIOS data"; + } const char* strings = (const char*) data + data->Header.Length; @@ -186,50 +202,57 @@ static const char* detectBySmbios(FFBatteryResult* battery) ffStrbufSetStatic(&battery->manufacturer, ffSmbiosLocateString(strings, data->Manufacturer)); ffCleanUpSmbiosValue(&battery->manufacturer); - if (data->ManufactureDate) - { + if (data->ManufactureDate) { ffStrbufSetStatic(&battery->manufactureDate, ffSmbiosLocateString(strings, data->ManufactureDate)); ffCleanUpSmbiosValue(&battery->manufactureDate); - } - else if (data->Header.Length > offsetof(FFSmbiosPortableBattery, SbdsManufactureDate)) - { + } else if (data->Header.Length > offsetof(FFSmbiosPortableBattery, SbdsManufactureDate)) { int day = data->SbdsManufactureDate & 0b11111; int month = (data->SbdsManufactureDate >> 5) & 0b1111; int year = (data->SbdsManufactureDate >> 9) + 1800; ffStrbufSetF(&battery->manufactureDate, "%.4d-%.2d-%.2d", year, month, day); } - switch (data->DeviceChemistry) - { - case 0x01: ffStrbufSetStatic(&battery->technology, "Other"); break; - case 0x02: ffStrbufSetStatic(&battery->technology, "Unknown"); break; - case 0x03: ffStrbufSetStatic(&battery->technology, "Lead Acid"); break; - case 0x04: ffStrbufSetStatic(&battery->technology, "Nickel Cadmium"); break; - case 0x05: ffStrbufSetStatic(&battery->technology, "Nickel metal hydride"); break; - case 0x06: ffStrbufSetStatic(&battery->technology, "Lithium-ion"); break; - case 0x07: ffStrbufSetStatic(&battery->technology, "Zinc air"); break; - case 0x08: ffStrbufSetStatic(&battery->technology, "Lithium Polymer"); break; + switch (data->DeviceChemistry) { + case 0x01: + ffStrbufSetStatic(&battery->technology, "Other"); + break; + case 0x02: + ffStrbufSetStatic(&battery->technology, "Unknown"); + break; + case 0x03: + ffStrbufSetStatic(&battery->technology, "Lead Acid"); + break; + case 0x04: + ffStrbufSetStatic(&battery->technology, "Nickel Cadmium"); + break; + case 0x05: + ffStrbufSetStatic(&battery->technology, "Nickel metal hydride"); + break; + case 0x06: + ffStrbufSetStatic(&battery->technology, "Lithium-ion"); + break; + case 0x07: + ffStrbufSetStatic(&battery->technology, "Zinc air"); + break; + case 0x08: + ffStrbufSetStatic(&battery->technology, "Lithium Polymer"); + break; } - if (data->SerialNumber) - { + if (data->SerialNumber) { ffStrbufSetStatic(&battery->serial, ffSmbiosLocateString(strings, data->SerialNumber)); ffCleanUpSmbiosValue(&battery->serial); - } - else if (data->Header.Length > offsetof(FFSmbiosPortableBattery, SbdsSerialNumber)) - { + } else if (data->Header.Length > offsetof(FFSmbiosPortableBattery, SbdsSerialNumber)) { ffStrbufSetF(&battery->serial, "%4X", data->SbdsSerialNumber); } return NULL; } -static const char* detectWithNtApi(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) -{ +static const char* detectWithNtApi(FF_MAYBE_UNUSED FFBatteryOptions* options, FFlist* results) { SYSTEM_BATTERY_STATE info; - if (NT_SUCCESS(NtPowerInformation(SystemBatteryState, NULL, 0, &info, sizeof(info))) && info.BatteryPresent) - { - FFBatteryResult* battery = (FFBatteryResult*)ffListAdd(results); + if (NT_SUCCESS(NtPowerInformation(SystemBatteryState, NULL, 0, &info, sizeof(info))) && info.BatteryPresent) { + FFBatteryResult* battery = (FFBatteryResult*) ffListAdd(results); ffStrbufInit(&battery->modelName); ffStrbufInit(&battery->manufacturer); ffStrbufInit(&battery->manufactureDate); @@ -241,15 +264,14 @@ static const char* detectWithNtApi(FF_MAYBE_UNUSED FFBatteryOptions* options, FF battery->timeRemaining = info.EstimatedTime == BATTERY_UNKNOWN_TIME ? -1 : (int32_t) info.EstimatedTime; battery->capacity = info.RemainingCapacity * 100.0 / info.MaxCapacity; - if(info.AcOnLine) - { + if (info.AcOnLine) { ffStrbufAppendS(&battery->status, "AC Connected"); - if(info.Charging) + if (info.Charging) { ffStrbufAppendS(&battery->status, ", Charging"); - } - else if(info.Discharging) + } + } else if (info.Discharging) { ffStrbufAppendS(&battery->status, "Discharging"); - + } detectBySmbios(battery); @@ -258,8 +280,7 @@ static const char* detectWithNtApi(FF_MAYBE_UNUSED FFBatteryOptions* options, FF return "NtPowerInformation(SystemBatteryState) failed"; } -const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) -{ +const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { return options->useSetupApi ? detectWithCmApi(options, results) : detectWithNtApi(options, results); diff --git a/src/detection/bios/bios.h b/src/detection/bios/bios.h index 4a0969d26..cdb48c292 100644 --- a/src/detection/bios/bios.h +++ b/src/detection/bios/bios.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/bios/option.h" -typedef struct FFBiosResult -{ +typedef struct FFBiosResult { FFstrbuf date; FFstrbuf release; FFstrbuf vendor; diff --git a/src/detection/bios/bios_android.c b/src/detection/bios/bios_android.c index b2b20aaf9..a53db0db5 100644 --- a/src/detection/bios/bios_android.c +++ b/src/detection/bios/bios_android.c @@ -1,13 +1,14 @@ #include "bios.h" #include "common/settings.h" -const char* ffDetectBios(FFBiosResult* bios) -{ - if (!ffSettingsGetAndroidProperty("ro.bootloader", &bios->version)) +const char* ffDetectBios(FFBiosResult* bios) { + if (!ffSettingsGetAndroidProperty("ro.bootloader", &bios->version)) { ffSettingsGetAndroidProperty("ro.boot.bootloader", &bios->version); + } - if (ffStrbufIgnCaseEqualS(&bios->version, "unknown")) + if (ffStrbufIgnCaseEqualS(&bios->version, "unknown")) { ffStrbufClear(&bios->version); + } ffStrbufSetStatic(&bios->type, "Bootloader"); diff --git a/src/detection/bios/bios_apple.c b/src/detection/bios/bios_apple.c index 87df39d35..96845d888 100644 --- a/src/detection/bios/bios_apple.c +++ b/src/detection/bios/bios_apple.c @@ -3,31 +3,33 @@ #include -const char* ffDetectBios(FFBiosResult* bios) -{ - #ifndef __aarch64__ +const char* ffDetectBios(FFBiosResult* bios) { +#ifndef __aarch64__ - //https://github.com/osquery/osquery/blob/master/osquery/tables/system/darwin/smbios_tables.cpp - //For Intel + // https://github.com/osquery/osquery/blob/master/osquery/tables/system/darwin/smbios_tables.cpp + // For Intel FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t deviceRom = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/rom"); - if (!deviceRom) + if (!deviceRom) { return "IODeviceTree:/rom not found"; + } FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef deviceRomProps = NULL; - if(IORegistryEntryCreateCFProperties(deviceRom, &deviceRomProps, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) + if (IORegistryEntryCreateCFProperties(deviceRom, &deviceRomProps, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { return "IORegistryEntryCreateCFProperties(deviceRom) failed"; + } ffCfDictGetString(deviceRomProps, CFSTR("vendor"), &bios->vendor); ffCfDictGetString(deviceRomProps, CFSTR("version"), &bios->version); ffCfDictGetString(deviceRomProps, CFSTR("release-date"), &bios->date); ffStrbufSetStatic(&bios->type, "UEFI"); - #else +#else - //For arm64 + // For arm64 FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t device = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/"); - if (!device) + if (!device) { return "IODeviceTree:/ not found"; + } FF_CFTYPE_AUTO_RELEASE CFDataRef manufacturer = IORegistryEntryCreateCFProperty(device, CFSTR("manufacturer"), kCFAllocatorDefault, kNilOptions); ffCfStrGetString(manufacturer, &bios->vendor); @@ -35,23 +37,21 @@ const char* ffDetectBios(FFBiosResult* bios) ffCfStrGetString(timeStamp, &bios->date); FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t deviceChosen = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/chosen"); - if (deviceChosen) - { + if (deviceChosen) { FF_CFTYPE_AUTO_RELEASE CFStringRef systemFirmwareVersion = IORegistryEntryCreateCFProperty(deviceChosen, CFSTR("system-firmware-version"), kCFAllocatorDefault, kNilOptions); - if (systemFirmwareVersion) - { + if (systemFirmwareVersion) { ffCfStrGetString(systemFirmwareVersion, &bios->version); uint32_t index = ffStrbufFirstIndexC(&bios->version, '-'); - if (index != bios->version.length) - { + if (index != bios->version.length) { ffStrbufAppendNS(&bios->type, index, bios->version.chars); ffStrbufRemoveSubstr(&bios->version, 0, index + 1); } } } - if (!bios->type.length) + if (!bios->type.length) { ffStrbufSetStatic(&bios->type, "iBoot"); - #endif + } +#endif return NULL; } diff --git a/src/detection/bios/bios_bsd.c b/src/detection/bios/bios_bsd.c index 35f371ab7..7911399d2 100644 --- a/src/detection/bios/bios_bsd.c +++ b/src/detection/bios/bios_bsd.c @@ -5,8 +5,7 @@ #include "common/io.h" #include "common/smbiosHelper.h" -const char* ffDetectBios(FFBiosResult* result) -{ +const char* ffDetectBios(FFBiosResult* result) { ffSettingsGetFreeBSDKenv("smbios.bios.reldate", &result->date); ffCleanUpSmbiosValue(&result->date); ffSettingsGetFreeBSDKenv("smbios.bios.revision", &result->release); @@ -17,16 +16,15 @@ const char* ffDetectBios(FFBiosResult* result) ffCleanUpSmbiosValue(&result->version); ffSysctlGetString("machdep.bootmethod", &result->type); - if (result->type.length == 0) - { - if (ffSettingsGetFreeBSDKenv("loader.efi", &result->type)) + if (result->type.length == 0) { + if (ffSettingsGetFreeBSDKenv("loader.efi", &result->type)) { ffStrbufSetStatic(&result->type, ffStrbufEqualS(&result->type, "1") ? "UEFI" : "BIOS"); - else - { + } else { ffStrbufSetStatic(&result->type, ffPathExists("/dev/efi" /*efidev*/, FF_PATHTYPE_FILE) || - ffPathExists("/boot/efi/efi/" /*efi partition. Note /boot/efi exists on BIOS system*/, FF_PATHTYPE_DIRECTORY) - ? "UEFI" : "BIOS"); + ffPathExists("/boot/efi/efi/" /*efi partition. Note /boot/efi exists on BIOS system*/, FF_PATHTYPE_DIRECTORY) + ? "UEFI" + : "BIOS"); } } return NULL; diff --git a/src/detection/bios/bios_linux.c b/src/detection/bios/bios_linux.c index 5e6a27a95..0661df485 100644 --- a/src/detection/bios/bios_linux.c +++ b/src/detection/bios/bios_linux.c @@ -2,23 +2,20 @@ #include "common/io.h" #include "common/smbiosHelper.h" -const char* ffDetectBios(FFBiosResult* bios) -{ - if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/bios_date", "/sys/class/dmi/id/bios_date", &bios->date)) - { +const char* ffDetectBios(FFBiosResult* bios) { + if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/bios_date", "/sys/class/dmi/id/bios_date", &bios->date)) { ffGetSmbiosValue("/sys/devices/virtual/dmi/id/bios_release", "/sys/class/dmi/id/bios_release", &bios->release); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/bios_vendor", "/sys/class/dmi/id/bios_vendor", &bios->vendor); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/bios_version", "/sys/class/dmi/id/bios_version", &bios->version); - } - else if (ffReadFileBuffer("/proc/device-tree/chosen/u-boot,version", &bios->version)) - { + } else if (ffReadFileBuffer("/proc/device-tree/chosen/u-boot,version", &bios->version)) { ffStrbufTrimRight(&bios->version, '\0'); ffStrbufSetStatic(&bios->vendor, "U-Boot"); } - if (ffPathExists("/sys/firmware/efi/", FF_PATHTYPE_DIRECTORY) || ffPathExists("/sys/firmware/acpi/tables/UEFI", FF_PATHTYPE_FILE)) + if (ffPathExists("/sys/firmware/efi/", FF_PATHTYPE_DIRECTORY) || ffPathExists("/sys/firmware/acpi/tables/UEFI", FF_PATHTYPE_FILE)) { ffStrbufSetStatic(&bios->type, "UEFI"); - else + } else { ffStrbufSetStatic(&bios->type, "BIOS"); + } return NULL; } diff --git a/src/detection/bios/bios_nbsd.c b/src/detection/bios/bios_nbsd.c index 10b326dd1..650862ce0 100644 --- a/src/detection/bios/bios_nbsd.c +++ b/src/detection/bios/bios_nbsd.c @@ -2,14 +2,16 @@ #include "common/sysctl.h" #include "common/smbiosHelper.h" -const char* ffDetectBios(FFBiosResult* bios) -{ - if (ffSysctlGetString("machdep.dmi.bios-date", &bios->date) == NULL) +const char* ffDetectBios(FFBiosResult* bios) { + if (ffSysctlGetString("machdep.dmi.bios-date", &bios->date) == NULL) { ffCleanUpSmbiosValue(&bios->date); - if (ffSysctlGetString("machdep.dmi.bios-version", &bios->version) == NULL) + } + if (ffSysctlGetString("machdep.dmi.bios-version", &bios->version) == NULL) { ffCleanUpSmbiosValue(&bios->version); - if (ffSysctlGetString("machdep.dmi.bios-vendor", &bios->vendor) == NULL) + } + if (ffSysctlGetString("machdep.dmi.bios-vendor", &bios->vendor) == NULL) { ffCleanUpSmbiosValue(&bios->vendor); + } ffSysctlGetString("machdep.bootmethod", &bios->type); return NULL; } diff --git a/src/detection/bios/bios_nosupport.c b/src/detection/bios/bios_nosupport.c index ac544fd3e..091bf631f 100644 --- a/src/detection/bios/bios_nosupport.c +++ b/src/detection/bios/bios_nosupport.c @@ -1,6 +1,5 @@ #include "bios.h" -const char* ffDetectBios(FF_MAYBE_UNUSED FFBiosResult* bios) -{ +const char* ffDetectBios(FF_MAYBE_UNUSED FFBiosResult* bios) { return "Not supported on this platform"; } diff --git a/src/detection/bios/bios_windows.c b/src/detection/bios/bios_windows.c index f1196a3d4..28271185f 100644 --- a/src/detection/bios/bios_windows.c +++ b/src/detection/bios/bios_windows.c @@ -2,38 +2,37 @@ #include "common/smbiosHelper.h" #ifdef _WIN32 -#include "common/windows/registry.h" +# include "common/windows/registry.h" -#include -#include "common/windows/nt.h" +# include +# include "common/windows/nt.h" #elif __OpenBSD__ -#include "common/io.h" +# include "common/io.h" -#include -#include +# include +# include #elif __sun -#include -#include +# include +# include #elif __APPLE__ -#include "common/apple/cf_helpers.h" -#include +# include "common/apple/cf_helpers.h" +# include #endif -typedef struct FFSmbiosBios -{ +typedef struct FFSmbiosBios { FFSmbiosHeader Header; - uint8_t Vendor; // string - uint8_t BiosVersion; // string + uint8_t Vendor; // string + uint8_t BiosVersion; // string uint16_t BiosStartingAddressSegment; // varies - uint8_t BiosReleaseDate; // string - uint8_t BiosRomSize; // string - uint64_t BiosCharacteristics; // bit field + uint8_t BiosReleaseDate; // string + uint8_t BiosRomSize; // string + uint64_t BiosCharacteristics; // bit field // 2.4+ - uint8_t BiosCharacteristicsExtensionBytes[2]; // bit field - uint8_t SystemBiosMajorRelease; // varies - uint8_t SystemBiosMinorRelease; // varies + uint8_t BiosCharacteristicsExtensionBytes[2]; // bit field + uint8_t SystemBiosMajorRelease; // varies + uint8_t SystemBiosMinorRelease; // varies uint8_t EmbeddedControllerFirmwareMajorRelease; // varies uint8_t EmbeddedControllerFirmwareMinorRelease; // varies @@ -44,16 +43,16 @@ typedef struct FFSmbiosBios static_assert(offsetof(FFSmbiosBios, ExtendedBiosRomSize) == 0x18, "FFSmbiosBios: Wrong struct alignment"); - -const char* ffDetectBios(FFBiosResult* bios) -{ +const char* ffDetectBios(FFBiosResult* bios) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosBios* data = (const FFSmbiosBios*) (*smbiosTable)[FF_SMBIOS_TYPE_BIOS]; - if (!data) + if (!data) { return "BIOS section is not found in SMBIOS data"; + } const char* strings = (const char*) data + data->Header.Length; @@ -64,41 +63,45 @@ const char* ffDetectBios(FFBiosResult* bios) ffStrbufSetStatic(&bios->date, ffSmbiosLocateString(strings, data->BiosReleaseDate)); ffCleanUpSmbiosValue(&bios->date); - if (data->Header.Length > offsetof(FFSmbiosBios, SystemBiosMajorRelease)) + if (data->Header.Length > offsetof(FFSmbiosBios, SystemBiosMajorRelease)) { ffStrbufSetF(&bios->release, "%u.%u", data->SystemBiosMajorRelease, data->SystemBiosMinorRelease); + } - #ifdef _WIN32 +#ifdef _WIN32 // Same as GetFirmwareType, but support (?) Windows 7 // https://ntdoc.m417z.com/system_information_class SYSTEM_BOOT_ENVIRONMENT_INFORMATION sbei; - if (NT_SUCCESS(NtQuerySystemInformation(SystemBootEnvironmentInformation, &sbei, sizeof(sbei), NULL))) - { - switch (sbei.FirmwareType) - { - case FirmwareTypeBios: ffStrbufSetStatic(&bios->type, "BIOS"); break; - case FirmwareTypeUefi: ffStrbufSetStatic(&bios->type, "UEFI"); break; - default: break; + if (NT_SUCCESS(NtQuerySystemInformation(SystemBootEnvironmentInformation, &sbei, sizeof(sbei), NULL))) { + switch (sbei.FirmwareType) { + case FirmwareTypeBios: + ffStrbufSetStatic(&bios->type, "BIOS"); + break; + case FirmwareTypeUefi: + ffStrbufSetStatic(&bios->type, "UEFI"); + break; + default: + break; } } - #elif __sun +#elif __sun di_node_t rootNode = di_init("/", DINFOPROP); - if (rootNode != DI_NODE_NIL) - { + if (rootNode != DI_NODE_NIL) { char* efiVersion = NULL; - if (di_prop_lookup_strings(DDI_DEV_T_ANY, rootNode, "efi-version", &efiVersion) > 0) + if (di_prop_lookup_strings(DDI_DEV_T_ANY, rootNode, "efi-version", &efiVersion) > 0) { ffStrbufSetStatic(&bios->type, "UEFI"); - else + } else { ffStrbufSetStatic(&bios->type, "BIOS"); + } } di_fini(rootNode); - #elif __HAIKU__ || __OpenBSD__ +#elif __HAIKU__ || __OpenBSD__ // Currently SMBIOS detection is supported in legacy BIOS only ffStrbufSetStatic(&bios->type, "BIOS"); - #elif __APPLE__ +#elif __APPLE__ // Intel Macs use UEFI from day one FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t deviceEfi = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/efi"); ffStrbufSetStatic(&bios->type, deviceEfi ? "UEFI" : "BIOS"); - #endif +#endif return NULL; } diff --git a/src/detection/bluetooth/bluetooth.h b/src/detection/bluetooth/bluetooth.h index 0a4153ce5..dde80853d 100644 --- a/src/detection/bluetooth/bluetooth.h +++ b/src/detection/bluetooth/bluetooth.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/bluetooth/option.h" -typedef struct FFBluetoothResult -{ +typedef struct FFBluetoothResult { FFstrbuf name; FFstrbuf address; FFstrbuf type; diff --git a/src/detection/bluetooth/bluetooth_bsd.c b/src/detection/bluetooth/bluetooth_bsd.c index 7425c614f..4af766307 100644 --- a/src/detection/bluetooth/bluetooth_bsd.c +++ b/src/detection/bluetooth/bluetooth_bsd.c @@ -3,15 +3,14 @@ #define L2CAP_SOCKET_CHECKED #include -static int enumDev(FF_MAYBE_UNUSED int sockfd, struct bt_devinfo const* dev, FFlist* devices) -{ +static int enumDev(FF_MAYBE_UNUSED int sockfd, struct bt_devinfo const* dev, FFlist* devices) { FFBluetoothResult* device = ffListAdd(devices); ffStrbufInitS(&device->name, - #if __FreeBSD__ +#if __FreeBSD__ bt_devremote_name_gen(dev->devname, &dev->bdaddr) - #else +#else dev->devname - #endif +#endif ); ffStrbufInitS(&device->address, bt_ntoa(&dev->bdaddr, NULL)); ffStrbufUpperCase(&device->address); @@ -21,11 +20,11 @@ static int enumDev(FF_MAYBE_UNUSED int sockfd, struct bt_devinfo const* dev, FFl return 0; } -const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothResult */) -{ +const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothResult */) { // struct hostent* ent = bt_gethostent(); - if (bt_devenum((void*) enumDev, devices) < 0) + if (bt_devenum((void*) enumDev, devices) < 0) { return "bt_devenum() failed"; + } return NULL; } diff --git a/src/detection/bluetooth/bluetooth_haiku.cpp b/src/detection/bluetooth/bluetooth_haiku.cpp index 188d2a845..e9b1ba426 100644 --- a/src/detection/bluetooth/bluetooth_haiku.cpp +++ b/src/detection/bluetooth/bluetooth_haiku.cpp @@ -5,13 +5,14 @@ extern "C" { #include -const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) -{ +const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) { using namespace Bluetooth; FF_SUPPRESS_IO(); LocalDevice* dev = LocalDevice::GetLocalDevice(); - if (!dev) return NULL; + if (!dev) { + return NULL; + } BString devClass; dev->GetDeviceClass().DumpDeviceClass(devClass); diff --git a/src/detection/bluetooth/bluetooth_linux.c b/src/detection/bluetooth/bluetooth_linux.c index 4f8c1c803..e7d96e664 100644 --- a/src/detection/bluetooth/bluetooth_linux.c +++ b/src/detection/bluetooth/bluetooth_linux.c @@ -2,8 +2,8 @@ #include "common/stringUtils.h" #ifdef FF_HAVE_DBUS -#include "common/dbus.h" -#include "common/io.h" +# include "common/dbus.h" +# include "common/io.h" /* Example dbus reply, striped to only the relevant parts: array [ //root @@ -45,103 +45,108 @@ array [ //root ] */ -static bool detectBluetoothValue(FFDBusData* dbus, DBusMessageIter* iter, FFBluetoothResult* device) -{ - if(dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) +static bool detectBluetoothValue(FFDBusData* dbus, DBusMessageIter* iter, FFBluetoothResult* device) { + if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) { return true; + } DBusMessageIter dictIter; dbus->lib->ffdbus_message_iter_recurse(iter, &dictIter); - if(dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_STRING) + if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_STRING) { return true; + } const char* deviceProperty; dbus->lib->ffdbus_message_iter_get_basic(&dictIter, &deviceProperty); dbus->lib->ffdbus_message_iter_next(&dictIter); - if(ffStrEquals(deviceProperty, "Address")) + if (ffStrEquals(deviceProperty, "Address")) { ffDBusGetString(dbus, &dictIter, &device->address); - else if(ffStrEquals(deviceProperty, "Name")) + } else if (ffStrEquals(deviceProperty, "Name")) { ffDBusGetString(dbus, &dictIter, &device->name); - else if(ffStrEquals(deviceProperty, "Icon")) + } else if (ffStrEquals(deviceProperty, "Icon")) { ffDBusGetString(dbus, &dictIter, &device->type); - else if(ffStrEquals(deviceProperty, "Percentage")) - { + } else if (ffStrEquals(deviceProperty, "Percentage")) { uint32_t percentage; - if (ffDBusGetUint(dbus, &dictIter, &percentage)) + if (ffDBusGetUint(dbus, &dictIter, &percentage)) { device->battery = (uint8_t) percentage; - } - else if(ffStrEquals(deviceProperty, "Connected")) + } + } else if (ffStrEquals(deviceProperty, "Connected")) { ffDBusGetBool(dbus, &dictIter, &device->connected); - else if(ffStrEquals(deviceProperty, "Paired")) - { + } else if (ffStrEquals(deviceProperty, "Paired")) { bool paired = true; ffDBusGetBool(dbus, &dictIter, &paired); - if (!paired) return false; + if (!paired) { + return false; + } } return true; } -static void detectBluetoothProperty(FFDBusData* dbus, DBusMessageIter* iter, FFBluetoothResult* device) -{ - if(dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) +static void detectBluetoothProperty(FFDBusData* dbus, DBusMessageIter* iter, FFBluetoothResult* device) { + if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) { return; + } DBusMessageIter dictIter; dbus->lib->ffdbus_message_iter_recurse(iter, &dictIter); - if(dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_STRING) + if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_STRING) { return; + } const char* propertyType; dbus->lib->ffdbus_message_iter_get_basic(&dictIter, &propertyType); - if(!ffStrContains(propertyType, ".Device") && !ffStrContains(propertyType, ".Battery")) + if (!ffStrContains(propertyType, ".Device") && !ffStrContains(propertyType, ".Battery")) { return; // We don't care about other properties + } dbus->lib->ffdbus_message_iter_next(&dictIter); - if(dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_ARRAY) + if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_ARRAY) { return; + } DBusMessageIter arrayIter; dbus->lib->ffdbus_message_iter_recurse(&dictIter, &arrayIter); - do - { + do { bool shouldContinue = detectBluetoothValue(dbus, &arrayIter, device); - if (!shouldContinue) - { + if (!shouldContinue) { ffStrbufClear(&device->name); break; } } while (dbus->lib->ffdbus_message_iter_next(&arrayIter)); } -static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbus, DBusMessageIter* iter) -{ - if(dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) +static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbus, DBusMessageIter* iter) { + if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) { return NULL; + } DBusMessageIter dictIter; dbus->lib->ffdbus_message_iter_recurse(iter, &dictIter); - if(dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_OBJECT_PATH) + if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_OBJECT_PATH) { return NULL; + } const char* objectPath; dbus->lib->ffdbus_message_iter_get_basic(&dictIter, &objectPath); // We don't want adapter objects - if(!ffStrContains(objectPath, "/dev_")) + if (!ffStrContains(objectPath, "/dev_")) { return NULL; + } dbus->lib->ffdbus_message_iter_next(&dictIter); - if(dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_ARRAY) + if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_ARRAY) { return NULL; + } DBusMessageIter arrayIter; dbus->lib->ffdbus_message_iter_recurse(&dictIter, &arrayIter); @@ -153,56 +158,53 @@ static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbu device->battery = 0; device->connected = false; - do - { + do { detectBluetoothProperty(dbus, &arrayIter, device); } while (dbus->lib->ffdbus_message_iter_next(&arrayIter)); return device; } -static void detectBluetoothRoot(FFlist* devices, FFDBusData* dbus, DBusMessageIter* iter, int32_t connectedCount) -{ - if(dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY) +static void detectBluetoothRoot(FFlist* devices, FFDBusData* dbus, DBusMessageIter* iter, int32_t connectedCount) { + if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY) { return; + } DBusMessageIter arrayIter; dbus->lib->ffdbus_message_iter_recurse(iter, &arrayIter); - do - { + do { FFBluetoothResult* device = detectBluetoothObject(devices, dbus, &arrayIter); - if (device) - { - if(device->name.length == 0 || (connectedCount > 0 && !device->connected)) - { + if (device) { + if (device->name.length == 0 || (connectedCount > 0 && !device->connected)) { ffStrbufDestroy(&device->name); ffStrbufDestroy(&device->address); ffStrbufDestroy(&device->type); --devices->length; } - if (device->connected && --connectedCount == 0) + if (device->connected && --connectedCount == 0) { break; + } } } while (dbus->lib->ffdbus_message_iter_next(&arrayIter)); } -static const char* detectBluetooth(FFlist* devices, int32_t connectedCount) -{ +static const char* detectBluetooth(FFlist* devices, int32_t connectedCount) { FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; const char* error = ffDBusLoadData(DBUS_BUS_SYSTEM, &dbus); - if(error) + if (error) { return error; + } DBusMessage* managedObjects = ffDBusGetMethodReply(&dbus, "org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", NULL, NULL); - if(!managedObjects) + if (!managedObjects) { return "Failed to call GetManagedObjects"; + } DBusMessageIter rootIter; - if(!dbus.lib->ffdbus_message_iter_init(managedObjects, &rootIter)) - { + if (!dbus.lib->ffdbus_message_iter_init(managedObjects, &rootIter)) { dbus.lib->ffdbus_message_unref(managedObjects); return "Failed to get root iterator of GetManagedObjects"; } @@ -213,18 +215,18 @@ static const char* detectBluetooth(FFlist* devices, int32_t connectedCount) return NULL; } -static uint32_t connectedDevices(void) -{ +static uint32_t connectedDevices(void) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth"); - if(dirp == NULL) + if (dirp == NULL) { return 0; + } uint32_t result = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (strchr(entry->d_name, ':') != NULL) + while ((entry = readdir(dirp)) != NULL) { + if (strchr(entry->d_name, ':') != NULL) { ++result; + } } return result; @@ -232,19 +234,18 @@ static uint32_t connectedDevices(void) #endif -const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothResult */) -{ - #ifdef FF_HAVE_DBUS - int32_t connectedCount = -1; - if (!options->showDisconnected) - { - connectedCount = (int32_t) connectedDevices(); - if (connectedCount == 0) - return NULL; +const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothResult */) { +#ifdef FF_HAVE_DBUS + int32_t connectedCount = -1; + if (!options->showDisconnected) { + connectedCount = (int32_t) connectedDevices(); + if (connectedCount == 0) { + return NULL; } + } - return detectBluetooth(devices, connectedCount); - #else - return "Fastfetch was compiled without DBus support"; - #endif + return detectBluetooth(devices, connectedCount); +#else + return "Fastfetch was compiled without DBus support"; +#endif } diff --git a/src/detection/bluetooth/bluetooth_nosupport.c b/src/detection/bluetooth/bluetooth_nosupport.c index c119ecb95..afba201e1 100644 --- a/src/detection/bluetooth/bluetooth_nosupport.c +++ b/src/detection/bluetooth/bluetooth_nosupport.c @@ -1,6 +1,5 @@ #include "bluetooth.h" -const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothResult */) -{ +const char* ffDetectBluetooth(FF_MAYBE_UNUSED FFBluetoothOptions* options, FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothResult */) { return "Not supported on this platform"; } diff --git a/src/detection/bluetooth/bluetooth_windows.c b/src/detection/bluetooth/bluetooth_windows.c index e69aff69f..ebb3aa2ae 100644 --- a/src/detection/bluetooth/bluetooth_windows.c +++ b/src/detection/bluetooth/bluetooth_windows.c @@ -7,73 +7,74 @@ #pragma GCC diagnostic ignored "-Wpointer-sign" -const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) -{ +const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) { FF_LIBRARY_LOAD_MESSAGE(bluetoothapis, "bluetoothapis.dll", 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothFindFirstDevice) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothFindNextDevice) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothFindDeviceClose) BLUETOOTH_DEVICE_INFO btdi = { - .dwSize = sizeof(btdi) - }; + .dwSize = sizeof(btdi)}; HBLUETOOTH_DEVICE_FIND hFind = ffBluetoothFindFirstDevice(&(BLUETOOTH_DEVICE_SEARCH_PARAMS) { - .fReturnConnected = TRUE, - .fReturnRemembered = options->showDisconnected, - .fReturnAuthenticated = options->showDisconnected, - .dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS) - }, &btdi); - if(!hFind) - { - if (GetLastError() == ERROR_NO_MORE_ITEMS) + .fReturnConnected = TRUE, + .fReturnRemembered = options->showDisconnected, + .fReturnAuthenticated = options->showDisconnected, + .dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS)}, + &btdi); + if (!hFind) { + if (GetLastError() == ERROR_NO_MORE_ITEMS) { return NULL; + } return "BluetoothFindFirstDevice() failed"; } do { FFBluetoothResult* device = ffListAdd(devices); ffStrbufInitWS(&device->name, btdi.szName); - ffStrbufInitF(&device->address, "%02X:%02X:%02X:%02X:%02X:%02X", - btdi.Address.rgBytes[5], - btdi.Address.rgBytes[4], - btdi.Address.rgBytes[3], - btdi.Address.rgBytes[2], - btdi.Address.rgBytes[1], - btdi.Address.rgBytes[0]); + ffStrbufInitF(&device->address, "%02X:%02X:%02X:%02X:%02X:%02X", btdi.Address.rgBytes[5], btdi.Address.rgBytes[4], btdi.Address.rgBytes[3], btdi.Address.rgBytes[2], btdi.Address.rgBytes[1], btdi.Address.rgBytes[0]); ffStrbufInit(&device->type); device->battery = 0; device->connected = !!btdi.fConnected; - //https://btprodspecificationrefs.blob.core.windows.net/assigned-numbers/Assigned%20Number%20Types/Assigned%20Numbers.pdf + // https://btprodspecificationrefs.blob.core.windows.net/assigned-numbers/Assigned%20Number%20Types/Assigned%20Numbers.pdf - if(BitTest(&btdi.ulClassofDevice, 13)) + if (BitTest(&btdi.ulClassofDevice, 13)) { ffStrbufAppendS(&device->type, "Limited Discoverable Mode, "); - if(BitTest(&btdi.ulClassofDevice, 14)) + } + if (BitTest(&btdi.ulClassofDevice, 14)) { ffStrbufAppendS(&device->type, "LE audio, "); - if(BitTest(&btdi.ulClassofDevice, 15)) + } + if (BitTest(&btdi.ulClassofDevice, 15)) { ffStrbufAppendS(&device->type, "Reserved for future use, "); - if(BitTest(&btdi.ulClassofDevice, 16)) + } + if (BitTest(&btdi.ulClassofDevice, 16)) { ffStrbufAppendS(&device->type, "Positioning, "); - if(BitTest(&btdi.ulClassofDevice, 17)) + } + if (BitTest(&btdi.ulClassofDevice, 17)) { ffStrbufAppendS(&device->type, "Networking, "); - if(BitTest(&btdi.ulClassofDevice, 18)) + } + if (BitTest(&btdi.ulClassofDevice, 18)) { ffStrbufAppendS(&device->type, "Rendering, "); - if(BitTest(&btdi.ulClassofDevice, 19)) + } + if (BitTest(&btdi.ulClassofDevice, 19)) { ffStrbufAppendS(&device->type, "Capturing, "); - if(BitTest(&btdi.ulClassofDevice, 20)) + } + if (BitTest(&btdi.ulClassofDevice, 20)) { ffStrbufAppendS(&device->type, "Object Transfer, "); - if(BitTest(&btdi.ulClassofDevice, 21)) + } + if (BitTest(&btdi.ulClassofDevice, 21)) { ffStrbufAppendS(&device->type, "Audio, "); - if(BitTest(&btdi.ulClassofDevice, 22)) + } + if (BitTest(&btdi.ulClassofDevice, 22)) { ffStrbufAppendS(&device->type, "Telephony, "); - if(BitTest(&btdi.ulClassofDevice, 23)) + } + if (BitTest(&btdi.ulClassofDevice, 23)) { ffStrbufAppendS(&device->type, "Information, "); + } - if(device->type.length == 0) - { + if (device->type.length == 0) { uint32_t majorDeviceClasses = (btdi.ulClassofDevice >> 8) & ~(UINT32_MAX << 5); - switch(majorDeviceClasses) - { + switch (majorDeviceClasses) { case 0b00000: ffStrbufAppendS(&device->type, "Miscellaneous"); break; @@ -111,9 +112,7 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF ffStrbufAppendS(&device->type, "Unknown"); break; } - } - else - { + } else { ffStrbufTrimRight(&device->type, ' '); ffStrbufTrimRight(&device->type, ','); } @@ -121,7 +120,7 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF ffBluetoothFindDeviceClose(hFind); - const char* ffBluetoothDetectBattery(FFlist* result); + const char* ffBluetoothDetectBattery(FFlist * result); ffBluetoothDetectBattery(devices); return NULL; diff --git a/src/detection/bluetooth/bluetooth_windows.cpp b/src/detection/bluetooth/bluetooth_windows.cpp index 3109037f4..da3abbbf5 100644 --- a/src/detection/bluetooth/bluetooth_windows.cpp +++ b/src/detection/bluetooth/bluetooth_windows.cpp @@ -1,84 +1,88 @@ -extern "C" -{ +extern "C" { #include "bluetooth.h" } #include "common/windows/wmi.hpp" #include "common/windows/unicode.hpp" #include "common/windows/util.hpp" -extern "C" -const char* ffBluetoothDetectBattery(FFlist* devices) -{ +extern "C" const char* ffBluetoothDetectBattery(FFlist* devices) { FFWmiQuery query(L"SELECT __PATH FROM Win32_PnPEntity WHERE Service = 'BthHFEnum'", nullptr, FFWmiNamespace::CIMV2); - if(!query) + if (!query) { return "Query WMI service failed"; + } IWbemClassObject* pInParams = nullptr; on_scope_exit releaseInParams([&] { pInParams && pInParams->Release(); }); { IWbemClassObject* pnpEntityClass = nullptr; - if (FAILED(query.pService->GetObjectW(bstr_t(L"Win32_PnPEntity"), 0, nullptr, &pnpEntityClass, nullptr))) + if (FAILED(query.pService->GetObjectW(bstr_t(L"Win32_PnPEntity"), 0, nullptr, &pnpEntityClass, nullptr))) { return "Failed to get PnP entity class"; + } on_scope_exit releasePnpEntityClass([&] { pnpEntityClass && pnpEntityClass->Release(); }); - if (FAILED(pnpEntityClass->GetMethod(bstr_t(L"GetDeviceProperties"), 0, &pInParams, NULL))) + if (FAILED(pnpEntityClass->GetMethod(bstr_t(L"GetDeviceProperties"), 0, &pInParams, NULL))) { return "Failed to get GetDeviceProperties method"; + } - FFWmiVariant devicePropertyKeys({ L"{104EA319-6EE2-4701-BD47-8DDBF425BBE5} 2", L"DEVPKEY_Bluetooth_DeviceAddress" }); - if (FAILED(pInParams->Put(L"devicePropertyKeys", 0, &devicePropertyKeys, CIM_FLAG_ARRAY | CIM_STRING))) + FFWmiVariant devicePropertyKeys({L"{104EA319-6EE2-4701-BD47-8DDBF425BBE5} 2", L"DEVPKEY_Bluetooth_DeviceAddress"}); + if (FAILED(pInParams->Put(L"devicePropertyKeys", 0, &devicePropertyKeys, CIM_FLAG_ARRAY | CIM_STRING))) { return "Failed to put devicePropertyKeys"; + } } - while (FFWmiRecord record = query.next()) - { + while (FFWmiRecord record = query.next()) { IWbemCallResult* pCallResult = nullptr; - if (FAILED(query.pService->ExecMethod(record.get(L"__PATH").bstrVal, bstr_t(L"GetDeviceProperties"), 0, nullptr, pInParams, nullptr, &pCallResult))) + if (FAILED(query.pService->ExecMethod(record.get(L"__PATH").bstrVal, bstr_t(L"GetDeviceProperties"), 0, nullptr, pInParams, nullptr, &pCallResult))) { continue; + } on_scope_exit releaseCallResult([&] { pCallResult && pCallResult->Release(); }); IWbemClassObject* pResultObject = nullptr; - if (FAILED(pCallResult->GetResultObject((LONG) WBEM_INFINITE, &pResultObject))) + if (FAILED(pCallResult->GetResultObject((LONG) WBEM_INFINITE, &pResultObject))) { continue; + } on_scope_exit releaseResultObject([&] { pResultObject && pResultObject->Release(); }); VARIANT propArray; - if (FAILED(pResultObject->Get(L"deviceProperties", 0, &propArray, nullptr, nullptr))) + if (FAILED(pResultObject->Get(L"deviceProperties", 0, &propArray, nullptr, nullptr))) { continue; + } on_scope_exit releasePropArray([&] { VariantClear(&propArray); }); if (propArray.vt != (VT_ARRAY | VT_UNKNOWN) || (propArray.parray->fFeatures & FADF_UNKNOWN) == 0 || propArray.parray->cDims != 1 || - propArray.parray->rgsabound[0].cElements != 2 - ) + propArray.parray->rgsabound[0].cElements != 2) { continue; + } uint8_t batt = 0; - for (LONG i = 0; i < 2; i++) - { + for (LONG i = 0; i < 2; i++) { IWbemClassObject* object = nullptr; - if (FAILED(SafeArrayGetElement(propArray.parray, &i, &object))) + if (FAILED(SafeArrayGetElement(propArray.parray, &i, &object))) { continue; + } FFWmiRecord rec(object); auto data = rec.get(L"Data"); - if (data.vt == VT_EMPTY) + if (data.vt == VT_EMPTY) { break; + } - if (i == 0) + if (i == 0) { batt = data.get(); - else - { + } else { FF_STRBUF_AUTO_DESTROY addr = ffStrbufCreateWSV(data.get()); // MAC address without colon - if (__builtin_expect(addr.length != 12, 0)) + if (__builtin_expect(addr.length != 12, 0)) { continue; + } - FF_LIST_FOR_EACH(FFBluetoothResult, bt, *devices) - { - if (bt->address.length != 12 + 5) + FF_LIST_FOR_EACH (FFBluetoothResult, bt, *devices) { + if (bt->address.length != 12 + 5) { continue; + } if (addr.chars[0] == bt->address.chars[0] && addr.chars[1] == bt->address.chars[1] && @@ -91,8 +95,7 @@ const char* ffBluetoothDetectBattery(FFlist* devices) addr.chars[8] == bt->address.chars[12] && addr.chars[9] == bt->address.chars[13] && addr.chars[10] == bt->address.chars[15] && - addr.chars[11] == bt->address.chars[16]) - { + addr.chars[11] == bt->address.chars[16]) { bt->battery = batt; break; } diff --git a/src/detection/bluetoothradio/bluetoothradio.c b/src/detection/bluetoothradio/bluetoothradio.c index 90a5b5453..117e2254f 100644 --- a/src/detection/bluetoothradio/bluetoothradio.c +++ b/src/detection/bluetoothradio/bluetoothradio.c @@ -53,60 +53,109 @@ #define BTH_MFG_ARUBA_NETWORKS 283 #define BTH_MFG_INTERNAL_USE 65535 -const char* ffBluetoothRadioGetVendor(uint32_t manufacturerId) -{ - switch (manufacturerId) - { - case BTH_MFG_ERICSSON: return "Ericsson"; - case BTH_MFG_NOKIA: return "Nokia"; - case BTH_MFG_INTEL: return "Intel"; - case BTH_MFG_IBM: return "IBM"; - case BTH_MFG_TOSHIBA: return "Toshiba"; - case BTH_MFG_3COM: return "3Com"; - case BTH_MFG_MICROSOFT: return "Microsoft"; - case BTH_MFG_LUCENT: return "Lucent"; - case BTH_MFG_MOTOROLA: return "Motorola"; - case BTH_MFG_INFINEON: return "Infineon"; - case BTH_MFG_CSR: return "CSR"; - case BTH_MFG_SILICONWAVE: return "Silicon-Wave"; - case BTH_MFG_DIGIANSWER: return "Digi-Answer"; - case BTH_MFG_TI: return "Ti"; - case BTH_MFG_PARTHUS: return "Parthus"; - case BTH_MFG_BROADCOM: return "Broadcom"; - case BTH_MFG_MITEL: return "Mitel"; - case BTH_MFG_WIDCOMM: return "Widcomm"; - case BTH_MFG_ZEEVO: return "Zeevo"; - case BTH_MFG_ATMEL: return "Atmel"; - case BTH_MFG_MITSIBUSHI: return "Mitsubishi"; - case BTH_MFG_RTX_TELECOM: return "RTX Telecom"; - case BTH_MFG_KC_TECHNOLOGY: return "KC Technology"; - case BTH_MFG_NEWLOGIC: return "Newlogic"; - case BTH_MFG_TRANSILICA: return "Transilica"; - case BTH_MFG_ROHDE_SCHWARZ: return "Rohde-Schwarz"; - case BTH_MFG_TTPCOM: return "TTPCom"; - case BTH_MFG_SIGNIA: return "Signia"; - case BTH_MFG_CONEXANT: return "Conexant"; - case BTH_MFG_QUALCOMM: return "Qualcomm"; - case BTH_MFG_INVENTEL: return "Inventel"; - case BTH_MFG_AVM_BERLIN: return "AVM Berlin"; - case BTH_MFG_BANDSPEED: return "Bandspeed"; - case BTH_MFG_MANSELLA: return "Mansella"; - case BTH_MFG_NEC: return "NEC"; - case BTH_MFG_WAVEPLUS_TECHNOLOGY_CO: return "Waveplus"; - case BTH_MFG_ALCATEL: return "Alcatel"; - case BTH_MFG_PHILIPS_SEMICONDUCTOR: return "Philips Semiconductors"; - case BTH_MFG_C_TECHNOLOGIES: return "C Technologies"; - case BTH_MFG_OPEN_INTERFACE: return "Open Interface"; - case BTH_MFG_RF_MICRO_DEVICES: return "RF Micro Devices"; - case BTH_MFG_HITACHI: return "Hitachi"; - case BTH_MFG_SYMBOL_TECHNOLOGIES: return "Symbol Technologies"; - case BTH_MFG_TENOVIS: return "Tenovis"; - case BTH_MFG_MACRONIX_INTERNATIONAL: return "Macronix International"; - case BTH_MFG_MARVELL: return "Marvell"; - case BTH_MFG_APPLE: return "Apple"; - case BTH_MFG_NORDIC_SEMICONDUCTORS_ASA: return "Nordic Semiconductor ASA"; - case BTH_MFG_ARUBA_NETWORKS: return "Aruba Networks"; - case BTH_MFG_INTERNAL_USE: return "Internal Use"; - default: return "Unknown"; +const char* ffBluetoothRadioGetVendor(uint32_t manufacturerId) { + switch (manufacturerId) { + case BTH_MFG_ERICSSON: + return "Ericsson"; + case BTH_MFG_NOKIA: + return "Nokia"; + case BTH_MFG_INTEL: + return "Intel"; + case BTH_MFG_IBM: + return "IBM"; + case BTH_MFG_TOSHIBA: + return "Toshiba"; + case BTH_MFG_3COM: + return "3Com"; + case BTH_MFG_MICROSOFT: + return "Microsoft"; + case BTH_MFG_LUCENT: + return "Lucent"; + case BTH_MFG_MOTOROLA: + return "Motorola"; + case BTH_MFG_INFINEON: + return "Infineon"; + case BTH_MFG_CSR: + return "CSR"; + case BTH_MFG_SILICONWAVE: + return "Silicon-Wave"; + case BTH_MFG_DIGIANSWER: + return "Digi-Answer"; + case BTH_MFG_TI: + return "Ti"; + case BTH_MFG_PARTHUS: + return "Parthus"; + case BTH_MFG_BROADCOM: + return "Broadcom"; + case BTH_MFG_MITEL: + return "Mitel"; + case BTH_MFG_WIDCOMM: + return "Widcomm"; + case BTH_MFG_ZEEVO: + return "Zeevo"; + case BTH_MFG_ATMEL: + return "Atmel"; + case BTH_MFG_MITSIBUSHI: + return "Mitsubishi"; + case BTH_MFG_RTX_TELECOM: + return "RTX Telecom"; + case BTH_MFG_KC_TECHNOLOGY: + return "KC Technology"; + case BTH_MFG_NEWLOGIC: + return "Newlogic"; + case BTH_MFG_TRANSILICA: + return "Transilica"; + case BTH_MFG_ROHDE_SCHWARZ: + return "Rohde-Schwarz"; + case BTH_MFG_TTPCOM: + return "TTPCom"; + case BTH_MFG_SIGNIA: + return "Signia"; + case BTH_MFG_CONEXANT: + return "Conexant"; + case BTH_MFG_QUALCOMM: + return "Qualcomm"; + case BTH_MFG_INVENTEL: + return "Inventel"; + case BTH_MFG_AVM_BERLIN: + return "AVM Berlin"; + case BTH_MFG_BANDSPEED: + return "Bandspeed"; + case BTH_MFG_MANSELLA: + return "Mansella"; + case BTH_MFG_NEC: + return "NEC"; + case BTH_MFG_WAVEPLUS_TECHNOLOGY_CO: + return "Waveplus"; + case BTH_MFG_ALCATEL: + return "Alcatel"; + case BTH_MFG_PHILIPS_SEMICONDUCTOR: + return "Philips Semiconductors"; + case BTH_MFG_C_TECHNOLOGIES: + return "C Technologies"; + case BTH_MFG_OPEN_INTERFACE: + return "Open Interface"; + case BTH_MFG_RF_MICRO_DEVICES: + return "RF Micro Devices"; + case BTH_MFG_HITACHI: + return "Hitachi"; + case BTH_MFG_SYMBOL_TECHNOLOGIES: + return "Symbol Technologies"; + case BTH_MFG_TENOVIS: + return "Tenovis"; + case BTH_MFG_MACRONIX_INTERNATIONAL: + return "Macronix International"; + case BTH_MFG_MARVELL: + return "Marvell"; + case BTH_MFG_APPLE: + return "Apple"; + case BTH_MFG_NORDIC_SEMICONDUCTORS_ASA: + return "Nordic Semiconductor ASA"; + case BTH_MFG_ARUBA_NETWORKS: + return "Aruba Networks"; + case BTH_MFG_INTERNAL_USE: + return "Internal Use"; + default: + return "Unknown"; } } diff --git a/src/detection/bluetoothradio/bluetoothradio.h b/src/detection/bluetoothradio/bluetoothradio.h index 8999b84a4..a3c120826 100644 --- a/src/detection/bluetoothradio/bluetoothradio.h +++ b/src/detection/bluetoothradio/bluetoothradio.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/bluetoothradio/option.h" -typedef struct FFBluetoothRadioResult -{ +typedef struct FFBluetoothRadioResult { FFstrbuf name; FFstrbuf address; FFstrbuf vendor; diff --git a/src/detection/bluetoothradio/bluetoothradio_linux.c b/src/detection/bluetoothradio/bluetoothradio_linux.c index 1583d43d0..83027c95d 100644 --- a/src/detection/bluetoothradio/bluetoothradio_linux.c +++ b/src/detection/bluetoothradio/bluetoothradio_linux.c @@ -2,8 +2,8 @@ #include "common/stringUtils.h" #ifdef FF_HAVE_DBUS -#include "common/dbus.h" -#include "common/io.h" +# include "common/dbus.h" +# include "common/io.h" /* Example dbus reply: array [ @@ -34,62 +34,61 @@ array [ ] */ -static const char* detectBluetoothProperty(FFBluetoothRadioResult* device, FFDBusData* dbus, DBusMessageIter* iter) -{ - if(dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) +static const char* detectBluetoothProperty(FFBluetoothRadioResult* device, FFDBusData* dbus, DBusMessageIter* iter) { + if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) { return "Expected dict entry"; + } DBusMessageIter dictIter; dbus->lib->ffdbus_message_iter_recurse(iter, &dictIter); - if(dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_STRING) + if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_STRING) { return "Expected dict entry key to be a string"; + } const char* deviceProperty; dbus->lib->ffdbus_message_iter_get_basic(&dictIter, &deviceProperty); dbus->lib->ffdbus_message_iter_next(&dictIter); - if(ffStrEquals(deviceProperty, "Address")) + if (ffStrEquals(deviceProperty, "Address")) { ffDBusGetString(dbus, &dictIter, &device->address); - else if(ffStrEquals(deviceProperty, "Alias")) + } else if (ffStrEquals(deviceProperty, "Alias")) { ffDBusGetString(dbus, &dictIter, &device->name); - else if(ffStrEquals(deviceProperty, "Manufacturer")) - { + } else if (ffStrEquals(deviceProperty, "Manufacturer")) { uint32_t vendorId; - if (ffDBusGetUint(dbus, &dictIter, &vendorId)) + if (ffDBusGetUint(dbus, &dictIter, &vendorId)) { ffStrbufSetStatic(&device->vendor, ffBluetoothRadioGetVendor(vendorId)); - } - else if(ffStrEquals(deviceProperty, "Version")) + } + } else if (ffStrEquals(deviceProperty, "Version")) { ffDBusGetUint(dbus, &dictIter, (uint32_t*) &device->lmpVersion); - else if(ffStrEquals(deviceProperty, "Powered")) + } else if (ffStrEquals(deviceProperty, "Powered")) { ffDBusGetBool(dbus, &dictIter, &device->enabled); - else if(ffStrEquals(deviceProperty, "Discoverable")) + } else if (ffStrEquals(deviceProperty, "Discoverable")) { ffDBusGetBool(dbus, &dictIter, &device->discoverable); - else if(ffStrEquals(deviceProperty, "Pairable")) + } else if (ffStrEquals(deviceProperty, "Pairable")) { ffDBusGetBool(dbus, &dictIter, &device->connectable); + } return NULL; } -static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const char* hciName, FFDBusData* dbus) -{ +static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const char* hciName, FFDBusData* dbus) { 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", NULL); - if(!properties) + if (!properties) { return "Failed to call org.freedesktop.DBus.Properties.GetAll"; + } DBusMessageIter rootIter; - if(!dbus->lib->ffdbus_message_iter_init(properties, &rootIter)) - { + if (!dbus->lib->ffdbus_message_iter_init(properties, &rootIter)) { dbus->lib->ffdbus_message_unref(properties); return "Failed to get root iterator of org.freedesktop.DBus.Properties.GetAll"; } - if(dbus->lib->ffdbus_message_iter_get_arg_type(&rootIter) != DBUS_TYPE_ARRAY) - { + if (dbus->lib->ffdbus_message_iter_get_arg_type(&rootIter) != DBUS_TYPE_ARRAY) { dbus->lib->ffdbus_message_unref(properties); return "Expected array"; } @@ -97,8 +96,7 @@ static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const cha DBusMessageIter arrayIter; dbus->lib->ffdbus_message_iter_recurse(&rootIter, &arrayIter); - do - { + do { detectBluetoothProperty(device, dbus, &arrayIter); } while (dbus->lib->ffdbus_message_iter_next(&arrayIter)); @@ -106,25 +104,27 @@ static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const cha return NULL; } -static const char* detectBluetooth(FFlist* devices) -{ +static const char* detectBluetooth(FFlist* devices) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth"); - if(dirp == NULL) + if (dirp == NULL) { return "Failed to open /sys/class/bluetooth"; + } FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; const char* error = ffDBusLoadData(DBUS_BUS_SYSTEM, &dbus); - if(error) + if (error) { return error; + } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } - if (strchr(entry->d_name, ':') != NULL) // ignore connected devices + if (strchr(entry->d_name, ':') != NULL) { // ignore connected devices continue; + } FFBluetoothRadioResult* device = ffListAdd(devices); ffStrbufInit(&device->name); @@ -140,12 +140,11 @@ static const char* detectBluetooth(FFlist* devices) #endif -const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) -{ - #ifdef FF_HAVE_DBUS - return detectBluetooth(devices); - #else - FF_UNUSED(devices) - return "Fastfetch was compiled without DBus support"; - #endif +const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) { +#ifdef FF_HAVE_DBUS + return detectBluetooth(devices); +#else + FF_UNUSED(devices) + return "Fastfetch was compiled without DBus support"; +#endif } diff --git a/src/detection/bluetoothradio/bluetoothradio_nosupport.c b/src/detection/bluetoothradio/bluetoothradio_nosupport.c index 1df1ce0e3..6176427be 100644 --- a/src/detection/bluetoothradio/bluetoothradio_nosupport.c +++ b/src/detection/bluetoothradio/bluetoothradio_nosupport.c @@ -1,6 +1,5 @@ #include "bluetoothradio.h" -const char* ffDetectBluetoothRadio(FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothRadioResult */) -{ +const char* ffDetectBluetoothRadio(FF_MAYBE_UNUSED FFlist* devices /* FFBluetoothRadioResult */) { return "Not supported on this platform"; } diff --git a/src/detection/bluetoothradio/bluetoothradio_windows.c b/src/detection/bluetoothradio/bluetoothradio_windows.c index 3d3d27c87..4d407fa8d 100644 --- a/src/detection/bluetoothradio/bluetoothradio_windows.c +++ b/src/detection/bluetoothradio/bluetoothradio_windows.c @@ -9,13 +9,12 @@ // #include -#define BTH_IOCTL_BASE 0 -#define BTH_CTL(id) CTL_CODE(FILE_DEVICE_BLUETOOTH, (id), METHOD_BUFFERED, FILE_ANY_ACCESS) -#define IOCTL_BTH_GET_LOCAL_INFO BTH_CTL(BTH_IOCTL_BASE+0x00) -#define LMP_LE_SUPPORTED(x) ((x >> 38) & 1) +#define BTH_IOCTL_BASE 0 +#define BTH_CTL(id) CTL_CODE(FILE_DEVICE_BLUETOOTH, (id), METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_BTH_GET_LOCAL_INFO BTH_CTL(BTH_IOCTL_BASE + 0x00) +#define LMP_LE_SUPPORTED(x) ((x >> 38) & 1) -typedef struct _BTH_RADIO_INFO -{ +typedef struct _BTH_RADIO_INFO { // Supported LMP features of the radio. Use LMP_XXX() to extract // the desired bits. ULONGLONG lmpSupportedFeatures; @@ -30,10 +29,9 @@ typedef struct _BTH_RADIO_INFO UCHAR lmpVersion; } __attribute__((__packed__)) BTH_RADIO_INFO; -typedef struct _BTH_LOCAL_RADIO_INFO -{ +typedef struct _BTH_LOCAL_RADIO_INFO { // Local BTH_ADDR, class of device, and radio name - BTH_DEVICE_INFO localInfo; + BTH_DEVICE_INFO localInfo; // Combo of LOCAL_RADIO_XXX values ULONG flags; @@ -51,8 +49,7 @@ static_assert(sizeof(BTH_LOCAL_RADIO_INFO) == 292, "BTH_LOCAL_RADIO_INFO should #pragma GCC diagnostic ignored "-Wpointer-sign" -const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) -{ +const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) { // Actually bluetoothapis.dll, but it's missing on Windows 7 FF_LIBRARY_LOAD_MESSAGE(bluetoothapis, "bluetoothapis.dll", 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothFindFirstRadio) @@ -63,33 +60,28 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) HANDLE hRadio = NULL; HBLUETOOTH_DEVICE_FIND hFind = ffBluetoothFindFirstRadio(&(BLUETOOTH_FIND_RADIO_PARAMS) { - .dwSize = sizeof(BLUETOOTH_FIND_RADIO_PARAMS) - }, &hRadio); - if(!hFind) - { - if (GetLastError() == ERROR_NO_MORE_ITEMS) + .dwSize = sizeof(BLUETOOTH_FIND_RADIO_PARAMS)}, + &hRadio); + if (!hFind) { + if (GetLastError() == ERROR_NO_MORE_ITEMS) { return "No Bluetooth radios found or service disabled"; - else + } else { return "BluetoothFindFirstRadio() failed"; + } } do { BTH_LOCAL_RADIO_INFO blri; DWORD returned; - if (!DeviceIoControl(hRadio, IOCTL_BTH_GET_LOCAL_INFO, NULL, 0, &blri, sizeof(blri), &returned, NULL)) + if (!DeviceIoControl(hRadio, IOCTL_BTH_GET_LOCAL_INFO, NULL, 0, &blri, sizeof(blri), &returned, NULL)) { continue; + } FFBluetoothRadioResult* device = ffListAdd(devices); ffStrbufInitS(&device->name, blri.localInfo.name); - BLUETOOTH_ADDRESS_STRUCT addr = { .ullLong = blri.localInfo.address }; - ffStrbufInitF(&device->address, "%02X:%02X:%02X:%02X:%02X:%02X", - addr.rgBytes[5], - addr.rgBytes[4], - addr.rgBytes[3], - addr.rgBytes[2], - addr.rgBytes[1], - addr.rgBytes[0]); + BLUETOOTH_ADDRESS_STRUCT addr = {.ullLong = blri.localInfo.address}; + ffStrbufInitF(&device->address, "%02X:%02X:%02X:%02X:%02X:%02X", addr.rgBytes[5], addr.rgBytes[4], addr.rgBytes[3], addr.rgBytes[2], addr.rgBytes[1], addr.rgBytes[0]); device->lmpVersion = blri.radioInfo.lmpVersion; device->lmpSubversion = blri.radioInfo.lmpSubversion; diff --git a/src/detection/board/board.h b/src/detection/board/board.h index f41e60e13..c092a7f63 100644 --- a/src/detection/board/board.h +++ b/src/detection/board/board.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/board/option.h" -typedef struct FFBoardResult -{ +typedef struct FFBoardResult { FFstrbuf name; FFstrbuf vendor; FFstrbuf version; diff --git a/src/detection/board/board_android.c b/src/detection/board/board_android.c index 64e917e6a..b5978d1f2 100644 --- a/src/detection/board/board_android.c +++ b/src/detection/board/board_android.c @@ -1,9 +1,9 @@ #include "board.h" #include "common/settings.h" -const char* ffDetectBoard(FFBoardResult* board) -{ - if (!ffSettingsGetAndroidProperty("ro.product.board", &board->name)) +const char* ffDetectBoard(FFBoardResult* board) { + if (!ffSettingsGetAndroidProperty("ro.product.board", &board->name)) { ffSettingsGetAndroidProperty("ro.board.platform", &board->name); + } return NULL; } diff --git a/src/detection/board/board_apple.c b/src/detection/board/board_apple.c index 6e93165b1..e7c4d381d 100644 --- a/src/detection/board/board_apple.c +++ b/src/detection/board/board_apple.c @@ -2,29 +2,31 @@ #include "common/apple/cf_helpers.h" -const char* ffDetectBoard(FFBoardResult* result) -{ +const char* ffDetectBoard(FFBoardResult* result) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t service = IOServiceGetMatchingService(MACH_PORT_NULL, IOServiceMatching("IOPlatformExpertDevice")); - if (!service) + if (!service) { return "No IOPlatformExpertDevice found"; + } FF_CFTYPE_AUTO_RELEASE CFTypeRef boardId = IORegistryEntryCreateCFProperty(service, CFSTR("board-id"), kCFAllocatorDefault, kNilOptions); - if (boardId) + if (boardId) { ffCfStrGetString(boardId, &result->name); - else - { + } else { io_name_t name; - if (IORegistryEntryGetName(service, name) == kIOReturnSuccess) + if (IORegistryEntryGetName(service, name) == kIOReturnSuccess) { ffStrbufSetS(&result->name, name); + } } FF_CFTYPE_AUTO_RELEASE CFStringRef version = IORegistryEntryCreateCFProperty(service, CFSTR("version"), kCFAllocatorDefault, kNilOptions); - if (version) + if (version) { ffCfStrGetString(version, &result->version); + } FF_CFTYPE_AUTO_RELEASE CFTypeRef manufacturer = IORegistryEntryCreateCFProperty(service, CFSTR("manufacturer"), kCFAllocatorDefault, kNilOptions); - if (manufacturer) + if (manufacturer) { ffCfStrGetString(manufacturer, &result->vendor); + } return NULL; } diff --git a/src/detection/board/board_bsd.c b/src/detection/board/board_bsd.c index 537ca35ad..c27a469f0 100644 --- a/src/detection/board/board_bsd.c +++ b/src/detection/board/board_bsd.c @@ -2,8 +2,7 @@ #include "common/settings.h" #include "common/smbiosHelper.h" -const char* ffDetectBoard(FFBoardResult* result) -{ +const char* ffDetectBoard(FFBoardResult* result) { ffSettingsGetFreeBSDKenv("smbios.planar.product", &result->name); ffCleanUpSmbiosValue(&result->name); ffSettingsGetFreeBSDKenv("smbios.planar.serial", &result->serial); diff --git a/src/detection/board/board_linux.c b/src/detection/board/board_linux.c index e9ebb3d18..f560df05a 100644 --- a/src/detection/board/board_linux.c +++ b/src/detection/board/board_linux.c @@ -2,29 +2,21 @@ #include "common/io.h" #include "common/smbiosHelper.h" -const char* ffDetectBoard(FFBoardResult* board) -{ - if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/board_name", "/sys/class/dmi/id/board_name", &board->name)) - { +const char* ffDetectBoard(FFBoardResult* board) { + if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/board_name", "/sys/class/dmi/id/board_name", &board->name)) { ffGetSmbiosValue("/sys/devices/virtual/dmi/id/board_serial", "/sys/class/dmi/id/board_serial", &board->serial); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/board_vendor", "/sys/class/dmi/id/board_vendor", &board->vendor); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/board_version", "/sys/class/dmi/id/board_version", &board->version); - } - else if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/baseboard/product", &board->name)) - { + } else if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/baseboard/product", &board->name)) { ffStrbufTrimRight(&board->name, '\0'); - if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/baseboard/manufacturer", &board->vendor)) + if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/baseboard/manufacturer", &board->vendor)) { ffStrbufTrimRight(&board->vendor, '\0'); - } - else if (ffReadFileBuffer("/sys/firmware/devicetree/base/board", &board->name)) - { + } + } else if (ffReadFileBuffer("/sys/firmware/devicetree/base/board", &board->name)) { ffStrbufTrimRightSpace(&board->name); - } - else if (ffReadFileBuffer("/sys/firmware/devicetree/base/compatible", &board->vendor)) - { + } else if (ffReadFileBuffer("/sys/firmware/devicetree/base/compatible", &board->vendor)) { uint32_t comma = ffStrbufFirstIndexC(&board->vendor, ','); - if (comma < board->vendor.length) - { + if (comma < board->vendor.length) { ffStrbufSetS(&board->name, board->vendor.chars + comma + 1); ffStrbufTrimRightSpace(&board->name); ffStrbufSubstrBefore(&board->vendor, comma); diff --git a/src/detection/board/board_nbsd.c b/src/detection/board/board_nbsd.c index bfe419020..a78dbb493 100644 --- a/src/detection/board/board_nbsd.c +++ b/src/detection/board/board_nbsd.c @@ -2,16 +2,19 @@ #include "common/sysctl.h" #include "common/smbiosHelper.h" -const char* ffDetectBoard(FFBoardResult* board) -{ - if (ffSysctlGetString("machdep.dmi.board-product", &board->name) == NULL) +const char* ffDetectBoard(FFBoardResult* board) { + if (ffSysctlGetString("machdep.dmi.board-product", &board->name) == NULL) { ffCleanUpSmbiosValue(&board->name); - if (ffSysctlGetString("machdep.dmi.board-version", &board->version) == NULL) + } + if (ffSysctlGetString("machdep.dmi.board-version", &board->version) == NULL) { ffCleanUpSmbiosValue(&board->version); - if (ffSysctlGetString("machdep.dmi.board-vendor", &board->vendor) == NULL) + } + if (ffSysctlGetString("machdep.dmi.board-vendor", &board->vendor) == NULL) { ffCleanUpSmbiosValue(&board->vendor); - if (ffSysctlGetString("machdep.dmi.board-serial", &board->serial) == NULL) + } + if (ffSysctlGetString("machdep.dmi.board-serial", &board->serial) == NULL) { ffCleanUpSmbiosValue(&board->serial); + } return NULL; } diff --git a/src/detection/board/board_nosupport.c b/src/detection/board/board_nosupport.c index bcf451d5b..3865b652e 100644 --- a/src/detection/board/board_nosupport.c +++ b/src/detection/board/board_nosupport.c @@ -1,6 +1,5 @@ #include "board.h" -const char* ffDetectBoard(FF_MAYBE_UNUSED FFBoardResult* board) -{ +const char* ffDetectBoard(FF_MAYBE_UNUSED FFBoardResult* board) { return "Not supported on this platform"; } diff --git a/src/detection/board/board_windows.c b/src/detection/board/board_windows.c index aeb7176c6..f731fe336 100644 --- a/src/detection/board/board_windows.c +++ b/src/detection/board/board_windows.c @@ -1,35 +1,35 @@ #include "board.h" #include "common/smbiosHelper.h" -typedef struct FFSmbiosBaseboard -{ +typedef struct FFSmbiosBaseboard { FFSmbiosHeader Header; - uint8_t Manufacturer; // string - uint8_t Product; // string - uint8_t Version; // string - uint8_t SerialNumber; // string - uint8_t AssetTag; // string - uint8_t FeatureFlags; // bit field - uint8_t LocationInChassis; // string - uint16_t ChassisHandle; // varies - uint8_t BoardType; // enum + uint8_t Manufacturer; // string + uint8_t Product; // string + uint8_t Version; // string + uint8_t SerialNumber; // string + uint8_t AssetTag; // string + uint8_t FeatureFlags; // bit field + uint8_t LocationInChassis; // string + uint16_t ChassisHandle; // varies + uint8_t BoardType; // enum uint8_t NumberOfContainedObjectHandles; // varies - uint16_t ContainedObjectHandles[]; // varies + uint16_t ContainedObjectHandles[]; // varies } __attribute__((__packed__)) FFSmbiosBaseboard; static_assert(offsetof(FFSmbiosBaseboard, ContainedObjectHandles) == 0x0F, "FFSmbiosBaseboard: Wrong struct alignment"); -const char* ffDetectBoard(FFBoardResult* board) -{ +const char* ffDetectBoard(FFBoardResult* board) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosBaseboard* data = (const FFSmbiosBaseboard*) (*smbiosTable)[FF_SMBIOS_TYPE_BASEBOARD_INFO]; - if (!data) + if (!data) { return "Baseboard information section is not found in SMBIOS data"; + } const char* strings = (const char*) data + data->Header.Length; diff --git a/src/detection/bootmgr/bootmgr.c b/src/detection/bootmgr/bootmgr.c index 47c9a418a..31838d490 100644 --- a/src/detection/bootmgr/bootmgr.c +++ b/src/detection/bootmgr/bootmgr.c @@ -1,23 +1,17 @@ #include "efi_helper.h" -static inline uint8_t evBits(uint16_t val, uint8_t mask, uint8_t shift) -{ +static inline uint8_t evBits(uint16_t val, uint8_t mask, uint8_t shift) { return (uint8_t) ((val & (mask << shift)) >> shift); } -static void ffEfiUcs2ToUtf8(const uint16_t *const chars, FFstrbuf* result) -{ - for (uint32_t i = 0; chars[i]; i++) - { - if (chars[i] <= 0x007f) +static void ffEfiUcs2ToUtf8(const uint16_t* const chars, FFstrbuf* result) { + for (uint32_t i = 0; chars[i]; i++) { + if (chars[i] <= 0x007f) { ffStrbufAppendC(result, (char) chars[i]); - else if (chars[i] > 0x007f && chars[i] <= 0x07ff) - { + } else if (chars[i] > 0x007f && chars[i] <= 0x07ff) { ffStrbufAppendC(result, (char) (0xc0 | evBits(chars[i], 0x1f, 6))); ffStrbufAppendC(result, (char) (0x80 | evBits(chars[i], 0x3f, 0))); - } - else - { + } else { ffStrbufAppendC(result, (char) (0xe0 | evBits(chars[i], 0xf, 12))); ffStrbufAppendC(result, (char) (0x80 | evBits(chars[i], 0x3f, 6))); ffStrbufAppendC(result, (char) (0x80 | evBits(chars[i], 0x3f, 0))); @@ -25,21 +19,21 @@ static void ffEfiUcs2ToUtf8(const uint16_t *const chars, FFstrbuf* result) } } -bool ffEfiFillLoadOption(const FFEfiLoadOption* efiOption, FFBootmgrResult* result) -{ +bool ffEfiFillLoadOption(const FFEfiLoadOption* efiOption, FFBootmgrResult* result) { uint32_t descLen = 0; - while (efiOption->Description[descLen]) ++descLen; + while (efiOption->Description[descLen]) { + ++descLen; + } - if (descLen) + if (descLen) { ffEfiUcs2ToUtf8(efiOption->Description, &result->name); + } for ( ffEfiDevicePathProtocol* filePathList = (ffEfiDevicePathProtocol*) &efiOption->Description[descLen + 1]; filePathList->Type != 0x7F; // End of Hardware Device Path - filePathList = (ffEfiDevicePathProtocol*) ((uint8_t*) filePathList + filePathList->Length)) - { - if (filePathList->Type == 4 && filePathList->SubType == 4) - { + filePathList = (ffEfiDevicePathProtocol*) ((uint8_t*) filePathList + filePathList->Length)) { + if (filePathList->Type == 4 && filePathList->SubType == 4) { // https://uefi.org/specs/UEFI/2.10/10_Protocols_Device_Path_Protocol.html#file-path-media-device-path ffEfiUcs2ToUtf8((uint16_t*) filePathList->SpecificDevicePathData, &result->firmware); return true; diff --git a/src/detection/bootmgr/bootmgr.h b/src/detection/bootmgr/bootmgr.h index e0fbcddcc..055b0ee51 100644 --- a/src/detection/bootmgr/bootmgr.h +++ b/src/detection/bootmgr/bootmgr.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/bootmgr/option.h" -typedef struct FFBootmgrResult -{ +typedef struct FFBootmgrResult { FFstrbuf name; FFstrbuf firmware; uint16_t order; diff --git a/src/detection/bootmgr/bootmgr_apple.c b/src/detection/bootmgr/bootmgr_apple.c index 2e00f7f23..25f4a826b 100644 --- a/src/detection/bootmgr/bootmgr_apple.c +++ b/src/detection/bootmgr/bootmgr_apple.c @@ -4,43 +4,48 @@ #include -static const char* detectSecureBoot(bool* result) -{ - #if __aarch64__ +static const char* detectSecureBoot(bool* result) { +#if __aarch64__ FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryDevice = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/chosen"); - if (!entryDevice) + if (!entryDevice) { return "IORegistryEntryFromPath() failed"; + } FF_CFTYPE_AUTO_RELEASE CFTypeRef prop = IORegistryEntryCreateCFProperty(entryDevice, CFSTR("secure-boot"), kCFAllocatorDefault, 0); - if (!prop) + if (!prop) { return "IORegistryEntryCreateCFProperty() failed"; + } - if (CFGetTypeID(prop) != CFDataGetTypeID() || CFDataGetLength((CFDataRef) prop) == 0) + if (CFGetTypeID(prop) != CFDataGetTypeID() || CFDataGetLength((CFDataRef) prop) == 0) { return "Invalid secure-boot property"; + } *result = (bool) *CFDataGetBytePtr((CFDataRef) prop); - #else +#else FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryDevice = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/options"); - if (!entryDevice) + if (!entryDevice) { return "IORegistryEntryFromPath() failed"; + } FF_CFTYPE_AUTO_RELEASE CFTypeRef prop = IORegistryEntryCreateCFProperty(entryDevice, CFSTR("94b73556-2197-4702-82a8-3e1337dafbfb:AppleSecureBootPolicy"), kCFAllocatorDefault, 0); - if (!prop) + if (!prop) { return "IORegistryEntryCreateCFProperty() failed"; + } - if (CFGetTypeID(prop) != CFDataGetTypeID() || CFDataGetLength((CFDataRef) prop) == 0) + if (CFGetTypeID(prop) != CFDataGetTypeID() || CFDataGetLength((CFDataRef) prop) == 0) { return "Invalid secure-boot property"; + } *result = *CFDataGetBytePtr((CFDataRef) prop) != 0x02 /* Permissive Security */; - #endif +#endif return NULL; } -const char* ffDetectBootmgr(FFBootmgrResult* result) -{ - if (ffPathExists("/System/Library/CoreServices/boot.efi", FF_PATHTYPE_FILE)) +const char* ffDetectBootmgr(FFBootmgrResult* result) { + if (ffPathExists("/System/Library/CoreServices/boot.efi", FF_PATHTYPE_FILE)) { ffStrbufSetStatic(&result->firmware, "/System/Library/CoreServices/boot.efi"); + } ffStrbufSetStatic(&result->name, "iBoot"); diff --git a/src/detection/bootmgr/bootmgr_bsd.c b/src/detection/bootmgr/bootmgr_bsd.c index c73485470..0815af057 100644 --- a/src/detection/bootmgr/bootmgr_bsd.c +++ b/src/detection/bootmgr/bootmgr_bsd.c @@ -3,26 +3,27 @@ #include "common/io.h" #ifdef __OpenBSD__ - #include +# include #else - #include +# include #endif #include #include #include #ifdef __NetBSD__ - typedef uint16_t efi_char; +typedef uint16_t efi_char; #endif #ifndef EFI_GLOBAL_VARIABLE - #define EFI_GLOBAL_VARIABLE { 0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, { 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c } } +# define EFI_GLOBAL_VARIABLE {0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, {0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c}} #endif -const char* ffDetectBootmgr(FFBootmgrResult* result) -{ +const char* ffDetectBootmgr(FFBootmgrResult* result) { FF_AUTO_CLOSE_FD int efifd = open("/dev/efi", O_RDWR | O_CLOEXEC); - if (efifd < 0) return "open(/dev/efi) failed"; + if (efifd < 0) { + return "open(/dev/efi) failed"; + } alignas(uint16_t) uint8_t buffer[2048]; struct efi_var_ioc ioc = { @@ -31,28 +32,31 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) }; ioc.datasize = sizeof(buffer); - ioc.name = (efi_char[]){ 'B', 'o', 'o', 't', 'C', 'u', 'r', 'r', 'e', 'n', 't', '\0' }; + ioc.name = (efi_char[]) {'B', 'o', 'o', 't', 'C', 'u', 'r', 'r', 'e', 'n', 't', '\0'}; ioc.namesize = sizeof("BootCurrent") * 2; - if (ioctl(efifd, EFIIOC_VAR_GET, &ioc) < 0 || ioc.datasize != 2) + if (ioctl(efifd, EFIIOC_VAR_GET, &ioc) < 0 || ioc.datasize != 2) { return "ioctl(EFIIOC_VAR_GET, BootCurrent) failed"; + } - result->order = *(uint16_t*)buffer; + result->order = *(uint16_t*) buffer; unsigned char hex[5]; snprintf((char*) hex, sizeof(hex), "%04X", result->order); ioc.datasize = sizeof(buffer); - ioc.name = (efi_char[]){ 'B', 'o', 'o', 't', hex[0], hex[1], hex[2], hex[3], '\0' }; + ioc.name = (efi_char[]) {'B', 'o', 'o', 't', hex[0], hex[1], hex[2], hex[3], '\0'}; ioc.namesize = sizeof("Boot####") * 2; - if (ioctl(efifd, EFIIOC_VAR_GET, &ioc) < 0 || ioc.datasize == sizeof(buffer)) + if (ioctl(efifd, EFIIOC_VAR_GET, &ioc) < 0 || ioc.datasize == sizeof(buffer)) { return "ioctl(EFIIOC_VAR_GET, Boot####) failed"; + } - ffEfiFillLoadOption((FFEfiLoadOption *)buffer, result); + ffEfiFillLoadOption((FFEfiLoadOption*) buffer, result); - ioc.name = (efi_char[]){ 'S', 'e', 'c', 'u', 'r', 'e', 'B', 'o', 'o', 't', '\0' }; + ioc.name = (efi_char[]) {'S', 'e', 'c', 'u', 'r', 'e', 'B', 'o', 'o', 't', '\0'}; ioc.namesize = sizeof("SecureBoot") * 2; ioc.datasize = sizeof(buffer); - if (ioctl(efifd, EFIIOC_VAR_GET, &ioc) == 0 && ioc.datasize == 1) + if (ioctl(efifd, EFIIOC_VAR_GET, &ioc) == 0 && ioc.datasize == 1) { result->secureBoot = !!buffer[0]; + } return NULL; } diff --git a/src/detection/bootmgr/bootmgr_linux.c b/src/detection/bootmgr/bootmgr_linux.c index e2aebcd42..0fd019a2f 100644 --- a/src/detection/bootmgr/bootmgr_linux.c +++ b/src/detection/bootmgr/bootmgr_linux.c @@ -6,26 +6,27 @@ #define FF_EFIVARS_PATH_PREFIX "/sys/firmware/efi/efivars/" -const char* ffDetectBootmgr(FFBootmgrResult* result) -{ +const char* ffDetectBootmgr(FFBootmgrResult* result) { alignas(uint16_t) uint8_t buffer[2048]; - if (ffReadFileData(FF_EFIVARS_PATH_PREFIX "BootCurrent-" FF_EFI_GLOBAL_GUID, sizeof(buffer), buffer) != 6) + if (ffReadFileData(FF_EFIVARS_PATH_PREFIX "BootCurrent-" FF_EFI_GLOBAL_GUID, sizeof(buffer), buffer) != 6) { return "Failed to read efivar: BootCurrent"; + } - - result->order = *(uint16_t *)&buffer[4]; + result->order = *(uint16_t*) &buffer[4]; snprintf((char*) buffer, sizeof(buffer), FF_EFIVARS_PATH_PREFIX "Boot%04X-" FF_EFI_GLOBAL_GUID, result->order); ssize_t size = ffReadFileData((const char*) buffer, sizeof(buffer), buffer); - if (size < 5 + (int) sizeof(FFEfiLoadOption) || size == (ssize_t) sizeof(buffer)) + if (size < 5 + (int) sizeof(FFEfiLoadOption) || size == (ssize_t) sizeof(buffer)) { return "Failed to read efivar: Boot####"; + } - ffEfiFillLoadOption((FFEfiLoadOption *)&buffer[4], result); + ffEfiFillLoadOption((FFEfiLoadOption*) &buffer[4], result); - if (ffReadFileData(FF_EFIVARS_PATH_PREFIX "SecureBoot-" FF_EFI_GLOBAL_GUID, sizeof(buffer), buffer) >= 5) + if (ffReadFileData(FF_EFIVARS_PATH_PREFIX "SecureBoot-" FF_EFI_GLOBAL_GUID, sizeof(buffer), buffer) >= 5) { result->secureBoot = buffer[4] == 1; + } return NULL; } diff --git a/src/detection/bootmgr/bootmgr_nosupport.c b/src/detection/bootmgr/bootmgr_nosupport.c index a61cce63b..324e3eafa 100644 --- a/src/detection/bootmgr/bootmgr_nosupport.c +++ b/src/detection/bootmgr/bootmgr_nosupport.c @@ -1,6 +1,5 @@ #include "bootmgr.h" -const char* ffDetectBootmgr(FF_MAYBE_UNUSED FFBootmgrResult* result) -{ +const char* ffDetectBootmgr(FF_MAYBE_UNUSED FFBootmgrResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/bootmgr/bootmgr_windows.c b/src/detection/bootmgr/bootmgr_windows.c index 17b3b784a..86206925f 100644 --- a/src/detection/bootmgr/bootmgr_windows.c +++ b/src/detection/bootmgr/bootmgr_windows.c @@ -6,61 +6,69 @@ #include #include -const char* enablePrivilege(const wchar_t* privilege) -{ +const char* enablePrivilege(const wchar_t* privilege) { FF_AUTO_CLOSE_FD HANDLE token = NULL; - if (!NT_SUCCESS(NtOpenProcessToken(NtCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))) + if (!NT_SUCCESS(NtOpenProcessToken(NtCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))) { return "NtOpenProcessToken() failed"; + } TOKEN_PRIVILEGES tp = { .PrivilegeCount = 1, .Privileges = { - (LUID_AND_ATTRIBUTES) { .Attributes = SE_PRIVILEGE_ENABLED } - }, + (LUID_AND_ATTRIBUTES) {.Attributes = SE_PRIVILEGE_ENABLED}}, }; - if (!LookupPrivilegeValueW(NULL, privilege, &tp.Privileges[0].Luid)) + if (!LookupPrivilegeValueW(NULL, privilege, &tp.Privileges[0].Luid)) { return "LookupPrivilegeValue() failed"; + } NTSTATUS status = NtAdjustPrivilegesToken(token, false, &tp, sizeof(tp), NULL, NULL); - if (!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { return "NtAdjustPrivilegesToken() failed"; + } - if (status == STATUS_NOT_ALL_ASSIGNED) + if (status == STATUS_NOT_ALL_ASSIGNED) { return "The token does not have the specified privilege; try sudo please"; + } return NULL; } -const char* ffDetectBootmgr(FFBootmgrResult* result) -{ +const char* ffDetectBootmgr(FFBootmgrResult* result) { const char* err = enablePrivilege(L"SeSystemEnvironmentPrivilege"); - if (err != NULL) + if (err != NULL) { return err; + } GUID efiGlobalGuid; - if (!NT_SUCCESS(RtlGUIDFromString(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"{" FF_EFI_GLOBAL_GUID L"}"), &efiGlobalGuid))) + if (!NT_SUCCESS(RtlGUIDFromString(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"{" FF_EFI_GLOBAL_GUID L"}"), &efiGlobalGuid))) { return "RtlGUIDFromString() failed"; + } ULONG size = sizeof(result->order); - if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"BootCurrent"), &efiGlobalGuid, &result->order, &size, NULL))) + if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"BootCurrent"), &efiGlobalGuid, &result->order, &size, NULL))) { return "NtQuerySystemEnvironmentValueEx(BootCurrent) failed"; - if (size != sizeof(result->order)) + } + if (size != sizeof(result->order)) { return "NtQuerySystemEnvironmentValueEx(BootCurrent) returned unexpected size"; + } uint8_t buffer[2048]; wchar_t key[9]; swprintf(key, ARRAY_SIZE(key), L"Boot%04X", result->order); size = sizeof(buffer); - if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(key), &efiGlobalGuid, buffer, &size, NULL))) + if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(key), &efiGlobalGuid, buffer, &size, NULL))) { return "NtQuerySystemEnvironmentValueEx(Boot####) failed"; - if (size < sizeof(FFEfiLoadOption) || size == ARRAY_SIZE(buffer)) + } + if (size < sizeof(FFEfiLoadOption) || size == ARRAY_SIZE(buffer)) { return "NtQuerySystemEnvironmentValueEx(Boot####) returned unexpected size"; + } - ffEfiFillLoadOption((FFEfiLoadOption *)buffer, result); + ffEfiFillLoadOption((FFEfiLoadOption*) buffer, result); SYSTEM_SECUREBOOT_INFORMATION ssi; - if (NT_SUCCESS(NtQuerySystemInformation(SystemSecureBootInformation, &ssi, sizeof(ssi), NULL))) + if (NT_SUCCESS(NtQuerySystemInformation(SystemSecureBootInformation, &ssi, sizeof(ssi), NULL))) { result->secureBoot = ssi.SecureBootEnabled; + } return NULL; } diff --git a/src/detection/bootmgr/efi_helper.h b/src/detection/bootmgr/efi_helper.h index d650c8e97..b52ec8a81 100644 --- a/src/detection/bootmgr/efi_helper.h +++ b/src/detection/bootmgr/efi_helper.h @@ -1,8 +1,7 @@ #include "bootmgr.h" // https://uefi.org/specs/UEFI/2.10/10_Protocols_Device_Path_Protocol.html#generic-device-path-structures -typedef struct ffEfiDevicePathProtocol -{ +typedef struct ffEfiDevicePathProtocol { uint8_t Type; uint8_t SubType; uint16_t Length; @@ -10,8 +9,7 @@ typedef struct ffEfiDevicePathProtocol } ffEfiDevicePathProtocol; // https://uefi.org/specs/UEFI/2.10/03_Boot_Manager.html#load-options -typedef struct FFEfiLoadOption -{ +typedef struct FFEfiLoadOption { uint32_t Attributes; uint16_t FilePathListLength; uint16_t Description[]; diff --git a/src/detection/brightness/brightness.h b/src/detection/brightness/brightness.h index 5f2f1405a..ae75abd32 100644 --- a/src/detection/brightness/brightness.h +++ b/src/detection/brightness/brightness.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/brightness/option.h" -typedef struct FFBrightnessResult -{ +typedef struct FFBrightnessResult { FFstrbuf name; double min, max, current; bool builtin; diff --git a/src/detection/brightness/brightness_apple.c b/src/detection/brightness/brightness_apple.c index 2ea39afd0..6b652bbd3 100644 --- a/src/detection/brightness/brightness_apple.c +++ b/src/detection/brightness/brightness_apple.c @@ -15,28 +15,25 @@ extern IOReturn IOAVServiceReadI2C(IOAVServiceRef service, uint32_t chipAddress, extern IOReturn IOAVServiceWriteI2C(IOAVServiceRef service, uint32_t chipAddress, uint32_t dataAddress, void* inputBuffer, uint32_t inputBufferSize) __attribute__((weak_import)); #else // DDC/CI (Intel) -#include -#include -#include +# include +# include +# include extern void CGSServiceForDisplayNumber(CGDirectDisplayID display, io_service_t* service) __attribute__((weak_import)); #endif // ACPI -extern int DisplayServicesGetBrightness(CGDirectDisplayID display, float *brightness) __attribute__((weak_import)); +extern int DisplayServicesGetBrightness(CGDirectDisplayID display, float* brightness) __attribute__((weak_import)); // Works for internal display -static const char* detectWithDisplayServices(const FFDisplayServerResult* displayServer, FFlist* result) -{ - if(DisplayServicesGetBrightness == NULL) +static const char* detectWithDisplayServices(const FFDisplayServerResult* displayServer, FFlist* result) { + if (DisplayServicesGetBrightness == NULL) { return "DisplayServices function DisplayServicesGetBrightness is not available"; + } - FF_LIST_FOR_EACH(FFDisplayResult, display, displayServer->displays) - { - if (display->type == FF_DISPLAY_TYPE_BUILTIN || display->type == FF_DISPLAY_TYPE_UNKNOWN) - { + FF_LIST_FOR_EACH (FFDisplayResult, display, displayServer->displays) { + if (display->type == FF_DISPLAY_TYPE_BUILTIN || display->type == FF_DISPLAY_TYPE_UNKNOWN) { float value; - if(DisplayServicesGetBrightness((CGDirectDisplayID) display->id, &value) == kCGErrorSuccess) - { + if (DisplayServicesGetBrightness((CGDirectDisplayID) display->id, &value) == kCGErrorSuccess) { FFBrightnessResult* brightness = (FFBrightnessResult*) ffListAdd(result); brightness->current = value; brightness->max = 1; @@ -53,56 +50,55 @@ static const char* detectWithDisplayServices(const FFDisplayServerResult* displa #ifdef __aarch64__ // https://github.com/waydabber/m1ddc // Works for Apple Silicon and USB-C adapter connection ( but not HTMI ) -static const char* detectWithDdcci(FF_MAYBE_UNUSED const FFDisplayServerResult* displayServer, FFBrightnessOptions* options, FFlist* result) -{ - if (!IOAVServiceCreate || !IOAVServiceReadI2C || !IOAVServiceWriteI2C) +static const char* detectWithDdcci(FF_MAYBE_UNUSED const FFDisplayServerResult* displayServer, FFBrightnessOptions* options, FFlist* result) { + if (!IOAVServiceCreate || !IOAVServiceReadI2C || !IOAVServiceWriteI2C) { return "IOAVService is not available"; + } FF_IOOBJECT_AUTO_RELEASE io_iterator_t iterator = IO_OBJECT_NULL; - if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("DCPAVServiceProxy"), &iterator) != kIOReturnSuccess) + if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("DCPAVServiceProxy"), &iterator) != kIOReturnSuccess) { return "IOServiceGetMatchingServices() failed"; + } io_registry_entry_t registryEntry; - while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) - { + while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { FF_CFTYPE_AUTO_RELEASE IOAVServiceRef service = NULL; { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryAv = registryEntry; FF_CFTYPE_AUTO_RELEASE CFBooleanRef IOAVServiceUserInterfaceSupported = IORegistryEntryCreateCFProperty(entryAv, CFSTR("IOAVServiceUserInterfaceSupported"), kCFAllocatorDefault, kNilOptions); - if (IOAVServiceUserInterfaceSupported && !CFBooleanGetValue(IOAVServiceUserInterfaceSupported)) - { + if (IOAVServiceUserInterfaceSupported && !CFBooleanGetValue(IOAVServiceUserInterfaceSupported)) { // IOAVServiceCreateWithService won't work continue; } FF_CFTYPE_AUTO_RELEASE CFStringRef location = IORegistryEntryCreateCFProperty(entryAv, CFSTR("Location"), kCFAllocatorDefault, kNilOptions); - if (location && CFStringCompare(location, CFSTR("Embedded"), 0) == 0) - { + if (location && CFStringCompare(location, CFSTR("Embedded"), 0) == 0) { // Builtin display should be handled by DisplayServices continue; } service = IOAVServiceCreateWithService(kCFAllocatorDefault, (io_service_t) registryEntry); - if (!service) continue; + if (!service) { + continue; + } } { - uint8_t i2cIn[4] = { 0x82, 0x01, 0x10 /* luminance */ }; + uint8_t i2cIn[4] = {0x82, 0x01, 0x10 /* luminance */}; i2cIn[3] = 0x6e ^ i2cIn[0] ^ i2cIn[1] ^ i2cIn[2]; - for (uint32_t i = 0; i < 2; ++i) - { + for (uint32_t i = 0; i < 2; ++i) { IOAVServiceWriteI2C(service, 0x37, 0x51, i2cIn, ARRAY_SIZE(i2cIn)); usleep(options->ddcciSleep * 1000); } } uint8_t i2cOut[12] = {}; - if (IOAVServiceReadI2C(service, 0x37, 0x51, i2cOut, ARRAY_SIZE(i2cOut)) == KERN_SUCCESS) - { - if (i2cOut[2] != 0x02 || i2cOut[3] != 0x00) + if (IOAVServiceReadI2C(service, 0x37, 0x51, i2cOut, ARRAY_SIZE(i2cOut)) == KERN_SUCCESS) { + if (i2cOut[2] != 0x02 || i2cOut[3] != 0x00) { continue; + } uint32_t current = ((uint32_t) i2cOut[8] << 8u) + (uint32_t) i2cOut[9]; uint32_t max = ((uint32_t) i2cOut[6] << 8u) + (uint32_t) i2cOut[7]; @@ -115,37 +111,38 @@ static const char* detectWithDdcci(FF_MAYBE_UNUSED const FFDisplayServerResult* brightness->builtin = false; uint8_t edid[128] = {}; - if (IOAVServiceReadI2C(service, 0x50, 0x00, edid, ARRAY_SIZE(edid)) == KERN_SUCCESS) + if (IOAVServiceReadI2C(service, 0x50, 0x00, edid, ARRAY_SIZE(edid)) == KERN_SUCCESS) { ffEdidGetName(edid, &brightness->name); + } } } return NULL; } #else -static IOOptionBits getSupportedTransactionType(void) -{ +static IOOptionBits getSupportedTransactionType(void) { FF_IOOBJECT_AUTO_RELEASE io_iterator_t iterator = IO_OBJECT_NULL; - if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceNameMatching("IOFramebufferI2CInterface"), &iterator) != KERN_SUCCESS) + if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceNameMatching("IOFramebufferI2CInterface"), &iterator) != KERN_SUCCESS) { return kIOI2CNoTransactionType; + } io_registry_entry_t registryEntry; - while ((registryEntry = IOIteratorNext(iterator)) != MACH_PORT_NULL) - { + while ((registryEntry = IOIteratorNext(iterator)) != MACH_PORT_NULL) { FF_IOOBJECT_AUTO_RELEASE io_service_t io_service = registryEntry; FF_CFTYPE_AUTO_RELEASE CFNumberRef IOI2CTransactionTypes = IORegistryEntryCreateCFProperty(io_service, CFSTR(kIOI2CTransactionTypesKey), kCFAllocatorDefault, kNilOptions); - if (IOI2CTransactionTypes) - { + if (IOI2CTransactionTypes) { int64_t types = 0; ffCfNumGetInt64(IOI2CTransactionTypes, &types); if (types) { - if ((1 << kIOI2CDDCciReplyTransactionType) & (uint64_t) types) + if ((1 << kIOI2CDDCciReplyTransactionType) & (uint64_t) types) { return kIOI2CDDCciReplyTransactionType; - if ((1 << kIOI2CSimpleTransactionType) & (uint64_t) types) + } + if ((1 << kIOI2CSimpleTransactionType) & (uint64_t) types) { return kIOI2CSimpleTransactionType; + } } } break; @@ -154,36 +151,41 @@ static IOOptionBits getSupportedTransactionType(void) return kIOI2CNoTransactionType; } -static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, FFBrightnessOptions* options, FFlist* result) -{ - if (!CGSServiceForDisplayNumber) return "CGSServiceForDisplayNumber is not available"; +static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, FFBrightnessOptions* options, FFlist* result) { + if (!CGSServiceForDisplayNumber) { + return "CGSServiceForDisplayNumber is not available"; + } IOOptionBits transactionType = getSupportedTransactionType(); - if (transactionType == kIOI2CNoTransactionType) + if (transactionType == kIOI2CNoTransactionType) { return "No supported IOI2C transaction type found"; + } - FF_LIST_FOR_EACH(FFDisplayResult, display, displayServer->displays) - { - if (display->type == FF_DISPLAY_TYPE_EXTERNAL) - { + FF_LIST_FOR_EACH (FFDisplayResult, display, displayServer->displays) { + if (display->type == FF_DISPLAY_TYPE_EXTERNAL) { FF_IOOBJECT_AUTO_RELEASE io_service_t framebuffer = IO_OBJECT_NULL; - CGSServiceForDisplayNumber((CGDirectDisplayID)display->id, &framebuffer); - if (framebuffer == IO_OBJECT_NULL) continue; + CGSServiceForDisplayNumber((CGDirectDisplayID) display->id, &framebuffer); + if (framebuffer == IO_OBJECT_NULL) { + continue; + } IOItemCount count; - if (IOFBGetI2CInterfaceCount(framebuffer, &count) != KERN_SUCCESS || count == 0) + if (IOFBGetI2CInterfaceCount(framebuffer, &count) != KERN_SUCCESS || count == 0) { continue; + } - for (IOItemCount bus = 0; bus < count; ++bus) - { + for (IOItemCount bus = 0; bus < count; ++bus) { FF_IOOBJECT_AUTO_RELEASE io_service_t interface = IO_OBJECT_NULL; - if (IOFBCopyI2CInterfaceForBus(framebuffer, bus, &interface) != KERN_SUCCESS) continue; + if (IOFBCopyI2CInterfaceForBus(framebuffer, bus, &interface) != KERN_SUCCESS) { + continue; + } uint8_t i2cOut[12] = {}; IOI2CConnectRef connect = NULL; - if (IOI2CInterfaceOpen(interface, kNilOptions, &connect) != KERN_SUCCESS) + if (IOI2CInterfaceOpen(interface, kNilOptions, &connect) != KERN_SUCCESS) { continue; + } - uint8_t i2cIn[] = { 0x51, 0x82, 0x01, 0x10 /* luminance */, 0 }; + uint8_t i2cIn[] = {0x51, 0x82, 0x01, 0x10 /* luminance */, 0}; i2cIn[4] = 0x6E ^ i2cIn[0] ^ i2cIn[1] ^ i2cIn[2] ^ i2cIn[3]; IOI2CRequest request = { @@ -202,8 +204,12 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F IOReturn ret = IOI2CSendRequest(connect, kNilOptions, &request); IOI2CInterfaceClose(connect, kNilOptions); - if (ret != KERN_SUCCESS || request.result != kIOReturnSuccess || request.replyBytes < 10) continue; - if (i2cOut[2] != 0x02 || i2cOut[3] != 0x00) continue; + if (ret != KERN_SUCCESS || request.result != kIOReturnSuccess || request.replyBytes < 10) { + continue; + } + if (i2cOut[2] != 0x02 || i2cOut[3] != 0x00) { + continue; + } uint32_t current = ((uint32_t) i2cOut[8] << 8u) + (uint32_t) i2cOut[9]; uint32_t max = ((uint32_t) i2cOut[6] << 8u) + (uint32_t) i2cOut[7]; @@ -224,14 +230,14 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F } #endif -const char* ffDetectBrightness(FFBrightnessOptions* options, FFlist* result) -{ +const char* ffDetectBrightness(FFBrightnessOptions* options, FFlist* result) { const FFDisplayServerResult* displayServer = ffConnectDisplayServer(); detectWithDisplayServices(displayServer, result); - if (displayServer->displays.length > result->length) + if (displayServer->displays.length > result->length) { detectWithDdcci(displayServer, options, result); + } return NULL; } diff --git a/src/detection/brightness/brightness_bsd.c b/src/detection/brightness/brightness_bsd.c index fb574e46e..ea708ad0d 100644 --- a/src/detection/brightness/brightness_bsd.c +++ b/src/detection/brightness/brightness_bsd.c @@ -2,29 +2,29 @@ #if __has_include() -#include "common/io.h" +# include "common/io.h" -#include -#include -#include -#include +# include +# include +# include +# include -const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) -{ +const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) { // https://man.freebsd.org/cgi/man.cgi?query=backlight&sektion=9 char path[] = "/dev/backlight/backlight0"; - for (char i = '0'; i <= '9'; ++i) - { + for (char i = '0'; i <= '9'; ++i) { path[ARRAY_SIZE(path) - 2] = i; FF_AUTO_CLOSE_FD int blfd = open(path, O_RDONLY | O_CLOEXEC); - if (blfd < 0) + if (blfd < 0) { continue; + } struct backlight_props status; - if(ioctl(blfd, BACKLIGHTGETSTATUS, &status) < 0) + if (ioctl(blfd, BACKLIGHTGETSTATUS, &status) < 0) { continue; + } FFBrightnessResult* brightness = (FFBrightnessResult*) ffListAdd(result); ffStrbufInit(&brightness->name); @@ -35,18 +35,18 @@ const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFl brightness->builtin = true; struct backlight_info info; - if(ioctl(blfd, BACKLIGHTGETINFO, &info) == 0) + if (ioctl(blfd, BACKLIGHTGETINFO, &info) == 0) { ffStrbufAppendS(&brightness->name, info.name); - else + } else { ffStrbufAppendS(&brightness->name, path + strlen("/dev/backlight/")); + } } return NULL; } #else -const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FF_MAYBE_UNUSED FFlist* result) { return "Backlight is supported only on FreeBSD 13 and newer"; } diff --git a/src/detection/brightness/brightness_linux.c b/src/detection/brightness/brightness_linux.c index 90655b355..ae9467e28 100644 --- a/src/detection/brightness/brightness_linux.c +++ b/src/detection/brightness/brightness_linux.c @@ -6,14 +6,14 @@ #include #include -static const char* detectWithBacklight(FFlist* result) -{ - //https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-class-backlight +static const char* detectWithBacklight(FFlist* result) { + // https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-class-backlight const char* backlightDirPath = "/sys/class/backlight/"; DIR* dirp = opendir(backlightDirPath); - if(dirp == NULL) + if (dirp == NULL) { return "Failed to open `/sys/class/backlight/`"; + } FF_STRBUF_AUTO_DESTROY backlightDir = ffStrbufCreateA(64); ffStrbufAppendS(&backlightDir, backlightDirPath); @@ -23,54 +23,46 @@ static const char* detectWithBacklight(FFlist* result) FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } ffStrbufAppendS(&backlightDir, entry->d_name); ffStrbufAppendS(&backlightDir, "/brightness"); - if(ffReadFileBuffer(backlightDir.chars, &buffer)) - { + if (ffReadFileBuffer(backlightDir.chars, &buffer)) { double actualBrightness = ffStrbufToDouble(&buffer, 0); ffStrbufSubstrBefore(&backlightDir, backlightDirLength); ffStrbufAppendS(&backlightDir, entry->d_name); ffStrbufAppendS(&backlightDir, "/max_brightness"); - if(ffReadFileBuffer(backlightDir.chars, &buffer)) - { + if (ffReadFileBuffer(backlightDir.chars, &buffer)) { FFBrightnessResult* brightness = (FFBrightnessResult*) ffListAdd(result); ffStrbufSubstrBeforeLastC(&backlightDir, '/'); ffStrbufAppendS(&backlightDir, "/device"); ffStrbufInitA(&brightness->name, PATH_MAX); - if(realpath(backlightDir.chars, brightness->name.chars)) - { + if (realpath(backlightDir.chars, brightness->name.chars)) { ffStrbufRecalculateLength(&brightness->name); // if we managed to get edid, use it ffStrbufAppendS(&brightness->name, "/edid"); uint8_t edidData[128]; - if(ffReadFileData(brightness->name.chars, ARRAY_SIZE(edidData), edidData) == ARRAY_SIZE(edidData)) - { + if (ffReadFileData(brightness->name.chars, ARRAY_SIZE(edidData), edidData) == ARRAY_SIZE(edidData)) { ffStrbufClear(&brightness->name); ffEdidGetName(edidData, &brightness->name); - } - else - { + } else { ffStrbufSubstrBeforeLastC(&brightness->name, '/'); // remove "/edid" - ffStrbufSubstrAfterLastC(&brightness->name, '/'); // try getting DRM connector name - if(ffCharIsDigit(brightness->name.chars[0])) - { + ffStrbufSubstrAfterLastC(&brightness->name, '/'); // try getting DRM connector name + if (ffCharIsDigit(brightness->name.chars[0])) { // PCI address or some unknown path, give up ffStrbufSetS(&brightness->name, entry->d_name); - } - else - { - if(ffStrbufStartsWithS(&brightness->name, "card") && ffCharIsDigit(brightness->name.chars[4])) + } else { + if (ffStrbufStartsWithS(&brightness->name, "card") && ffCharIsDigit(brightness->name.chars[4])) { ffStrbufSubstrAfterFirstC(&brightness->name, '-'); + } } } - } - else + } else { ffStrbufInitS(&brightness->name, entry->d_name); + } brightness->max = ffStrbufToDouble(&buffer, 0); brightness->min = 0; brightness->current = actualBrightness; @@ -86,22 +78,21 @@ static const char* detectWithBacklight(FFlist* result) } #ifdef FF_HAVE_DDCUTIL -#include "detection/displayserver/displayserver.h" -#include "common/library.h" -#include "common/mallocHelper.h" +# include "detection/displayserver/displayserver.h" +# include "common/library.h" +# include "common/mallocHelper.h" -#include -#include +# include +# include // Try to be compatible with ddcutil 2.0 -#if DDCUTIL_VMAJOR >= 2 +# if DDCUTIL_VMAJOR >= 2 double ddca_set_default_sleep_multiplier(double multiplier); // ddcutil 1.4 -#else -DDCA_Status ddca_init(const char *libopts, int syslog_level, int opts); -#endif +# else +DDCA_Status ddca_init(const char* libopts, int syslog_level, int opts); +# endif -static const char* detectWithDdcci(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) -{ +static const char* detectWithDdcci(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) { FF_LIBRARY_LOAD_MESSAGE(libddcutil, "libddcutil" FF_LIBRARY_EXTENSION, 5); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libddcutil, ddca_get_display_info_list2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libddcutil, ddca_open_display2) @@ -109,49 +100,48 @@ static const char* detectWithDdcci(FF_MAYBE_UNUSED FFBrightnessOptions* options, FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libddcutil, ddca_free_any_vcp_value) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libddcutil, ddca_close_display) - #ifndef FF_DISABLE_DLOPEN +# ifndef FF_DISABLE_DLOPEN FF_LIBRARY_LOAD_SYMBOL_LAZY(libddcutil, ddca_init) - if (ffddca_init) - { + if (ffddca_init) { FF_SUPPRESS_IO(); // Ref: https://github.com/rockowitz/ddcutil/issues/344 - if (ffddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) + if (ffddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { return "ddca_init() failed"; - } - else - { + } + } else { FF_LIBRARY_LOAD_SYMBOL_LAZY(libddcutil, ddca_set_default_sleep_multiplier); - if (ffddca_set_default_sleep_multiplier) + if (ffddca_set_default_sleep_multiplier) { ffddca_set_default_sleep_multiplier(options->ddcciSleep / 40.0); + } libddcutil = NULL; // Don't dlclose libddcutil. See https://github.com/rockowitz/ddcutil/issues/330 } - #else - #if DDCUTIL_VMAJOR >= 2 - if (ddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) - return "ddca_init() failed"; - #else - ddca_set_default_sleep_multiplier(options->ddcciSleep / 40.0); - #endif - #endif +# else +# if DDCUTIL_VMAJOR >= 2 + if (ddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { + return "ddca_init() failed"; + } +# else + ddca_set_default_sleep_multiplier(options->ddcciSleep / 40.0); +# endif +# endif FF_AUTO_FREE DDCA_Display_Info_List* infoList = NULL; - if (ffddca_get_display_info_list2(false, &infoList) < 0) + if (ffddca_get_display_info_list2(false, &infoList) < 0) { return "ddca_get_display_info_list2(false, &infoList) failed"; + } - if (infoList->ct == 0) + if (infoList->ct == 0) { return "No DDC/CI compatible displays found"; + } - for (int index = 0; index < infoList->ct; ++index) - { + for (int index = 0; index < infoList->ct; ++index) { const DDCA_Display_Info* display = &infoList->info[index]; DDCA_Display_Handle handle; - if (ffddca_open_display2(display->dref, false, &handle) >= 0) - { + if (ffddca_open_display2(display->dref, false, &handle) >= 0) { DDCA_Any_Vcp_Value* vcpValue = NULL; - if (ffddca_get_any_vcp_value_using_explicit_type(handle, 0x10 /*brightness*/, DDCA_NON_TABLE_VCP_VALUE, &vcpValue) >= 0) - { + if (ffddca_get_any_vcp_value_using_explicit_type(handle, 0x10 /*brightness*/, DDCA_NON_TABLE_VCP_VALUE, &vcpValue) >= 0) { assert(vcpValue->value_type == DDCA_NON_TABLE_VCP_VALUE); int current = VALREC_CUR_VAL(vcpValue), max = VALREC_MAX_VAL(vcpValue); ffddca_free_any_vcp_value(vcpValue); @@ -170,15 +160,15 @@ static const char* detectWithDdcci(FF_MAYBE_UNUSED FFBrightnessOptions* options, } #endif -const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) -{ +const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) { detectWithBacklight(result); - #ifdef FF_HAVE_DDCUTIL +#ifdef FF_HAVE_DDCUTIL const FFDisplayServerResult* displayServer = ffConnectDisplayServer(); - if (result->length < displayServer->displays.length) + if (result->length < displayServer->displays.length) { detectWithDdcci(options, result); - #endif + } +#endif return NULL; } diff --git a/src/detection/brightness/brightness_nbsd.c b/src/detection/brightness/brightness_nbsd.c index 67464772e..9eb56f68f 100644 --- a/src/detection/brightness/brightness_nbsd.c +++ b/src/detection/brightness/brightness_nbsd.c @@ -2,17 +2,17 @@ #include "common/sysctl.h" -const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) -{ +const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) { // https://man.netbsd.org/NetBSD-10.1/acpiout.4#DESCRIPTION char key[] = "hw.acpi.acpiout0.brightness"; char* pn = key + strlen("hw.acpi.acpiout"); - for (uint32_t i = 0; i <= 9; ++i) - { + for (uint32_t i = 0; i <= 9; ++i) { *pn = (char) ('0' + i); int value = ffSysctlGetInt(key, -1); - if (value == -1) continue; + if (value == -1) { + continue; + } FFBrightnessResult* brightness = (FFBrightnessResult*) ffListAdd(result); ffStrbufInitF(&brightness->name, "acpiout%d", i); diff --git a/src/detection/brightness/brightness_nosupport.c b/src/detection/brightness/brightness_nosupport.c index 3ad99ed33..133075057 100644 --- a/src/detection/brightness/brightness_nosupport.c +++ b/src/detection/brightness/brightness_nosupport.c @@ -1,6 +1,5 @@ #include "brightness.h" -const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FF_MAYBE_UNUSED FFlist* result) { return "Not supported on this platform"; } diff --git a/src/detection/brightness/brightness_obsd.c b/src/detection/brightness/brightness_obsd.c index 9dbb65afc..f19c3cbad 100644 --- a/src/detection/brightness/brightness_obsd.c +++ b/src/detection/brightness/brightness_obsd.c @@ -6,8 +6,7 @@ #include #include -const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) -{ +const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) { char path[] = "/dev/ttyCX"; for (char i = '0'; i <= '9'; ++i) { path[strlen("/dev/ttyC")] = i; @@ -15,10 +14,12 @@ const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFl FF_AUTO_CLOSE_FD int devfd = open(path, O_RDONLY | O_CLOEXEC); if (devfd < 0) { - if (errno == EACCES && i == '0') + if (errno == EACCES && i == '0') { return "Permission denied when opening tty device"; - if (errno == ENOENT) + } + if (errno == ENOENT) { break; + } continue; } @@ -26,8 +27,9 @@ const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFl .param = WSDISPLAYIO_PARAM_BRIGHTNESS, }; - if (ioctl(devfd, WSDISPLAYIO_GETPARAM, ¶m) < 0) + if (ioctl(devfd, WSDISPLAYIO_GETPARAM, ¶m) < 0) { continue; + } FFBrightnessResult* brightness = (FFBrightnessResult*) ffListAdd(result); ffStrbufInitF(&brightness->name, "ttyC%c", i); diff --git a/src/detection/brightness/brightness_windows.cpp b/src/detection/brightness/brightness_windows.cpp index f5fc477fb..7c11fbfb0 100644 --- a/src/detection/brightness/brightness_windows.cpp +++ b/src/detection/brightness/brightness_windows.cpp @@ -1,5 +1,4 @@ -extern "C" -{ +extern "C" { #include "brightness.h" #include "detection/displayserver/displayserver.h" #include "common/library.h" @@ -10,45 +9,40 @@ extern "C" #include NTSYSAPI NTSTATUS WINAPI GetPhysicalMonitors( - _In_ UNICODE_STRING *pstrDeviceName, - _In_ DWORD dwPhysicalMonitorArraySize, - _Out_ DWORD *pdwNumPhysicalMonitorHandlesInArray, - _Out_ HANDLE *phPhysicalMonitorArray -); + _In_ UNICODE_STRING* pstrDeviceName, + _In_ DWORD dwPhysicalMonitorArraySize, + _Out_ DWORD* pdwNumPhysicalMonitorHandlesInArray, + _Out_ HANDLE* phPhysicalMonitorArray); typedef enum _MC_VCP_CODE_TYPE { - MC_MOMENTARY, - MC_SET_PARAMETER -} MC_VCP_CODE_TYPE, *LPMC_VCP_CODE_TYPE; + MC_MOMENTARY, + MC_SET_PARAMETER +} MC_VCP_CODE_TYPE, + *LPMC_VCP_CODE_TYPE; NTSYSAPI NTSTATUS WINAPI DDCCIGetVCPFeature( - _In_ HANDLE hMonitor, - _In_ DWORD dwVCPCode, - _Out_opt_ LPMC_VCP_CODE_TYPE pvct, - _Out_ DWORD *pdwCurrentValue, - _Out_opt_ DWORD *pdwMaximumValue -); + _In_ HANDLE hMonitor, + _In_ DWORD dwVCPCode, + _Out_opt_ LPMC_VCP_CODE_TYPE pvct, + _Out_ DWORD* pdwCurrentValue, + _Out_opt_ DWORD* pdwMaximumValue); NTSYSAPI NTSTATUS WINAPI DestroyPhysicalMonitorInternal( - _In_ HANDLE hMonitor -); + _In_ HANDLE hMonitor); NTSTATUS WINAPI GetPhysicalMonitorDescription( - _In_ HANDLE hMonitor, - _In_ DWORD dwPhysicalMonitorDescriptionSizeInChars, - _Out_ LPWSTR szPhysicalMonitorDescription -); + _In_ HANDLE hMonitor, + _In_ DWORD dwPhysicalMonitorDescriptionSizeInChars, + _Out_ LPWSTR szPhysicalMonitorDescription); -static const char* detectWithWmi(FFlist* result) -{ +static const char* detectWithWmi(FFlist* result) { FFWmiQuery query(L"SELECT CurrentBrightness, InstanceName FROM WmiMonitorBrightness WHERE Active = true", nullptr, FFWmiNamespace::WMI); - if(!query) + if (!query) { return "Query WMI service failed"; + } - while(FFWmiRecord record = query.next()) - { - if(FFWmiVariant vtValue = record.get(L"CurrentBrightness")) - { + while (FFWmiRecord record = query.next()) { + if (FFWmiVariant vtValue = record.get(L"CurrentBrightness")) { FFBrightnessResult* brightness = (FFBrightnessResult*) ffListAdd(result); brightness->max = 100; brightness->min = 0; @@ -56,8 +50,7 @@ static const char* detectWithWmi(FFlist* result) brightness->builtin = true; ffStrbufInit(&brightness->name); - if (FFWmiVariant vtName = record.get(L"InstanceName")) - { + if (FFWmiVariant vtName = record.get(L"InstanceName")) { ffStrbufSetWSV(&brightness->name, vtName.get()); ffStrbufSubstrAfterFirstC(&brightness->name, '\\'); ffStrbufSubstrBeforeFirstC(&brightness->name, '\\'); @@ -67,22 +60,25 @@ static const char* detectWithWmi(FFlist* result) return NULL; } -static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, FFlist* result) -{ +static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, FFlist* result) { void* gdi32 = ffLibraryGetModule(L"gdi32.dll"); - if (!gdi32) return "ffLibraryGetModule(gdi32.dll) failed"; + if (!gdi32) { + return "ffLibraryGetModule(gdi32.dll) failed"; + } FF_LIBRARY_LOAD_SYMBOL_MESSAGE(gdi32, GetPhysicalMonitors) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(gdi32, DDCCIGetVCPFeature) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(gdi32, DestroyPhysicalMonitorInternal) - FF_LIST_FOR_EACH(FFDisplayResult, display, displayServer->displays) - { - if (display->type == FF_DISPLAY_TYPE_BUILTIN) continue; + FF_LIST_FOR_EACH (FFDisplayResult, display, displayServer->displays) { + if (display->type == FF_DISPLAY_TYPE_BUILTIN) { + continue; + } MONITORINFOEXW mi; mi.cbSize = sizeof(mi); - if (!GetMonitorInfoW((HMONITOR)(uintptr_t) display->id, (LPMONITORINFO) &mi)) + if (!GetMonitorInfoW((HMONITOR) (uintptr_t) display->id, (LPMONITORINFO) &mi)) { continue; + } UNICODE_STRING deviceName = { .Length = (USHORT) (wcslen(mi.szDevice) * sizeof(wchar_t)), @@ -91,25 +87,23 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F }; HANDLE physicalMonitor; DWORD monitorCount = 0; - if (NT_SUCCESS(ffGetPhysicalMonitors(&deviceName, 1, &monitorCount, &physicalMonitor)) && monitorCount >= 1) - { + if (NT_SUCCESS(ffGetPhysicalMonitors(&deviceName, 1, &monitorCount, &physicalMonitor)) && monitorCount >= 1) { DWORD curr = 0, max = 0; - if (NT_SUCCESS(ffDDCCIGetVCPFeature(physicalMonitor, 0x10 /* luminance */, NULL, &curr, &max))) - { + if (NT_SUCCESS(ffDDCCIGetVCPFeature(physicalMonitor, 0x10 /* luminance */, NULL, &curr, &max))) { FFBrightnessResult* brightness = (FFBrightnessResult*) ffListAdd(result); - if (display->name.length > 0) + if (display->name.length > 0) { ffStrbufInitCopy(&brightness->name, &display->name); - else - { + } else { FF_LIBRARY_LOAD_SYMBOL_LAZY(gdi32, GetPhysicalMonitorDescription) - if (ffGetPhysicalMonitorDescription) - { + if (ffGetPhysicalMonitorDescription) { wchar_t description[128 /*MUST be PHYSICAL_MONITOR_DESCRIPTION_SIZE*/]; - if (NT_SUCCESS(ffGetPhysicalMonitorDescription(physicalMonitor, ARRAY_SIZE(description), description))) + if (NT_SUCCESS(ffGetPhysicalMonitorDescription(physicalMonitor, ARRAY_SIZE(description), description))) { ffStrbufInitWS(&brightness->name, description); + } } - if (brightness->name.length == 0) + if (brightness->name.length == 0) { ffStrbufSetNWS(&brightness->name, deviceName.Length / 2, deviceName.Buffer); + } } brightness->max = max; brightness->min = 0; @@ -123,25 +117,24 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F return NULL; } -static bool hasBuiltinDisplay(const FFDisplayServerResult* displayServer) -{ - FF_LIST_FOR_EACH(FFDisplayResult, display, displayServer->displays) - { - if (display->type == FF_DISPLAY_TYPE_BUILTIN || display->type == FF_DISPLAY_TYPE_UNKNOWN) +static bool hasBuiltinDisplay(const FFDisplayServerResult* displayServer) { + FF_LIST_FOR_EACH (FFDisplayResult, display, displayServer->displays) { + if (display->type == FF_DISPLAY_TYPE_BUILTIN || display->type == FF_DISPLAY_TYPE_UNKNOWN) { return true; + } } return false; } -extern "C" -const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) -{ +extern "C" const char* ffDetectBrightness(FF_MAYBE_UNUSED FFBrightnessOptions* options, FFlist* result) { const FFDisplayServerResult* displayServer = ffConnectDisplayServer(); - if (hasBuiltinDisplay(displayServer)) + if (hasBuiltinDisplay(displayServer)) { detectWithWmi(result); + } - if (result->length < displayServer->displays.length) + if (result->length < displayServer->displays.length) { detectWithDdcci(displayServer, result); + } return NULL; } diff --git a/src/detection/btrfs/btrfs.h b/src/detection/btrfs/btrfs.h index 3fca95784..08ea4e9bc 100644 --- a/src/detection/btrfs/btrfs.h +++ b/src/detection/btrfs/btrfs.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/btrfs/option.h" -typedef struct FFBtrfsDiskUsage -{ +typedef struct FFBtrfsDiskUsage { uint64_t total; uint64_t used; const char* type; @@ -12,8 +11,7 @@ typedef struct FFBtrfsDiskUsage uint8_t copies; } FFBtrfsDiskUsage; -typedef struct FFBtrfsResult -{ +typedef struct FFBtrfsResult { FFstrbuf name; FFstrbuf uuid; FFstrbuf devices; diff --git a/src/detection/btrfs/btrfs_linux.c b/src/detection/btrfs/btrfs_linux.c index 369e38371..edfb90deb 100644 --- a/src/detection/btrfs/btrfs_linux.c +++ b/src/detection/btrfs/btrfs_linux.c @@ -5,132 +5,141 @@ enum { uuidLen = (uint32_t) __builtin_strlen("00000000-0000-0000-0000-000000000000") }; -static const char* enumerateDevices(FFBtrfsResult* item, int dfd, FFstrbuf* buffer) -{ +static const char* enumerateDevices(FFBtrfsResult* item, int dfd, FFstrbuf* buffer) { int subfd = openat(dfd, "devices", O_RDONLY | O_CLOEXEC | O_DIRECTORY); - if (subfd < 0) return "openat(\"/sys/fs/btrfs/UUID/devices\") == -1"; + if (subfd < 0) { + return "openat(\"/sys/fs/btrfs/UUID/devices\") == -1"; + } FF_AUTO_CLOSE_DIR DIR* dirp = fdopendir(subfd); - if(dirp == NULL) - { + if (dirp == NULL) { close(subfd); return "fdopendir(\"/sys/fs/btrfs/UUID/devices\") == NULL"; } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } - if (item->devices.length) + if (item->devices.length) { ffStrbufAppendC(&item->devices, ','); + } ffStrbufAppendS(&item->devices, entry->d_name); char path[sizeof(entry->d_name) + sizeof("/size") + 1]; snprintf(path, ARRAY_SIZE(path), "%s/size", entry->d_name); - if (ffReadFileBufferRelative(subfd, path, buffer)) + if (ffReadFileBufferRelative(subfd, path, buffer)) { item->totalSize += ffStrbufToUInt(buffer, 0) * 512; + } } return NULL; } -static const char* enumerateFeatures(FFBtrfsResult* item, int dfd) -{ +static const char* enumerateFeatures(FFBtrfsResult* item, int dfd) { int subfd = openat(dfd, "features", O_RDONLY | O_CLOEXEC | O_DIRECTORY); - if (subfd < 0) return "openat(\"/sys/fs/btrfs/UUID/features\") == -1"; + if (subfd < 0) { + return "openat(\"/sys/fs/btrfs/UUID/features\") == -1"; + } FF_AUTO_CLOSE_DIR DIR* dirp = fdopendir(subfd); - if(dirp == NULL) + if (dirp == NULL) { return "fdopendir(\"/sys/fs/btrfs/UUID/features\") == NULL"; + } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; - if (item->features.length) + } + if (item->features.length) { ffStrbufAppendC(&item->features, ','); + } ffStrbufAppendS(&item->features, entry->d_name); } return NULL; } -static const char* detectAllocation(FFBtrfsResult* item, int dfd, FFstrbuf* buffer) -{ +static const char* detectAllocation(FFBtrfsResult* item, int dfd, FFstrbuf* buffer) { FF_AUTO_CLOSE_FD int subfd = openat(dfd, "allocation", O_RDONLY | O_CLOEXEC | O_PATH | O_DIRECTORY); - if (subfd < 0) return "openat(\"/sys/fs/btrfs/UUID/allocation\") == -1"; + if (subfd < 0) { + return "openat(\"/sys/fs/btrfs/UUID/allocation\") == -1"; + } - if (ffReadFileBufferRelative(subfd, "global_rsv_size", buffer)) + if (ffReadFileBufferRelative(subfd, "global_rsv_size", buffer)) { item->globalReservationTotal = ffStrbufToUInt(buffer, 0); - else + } else { return "ffReadFileBuffer(\"/sys/fs/btrfs/UUID/allocation/global_rsv_size\") == NULL"; + } - if (ffReadFileBufferRelative(subfd, "global_rsv_reserved", buffer)) + if (ffReadFileBufferRelative(subfd, "global_rsv_reserved", buffer)) { item->globalReservationUsed = ffStrbufToUInt(buffer, 0); + } item->globalReservationUsed = item->globalReservationTotal - item->globalReservationUsed; - #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; \ - } +#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; \ + } - #define FF_BTRFS_DETECT_TYPE(_index, _type) \ - do { \ - item->allocation[_index].type = _type; \ +#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; \ - } \ + 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 +#undef FF_BTRFS_DETECT_TYPE return NULL; } -const char* ffDetectBtrfs(FFlist* result) -{ +const char* ffDetectBtrfs(FFlist* result) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/fs/btrfs/"); - if(dirp == NULL) + if (dirp == NULL) { return "opendir(\"/sys/fs/btrfs\") == NULL"; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; - if (strlen(entry->d_name) != uuidLen) + } + if (strlen(entry->d_name) != uuidLen) { continue; + } FFBtrfsResult* item = ffListAdd(result); - (*item) = (FFBtrfsResult){ + (*item) = (FFBtrfsResult) { .uuid = ffStrbufCreateNS(uuidLen, entry->d_name), .name = ffStrbufCreate(), .devices = ffStrbufCreate(), @@ -138,23 +147,29 @@ const char* ffDetectBtrfs(FFlist* result) }; FF_AUTO_CLOSE_FD int dfd = openat(dirfd(dirp), entry->d_name, O_RDONLY | O_CLOEXEC | O_PATH | O_DIRECTORY); - if (dfd < 0) continue; + if (dfd < 0) { + continue; + } - if (ffAppendFileBufferRelative(dfd, "label", &item->name)) + if (ffAppendFileBufferRelative(dfd, "label", &item->name)) { ffStrbufTrimRightSpace(&item->name); + } enumerateDevices(item, dfd, &buffer); enumerateFeatures(item, dfd); - if (ffReadFileBufferRelative(dfd, "generation", &buffer)) + if (ffReadFileBufferRelative(dfd, "generation", &buffer)) { item->generation = (uint32_t) ffStrbufToUInt(&buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "nodesize", &buffer)) + if (ffReadFileBufferRelative(dfd, "nodesize", &buffer)) { item->nodeSize = (uint32_t) ffStrbufToUInt(&buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "sectorsize", &buffer)) + if (ffReadFileBufferRelative(dfd, "sectorsize", &buffer)) { item->sectorSize = (uint32_t) ffStrbufToUInt(&buffer, 0); + } detectAllocation(item, dfd, &buffer); } diff --git a/src/detection/btrfs/btrfs_nosupport.c b/src/detection/btrfs/btrfs_nosupport.c index 23c70a1ef..207902572 100644 --- a/src/detection/btrfs/btrfs_nosupport.c +++ b/src/detection/btrfs/btrfs_nosupport.c @@ -1,6 +1,5 @@ #include "btrfs.h" -const char* ffDetectBtrfs(FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectBtrfs(FF_MAYBE_UNUSED FFlist* result) { return "Not supported on this platform"; } diff --git a/src/detection/camera/camera.h b/src/detection/camera/camera.h index ee0c32d0c..52036b5cf 100644 --- a/src/detection/camera/camera.h +++ b/src/detection/camera/camera.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/camera/option.h" -typedef struct FFCameraResult -{ +typedef struct FFCameraResult { FFstrbuf name; FFstrbuf vendor; FFstrbuf id; diff --git a/src/detection/camera/camera_android.c b/src/detection/camera/camera_android.c index 7f5f24447..cb427de88 100644 --- a/src/detection/camera/camera_android.c +++ b/src/detection/camera/camera_android.c @@ -6,54 +6,51 @@ #define FF_TERMUX_API_PATH FASTFETCH_TARGET_DIR_ROOT "/libexec/termux-api" #define FF_TERMUX_API_PARAM "CameraInfo" -static inline void wrapYyjsonFree(yyjson_doc** doc) -{ +static inline void wrapYyjsonFree(yyjson_doc** doc) { assert(doc); - if (*doc) + if (*doc) { yyjson_doc_free(*doc); + } } -const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if(ffProcessAppendStdOut(&buffer, (char* const[]){ - FF_TERMUX_API_PATH, - FF_TERMUX_API_PARAM, - NULL - })) + if (ffProcessAppendStdOut(&buffer, (char* const[]) {FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, NULL})) { return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed"; + } yyjson_doc* __attribute__((__cleanup__(wrapYyjsonFree))) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, NULL, NULL); - if (!doc) + if (!doc) { return "Failed to parse camera info"; + } yyjson_val* root = yyjson_doc_get_root(doc); - if (!yyjson_is_arr(root)) + if (!yyjson_is_arr(root)) { return "Camera info result is not a JSON array"; + } yyjson_val* device; size_t idx, max; - yyjson_arr_foreach(root, idx, max, device) - { + yyjson_arr_foreach (root, idx, max, device) { FFCameraResult* camera = (FFCameraResult*) ffListAdd(result); { const char* facing = yyjson_get_str(yyjson_obj_get(device, "facing")); - if (facing) + if (facing) { ffStrbufInitF(&camera->name, "builtin-%s", facing); - else + } else { ffStrbufInitStatic(&camera->name, "Unknown"); + } } ffStrbufInit(&camera->vendor); ffStrbufInitJsonVal(&camera->id, yyjson_obj_get(device, "id")); yyjson_val* sizes = yyjson_arr_get_first(yyjson_obj_get(device, "jpeg_output_sizes")); - if (yyjson_is_obj(sizes)) - { + if (yyjson_is_obj(sizes)) { camera->width = (uint32_t) yyjson_get_uint(yyjson_obj_get(sizes, "width")); camera->height = (uint32_t) yyjson_get_uint(yyjson_obj_get(sizes, "height")); - } - else + } else { camera->width = camera->height = 0; + } ffStrbufInit(&camera->colorspace); } diff --git a/src/detection/camera/camera_linux.c b/src/detection/camera/camera_linux.c index 52e1ea136..924f02a96 100644 --- a/src/detection/camera/camera_linux.c +++ b/src/detection/camera/camera_linux.c @@ -6,57 +6,81 @@ #include #if FF_HAVE_LINUX_VIDEODEV2 - #include +# include #elif __has_include() // OpenBSD - #include - #define FF_HAVE_LINUX_VIDEODEV2 1 +# include +# define FF_HAVE_LINUX_VIDEODEV2 1 #endif -const char* ffDetectCamera(FFlist* result) -{ +const char* ffDetectCamera(FFlist* result) { #if FF_HAVE_LINUX_VIDEODEV2 char path[] = "/dev/videoN"; - for (uint32_t i = 0; i <= 9; ++i) - { + for (uint32_t i = 0; i <= 9; ++i) { path[ARRAY_SIZE(path) - 2] = (char) (i + '0'); FF_AUTO_CLOSE_FD int fd = open(path, O_RDONLY | O_CLOEXEC); - if (fd < 0) - { - if (errno == ENOENT) + if (fd < 0) { + if (errno == ENOENT) { break; - if (errno == ENXIO) + } + if (errno == ENXIO) { continue; + } return "Failed to open /dev/videoN"; } struct v4l2_capability cap = {}; - if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0 || !(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) + if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0 || !(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { continue; + } - struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE }; - if (ioctl(fd, VIDIOC_G_FMT, &fmt) < 0) + struct v4l2_format fmt = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE}; + if (ioctl(fd, VIDIOC_G_FMT, &fmt) < 0) { continue; + } FFCameraResult* camera = (FFCameraResult*) ffListAdd(result); ffStrbufInitS(&camera->name, (const char*) cap.card); ffStrbufInit(&camera->vendor); ffStrbufInitS(&camera->id, (const char*) cap.bus_info); - switch (fmt.fmt.pix.colorspace) - { - case V4L2_COLORSPACE_SMPTE170M: ffStrbufInitStatic(&camera->colorspace, "SMPTE 170M"); break; - case V4L2_COLORSPACE_SMPTE240M: ffStrbufInitStatic(&camera->colorspace, "SMPTE 240M"); break; - case V4L2_COLORSPACE_BT878: ffStrbufInitStatic(&camera->colorspace, "BT.878"); break; - case V4L2_COLORSPACE_470_SYSTEM_M: ffStrbufInitStatic(&camera->colorspace, "NTSC"); break; - case V4L2_COLORSPACE_470_SYSTEM_BG: ffStrbufInitStatic(&camera->colorspace, "EBU 3213"); break; - case V4L2_COLORSPACE_JPEG: ffStrbufInitStatic(&camera->colorspace, "JPEG"); break; - case V4L2_COLORSPACE_REC709: - case V4L2_COLORSPACE_SRGB: ffStrbufInitStatic(&camera->colorspace, "sRGB"); break; - case 9 /* V4L2_COLORSPACE_OPRGB */: ffStrbufInitStatic(&camera->colorspace, "Adobe RGB"); break; - case 10 /* V4L2_COLORSPACE_BT2020 */: ffStrbufInitStatic(&camera->colorspace, "BT.2020"); break; - case 11 /* V4L2_COLORSPACE_RAW */: ffStrbufInitStatic(&camera->colorspace, "RAW"); break; - case 12 /* V4L2_COLORSPACE_DCI_P3 */: ffStrbufInitStatic(&camera->colorspace, "DCI-P3"); break; - default: ffStrbufInit(&camera->colorspace); break; + switch (fmt.fmt.pix.colorspace) { + case V4L2_COLORSPACE_SMPTE170M: + ffStrbufInitStatic(&camera->colorspace, "SMPTE 170M"); + break; + case V4L2_COLORSPACE_SMPTE240M: + ffStrbufInitStatic(&camera->colorspace, "SMPTE 240M"); + break; + case V4L2_COLORSPACE_BT878: + ffStrbufInitStatic(&camera->colorspace, "BT.878"); + break; + case V4L2_COLORSPACE_470_SYSTEM_M: + ffStrbufInitStatic(&camera->colorspace, "NTSC"); + break; + case V4L2_COLORSPACE_470_SYSTEM_BG: + ffStrbufInitStatic(&camera->colorspace, "EBU 3213"); + break; + case V4L2_COLORSPACE_JPEG: + ffStrbufInitStatic(&camera->colorspace, "JPEG"); + break; + case V4L2_COLORSPACE_REC709: + case V4L2_COLORSPACE_SRGB: + ffStrbufInitStatic(&camera->colorspace, "sRGB"); + break; + case 9 /* V4L2_COLORSPACE_OPRGB */: + ffStrbufInitStatic(&camera->colorspace, "Adobe RGB"); + break; + case 10 /* V4L2_COLORSPACE_BT2020 */: + ffStrbufInitStatic(&camera->colorspace, "BT.2020"); + break; + case 11 /* V4L2_COLORSPACE_RAW */: + ffStrbufInitStatic(&camera->colorspace, "RAW"); + break; + case 12 /* V4L2_COLORSPACE_DCI_P3 */: + ffStrbufInitStatic(&camera->colorspace, "DCI-P3"); + break; + default: + ffStrbufInit(&camera->colorspace); + break; } camera->width = fmt.fmt.pix.width; camera->height = fmt.fmt.pix.height; diff --git a/src/detection/camera/camera_nosupport.c b/src/detection/camera/camera_nosupport.c index 383e4cec1..fae48d4f8 100644 --- a/src/detection/camera/camera_nosupport.c +++ b/src/detection/camera/camera_nosupport.c @@ -1,6 +1,5 @@ #include "camera.h" -const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) { return "Not support on this platform"; } diff --git a/src/detection/camera/camera_windows.cpp b/src/detection/camera/camera_windows.cpp index 91221374f..e91d4eb1d 100644 --- a/src/detection/camera/camera_windows.cpp +++ b/src/detection/camera/camera_windows.cpp @@ -10,42 +10,43 @@ extern "C" { #include #include -extern "C" -const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) -{ +extern "C" const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) { FF_LIBRARY_LOAD_MESSAGE(mfplat, "mfplat" FF_LIBRARY_EXTENSION, 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(mfplat, MFCreateAttributes) FF_LIBRARY_LOAD_MESSAGE(mf, "mf" FF_LIBRARY_EXTENSION, 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(mf, MFEnumDeviceSources) const char* error = ffInitCom(); - if (error) + if (error) { return error; + } IMFAttributes* FF_AUTO_RELEASE_COM_OBJECT attrs = nullptr; - if (FAILED(ffMFCreateAttributes(&attrs, 1))) + if (FAILED(ffMFCreateAttributes(&attrs, 1))) { return "MFCreateAttributes() failed"; + } if (FAILED(attrs->SetGUID( - MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, - MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID - ))) + MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, + MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID))) { return "SetGUID(MF_*) failed"; + } IMFActivate** devices = NULL; uint32_t count; - if (FAILED(ffMFEnumDeviceSources(attrs, &devices, &count))) + if (FAILED(ffMFEnumDeviceSources(attrs, &devices, &count))) { return "MFEnumDeviceSources() failed"; + } - for (uint32_t i = 0; i < count; i++) - { + for (uint32_t i = 0; i < count; i++) { IMFActivate* FF_AUTO_RELEASE_COM_OBJECT device = devices[i]; wchar_t buffer[256]; uint32_t length = 0; - if (FAILED(device->GetString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, buffer, ARRAY_SIZE(buffer), &length)) || length == 0) + if (FAILED(device->GetString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, buffer, ARRAY_SIZE(buffer), &length)) || length == 0) { continue; + } FFCameraResult* camera = (FFCameraResult*) ffListAdd(result); ffStrbufInitNWS(&camera->name, length, buffer); @@ -55,60 +56,85 @@ const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) camera->width = 0; camera->height = 0; - if (SUCCEEDED(device->GetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, buffer, ARRAY_SIZE(buffer), &length)) && length > 0) + if (SUCCEEDED(device->GetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, buffer, ARRAY_SIZE(buffer), &length)) && length > 0) { ffStrbufSetNWS(&camera->id, length, buffer); + } IMFMediaSource* FF_AUTO_RELEASE_COM_OBJECT source = nullptr; - if (FAILED(device->ActivateObject(IID_PPV_ARGS(&source)))) + if (FAILED(device->ActivateObject(IID_PPV_ARGS(&source)))) { continue; + } on_scope_exit destroySource([&] { source->Shutdown(); }); IMFPresentationDescriptor* FF_AUTO_RELEASE_COM_OBJECT pd = nullptr; - if (FAILED(source->CreatePresentationDescriptor(&pd))) + if (FAILED(source->CreatePresentationDescriptor(&pd))) { continue; + } IMFStreamDescriptor* FF_AUTO_RELEASE_COM_OBJECT sd = NULL; BOOL selected; - if (FAILED(pd->GetStreamDescriptorByIndex(0, &selected, &sd))) + if (FAILED(pd->GetStreamDescriptorByIndex(0, &selected, &sd))) { continue; + } IMFMediaTypeHandler* FF_AUTO_RELEASE_COM_OBJECT handler = NULL; - if (FAILED(sd->GetMediaTypeHandler(&handler))) + if (FAILED(sd->GetMediaTypeHandler(&handler))) { continue; + } DWORD mediaTypeCount; - if (FAILED(handler->GetMediaTypeCount(&mediaTypeCount))) + if (FAILED(handler->GetMediaTypeCount(&mediaTypeCount))) { continue; + } // Assume first type is the maximum resolution IMFMediaType* type = NULL; - for (DWORD idx = 0; SUCCEEDED(handler->GetMediaTypeByIndex(idx, &type)); ++idx) - { + for (DWORD idx = 0; SUCCEEDED(handler->GetMediaTypeByIndex(idx, &type)); ++idx) { on_scope_exit destroyType([=] { type->Release(); }); GUID majorType; - if (FAILED(type->GetMajorType(&majorType)) || majorType != MFMediaType_Video) + if (FAILED(type->GetMajorType(&majorType)) || majorType != MFMediaType_Video) { continue; + } MFVideoPrimaries primaries; static_assert(sizeof(primaries) == sizeof(uint32_t), ""); - if (SUCCEEDED(type->GetUINT32(MF_MT_VIDEO_PRIMARIES, (uint32_t*) &primaries))) - { - switch (primaries) - { - case MFVideoPrimaries_BT709: ffStrbufSetStatic(&camera->colorspace, "sRGB"); break; - case MFVideoPrimaries_BT470_2_SysM: - case MFVideoPrimaries_BT470_2_SysBG: ffStrbufSetStatic(&camera->colorspace, "NTSC"); break; - case MFVideoPrimaries_SMPTE170M: ffStrbufSetStatic(&camera->colorspace, "SMPTE 170M"); break; - case MFVideoPrimaries_SMPTE240M: ffStrbufSetStatic(&camera->colorspace, "SMPTE 240M"); break; - case MFVideoPrimaries_EBU3213: ffStrbufSetStatic(&camera->colorspace, "EBU 3213"); break; - case MFVideoPrimaries_SMPTE_C: ffStrbufSetStatic(&camera->colorspace, "SMPTE C"); break; - case MFVideoPrimaries_BT2020: ffStrbufSetStatic(&camera->colorspace, "BT.2020"); break; - case MFVideoPrimaries_XYZ: ffStrbufSetStatic(&camera->colorspace, "XYZ"); break; - case MFVideoPrimaries_DCI_P3: ffStrbufSetStatic(&camera->colorspace, "DCI-P3"); break; - case MFVideoPrimaries_ACES: ffStrbufSetStatic(&camera->colorspace, "ACES"); break; - default: break; + if (SUCCEEDED(type->GetUINT32(MF_MT_VIDEO_PRIMARIES, (uint32_t*) &primaries))) { + switch (primaries) { + case MFVideoPrimaries_BT709: + ffStrbufSetStatic(&camera->colorspace, "sRGB"); + break; + case MFVideoPrimaries_BT470_2_SysM: + case MFVideoPrimaries_BT470_2_SysBG: + ffStrbufSetStatic(&camera->colorspace, "NTSC"); + break; + case MFVideoPrimaries_SMPTE170M: + ffStrbufSetStatic(&camera->colorspace, "SMPTE 170M"); + break; + case MFVideoPrimaries_SMPTE240M: + ffStrbufSetStatic(&camera->colorspace, "SMPTE 240M"); + break; + case MFVideoPrimaries_EBU3213: + ffStrbufSetStatic(&camera->colorspace, "EBU 3213"); + break; + case MFVideoPrimaries_SMPTE_C: + ffStrbufSetStatic(&camera->colorspace, "SMPTE C"); + break; + case MFVideoPrimaries_BT2020: + ffStrbufSetStatic(&camera->colorspace, "BT.2020"); + break; + case MFVideoPrimaries_XYZ: + ffStrbufSetStatic(&camera->colorspace, "XYZ"); + break; + case MFVideoPrimaries_DCI_P3: + ffStrbufSetStatic(&camera->colorspace, "DCI-P3"); + break; + case MFVideoPrimaries_ACES: + ffStrbufSetStatic(&camera->colorspace, "ACES"); + break; + default: + break; } } @@ -117,7 +143,9 @@ const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result) } } - if (devices) CoTaskMemFree(devices); + if (devices) { + CoTaskMemFree(devices); + } return nullptr; } diff --git a/src/detection/chassis/chassis.c b/src/detection/chassis/chassis.c index b1b44a377..77971d6dd 100644 --- a/src/detection/chassis/chassis.c +++ b/src/detection/chassis/chassis.c @@ -1,47 +1,82 @@ #include "chassis.h" -const char* ffChassisTypeToString(uint32_t type) -{ +const char* ffChassisTypeToString(uint32_t type) { // https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.7.0.pdf // 7.4.1 System Enclosure or Chassis Types - switch (type & 0b01111111) - { - case 0x01: return "Other"; - case 0x02: return "Unknown"; - case 0x03: return "Desktop"; - case 0x04: return "Low Profile Desktop"; - case 0x05: return "Pizza Box"; - case 0x06: return "Mini Tower"; - case 0x07: return "Tower"; - case 0x08: return "Portable"; - case 0x09: return "Laptop"; - case 0x0A: return "Notebook"; - case 0x0B: return "Hand Held"; - case 0x0C: return "Docking Station"; - case 0x0D: return "All in One"; - case 0x0E: return "Sub Notebook"; - case 0x0F: return "Space-saving"; - case 0x10: return "Lunch Box"; - case 0x11: return "Main Server Chassis"; - case 0x12: return "Expansion Chassis"; - case 0x13: return "SubChassis"; - case 0x14: return "Bus Expansion Chassis"; - case 0x15: return "Peripheral Chassis"; - case 0x16: return "RAID Chassis"; - case 0x17: return "Rack Mount Chassis"; - case 0x18: return "Sealed-case PC"; - case 0x19: return "Multi-system chassis"; - case 0x1A: return "Compact PCI"; - case 0x1B: return "Advanced TCA"; - case 0x1C: return "Blade"; - case 0x1D: return "Mobile Workstation"; - case 0x1E: return "Tablet"; - case 0x1F: return "Convertible"; - case 0x20: return "Detachable"; - case 0x21: return "IoT Gateway"; - case 0x22: return "Embedded PC"; - case 0x23: return "Mini PC"; - case 0x24: return "Stick PC"; - default: return NULL; + switch (type & 0b01111111) { + case 0x01: + return "Other"; + case 0x02: + return "Unknown"; + case 0x03: + return "Desktop"; + case 0x04: + return "Low Profile Desktop"; + case 0x05: + return "Pizza Box"; + case 0x06: + return "Mini Tower"; + case 0x07: + return "Tower"; + case 0x08: + return "Portable"; + case 0x09: + return "Laptop"; + case 0x0A: + return "Notebook"; + case 0x0B: + return "Hand Held"; + case 0x0C: + return "Docking Station"; + case 0x0D: + return "All in One"; + case 0x0E: + return "Sub Notebook"; + case 0x0F: + return "Space-saving"; + case 0x10: + return "Lunch Box"; + case 0x11: + return "Main Server Chassis"; + case 0x12: + return "Expansion Chassis"; + case 0x13: + return "SubChassis"; + case 0x14: + return "Bus Expansion Chassis"; + case 0x15: + return "Peripheral Chassis"; + case 0x16: + return "RAID Chassis"; + case 0x17: + return "Rack Mount Chassis"; + case 0x18: + return "Sealed-case PC"; + case 0x19: + return "Multi-system chassis"; + case 0x1A: + return "Compact PCI"; + case 0x1B: + return "Advanced TCA"; + case 0x1C: + return "Blade"; + case 0x1D: + return "Mobile Workstation"; + case 0x1E: + return "Tablet"; + case 0x1F: + return "Convertible"; + case 0x20: + return "Detachable"; + case 0x21: + return "IoT Gateway"; + case 0x22: + return "Embedded PC"; + case 0x23: + return "Mini PC"; + case 0x24: + return "Stick PC"; + default: + return NULL; } } diff --git a/src/detection/chassis/chassis.h b/src/detection/chassis/chassis.h index 8f57232ec..4e57ad081 100644 --- a/src/detection/chassis/chassis.h +++ b/src/detection/chassis/chassis.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/chassis/option.h" -typedef struct FFChassisResult -{ +typedef struct FFChassisResult { FFstrbuf type; FFstrbuf serial; FFstrbuf vendor; diff --git a/src/detection/chassis/chassis_apple.c b/src/detection/chassis/chassis_apple.c index 956386d08..1ff4fee52 100644 --- a/src/detection/chassis/chassis_apple.c +++ b/src/detection/chassis/chassis_apple.c @@ -1,8 +1,7 @@ #include "chassis.h" #include "detection/host/host.h" -const char* ffDetectChassis(FFChassisResult* result) -{ +const char* ffDetectChassis(FFChassisResult* result) { FFHostResult host = { .family = ffStrbufCreate(), .name = ffStrbufCreate(), @@ -12,18 +11,20 @@ const char* ffDetectChassis(FFChassisResult* result) .uuid = ffStrbufCreate(), .vendor = ffStrbufCreate(), }; - if (ffDetectHost(&host) != NULL) + if (ffDetectHost(&host) != NULL) { return "Failed to detect host"; + } - if (ffStrbufStartsWithS(&host.name, "MacBook ")) + if (ffStrbufStartsWithS(&host.name, "MacBook ")) { ffStrbufSetStatic(&result->type, "Laptop"); - else if (ffStrbufStartsWithS(&host.name, "Mac mini ") || - ffStrbufStartsWithS(&host.name, "Mac Studio ")) + } else if (ffStrbufStartsWithS(&host.name, "Mac mini ") || + ffStrbufStartsWithS(&host.name, "Mac Studio ")) { ffStrbufSetStatic(&result->type, "Mini PC"); - else if (ffStrbufStartsWithS(&host.name, "iMac ")) + } else if (ffStrbufStartsWithS(&host.name, "iMac ")) { ffStrbufSetStatic(&result->type, "All in One"); - else + } else { ffStrbufSetStatic(&result->type, "Desktop"); + } ffStrbufSet(&result->vendor, &host.vendor); diff --git a/src/detection/chassis/chassis_bsd.c b/src/detection/chassis/chassis_bsd.c index dd050f3c5..12572817c 100644 --- a/src/detection/chassis/chassis_bsd.c +++ b/src/detection/chassis/chassis_bsd.c @@ -2,8 +2,7 @@ #include "common/settings.h" #include "common/smbiosHelper.h" -const char* ffDetectChassis(FFChassisResult* result) -{ +const char* ffDetectChassis(FFChassisResult* result) { // Unlike other platforms, `smbios.chassis.type` return display string directly on my machine ffSettingsGetFreeBSDKenv("smbios.chassis.type", &result->type); ffCleanUpSmbiosValue(&result->type); diff --git a/src/detection/chassis/chassis_linux.c b/src/detection/chassis/chassis_linux.c index 999f0036a..648365569 100644 --- a/src/detection/chassis/chassis_linux.c +++ b/src/detection/chassis/chassis_linux.c @@ -4,37 +4,33 @@ #include -const char* ffDetectChassis(FFChassisResult* result) -{ - if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/chassis_type", "/sys/class/dmi/id/chassis_type", &result->type)) - { +const char* ffDetectChassis(FFChassisResult* result) { + if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/chassis_type", "/sys/class/dmi/id/chassis_type", &result->type)) { ffGetSmbiosValue("/sys/devices/virtual/dmi/id/chassis_serial", "/sys/class/dmi/id/chassis_serial", &result->serial); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/chassis_vendor", "/sys/class/dmi/id/chassis_vendor", &result->vendor); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/chassis_version", "/sys/class/dmi/id/chassis_version", &result->version); - if(result->type.length) - { + if (result->type.length) { const char* typeStr = ffChassisTypeToString((uint32_t) ffStrbufToUInt(&result->type, 9999)); - if(typeStr) + if (typeStr) { ffStrbufSetStatic(&result->type, typeStr); + } } - } - else - { + } else { // Available on Asahi Linux uint32_t chassisType = 0; if (ffReadFileData("/sys/firmware/devicetree/base/smbios/smbios/chassis/chassis-type", sizeof(chassisType), &chassisType)) // big endian { chassisType = __builtin_bswap32(chassisType); const char* typeStr = ffChassisTypeToString(chassisType); - if(typeStr) + if (typeStr) { ffStrbufSetStatic(&result->type, typeStr); + } - if(ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/chassis/manufacturer", &result->vendor) && result->vendor.length > 0) + if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/chassis/manufacturer", &result->vendor) && result->vendor.length > 0) { ffStrbufTrimRight(&result->vendor, '\0'); - } - else if(ffReadFileBuffer("/sys/firmware/devicetree/base/chassis-type", &result->type) && result->type.length > 0) - { + } + } else if (ffReadFileBuffer("/sys/firmware/devicetree/base/chassis-type", &result->type) && result->type.length > 0) { ffStrbufTrimRight(&result->type, '\0'); result->type.chars[0] = (char) toupper(result->type.chars[0]); } diff --git a/src/detection/chassis/chassis_nbsd.c b/src/detection/chassis/chassis_nbsd.c index 5b9bb23fa..f3f240d74 100644 --- a/src/detection/chassis/chassis_nbsd.c +++ b/src/detection/chassis/chassis_nbsd.c @@ -2,16 +2,19 @@ #include "common/sysctl.h" #include "common/smbiosHelper.h" -const char* ffDetectChassis(FFChassisResult* chassis) -{ - if (ffSysctlGetString("machdep.dmi.chassis-type", &chassis->type) == NULL) +const char* ffDetectChassis(FFChassisResult* chassis) { + if (ffSysctlGetString("machdep.dmi.chassis-type", &chassis->type) == NULL) { ffCleanUpSmbiosValue(&chassis->type); - if (ffSysctlGetString("machdep.dmi.chassis-version", &chassis->version) == NULL) + } + if (ffSysctlGetString("machdep.dmi.chassis-version", &chassis->version) == NULL) { ffCleanUpSmbiosValue(&chassis->version); - if (ffSysctlGetString("machdep.dmi.chassis-vendor", &chassis->vendor) == NULL) + } + if (ffSysctlGetString("machdep.dmi.chassis-vendor", &chassis->vendor) == NULL) { ffCleanUpSmbiosValue(&chassis->vendor); - if (ffSysctlGetString("machdep.dmi.chassis-serial", &chassis->serial) == NULL) + } + if (ffSysctlGetString("machdep.dmi.chassis-serial", &chassis->serial) == NULL) { ffCleanUpSmbiosValue(&chassis->serial); + } return NULL; } diff --git a/src/detection/chassis/chassis_nosupport.c b/src/detection/chassis/chassis_nosupport.c index c2acd7579..5cdb873a5 100644 --- a/src/detection/chassis/chassis_nosupport.c +++ b/src/detection/chassis/chassis_nosupport.c @@ -1,6 +1,5 @@ #include "chassis.h" -const char* ffDetectChassis(FF_MAYBE_UNUSED FFChassisResult* result) -{ +const char* ffDetectChassis(FF_MAYBE_UNUSED FFChassisResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/chassis/chassis_windows.c b/src/detection/chassis/chassis_windows.c index f50eaf9e0..f4e4f09b9 100644 --- a/src/detection/chassis/chassis_windows.c +++ b/src/detection/chassis/chassis_windows.c @@ -2,43 +2,43 @@ #include "common/smbiosHelper.h" // 7.4 -typedef struct FFSmbiosSystemEnclosure -{ +typedef struct FFSmbiosSystemEnclosure { FFSmbiosHeader Header; - uint8_t Manufacturer; // string - uint8_t Type; // varies - uint8_t Version; // string - uint8_t SerialNumber; // string + uint8_t Manufacturer; // string + uint8_t Type; // varies + uint8_t Version; // string + uint8_t SerialNumber; // string uint8_t AssetTagNumber; // string // 2.1+ - uint8_t BootupState; // enum + uint8_t BootupState; // enum uint8_t PowerSupplyState; // enum - uint8_t ThermalState; // enum - uint8_t SecurityStatus; // enum + uint8_t ThermalState; // enum + uint8_t SecurityStatus; // enum // 2.3+ - uint32_t OEMDefined; // varies - uint8_t Height; // varies - uint8_t NumberOfPowerCords; // varies + uint32_t OEMDefined; // varies + uint8_t Height; // varies + uint8_t NumberOfPowerCords; // varies uint8_t ContainedElementCount; // varies uint8_t ContainedRecordLength; // varies - uint8_t ContainedElements[]; // varies + uint8_t ContainedElements[]; // varies } __attribute__((__packed__)) FFSmbiosSystemEnclosure; static_assert(offsetof(FFSmbiosSystemEnclosure, ContainedElements) == 0x15, "FFSmbiosSystemEnclosure: Wrong struct alignment"); -const char* ffDetectChassis(FFChassisResult* result) -{ +const char* ffDetectChassis(FFChassisResult* result) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosSystemEnclosure* data = (const FFSmbiosSystemEnclosure*) (*smbiosTable)[FF_SMBIOS_TYPE_SYSTEM_ENCLOSURE]; - if (!data) + if (!data) { return "System enclosure is not found in SMBIOS data"; + } const char* strings = (const char*) data + data->Header.Length; diff --git a/src/detection/command/command.c b/src/detection/command/command.c index 982b66fa4..caec403ef 100644 --- a/src/detection/command/command.c +++ b/src/detection/command/command.c @@ -2,8 +2,7 @@ #include "common/processing.h" #include "common/FFstrbuf.h" -typedef struct FFCommandResultBundle -{ +typedef struct FFCommandResultBundle { FFProcessHandle handle; const char* error; } FFCommandResultBundle; @@ -13,26 +12,25 @@ static FFlist commandQueue = { .elementSize = sizeof(FFCommandResultBundle), }; -static const char* spawnProcess(FFCommandOptions* options, FFProcessHandle* handle) -{ - if (options->text.length == 0) +static const char* spawnProcess(FFCommandOptions* options, FFProcessHandle* handle) { + if (options->text.length == 0) { return "No command text specified"; + } - return ffProcessSpawn(options->param.length ? (char* const[]){ - options->shell.chars, - options->param.chars, - options->text.chars, - NULL - } : (char* const[]){ - options->shell.chars, - options->text.chars, - NULL - }, options->useStdErr, handle); + return ffProcessSpawn(options->param.length ? (char* const[]) { + options->shell.chars, + options->param.chars, + options->text.chars, + NULL} + : (char* const[]) {options->shell.chars, options->text.chars, NULL}, + options->useStdErr, + handle); } -bool ffPrepareCommand(FFCommandOptions* options) -{ - if (!options->parallel) return false; +bool ffPrepareCommand(FFCommandOptions* options) { + if (!options->parallel) { + return false; + } FFCommandResultBundle* bundle = ffListAdd(&commandQueue); bundle->error = spawnProcess(options, &bundle->handle); @@ -40,20 +38,22 @@ bool ffPrepareCommand(FFCommandOptions* options) return true; } -const char* ffDetectCommand(FFCommandOptions* options, FFstrbuf* result) -{ +const char* ffDetectCommand(FFCommandOptions* options, FFstrbuf* result) { FFCommandResultBundle bundle = {}; - if (!options->parallel) + if (!options->parallel) { bundle.error = spawnProcess(options, &bundle.handle); - else if (!ffListShift(&commandQueue, &bundle)) + } else if (!ffListShift(&commandQueue, &bundle)) { return "[BUG] command queue is empty"; + } - if (bundle.error) + if (bundle.error) { return bundle.error; + } bundle.error = ffProcessReadOutput(&bundle.handle, result); - if (bundle.error) + if (bundle.error) { return bundle.error; + } ffStrbufTrimRightSpace(result); return NULL; diff --git a/src/detection/cpu/cpu.c b/src/detection/cpu/cpu.c index 9bfa7e7fd..45f65c171 100644 --- a/src/detection/cpu/cpu.c +++ b/src/detection/cpu/cpu.c @@ -2,111 +2,126 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu); -const char* ffDetectCPU(const FFCPUOptions* options, FFCPUResult* cpu) -{ +const char* ffDetectCPU(const FFCPUOptions* options, FFCPUResult* cpu) { const char* error = ffDetectCPUImpl(options, cpu); - if (error) return error; + if (error) { + return error; + } const char* removeStrings[] = { - " CPU", " FPU", " APU", " Processor", - " Dual-Core", " Quad-Core", " Six-Core", " Eight-Core", " Ten-Core", - " 2-Core", " 4-Core", " 6-Core", " 8-Core", " 10-Core", " 12-Core", " 14-Core", " 16-Core" - }; + " CPU", " FPU", " APU", " Processor", " Dual-Core", " Quad-Core", " Six-Core", " Eight-Core", " Ten-Core", " 2-Core", " 4-Core", " 6-Core", " 8-Core", " 10-Core", " 12-Core", " 14-Core", " 16-Core"}; ffStrbufRemoveStrings(&cpu->name, ARRAY_SIZE(removeStrings), removeStrings); uint32_t radeonGraphics = ffStrbufFirstIndexS(&cpu->name, " w/ Radeon "); // w/ Radeon 780M Graphics - if (radeonGraphics >= cpu->name.length) + if (radeonGraphics >= cpu->name.length) { radeonGraphics = ffStrbufFirstIndexS(&cpu->name, " with Radeon "); - if (radeonGraphics < cpu->name.length) + } + if (radeonGraphics < cpu->name.length) { ffStrbufSubstrBefore(&cpu->name, radeonGraphics); - ffStrbufSubstrBeforeFirstC(&cpu->name, '@'); //Cut the speed output in the name as we append our own - ffStrbufTrimRight(&cpu->name, ' '); //If we removed the @ in previous step there was most likely a space before it + } + ffStrbufSubstrBeforeFirstC(&cpu->name, '@'); // Cut the speed output in the name as we append our own + ffStrbufTrimRight(&cpu->name, ' '); // If we removed the @ in previous step there was most likely a space before it ffStrbufRemoveDupWhitespaces(&cpu->name); return NULL; } -const char* ffCPUAppleCodeToName(uint32_t code) -{ +const char* ffCPUAppleCodeToName(uint32_t code) { // https://github.com/AsahiLinux/docs/wiki/Codenames - switch (code) - { - case 8103: return "Apple M1"; - case 6000: return "Apple M1 Pro"; - case 6001: return "Apple M1 Max"; - case 6002: return "Apple M1 Ultra"; - case 8112: return "Apple M2"; - case 6020: return "Apple M2 Pro"; - case 6021: return "Apple M2 Max"; - case 6022: return "Apple M2 Ultra"; - case 8122: return "Apple M3"; - case 6030: return "Apple M3 Pro"; + switch (code) { + case 8103: + return "Apple M1"; + case 6000: + return "Apple M1 Pro"; + case 6001: + return "Apple M1 Max"; + case 6002: + return "Apple M1 Ultra"; + case 8112: + return "Apple M2"; + case 6020: + return "Apple M2 Pro"; + case 6021: + return "Apple M2 Max"; + case 6022: + return "Apple M2 Ultra"; + case 8122: + return "Apple M3"; + case 6030: + return "Apple M3 Pro"; case 6031: - case 6034: return "Apple M3 Max"; - case 8132: return "Apple M4"; - case 6040: return "Apple M4 Pro"; - case 6041: return "Apple M4 Max"; - default: return NULL; + case 6034: + return "Apple M3 Max"; + case 8132: + return "Apple M4"; + case 6040: + return "Apple M4 Pro"; + case 6041: + return "Apple M4 Max"; + default: + return NULL; } } -const char* ffCPUQualcommCodeToName(uint32_t code) -{ +const char* ffCPUQualcommCodeToName(uint32_t code) { // https://github.com/AsahiLinux/docs/wiki/Codenames - switch (code) - { - case 7180: return "Qualcomm Snapdragon 7c"; - case 7280: return "Qualcomm Snapdragon 7c+ Gen 3"; - case 8180: return "Qualcomm Snapdragon 8cx Gen 2 5G"; - case 8280: return "Qualcomm Snapdragon 8cx Gen 3"; - default: return NULL; + switch (code) { + case 7180: + return "Qualcomm Snapdragon 7c"; + case 7280: + return "Qualcomm Snapdragon 7c+ Gen 3"; + case 8180: + return "Qualcomm Snapdragon 8cx Gen 2 5G"; + case 8280: + return "Qualcomm Snapdragon 8cx Gen 3"; + default: + return NULL; } } #if defined(__x86_64__) || defined(__i386__) -#include +# include -void ffCPUDetectByCpuid(FFCPUResult* cpu) -{ +void ffCPUDetectByCpuid(FFCPUResult* cpu) { uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0; - if (__get_cpuid(0x16, &eax, &ebx, &ecx, &edx)) - { + 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 (eax) { + cpu->frequencyBase = eax; + } + if (ebx) { + cpu->frequencyMax = ebx; + } } - if (__get_cpuid(1, &eax, &ebx, &ecx, &edx)) - { + 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; + 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 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 avx_os = false; bool avx512_os = false; - if (osxsave) - { + if (osxsave) { __asm__ __volatile__( "xgetbv" : "=a"(eax), "=d"(edx) : "c"(0) - : - ); - uint64_t xcr0 = ((uint64_t)edx << 32) | eax; + :); + uint64_t xcr0 = ((uint64_t) edx << 32) | eax; // AVX requires XCR0[1:2] == 11b (XMM and YMM state) avx_os = (xcr0 & 0x6ULL) == 0x6ULL; @@ -115,10 +130,15 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) } 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"; + 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"; + } } } @@ -129,33 +149,32 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) // 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.h" -#include +# ifdef __linux__ +# include "common/io.h" +# include // #include -void ffCPUDetectByCpuid(FFCPUResult* cpu) -{ +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; + 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) - { + 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) - { + } else if (auxv->a_type == AT_HWCAP2) { hwcap2 = auxv->a_un.a_val; } } - if (!hwcap) return; + if (!hwcap) { + return; + } cpu->march = "unknown"; @@ -164,31 +183,31 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) bool has_asimd = (hwcap & (1 << 1) /* HWCAP_ASIMD */) != 0; // ARMv8.1-A - bool has_atomics = (hwcap & (1 << 8) /* HWCAP_ATOMICS */) != 0; // optional from v8.0 - bool has_crc32 = (hwcap & (1 << 7) /* HWCAP_CRC32 */) != 0; // optional from v8.0 + bool has_atomics = (hwcap & (1 << 8) /* HWCAP_ATOMICS */) != 0; // optional from v8.0 + bool has_crc32 = (hwcap & (1 << 7) /* HWCAP_CRC32 */) != 0; // optional from v8.0 bool has_asimdrdm = (hwcap & (1 << 12) /* HWCAP_ASIMDRDM */) != 0; // optional from v8.0 // ARMv8.2-A - bool has_fphp = (hwcap & (1 << 9) /* HWCAP_FPHP */) != 0; // optional + bool has_fphp = (hwcap & (1 << 9) /* HWCAP_FPHP */) != 0; // optional bool has_dcpop = (hwcap & (1 << 16) /* HWCAP_DCPOP */) != 0; // DC CVAP, optional from v8.1 // ARMv8.3-A - bool has_paca = (hwcap & (1 << 30) /* HWCAP_PACA */) != 0; // optional from v8.2 + bool has_paca = (hwcap & (1 << 30) /* HWCAP_PACA */) != 0; // optional from v8.2 bool has_lrcpc = (hwcap & (1 << 15) /* HWCAP_LRCPC */) != 0; // optional from v8.2 - bool has_fcma = (hwcap & (1 << 14) /* HWCAP_FCMA */) != 0; // optional from v8.2 + bool has_fcma = (hwcap & (1 << 14) /* HWCAP_FCMA */) != 0; // optional from v8.2 bool has_jscvt = (hwcap & (1 << 13) /* HWCAP_JSCVT */) != 0; // optional from v8.2 // ARMv8.4-A - bool has_dit = (hwcap & (1 << 24) /* HWCAP_DIT */) != 0; // optional from v8.3 - bool has_flagm = (hwcap & (1 << 27) /* HWCAP_FLAGM */) != 0; // optional from v8.1 + bool has_dit = (hwcap & (1 << 24) /* HWCAP_DIT */) != 0; // optional from v8.3 + bool has_flagm = (hwcap & (1 << 27) /* HWCAP_FLAGM */) != 0; // optional from v8.1 bool has_ilrcpc = (hwcap & (1 << 26) /* HWCAP_ILRCPC */) != 0; // optional from v8.2 // ARMv8.5-A - bool has_bti = (hwcap2 & (1 << 17) /* HWCAP2_BTI */) != 0; // optional from v8.4 - bool has_sb = (hwcap & (1 << 29) /* HWCAP_SB */) != 0; // optional from v8.0 + bool has_bti = (hwcap2 & (1 << 17) /* HWCAP2_BTI */) != 0; // optional from v8.4 + bool has_sb = (hwcap & (1 << 29) /* HWCAP_SB */) != 0; // optional from v8.0 bool has_dcpodp = (hwcap2 & (1 << 0) /* HWCAP2_DCPODP */) != 0; // optional from v8.1 bool has_flagm2 = (hwcap2 & (1 << 7) /* HWCAP2_FLAGM2 */) != 0; // optional from v8.4 - bool has_frint = (hwcap2 & (1 << 8) /* HWCAP2_FRINT */) != 0; // optional from v8.4 + bool has_frint = (hwcap2 & (1 << 8) /* HWCAP2_FRINT */) != 0; // optional from v8.4 // ARMv9.0-A bool has_sve2 = (hwcap2 & (1 << 1) /* HWCAP2_SVE2 */) != 0; @@ -221,7 +240,7 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) bool has_f8e5m2 = (hwcap2 & (1UL << 56) /* HWCAP2_F8E5M2 */) != 0; // optional from v9.2 // ARMv9.6-A - bool has_cmpbr = (hwcap & (1UL << 33) /* HWCAP_CMPBR */) != 0; // optional from v9.5 + bool has_cmpbr = (hwcap & (1UL << 33) /* HWCAP_CMPBR */) != 0; // optional from v9.5 bool has_fprcvt = (hwcap & (1UL << 34) /* HWCAP_FPRCVT */) != 0; // optional from v9.5 if (has_sve2 || has_sme) { @@ -266,77 +285,78 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) } } } -#elif __APPLE__ -#include +# elif __APPLE__ +# include // #include // Not available in macOS 14- -void ffCPUDetectByCpuid(FFCPUResult* cpu) -{ +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; + 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)) +// 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) + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 @@ -376,85 +396,82 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) } } - #undef HAS_CAP +# undef HAS_CAP } -#elif _WIN32 -#include +# elif _WIN32 +# include // 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 +# 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) -{ +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) + 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 + 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 + 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 + 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 (*) + 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 + 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 + 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 + 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 + bool has_sme = IsProcessorFeaturePresent(PF_ARM_SME_INSTRUCTIONS_AVAILABLE); // SME // ARMv9.3-A - bool has_sme2 = IsProcessorFeaturePresent(PF_ARM_SME2_INSTRUCTIONS_AVAILABLE); // SME2 + 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 + bool has_sme2p1 = IsProcessorFeaturePresent(PF_ARM_SME2_1_INSTRUCTIONS_AVAILABLE); // SME2.1 - - if (has_sve2 || has_sme) - { + if (has_sve2 || has_sme) { // ARMv9 family if (has_sme2p1) { cpu->march = "ARMv9.4-A"; @@ -467,9 +484,7 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) } else { cpu->march = "ARMv9.0-A"; } - } - else - { + } else { // ARMv8 family if (has_ebf16) { cpu->march = "ARMv8.7-A"; @@ -488,17 +503,15 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) } } } -#else -void ffCPUDetectByCpuid(FF_MAYBE_UNUSED FFCPUResult* cpu) -{ +# else +void ffCPUDetectByCpuid(FF_MAYBE_UNUSED FFCPUResult* cpu) { // Unsupported system } -#endif +# endif #else -void ffCPUDetectByCpuid(FF_MAYBE_UNUSED FFCPUResult* cpu) -{ +void ffCPUDetectByCpuid(FF_MAYBE_UNUSED FFCPUResult* cpu) { // Unsupported architecture } diff --git a/src/detection/cpu/cpu.h b/src/detection/cpu/cpu.h index 906173cae..0f7eeceb5 100644 --- a/src/detection/cpu/cpu.h +++ b/src/detection/cpu/cpu.h @@ -5,14 +5,12 @@ #define FF_CPU_TEMP_UNSET (-DBL_MAX) -typedef struct FFCPUCore -{ +typedef struct FFCPUCore { uint32_t freq; uint32_t count; } FFCPUCore; -typedef struct FFCPUResult -{ +typedef struct FFCPUResult { FFstrbuf name; FFstrbuf vendor; const char* march; // Microarchitecture @@ -24,7 +22,7 @@ typedef struct FFCPUResult uint16_t numaNodes; uint32_t frequencyBase; // GHz - uint32_t frequencyMax; // GHz + uint32_t frequencyMax; // GHz FFCPUCore coreTypes[16]; // number of P cores, E cores, etc. diff --git a/src/detection/cpu/cpu_apple.c b/src/detection/cpu/cpu_apple.c index c141a7284..c7cdc3de3 100644 --- a/src/detection/cpu/cpu_apple.c +++ b/src/detection/cpu/cpu_apple.c @@ -3,106 +3,114 @@ #include "common/apple/smc_temps.h" #include "common/stringUtils.h" -static double detectCpuTemp(const FFCPUOptions* options, const FFstrbuf* cpuName) -{ +static double detectCpuTemp(const FFCPUOptions* options, const FFstrbuf* cpuName) { double result = 0; const char* error = NULL; - if (options->tempSensor.length) - { + if (options->tempSensor.length) { error = ffDetectSmcSpecificTemp(options->tempSensor.chars, &result); - } - else - { - if (ffStrbufStartsWithS(cpuName, "Apple M")) - { - switch (strtol(cpuName->chars + strlen("Apple M"), NULL, 10)) - { - case 1: error = ffDetectSmcTemps(FF_TEMP_CPU_M1X, &result); break; - case 2: error = ffDetectSmcTemps(FF_TEMP_CPU_M2X, &result); break; - case 3: error = ffDetectSmcTemps(FF_TEMP_CPU_M3X, &result); break; - case 4: error = ffDetectSmcTemps(FF_TEMP_CPU_M4X, &result); break; - default: error = "Unsupported Apple Silicon CPU"; + } else { + if (ffStrbufStartsWithS(cpuName, "Apple M")) { + switch (strtol(cpuName->chars + strlen("Apple M"), NULL, 10)) { + case 1: + error = ffDetectSmcTemps(FF_TEMP_CPU_M1X, &result); + break; + case 2: + error = ffDetectSmcTemps(FF_TEMP_CPU_M2X, &result); + break; + case 3: + error = ffDetectSmcTemps(FF_TEMP_CPU_M3X, &result); + break; + case 4: + error = ffDetectSmcTemps(FF_TEMP_CPU_M4X, &result); + break; + default: + error = "Unsupported Apple Silicon CPU"; } - } - else // PPC? + } else { // PPC? error = ffDetectSmcTemps(FF_TEMP_CPU_X64, &result); + } } - if (error) + if (error) { return FF_CPU_TEMP_UNSET; + } return result; } #ifdef __aarch64__ -#include "common/apple/cf_helpers.h" +# include "common/apple/cf_helpers.h" -#include +# include -static const char* detectFrequency(FFCPUResult* cpu) -{ +static const char* detectFrequency(FFCPUResult* cpu) { // https://github.com/giampaolo/psutil/pull/2222/files FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryDevice = IOServiceGetMatchingService(MACH_PORT_NULL, IOServiceNameMatching("pmgr")); - if (!entryDevice) + if (!entryDevice) { return "IOServiceGetMatchingService() failed"; + } - if (!IOObjectConformsTo(entryDevice, "AppleARMIODevice")) + if (!IOObjectConformsTo(entryDevice, "AppleARMIODevice")) { return "\"pmgr\" should conform to \"AppleARMIODevice\""; + } FF_CFTYPE_AUTO_RELEASE CFDataRef freqProperty = (CFDataRef) IORegistryEntryCreateCFProperty(entryDevice, CFSTR("voltage-states5-sram"), kCFAllocatorDefault, kNilOptions); - if (!freqProperty || CFGetTypeID(freqProperty) != CFDataGetTypeID()) + if (!freqProperty || CFGetTypeID(freqProperty) != CFDataGetTypeID()) { return "\"voltage-states5-sram\" in \"pmgr\" is not found"; + } // voltage-states5-sram stores supported pairs of pcores from the lowest to the highest // voltage-states1-sram stores ecores' CFIndex propLength = CFDataGetLength(freqProperty); - if (propLength == 0 || propLength % (CFIndex) sizeof(uint32_t) * 2 != 0) + if (propLength == 0 || propLength % (CFIndex) sizeof(uint32_t) * 2 != 0) { return "Invalid \"voltage-states5-sram\" length"; + } uint32_t* pStart = (uint32_t*) CFDataGetBytePtr(freqProperty); uint32_t pMax = *pStart; - for (CFIndex i = 2; i < propLength / (CFIndex) sizeof(uint32_t) && pStart[i] > 0; i += 2 /* skip voltage */) + for (CFIndex i = 2; i < propLength / (CFIndex) sizeof(uint32_t) && pStart[i] > 0; i += 2 /* skip voltage */) { pMax = pMax > pStart[i] ? pMax : pStart[i]; + } - if (pMax > 0) - { - if (pMax > 100000000) // Assume that pMax is in Hz, M1~M3 + if (pMax > 0) { + if (pMax > 100000000) { // Assume that pMax is in Hz, M1~M3 cpu->frequencyMax = pMax / 1000 / 1000; - else // Assume that pMax is in kHz, M4 and later (#1394) + } else { // Assume that pMax is in kHz, M4 and later (#1394) cpu->frequencyMax = pMax / 1000; + } } return NULL; } #else -static const char* detectFrequency(FFCPUResult* cpu) -{ +static const char* detectFrequency(FFCPUResult* cpu) { cpu->frequencyBase = (uint32_t) (ffSysctlGetInt64("hw.cpufrequency", 0) / 1000 / 1000); cpu->frequencyMax = (uint32_t) (ffSysctlGetInt64("hw.cpufrequency_max", 0) / 1000 / 1000); - if(cpu->frequencyBase == 0) - { + if (cpu->frequencyBase == 0) { unsigned current = 0; size_t size = sizeof(current); - if (sysctl((int[]){ CTL_HW, HW_CPU_FREQ }, 2, ¤t, &size, NULL, 0) == 0) + if (sysctl((int[]) {CTL_HW, HW_CPU_FREQ}, 2, ¤t, &size, NULL, 0) == 0) { cpu->frequencyBase = (uint32_t) (current / 1000 / 1000); + } } return NULL; } #endif -static const char* detectCoreCount(FFCPUResult* cpu) -{ +static const char* detectCoreCount(FFCPUResult* cpu) { uint32_t nPerfLevels = (uint32_t) ffSysctlGetInt("hw.nperflevels", 0); - if (nPerfLevels <= 0) return "sysctl(hw.nperflevels) failed"; + if (nPerfLevels <= 0) { + return "sysctl(hw.nperflevels) failed"; + } char sysctlKey[] = "hw.perflevelN.logicalcpu"; - if (nPerfLevels > ARRAY_SIZE(cpu->coreTypes)) + if (nPerfLevels > ARRAY_SIZE(cpu->coreTypes)) { nPerfLevels = ARRAY_SIZE(cpu->coreTypes); - for (uint32_t i = 0; i < nPerfLevels; ++i) - { + } + for (uint32_t i = 0; i < nPerfLevels; ++i) { sysctlKey[strlen("hw.perflevel")] = (char) ('0' + i); cpu->coreTypes[i] = (FFCPUCore) { .freq = nPerfLevels - i, @@ -112,31 +120,37 @@ static const char* detectCoreCount(FFCPUResult* cpu) return NULL; } -const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) -{ - if (ffSysctlGetString("machdep.cpu.brand_string", &cpu->name) != NULL) +const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { + if (ffSysctlGetString("machdep.cpu.brand_string", &cpu->name) != NULL) { return "sysctlbyname(machdep.cpu.brand_string) failed"; + } ffSysctlGetString("machdep.cpu.vendor", &cpu->vendor); cpu->packages = (uint16_t) ffSysctlGetInt("hw.packages", 1); - if (cpu->vendor.length == 0 && ffStrbufStartsWithS(&cpu->name, "Apple ")) + if (cpu->vendor.length == 0 && ffStrbufStartsWithS(&cpu->name, "Apple ")) { ffStrbufAppendS(&cpu->vendor, "Apple"); + } cpu->coresPhysical = (uint16_t) ffSysctlGetInt("hw.physicalcpu_max", 1); - if(cpu->coresPhysical == 1) + if (cpu->coresPhysical == 1) { cpu->coresPhysical = (uint16_t) ffSysctlGetInt("hw.physicalcpu", 1); + } cpu->coresLogical = (uint16_t) ffSysctlGetInt("hw.logicalcpu_max", 1); - if(cpu->coresLogical == 1) + if (cpu->coresLogical == 1) { cpu->coresLogical = (uint16_t) ffSysctlGetInt("hw.ncpu", 1); + } cpu->coresOnline = (uint16_t) ffSysctlGetInt("hw.logicalcpu", 1); - if(cpu->coresOnline == 1) + if (cpu->coresOnline == 1) { cpu->coresOnline = (uint16_t) ffSysctlGetInt("hw.activecpu", 1); + } ffCPUDetectByCpuid(cpu); detectFrequency(cpu); - if (options->showPeCoreCount) detectCoreCount(cpu); + if (options->showPeCoreCount) { + detectCoreCount(cpu); + } cpu->temperature = options->temp ? detectCpuTemp(options, &cpu->name) : FF_CPU_TEMP_UNSET; diff --git a/src/detection/cpu/cpu_arm.h b/src/detection/cpu/cpu_arm.h index 9f9a45042..571761aeb 100644 --- a/src/detection/cpu/cpu_arm.h +++ b/src/detection/cpu/cpu_arm.h @@ -5,374 +5,584 @@ // https://github.com/util-linux/util-linux/blob/master/sys-utils/lscpu-arm.c // We use the util-linux's data but not its code. Call me if it violates util-linux's GPL license. -static const char* hwImplId2Vendor(uint32_t implId) -{ - switch (implId) - { - case 0x41: return "ARM"; - case 0x42: return "Broadcom"; - case 0x43: return "Cavium"; - case 0x44: return "DEC"; - case 0x46: return "FUJITSU"; - case 0x48: return "HiSilicon"; - case 0x49: return "Infineon"; - case 0x4d: return "Motorola"; - case 0x4e: return "NVIDIA"; - case 0x50: return "APM"; - case 0x51: return "Qualcomm"; - case 0x53: return "Samsung"; - case 0x56: return "Marvell"; - case 0x61: return "Apple"; - case 0x66: return "Faraday"; - case 0x69: return "Intel"; - case 0x6D: return "Microsoft"; - case 0x70: return "Phytium"; - case 0xc0: return "Ampere"; - default: return "Unknown"; +static const char* hwImplId2Vendor(uint32_t implId) { + switch (implId) { + case 0x41: + return "ARM"; + case 0x42: + return "Broadcom"; + case 0x43: + return "Cavium"; + case 0x44: + return "DEC"; + case 0x46: + return "FUJITSU"; + case 0x48: + return "HiSilicon"; + case 0x49: + return "Infineon"; + case 0x4d: + return "Motorola"; + case 0x4e: + return "NVIDIA"; + case 0x50: + return "APM"; + case 0x51: + return "Qualcomm"; + case 0x53: + return "Samsung"; + case 0x56: + return "Marvell"; + case 0x61: + return "Apple"; + case 0x66: + return "Faraday"; + case 0x69: + return "Intel"; + case 0x6D: + return "Microsoft"; + case 0x70: + return "Phytium"; + case 0xc0: + return "Ampere"; + default: + return "Unknown"; } } -static const char* armPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x810: return "ARM810"; - case 0x920: return "ARM920"; - case 0x922: return "ARM922"; - case 0x926: return "ARM926"; - case 0x940: return "ARM940"; - case 0x946: return "ARM946"; - case 0x966: return "ARM966"; - case 0xa20: return "ARM1020"; - case 0xa22: return "ARM1022"; - case 0xa26: return "ARM1026"; - case 0xb02: return "ARM11-MPCore"; - case 0xb36: return "ARM1136"; - case 0xb56: return "ARM1156"; - case 0xb76: return "ARM1176"; - case 0xc05: return "Cortex-A5"; - case 0xc07: return "Cortex-A7"; - case 0xc08: return "Cortex-A8"; - case 0xc09: return "Cortex-A9"; - case 0xc0d: return "Cortex-A17"; /* Originally A12 */ - case 0xc0f: return "Cortex-A15"; - case 0xc0e: return "Cortex-A17"; - case 0xc14: return "Cortex-R4"; - case 0xc15: return "Cortex-R5"; - case 0xc17: return "Cortex-R7"; - case 0xc18: return "Cortex-R8"; - case 0xc20: return "Cortex-M0"; - case 0xc21: return "Cortex-M1"; - case 0xc23: return "Cortex-M3"; - case 0xc24: return "Cortex-M4"; - case 0xc27: return "Cortex-M7"; - case 0xc60: return "Cortex-M0+"; - case 0xd01: return "Cortex-A32"; - case 0xd02: return "Cortex-A34"; - case 0xd03: return "Cortex-A53"; - case 0xd04: return "Cortex-A35"; - case 0xd05: return "Cortex-A55"; - case 0xd06: return "Cortex-A65"; - case 0xd07: return "Cortex-A57"; - case 0xd08: return "Cortex-A72"; - case 0xd09: return "Cortex-A73"; - case 0xd0a: return "Cortex-A75"; - case 0xd0b: return "Cortex-A76"; - case 0xd0c: return "Neoverse-N1"; - case 0xd0d: return "Cortex-A77"; - case 0xd0e: return "Cortex-A76AE"; - case 0xd13: return "Cortex-R52"; - case 0xd14: return "Cortex-R82AE"; - case 0xd15: return "Cortex-R82"; - case 0xd16: return "Cortex-R52+"; - case 0xd20: return "Cortex-M23"; - case 0xd21: return "Cortex-M33"; - case 0xd24: return "Cortex-M52"; - case 0xd22: return "Cortex-M55"; - case 0xd23: return "Cortex-M85"; - case 0xd40: return "Neoverse-V1"; - case 0xd41: return "Cortex-A78"; - case 0xd42: return "Cortex-A78AE"; - case 0xd43: return "Cortex-A65AE"; - case 0xd44: return "Cortex-X1"; - case 0xd46: return "Cortex-A510"; - case 0xd47: return "Cortex-A710"; - case 0xd48: return "Cortex-X2"; - case 0xd49: return "Neoverse-N2"; - case 0xd4a: return "Neoverse-E1"; - case 0xd4b: return "Cortex-A78C"; - case 0xd4c: return "Cortex-X1C"; - case 0xd4d: return "Cortex-A715"; - case 0xd4e: return "Cortex-X3"; - case 0xd4f: return "Neoverse-V2"; - case 0xd80: return "Cortex-A520"; - case 0xd81: return "Cortex-A720"; - case 0xd82: return "Cortex-X4"; - case 0xd83: return "Neoverse-V3AE"; - case 0xd84: return "Neoverse-V3"; - case 0xd85: return "Cortex-X925"; - case 0xd87: return "Cortex-A725"; - case 0xd88: return "Cortex-A520AE"; - case 0xd89: return "Cortex-A720AE"; - case 0xd8a: return "C1-Nano"; - case 0xd8b: return "C1-Pro"; - case 0xd8c: return "C1-Ultra"; - case 0xd8e: return "Neoverse-N3"; - case 0xd8f: return "Cortex-A320"; - case 0xd90: return "C1-Premium"; - default: return NULL; +static const char* armPartId2name(uint32_t partId) { + switch (partId) { + case 0x810: + return "ARM810"; + case 0x920: + return "ARM920"; + case 0x922: + return "ARM922"; + case 0x926: + return "ARM926"; + case 0x940: + return "ARM940"; + case 0x946: + return "ARM946"; + case 0x966: + return "ARM966"; + case 0xa20: + return "ARM1020"; + case 0xa22: + return "ARM1022"; + case 0xa26: + return "ARM1026"; + case 0xb02: + return "ARM11-MPCore"; + case 0xb36: + return "ARM1136"; + case 0xb56: + return "ARM1156"; + case 0xb76: + return "ARM1176"; + case 0xc05: + return "Cortex-A5"; + case 0xc07: + return "Cortex-A7"; + case 0xc08: + return "Cortex-A8"; + case 0xc09: + return "Cortex-A9"; + case 0xc0d: + return "Cortex-A17"; /* Originally A12 */ + case 0xc0f: + return "Cortex-A15"; + case 0xc0e: + return "Cortex-A17"; + case 0xc14: + return "Cortex-R4"; + case 0xc15: + return "Cortex-R5"; + case 0xc17: + return "Cortex-R7"; + case 0xc18: + return "Cortex-R8"; + case 0xc20: + return "Cortex-M0"; + case 0xc21: + return "Cortex-M1"; + case 0xc23: + return "Cortex-M3"; + case 0xc24: + return "Cortex-M4"; + case 0xc27: + return "Cortex-M7"; + case 0xc60: + return "Cortex-M0+"; + case 0xd01: + return "Cortex-A32"; + case 0xd02: + return "Cortex-A34"; + case 0xd03: + return "Cortex-A53"; + case 0xd04: + return "Cortex-A35"; + case 0xd05: + return "Cortex-A55"; + case 0xd06: + return "Cortex-A65"; + case 0xd07: + return "Cortex-A57"; + case 0xd08: + return "Cortex-A72"; + case 0xd09: + return "Cortex-A73"; + case 0xd0a: + return "Cortex-A75"; + case 0xd0b: + return "Cortex-A76"; + case 0xd0c: + return "Neoverse-N1"; + case 0xd0d: + return "Cortex-A77"; + case 0xd0e: + return "Cortex-A76AE"; + case 0xd13: + return "Cortex-R52"; + case 0xd14: + return "Cortex-R82AE"; + case 0xd15: + return "Cortex-R82"; + case 0xd16: + return "Cortex-R52+"; + case 0xd20: + return "Cortex-M23"; + case 0xd21: + return "Cortex-M33"; + case 0xd24: + return "Cortex-M52"; + case 0xd22: + return "Cortex-M55"; + case 0xd23: + return "Cortex-M85"; + case 0xd40: + return "Neoverse-V1"; + case 0xd41: + return "Cortex-A78"; + case 0xd42: + return "Cortex-A78AE"; + case 0xd43: + return "Cortex-A65AE"; + case 0xd44: + return "Cortex-X1"; + case 0xd46: + return "Cortex-A510"; + case 0xd47: + return "Cortex-A710"; + case 0xd48: + return "Cortex-X2"; + case 0xd49: + return "Neoverse-N2"; + case 0xd4a: + return "Neoverse-E1"; + case 0xd4b: + return "Cortex-A78C"; + case 0xd4c: + return "Cortex-X1C"; + case 0xd4d: + return "Cortex-A715"; + case 0xd4e: + return "Cortex-X3"; + case 0xd4f: + return "Neoverse-V2"; + case 0xd80: + return "Cortex-A520"; + case 0xd81: + return "Cortex-A720"; + case 0xd82: + return "Cortex-X4"; + case 0xd83: + return "Neoverse-V3AE"; + case 0xd84: + return "Neoverse-V3"; + case 0xd85: + return "Cortex-X925"; + case 0xd87: + return "Cortex-A725"; + case 0xd88: + return "Cortex-A520AE"; + case 0xd89: + return "Cortex-A720AE"; + case 0xd8a: + return "C1-Nano"; + case 0xd8b: + return "C1-Pro"; + case 0xd8c: + return "C1-Ultra"; + case 0xd8e: + return "Neoverse-N3"; + case 0xd8f: + return "Cortex-A320"; + case 0xd90: + return "C1-Premium"; + default: + return NULL; } } -static const char* brcmPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x0f: return "Brahma-B15"; - case 0x100: return "Brahma-B53"; - case 0x516: return "ThunderX2"; - default: return NULL; +static const char* brcmPartId2name(uint32_t partId) { + switch (partId) { + case 0x0f: + return "Brahma-B15"; + case 0x100: + return "Brahma-B53"; + case 0x516: + return "ThunderX2"; + default: + return NULL; } } -static const char* decPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0xa10: return "SA110"; - case 0xa11: return "SA1100"; - default: return NULL; +static const char* decPartId2name(uint32_t partId) { + switch (partId) { + case 0xa10: + return "SA110"; + case 0xa11: + return "SA1100"; + default: + return NULL; } } -static const char* caviumPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x0a0: return "ThunderX"; - case 0x0a1: return "ThunderX-88XX"; - case 0x0a2: return "ThunderX-81XX"; - case 0x0a3: return "ThunderX-83XX"; - case 0x0af: return "ThunderX2-99xx"; - case 0x0b0: return "OcteonTX2"; - case 0x0b1: return "OcteonTX2-98XX"; - case 0x0b2: return "OcteonTX2-96XX"; - case 0x0b3: return "OcteonTX2-95XX"; - case 0x0b4: return "OcteonTX2-95XXN"; - case 0x0b5: return "OcteonTX2-95XXMM"; - case 0x0b6: return "OcteonTX2-95XXO"; - case 0x0b8: return "ThunderX3-T110"; - default: return NULL; +static const char* caviumPartId2name(uint32_t partId) { + switch (partId) { + case 0x0a0: + return "ThunderX"; + case 0x0a1: + return "ThunderX-88XX"; + case 0x0a2: + return "ThunderX-81XX"; + case 0x0a3: + return "ThunderX-83XX"; + case 0x0af: + return "ThunderX2-99xx"; + case 0x0b0: + return "OcteonTX2"; + case 0x0b1: + return "OcteonTX2-98XX"; + case 0x0b2: + return "OcteonTX2-96XX"; + case 0x0b3: + return "OcteonTX2-95XX"; + case 0x0b4: + return "OcteonTX2-95XXN"; + case 0x0b5: + return "OcteonTX2-95XXMM"; + case 0x0b6: + return "OcteonTX2-95XXO"; + case 0x0b8: + return "ThunderX3-T110"; + default: + return NULL; } } -static const char* apmPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x000: return "X-Gene"; - default: return NULL; +static const char* apmPartId2name(uint32_t partId) { + switch (partId) { + case 0x000: + return "X-Gene"; + default: + return NULL; } } -static const char* qcomPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x001: return "Oryon 1"; - case 0x002: return "Oryon 2"; - case 0x00f: return "Scorpion"; - case 0x02d: return "Scorpion"; - case 0x04d: return "Krait"; - case 0x06f: return "Krait"; - case 0x201: return "Kryo"; - case 0x205: return "Kryo"; - case 0x211: return "Kryo"; - case 0x800: return "Falkor-V1/Kryo"; - case 0x801: return "Kryo-V2"; - case 0x802: return "Kryo-3XX-Gold"; - case 0x803: return "Kryo-3XX-Silver"; - case 0x804: return "Kryo-4XX-Gold"; - case 0x805: return "Kryo-4XX-Silver"; - case 0xc00: return "Falkor"; - case 0xc01: return "Saphira"; - default: return NULL; +static const char* qcomPartId2name(uint32_t partId) { + switch (partId) { + case 0x001: + return "Oryon 1"; + case 0x002: + return "Oryon 2"; + case 0x00f: + return "Scorpion"; + case 0x02d: + return "Scorpion"; + case 0x04d: + return "Krait"; + case 0x06f: + return "Krait"; + case 0x201: + return "Kryo"; + case 0x205: + return "Kryo"; + case 0x211: + return "Kryo"; + case 0x800: + return "Falkor-V1/Kryo"; + case 0x801: + return "Kryo-V2"; + case 0x802: + return "Kryo-3XX-Gold"; + case 0x803: + return "Kryo-3XX-Silver"; + case 0x804: + return "Kryo-4XX-Gold"; + case 0x805: + return "Kryo-4XX-Silver"; + case 0xc00: + return "Falkor"; + case 0xc01: + return "Saphira"; + default: + return NULL; } } -static const char* samsungPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x001: return "Exynos-M1"; - case 0x002: return "Exynos-M3"; - case 0x003: return "Exynos-M4"; - case 0x004: return "Exynos-M5"; - default: return NULL; +static const char* samsungPartId2name(uint32_t partId) { + switch (partId) { + case 0x001: + return "Exynos-M1"; + case 0x002: + return "Exynos-M3"; + case 0x003: + return "Exynos-M4"; + case 0x004: + return "Exynos-M5"; + default: + return NULL; } } -static const char* nvidiaPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x000: return "Denver"; - case 0x003: return "Denver-2"; - case 0x004: return "Carmel"; - case 0x010: return "Olympus"; - default: return NULL; +static const char* nvidiaPartId2name(uint32_t partId) { + switch (partId) { + case 0x000: + return "Denver"; + case 0x003: + return "Denver-2"; + case 0x004: + return "Carmel"; + case 0x010: + return "Olympus"; + default: + return NULL; } } -static const char* marvellPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x131: return "Feroceon-88FR131"; - case 0x581: return "PJ4/PJ4b"; - case 0x584: return "PJ4B-MP"; - default: return NULL; +static const char* marvellPartId2name(uint32_t partId) { + switch (partId) { + case 0x131: + return "Feroceon-88FR131"; + case 0x581: + return "PJ4/PJ4b"; + case 0x584: + return "PJ4B-MP"; + default: + return NULL; } } -static const char* applePartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x000: return "Swift"; - case 0x001: return "Cyclone"; - case 0x002: return "Typhoon"; - case 0x003: return "Typhoon/Capri"; - case 0x004: return "Twister"; - case 0x005: return "Twister/Elba/Malta"; - case 0x006: return "Hurricane"; - case 0x007: return "Hurricane/Myst"; - case 0x008: return "Monsoon"; - case 0x009: return "Mistral"; - case 0x00b: return "Vortex"; - case 0x00c: return "Tempest"; - case 0x00f: return "Tempest-M9"; - case 0x010: return "Vortex/Aruba"; - case 0x011: return "Tempest/Aruba"; - case 0x012: return "Lightning"; - case 0x013: return "Thunder"; - case 0x020: return "Icestorm-A14"; - case 0x021: return "Firestorm-A14"; - case 0x022: return "Icestorm-M1"; - case 0x023: return "Firestorm-M1"; - case 0x024: return "Icestorm-M1-Pro"; - case 0x025: return "Firestorm-M1-Pro"; - case 0x026: return "Thunder-M10"; - case 0x028: return "Icestorm-M1-Max"; - case 0x029: return "Firestorm-M1-Max"; - case 0x030: return "Blizzard-A15"; - case 0x031: return "Avalanche-A15"; - case 0x032: return "Blizzard-M2"; - case 0x033: return "Avalanche-M2"; - case 0x034: return "Blizzard-M2-Pro"; - case 0x035: return "Avalanche-M2-Pro"; - case 0x036: return "Sawtooth-A16"; - case 0x037: return "Everest-A16"; - case 0x038: return "Blizzard-M2-Max"; - case 0x039: return "Avalanche-M2-Max"; - case 0x046: return "Sawtooth-M11"; - case 0x048: return "Sawtooth-M3-Max"; - case 0x049: return "Everest-M3-Max"; - default: return NULL; +static const char* applePartId2name(uint32_t partId) { + switch (partId) { + case 0x000: + return "Swift"; + case 0x001: + return "Cyclone"; + case 0x002: + return "Typhoon"; + case 0x003: + return "Typhoon/Capri"; + case 0x004: + return "Twister"; + case 0x005: + return "Twister/Elba/Malta"; + case 0x006: + return "Hurricane"; + case 0x007: + return "Hurricane/Myst"; + case 0x008: + return "Monsoon"; + case 0x009: + return "Mistral"; + case 0x00b: + return "Vortex"; + case 0x00c: + return "Tempest"; + case 0x00f: + return "Tempest-M9"; + case 0x010: + return "Vortex/Aruba"; + case 0x011: + return "Tempest/Aruba"; + case 0x012: + return "Lightning"; + case 0x013: + return "Thunder"; + case 0x020: + return "Icestorm-A14"; + case 0x021: + return "Firestorm-A14"; + case 0x022: + return "Icestorm-M1"; + case 0x023: + return "Firestorm-M1"; + case 0x024: + return "Icestorm-M1-Pro"; + case 0x025: + return "Firestorm-M1-Pro"; + case 0x026: + return "Thunder-M10"; + case 0x028: + return "Icestorm-M1-Max"; + case 0x029: + return "Firestorm-M1-Max"; + case 0x030: + return "Blizzard-A15"; + case 0x031: + return "Avalanche-A15"; + case 0x032: + return "Blizzard-M2"; + case 0x033: + return "Avalanche-M2"; + case 0x034: + return "Blizzard-M2-Pro"; + case 0x035: + return "Avalanche-M2-Pro"; + case 0x036: + return "Sawtooth-A16"; + case 0x037: + return "Everest-A16"; + case 0x038: + return "Blizzard-M2-Max"; + case 0x039: + return "Avalanche-M2-Max"; + case 0x046: + return "Sawtooth-M11"; + case 0x048: + return "Sawtooth-M3-Max"; + case 0x049: + return "Everest-M3-Max"; + default: + return NULL; } } -static const char* faradayPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x526: return "FA526"; - case 0x626: return "FA626"; - default: return NULL; +static const char* faradayPartId2name(uint32_t partId) { + switch (partId) { + case 0x526: + return "FA526"; + case 0x626: + return "FA626"; + default: + return NULL; } } -static const char* intelPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x200: return "i80200"; - case 0x210: return "PXA250A"; - case 0x212: return "PXA210A"; - case 0x242: return "i80321-400"; - case 0x243: return "i80321-600"; - case 0x290: return "PXA250B/PXA26x"; - case 0x292: return "PXA210B"; - case 0x2c2: return "i80321-400-B0"; - case 0x2c3: return "i80321-600-B0"; - case 0x2d0: return "PXA250C/PXA255/PXA26x"; - case 0x2d2: return "PXA210C"; - case 0x411: return "PXA27x"; - case 0x41c: return "IPX425-533"; - case 0x41d: return "IPX425-400"; - case 0x41f: return "IPX425-266"; - case 0x682: return "PXA32x"; - case 0x683: return "PXA930/PXA935"; - case 0x688: return "PXA30x"; - case 0x689: return "PXA31x"; - case 0xb11: return "SA1110"; - case 0xc12: return "IPX1200"; - default: return NULL; +static const char* intelPartId2name(uint32_t partId) { + switch (partId) { + case 0x200: + return "i80200"; + case 0x210: + return "PXA250A"; + case 0x212: + return "PXA210A"; + case 0x242: + return "i80321-400"; + case 0x243: + return "i80321-600"; + case 0x290: + return "PXA250B/PXA26x"; + case 0x292: + return "PXA210B"; + case 0x2c2: + return "i80321-400-B0"; + case 0x2c3: + return "i80321-600-B0"; + case 0x2d0: + return "PXA250C/PXA255/PXA26x"; + case 0x2d2: + return "PXA210C"; + case 0x411: + return "PXA27x"; + case 0x41c: + return "IPX425-533"; + case 0x41d: + return "IPX425-400"; + case 0x41f: + return "IPX425-266"; + case 0x682: + return "PXA32x"; + case 0x683: + return "PXA930/PXA935"; + case 0x688: + return "PXA30x"; + case 0x689: + return "PXA31x"; + case 0xb11: + return "SA1110"; + case 0xc12: + return "IPX1200"; + default: + return NULL; } } -static const char* fujitsuPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x001: return "A64FX"; - case 0x003: return "MONAKA"; - default: return NULL; +static const char* fujitsuPartId2name(uint32_t partId) { + switch (partId) { + case 0x001: + return "A64FX"; + case 0x003: + return "MONAKA"; + default: + return NULL; } } -static const char* hisiPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0xd01: return "TaiShan-v110"; /* used in Kunpeng-920 SoC */ - case 0xd02: return "TaiShan-v120"; /* used in Kirin 990A and 9000S SoCs */ - case 0xd40: return "Cortex-A76"; /* HiSilicon uses this ID though advertises A76 */ - case 0xd41: return "Cortex-A77"; /* HiSilicon uses this ID though advertises A77 */ - default: return NULL; +static const char* hisiPartId2name(uint32_t partId) { + switch (partId) { + case 0xd01: + return "TaiShan-v110"; /* used in Kunpeng-920 SoC */ + case 0xd02: + return "TaiShan-v120"; /* used in Kirin 990A and 9000S SoCs */ + case 0xd40: + return "Cortex-A76"; /* HiSilicon uses this ID though advertises A76 */ + case 0xd41: + return "Cortex-A77"; /* HiSilicon uses this ID though advertises A77 */ + default: + return NULL; } } -static const char* amperePartId2name(uint32_t partId) -{ - switch (partId) - { - case 0xac3: return "Ampere-1"; - case 0xac4: return "Ampere-1a"; - default: return NULL; +static const char* amperePartId2name(uint32_t partId) { + switch (partId) { + case 0xac3: + return "Ampere-1"; + case 0xac4: + return "Ampere-1a"; + default: + return NULL; } } -static const char* ftPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0x303: return "FTC310"; - case 0x660: return "FTC660"; - case 0x661: return "FTC661"; - case 0x662: return "FTC662"; - case 0x663: return "FTC663"; - case 0x664: return "FTC664"; - case 0x862: return "FTC862"; - default: return NULL; +static const char* ftPartId2name(uint32_t partId) { + switch (partId) { + case 0x303: + return "FTC310"; + case 0x660: + return "FTC660"; + case 0x661: + return "FTC661"; + case 0x662: + return "FTC662"; + case 0x663: + return "FTC663"; + case 0x664: + return "FTC664"; + case 0x862: + return "FTC862"; + default: + return NULL; } } -static const char* msPartId2name(uint32_t partId) -{ - switch (partId) - { - case 0xd49: return "Azure-Cobalt-100"; - default: return NULL; +static const char* msPartId2name(uint32_t partId) { + switch (partId) { + case 0xd49: + return "Azure-Cobalt-100"; + default: + return NULL; } } diff --git a/src/detection/cpu/cpu_bsd.c b/src/detection/cpu/cpu_bsd.c index c8401dde1..58ee80361 100644 --- a/src/detection/cpu/cpu_bsd.c +++ b/src/detection/cpu/cpu_bsd.c @@ -4,28 +4,25 @@ #include #if __has_include() - #include - #define FF_HAVE_CPUSET 1 +# include +# define FF_HAVE_CPUSET 1 #endif -static const char* detectCpuTemp(const FFCPUOptions* options, double* current) -{ +static const char* detectCpuTemp(const FFCPUOptions* options, double* current) { int temp; - if (options->tempSensor.length > 0) - { + if (options->tempSensor.length > 0) { temp = ffSysctlGetInt(options->tempSensor.chars, -999999); - if (temp == -999999) + if (temp == -999999) { return "ffSysctlGetInt(options->tempSensor) failed"; - } - else - { + } + } else { temp = ffSysctlGetInt("dev.cpu.0.temperature", -999999); - if (temp == -999999) - { + if (temp == -999999) { // Thermal zone temperature temp = ffSysctlGetInt("hw.acpi.thermal.tz0.temperature", -999999); - if (temp == -999999) + if (temp == -999999) { return "ffSysctlGetInt(\"dev.cpu.0.temperature\" or \"hw.acpi.thermal.tz0.temperature\") failed"; + } } } @@ -34,18 +31,17 @@ static const char* detectCpuTemp(const FFCPUOptions* options, double* current) return NULL; } -const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) -{ - if (ffSysctlGetString("hw.model", &cpu->name) != NULL) +const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { + if (ffSysctlGetString("hw.model", &cpu->name) != NULL) { return "sysctlbyname(hw.model) failed"; + } cpu->coresLogical = (uint16_t) ffSysctlGetInt("hw.ncpu", 1); cpu->coresPhysical = (uint16_t) ffSysctlGetInt("kern.smp.cores", 0); cpu->coresOnline = (uint16_t) ffSysctlGetInt("kern.smp.cpus", cpu->coresLogical); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffSysctlGetString("kern.sched.topology_spec", &buffer) == NULL && buffer.length > 0) - { + if (ffSysctlGetString("kern.sched.topology_spec", &buffer) == NULL && buffer.length > 0) { // // // 0, 1, 2, 3 @@ -61,8 +57,9 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) // // // - for (char* p = buffer.chars; (p = strstr(p, "\n \n")); ++p) + for (char* p = buffer.chars; (p = strstr(p, "\n \n")); ++p) { cpu->packages++; + } } #if FF_HAVE_CPUSET && (__x86_64__ || __i386__) @@ -77,28 +74,34 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) ffCPUDetectByCpuid(cpu); uint32_t clockrate = (uint32_t) ffSysctlGetInt("hw.clockrate", 0); - if (clockrate > cpu->frequencyBase) cpu->frequencyBase = clockrate; + if (clockrate > cpu->frequencyBase) { + cpu->frequencyBase = clockrate; + } - for (uint16_t i = 0; i < cpu->coresLogical; ++i) - { + for (uint16_t i = 0; i < cpu->coresLogical; ++i) { ffStrbufClear(&buffer); char key[32]; snprintf(key, sizeof(key), "dev.cpu.%u.freq_levels", i); - if (ffSysctlGetString(key, &buffer) == NULL) - { - if (buffer.length == 0) continue; + if (ffSysctlGetString(key, &buffer) == NULL) { + if (buffer.length == 0) { + continue; + } // MHz/Watts pairs like: 2501/32000 2187/27125 2000/24000 uint32_t fmax = (uint32_t) strtoul(buffer.chars, NULL, 10); - if (cpu->frequencyMax < fmax) cpu->frequencyMax = fmax; - } - else + if (cpu->frequencyMax < fmax) { + cpu->frequencyMax = fmax; + } + } else { break; + } } cpu->temperature = FF_CPU_TEMP_UNSET; - if (options->temp) detectCpuTemp(options, &cpu->temperature); + if (options->temp) { + detectCpuTemp(options, &cpu->temperature); + } cpu->numaNodes = (uint16_t) ffSysctlGetInt("vm.ndomains", 0); diff --git a/src/detection/cpu/cpu_haiku.c b/src/detection/cpu/cpu_haiku.c index 7e38f31f6..1831a83e0 100644 --- a/src/detection/cpu/cpu_haiku.c +++ b/src/detection/cpu/cpu_haiku.c @@ -4,28 +4,29 @@ #include #include -const char* ffDetectCPUImpl(FF_MAYBE_UNUSED const FFCPUOptions* options, FFCPUResult* cpu) -{ +const char* ffDetectCPUImpl(FF_MAYBE_UNUSED const FFCPUOptions* options, FFCPUResult* cpu) { system_info sysInfo; - if (get_system_info(&sysInfo) != B_OK) + if (get_system_info(&sysInfo) != B_OK) { return "get_system_info() failed"; + } uint32 topoNodeCount = 0; get_cpu_topology_info(NULL, &topoNodeCount); - if (topoNodeCount == 0) + if (topoNodeCount == 0) { return "get_cpu_topology_info(NULL) failed"; + } FF_AUTO_FREE cpu_topology_node_info* topology = malloc(sizeof(*topology) * topoNodeCount); - if (get_cpu_topology_info(topology, &topoNodeCount) != B_OK) + if (get_cpu_topology_info(topology, &topoNodeCount) != B_OK) { return "get_cpu_topology_info(topology) failed"; + } enum cpu_platform platform = B_CPU_UNKNOWN; enum cpu_vendor cpuVendor = B_CPU_VENDOR_UNKNOWN; uint32 cpuModel = 0, frequency = 0; uint16_t packages = 0, cores = 0; - for (uint32 i = 0; i < topoNodeCount; i++) - { + for (uint32 i = 0; i < topoNodeCount; i++) { switch (topology[i].type) { case B_TOPOLOGY_ROOT: platform = topology[i].data.root.platform; @@ -48,15 +49,18 @@ const char* ffDetectCPUImpl(FF_MAYBE_UNUSED const FFCPUOptions* options, FFCPURe } } - const char *model = get_cpu_model_string(platform, cpuVendor, cpuModel); - if (model) + const char* model = get_cpu_model_string(platform, cpuVendor, cpuModel); + if (model) { ffStrbufSetS(&cpu->name, model); - else + } else { ffStrbufSetF(&cpu->name, "(Unknown %" B_PRIx32 ")", cpuModel); + } ffStrbufSetS(&cpu->vendor, get_cpu_vendor_string(cpuVendor)); ffCPUDetectByCpuid(cpu); - if (cpu->frequencyBase < frequency) cpu->frequencyBase = frequency; + if (cpu->frequencyBase < frequency) { + cpu->frequencyBase = frequency; + } cpu->packages = packages; cpu->coresPhysical = cores; cpu->coresOnline = cpu->coresLogical = (uint16_t) sysInfo.cpu_count; diff --git a/src/detection/cpu/cpu_linux.c b/src/detection/cpu/cpu_linux.c index cdbf58413..359b24165 100644 --- a/src/detection/cpu/cpu_linux.c +++ b/src/detection/cpu/cpu_linux.c @@ -14,169 +14,171 @@ #define FF_CPUINFO_PATH "/proc/cpuinfo" -static double readTempFile(int dfd, const char* filename, FFstrbuf* buffer) -{ - if (filename ? !ffReadFileBufferRelative(dfd, filename, buffer) : !ffReadFDBuffer(dfd, buffer)) +static double readTempFile(int dfd, const char* filename, FFstrbuf* buffer) { + if (filename ? !ffReadFileBufferRelative(dfd, filename, buffer) : !ffReadFDBuffer(dfd, buffer)) { return FF_CPU_TEMP_UNSET; + } double value = ffStrbufToDouble(buffer, FF_CPU_TEMP_UNSET); // millidegree Celsius - if (value == FF_CPU_TEMP_UNSET) + if (value == FF_CPU_TEMP_UNSET) { return FF_CPU_TEMP_UNSET; + } return value / 1000.; } -static double parseTZDir(int dfd, FFstrbuf* buffer) -{ - if (!ffReadFileBufferRelative(dfd, "type", buffer)) +static double parseTZDir(int dfd, FFstrbuf* buffer) { + if (!ffReadFileBufferRelative(dfd, "type", buffer)) { return FF_CPU_TEMP_UNSET; + } if (!ffStrbufStartsWithS(buffer, "cpu") && !ffStrbufStartsWithS(buffer, "soc") && - #if __x86_64__ || __i386__ +#if __x86_64__ || __i386__ !ffStrbufEqualS(buffer, "x86_pkg_temp") && - #endif - true - ) return FF_CPU_TEMP_UNSET; +#endif + true) + return FF_CPU_TEMP_UNSET; return readTempFile(dfd, "temp", buffer); } -static double parseHwmonDir(int dfd, FFstrbuf* buffer) -{ - //https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface - if (!ffReadFileBufferRelative(dfd, "name", buffer)) +static double parseHwmonDir(int dfd, FFstrbuf* buffer) { + // https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface + if (!ffReadFileBufferRelative(dfd, "name", buffer)) { return FF_CPU_TEMP_UNSET; + } ffStrbufTrimRightSpace(buffer); if ( !ffStrbufContainS(buffer, "cpu") && - #if __x86_64__ || __i386__ - !ffStrbufEqualS(buffer, "k10temp") && // AMD +#if __x86_64__ || __i386__ + !ffStrbufEqualS(buffer, "k10temp") && // AMD !ffStrbufEqualS(buffer, "fam15h_power") && // AMD - !ffStrbufEqualS(buffer, "coretemp") && // Intel - #endif - true - ) return FF_CPU_TEMP_UNSET; + !ffStrbufEqualS(buffer, "coretemp") && // Intel +#endif + true) + return FF_CPU_TEMP_UNSET; return readTempFile(dfd, "temp1_input", buffer); } -static double detectCPUTemp(const FFCPUOptions* options) -{ +static double detectCPUTemp(const FFCPUOptions* options) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (options->tempSensor.length > 0) - { + if (options->tempSensor.length > 0) { FF_AUTO_CLOSE_FD int subfd = -1; const char* fileName = NULL; - if (ffStrbufStartsWithS(&options->tempSensor, "hwmon") && ffCharIsDigit(options->tempSensor.chars[strlen("hwmon")])) - { + if (ffStrbufStartsWithS(&options->tempSensor, "hwmon") && ffCharIsDigit(options->tempSensor.chars[strlen("hwmon")])) { FF_AUTO_CLOSE_FD int dfd = open("/sys/class/hwmon/", O_PATH | O_CLOEXEC); subfd = openat(dfd, options->tempSensor.chars, O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (subfd >= 0) + if (subfd >= 0) { fileName = "temp1_input"; - else + } else { subfd = openat(dfd, options->tempSensor.chars, O_RDONLY | O_CLOEXEC); - } - else if (ffStrbufStartsWithS(&options->tempSensor, "thermal_zone") && ffCharIsDigit(options->tempSensor.chars[strlen("thermal_zone")])) - { + } + } else if (ffStrbufStartsWithS(&options->tempSensor, "thermal_zone") && ffCharIsDigit(options->tempSensor.chars[strlen("thermal_zone")])) { FF_AUTO_CLOSE_FD int dfd = open("/sys/class/thermal/", O_PATH | O_CLOEXEC); subfd = openat(dfd, options->tempSensor.chars, O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (subfd >= 0) + if (subfd >= 0) { fileName = "temp"; - else + } else { subfd = openat(dfd, options->tempSensor.chars, O_RDONLY | O_CLOEXEC); - } - else if (ffStrbufStartsWithS(&options->tempSensor, "cputemp.") && ffCharIsDigit(options->tempSensor.chars[strlen("cputemp.")])) - { + } + } else if (ffStrbufStartsWithS(&options->tempSensor, "cputemp.") && ffCharIsDigit(options->tempSensor.chars[strlen("cputemp.")])) { FF_AUTO_CLOSE_FD int dfd = open("/sys/class/platform/", O_PATH | O_CLOEXEC); subfd = openat(dfd, options->tempSensor.chars, O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (subfd >= 0) + if (subfd >= 0) { fileName = "temp1_input"; - else + } else { subfd = openat(dfd, options->tempSensor.chars, O_RDONLY | O_CLOEXEC); - } - else if (ffIsAbsolutePath(options->tempSensor.chars)) - { + } + } else if (ffIsAbsolutePath(options->tempSensor.chars)) { subfd = open(options->tempSensor.chars, O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (subfd >= 0) + if (subfd >= 0) { fileName = "temp1_input"; - else + } else { subfd = open(options->tempSensor.chars, O_RDONLY | O_CLOEXEC); + } } - if (subfd < 0) + if (subfd < 0) { return FF_CPU_TEMP_UNSET; + } return readTempFile(subfd, fileName, &buffer); } { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/hwmon/"); - if(dirp) - { + if (dirp) { int dfd = dirfd(dirp); struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } FF_AUTO_CLOSE_FD int subfd = openat(dfd, entry->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if(subfd < 0) + if (subfd < 0) { continue; + } double result = parseHwmonDir(subfd, &buffer); - if (result != FF_CPU_TEMP_UNSET) + if (result != FF_CPU_TEMP_UNSET) { return result; + } } } } { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/thermal/"); - if(dirp) - { + if (dirp) { int dfd = dirfd(dirp); struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; - if(!ffStrStartsWith(entry->d_name, "thermal_zone")) + } + 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) + if (subfd < 0) { continue; + } double result = parseTZDir(subfd, &buffer); - if (result != FF_CPU_TEMP_UNSET) + if (result != FF_CPU_TEMP_UNSET) { return result; + } } } } { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/devices/platform/"); - if(dirp) - { + if (dirp) { int dfd = dirfd(dirp); struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; - if(!ffStrStartsWith(entry->d_name, "cputemp.")) + } + 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) + if (subfd < 0) { continue; + } double result = parseHwmonDir(subfd, &buffer); - if (result != FF_CPU_TEMP_UNSET) + if (result != FF_CPU_TEMP_UNSET) { return result; + } } } } @@ -184,62 +186,109 @@ static double detectCPUTemp(const FFCPUOptions* options) return FF_CPU_TEMP_UNSET; } -static void detectNumaNodes(FFCPUResult* cpu) -{ +static void detectNumaNodes(FFCPUResult* cpu) { FF_AUTO_CLOSE_DIR DIR* dir = opendir("/sys/devices/system/node/"); - if (!dir) return; + if (!dir) { + return; + } struct dirent* entry; - while ((entry = readdir(dir)) != NULL) - { - if (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN) + while ((entry = readdir(dir)) != NULL) { + if (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN) { continue; - if (ffStrStartsWith(entry->d_name, "node") && ffCharIsDigit(entry->d_name[strlen("node")])) + } + if (ffStrStartsWith(entry->d_name, "node") && ffCharIsDigit(entry->d_name[strlen("node")])) { cpu->numaNodes++; + } } } #ifdef __ANDROID__ -#include "common/settings.h" +# include "common/settings.h" -static void detectQualcomm(FFCPUResult* cpu) -{ +static void detectQualcomm(FFCPUResult* cpu) { // https://en.wikipedia.org/wiki/List_of_Qualcomm_Snapdragon_systems_on_chips assert(cpu->name.length >= 2); uint32_t code = (uint32_t) strtoul(cpu->name.chars + 2, NULL, 10); const char* name = NULL; - switch (code) - { - case 8845: name = "8 Gen 5"; break; // ? - case 8850: name = "8 Elite Gen 5"; break; - case 8735: name = "8s Gen 4"; break; - case 8750: name = "8 Elite"; break; - case 8635: name = "8s Gen 3"; break; - case 8650: name = "8 Gen 3"; break; - case 8550: name = "8 Gen 2"; break; - case 8475: name = "8+ Gen 1"; break; - case 8450: name = "8 Gen 1"; break; - case 7750: name = "7 Gen 4"; break; - case 7675: name = "7+ Gen 3"; break; - case 7635: name = "7s Gen 3"; break; - case 7550: name = "7 Gen 3"; break; - case 7475: name = "7+ Gen 2"; break; - case 7435: name = "7s Gen 2"; break; - case 7450: name = "7 Gen 1"; break; - case 6650: name = "6 Gen 4"; break; - case 6375: name = "6s Gen 3"; break; - case 6475: name = "6 Gen 3"; break; - case 6115: name = "6s Gen 1"; break; - case 6450: name = "6 Gen 1"; break; - case 4635: name = "4s Gen 2"; break; - case 4450: name = "4 Gen 2"; break; - case 4375: name = "4 Gen 1"; break; + switch (code) { + case 8845: + name = "8 Gen 5"; + break; // ? + case 8850: + name = "8 Elite Gen 5"; + break; + case 8735: + name = "8s Gen 4"; + break; + case 8750: + name = "8 Elite"; + break; + case 8635: + name = "8s Gen 3"; + break; + case 8650: + name = "8 Gen 3"; + break; + case 8550: + name = "8 Gen 2"; + break; + case 8475: + name = "8+ Gen 1"; + break; + case 8450: + name = "8 Gen 1"; + break; + case 7750: + name = "7 Gen 4"; + break; + case 7675: + name = "7+ Gen 3"; + break; + case 7635: + name = "7s Gen 3"; + break; + case 7550: + name = "7 Gen 3"; + break; + case 7475: + name = "7+ Gen 2"; + break; + case 7435: + name = "7s Gen 2"; + break; + case 7450: + name = "7 Gen 1"; + break; + case 6650: + name = "6 Gen 4"; + break; + case 6375: + name = "6s Gen 3"; + break; + case 6475: + name = "6 Gen 3"; + break; + case 6115: + name = "6s Gen 1"; + break; + case 6450: + name = "6 Gen 1"; + break; + case 4635: + name = "4s Gen 2"; + break; + case 4450: + name = "4 Gen 2"; + break; + case 4375: + name = "4 Gen 1"; + break; } - if (name) - { + if (name) { char str[32]; ffStrCopy(str, cpu->name.chars, sizeof(str)); ffStrbufSetF(&cpu->name, "Qualcomm Snapdragon %s [%s]", name, str); @@ -247,8 +296,7 @@ static void detectQualcomm(FFCPUResult* cpu) } } -static void detectMediaTek(FFCPUResult* cpu) -{ +static void detectMediaTek(FFCPUResult* cpu) { // https://en.wikipedia.org/wiki/List_of_MediaTek_systems_on_chips assert(cpu->name.length >= 2); @@ -257,24 +305,43 @@ static void detectMediaTek(FFCPUResult* cpu) switch (code) // The SOC code of MTK Dimensity series is full of mess { - case 6993: name = "9500"; break; - case 6991: name = "9400"; break; + case 6993: + name = "9500"; + break; + case 6991: + name = "9400"; + break; case 6989: - case 8796: name = "9300"; break; - case 6985: name = "9200"; break; + case 8796: + name = "9300"; + break; + case 6985: + name = "9200"; + break; case 6983: - case 8798: name = "9000"; break; + case 8798: + name = "9000"; + break; - case 6899: name = "8400"; break; + case 6899: + name = "8400"; + break; case 6897: - case 8792: name = "8300"; break; - case 6896: name = "8200"; break; - case 8795: name = "8100"; break; - case 6895: name = "8000"; break; + case 8792: + name = "8300"; + break; + case 6896: + name = "8200"; + break; + case 8795: + name = "8100"; + break; + case 6895: + name = "8000"; + break; } - if (name) - { + if (name) { char str[32]; ffStrCopy(str, cpu->name.chars, sizeof(str)); ffStrbufSetF(&cpu->name, "MediaTek Dimensity %s [%s]", name, str); @@ -282,38 +349,63 @@ static void detectMediaTek(FFCPUResult* cpu) } } -static void detectExynos(FFCPUResult* cpu) -{ +static void detectExynos(FFCPUResult* cpu) { // https://en.wikipedia.org/wiki/Exynos assert(cpu->name.length > 3); uint32_t code = (uint32_t) strtoul(cpu->name.chars + 3, NULL, 10); const char* name = NULL; - switch (code) - { - case 9955: name = "2500"; break; - case 9945: name = "2400"; break; + switch (code) { + case 9955: + name = "2500"; + break; + case 9945: + name = "2400"; + break; // No 2300 - case 9925: name = "2200"; break; - case 9840: name = "2100"; break; + case 9925: + name = "2200"; + break; + case 9840: + name = "2100"; + break; - case 8855: name = "1580"; break; - case 8845: name = "1480"; break; - case 8835: name = "1380"; break; - case 8535: name = "1330"; break; - case 8825: name = "1280"; break; - case 9815: name = "1080"; break; + case 8855: + name = "1580"; + break; + case 8845: + name = "1480"; + break; + case 8835: + name = "1380"; + break; + case 8535: + name = "1330"; + break; + case 8825: + name = "1280"; + break; + case 9815: + name = "1080"; + break; - case 9830: name = "990"; break; - case 9630: name = "980"; break; + case 9830: + name = "990"; + break; + case 9630: + name = "980"; + break; - case 8805: name = "880"; break; - case 3830: name = "850"; break; + case 8805: + name = "880"; + break; + case 3830: + name = "850"; + break; } - if (name) - { + if (name) { char str[32]; ffStrCopy(str, cpu->name.chars, sizeof(str)); ffStrbufSetF(&cpu->name, "Samsung Exynos %s [%s]", name, str); @@ -321,35 +413,37 @@ static void detectExynos(FFCPUResult* cpu) } } -static void detectAndroid(FFCPUResult* cpu) -{ - if (cpu->name.length == 0) - { - if (ffSettingsGetAndroidProperty("ro.soc.model", &cpu->name)) +static void detectAndroid(FFCPUResult* cpu) { + if (cpu->name.length == 0) { + if (ffSettingsGetAndroidProperty("ro.soc.model", &cpu->name)) { ffStrbufClear(&cpu->vendor); // We usually detect the vendor of CPU core as ARM, but instead we want the vendor of SOC + } } - if (cpu->vendor.length == 0) - { - if (!ffSettingsGetAndroidProperty("ro.soc.manufacturer", &cpu->vendor)) - if (!ffSettingsGetAndroidProperty("ro.product.product.manufacturer", &cpu->vendor)) - if (!ffSettingsGetAndroidProperty("ro.product.vendor.manufacturer", &cpu->vendor)) - if(ffSettingsGetAndroidProperty("ro.mediatek.platform", &cpu->name)) + if (cpu->vendor.length == 0) { + if (!ffSettingsGetAndroidProperty("ro.soc.manufacturer", &cpu->vendor)) { + if (!ffSettingsGetAndroidProperty("ro.product.product.manufacturer", &cpu->vendor)) { + if (!ffSettingsGetAndroidProperty("ro.product.vendor.manufacturer", &cpu->vendor)) { + if (ffSettingsGetAndroidProperty("ro.mediatek.platform", &cpu->name)) { ffStrbufSetStatic(&cpu->vendor, "MediaTek"); + } + } + } + } } - if (ffStrbufEqualS(&cpu->vendor, "QTI")) + if (ffStrbufEqualS(&cpu->vendor, "QTI")) { ffStrbufSetStatic(&cpu->vendor, "Qualcomm"); - else if (ffStrbufIgnCaseEqualS(&cpu->vendor, "MediaTek")) // sometimes "Mediatek" + } else if (ffStrbufIgnCaseEqualS(&cpu->vendor, "MediaTek")) { // sometimes "Mediatek" ffStrbufSetStatic(&cpu->vendor, "MediaTek"); - else if (cpu->vendor.length > 0) + } else if (cpu->vendor.length > 0) { cpu->vendor.chars[0] = (char) toupper(cpu->vendor.chars[0]); + } - if (ffStrbufEqualS(&cpu->vendor, "Qualcomm") && ffStrbufStartsWithS(&cpu->name, "SM")) + if (ffStrbufEqualS(&cpu->vendor, "Qualcomm") && ffStrbufStartsWithS(&cpu->name, "SM")) { detectQualcomm(cpu); - else if (ffStrbufEqualS(&cpu->vendor, "MediaTek") && ffStrbufStartsWithS(&cpu->name, "MT")) + } else if (ffStrbufEqualS(&cpu->vendor, "MediaTek") && ffStrbufStartsWithS(&cpu->name, "MT")) { detectMediaTek(cpu); - else if (ffStrbufEqualS(&cpu->vendor, "Samsung") && ffStrbufStartsWithS(&cpu->name, "s5e")) - { + } else if (ffStrbufEqualS(&cpu->vendor, "Samsung") && ffStrbufStartsWithS(&cpu->name, "s5e")) { cpu->name.chars[0] = 'S'; cpu->name.chars[2] = 'E'; detectExynos(cpu); @@ -358,35 +452,55 @@ static void detectAndroid(FFCPUResult* cpu) #endif #if __arm__ || __aarch64__ -#include "cpu_arm.h" +# include "cpu_arm.h" -static void detectArmName(FFstrbuf* cpuinfo, FFCPUResult* cpu, uint32_t implId) -{ +static void detectArmName(FFstrbuf* cpuinfo, FFCPUResult* cpu, uint32_t implId) { char* line = NULL; size_t len = 0; uint32_t lastPartId = UINT32_MAX; uint32_t num = 0; - while(ffStrbufGetline(&line, &len, cpuinfo)) - { - if (!ffStrStartsWith(line, "CPU part\t: ")) continue; + while (ffStrbufGetline(&line, &len, cpuinfo)) { + if (!ffStrStartsWith(line, "CPU part\t: ")) { + continue; + } uint32_t partId = (uint32_t) strtoul(line + strlen("CPU part\t: "), NULL, 16); const char* name = NULL; - switch (implId) - { - case 0x41: name = armPartId2name(partId); break; - case 0x42: name = brcmPartId2name(partId); break; - case 0x43: name = caviumPartId2name(partId); break; - case 0x44: name = decPartId2name(partId); break; - case 0x46: name = fujitsuPartId2name(partId); break; - case 0x48: name = hisiPartId2name(partId); break; - case 0x4e: name = nvidiaPartId2name(partId); break; - case 0x50: name = apmPartId2name(partId); break; - case 0x51: name = qcomPartId2name(partId); break; - case 0x53: name = samsungPartId2name(partId); break; - case 0x56: name = marvellPartId2name(partId); break; + switch (implId) { + case 0x41: + name = armPartId2name(partId); + break; + case 0x42: + name = brcmPartId2name(partId); + break; + case 0x43: + name = caviumPartId2name(partId); + break; + case 0x44: + name = decPartId2name(partId); + break; + case 0x46: + name = fujitsuPartId2name(partId); + break; + case 0x48: + name = hisiPartId2name(partId); + break; + case 0x4e: + name = nvidiaPartId2name(partId); + break; + case 0x50: + name = apmPartId2name(partId); + break; + case 0x51: + name = qcomPartId2name(partId); + break; + case 0x53: + name = samsungPartId2name(partId); + break; + case 0x56: + name = marvellPartId2name(partId); + break; case 0x61: - if (partId == 0) - { + if (partId == 0) { // https://github.com/Dr-Noob/cpufetch/issues/213#issuecomment-1927782105 ffStrbufSetStatic(&cpu->name, "Virtualized Apple Silicon"); ffStrbufGetlineRestore(&line, &len, cpuinfo); @@ -394,34 +508,45 @@ static void detectArmName(FFstrbuf* cpuinfo, FFCPUResult* cpu, uint32_t implId) } name = applePartId2name(partId); break; - case 0x66: name = faradayPartId2name(partId); break; - case 0x69: name = intelPartId2name(partId); break; - case 0x6d: name = msPartId2name(partId); break; - case 0x70: name = ftPartId2name(partId); break; - case 0xc0: name = amperePartId2name(partId); break; + case 0x66: + name = faradayPartId2name(partId); + break; + case 0x69: + name = intelPartId2name(partId); + break; + case 0x6d: + name = msPartId2name(partId); + break; + case 0x70: + name = ftPartId2name(partId); + break; + case 0xc0: + name = amperePartId2name(partId); + break; } - if (lastPartId != partId) - { - if (lastPartId != UINT32_MAX) - { - if (num > 1) + if (lastPartId != partId) { + if (lastPartId != UINT32_MAX) { + if (num > 1) { ffStrbufAppendF(&cpu->name, "*%u", num); + } ffStrbufAppendS(&cpu->name, " + "); } - if (name) + if (name) { ffStrbufAppendS(&cpu->name, name); - else if (partId) + } else if (partId) { ffStrbufAppendF(&cpu->name, "%s-%X", cpu->vendor.chars, partId); - else + } else { ffStrbufAppend(&cpu->name, &cpu->vendor); + } lastPartId = partId; num = 1; - } - else + } else { ++num; + } } - if (num > 1) + if (num > 1) { ffStrbufAppendF(&cpu->name, "*%u", num); + } } #endif @@ -432,150 +557,148 @@ static const char* parseCpuInfo( FF_MAYBE_UNUSED FFstrbuf* cpuMHz, FF_MAYBE_UNUSED FFstrbuf* cpuIsa, FF_MAYBE_UNUSED FFstrbuf* cpuUarch, - FF_MAYBE_UNUSED FFstrbuf* cpuImplementer) -{ + FF_MAYBE_UNUSED FFstrbuf* cpuImplementer) { char* line = NULL; size_t len = 0; - while(ffStrbufGetline(&line, &len, cpuinfo)) - { - //Stop after reasonable information is acquired - if((*line == '\0' || *line == '\n') && cpu->name.length > 0) - { + while (ffStrbufGetline(&line, &len, cpuinfo)) { + // Stop after reasonable information is acquired + if ((*line == '\0' || *line == '\n') && cpu->name.length > 0) { ffStrbufGetlineRestore(&line, &len, cpuinfo); break; } - (void)( - // arm64 doesn't have "model name"; arm32 does have "model name" but its value is not useful. - // "Hardware" should always be used in this case - #if __x86_64__ || __i386__ + (void) ( +// arm64 doesn't have "model name"; arm32 does have "model name" but its value is not useful. +// "Hardware" should always be used in this case +#if __x86_64__ || __i386__ (cpu->name.length == 0 && ffParsePropLine(line, "model name :", &cpu->name)) || (cpu->vendor.length == 0 && ffParsePropLine(line, "vendor_id :", &cpu->vendor)) || (physicalCoresBuffer->length == 0 && ffParsePropLine(line, "cpu cores :", physicalCoresBuffer)) || (cpuMHz->length == 0 && ffParsePropLine(line, "cpu MHz :", cpuMHz)) || - #elif __arm__ || __aarch64__ +#elif __arm__ || __aarch64__ (cpuImplementer->length == 0 && ffParsePropLine(line, "CPU implementer :", cpuImplementer)) || - (cpu->name.length == 0 && ffParsePropLine(line, "Hardware :", &cpu->name)) || //For Android devices - #elif __powerpc__ || __powerpc + (cpu->name.length == 0 && ffParsePropLine(line, "Hardware :", &cpu->name)) || // For Android devices +#elif __powerpc__ || __powerpc (cpuMHz->length == 0 && ffParsePropLine(line, "clock :", cpuMHz)) || (cpu->name.length == 0 && ffParsePropLine(line, "cpu :", &cpu->name)) || - #elif __mips__ || __mips +#elif __mips__ || __mips (cpu->name.length == 0 && ffParsePropLine(line, "cpu model :", &cpu->name)) || - #elif __loongarch__ +#elif __loongarch__ (cpu->name.length == 0 && ffParsePropLine(line, "Model Name :", &cpu->name)) || (cpuMHz->length == 0 && ffParsePropLine(line, "CPU MHz :", cpuMHz)) || - #elif __riscv__ || __riscv +#elif __riscv__ || __riscv (cpuIsa->length == 0 && ffParsePropLine(line, "isa :", cpuIsa)) || (cpuUarch->length == 0 && ffParsePropLine(line, "uarch :", cpuUarch)) || - #elif __s390x__ +#elif __s390x__ (cpu->name.length == 0 && ffParsePropLine(line, "machine :", &cpu->name)) || (cpu->vendor.length == 0 && ffParsePropLine(line, "vendor_id :", &cpu->vendor)) || (cpuMHz->length == 0 && ffParsePropLine(line, "cpu MHz static :", cpuMHz)) || - #elif __ia64__ +#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)) || - #elif __hppa__ +#elif __hppa__ (cpu->name.length == 0 && ffParsePropLine(line, "cpu :", &cpu->name)) || - #elif __sh__ +#elif __sh__ (cpu->name.length == 0 && ffParsePropLine(line, "cpu type :", &cpu->name)) || - #else +#else (cpu->name.length == 0 && ffParsePropLine(line, "model name :", &cpu->name)) || (cpu->name.length == 0 && ffParsePropLine(line, "model :", &cpu->name)) || (cpu->name.length == 0 && ffParsePropLine(line, "cpu model :", &cpu->name)) || (cpu->name.length == 0 && ffParsePropLine(line, "hardware :", &cpu->name)) || (cpu->name.length == 0 && ffParsePropLine(line, "processor :", &cpu->name)) || - #endif +#endif - false - ); + false); } return NULL; } -static uint32_t getFrequency(FFstrbuf* basePath, const char* cpuinfoFileName, const char* scalingFileName, FFstrbuf* buffer) -{ +static uint32_t getFrequency(FFstrbuf* basePath, const char* cpuinfoFileName, const char* scalingFileName, FFstrbuf* buffer) { uint32_t baseLen = basePath->length; ffStrbufAppendS(basePath, cpuinfoFileName); bool ok = ffReadFileBuffer(basePath->chars, buffer); ffStrbufSubstrBefore(basePath, baseLen); - if (ok) + if (ok) { return (uint32_t) (ffStrbufToUInt(buffer, 0) / 1000); + } - if (scalingFileName) - { + if (scalingFileName) { ffStrbufAppendS(basePath, scalingFileName); ok = ffReadFileBuffer(basePath->chars, buffer); ffStrbufSubstrBefore(basePath, baseLen); - if (ok) + if (ok) { return (uint32_t) (ffStrbufToUInt(buffer, 0) / 1000); + } } return 0; } -static uint8_t getNumCores(FFstrbuf* basePath, FFstrbuf* buffer) -{ +static uint8_t getNumCores(FFstrbuf* basePath, FFstrbuf* buffer) { uint32_t baseLen = basePath->length; ffStrbufAppendS(basePath, "/affected_cpus"); bool ok = ffReadFileBuffer(basePath->chars, buffer); ffStrbufSubstrBefore(basePath, baseLen); - if (ok) + if (ok) { return (uint8_t) (ffStrbufCountC(buffer, ' ') + 1); + } ffStrbufAppendS(basePath, "/related_cpus"); ok = ffReadFileBuffer(basePath->chars, buffer); ffStrbufSubstrBefore(basePath, baseLen); - if (ok) + if (ok) { return (uint8_t) (ffStrbufCountC(buffer, ' ') + 1); + } return 0; } -static bool detectFrequency(FFCPUResult* cpu, const FFCPUOptions* options) -{ +static bool detectFrequency(FFCPUResult* cpu, const FFCPUOptions* options) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/sys/devices/system/cpu/cpufreq/"); FF_AUTO_CLOSE_DIR DIR* dir = opendir(path.chars); - if (!dir) return false; + if (!dir) { + return false; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); uint32_t baseLen = path.length; struct dirent* entry; - while ((entry = readdir(dir)) != NULL) - { - if (ffStrStartsWith(entry->d_name, "policy") && ffCharIsDigit(entry->d_name[strlen("policy")])) - { + while ((entry = readdir(dir)) != NULL) { + if (ffStrStartsWith(entry->d_name, "policy") && ffCharIsDigit(entry->d_name[strlen("policy")])) { ffStrbufAppendS(&path, entry->d_name); uint32_t fmax = getFrequency(&path, "/cpuinfo_max_freq", "/scaling_max_freq", &buffer); - if (fmax == 0) continue; + if (fmax == 0) { + continue; + } - if (cpu->frequencyMax >= fmax) - { - if (!options->showPeCoreCount) - { + if (cpu->frequencyMax >= fmax) { + if (!options->showPeCoreCount) { ffStrbufSubstrBefore(&path, baseLen); continue; } - } - else + } else { cpu->frequencyMax = fmax; + } uint32_t fbase = getFrequency(&path, "/base_frequency", NULL, &buffer); - if (fbase > 0) + if (fbase > 0) { cpu->frequencyBase = cpu->frequencyBase > fbase ? cpu->frequencyBase : fbase; + } - if (options->showPeCoreCount) - { + if (options->showPeCoreCount) { uint32_t freq = fbase == 0 ? fmax : fbase; // seems base frequencies are more stable uint32_t ifreq = 0; - while (cpu->coreTypes[ifreq].freq != freq && cpu->coreTypes[ifreq].freq > 0) + while (cpu->coreTypes[ifreq].freq != freq && cpu->coreTypes[ifreq].freq > 0) { ++ifreq; - if (cpu->coreTypes[ifreq].freq == 0) + } + if (cpu->coreTypes[ifreq].freq == 0) { cpu->coreTypes[ifreq].freq = freq; + } cpu->coreTypes[ifreq].count += getNumCores(&path, &buffer); } ffStrbufSubstrBefore(&path, baseLen); @@ -586,48 +709,51 @@ static bool detectFrequency(FFCPUResult* cpu, const FFCPUOptions* options) #if __i386__ || __x86_64__ -FF_MAYBE_UNUSED static uint16_t getPackageCount(FFstrbuf* cpuinfo) -{ +FF_MAYBE_UNUSED static uint16_t getPackageCount(FFstrbuf* cpuinfo) { const char* p = cpuinfo->chars; uint64_t low = 0, high = 0; - while ((p = memmem(p, cpuinfo->length - (uint32_t) (p - cpuinfo->chars), "\nphysical id\t:", strlen("\nphysical id\t:")))) - { + while ((p = memmem(p, cpuinfo->length - (uint32_t) (p - cpuinfo->chars), "\nphysical id\t:", strlen("\nphysical id\t:")))) { p += strlen("\nphysical id\t:"); char* pend; unsigned long long id = strtoul(p, &pend, 10); - if (__builtin_expect(id > 64, false)) // Do 129-socket boards exist? + if (__builtin_expect(id > 64, false)) { // Do 129-socket boards exist? high |= 1ULL << (id - 64); - else + } else { low |= 1ULL << id; + } p = pend; } return (uint16_t) (__builtin_popcountll(low) + __builtin_popcountll(high)); } -FF_MAYBE_UNUSED static const char* detectCPUX86(const FFCPUOptions* options, FFCPUResult* cpu) -{ +FF_MAYBE_UNUSED static const char* detectCPUX86(const FFCPUOptions* options, FFCPUResult* cpu) { FF_STRBUF_AUTO_DESTROY cpuinfo = ffStrbufCreateA(PROC_FILE_BUFFSIZ); - if (!ffReadFileBuffer(FF_CPUINFO_PATH, &cpuinfo) || cpuinfo.length == 0) + if (!ffReadFileBuffer(FF_CPUINFO_PATH, &cpuinfo) || cpuinfo.length == 0) { return "ffReadFileBuffer(\"" FF_CPUINFO_PATH "\") failed"; + } FF_STRBUF_AUTO_DESTROY physicalCoresBuffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY cpuMHz = ffStrbufCreate(); - const char* error = parseCpuInfo(&cpuinfo, cpu, &physicalCoresBuffer, &cpuMHz, NULL,NULL, NULL); - if (error) return error; + const char* error = parseCpuInfo(&cpuinfo, cpu, &physicalCoresBuffer, &cpuMHz, NULL, NULL, NULL); + if (error) { + return error; + } cpu->coresLogical = (uint16_t) get_nprocs_conf(); cpu->coresOnline = (uint16_t) get_nprocs(); cpu->packages = getPackageCount(&cpuinfo); cpu->coresPhysical = (uint16_t) ffStrbufToUInt(&physicalCoresBuffer, 0); // physical cores in single package - if (cpu->coresPhysical > 0 && cpu->packages > 1) + if (cpu->coresPhysical > 0 && cpu->packages > 1) { cpu->coresPhysical *= cpu->packages; + } // Ref https://github.com/fastfetch-cli/fastfetch/issues/1194#issuecomment-2295058252 ffCPUDetectByCpuid(cpu); - if (!detectFrequency(cpu, options) || cpu->frequencyBase == 0) + if (!detectFrequency(cpu, options) || cpu->frequencyBase == 0) { cpu->frequencyBase = (uint32_t) ffStrbufToUInt(&cpuMHz, 0); + } detectNumaNodes(cpu); @@ -636,26 +762,30 @@ FF_MAYBE_UNUSED static const char* detectCPUX86(const FFCPUOptions* options, FFC #else -static const char* detectPhysicalCores(FFCPUResult* cpu) -{ +static const char* detectPhysicalCores(FFCPUResult* cpu) { int dfd = open("/sys/devices/system/cpu/", O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (dfd < 0) return "open(\"/sys/devices/system/cpu/\") failed"; + if (dfd < 0) { + return "open(\"/sys/devices/system/cpu/\") failed"; + } FF_AUTO_CLOSE_DIR DIR* dir = fdopendir(dfd); - if (!dir) return "fdopendir(dfd) failed"; + if (!dir) { + return "fdopendir(dfd) failed"; + } uint64_t pkgLow = 0, pkgHigh = 0; struct dirent* entry; FF_LIST_AUTO_DESTROY cpuList = ffListCreate(sizeof(uint32_t)); - while ((entry = readdir(dir)) != NULL) - { - if (entry->d_type != DT_DIR || !ffStrStartsWith(entry->d_name, "cpu") || !ffCharIsDigit(entry->d_name[strlen("cpu")])) + while ((entry = readdir(dir)) != NULL) { + if (entry->d_type != DT_DIR || !ffStrStartsWith(entry->d_name, "cpu") || !ffCharIsDigit(entry->d_name[strlen("cpu")])) { continue; + } FF_AUTO_CLOSE_FD int cpuxfd = openat(dirfd(dir), entry->d_name, O_RDONLY | O_DIRECTORY); - if (cpuxfd < 0) + if (cpuxfd < 0) { continue; + } char buf[128]; @@ -663,45 +793,46 @@ static const char* detectPhysicalCores(FFCPUResult* cpu) // that lists the physical package id of the CPU. ssize_t len = ffReadFileDataRelative(cpuxfd, "topology/physical_package_id", sizeof(buf) - 1, buf); - if (len > 0) - { + if (len > 0) { buf[len] = '\0'; unsigned long long id = strtoul(buf, NULL, 10); - if (__builtin_expect(id > 64, false)) // Do 129-socket boards exist? + if (__builtin_expect(id > 64, false)) { // Do 129-socket boards exist? pkgHigh |= 1ULL << (id - 64); - else + } else { pkgLow |= 1ULL << id; + } } // Check if the directory contains a file named "topology/core_cpus_list" // that lists the physical cores in the package. len = ffReadFileDataRelative(cpuxfd, "topology/core_cpus_list", sizeof(buf) - 1, buf); - if (len > 0) - { + if (len > 0) { buf[len] = '\0'; // low-high or low - for (const char* p = buf; *p;) - { + for (const char* p = buf; *p;) { char* pend; uint32_t coreId = (uint32_t) strtoul(p, &pend, 10); - if (pend == p) break; + if (pend == p) { + break; + } bool found = false; - FF_LIST_FOR_EACH(uint32_t, id, cpuList) - { - if (*id == coreId) - { + FF_LIST_FOR_EACH (uint32_t, id, cpuList) { + if (*id == coreId) { // This core is already counted found = true; break; } } - if (!found) + if (!found) { *(uint32_t*) ffListAdd(&cpuList) = coreId; + } p = strchr(pend, ','); - if (!p) break; + if (!p) { + break; + } ++p; } } @@ -712,20 +843,18 @@ static const char* detectPhysicalCores(FFCPUResult* cpu) return NULL; } -FF_MAYBE_UNUSED static void parseIsa(FFstrbuf* cpuIsa) -{ +FF_MAYBE_UNUSED static void parseIsa(FFstrbuf* cpuIsa) { // Always use the last part of the ISA string. Ref: #590 #1204 ffStrbufSubstrAfterLastC(cpuIsa, ' '); - if(ffStrbufStartsWithS(cpuIsa, "rv")) - { + if (ffStrbufStartsWithS(cpuIsa, "rv")) { // RISC-V ISA string example: "rv64imafdch_zicsr_zifencei". // The _z parts are not important for CPU showcasing, so we remove them. - if(ffStrbufContainC(cpuIsa, '_')) + if (ffStrbufContainC(cpuIsa, '_')) { ffStrbufSubstrBeforeFirstC(cpuIsa, '_'); + } // Then we replace "imafd" with "g" since "g" is a shorthand. - if(ffStrbufContainS(cpuIsa, "imafd")) - { + if (ffStrbufContainS(cpuIsa, "imafd")) { // Remove 4 of the 5 characters and replace the remaining one with "g". ffStrbufRemoveSubstr(cpuIsa, 4, 8); cpuIsa->chars[4] = 'g'; @@ -734,162 +863,164 @@ FF_MAYBE_UNUSED static void parseIsa(FFstrbuf* cpuIsa) } } -FF_MAYBE_UNUSED static void detectSocName(FFCPUResult* cpu) -{ - if (cpu->name.length > 0) +FF_MAYBE_UNUSED static void detectSocName(FFCPUResult* cpu) { + if (cpu->name.length > 0) { return; + } // [x-vendor,x-model\0]*N char content[512]; ssize_t length = ffReadFileData("/sys/firmware/devicetree/base/compatible", ARRAY_SIZE(content), content); - if (length < 4) return; // v,m\0 + if (length < 4) { + return; // v,m\0 + } - if (content[length - 1] != '\0') return; // must end with \0 + if (content[length - 1] != '\0') { + return; // must end with \0 + } --length; char* vendor = NULL; char* model = NULL; - for (char* p; length > 0; length = p ? (ssize_t) (p - content) - 1 : 0) - { + for (char* p; length > 0; length = p ? (ssize_t) (p - content) - 1 : 0) { p = memrchr(content, '\0', (size_t) length); vendor = p /* first entry */ ? p + 1 : content; size_t partLen = (size_t) (length - (vendor - content)); - if (partLen < 3) continue; + if (partLen < 3) { + continue; + } char* comma = memchr(vendor, ',', partLen); - if (!comma) continue; + if (!comma) { + continue; + } size_t vendorLen = (size_t) (comma - vendor); - if (vendorLen == 0) continue; + if (vendorLen == 0) { + continue; + } model = comma + 1; size_t modelLen = (size_t) (partLen - (size_t) (model - vendor)); - if (modelLen == 0) continue; + if (modelLen == 0) { + continue; + } if ((modelLen >= strlen("-platform") && ffStrEndsWith(model, "-platform")) || - (modelLen >= strlen("-soc") && ffStrEndsWith(model, "-soc"))) + (modelLen >= strlen("-soc") && ffStrEndsWith(model, "-soc"))) { continue; + } *comma = '\0'; break; } - if (!length) return; + if (!length) { + return; + } - if (false) {} - #if __aarch64__ - else if (ffStrEquals(vendor, "apple")) - { + if (false) { + } +# if __aarch64__ + else if (ffStrEquals(vendor, "apple")) { // https://elixir.bootlin.com/linux/v6.11/source/arch/arm64/boot/dts/apple - if (model[0] == 't') - { + if (model[0] == 't') { uint32_t deviceId = (uint32_t) strtoul(model + 1, NULL, 10); ffStrbufSetStatic(&cpu->name, ffCPUAppleCodeToName(deviceId)); - if (!cpu->name.length) - { + if (!cpu->name.length) { ffStrbufSetS(&cpu->name, "Apple Silicon "); ffStrbufAppendS(&cpu->name, model); } - } - else + } else { ffStrbufSetS(&cpu->name, model); + } ffStrbufSetStatic(&cpu->vendor, "Apple"); } - #endif - else if (ffStrEquals(vendor, "qcom")) - { +# endif + else if (ffStrEquals(vendor, "qcom")) { // https://elixir.bootlin.com/linux/v6.11/source/arch/arm64/boot/dts/qcom - if (ffStrStartsWith(model, "x")) - { + if (ffStrStartsWith(model, "x")) { ffStrbufSetS(&cpu->name, "Qualcomm Snapdragon X Elite "); - for (const char* p = model + 1; *p; ++p) + for (const char* p = model + 1; *p; ++p) { ffStrbufAppendC(&cpu->name, (char) toupper(*p)); - } - else if (ffStrStartsWith(model, "sc")) - { + } + } else if (ffStrStartsWith(model, "sc")) { const char* code = model + 2; uint32_t deviceId = (uint32_t) strtoul(code, NULL, 10); ffStrbufSetStatic(&cpu->name, ffCPUQualcommCodeToName(deviceId)); - if (!cpu->name.length) - { + if (!cpu->name.length) { ffStrbufAppendS(&cpu->name, "Qualcomm Snapdragon SC"); ffStrbufAppendS(&cpu->name, code); } - } - else + } else { ffStrbufSetS(&cpu->name, model); + } ffStrbufSetStatic(&cpu->vendor, "Qualcomm"); - } - else if (ffStrEquals(vendor, "brcm")) - { + } else if (ffStrEquals(vendor, "brcm")) { // Raspberry Pi ffStrbufSetStatic(&cpu->vendor, "Broadcom"); - for (const char* p = model; *p; ++p) + for (const char* p = model; *p; ++p) { ffStrbufAppendC(&cpu->name, (char) toupper(*p)); - } - else if (ffStrEquals(vendor, "thead")) - { + } + } else if (ffStrEquals(vendor, "thead")) { // Lichee Pi? ffStrbufSetStatic(&cpu->vendor, "T-Head"); - for (const char* p = model; *p; ++p) + for (const char* p = model; *p; ++p) { ffStrbufAppendC(&cpu->name, (char) toupper(*p)); - } - else - { + } + } else { ffStrbufSetS(&cpu->name, model); ffStrbufSetS(&cpu->vendor, vendor); cpu->vendor.chars[0] = (char) toupper(vendor[0]); } } -#ifdef __loongarch__ -FF_MAYBE_UNUSED static uint16_t getLoongarchPropCount(FFstrbuf* cpuinfo, const char* key) -{ +# ifdef __loongarch__ +FF_MAYBE_UNUSED static uint16_t getLoongarchPropCount(FFstrbuf* cpuinfo, const char* key) { const char* p = cpuinfo->chars; uint64_t low = 0, high = 0; uint32_t keylen = (uint32_t) strlen(key); - while ((p = memmem(p, cpuinfo->length - (uint32_t) (p - cpuinfo->chars), key, keylen))) - { + while ((p = memmem(p, cpuinfo->length - (uint32_t) (p - cpuinfo->chars), key, keylen))) { p += keylen; char* pend; unsigned long id = strtoul(p, &pend, 10); - if (__builtin_expect(id > 64, false)) + if (__builtin_expect(id > 64, false)) { high |= 1UL << (id - 64); - else + } else { low |= 1UL << id; + } p = pend; } return (uint16_t) (__builtin_popcountll(low) + __builtin_popcountll(high)); } -#endif +# endif -FF_MAYBE_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, FFCPUResult* cpu) -{ +FF_MAYBE_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, FFCPUResult* cpu) { cpu->coresLogical = (uint16_t) get_nprocs_conf(); cpu->coresOnline = (uint16_t) get_nprocs(); - #if __ANDROID__ +# if __ANDROID__ detectAndroid(cpu); - #elif !__powerpc__ && !__powerpc +# elif !__powerpc__ && !__powerpc detectSocName(cpu); - #endif +# endif detectFrequency(cpu, options); - if (cpu->name.length == 0) - { + if (cpu->name.length == 0) { FF_STRBUF_AUTO_DESTROY cpuinfo = ffStrbufCreateA(PROC_FILE_BUFFSIZ); - if (!ffReadFileBuffer(FF_CPUINFO_PATH, &cpuinfo) || cpuinfo.length == 0) + if (!ffReadFileBuffer(FF_CPUINFO_PATH, &cpuinfo) || cpuinfo.length == 0) { return "ffReadFileBuffer(\"" FF_CPUINFO_PATH "\") failed"; + } FF_STRBUF_AUTO_DESTROY cpuMHz = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY cpuIsa = ffStrbufCreate(); @@ -897,46 +1028,54 @@ FF_MAYBE_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, FF_STRBUF_AUTO_DESTROY cpuImplementerStr = ffStrbufCreate(); const char* error = parseCpuInfo(&cpuinfo, cpu, NULL, &cpuMHz, &cpuIsa, &cpuUarch, &cpuImplementerStr); - if (error) return error; + if (error) { + return error; + } - if (cpu->frequencyBase == 0) + if (cpu->frequencyBase == 0) { cpu->frequencyBase = (uint32_t) ffStrbufToUInt(&cpuMHz, 0); + } - #if __arm__ || __aarch64__ +# if __arm__ || __aarch64__ uint32_t cpuImplementer = (uint32_t) strtoul(cpuImplementerStr.chars, NULL, 16); ffStrbufSetStatic(&cpu->vendor, hwImplId2Vendor(cpuImplementer)); - if (cpu->name.length == 0) + if (cpu->name.length == 0) { detectArmName(&cpuinfo, cpu, cpuImplementer); - #elif __riscv__ || __riscv - if (cpu->name.length == 0) - { - if(cpuUarch.length > 0) - { - if(cpu->name.length > 0) + } +# elif __riscv__ || __riscv + if (cpu->name.length == 0) { + if (cpuUarch.length > 0) { + if (cpu->name.length > 0) { ffStrbufAppendC(&cpu->name, ' '); + } ffStrbufAppend(&cpu->name, &cpuUarch); } - if(cpuIsa.length > 0) - { + if (cpuIsa.length > 0) { parseIsa(&cpuIsa); - if(cpu->name.length > 0) + if (cpu->name.length > 0) { ffStrbufAppendC(&cpu->name, ' '); + } ffStrbufAppend(&cpu->name, &cpuIsa); } } - #elif __loongarch__ +# elif __loongarch__ cpu->packages = getLoongarchPropCount(&cpuinfo, "\npackage\t\t\t:"); cpu->coresPhysical = getLoongarchPropCount(&cpuinfo, "\ncore\t\t\t:"); - if (cpu->packages > 1) cpu->coresPhysical *= cpu->packages; - #elif __s390x__ - if (cpu->name.length) ffStrbufPrependS(&cpu->name, "Machine "); - #endif + if (cpu->packages > 1) { + cpu->coresPhysical *= cpu->packages; + } +# elif __s390x__ + if (cpu->name.length) { + ffStrbufPrependS(&cpu->name, "Machine "); + } +# endif } - if (cpu->coresPhysical == 0) + if (cpu->coresPhysical == 0) { detectPhysicalCores(cpu); + } ffCPUDetectByCpuid(cpu); detectNumaNodes(cpu); @@ -945,13 +1084,12 @@ FF_MAYBE_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, } #endif -const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) -{ +const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { cpu->temperature = options->temp ? detectCPUTemp(options) : FF_CPU_TEMP_UNSET; - #if __x86_64__ || __i386__ +#if __x86_64__ || __i386__ return detectCPUX86(options, cpu); - #else +#else return detectCPUOthers(options, cpu); - #endif +#endif } diff --git a/src/detection/cpu/cpu_nbsd.c b/src/detection/cpu/cpu_nbsd.c index 104b02e4d..2a1edeb94 100644 --- a/src/detection/cpu/cpu_nbsd.c +++ b/src/detection/cpu/cpu_nbsd.c @@ -9,66 +9,78 @@ #include #include -static void freePropDict(prop_dictionary_t* pdict) -{ +static void freePropDict(prop_dictionary_t* pdict) { assert(pdict != NULL); - if (*pdict == NULL) return; + if (*pdict == NULL) { + return; + } prop_object_release(*pdict); } -static const char* detectCpuTemp(const FFCPUOptions* options, double* current) -{ +static const char* detectCpuTemp(const FFCPUOptions* options, double* current) { FF_AUTO_CLOSE_FD int fd = open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC); - if (fd < 0) return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed"; + if (fd < 0) { + return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed"; + } __attribute__((__cleanup__(freePropDict))) prop_dictionary_t root = NULL; - if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) + if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) { return "prop_dictionary_recv_ioctl(ENVSYS_GETDICTIONARY) failed"; + } prop_array_t array; - if (options->tempSensor.length > 0) - { + if (options->tempSensor.length > 0) { array = prop_dictionary_get(root, options->tempSensor.chars); - if (!array) return "No temp data found in specified sensor"; - } - else - { + if (!array) { + return "No temp data found in specified sensor"; + } + } else { array = prop_dictionary_get(root, "coretemp0"); - if (!array) array = prop_dictionary_get(root, "amdzentemp0"); - if (!array) array = prop_dictionary_get(root, "viac7temp0"); - if (!array) array = prop_dictionary_get(root, "acpitz0"); // Thermal Zones - if (!array) return "No temp data found in root dictionary"; + if (!array) { + array = prop_dictionary_get(root, "amdzentemp0"); + } + if (!array) { + array = prop_dictionary_get(root, "viac7temp0"); + } + if (!array) { + array = prop_dictionary_get(root, "acpitz0"); // Thermal Zones + } + if (!array) { + return "No temp data found in root dictionary"; + } } - if (prop_array_count(array) != 2) + if (prop_array_count(array) != 2) { return "Unexpected `xtemp0` data"; + } prop_dictionary_t dict = prop_array_get(array, 0); - if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) + if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) { return "Unexpected `xtemp0[0]`"; + } int temp = 0; // in µK - if (!prop_dictionary_get_int(dict, "cur-value", &temp)) + if (!prop_dictionary_get_int(dict, "cur-value", &temp)) { return "Failed to get temperature"; + } *current = temp / 1e6 - 273.15; return NULL; } -const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) -{ +const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { if (ffSysctlGetString("machdep.cpu_brand", &cpu->name) != NULL && ffSysctlGetString("machdep.dmi.processor-version", &cpu->name) != NULL && ffSysctlGetString("hw.cpu0.name", &cpu->name) != NULL && - ffSysctlGetString("hw.model", &cpu->name) != NULL) - { + ffSysctlGetString("hw.model", &cpu->name) != NULL) { ffStrbufSetS(&cpu->name, "Unknown CPU"); } - if (ffSysctlGetString("machdep.dmi.processor-vendor", &cpu->vendor) == NULL) + if (ffSysctlGetString("machdep.dmi.processor-vendor", &cpu->vendor) == NULL) { ffStrbufTrimRightSpace(&cpu->vendor); + } cpu->coresPhysical = (uint16_t) ffSysctlGetInt("hw.ncpu", 1); cpu->coresLogical = cpu->coresPhysical; @@ -77,13 +89,21 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* 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); - if (freq == 0) freq = (uint32_t) ffSysctlGetInt("machdep.dmi.processor-frequency", 0); - if (freq > cpu->frequencyBase) cpu->frequencyBase = freq; + if (freq == 0) { + freq = (uint32_t) (ffSysctlGetInt64("hw.cpu0.clock_frequency", 0) / 1000000); + } + if (freq == 0) { + freq = (uint32_t) ffSysctlGetInt("machdep.dmi.processor-frequency", 0); + } + if (freq > cpu->frequencyBase) { + cpu->frequencyBase = freq; + } cpu->temperature = FF_CPU_TEMP_UNSET; - if (options->temp) detectCpuTemp(options, &cpu->temperature); + if (options->temp) { + detectCpuTemp(options, &cpu->temperature); + } return NULL; } diff --git a/src/detection/cpu/cpu_nosupport.c b/src/detection/cpu/cpu_nosupport.c index 49e125b5a..cddcf1e11 100644 --- a/src/detection/cpu/cpu_nosupport.c +++ b/src/detection/cpu/cpu_nosupport.c @@ -1,6 +1,5 @@ #include "cpu.h" -const char* ffDetectCPUImpl(FF_MAYBE_UNUSED const FFCPUOptions* options, FF_MAYBE_UNUSED FFCPUResult* cpu) -{ +const char* ffDetectCPUImpl(FF_MAYBE_UNUSED const FFCPUOptions* options, FF_MAYBE_UNUSED FFCPUResult* cpu) { return "Not supported on this platform"; } diff --git a/src/detection/cpu/cpu_obsd.c b/src/detection/cpu/cpu_obsd.c index 16ffd5cc0..2b49c2205 100644 --- a/src/detection/cpu/cpu_obsd.c +++ b/src/detection/cpu/cpu_obsd.c @@ -6,48 +6,46 @@ #include #include -static const char* detectCPUTemp(const FFCPUOptions* options, FFCPUResult* cpu) -{ +static const char* detectCPUTemp(const FFCPUOptions* options, FFCPUResult* cpu) { int mib[5] = {CTL_HW, HW_SENSORS, 0, SENSOR_TEMP, 0}; - for (mib[2] = 0; mib[2] < 1024; mib[2]++) - { + for (mib[2] = 0; mib[2] < 1024; mib[2]++) { struct sensordev sensordev; size_t sdlen = sizeof(struct sensordev); - if (sysctl(mib, 3, &sensordev, &sdlen, NULL, 0) < 0) - { - if (errno == ENOENT) + if (sysctl(mib, 3, &sensordev, &sdlen, NULL, 0) < 0) { + if (errno == ENOENT) { break; - if (errno == ENXIO) + } + if (errno == ENXIO) { continue; + } return "sysctl(sensordev) failed"; } - if (options->tempSensor.length > 0) - { - if (!ffStrbufEqualS(&options->tempSensor, sensordev.xname)) - continue; - } - else - { - if (!ffStrStartsWith(sensordev.xname, "cpu")) - continue; - } - - for (mib[4] = 0; mib[4] < sensordev.maxnumt[SENSOR_TEMP]; mib[4]++) - { - struct sensor sensor; - size_t slen = sizeof(struct sensor); - if (sysctl(mib, 5, &sensor, &slen, NULL, 0) < 0) - { - if (errno != ENOENT) - return "sysctl(sensor) failed"; + if (options->tempSensor.length > 0) { + if (!ffStrbufEqualS(&options->tempSensor, sensordev.xname)) { continue; } - if (sensor.flags & SENSOR_FINVALID) + } else { + if (!ffStrStartsWith(sensordev.xname, "cpu")) { continue; + } + } - cpu->temperature = (double)(sensor.value - 273150000) / 1E6; + for (mib[4] = 0; mib[4] < sensordev.maxnumt[SENSOR_TEMP]; mib[4]++) { + struct sensor sensor; + size_t slen = sizeof(struct sensor); + if (sysctl(mib, 5, &sensor, &slen, NULL, 0) < 0) { + if (errno != ENOENT) { + return "sysctl(sensor) failed"; + } + continue; + } + if (sensor.flags & SENSOR_FINVALID) { + continue; + } + + cpu->temperature = (double) (sensor.value - 273150000) / 1E6; return NULL; } } @@ -55,10 +53,10 @@ static const char* detectCPUTemp(const FFCPUOptions* options, FFCPUResult* cpu) return "No sensor for CPU temp found"; } -const char *ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) -{ - if (ffSysctlGetString(CTL_HW, HW_MODEL, &cpu->name)) +const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { + if (ffSysctlGetString(CTL_HW, HW_MODEL, &cpu->name)) { return "sysctl(hw.model) failed"; + } cpu->coresPhysical = (uint16_t) ffSysctlGetInt(CTL_HW, HW_NCPU, 1); cpu->coresLogical = cpu->coresPhysical; @@ -67,10 +65,14 @@ const char *ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) ffCPUDetectByCpuid(cpu); uint32_t cpuspeed = (uint32_t) ffSysctlGetInt(CTL_HW, HW_CPUSPEED, 0); - if (cpuspeed > cpu->frequencyBase) cpu->frequencyBase = cpuspeed; + if (cpuspeed > cpu->frequencyBase) { + cpu->frequencyBase = cpuspeed; + } cpu->temperature = FF_CPU_TEMP_UNSET; - if (options->temp) detectCPUTemp(options, cpu); + if (options->temp) { + detectCPUTemp(options, cpu); + } return NULL; } diff --git a/src/detection/cpu/cpu_sunos.c b/src/detection/cpu/cpu_sunos.c index fec93a486..e400a0437 100644 --- a/src/detection/cpu/cpu_sunos.c +++ b/src/detection/cpu/cpu_sunos.c @@ -3,8 +3,7 @@ #include "common/stringUtils.h" #include -static const char* detectCPUTempByKstat(const FFCPUOptions* options, kstat_ctl_t* kc, FFCPUResult* cpu) -{ +static const char* detectCPUTempByKstat(const FFCPUOptions* options, kstat_ctl_t* kc, FFCPUResult* cpu) { const char* possibleModules[] = {"temperature", "cpu_temp", "acpi_thermal", NULL}; if (options->tempSensor.length > 0) { @@ -19,10 +18,10 @@ static const char* detectCPUTempByKstat(const FFCPUOptions* options, kstat_ctl_t if (kn) { switch (kn->data_type) { case KSTAT_DATA_INT32: - cpu->temperature = (float)kn->value.i32; + cpu->temperature = (float) kn->value.i32; return NULL; case KSTAT_DATA_UINT32: - cpu->temperature = (float)kn->value.ui32; + cpu->temperature = (float) kn->value.ui32; return NULL; case KSTAT_DATA_FLOAT: cpu->temperature = kn->value.f; @@ -35,61 +34,53 @@ static const char* detectCPUTempByKstat(const FFCPUOptions* options, kstat_ctl_t return "Failed to find CPU temperature using kstat"; } -static const char* detectCPUTempByIpmiTool(FFCPUResult* cpu) -{ +static const char* detectCPUTempByIpmiTool(FFCPUResult* cpu) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - const char* error = ffProcessAppendStdOut(&buffer, (char* const[]){ - "ipmitool", - "-c", - "sdr", - "list", - NULL - }); + const char* error = ffProcessAppendStdOut(&buffer, (char* const[]) {"ipmitool", "-c", "sdr", "list", NULL}); - if (error) + if (error) { return error; + } char* line = NULL; size_t len = 0; - while (ffStrbufGetline(&line, &len, &buffer)) - { - if (sscanf(line, "CPU%*d Temp,%lf,degrees C,ok", &cpu->temperature) == 1) + while (ffStrbufGetline(&line, &len, &buffer)) { + if (sscanf(line, "CPU%*d Temp,%lf,degrees C,ok", &cpu->temperature) == 1) { return NULL; + } } return "ipmitool sdr list failed to find CPU temperature"; } -static inline void kstatFreeWrap(kstat_ctl_t** pkc) -{ +static inline void kstatFreeWrap(kstat_ctl_t** pkc) { assert(pkc); - if (*pkc) + if (*pkc) { kstat_close(*pkc); + } } -static inline uint16_t countTypeId(kstat_ctl_t* kc, const char* type) -{ +static inline uint16_t countTypeId(kstat_ctl_t* kc, const char* type) { uint64_t low = 0, high = 0; - for (kstat_t* ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) - { - if (ffStrStartsWith(ksp->ks_module, "cpu_info")) - { - if (kstat_read(kc, ksp, NULL) < 0) + for (kstat_t* ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) { + if (ffStrStartsWith(ksp->ks_module, "cpu_info")) { + if (kstat_read(kc, ksp, NULL) < 0) { continue; + } kstat_named_t* stat = kstat_data_lookup(ksp, type); - if (!stat) + if (!stat) { continue; + } uint32_t id = 0; - switch (stat->data_type) - { - #ifdef _INT64_TYPE + switch (stat->data_type) { +#ifdef _INT64_TYPE case KSTAT_DATA_INT64: case KSTAT_DATA_UINT64: id = (uint32_t) stat->value.ui64; break; - #endif +#endif case KSTAT_DATA_INT32: case KSTAT_DATA_UINT32: id = stat->value.ui32; @@ -97,57 +88,66 @@ static inline uint16_t countTypeId(kstat_ctl_t* kc, const char* type) default: continue; } - if (__builtin_expect(id > 64, false)) + if (__builtin_expect(id > 64, false)) { high |= 1ULL << (id - 64); - else + } else { low |= 1ULL << id; + } } } return (uint16_t) (__builtin_popcountll(low) + __builtin_popcountll(high)); } -const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) -{ +const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { __attribute__((__cleanup__(kstatFreeWrap))) kstat_ctl_t* kc = kstat_open(); - if (!kc) + if (!kc) { return "kstat_open() failed"; + } kstat_t* ks = kstat_lookup(kc, "cpu_info", -1, NULL); - if (!ks) + if (!ks) { return "kstat_lookup() failed"; + } - if (kstat_read(kc, ks, NULL) < 0) + if (kstat_read(kc, ks, NULL) < 0) { return "kstat_read() failed"; + } { kstat_named_t* kn = kstat_data_lookup(ks, "brand"); - if (kn) ffStrbufSetNS(&cpu->name, KSTAT_NAMED_STR_BUFLEN(kn) - 1, KSTAT_NAMED_STR_PTR(kn)); + if (kn) { + ffStrbufSetNS(&cpu->name, KSTAT_NAMED_STR_BUFLEN(kn) - 1, KSTAT_NAMED_STR_PTR(kn)); + } } { 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)); + if (kn) { + ffStrbufSetNS(&cpu->vendor, KSTAT_NAMED_STR_BUFLEN(kn) - 1, KSTAT_NAMED_STR_PTR(kn)); + } } ffCPUDetectByCpuid(cpu); { kstat_named_t* kn = kstat_data_lookup(ks, "clock_MHz"); - if (kn && kn->value.ui32 > cpu->frequencyBase) + if (kn && kn->value.ui32 > cpu->frequencyBase) { cpu->frequencyBase = kn->value.ui32; + } } ks = kstat_lookup(kc, "unix", -1, "system_misc"); - if (ks && kstat_read(kc, ks, NULL) >= 0) - { + if (ks && kstat_read(kc, ks, NULL) >= 0) { kstat_named_t* kn = kstat_data_lookup(ks, "ncpus"); - if (kn) cpu->coresLogical = cpu->coresOnline = (uint16_t) kn->value.ui32; + if (kn) { + cpu->coresLogical = cpu->coresOnline = (uint16_t) kn->value.ui32; + } } cpu->packages = countTypeId(kc, "chip_id"); cpu->coresPhysical = countTypeId(kc, "core_id"); - if (options->temp) - { - if (detectCPUTempByKstat(options, kc, cpu) != NULL) + if (options->temp) { + if (detectCPUTempByKstat(options, kc, cpu) != NULL) { detectCPUTempByIpmiTool(cpu); + } } return NULL; diff --git a/src/detection/cpu/cpu_windows.c b/src/detection/cpu/cpu_windows.c index 0dd06a1f3..bb0f6e1b4 100644 --- a/src/detection/cpu/cpu_windows.c +++ b/src/detection/cpu/cpu_windows.c @@ -9,26 +9,22 @@ #include "common/windows/nt.h" #include -static inline void ffPerfCloseQueryHandle(HANDLE* phQuery) -{ - if (*phQuery != NULL) - { +static inline void ffPerfCloseQueryHandle(HANDLE* phQuery) { + if (*phQuery != NULL) { PerfCloseQueryHandle(*phQuery); *phQuery = NULL; } } -const char* detectThermalTemp(const FFCPUOptions* options, double* result) -{ - struct FFPerfQuerySpec - { +const char* detectThermalTemp(const FFCPUOptions* options, double* result) { + struct FFPerfQuerySpec { PERF_COUNTER_IDENTIFIER Identifier; WCHAR Name[16]; } querySpec = { .Identifier = { // Thermal Zone Information // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\_V2Providers\{383487a6-3676-4870-a4e7-d45b30c35629}\{52bc5412-dac2-449c-8bc2-96443888fe6b} - .CounterSetGuid = { 0x52bc5412, 0xdac2, 0x449c, {0x8b, 0xc2, 0x96, 0x44, 0x38, 0x88, 0xfe, 0x6b} }, + .CounterSetGuid = {0x52bc5412, 0xdac2, 0x449c, {0x8b, 0xc2, 0x96, 0x44, 0x38, 0x88, 0xfe, 0x6b}}, .Size = sizeof(querySpec), .CounterId = PERF_WILDCARD_COUNTER, .InstanceId = PERF_WILDCARD_COUNTER, @@ -36,43 +32,47 @@ const char* detectThermalTemp(const FFCPUOptions* options, double* result) .Name = L"\\_TZ.CPUZ", // The standard(?) instance name for CPU temperature in the thermal provider }; - if (options->tempSensor.length > 0) - { - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(querySpec.Name, (ULONG) sizeof(querySpec.Name), NULL, options->tempSensor.chars, (ULONG)options->tempSensor.length + 1))) + if (options->tempSensor.length > 0) { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(querySpec.Name, (ULONG) sizeof(querySpec.Name), NULL, options->tempSensor.chars, (ULONG) options->tempSensor.length + 1))) { return "Invalid temp sensor string"; + } } DWORD dataSize = 0; - if (PerfEnumerateCounterSetInstances(NULL, &querySpec.Identifier.CounterSetGuid, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) + if (PerfEnumerateCounterSetInstances(NULL, &querySpec.Identifier.CounterSetGuid, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { return "PerfEnumerateCounterSetInstances() failed"; + } - if (dataSize <= sizeof(PERF_INSTANCE_HEADER)) + if (dataSize <= sizeof(PERF_INSTANCE_HEADER)) { return "No `Thermal Zone Information` instances found"; + } { FF_AUTO_FREE PERF_INSTANCE_HEADER* const pHead = malloc(dataSize); - if (PerfEnumerateCounterSetInstances(NULL, &querySpec.Identifier.CounterSetGuid, pHead, dataSize, &dataSize) != ERROR_SUCCESS) + if (PerfEnumerateCounterSetInstances(NULL, &querySpec.Identifier.CounterSetGuid, pHead, dataSize, &dataSize) != ERROR_SUCCESS) { return "PerfEnumerateCounterSetInstances() failed to get instance headers"; - - PERF_INSTANCE_HEADER* pInstanceHeader = pHead; - while (1) - { - const wchar_t* instanceName = (const wchar_t*)((BYTE*)pInstanceHeader + sizeof(*pInstanceHeader)); - if (wcscmp(instanceName, querySpec.Name) == 0) - break; - - dataSize -= pInstanceHeader->Size; - if (dataSize == 0) - break; - pInstanceHeader = (PERF_INSTANCE_HEADER*)((BYTE*)pInstanceHeader + pInstanceHeader->Size); } - if (dataSize == 0) - { - if (options->tempSensor.length > 0) - return "Unable to find CPU sensor"; + PERF_INSTANCE_HEADER* pInstanceHeader = pHead; + while (1) { + const wchar_t* instanceName = (const wchar_t*) ((BYTE*) pInstanceHeader + sizeof(*pInstanceHeader)); + if (wcscmp(instanceName, querySpec.Name) == 0) { + break; + } - const wchar_t* instanceName = (const wchar_t*)((BYTE*)pHead + sizeof(*pHead)); + dataSize -= pInstanceHeader->Size; + if (dataSize == 0) { + break; + } + pInstanceHeader = (PERF_INSTANCE_HEADER*) ((BYTE*) pInstanceHeader + pInstanceHeader->Size); + } + + if (dataSize == 0) { + if (options->tempSensor.length > 0) { + return "Unable to find CPU sensor"; + } + + const wchar_t* instanceName = (const wchar_t*) ((BYTE*) pHead + sizeof(*pHead)); wcscpy(querySpec.Name, instanceName); // Use the first instance name if the specific one is not found } } @@ -80,75 +80,80 @@ const char* detectThermalTemp(const FFCPUOptions* options, double* result) __attribute__((__cleanup__(ffPerfCloseQueryHandle))) HANDLE hQuery = NULL; - if (PerfOpenQueryHandle(NULL, &hQuery) != ERROR_SUCCESS) + if (PerfOpenQueryHandle(NULL, &hQuery) != ERROR_SUCCESS) { return "PerfOpenQueryHandle() failed"; + } - if (PerfAddCounters(hQuery, &querySpec.Identifier, sizeof(querySpec)) != ERROR_SUCCESS) + if (PerfAddCounters(hQuery, &querySpec.Identifier, sizeof(querySpec)) != ERROR_SUCCESS) { return "PerfAddCounters() failed"; + } - if (querySpec.Identifier.Status != ERROR_SUCCESS) + if (querySpec.Identifier.Status != ERROR_SUCCESS) { return "PerfAddCounters() reports invalid identifier"; + } - if (PerfQueryCounterData(hQuery, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) + if (PerfQueryCounterData(hQuery, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { return "PerfQueryCounterData(NULL) failed"; + } - if (dataSize <= sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER)) // PERF_ERROR_RETURN, should not happen + if (dataSize <= sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER)) { // PERF_ERROR_RETURN, should not happen return "instance doesn't exist"; + } FF_AUTO_FREE PERF_DATA_HEADER* const pDataHeader = malloc(dataSize); - if (PerfQueryCounterData(hQuery, pDataHeader, dataSize, &dataSize) != ERROR_SUCCESS) + if (PerfQueryCounterData(hQuery, pDataHeader, dataSize, &dataSize) != ERROR_SUCCESS) { return "PerfQueryCounterData(pDataHeader) failed"; + } - PERF_COUNTER_HEADER* pCounterHeader = (PERF_COUNTER_HEADER*)(pDataHeader + 1); - if (pCounterHeader->dwType != PERF_MULTIPLE_COUNTERS) + PERF_COUNTER_HEADER* pCounterHeader = (PERF_COUNTER_HEADER*) (pDataHeader + 1); + if (pCounterHeader->dwType != PERF_MULTIPLE_COUNTERS) { return "Invalid counter type"; + } - PERF_MULTI_COUNTERS* pMultiCounters = (PERF_MULTI_COUNTERS*)(pCounterHeader + 1); - PERF_COUNTER_DATA* pCounterData = (PERF_COUNTER_DATA*)((BYTE*)pMultiCounters + pMultiCounters->dwSize); + PERF_MULTI_COUNTERS* pMultiCounters = (PERF_MULTI_COUNTERS*) (pCounterHeader + 1); + PERF_COUNTER_DATA* pCounterData = (PERF_COUNTER_DATA*) ((BYTE*) pMultiCounters + pMultiCounters->dwSize); - for (ULONG iCounter = 0; iCounter != pMultiCounters->dwCounters; iCounter++) - { - if (pCounterData->dwDataSize == sizeof(int32_t)) - { - DWORD* pCounterIds = (DWORD*)(pMultiCounters + 1); - int32_t value = *(int32_t*)(pCounterData + 1); - if (value == 0) + for (ULONG iCounter = 0; iCounter != pMultiCounters->dwCounters; iCounter++) { + if (pCounterData->dwDataSize == sizeof(int32_t)) { + DWORD* pCounterIds = (DWORD*) (pMultiCounters + 1); + int32_t value = *(int32_t*) (pCounterData + 1); + if (value == 0) { return "Temperature data is zero"; + } switch (pCounterIds[iCounter]) { - case 0: // Temperature - *result = value - 273; - break; - case 3: // High Precision Temperature - *result = value / 10.0 - 273; - break; + case 0: // Temperature + *result = value - 273; + break; + case 3: // High Precision Temperature + *result = value / 10.0 - 273; + break; } } - pCounterData = (PERF_COUNTER_DATA*)((BYTE*)pCounterData + pCounterData->dwSize); + pCounterData = (PERF_COUNTER_DATA*) ((BYTE*) pCounterData + pCounterData->dwSize); } return NULL; } // 7.5 -typedef struct FFSmbiosProcessorInfo -{ +typedef struct FFSmbiosProcessorInfo { FFSmbiosHeader Header; - uint8_t SocketDesignation; // string - uint8_t ProcessorType; // enum - uint8_t ProcessorFamily; // enum + uint8_t SocketDesignation; // string + uint8_t ProcessorType; // enum + uint8_t ProcessorFamily; // enum uint8_t ProcessorManufacturer; // string - uint64_t ProcessorID; // varies - uint8_t ProcessorVersion; // string - uint8_t Voltage; // varies - uint16_t ExternalClock; // varies - uint16_t MaxSpeed; // varies - uint16_t CurrentSpeed; // varies - uint8_t Status; // varies - uint8_t ProcessorUpgrade; // enum + uint64_t ProcessorID; // varies + uint8_t ProcessorVersion; // string + uint8_t Voltage; // varies + uint16_t ExternalClock; // varies + uint16_t MaxSpeed; // varies + uint16_t CurrentSpeed; // varies + uint8_t Status; // varies + uint8_t ProcessorUpgrade; // enum // 2.1+ uint16_t L1CacheHandle; // varies @@ -157,20 +162,20 @@ typedef struct FFSmbiosProcessorInfo // 2.3+ uint8_t SerialNumber; // string - uint8_t AssertTag; // string - uint8_t PartNumber; // string + uint8_t AssertTag; // string + uint8_t PartNumber; // string // 2.5+ - uint8_t CoreCount; // varies - uint8_t CoreEnabled; // varies - uint8_t ThreadCount; // varies + uint8_t CoreCount; // varies + uint8_t CoreEnabled; // varies + uint8_t ThreadCount; // varies uint16_t ProcessorCharacteristics; // bit field // 2.6+ uint16_t ProcessorFamily2; // enum // 3.0+ - uint16_t CoreCount2; // varies + uint16_t CoreCount2; // varies uint16_t CoreEnabled2; // varies uint16_t ThreadCount2; // varies @@ -181,128 +186,135 @@ typedef struct FFSmbiosProcessorInfo static_assert(offsetof(FFSmbiosProcessorInfo, ThreadEnabled) == 0x30, "FFSmbiosProcessorInfo: Wrong struct alignment"); -static const char* detectMaxSpeedBySmbios(FFCPUResult* cpu) -{ +static const char* detectMaxSpeedBySmbios(FFCPUResult* cpu) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosProcessorInfo* data = (const FFSmbiosProcessorInfo*) (*smbiosTable)[FF_SMBIOS_TYPE_PROCESSOR_INFO]; - if (!data) + if (!data) { return "Processor information is not found in SMBIOS data"; + } - while (data->ProcessorType != 0x03 /*Central Processor*/ || (data->Status & 0b00000111) != 1 /*Enabled*/) - { + while (data->ProcessorType != 0x03 /*Central Processor*/ || (data->Status & 0b00000111) != 1 /*Enabled*/) { data = (const FFSmbiosProcessorInfo*) ffSmbiosNextEntry(&data->Header); - if (data->Header.Type != FF_SMBIOS_TYPE_PROCESSOR_INFO) + if (data->Header.Type != FF_SMBIOS_TYPE_PROCESSOR_INFO) { return "No active CPU is found in SMBIOS data"; + } } uint32_t speed = data->MaxSpeed; // Sometimes SMBIOS reports invalid value. We assume that max speed is small than 2x of base - if (speed < cpu->frequencyBase || speed > cpu->frequencyBase * 2) + if (speed < cpu->frequencyBase || speed > cpu->frequencyBase * 2) { return "Possible invalid CPU max speed in SMBIOS data. See #800"; + } cpu->frequencyMax = speed; return NULL; } -static const char* detectNCores(FFCPUResult* cpu) -{ +static const char* detectNCores(FFCPUResult* cpu) { LOGICAL_PROCESSOR_RELATIONSHIP lpr = RelationAll; ULONG length = 0; NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), NULL, 0, &length); - if (length == 0) + if (length == 0) { return "GetLogicalProcessorInformationEx(RelationAll, NULL, &length) failed"; + } SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* FF_AUTO_FREE - pProcessorInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)malloc(length); + pProcessorInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) malloc(length); - if (!NT_SUCCESS(NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), pProcessorInfo, length, &length))) + if (!NT_SUCCESS(NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), pProcessorInfo, length, &length))) { return "GetLogicalProcessorInformationEx(RelationAll, pProcessorInfo, &length) failed"; + } - for( + for ( SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* ptr = pProcessorInfo; - (uint8_t*)ptr < ((uint8_t*)pProcessorInfo) + length; - ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((uint8_t*)ptr) + ptr->Size) - ) - { - if (ptr->Relationship == RelationGroup) - { - for (uint32_t index = 0; index < ptr->Group.ActiveGroupCount; ++index) - { + (uint8_t*) ptr < ((uint8_t*) pProcessorInfo) + length; + ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) (((uint8_t*) ptr) + ptr->Size)) { + if (ptr->Relationship == RelationGroup) { + for (uint32_t index = 0; index < ptr->Group.ActiveGroupCount; ++index) { cpu->coresOnline += ptr->Group.GroupInfo[index].ActiveProcessorCount; cpu->coresLogical += ptr->Group.GroupInfo[index].MaximumProcessorCount; } - } - else if (ptr->Relationship == RelationProcessorCore) + } else if (ptr->Relationship == RelationProcessorCore) { ++cpu->coresPhysical; - else if (ptr->Relationship == RelationProcessorPackage) + } else if (ptr->Relationship == RelationProcessorPackage) { ++cpu->packages; - else if (ptr->Relationship == RelationNumaNode) + } else if (ptr->Relationship == RelationNumaNode) { ++cpu->numaNodes; + } } return NULL; } -static const char* detectByRegistry(FFCPUResult* cpu) -{ +static const char* detectByRegistry(FFCPUResult* cpu) { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &hKey, NULL)) + if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &hKey, NULL)) { return "ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L\"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\", &hKey, NULL) failed"; + } if (ffRegReadValues(hKey, 3, (FFRegValueArg[]) { - FF_ARG(cpu->name, L"ProcessorNameString"), - FF_ARG(cpu->vendor, L"VendorIdentifier"), - FF_ARG(cpu->frequencyBase, L"~MHz"), - }, NULL)) + FF_ARG(cpu->name, L"ProcessorNameString"), + FF_ARG(cpu->vendor, L"VendorIdentifier"), + FF_ARG(cpu->frequencyBase, L"~MHz"), + }, + NULL)) { ffStrbufTrimRightSpace(&cpu->vendor); - else + } else { return "ffRegReadValues() failed for CPU registry key"; + } return NULL; } -static const char* detectCoreTypes(FFCPUResult* cpu) -{ +static const char* detectCoreTypes(FFCPUResult* cpu) { FF_AUTO_FREE PROCESSOR_POWER_INFORMATION* pinfo = calloc(cpu->coresLogical, sizeof(PROCESSOR_POWER_INFORMATION)); - if (!NT_SUCCESS(NtPowerInformation(ProcessorInformation, NULL, 0, pinfo, (ULONG) sizeof(PROCESSOR_POWER_INFORMATION) * cpu->coresLogical))) + if (!NT_SUCCESS(NtPowerInformation(ProcessorInformation, NULL, 0, pinfo, (ULONG) sizeof(PROCESSOR_POWER_INFORMATION) * cpu->coresLogical))) { return "NtPowerInformation(ProcessorInformation, NULL, 0, pinfo, size) failed"; + } - for (uint32_t icore = 0; icore < cpu->coresLogical && pinfo[icore].MhzLimit; ++icore) - { + for (uint32_t icore = 0; icore < cpu->coresLogical && pinfo[icore].MhzLimit; ++icore) { uint32_t ifreq = 0; - while (cpu->coreTypes[ifreq].freq != pinfo[icore].MhzLimit && cpu->coreTypes[ifreq].freq > 0) + while (cpu->coreTypes[ifreq].freq != pinfo[icore].MhzLimit && cpu->coreTypes[ifreq].freq > 0) { ++ifreq; - if (cpu->coreTypes[ifreq].freq == 0) + } + if (cpu->coreTypes[ifreq].freq == 0) { cpu->coreTypes[ifreq].freq = pinfo[icore].MhzLimit; + } ++cpu->coreTypes[ifreq].count; } - if (cpu->frequencyBase == 0) + if (cpu->frequencyBase == 0) { cpu->frequencyBase = pinfo->MaxMhz; + } return NULL; } -const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) -{ +const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { detectNCores(cpu); const char* error = detectByRegistry(cpu); - if (error) + if (error) { return error; + } ffCPUDetectByCpuid(cpu); - if (options->showPeCoreCount) detectCoreTypes(cpu); + if (options->showPeCoreCount) { + detectCoreTypes(cpu); + } - if (cpu->frequencyMax == 0) + if (cpu->frequencyMax == 0) { detectMaxSpeedBySmbios(cpu); + } - if(options->temp) + if (options->temp) { detectThermalTemp(options, &cpu->temperature); + } return NULL; } diff --git a/src/detection/cpucache/cpucache.h b/src/detection/cpucache/cpucache.h index 2e6e060e4..5d917d9e5 100644 --- a/src/detection/cpucache/cpucache.h +++ b/src/detection/cpucache/cpucache.h @@ -3,43 +3,37 @@ #include "fastfetch.h" #include "modules/cpucache/option.h" -typedef enum __attribute__((__packed__)) FFCPUCacheType -{ +typedef enum __attribute__((__packed__)) FFCPUCacheType { FF_CPU_CACHE_TYPE_UNIFIED = 0, FF_CPU_CACHE_TYPE_INSTRUCTION = 1, FF_CPU_CACHE_TYPE_DATA = 2, FF_CPU_CACHE_TYPE_TRACE = 3, } FFCPUCacheType; -typedef struct FFCPUCache -{ +typedef struct FFCPUCache { uint32_t size; uint32_t num; uint32_t lineSize; FFCPUCacheType type; } FFCPUCache; -typedef struct FFCPUCacheResult -{ +typedef struct FFCPUCacheResult { FFlist caches[4]; // L1, L2, L3, L4(?) } FFCPUCacheResult; const char* ffDetectCPUCache(FFCPUCacheResult* result); -static inline FFCPUCache* ffCPUCacheAddItem(FFCPUCacheResult* result, uint32_t level, uint32_t size, uint32_t lineSize, FFCPUCacheType type) -{ +static inline FFCPUCache* ffCPUCacheAddItem(FFCPUCacheResult* result, uint32_t level, uint32_t size, uint32_t lineSize, FFCPUCacheType type) { FFlist* cacheLevel = &result->caches[level - 1]; - FF_LIST_FOR_EACH(FFCPUCache, item, *cacheLevel) - { - if (item->type == type && item->size == size && item->lineSize == lineSize) - { + FF_LIST_FOR_EACH (FFCPUCache, item, *cacheLevel) { + if (item->type == type && item->size == size && item->lineSize == lineSize) { item->num++; return item; } } - FFCPUCache* item = (FFCPUCache*)ffListAdd(cacheLevel); + FFCPUCache* item = (FFCPUCache*) ffListAdd(cacheLevel); *item = (FFCPUCache) { .size = size, .num = 1, diff --git a/src/detection/cpucache/cpucache_apple.c b/src/detection/cpucache/cpucache_apple.c index 09e890c28..61afcd750 100644 --- a/src/detection/cpucache/cpucache_apple.c +++ b/src/detection/cpucache/cpucache_apple.c @@ -2,11 +2,12 @@ #include "common/sysctl.h" #include "common/stringUtils.h" -const char* ffDetectCPUCache(FFCPUCacheResult* result) -{ +const char* ffDetectCPUCache(FFCPUCacheResult* result) { // https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_system_capabilities#3901385 uint32_t nPerfLevels = (uint32_t) ffSysctlGetInt("hw.nperflevels", 0); - if (nPerfLevels <= 0) return "sysctl(hw.nperflevels) failed"; + if (nPerfLevels <= 0) { + return "sysctl(hw.nperflevels) failed"; + } // macOS provides the global system cache line size uint32_t lineSize = (uint32_t) ffSysctlGetInt64("hw.cachelinesize", 0); @@ -16,42 +17,45 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) char* pSubkey = sysctlKey + strlen("hw.perflevelN."); const size_t lenLeft = ARRAY_SIZE(sysctlKey) - strlen("hw.perflevelN."); - for (uint32_t i = 0; i < nPerfLevels; ++i) - { + for (uint32_t i = 0; i < nPerfLevels; ++i) { *pNum = (char) ('0' + i); ffStrCopy(pSubkey, "physicalcpu", lenLeft); uint32_t ncpu = (uint32_t) ffSysctlGetInt(sysctlKey, 0); - if (ncpu <= 0) continue; + if (ncpu <= 0) { + continue; + } ffStrCopy(pSubkey, "l1icachesize", lenLeft); uint32_t size = (uint32_t) ffSysctlGetInt(sysctlKey, 0); - if (size) + if (size) { ffCPUCacheAddItem(result, 1, size, lineSize, FF_CPU_CACHE_TYPE_INSTRUCTION)->num = ncpu; + } ffStrCopy(pSubkey, "l1dcachesize", lenLeft); size = (uint32_t) ffSysctlGetInt(sysctlKey, 0); - if (size) + if (size) { ffCPUCacheAddItem(result, 1, size, lineSize, FF_CPU_CACHE_TYPE_DATA)->num = ncpu; + } ffStrCopy(pSubkey, "l2cachesize", lenLeft); size = (uint32_t) ffSysctlGetInt(sysctlKey, 0); - if (size) - { + if (size) { ffStrCopy(pSubkey, "cpusperl2", lenLeft); uint32_t cpuSper = (uint32_t) ffSysctlGetInt(sysctlKey, 0); - if (cpuSper) + if (cpuSper) { ffCPUCacheAddItem(result, 2, size, lineSize, FF_CPU_CACHE_TYPE_UNIFIED)->num = ncpu / cpuSper; + } } ffStrCopy(pSubkey, "l3cachesize", lenLeft); size = (uint32_t) ffSysctlGetInt(sysctlKey, 0); - if (size) - { + if (size) { ffStrCopy(pSubkey, "cpusperl3", lenLeft); uint32_t cpuSper = (uint32_t) ffSysctlGetInt(sysctlKey, 0); - if (cpuSper) + if (cpuSper) { ffCPUCacheAddItem(result, 3, size, lineSize, FF_CPU_CACHE_TYPE_UNIFIED)->num = ncpu / cpuSper; + } } } diff --git a/src/detection/cpucache/cpucache_linux.c b/src/detection/cpucache/cpucache_linux.c index 975a742e8..8f435d8ea 100644 --- a/src/detection/cpucache/cpucache_linux.c +++ b/src/detection/cpucache/cpucache_linux.c @@ -2,107 +2,130 @@ #include "common/io.h" #include "common/stringUtils.h" -static const char* parseCpuCacheIndex(FFstrbuf* path, FFCPUCacheResult* result, FFstrbuf* buffer, FFstrbuf* added) -{ +static const char* parseCpuCacheIndex(FFstrbuf* path, FFCPUCacheResult* result, FFstrbuf* buffer, FFstrbuf* added) { uint32_t baseLen = path->length; ffStrbufAppendS(path, "/level"); - if (!ffReadFileBuffer(path->chars, buffer)) + if (!ffReadFileBuffer(path->chars, buffer)) { return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/level\") == NULL"; + } uint32_t level = (uint32_t) ffStrbufToUInt(buffer, 0); - if (level < 1 || level > 4) return "level < 1 || level > 4"; + if (level < 1 || level > 4) { + return "level < 1 || level > 4"; + } ffStrbufSubstrBefore(path, baseLen); ffStrbufAppendS(path, "/size"); - if (!ffReadFileBuffer(path->chars, buffer)) + if (!ffReadFileBuffer(path->chars, buffer)) { return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/size\") == NULL"; + } uint32_t sizeKb = (uint32_t) ffStrbufToUInt(buffer, 0); - if (sizeKb == 0) return "size == 0"; + if (sizeKb == 0) { + return "size == 0"; + } ffStrbufSubstrBefore(path, baseLen); ffStrbufAppendS(path, "/type"); - if (!ffReadFileBuffer(path->chars, buffer)) + if (!ffReadFileBuffer(path->chars, buffer)) { return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/type\") == NULL"; + } ffStrbufTrimRightSpace(buffer); FFCPUCacheType cacheType = 0; - switch (buffer->chars[0]) - { - case 'I': cacheType = FF_CPU_CACHE_TYPE_INSTRUCTION; break; - case 'D': cacheType = FF_CPU_CACHE_TYPE_DATA; break; - case 'U': cacheType = FF_CPU_CACHE_TYPE_UNIFIED; break; - case 'T': cacheType = FF_CPU_CACHE_TYPE_TRACE; break; - default: return "unknown cache type"; + switch (buffer->chars[0]) { + case 'I': + cacheType = FF_CPU_CACHE_TYPE_INSTRUCTION; + break; + case 'D': + cacheType = FF_CPU_CACHE_TYPE_DATA; + break; + case 'U': + cacheType = FF_CPU_CACHE_TYPE_UNIFIED; + break; + case 'T': + cacheType = FF_CPU_CACHE_TYPE_TRACE; + break; + default: + return "unknown cache type"; } uint32_t lineSize = 0; ffStrbufSubstrBefore(path, baseLen); ffStrbufAppendS(path, "/coherency_line_size"); - if (ffReadFileBuffer(path->chars, buffer)) + if (ffReadFileBuffer(path->chars, buffer)) { lineSize = (uint32_t) ffStrbufToUInt(buffer, 0); + } ffStrbufSubstrBefore(path, baseLen); ffStrbufAppendS(path, "/shared_cpu_list"); ffStrbufClear(buffer); ffStrbufAppendC(buffer, '['); - if (!ffAppendFileBuffer(path->chars, buffer)) + if (!ffAppendFileBuffer(path->chars, buffer)) { return "ffAppendFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/shared_cpu_list\") == NULL"; + } ffStrbufTrimRightSpace(buffer); // deduplicate shared caches ffStrbufAppendF(buffer, "_%u_%u_%u_%u]", level, sizeKb, lineSize, cacheType); - if (ffStrbufContain(added, buffer)) return NULL; + if (ffStrbufContain(added, buffer)) { + return NULL; + } ffStrbufAppend(added, buffer); ffCPUCacheAddItem(result, level, sizeKb * 1024, lineSize, cacheType); return NULL; } -static const char* parseCpuCache(FFstrbuf* path, FFCPUCacheResult* result, FFstrbuf* buffer, FFstrbuf* added) -{ +static const char* parseCpuCache(FFstrbuf* path, FFCPUCacheResult* result, FFstrbuf* buffer, FFstrbuf* added) { ffStrbufAppendS(path, "/cache/"); uint32_t baseLen = path->length; FF_AUTO_CLOSE_DIR DIR* pathCacheDir = opendir(path->chars); - if (!pathCacheDir) + if (!pathCacheDir) { return "opendir(\"/sys/devices/system/cpu/cpuX/cache/\") == NULL"; + } struct dirent* pathCacheEntry; - while ((pathCacheEntry = readdir(pathCacheDir)) != NULL) - { - if (!ffStrStartsWith(pathCacheEntry->d_name, "index") - || !ffCharIsDigit(pathCacheEntry->d_name[strlen("index")])) continue; + while ((pathCacheEntry = readdir(pathCacheDir)) != NULL) { + if (!ffStrStartsWith(pathCacheEntry->d_name, "index") || !ffCharIsDigit(pathCacheEntry->d_name[strlen("index")])) { + continue; + } ffStrbufAppendS(path, pathCacheEntry->d_name); const char* error = parseCpuCacheIndex(path, result, buffer, added); - if (error) return error; + if (error) { + return error; + } ffStrbufSubstrBefore(path, baseLen); } return NULL; } -const char* ffDetectCPUCache(FFCPUCacheResult* result) -{ +const char* ffDetectCPUCache(FFCPUCacheResult* result) { // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-devices-system-cpu FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/sys/devices/system/cpu/"); uint32_t baseLen = path.length; FF_AUTO_CLOSE_DIR DIR* pathCpuDir = opendir(path.chars); - if (!pathCpuDir) + if (!pathCpuDir) { return "opendir(\"/sys/devices/system/cpu/\") == NULL"; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY added = ffStrbufCreate(); struct dirent* pathCpuEntry; - while ((pathCpuEntry = readdir(pathCpuDir)) != NULL) - { + while ((pathCpuEntry = readdir(pathCpuDir)) != NULL) { if (!ffStrStartsWith(pathCpuEntry->d_name, "cpu") || - !ffCharIsDigit(pathCpuEntry->d_name[strlen("cpu")])) continue; + !ffCharIsDigit(pathCpuEntry->d_name[strlen("cpu")])) { + continue; + } ffStrbufAppendS(&path, pathCpuEntry->d_name); const char* error = parseCpuCache(&path, result, &buffer, &added); - if (error) return error; + if (error) { + return error; + } ffStrbufSubstrBefore(&path, baseLen); } return NULL; diff --git a/src/detection/cpucache/cpucache_nosupport.c b/src/detection/cpucache/cpucache_nosupport.c index b405b9079..fae988593 100644 --- a/src/detection/cpucache/cpucache_nosupport.c +++ b/src/detection/cpucache/cpucache_nosupport.c @@ -1,6 +1,5 @@ #include "cpucache.h" -const char* ffDetectCPUCache(FF_MAYBE_UNUSED FFCPUCacheResult* result) -{ +const char* ffDetectCPUCache(FF_MAYBE_UNUSED FFCPUCacheResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/cpucache/cpucache_shared.c b/src/detection/cpucache/cpucache_shared.c index 14293c502..32b64e596 100644 --- a/src/detection/cpucache/cpucache_shared.c +++ b/src/detection/cpucache/cpucache_shared.c @@ -2,61 +2,60 @@ #include "common/smbiosHelper.h" #include "common/stringUtils.h" -typedef struct FFSmbiosCacheInfo -{ +typedef struct FFSmbiosCacheInfo { FFSmbiosHeader Header; - uint8_t SocketDesignation; // string + uint8_t SocketDesignation; // string uint16_t CacheConfiguration; // varies - uint16_t MaximumCacheSize; // varies - uint16_t InstalledSize; // varies - uint16_t SupportedSramType; // bit field - uint16_t CurrentSramType; // bit field + uint16_t MaximumCacheSize; // varies + uint16_t InstalledSize; // varies + uint16_t SupportedSramType; // bit field + uint16_t CurrentSramType; // bit field // 2.1+ - uint8_t CacheSpeed; // varies + uint8_t CacheSpeed; // varies uint8_t ErrorCorrectionType; // enum - uint8_t SystemCacheType; // enum - uint8_t Associativity; // enum + uint8_t SystemCacheType; // enum + uint8_t Associativity; // enum // 3.1+ - uint32_t MaximumCacheSize2; // bit field + uint32_t MaximumCacheSize2; // bit field uint32_t InstalledCacheSize2; // bit field } __attribute__((__packed__)) FFSmbiosCacheInfo; static_assert(offsetof(FFSmbiosCacheInfo, InstalledCacheSize2) == 0x17, "FFSmbiosCacheInfo: Wrong struct alignment"); -const char* ffDetectCPUCache(FFCPUCacheResult* result) -{ +const char* ffDetectCPUCache(FFCPUCacheResult* result) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosCacheInfo* data = (const FFSmbiosCacheInfo*) (*smbiosTable)[FF_SMBIOS_TYPE_CACHE_INFO]; - if (!data) + if (!data) { return "Cache information is not found in SMBIOS data"; + } const FFSmbiosCacheInfo* endOfTable = (const FFSmbiosCacheInfo*) (*smbiosTable)[FF_SMBIOS_TYPE_END_OF_TABLE]; - for (; data != endOfTable; data = (const FFSmbiosCacheInfo*) ffSmbiosNextEntry(&data->Header)) - { - if (data->Header.Type != FF_SMBIOS_TYPE_CACHE_INFO) + for (; data != endOfTable; data = (const FFSmbiosCacheInfo*) ffSmbiosNextEntry(&data->Header)) { + if (data->Header.Type != FF_SMBIOS_TYPE_CACHE_INFO) { continue; + } bool enabled = !!(data->CacheConfiguration & (1 << 7)); - if (!enabled) + if (!enabled) { continue; + } uint32_t size = data->InstalledSize; - if (size == 0) + if (size == 0) { continue; - - if (data->InstalledSize != 0xFFFF) - { - size *= (size >> 15 ? 64 : 1) * 1024u; } - else if (data->Header.Length > offsetof(FFSmbiosCacheInfo, InstalledCacheSize2)) - { + + if (data->InstalledSize != 0xFFFF) { + size *= (size >> 15 ? 64 : 1) * 1024u; + } else if (data->Header.Length > offsetof(FFSmbiosCacheInfo, InstalledCacheSize2)) { size = data->InstalledCacheSize2; size *= (size >> 31 ? 64 : 1) * 1024u; } @@ -64,11 +63,16 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) uint32_t level = (data->CacheConfiguration & 0b111u) + 1; FFCPUCacheType type; - switch (data->SystemCacheType) - { - case 3: type = FF_CPU_CACHE_TYPE_INSTRUCTION; break; - case 4: type = FF_CPU_CACHE_TYPE_DATA; break; - default: type = FF_CPU_CACHE_TYPE_UNIFIED; break; + switch (data->SystemCacheType) { + case 3: + type = FF_CPU_CACHE_TYPE_INSTRUCTION; + break; + case 4: + type = FF_CPU_CACHE_TYPE_DATA; + break; + default: + type = FF_CPU_CACHE_TYPE_UNIFIED; + break; } ffCPUCacheAddItem(result, level, size, 0, type); diff --git a/src/detection/cpucache/cpucache_windows.c b/src/detection/cpucache/cpucache_windows.c index 537a69a75..b9d3815fd 100644 --- a/src/detection/cpucache/cpucache_windows.c +++ b/src/detection/cpucache/cpucache_windows.c @@ -2,36 +2,42 @@ #include "common/mallocHelper.h" #include "common/windows/nt.h" -const char* ffDetectCPUCache(FFCPUCacheResult* result) -{ +const char* ffDetectCPUCache(FFCPUCacheResult* result) { LOGICAL_PROCESSOR_RELATIONSHIP lpr = RelationCache; DWORD length = 0; NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), NULL, 0, &length); - if (length == 0) + if (length == 0) { return "GetLogicalProcessorInformationEx(RelationCache, NULL, &length) failed"; + } SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* FF_AUTO_FREE - pProcessorInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)malloc(length); + pProcessorInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) malloc(length); - if (!NT_SUCCESS(NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), pProcessorInfo, length, &length))) + if (!NT_SUCCESS(NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), pProcessorInfo, length, &length))) { return "GetLogicalProcessorInformationEx(RelationCache, pProcessorInfo, &length) failed"; + } - for( + for ( SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* ptr = pProcessorInfo; - (uint8_t*)ptr < ((uint8_t*)pProcessorInfo) + length; - ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((uint8_t*)ptr) + ptr->Size) - ) - { - if(__builtin_expect(ptr->Relationship == RelationCache && ptr->Cache.Level > 0 && ptr->Cache.Level <= 4, true)) - { + (uint8_t*) ptr < ((uint8_t*) pProcessorInfo) + length; + ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) (((uint8_t*) ptr) + ptr->Size)) { + if (__builtin_expect(ptr->Relationship == RelationCache && ptr->Cache.Level > 0 && ptr->Cache.Level <= 4, true)) { FFCPUCacheType cacheType = 0; - switch (ptr->Cache.Type) - { - case CacheUnified: cacheType = FF_CPU_CACHE_TYPE_UNIFIED; break; - case CacheInstruction: cacheType = FF_CPU_CACHE_TYPE_INSTRUCTION; break; - case CacheData: cacheType = FF_CPU_CACHE_TYPE_DATA; break; - case CacheTrace: cacheType = FF_CPU_CACHE_TYPE_TRACE; break; - default: break; + switch (ptr->Cache.Type) { + case CacheUnified: + cacheType = FF_CPU_CACHE_TYPE_UNIFIED; + break; + case CacheInstruction: + cacheType = FF_CPU_CACHE_TYPE_INSTRUCTION; + break; + case CacheData: + cacheType = FF_CPU_CACHE_TYPE_DATA; + break; + case CacheTrace: + cacheType = FF_CPU_CACHE_TYPE_TRACE; + break; + default: + break; } ffCPUCacheAddItem(result, ptr->Cache.Level, ptr->Cache.CacheSize, ptr->Cache.LineSize, cacheType); } diff --git a/src/detection/cpuusage/cpuusage.c b/src/detection/cpuusage/cpuusage.c index 72393aa45..3013e99f7 100644 --- a/src/detection/cpuusage/cpuusage.c +++ b/src/detection/cpuusage/cpuusage.c @@ -7,50 +7,53 @@ static FFlist cpuTimes1; static uint64_t startTime; -void ffPrepareCPUUsage(void) -{ - if (cpuTimes1.elementSize != 0) return; // Already prepared +void ffPrepareCPUUsage(void) { + if (cpuTimes1.elementSize != 0) { + return; // Already prepared + } ffListInit(&cpuTimes1, sizeof(FFCpuUsageInfo)); ffGetCpuUsageInfo(&cpuTimes1); startTime = ffTimeGetNow(); } -const char* ffGetCpuUsageResult(FFCPUUsageOptions* options, FFlist* result) -{ +const char* ffGetCpuUsageResult(FFCPUUsageOptions* options, FFlist* result) { const char* error = NULL; - if(cpuTimes1.elementSize == 0) - { + if (cpuTimes1.elementSize == 0) { ffListInit(&cpuTimes1, sizeof(FFCpuUsageInfo)); error = ffGetCpuUsageInfo(&cpuTimes1); - if(error) return error; + if (error) { + return error; + } ffTimeSleep(options->waitTime); - } - else - { + } else { uint64_t elapsedTime = ffTimeGetNow() - startTime; - if (elapsedTime < options->waitTime) - ffTimeSleep(options->waitTime - (uint32_t)elapsedTime); + if (elapsedTime < options->waitTime) { + ffTimeSleep(options->waitTime - (uint32_t) elapsedTime); + } } - if(cpuTimes1.length == 0) return "No CPU cores found"; + if (cpuTimes1.length == 0) { + return "No CPU cores found"; + } FF_LIST_AUTO_DESTROY cpuTimes2 = ffListCreate(sizeof(FFCpuUsageInfo)); uint32_t retryCount = 0; retry: error = ffGetCpuUsageInfo(&cpuTimes2); - if(error) return error; - if(cpuTimes1.length != cpuTimes2.length) return "Unexpected CPU usage result"; + if (error) { + return error; + } + if (cpuTimes1.length != cpuTimes2.length) { + return "Unexpected CPU usage result"; + } - for (uint32_t i = 0; i < cpuTimes1.length; ++i) - { + for (uint32_t i = 0; i < cpuTimes1.length; ++i) { FFCpuUsageInfo* cpuTime1 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes1, i); FFCpuUsageInfo* cpuTime2 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes2, i); - if (cpuTime2->totalAll <= cpuTime1->totalAll) - { - if (++retryCount <= 3) - { + if (cpuTime2->totalAll <= cpuTime1->totalAll) { + if (++retryCount <= 3) { ffListClear(&cpuTimes2); ffTimeSleep(options->waitTime); goto retry; @@ -59,11 +62,10 @@ retry: } } - for (uint32_t i = 0; i < cpuTimes1.length; ++i) - { + for (uint32_t i = 0; i < cpuTimes1.length; ++i) { FFCpuUsageInfo* cpuTime1 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes1, i); FFCpuUsageInfo* cpuTime2 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes2, i); - *(double*) ffListAdd(result) = (double)(cpuTime2->inUseAll - cpuTime1->inUseAll) / (double)(cpuTime2->totalAll - cpuTime1->totalAll) * 100; + *(double*) ffListAdd(result) = (double) (cpuTime2->inUseAll - cpuTime1->inUseAll) / (double) (cpuTime2->totalAll - cpuTime1->totalAll) * 100; cpuTime1->inUseAll = cpuTime2->inUseAll; cpuTime1->totalAll = cpuTime2->totalAll; } diff --git a/src/detection/cpuusage/cpuusage_apple.c b/src/detection/cpuusage/cpuusage_apple.c index 0630072ca..a3e9aa67f 100644 --- a/src/detection/cpuusage/cpuusage_apple.c +++ b/src/detection/cpuusage/cpuusage_apple.c @@ -5,28 +5,26 @@ #include #include -const char* ffGetCpuUsageInfo(FFlist* cpuTimes) -{ +const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { natural_t numCPUs = 0U; processor_info_array_t cpuInfo; mach_msg_type_number_t numCpuInfo; - if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUs, &cpuInfo, &numCpuInfo) != KERN_SUCCESS) + if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUs, &cpuInfo, &numCpuInfo) != KERN_SUCCESS) { return "host_processor_info() failed"; - if (numCPUs * CPU_STATE_MAX != numCpuInfo) + } + if (numCPUs * CPU_STATE_MAX != numCpuInfo) { return "Unexpected host_processor_info() result"; + } - for (natural_t i = 0U; i < numCPUs; ++i) - { - integer_t inUse = cpuInfo[CPU_STATE_MAX * i + CPU_STATE_USER] - + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_SYSTEM] - + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_NICE]; + for (natural_t i = 0U; i < numCPUs; ++i) { + integer_t inUse = cpuInfo[CPU_STATE_MAX * i + CPU_STATE_USER] + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_SYSTEM] + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_NICE]; integer_t total = inUse + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_IDLE]; FFCpuUsageInfo* info = (FFCpuUsageInfo*) ffListAdd(cpuTimes); *info = (FFCpuUsageInfo) { - .inUseAll = (uint64_t)inUse, - .totalAll = (uint64_t)total, + .inUseAll = (uint64_t) inUse, + .totalAll = (uint64_t) total, }; } diff --git a/src/detection/cpuusage/cpuusage_bsd.c b/src/detection/cpuusage/cpuusage_bsd.c index eee4ac20d..ba37ea331 100644 --- a/src/detection/cpuusage/cpuusage_bsd.c +++ b/src/detection/cpuusage/cpuusage_bsd.c @@ -7,23 +7,24 @@ #include #if __OpenBSD__ || __NetBSD__ - #include +# include #endif -const char* ffGetCpuUsageInfo(FFlist* cpuTimes) -{ +const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { size_t neededLength = 0; -#if __OpenBSD__|| __NetBSD__ - #ifdef KERN_CPTIME - int ctls[] = {CTL_KERN, KERN_CPTIME}; - #else - int ctls[] = {CTL_KERN, KERN_CP_TIME}; - #endif - if (sysctl(ctls, 2, NULL, &neededLength, NULL, 0) != 0) +#if __OpenBSD__ || __NetBSD__ +# ifdef KERN_CPTIME + int ctls[] = {CTL_KERN, KERN_CPTIME}; +# else + int ctls[] = {CTL_KERN, KERN_CP_TIME}; +# endif + if (sysctl(ctls, 2, NULL, &neededLength, NULL, 0) != 0) { return "sysctl({CTL_KERN, KERN_CPTIME}, 2, NULL) failed"; + } #else - if(sysctlbyname("kern.cp_times", NULL, &neededLength, NULL, 0) != 0) + if (sysctlbyname("kern.cp_times", NULL, &neededLength, NULL, 0) != 0) { return "sysctlbyname(kern.cp_times, NULL) failed"; + } #endif uint32_t coreCount = (uint32_t) (neededLength / (CPUSTATES * sizeof(uint64_t))); @@ -32,15 +33,16 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) FF_AUTO_FREE uint64_t (*cpTimes)[CPUSTATES] = malloc(neededLength); #if __OpenBSD__ || __NetBSD__ - if (sysctl(ctls, 2, cpTimes, &neededLength, NULL, 0) != 0) + if (sysctl(ctls, 2, cpTimes, &neededLength, NULL, 0) != 0) { return "sysctl({CTL_KERN, KERN_CPTIME}, 2, NULL) failed"; + } #else - if(sysctlbyname("kern.cp_times", cpTimes, &neededLength, NULL, 0) != 0) + if (sysctlbyname("kern.cp_times", cpTimes, &neededLength, NULL, 0) != 0) { return "sysctlbyname(kern.cp_times, cpTime) failed"; + } #endif - for (uint32_t i = 0; i < coreCount; ++i) - { + for (uint32_t i = 0; i < coreCount; ++i) { uint64_t* cpTime = cpTimes[i]; uint64_t inUse = cpTime[CP_USER] + cpTime[CP_NICE] + cpTime[CP_SYS] + cpTime[CP_INTR]; uint64_t total = inUse + cpTime[CP_IDLE]; diff --git a/src/detection/cpuusage/cpuusage_haiku.c b/src/detection/cpuusage/cpuusage_haiku.c index f946ecbf4..3089b8549 100644 --- a/src/detection/cpuusage/cpuusage_haiku.c +++ b/src/detection/cpuusage/cpuusage_haiku.c @@ -4,20 +4,20 @@ #include -const char* ffGetCpuUsageInfo(FFlist* cpuTimes) -{ +const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { system_info sysInfo; - if (get_system_info(&sysInfo) != B_OK) + if (get_system_info(&sysInfo) != B_OK) { return "get_system_info() failed"; + } FF_AUTO_FREE cpu_info* cpuInfo = malloc(sizeof(*cpuInfo) * sysInfo.cpu_count); - if (get_cpu_info(0, sysInfo.cpu_count, cpuInfo) != B_OK) + if (get_cpu_info(0, sysInfo.cpu_count, cpuInfo) != B_OK) { return "get_cpu_info() failed"; + } uint64_t uptime = (uint64_t) system_time(); - for (uint32_t i = 0; i < sysInfo.cpu_count; ++i) - { + for (uint32_t i = 0; i < sysInfo.cpu_count; ++i) { FFCpuUsageInfo* info = (FFCpuUsageInfo*) ffListAdd(cpuTimes); info->inUseAll = (uint64_t) cpuInfo[i].active_time; info->totalAll = uptime; diff --git a/src/detection/cpuusage/cpuusage_linux.c b/src/detection/cpuusage/cpuusage_linux.c index 355fb2d12..6d447a59b 100644 --- a/src/detection/cpuusage/cpuusage_linux.c +++ b/src/detection/cpuusage/cpuusage_linux.c @@ -5,32 +5,29 @@ #include #include -const char* ffGetCpuUsageInfo(FFlist* cpuTimes) -{ +const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { char buf[PROC_FILE_BUFFSIZ]; ssize_t nRead = ffReadFileData("/proc/stat", ARRAY_SIZE(buf) - 1, buf); - if(nRead < 0) - { - #ifdef __ANDROID__ + if (nRead < 0) { +#ifdef __ANDROID__ return "Accessing \"/proc/stat\" is restricted on Android O+"; - #else +#else return "ffReadFileData(\"/proc/stat\", ARRAY_SIZE(buf) - 1, buf) failed"; - #endif +#endif } buf[nRead] = '\0'; // Skip first line - char *start = NULL; - if((start = strchr(buf, '\n')) == NULL) + char* start = NULL; + if ((start = strchr(buf, '\n')) == NULL) { return "skip first line failed"; + } ++start; uint64_t user = 0, nice = 0, system = 0, idle = 0, iowait = 0, irq = 0, softirq = 0; - char *token = NULL; - while ((token = strchr(start, '\n'))) - { - if(sscanf(start, "cpu%*d%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%*[^\n]\n", &user, &nice, &system, &idle, &iowait, &irq, &softirq) == 7) - { + char* token = NULL; + while ((token = strchr(start, '\n'))) { + if (sscanf(start, "cpu%*d%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%*[^\n]\n", &user, &nice, &system, &idle, &iowait, &irq, &softirq) == 7) { uint64_t inUse = user + nice + system + irq + softirq; uint64_t total = inUse + idle + iowait; @@ -39,9 +36,9 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) .inUseAll = inUse, .totalAll = total, }; - } - else + } else { break; + } start = token + 1; } diff --git a/src/detection/cpuusage/cpuusage_nosupport.c b/src/detection/cpuusage/cpuusage_nosupport.c index da8bbdddd..d802dbdd2 100644 --- a/src/detection/cpuusage/cpuusage_nosupport.c +++ b/src/detection/cpuusage/cpuusage_nosupport.c @@ -1,7 +1,6 @@ #include "fastfetch.h" #include "detection/cpuusage/cpuusage.h" -const char* ffGetCpuUsageInfo(FF_MAYBE_UNUSED FFlist* cpuTimes) -{ +const char* ffGetCpuUsageInfo(FF_MAYBE_UNUSED FFlist* cpuTimes) { return "Not support on this platform"; } diff --git a/src/detection/cpuusage/cpuusage_sunos.c b/src/detection/cpuusage/cpuusage_sunos.c index 2e36adbfe..9ef75d83b 100644 --- a/src/detection/cpuusage/cpuusage_sunos.c +++ b/src/detection/cpuusage/cpuusage_sunos.c @@ -4,26 +4,26 @@ #include #include -static inline void kstatFreeWrap(kstat_ctl_t** pkc) -{ +static inline void kstatFreeWrap(kstat_ctl_t** pkc) { assert(pkc); - if (*pkc) + if (*pkc) { kstat_close(*pkc); + } } -const char* ffGetCpuUsageInfo(FFlist* cpuTimes) -{ +const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { __attribute__((__cleanup__(kstatFreeWrap))) kstat_ctl_t* kc = kstat_open(); - if (!kc) + if (!kc) { return "kstat_open() failed"; + } - for (int i = 0;; ++i) - { + for (int i = 0;; ++i) { kstat_t* ks = kstat_lookup(kc, "cpu_stat", i, NULL); cpu_stat_t cs; - if (!ks || kstat_read(kc, ks, &cs) < 0) + if (!ks || kstat_read(kc, ks, &cs) < 0) { break; + } uint64_t inUse = cs.cpu_sysinfo.cpu[CPU_USER] + cs.cpu_sysinfo.cpu[CPU_KERNEL]; uint64_t total = inUse + cs.cpu_sysinfo.cpu[CPU_IDLE] + cs.cpu_sysinfo.cpu[CPU_WAIT]; diff --git a/src/detection/cpuusage/cpuusage_windows.c b/src/detection/cpuusage/cpuusage_windows.c index 1e96f43d5..05505577e 100644 --- a/src/detection/cpuusage/cpuusage_windows.c +++ b/src/detection/cpuusage/cpuusage_windows.c @@ -8,25 +8,25 @@ #include "common/windows/perflib_.h" #include "common/windows/nt.h" -static const char* getInfoByNqsi(FFlist* cpuTimes) -{ +static const char* getInfoByNqsi(FFlist* cpuTimes) { ULONG size = 0; - if(NtQuerySystemInformation(SystemProcessorPerformanceInformation, NULL, 0, &size) != STATUS_INFO_LENGTH_MISMATCH) + if (NtQuerySystemInformation(SystemProcessorPerformanceInformation, NULL, 0, &size) != STATUS_INFO_LENGTH_MISMATCH) { return "NtQuerySystemInformation(SystemProcessorPerformanceInformation, NULL) failed"; + } - SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* FF_AUTO_FREE pinfo = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION*)malloc(size); - if(!NT_SUCCESS(NtQuerySystemInformation(SystemProcessorPerformanceInformation, pinfo, size, &size))) + SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* FF_AUTO_FREE pinfo = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION*) malloc(size); + if (!NT_SUCCESS(NtQuerySystemInformation(SystemProcessorPerformanceInformation, pinfo, size, &size))) { return "NtQuerySystemInformation(SystemProcessorPerformanceInformation, size) failed"; + } - for (uint32_t i = 0; i < size / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION); ++i) - { + for (uint32_t i = 0; i < size / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION); ++i) { SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* coreInfo = pinfo + i; // KernelTime includes IdleTime and DpcTime. coreInfo->KernelTime.QuadPart -= coreInfo->IdleTime.QuadPart; uint64_t inUse = (uint64_t) (coreInfo->UserTime.QuadPart + coreInfo->KernelTime.QuadPart); - uint64_t total = inUse + (uint64_t)coreInfo->IdleTime.QuadPart; + uint64_t total = inUse + (uint64_t) coreInfo->IdleTime.QuadPart; FFCpuUsageInfo* info = (FFCpuUsageInfo*) ffListAdd(cpuTimes); *info = (FFCpuUsageInfo) { @@ -38,21 +38,18 @@ static const char* getInfoByNqsi(FFlist* cpuTimes) return NULL; } -static const char* getInfoByPerflib(FFlist* cpuTimes) -{ +static const char* getInfoByPerflib(FFlist* cpuTimes) { static HANDLE hQuery = NULL; - if (hQuery == NULL) - { - struct FFPerfQuerySpec - { + if (hQuery == NULL) { + struct FFPerfQuerySpec { PERF_COUNTER_IDENTIFIER Identifier; WCHAR Name[16]; } querySpec = { .Identifier = { // Processor Information GUID // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\_V2Providers\{383487a6-3676-4870-a4e7-d45b30c35629}\{b4fc721a-0378-476f-89ba-a5a79f810b36} - .CounterSetGuid = { 0xb4fc721a, 0x0378, 0x476f, {0x89, 0xba, 0xa5, 0xa7, 0x9f, 0x81, 0x0b, 0x36} }, + .CounterSetGuid = {0xb4fc721a, 0x0378, 0x476f, {0x89, 0xba, 0xa5, 0xa7, 0x9f, 0x81, 0x0b, 0x36}}, .Size = sizeof(querySpec), .CounterId = PERF_WILDCARD_COUNTER, // https://learn.microsoft.com/en-us/windows/win32/perfctrs/using-the-perflib-functions-to-consume-counter-data .InstanceId = PERF_WILDCARD_COUNTER, @@ -60,84 +57,86 @@ static const char* getInfoByPerflib(FFlist* cpuTimes) .Name = PERF_WILDCARD_INSTANCE, }; - if (PerfOpenQueryHandle(NULL, &hQuery) != ERROR_SUCCESS) - { + if (PerfOpenQueryHandle(NULL, &hQuery) != ERROR_SUCCESS) { PerfCloseQueryHandle(hQuery); hQuery = INVALID_HANDLE_VALUE; return "PerfOpenQueryHandle() failed"; } - if (PerfAddCounters(hQuery, &querySpec.Identifier, sizeof(querySpec)) != ERROR_SUCCESS) - { + if (PerfAddCounters(hQuery, &querySpec.Identifier, sizeof(querySpec)) != ERROR_SUCCESS) { PerfCloseQueryHandle(hQuery); hQuery = INVALID_HANDLE_VALUE; return "PerfAddCounters() failed"; } - if (querySpec.Identifier.Status != ERROR_SUCCESS) - { + if (querySpec.Identifier.Status != ERROR_SUCCESS) { PerfCloseQueryHandle(hQuery); hQuery = INVALID_HANDLE_VALUE; return "PerfAddCounters() reports invalid identifier"; } } - if (hQuery == INVALID_HANDLE_VALUE) + if (hQuery == INVALID_HANDLE_VALUE) { return "Init hQuery failed"; + } DWORD dataSize = 0; - if (PerfQueryCounterData(hQuery, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) + if (PerfQueryCounterData(hQuery, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { return "PerfQueryCounterData(NULL) failed"; + } - if (dataSize <= sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER)) + if (dataSize <= sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER)) { return "instance doesn't exist"; + } - FF_AUTO_FREE PERF_DATA_HEADER* const pDataHeader = (PERF_DATA_HEADER*)malloc(dataSize); - if (PerfQueryCounterData(hQuery, pDataHeader, dataSize, &dataSize) != ERROR_SUCCESS) + FF_AUTO_FREE PERF_DATA_HEADER* const pDataHeader = (PERF_DATA_HEADER*) malloc(dataSize); + if (PerfQueryCounterData(hQuery, pDataHeader, dataSize, &dataSize) != ERROR_SUCCESS) { return "PerfQueryCounterData(pDataHeader) failed"; + } - PERF_COUNTER_HEADER* pCounterHeader = (PERF_COUNTER_HEADER*)(pDataHeader + 1); - if (pCounterHeader->dwType != PERF_COUNTERSET) + PERF_COUNTER_HEADER* pCounterHeader = (PERF_COUNTER_HEADER*) (pDataHeader + 1); + if (pCounterHeader->dwType != PERF_COUNTERSET) { return "Invalid counter type"; + } - PERF_MULTI_COUNTERS* pMultiCounters = (PERF_MULTI_COUNTERS*)(pCounterHeader + 1); - if (pMultiCounters->dwCounters == 0) + PERF_MULTI_COUNTERS* pMultiCounters = (PERF_MULTI_COUNTERS*) (pCounterHeader + 1); + if (pMultiCounters->dwCounters == 0) { return "No CPU counters found"; + } - PERF_MULTI_INSTANCES* pMultiInstances = (PERF_MULTI_INSTANCES*)((BYTE*)pMultiCounters + pMultiCounters->dwSize); - if (pMultiInstances->dwInstances == 0) + PERF_MULTI_INSTANCES* pMultiInstances = (PERF_MULTI_INSTANCES*) ((BYTE*) pMultiCounters + pMultiCounters->dwSize); + if (pMultiInstances->dwInstances == 0) { return "No CPU instances found"; + } - PERF_INSTANCE_HEADER* pInstanceHeader = (PERF_INSTANCE_HEADER*)(pMultiInstances + 1); - for (DWORD iInstance = 0; iInstance < pMultiInstances->dwInstances; ++iInstance) - { - const wchar_t* instanceName = (const wchar_t*)((BYTE*)pInstanceHeader + sizeof(*pInstanceHeader)); + PERF_INSTANCE_HEADER* pInstanceHeader = (PERF_INSTANCE_HEADER*) (pMultiInstances + 1); + for (DWORD iInstance = 0; iInstance < pMultiInstances->dwInstances; ++iInstance) { + const wchar_t* instanceName = (const wchar_t*) ((BYTE*) pInstanceHeader + sizeof(*pInstanceHeader)); - PERF_COUNTER_DATA* pCounterData = (PERF_COUNTER_DATA*)((BYTE*)pInstanceHeader + pInstanceHeader->Size); + PERF_COUNTER_DATA* pCounterData = (PERF_COUNTER_DATA*) ((BYTE*) pInstanceHeader + pInstanceHeader->Size); uint64_t processorUtility = UINT64_MAX, utilityBase = UINT64_MAX; - for (ULONG iCounter = 0; iCounter != pMultiCounters->dwCounters; iCounter++) - { - DWORD* pCounterIds = (DWORD*)(pMultiCounters + 1); + for (ULONG iCounter = 0; iCounter != pMultiCounters->dwCounters; iCounter++) { + DWORD* pCounterIds = (DWORD*) (pMultiCounters + 1); // https://learn.microsoft.com/en-us/windows/win32/perfctrs/using-the-perflib-functions-to-consume-counter-data switch (pCounterIds[iCounter]) { - case 26: // % Processor Utility (#26, Type=PERF_AVERAGE_BULK) - assert(pCounterData->dwDataSize == sizeof(uint64_t)); - processorUtility = *(uint64_t*)(pCounterData + 1); - break; - case 27: // % Utility Base (#27, Type=PERF_AVERAGE_BASE) - assert(pCounterData->dwDataSize == sizeof(uint32_t)); - utilityBase = *(uint32_t*)(pCounterData + 1) * 100LLU; - break; + case 26: // % Processor Utility (#26, Type=PERF_AVERAGE_BULK) + assert(pCounterData->dwDataSize == sizeof(uint64_t)); + processorUtility = *(uint64_t*) (pCounterData + 1); + break; + case 27: // % Utility Base (#27, Type=PERF_AVERAGE_BASE) + assert(pCounterData->dwDataSize == sizeof(uint32_t)); + utilityBase = *(uint32_t*) (pCounterData + 1) * 100LLU; + break; } - pCounterData = (PERF_COUNTER_DATA*)((BYTE*)pCounterData + pCounterData->dwSize); + pCounterData = (PERF_COUNTER_DATA*) ((BYTE*) pCounterData + pCounterData->dwSize); } - if (wcschr(instanceName, L'_') == NULL /* ignore `_Total` */) - { - if (processorUtility == UINT64_MAX) + if (wcschr(instanceName, L'_') == NULL /* ignore `_Total` */) { + if (processorUtility == UINT64_MAX) { return "Counter \"% Processor Utility\" are not supported"; + } FFCpuUsageInfo* info = (FFCpuUsageInfo*) ffListAdd(cpuTimes); *info = (FFCpuUsageInfo) { @@ -146,21 +145,21 @@ static const char* getInfoByPerflib(FFlist* cpuTimes) }; } - pInstanceHeader = (PERF_INSTANCE_HEADER*)pCounterData; + pInstanceHeader = (PERF_INSTANCE_HEADER*) pCounterData; } return NULL; } -const char* ffGetCpuUsageInfo(FFlist* cpuTimes) -{ +const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { const char* error = NULL; - if (ffIsWindows10OrGreater()) - { + if (ffIsWindows10OrGreater()) { error = getInfoByPerflib(cpuTimes); FF_DEBUG("Get CPU usage info by Perflib: %s", error ?: "success"); - if (!error) return NULL; + if (!error) { + return NULL; + } ffListClear(cpuTimes); } diff --git a/src/detection/cursor/cursor.h b/src/detection/cursor/cursor.h index 6a6f68b27..34ef86c8f 100644 --- a/src/detection/cursor/cursor.h +++ b/src/detection/cursor/cursor.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/cursor/option.h" -typedef struct FFCursorResult -{ +typedef struct FFCursorResult { FFstrbuf theme; FFstrbuf size; FFstrbuf error; diff --git a/src/detection/cursor/cursor_linux.c b/src/detection/cursor/cursor_linux.c index 4cccd721d..ae7b01c73 100644 --- a/src/detection/cursor/cursor_linux.c +++ b/src/detection/cursor/cursor_linux.c @@ -9,58 +9,54 @@ #include -static bool detectCursorGTK(FFCursorResult* result) -{ +static bool detectCursorGTK(FFCursorResult* result) { const FFGTKResult* gtk = ffDetectGTK4(); - if(gtk->cursor.length == 0) + if (gtk->cursor.length == 0) { gtk = ffDetectGTK3(); + } - if(gtk->cursor.length == 0) + if (gtk->cursor.length == 0) { gtk = ffDetectGTK2(); + } - if(gtk->cursor.length == 0) + if (gtk->cursor.length == 0) { return false; + } ffStrbufAppend(&result->theme, >k->cursor); ffStrbufAppend(&result->size, >k->cursorSize); return true; } -static void detectCursorFromConfigFile(const char* relativeFilePath, const char* themeStart, const char* themeDefault, const char* sizeStart, const char* sizeDefault, FFCursorResult* result) -{ - if(ffParsePropFileConfigValues(relativeFilePath, 2, (FFpropquery[]) { - {themeStart, &result->theme}, - {sizeStart, &result->size} - })) { - - if(result->theme.length == 0) +static void detectCursorFromConfigFile(const char* relativeFilePath, const char* themeStart, const char* themeDefault, const char* sizeStart, const char* sizeDefault, FFCursorResult* result) { + if (ffParsePropFileConfigValues(relativeFilePath, 2, (FFpropquery[]) {{themeStart, &result->theme}, {sizeStart, &result->size}})) { + if (result->theme.length == 0) { ffStrbufAppendS(&result->theme, themeDefault); + } - if(result->size.length == 0) + if (result->size.length == 0) { ffStrbufAppendS(&result->size, sizeDefault); + } } - if(result->theme.length == 0) + if (result->theme.length == 0) { ffStrbufAppendF(&result->error, "Couldn't find cursor in %s", relativeFilePath); + } } -static bool detectCursorFromXResources(FFCursorResult* result) -{ - ffParsePropFileHomeValues(".Xresources", 2, (FFpropquery[]) { - {"Xcursor.theme :", &result->theme}, - {"Xcursor.size :", &result->size} - }); +static bool detectCursorFromXResources(FFCursorResult* result) { + ffParsePropFileHomeValues(".Xresources", 2, (FFpropquery[]) {{"Xcursor.theme :", &result->theme}, {"Xcursor.size :", &result->size}}); return result->theme.length > 0; } -static bool detectCursorFromEnv(FFCursorResult* result) -{ +static bool detectCursorFromEnv(FFCursorResult* result) { const char* xcursor_theme = getenv("XCURSOR_THEME"); - if(!ffStrSet(xcursor_theme)) + if (!ffStrSet(xcursor_theme)) { return false; + } ffStrbufAppendS(&result->theme, xcursor_theme); ffStrbufAppendS(&result->size, getenv("XCURSOR_SIZE")); @@ -68,12 +64,12 @@ static bool detectCursorFromEnv(FFCursorResult* result) return true; } -static bool detectCursorHyprcursor(FFCursorResult* result) -{ +static bool detectCursorHyprcursor(FFCursorResult* result) { const char* hyprcursor_theme = getenv("HYPRCURSOR_THEME"); - if(!ffStrSet(hyprcursor_theme)) + if (!ffStrSet(hyprcursor_theme)) { return false; + } ffStrbufAppendS(&result->theme, hyprcursor_theme); ffStrbufAppendS(&result->size, getenv("HYPRCURSOR_SIZE")); @@ -81,25 +77,25 @@ static bool detectCursorHyprcursor(FFCursorResult* result) return true; } -void ffDetectCursor(FFCursorResult* result) -{ +void ffDetectCursor(FFCursorResult* result) { const FFDisplayServerResult* wmde = ffConnectDisplayServer(); - if(ffStrbufEqualS(&wmde->wmPrettyName, FF_WM_PRETTY_WSLG)) + if (ffStrbufEqualS(&wmde->wmPrettyName, FF_WM_PRETTY_WSLG)) { ffStrbufAppendS(&result->error, "WSLg uses native windows cursor"); - else if(ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) + } else if (ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) { ffStrbufAppendS(&result->error, "Cursor isn't supported in TTY"); - else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_PLASMA)) + } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_PLASMA)) { detectCursorFromConfigFile("kcminputrc", "cursorTheme =", "Breeze", "cursorSize =", "24", result); - else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_LXQT)) + } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_LXQT)) { detectCursorFromConfigFile("lxqt/session.conf", "cursor_theme =", "Adwaita", "cursor_size =", "24", result); - else if(ffStrbufIgnCaseEqualS(&wmde->wmPrettyName, FF_WM_PRETTY_HYPRLAND) && detectCursorHyprcursor(result)) + } else if (ffStrbufIgnCaseEqualS(&wmde->wmPrettyName, FF_WM_PRETTY_HYPRLAND) && detectCursorHyprcursor(result)) { return; - else if( + } else if ( !detectCursorGTK(result) && !detectCursorFromEnv(result) && !ffParsePropFileHome(".icons/default/index.theme", "Inherits =", &result->theme) && !detectCursorFromXResources(result) && - !ffParsePropFileData("icons/default/index.theme", "Inherits =", &result->theme) - ) ffStrbufAppendS(&result->error, "Couldn't find cursor"); + !ffParsePropFileData("icons/default/index.theme", "Inherits =", &result->theme)) { + ffStrbufAppendS(&result->error, "Couldn't find cursor"); + } } diff --git a/src/detection/cursor/cursor_nosupport.c b/src/detection/cursor/cursor_nosupport.c index 6e36e55ca..797d4207b 100644 --- a/src/detection/cursor/cursor_nosupport.c +++ b/src/detection/cursor/cursor_nosupport.c @@ -1,6 +1,5 @@ #include "cursor.h" -void ffDetectCursor(FF_MAYBE_UNUSED FFCursorResult* result) -{ +void ffDetectCursor(FF_MAYBE_UNUSED FFCursorResult* result) { ffStrbufInitS(&result->error, "Not supported on this platform"); } diff --git a/src/detection/cursor/cursor_windows.c b/src/detection/cursor/cursor_windows.c index 220b76309..d9a4e5ae7 100644 --- a/src/detection/cursor/cursor_windows.c +++ b/src/detection/cursor/cursor_windows.c @@ -3,16 +3,16 @@ #include "common/io.h" #include "common/windows/registry.h" -void ffDetectCursor(FFCursorResult* result) -{ +void ffDetectCursor(FFCursorResult* result) { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Cursors", &hKey, &result->error)) - { + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Cursors", &hKey, &result->error)) { uint32_t cursorBaseSize; if (ffRegReadValues(hKey, 2, (FFRegValueArg[]) { - FF_ARG(result->theme, NULL), - FF_ARG(cursorBaseSize, L"CursorBaseSize"), - }, &result->error)) + FF_ARG(result->theme, NULL), + FF_ARG(cursorBaseSize, L"CursorBaseSize"), + }, + &result->error)) { ffStrbufAppendUInt(&result->size, cursorBaseSize); + } } } diff --git a/src/detection/de/de_linux.c b/src/detection/de/de_linux.c index b7ac7a6ed..7c83aa6f1 100644 --- a/src/detection/de/de_linux.c +++ b/src/detection/de/de_linux.c @@ -12,125 +12,106 @@ #include #ifdef __FreeBSD__ - #include - #ifndef _PATH_LOCALBASE - #define _PATH_LOCALBASE "/usr/local" - #endif +# include +# ifndef _PATH_LOCALBASE +# define _PATH_LOCALBASE "/usr/local" +# endif #elif __OpenBSD__ - #define _PATH_LOCALBASE "/usr/local" +# define _PATH_LOCALBASE "/usr/local" #elif __NetBSD__ - #define _PATH_LOCALBASE "/usr/pkg" +# define _PATH_LOCALBASE "/usr/pkg" #endif -static void getKDE(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static void getKDE(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { #ifdef _PATH_LOCALBASE ffParsePropFile(_PATH_LOCALBASE "/share/wayland-sessions/plasma.desktop", "X-KDE-PluginInfo-Version =", result); - if(result->length == 0) + if (result->length == 0) { ffParsePropFile(_PATH_LOCALBASE "/share/xsessions/plasmax11.desktop", "X-KDE-PluginInfo-Version =", result); + } #else ffParsePropFile(FASTFETCH_TARGET_DIR_USR "/share/wayland-sessions/plasma.desktop", "X-KDE-PluginInfo-Version =", result); - if(result->length == 0) + if (result->length == 0) { ffParsePropFile(FASTFETCH_TARGET_DIR_USR "/share/xsessions/plasmax11.desktop", "X-KDE-PluginInfo-Version =", result); + } #endif - if(result->length == 0) + if (result->length == 0) { ffParsePropFileData("xsessions/plasma.desktop", "X-KDE-PluginInfo-Version =", result); - if(result->length == 0) + } + if (result->length == 0) { ffParsePropFileData("xsessions/plasma5.desktop", "X-KDE-PluginInfo-Version =", result); + } - if(result->length == 0) + if (result->length == 0) { ffParsePropFileData("wayland-sessions/plasmawayland.desktop", "X-KDE-PluginInfo-Version =", result); - if(result->length == 0) + } + if (result->length == 0) { ffParsePropFileData("wayland-sessions/plasmawayland5.desktop", "X-KDE-PluginInfo-Version =", result); + } - if(result->length == 0) - { - if (ffProcessAppendStdOut(result, (char* const[]){ - "plasmashell", - "--version", - NULL - }) == NULL) // plasmashell 5.27.5 + if (result->length == 0) { + if (ffProcessAppendStdOut(result, (char* const[]) {"plasmashell", "--version", NULL}) == NULL) { // plasmashell 5.27.5 ffStrbufSubstrAfterLastC(result, ' '); + } } } -static const char* getGnomeByDbus(FF_MAYBE_UNUSED FFstrbuf* result) -{ +static const char* getGnomeByDbus(FF_MAYBE_UNUSED FFstrbuf* result) { #ifdef FF_HAVE_DBUS FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; - if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) + if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { return "ffDBusLoadData() failed"; + } ffDBusGetPropertyString(&dbus, "org.gnome.Shell", "/org/gnome/Shell", "org.gnome.Shell", "ShellVersion", result); return NULL; -#else // FF_HAVE_DBUS +#else // FF_HAVE_DBUS return "ffDBusLoadData() failed: dbus support not compiled in"; #endif // FF_HAVE_DBUS } -static void getGnome(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static void getGnome(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { getGnomeByDbus(result); - if (result->length == 0) - { - if (ffProcessAppendStdOut(result, (char* const[]){ - "gnome-shell", - "--version", - NULL - }) == NULL) // GNOME Shell 44.1 + if (result->length == 0) { + if (ffProcessAppendStdOut(result, (char* const[]) {"gnome-shell", "--version", NULL}) == NULL) { // GNOME Shell 44.1 ffStrbufSubstrAfterLastC(result, ' '); + } } } -static void getCinnamon(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static void getCinnamon(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { ffStrbufSetS(result, getenv("CINNAMON_VERSION")); - if (result->length == 0) + if (result->length == 0) { ffParsePropFileData("applications/cinnamon.desktop", "X-GNOME-Bugzilla-Version =", result); + } - if (result->length == 0) - { - if (ffProcessAppendStdOut(result, (char* const[]){ - "cinnamon", - "--version", - NULL - }) == NULL) // Cinnamon 6.2.2 + if (result->length == 0) { + if (ffProcessAppendStdOut(result, (char* const[]) {"cinnamon", "--version", NULL}) == NULL) { // Cinnamon 6.2.2 ffStrbufSubstrAfterLastC(result, ' '); + } } } -static void getMate(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static void getMate(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { FF_STRBUF_AUTO_DESTROY major = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY minor = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY micro = ffStrbufCreate(); - ffParsePropFileDataValues("mate-about/mate-version.xml", 3, (FFpropquery[]) { - {"", &major}, - {"", &minor}, - {"", µ} - }); + ffParsePropFileDataValues("mate-about/mate-version.xml", 3, (FFpropquery[]) {{"", &major}, {"", &minor}, {"", µ}}); ffParseSemver(result, &major, &minor, µ); - if(result->length == 0) - { - ffProcessAppendStdOut(result, (char* const[]){ - "mate-session", - "--version", - NULL - }); + if (result->length == 0) { + ffProcessAppendStdOut(result, (char* const[]) {"mate-session", "--version", NULL}); ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufTrim(result, ' '); } } -static const char* getXfce4ByLib(FFstrbuf* result) -{ +static const char* getXfce4ByLib(FFstrbuf* result) { #ifndef FF_DISABLE_DLOPEN const char* xfce_version_string(void); // from `xfce4/libxfce4util/xfce-misutils.h FF_LIBRARY_LOAD_MESSAGE(xfce4util, "libxfce4util" FF_LIBRARY_EXTENSION, 7); @@ -143,18 +124,12 @@ static const char* getXfce4ByLib(FFstrbuf* result) #endif } -static void getXFCE4(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static void getXFCE4(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { getXfce4ByLib(result); - if(result->length == 0) - { - //This is somewhat slow - ffProcessAppendStdOut(result, (char* const[]){ - "xfce4-session", - "--version", - NULL - }); + if (result->length == 0) { + // This is somewhat slow + ffProcessAppendStdOut(result, (char* const[]) {"xfce4-session", "--version", NULL}); ffStrbufSubstrBeforeFirstC(result, ')'); ffStrbufSubstrAfterLastC(result, ' '); @@ -162,83 +137,71 @@ static void getXFCE4(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) } } -static void getLXQt(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static void getLXQt(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { ffParsePropFileData("gconfig/lxqt.pc", "Version:", result); - if(result->length == 0) + if (result->length == 0) { ffParsePropFileData("cmake/lxqt/lxqt-config.cmake", "set ( LXQT_VERSION", result); - if(result->length == 0) + } + if (result->length == 0) { ffParsePropFileData("cmake/lxqt/lxqt-config-version.cmake", "set ( PACKAGE_VERSION", result); + } - if(result->length == 0) - { - //This is really, really, really slow. Thank you, LXQt developers - ffProcessAppendStdOut(result, (char* const[]){ - "lxqt-session", - "-v", - NULL - }); + if (result->length == 0) { + // This is really, really, really slow. Thank you, LXQt developers + ffProcessAppendStdOut(result, (char* const[]) {"lxqt-session", "-v", NULL}); - result->length = 0; //don't set '\0' byte - ffParsePropLines(result->chars , "liblxqt", result); + result->length = 0; // don't set '\0' byte + ffParsePropLines(result->chars, "liblxqt", result); } } -static void getBudgie(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static void getBudgie(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { ffParsePropFileData("budgie/budgie-version.xml", "", result); } -static void getUnity(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ - if (ffParsePropFile("/usr/bin/unity", "parser = OptionParser(version= \"%prog ", result)) +static void getUnity(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { + if (ffParsePropFile("/usr/bin/unity", "parser = OptionParser(version= \"%prog ", result)) { ffStrbufSubstrBeforeFirstC(result, '"'); + } } -static bool extractTdeVersion(const char* line, uint32_t len, void *userdata) -{ +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; + if (count == 0) { + return true; + } ffStrbufSetNS((FFstrbuf*) userdata, len, line); return false; } -static const char* getTrinity(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +static const char* getTrinity(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); const char* error = ffFindExecutableInPath("tde-config", &path); - if (error) return "Failed to find 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) + if (ffBinaryExtractStrings(path.chars, extractTdeVersion, result, strlen("R0.0.0")) == NULL) { return NULL; + } ffStrbufClear(&path); - if (ffProcessAppendStdOut(&path, (char* const[]){ - "tde-config", - "--version", - NULL - }) == NULL) - { - ffParsePropLines(path.chars , "TDE: ", result); + if (ffProcessAppendStdOut(&path, (char* const[]) {"tde-config", "--version", NULL}) == NULL) { + ffParsePropLines(path.chars, "TDE: ", result); return NULL; } return "All methods failed"; } -static const char* getCosmic(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ - if (ffProcessAppendStdOut(result, (char* const[]){ - "cosmic-comp", - "--version", - NULL - }) == NULL) { +static const char* getCosmic(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { + if (ffProcessAppendStdOut(result, (char* const[]) {"cosmic-comp", "--version", NULL}) == NULL) { // cosmic-comp 0.1.0 (git commit fa88002ba41d2edec25dd7ffdee9719fbb928fc0) ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufSubstrBeforeFirstC(result, ' '); @@ -248,31 +211,33 @@ static const char* getCosmic(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* opti return "All methods failed"; } -const char* ffDetectDEVersion(const FFstrbuf* deName, FFstrbuf* result, FFDEOptions* options) -{ - if (!instance.config.general.detectVersion) return "Disabled by config"; +const char* ffDetectDEVersion(const FFstrbuf* deName, FFstrbuf* result, FFDEOptions* options) { + if (!instance.config.general.detectVersion) { + return "Disabled by config"; + } - if (ffStrbufEqualS(deName, FF_DE_PRETTY_PLASMA)) + if (ffStrbufEqualS(deName, FF_DE_PRETTY_PLASMA)) { getKDE(result, options); - else if (ffStrbufEqualS(deName, FF_DE_PRETTY_GNOME)) + } else if (ffStrbufEqualS(deName, FF_DE_PRETTY_GNOME)) { getGnome(result, options); - else if (ffStrbufEqualS(deName, FF_DE_PRETTY_CINNAMON)) + } else if (ffStrbufEqualS(deName, FF_DE_PRETTY_CINNAMON)) { getCinnamon(result, options); - else if (ffStrbufEqualS(deName, FF_DE_PRETTY_XFCE4)) + } else if (ffStrbufEqualS(deName, FF_DE_PRETTY_XFCE4)) { getXFCE4(result, options); - else if (ffStrbufEqualS(deName, FF_DE_PRETTY_MATE)) + } else if (ffStrbufEqualS(deName, FF_DE_PRETTY_MATE)) { getMate(result, options); - else if (ffStrbufEqualS(deName, FF_DE_PRETTY_LXQT)) + } else if (ffStrbufEqualS(deName, FF_DE_PRETTY_LXQT)) { getLXQt(result, options); - else if (ffStrbufEqualS(deName, FF_DE_PRETTY_BUDGIE)) + } else if (ffStrbufEqualS(deName, FF_DE_PRETTY_BUDGIE)) { getBudgie(result, options); - else if (ffStrbufEqualS(deName, FF_DE_PRETTY_UNITY)) + } else if (ffStrbufEqualS(deName, FF_DE_PRETTY_UNITY)) { getUnity(result, options); - else if (ffStrbufEqualS(deName, "trinity")) + } else if (ffStrbufEqualS(deName, "trinity")) { getTrinity(result, options); - else if (ffStrbufEqualS(deName, "COSMIC")) + } else if (ffStrbufEqualS(deName, "COSMIC")) { getCosmic(result, options); - else + } else { return "Unsupported DE"; + } return NULL; } diff --git a/src/detection/de/de_nosupport.c b/src/detection/de/de_nosupport.c index 943e035f0..2dc3c4508 100644 --- a/src/detection/de/de_nosupport.c +++ b/src/detection/de/de_nosupport.c @@ -1,6 +1,5 @@ #include "de.h" -const char* ffDetectDEVersion(FF_MAYBE_UNUSED const FFstrbuf* deName, FF_MAYBE_UNUSED FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) -{ +const char* ffDetectDEVersion(FF_MAYBE_UNUSED const FFstrbuf* deName, FF_MAYBE_UNUSED FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/disk/disk.c b/src/detection/disk/disk.c index d63a105fe..758a5c0cb 100644 --- a/src/detection/disk/disk.c +++ b/src/detection/disk/disk.c @@ -1,31 +1,29 @@ #include "disk.h" -static int compareDisks(const FFDisk* disk1, const FFDisk* disk2) -{ +static int compareDisks(const FFDisk* disk1, const FFDisk* disk2) { return ffStrbufComp(&disk1->mountpoint, &disk2->mountpoint); } -const char* ffDetectDisks(FFDiskOptions* options, FFlist* disks) -{ +const char* ffDetectDisks(FFDiskOptions* options, FFlist* disks) { const char* error = ffDetectDisksImpl(options, disks); - if (error) return error; - if (disks->length == 0) return NULL; + if (error) { + return error; + } + if (disks->length == 0) { + return NULL; + } - //We need to sort the disks, so that we can detect, which disk a path resides on - // For example for /boot/efi/bootmgr we need to check /boot/efi before /boot - //Note that we sort alphabetically here for a better ordering when printing the list, - // so the check must be done in reverse order + // We need to sort the disks, so that we can detect, which disk a path resides on + // For example for /boot/efi/bootmgr we need to check /boot/efi before /boot + // Note that we sort alphabetically here for a better ordering when printing the list, + // so the check must be done in reverse order ffListSort(disks, (void*) compareDisks); - FF_LIST_FOR_EACH(FFDisk, disk, *disks) - { - if(disk->bytesTotal == 0) + FF_LIST_FOR_EACH (FFDisk, disk, *disks) { + if (disk->bytesTotal == 0) { disk->type |= FF_DISK_VOLUME_TYPE_UNKNOWN_BIT; - else - { - disk->bytesUsed = disk->bytesTotal - ( - options->calcType == FF_DISK_CALC_TYPE_FREE ? disk->bytesFree : disk->bytesAvailable - ); + } else { + disk->bytesUsed = disk->bytesTotal - (options->calcType == FF_DISK_CALC_TYPE_FREE ? disk->bytesFree : disk->bytesAvailable); } } @@ -33,13 +31,11 @@ const char* ffDetectDisks(FFDiskOptions* options, FFlist* disks) } #ifndef _WIN32 -#include +# include -bool ffDiskMatchesFolderPatterns(FFstrbuf* folders, const char* path, char separator) -{ +bool ffDiskMatchesFolderPatterns(FFstrbuf* folders, const char* path, char separator) { uint32_t startIndex = 0; - while(startIndex < folders->length) - { + while (startIndex < folders->length) { uint32_t sepIndex = ffStrbufNextIndexC(folders, startIndex, separator); char savedSep = folders->chars[sepIndex]; // Can be '\0' if at end @@ -48,7 +44,9 @@ bool ffDiskMatchesFolderPatterns(FFstrbuf* folders, const char* path, char separ bool matched = fnmatch(&folders->chars[startIndex], path, 0) == 0; folders->chars[sepIndex] = savedSep; - if (matched) return true; + if (matched) { + return true; + } startIndex = sepIndex + 1; } diff --git a/src/detection/disk/disk.h b/src/detection/disk/disk.h index abf688448..f8754001f 100644 --- a/src/detection/disk/disk.h +++ b/src/detection/disk/disk.h @@ -4,13 +4,12 @@ #include "modules/disk/option.h" #ifdef _WIN32 - #define FF_DISK_FOLDER_SEPARATOR ';' +# define FF_DISK_FOLDER_SEPARATOR ';' #else - #define FF_DISK_FOLDER_SEPARATOR ':' +# define FF_DISK_FOLDER_SEPARATOR ':' #endif -typedef struct FFDisk -{ +typedef struct FFDisk { FFstrbuf mountFrom; FFstrbuf mountpoint; FFstrbuf filesystem; diff --git a/src/detection/disk/disk_bsd.c b/src/detection/disk/disk_bsd.c index 8781fd107..9c4d32fad 100644 --- a/src/detection/disk/disk_bsd.c +++ b/src/detection/disk/disk_bsd.c @@ -6,168 +6,180 @@ #include #ifdef __NetBSD__ -#include -#include -#define statfs statvfs -#define f_flags f_flag -#define f_bsize f_frsize +# include +# include +# define statfs statvfs +# define f_flags f_flag +# define f_bsize f_frsize #endif #ifdef __FreeBSD__ -#if __has_include() -#include +# if __has_include() +# include -static const char* detectFsLabel(struct statfs* fs, FFDisk* disk) -{ - if (!ffStrStartsWith(fs->f_mntfromname, "/dev/")) +static const char* detectFsLabel(struct statfs* fs, FFDisk* disk) { + if (!ffStrStartsWith(fs->f_mntfromname, "/dev/")) { return "Only block devices are supported"; + } // Detect volume label in geom tree static struct gmesh geomTree; static struct gclass* cLabels; - if (!cLabels) - { - if (geomTree.lg_ident) + if (!cLabels) { + if (geomTree.lg_ident) { return "Previous geom_gettree() failed"; + } - if (geom_gettree(&geomTree) < 0) - { - geomTree.lg_ident = (void*)(intptr_t)-1; + if (geom_gettree(&geomTree) < 0) { + geomTree.lg_ident = (void*) (intptr_t) -1; return "geom_gettree() failed"; } for (cLabels = geomTree.lg_class.lh_first; cLabels && !ffStrEquals(cLabels->lg_name, "LABEL"); cLabels = cLabels->lg_class.le_next); - if (!cLabels) + if (!cLabels) { return "Class LABEL is not found"; + } } - for (struct ggeom* label = cLabels->lg_geom.lh_first; label; label = label->lg_geom.le_next) - { + for (struct ggeom* label = cLabels->lg_geom.lh_first; label; label = label->lg_geom.le_next) { struct gprovider* provider = label->lg_provider.lh_first; - if (!provider || !ffStrEquals(label->lg_name, fs->f_mntfromname + strlen("/dev/"))) continue; + if (!provider || !ffStrEquals(label->lg_name, fs->f_mntfromname + strlen("/dev/"))) { + continue; + } const char* str = strchr(provider->lg_name, '/'); ffStrbufSetS(&disk->name, str ? str + 1 : provider->lg_name); } return NULL; } -#else -static const char* detectFsLabel(FF_MAYBE_UNUSED struct statfs* fs, FF_MAYBE_UNUSED FFDisk* disk) -{ +# else +static const char* detectFsLabel(FF_MAYBE_UNUSED struct statfs* fs, FF_MAYBE_UNUSED FFDisk* disk) { return "Fastfetch was compiled without libgeom support"; } -#endif +# endif -static void detectFsInfo(struct statfs* fs, FFDisk* disk) -{ - if(ffStrbufEqualS(&disk->filesystem, "zfs")) - { +static void detectFsInfo(struct statfs* fs, FFDisk* disk) { + if (ffStrbufEqualS(&disk->filesystem, "zfs")) { disk->type = !ffStrbufStartsWithS(&disk->mountFrom, "zroot/") || ffStrbufStartsWithS(&disk->mountFrom, "zroot/ROOT/") ? FF_DISK_VOLUME_TYPE_REGULAR_BIT : FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT; - } - else if(fs->f_flags & MNT_IGNORE) + } else if (fs->f_flags & MNT_IGNORE) { disk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT; - else if(!(fs->f_flags & MNT_LOCAL)) + } else if (!(fs->f_flags & MNT_LOCAL)) { disk->type = FF_DISK_VOLUME_TYPE_EXTERNAL_BIT; - else + } else { disk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; + } detectFsLabel(fs, disk); } #elif __APPLE__ -#include "common/apple/cf_helpers.h" +# include "common/apple/cf_helpers.h" -#include -#include +# include +# include -#ifndef MAC_OS_X_VERSION_10_15 - #define MNT_REMOVABLE 0x00000200 -#endif +# ifndef MAC_OS_X_VERSION_10_15 +# define MNT_REMOVABLE 0x00000200 +# endif struct CmnAttrBuf { - uint32_t length; + uint32_t length; attrreference_t nameRef; - char nameSpace[NAME_MAX * 3 + 1]; + char nameSpace[NAME_MAX * 3 + 1]; } __attribute__((aligned(4), packed)); -void detectFsInfo(struct statfs* fs, FFDisk* disk) -{ - if(fs->f_flags & MNT_DONTBROWSE) +void detectFsInfo(struct statfs* fs, FFDisk* disk) { + if (fs->f_flags & MNT_DONTBROWSE) { disk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT; - else if(fs->f_flags & MNT_REMOVABLE || !(fs->f_flags & MNT_LOCAL)) + } else if (fs->f_flags & MNT_REMOVABLE || !(fs->f_flags & MNT_LOCAL)) { disk->type = FF_DISK_VOLUME_TYPE_EXTERNAL_BIT; - else + } else { disk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; + } struct CmnAttrBuf attrBuf; if (getattrlist(disk->mountpoint.chars, &(struct attrlist) { - .bitmapcount = ATTR_BIT_MAP_COUNT, - .commonattr = ATTR_CMN_NAME, - }, &attrBuf, sizeof(attrBuf), 0) == 0) + .bitmapcount = ATTR_BIT_MAP_COUNT, + .commonattr = ATTR_CMN_NAME, + }, + &attrBuf, + sizeof(attrBuf), + 0) == 0) { ffStrbufInitNS(&disk->name, attrBuf.nameRef.attr_length - 1 /* excluding '\0' */, attrBuf.nameSpace); + } } #else -static void detectFsInfo(struct statfs* fs, FFDisk* disk) -{ - #ifdef MNT_IGNORE - if(fs->f_flags & MNT_IGNORE) +static void detectFsInfo(struct statfs* fs, FFDisk* disk) { +# ifdef MNT_IGNORE + if (fs->f_flags & MNT_IGNORE) { disk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT; - else - #endif - if(!(fs->f_flags & MNT_LOCAL)) + } else +# endif + if (!(fs->f_flags & MNT_LOCAL)) { disk->type = FF_DISK_VOLUME_TYPE_EXTERNAL_BIT; - else + } else { disk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; + } } #endif -const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) -{ - #ifndef __NetBSD__ +const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { +#ifndef __NetBSD__ int size = getfsstat(NULL, 0, MNT_WAIT); - if(size <= 0) return "getfsstat(NULL, 0, MNT_WAIT) failed"; - #else + if (size <= 0) { + return "getfsstat(NULL, 0, MNT_WAIT) failed"; + } +#else int size = getvfsstat(NULL, 0, ST_WAIT); - if(size <= 0) return "getvfsstat(NULL, 0, ST_WAIT) failed"; - #endif + if (size <= 0) { + return "getvfsstat(NULL, 0, ST_WAIT) failed"; + } +#endif FF_AUTO_FREE struct statfs* buf = malloc(sizeof(*buf) * (unsigned) size); - #ifndef __NetBSD__ - if(getfsstat(buf, (int) (sizeof(*buf) * (unsigned) size), MNT_NOWAIT) <= 0) +#ifndef __NetBSD__ + if (getfsstat(buf, (int) (sizeof(*buf) * (unsigned) size), MNT_NOWAIT) <= 0) { return "getfsstat(buf, size, MNT_NOWAIT) failed"; - #else - if(getvfsstat(buf, sizeof(*buf) * (unsigned) size, ST_NOWAIT) <= 0) + } +#else + if (getvfsstat(buf, sizeof(*buf) * (unsigned) size, ST_NOWAIT) <= 0) { return "getvfsstat(buf, size, ST_NOWAIT) failed"; - #endif + } +#endif - for(struct statfs* fs = buf; fs < buf + size; ++fs) - { - if(__builtin_expect(options->folders.length > 0, 0)) - { - if(!ffStrbufSeparatedContainS(&options->folders, fs->f_mntonname, FF_DISK_FOLDER_SEPARATOR)) + for (struct statfs* fs = buf; fs < buf + size; ++fs) { + if (__builtin_expect(options->folders.length > 0, 0)) { + if (!ffStrbufSeparatedContainS(&options->folders, fs->f_mntonname, FF_DISK_FOLDER_SEPARATOR)) { continue; + } + } else if (!ffStrEquals(fs->f_mntonname, "/") && !ffStrStartsWith(fs->f_mntfromname, "/dev/") && !ffStrEquals(fs->f_fstypename, "zfs") && !ffStrEquals(fs->f_fstypename, "fusefs.sshfs")) { + continue; } - else if(!ffStrEquals(fs->f_mntonname, "/") && !ffStrStartsWith(fs->f_mntfromname, "/dev/") && !ffStrEquals(fs->f_fstypename, "zfs") && !ffStrEquals(fs->f_fstypename, "fusefs.sshfs")) - continue; - if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, fs->f_mntonname, FF_DISK_FOLDER_SEPARATOR)) + if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, fs->f_mntonname, FF_DISK_FOLDER_SEPARATOR)) { continue; + } - if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, fs->f_fstypename, ':')) + if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, fs->f_fstypename, ':')) { continue; + } - #ifdef __FreeBSD__ +#ifdef __FreeBSD__ // f_bavail and f_ffree are signed on FreeBSD... - if(fs->f_bavail < 0) fs->f_bavail = 0; - if(fs->f_ffree < 0) fs->f_ffree = 0; - #endif + if (fs->f_bavail < 0) { + fs->f_bavail = 0; + } + if (fs->f_ffree < 0) { + fs->f_ffree = 0; + } +#endif FFDisk* disk = ffListAdd(disks); - disk->bytesTotal = (uint64_t)fs->f_blocks * (uint64_t)fs->f_bsize; - disk->bytesFree = (uint64_t)fs->f_bfree * (uint64_t)fs->f_bsize; - disk->bytesAvailable = (uint64_t)fs->f_bavail * (uint64_t)fs->f_bsize; + disk->bytesTotal = (uint64_t) fs->f_blocks * (uint64_t) fs->f_bsize; + disk->bytesFree = (uint64_t) fs->f_bfree * (uint64_t) fs->f_bsize; + disk->bytesAvailable = (uint64_t) fs->f_bavail * (uint64_t) fs->f_bsize; disk->bytesUsed = 0; // To be filled in ./disk.c disk->filesTotal = (uint32_t) fs->f_files; @@ -182,17 +194,19 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) detectFsInfo(fs, disk); - if(fs->f_flags & MNT_RDONLY) + if (fs->f_flags & MNT_RDONLY) { disk->type |= FF_DISK_VOLUME_TYPE_READONLY_BIT; + } - #ifdef __OpenBSD__ - #define st_birthtimespec __st_birthtim - #endif - #ifndef __DragonFly__ +#ifdef __OpenBSD__ +# define st_birthtimespec __st_birthtim +#endif +#ifndef __DragonFly__ struct stat st; - if(stat(fs->f_mntonname, &st) == 0 && st.st_birthtimespec.tv_sec > 0) - disk->createTime = (uint64_t)(((uint64_t) st.st_birthtimespec.tv_sec * 1000) + ((uint64_t) st.st_birthtimespec.tv_nsec / 1000000)); - #endif + if (stat(fs->f_mntonname, &st) == 0 && st.st_birthtimespec.tv_sec > 0) { + disk->createTime = (uint64_t) (((uint64_t) st.st_birthtimespec.tv_sec * 1000) + ((uint64_t) st.st_birthtimespec.tv_nsec / 1000000)); + } +#endif } return NULL; diff --git a/src/detection/disk/disk_haiku.cpp b/src/detection/disk/disk_haiku.cpp index 267e75845..b6b37d91a 100644 --- a/src/detection/disk/disk_haiku.cpp +++ b/src/detection/disk/disk_haiku.cpp @@ -1,5 +1,4 @@ -extern "C" -{ +extern "C" { #include "disk.h" #include "common/stringUtils.h" } @@ -7,36 +6,40 @@ extern "C" #include #include -const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) -{ +const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { int32 pos = 0; - for (dev_t dev; (dev = next_dev(&pos)) >= B_OK;) - { + for (dev_t dev; (dev = next_dev(&pos)) >= B_OK;) { fs_info fs; - if (fs_stat_dev(dev, &fs) < 0) continue; + if (fs_stat_dev(dev, &fs) < 0) { + continue; + } node_ref node(fs.dev, fs.root); BDirectory dir(&node); BPath path(&dir); - if (path.InitCheck() != B_OK) continue; - - if (__builtin_expect(options->folders.length, 0)) - { - if (!ffStrbufSeparatedContainS(&options->folders, path.Path(), FF_DISK_FOLDER_SEPARATOR)) - continue; + if (path.InitCheck() != B_OK) { + continue; } - if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, path.Path(), FF_DISK_FOLDER_SEPARATOR)) - continue; + if (__builtin_expect(options->folders.length, 0)) { + if (!ffStrbufSeparatedContainS(&options->folders, path.Path(), FF_DISK_FOLDER_SEPARATOR)) { + continue; + } + } - if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, fs.fsh_name, ':')) + if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, path.Path(), FF_DISK_FOLDER_SEPARATOR)) { continue; + } + + if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, fs.fsh_name, ':')) { + continue; + } FFDisk* disk = (FFDisk*) ffListAdd(disks); - disk->bytesTotal = (uint64_t)fs.total_blocks * (uint64_t) fs.block_size; - disk->bytesFree = (uint64_t)fs.free_blocks * (uint64_t) fs.block_size; + disk->bytesTotal = (uint64_t) fs.total_blocks * (uint64_t) fs.block_size; + disk->bytesFree = (uint64_t) fs.free_blocks * (uint64_t) fs.block_size; disk->bytesAvailable = disk->bytesFree; disk->bytesUsed = 0; // To be filled in ./disk.c @@ -48,18 +51,24 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) ffStrbufInitS(&disk->filesystem, fs.fsh_name); ffStrbufInitS(&disk->name, fs.volume_name); disk->type = FF_DISK_VOLUME_TYPE_NONE; - if (!(fs.flags & B_FS_IS_PERSISTENT)) + if (!(fs.flags & B_FS_IS_PERSISTENT)) { disk->type = (FFDiskVolumeType) (disk->type | FF_DISK_VOLUME_TYPE_HIDDEN_BIT); - if (fs.flags & B_FS_IS_READONLY) + } + if (fs.flags & B_FS_IS_READONLY) { disk->type = (FFDiskVolumeType) (disk->type | FF_DISK_VOLUME_TYPE_READONLY_BIT); - if (fs.flags & B_FS_IS_REMOVABLE) + } + if (fs.flags & B_FS_IS_REMOVABLE) { disk->type = (FFDiskVolumeType) (disk->type | FF_DISK_VOLUME_TYPE_EXTERNAL_BIT); - if (disk->type == FF_DISK_VOLUME_TYPE_NONE) disk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; + } + if (disk->type == FF_DISK_VOLUME_TYPE_NONE) { + disk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; + } disk->createTime = 0; time_t crTime; - if (dir.GetCreationTime(&crTime) == B_OK) + if (dir.GetCreationTime(&crTime) == B_OK) { disk->createTime = (uint64_t) crTime * 1000; + } } return NULL; } diff --git a/src/detection/disk/disk_linux.c b/src/detection/disk/disk_linux.c index 70474710f..c256527ab 100644 --- a/src/detection/disk/disk_linux.c +++ b/src/detection/disk/disk_linux.c @@ -11,98 +11,113 @@ #include #if defined(STATX_BTIME) && !defined(__ANDROID__) - #include +# include #endif #ifdef __USE_LARGEFILE64 - #define stat stat64 - #define statvfs statvfs64 - #define dirent dirent64 - #define readdir readdir64 +# define stat stat64 +# define statvfs statvfs64 +# define dirent dirent64 +# define readdir readdir64 #endif -static bool isPhysicalDevice(const struct mntent* device) -{ - #ifndef __ANDROID__ //On Android, `/dev` is not accessible, so that the following checks always fail +static bool isPhysicalDevice(const struct mntent* device) { +#ifndef __ANDROID__ // On Android, `/dev` is not accessible, so that the following checks always fail - //Always show the root path - if(ffStrEquals(device->mnt_dir, "/")) + // Always show the root path + if (ffStrEquals(device->mnt_dir, "/")) { return true; + } - if(ffStrEquals(device->mnt_fsname, "none")) + if (ffStrEquals(device->mnt_fsname, "none")) { return false; + } - //DrvFs is a filesystem plugin to WSL that was designed to support interop between WSL and the Windows filesystem. - if(ffStrEquals(device->mnt_type, "9p")) + // DrvFs is a filesystem plugin to WSL that was designed to support interop between WSL and the Windows filesystem. + if (ffStrEquals(device->mnt_type, "9p")) { return ffStrContains(device->mnt_opts, "aname=drvfs"); + } - //ZFS pool - if(ffStrEquals(device->mnt_type, "zfs")) + // ZFS pool + if (ffStrEquals(device->mnt_type, "zfs")) { return true; + } - //sshfs - if(ffStrEquals(device->mnt_type, "fuse.sshfs")) + // sshfs + if (ffStrEquals(device->mnt_type, "fuse.sshfs")) { return true; + } - //Pseudo filesystems don't have a device in /dev - if(!ffStrStartsWith(device->mnt_fsname, "/dev/")) + // Pseudo filesystems don't have a device in /dev + if (!ffStrStartsWith(device->mnt_fsname, "/dev/")) { return false; + } - //#731 - if(ffStrEquals(device->mnt_type, "bcachefs")) + // #731 + if (ffStrEquals(device->mnt_type, "bcachefs")) { return true; + } - if( - ffStrStartsWith(device->mnt_fsname + 5, "loop") || //Ignore loop devices - ffStrStartsWith(device->mnt_fsname + 5, "ram") || //Ignore ram devices - ffStrStartsWith(device->mnt_fsname + 5, "fd") //Ignore fd devices - ) return false; - - if (ffStrStartsWith(device->mnt_dir, "/bedrock/")) // Ignore Bedrock Linux subvolumes + if ( + ffStrStartsWith(device->mnt_fsname + 5, "loop") || // Ignore loop devices + ffStrStartsWith(device->mnt_fsname + 5, "ram") || // Ignore ram devices + ffStrStartsWith(device->mnt_fsname + 5, "fd") // Ignore fd devices + ) { return false; + } + + if (ffStrStartsWith(device->mnt_dir, "/bedrock/")) { // Ignore Bedrock Linux subvolumes + return false; + } struct stat deviceStat; - if(stat(device->mnt_fsname, &deviceStat) != 0) + if (stat(device->mnt_fsname, &deviceStat) != 0) { return false; + } - //Ignore all devices that are not block devices - if(!S_ISBLK(deviceStat.st_mode)) + // Ignore all devices that are not block devices + if (!S_ISBLK(deviceStat.st_mode)) { return false; + } - #else +#else - //Pseudo filesystems don't have a device in /dev - if(!ffStrStartsWith(device->mnt_fsname, "/dev/")) + // Pseudo filesystems don't have a device in /dev + if (!ffStrStartsWith(device->mnt_fsname, "/dev/")) { return false; + } - if( - ffStrStartsWith(device->mnt_fsname + 5, "loop") || //Ignore loop devices - ffStrStartsWith(device->mnt_fsname + 5, "ram") || //Ignore ram devices - ffStrStartsWith(device->mnt_fsname + 5, "fd") //Ignore fd devices - ) return false; + if ( + ffStrStartsWith(device->mnt_fsname + 5, "loop") || // Ignore loop devices + ffStrStartsWith(device->mnt_fsname + 5, "ram") || // Ignore ram devices + ffStrStartsWith(device->mnt_fsname + 5, "fd") // Ignore fd devices + ) { + return false; + } // https://source.android.com/docs/core/ota/apex?hl=zh-cn - if(ffStrStartsWith(device->mnt_dir, "/apex/")) + if (ffStrStartsWith(device->mnt_dir, "/apex/")) { return false; + } - #endif // __ANDROID__ +#endif // __ANDROID__ return true; } -static void detectNameFromPath(FFDisk* disk, const struct stat* deviceStat, FFstrbuf* basePath) -{ +static void detectNameFromPath(FFDisk* disk, const struct stat* deviceStat, FFstrbuf* basePath) { FF_AUTO_CLOSE_DIR DIR* dir = opendir(basePath->chars); - if(dir == NULL) + if (dir == NULL) { return; + } uint32_t basePathLength = basePath->length; struct dirent* entry; - while((entry = readdir(dir)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dir)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } ffStrbufAppendS(basePath, entry->d_name); @@ -111,205 +126,208 @@ static void detectNameFromPath(FFDisk* disk, const struct stat* deviceStat, FFst ffStrbufSubstrBefore(basePath, basePathLength); - if(!ret || deviceStat->st_ino != entryStat.st_ino) + if (!ret || deviceStat->st_ino != entryStat.st_ino) { continue; + } ffStrbufAppendS(&disk->name, entry->d_name); break; } } -static void detectName(FFDisk* disk) -{ +static void detectName(FFDisk* disk) { struct stat deviceStat; - if(stat(disk->mountFrom.chars, &deviceStat) != 0) + if (stat(disk->mountFrom.chars, &deviceStat) != 0) { return; + } FF_STRBUF_AUTO_DESTROY basePath = ffStrbufCreate(); - //Try label first + // Try label first ffStrbufSetS(&basePath, "/dev/disk/by-label/"); detectNameFromPath(disk, &deviceStat, &basePath); - if(disk->name.length == 0) - { - //Try partlabel second + if (disk->name.length == 0) { + // Try partlabel second ffStrbufSetS(&basePath, "/dev/disk/by-partlabel/"); detectNameFromPath(disk, &deviceStat, &basePath); } - if (disk->name.length == 0) return; + if (disk->name.length == 0) { + return; + } ffStrbufDecodeHexEscapeSequences(&disk->name); } #ifdef __ANDROID__ -static void detectType(FF_MAYBE_UNUSED const FFlist* disks, FFDisk* currentDisk, FF_MAYBE_UNUSED struct mntent* device) -{ - if(ffStrbufEqualS(¤tDisk->mountpoint, "/") || ffStrbufEqualS(¤tDisk->mountpoint, "/storage/emulated")) +static void detectType(FF_MAYBE_UNUSED const FFlist* disks, FFDisk* currentDisk, FF_MAYBE_UNUSED struct mntent* device) { + if (ffStrbufEqualS(¤tDisk->mountpoint, "/") || ffStrbufEqualS(¤tDisk->mountpoint, "/storage/emulated")) { currentDisk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; - else if(ffStrbufStartsWithS(¤tDisk->mountpoint, "/mnt/media_rw/")) + } else if (ffStrbufStartsWithS(¤tDisk->mountpoint, "/mnt/media_rw/")) { currentDisk->type = FF_DISK_VOLUME_TYPE_EXTERNAL_BIT; - else + } else { currentDisk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT; + } } #else -static bool isSubvolume(const FFlist* disks, FFDisk* currentDisk) -{ - if(ffStrbufEqualS(¤tDisk->mountFrom, "drvfs")) // WSL Windows drives +static bool isSubvolume(const FFlist* disks, FFDisk* currentDisk) { + if (ffStrbufEqualS(¤tDisk->mountFrom, "drvfs")) { // WSL Windows drives return false; + } - if(ffStrbufEqualS(¤tDisk->filesystem, "zfs")) - { - //ZFS subvolumes + if (ffStrbufEqualS(¤tDisk->filesystem, "zfs")) { + // ZFS subvolumes uint32_t index = ffStrbufFirstIndexC(¤tDisk->mountFrom, '/'); - if (index == currentDisk->mountFrom.length) + if (index == currentDisk->mountFrom.length) { return false; + } FF_STRBUF_AUTO_DESTROY zpoolName = ffStrbufCreateNS(index, currentDisk->mountFrom.chars); - for(uint32_t i = 0; i < disks->length - 1; i++) - { + for (uint32_t i = 0; i < disks->length - 1; i++) { const FFDisk* otherDevice = FF_LIST_GET(FFDisk, *disks, i); - if(ffStrbufEqualS(&otherDevice->filesystem, "zfs") && ffStrbufStartsWith(&otherDevice->mountFrom, &zpoolName)) + if (ffStrbufEqualS(&otherDevice->filesystem, "zfs") && ffStrbufStartsWith(&otherDevice->mountFrom, &zpoolName)) { return true; + } } return false; - } - else - { - //Filter all disks which device was already found. This catches BTRFS subvolumes. - for(uint32_t i = 0; i < disks->length - 1; i++) - { + } else { + // Filter all disks which device was already found. This catches BTRFS subvolumes. + for (uint32_t i = 0; i < disks->length - 1; i++) { const FFDisk* otherDevice = FF_LIST_GET(FFDisk, *disks, i); - if(ffStrbufEqual(¤tDisk->mountFrom, &otherDevice->mountFrom)) + if (ffStrbufEqual(¤tDisk->mountFrom, &otherDevice->mountFrom)) { return true; + } } } return false; } -static bool isRemovable(FFDisk* currentDisk) -{ - if (!ffStrbufStartsWithS(¤tDisk->mountFrom, "/dev/")) +static bool isRemovable(FFDisk* currentDisk) { + if (!ffStrbufStartsWithS(¤tDisk->mountFrom, "/dev/")) { return false; + } char sysBlockPartition[64]; snprintf(sysBlockPartition, ARRAY_SIZE(sysBlockPartition), "/sys/class/block/%s", currentDisk->mountFrom.chars + strlen("/dev/")); char sysBlockVolume[PATH_MAX]; // /sys/devices/pci0000:00/0000:00:14.0/usb4/4-3/4-3:1.0/host0/target0:0:0/0:0:0:0/block/sda/sda1 - if (realpath(sysBlockPartition, sysBlockVolume) == NULL) + if (realpath(sysBlockPartition, sysBlockVolume) == NULL) { return false; + } char* lastSlash = strrchr(sysBlockVolume, '/'); - if (lastSlash == NULL) + if (lastSlash == NULL) { return false; + } strcpy(lastSlash + 1, "removable"); char removableChar = '0'; return ffReadFileData(sysBlockVolume, 1, &removableChar) > 0 && removableChar == '1'; } -static void detectType(const FFlist* disks, FFDisk* currentDisk, struct mntent* device) -{ - if(hasmntopt(device, "x-gvfs-hide") || hasmntopt(device, "hidden")) +static void detectType(const FFlist* disks, FFDisk* currentDisk, struct mntent* device) { + if (hasmntopt(device, "x-gvfs-hide") || hasmntopt(device, "hidden")) { currentDisk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT; - else if(isSubvolume(disks, currentDisk)) + } else if (isSubvolume(disks, currentDisk)) { currentDisk->type = FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT; - else if(isRemovable(currentDisk)) + } else if (isRemovable(currentDisk)) { currentDisk->type = FF_DISK_VOLUME_TYPE_EXTERNAL_BIT; - else + } else { currentDisk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; - if (hasmntopt(device, MNTOPT_RO)) + } + if (hasmntopt(device, MNTOPT_RO)) { currentDisk->type |= FF_DISK_VOLUME_TYPE_READONLY_BIT; + } } #endif -static void detectStats(FFDisk* disk) -{ +static void detectStats(FFDisk* disk) { struct statvfs fs; - if(statvfs(disk->mountpoint.chars, &fs) != 0) - memset(&fs, 0, sizeof(fs)); //Set all values to 0, so our values get initialized to 0 too + if (statvfs(disk->mountpoint.chars, &fs) != 0) { + memset(&fs, 0, sizeof(fs)); // Set all values to 0, so our values get initialized to 0 too + } disk->bytesTotal = fs.f_blocks * (uint64_t) fs.f_frsize; disk->bytesFree = fs.f_bfree * (uint64_t) fs.f_frsize; disk->bytesAvailable = fs.f_bavail * (uint64_t) fs.f_frsize; disk->bytesUsed = 0; // To be filled in ./disk.c - if (fs.f_files >= fs.f_ffree) - { + if (fs.f_files >= fs.f_ffree) { disk->filesTotal = (uint32_t) fs.f_files; disk->filesUsed = (uint32_t) (disk->filesTotal - fs.f_ffree); - } - else - { + } else { // Windows filesystem in WSL disk->filesTotal = disk->filesUsed = 0; } disk->createTime = 0; - #ifdef SYS_statx +#ifdef SYS_statx struct statx stx; - if (syscall(SYS_statx, 0, disk->mountpoint.chars, 0, STATX_BTIME, &stx) == 0 && (stx.stx_mask & STATX_BTIME) && stx.stx_btime.tv_sec > 685065600 /*birth of Linux*/) - disk->createTime = (uint64_t)((stx.stx_btime.tv_sec * 1000) + (stx.stx_btime.tv_nsec / 1000000)); - #endif + if (syscall(SYS_statx, 0, disk->mountpoint.chars, 0, STATX_BTIME, &stx) == 0 && (stx.stx_mask & STATX_BTIME) && stx.stx_btime.tv_sec > 685065600 /*birth of Linux*/) { + disk->createTime = (uint64_t) ((stx.stx_btime.tv_sec * 1000) + (stx.stx_btime.tv_nsec / 1000000)); + } +#endif - #ifdef __ANDROID__ // hasmntopt requires a higher Android API level - if(fs.f_flag & ST_RDONLY) +#ifdef __ANDROID__ // hasmntopt requires a higher Android API level + if (fs.f_flag & ST_RDONLY) { disk->type |= FF_DISK_VOLUME_TYPE_READONLY_BIT; - #endif + } +#endif } -const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) -{ +const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { FILE* mountsFile = setmntent("/proc/mounts", "r"); - if(mountsFile == NULL) + if (mountsFile == NULL) { return "setmntent(\"/proc/mounts\", \"r\") == NULL"; + } struct mntent* device; - while((device = getmntent(mountsFile))) - { - if (__builtin_expect(options->folders.length > 0, false)) - { - if (!ffStrbufSeparatedContainS(&options->folders, device->mnt_dir, FF_DISK_FOLDER_SEPARATOR)) + while ((device = getmntent(mountsFile))) { + if (__builtin_expect(options->folders.length > 0, false)) { + if (!ffStrbufSeparatedContainS(&options->folders, device->mnt_dir, FF_DISK_FOLDER_SEPARATOR)) { continue; + } + } else if (!isPhysicalDevice(device)) { + continue; } - else if(!isPhysicalDevice(device)) - continue; - if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, device->mnt_dir, FF_DISK_FOLDER_SEPARATOR)) + if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, device->mnt_dir, FF_DISK_FOLDER_SEPARATOR)) { continue; + } - if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, device->mnt_type, ':')) + if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, device->mnt_type, ':')) { continue; + } - //We have a valid device, add it to the list + // We have a valid device, add it to the list FFDisk* disk = ffListAdd(disks); disk->type = FF_DISK_VOLUME_TYPE_NONE; - //detect mountFrom + // detect mountFrom ffStrbufInitS(&disk->mountFrom, device->mnt_fsname); - //detect mountpoint + // detect mountpoint ffStrbufInitS(&disk->mountpoint, device->mnt_dir); - //detect filesystem + // detect filesystem ffStrbufInitS(&disk->filesystem, device->mnt_type); - //detect name + // detect name ffStrbufInit(&disk->name); detectName(disk); // Also detects external devices - //detect type + // detect type detectType(disks, disk, device); - //Detects stats + // Detects stats detectStats(disk); } diff --git a/src/detection/disk/disk_nosupport.c b/src/detection/disk/disk_nosupport.c index c680c549e..b2c4ac9b2 100644 --- a/src/detection/disk/disk_nosupport.c +++ b/src/detection/disk/disk_nosupport.c @@ -1,6 +1,5 @@ #include "disk.h" -const char* ffDetectDisksImpl(FF_MAYBE_UNUSED FFDiskOptions* options, FF_MAYBE_UNUSED FFlist* disks) -{ +const char* ffDetectDisksImpl(FF_MAYBE_UNUSED FFDiskOptions* options, FF_MAYBE_UNUSED FFlist* disks) { return "Not supported on this platform"; } diff --git a/src/detection/disk/disk_sunos.c b/src/detection/disk/disk_sunos.c index aa201c6c7..cf3be7c99 100644 --- a/src/detection/disk/disk_sunos.c +++ b/src/detection/disk/disk_sunos.c @@ -8,85 +8,88 @@ #include #include -static bool isPhysicalDevice(const struct mnttab* device) -{ - //Always show the root path - if(ffStrEquals(device->mnt_mountp, "/")) +static bool isPhysicalDevice(const struct mnttab* device) { + // Always show the root path + if (ffStrEquals(device->mnt_mountp, "/")) { return true; + } - if(ffStrEquals(device->mnt_special, "none")) + if (ffStrEquals(device->mnt_special, "none")) { return false; + } - //ZFS pool - if(ffStrEquals(device->mnt_fstype, "zfs")) + // ZFS pool + if (ffStrEquals(device->mnt_fstype, "zfs")) { return true; + } - //Pseudo filesystems don't have a device in /dev - if(!ffStrStartsWith(device->mnt_special, "/dev/")) + // Pseudo filesystems don't have a device in /dev + if (!ffStrStartsWith(device->mnt_special, "/dev/")) { return false; + } struct stat deviceStat; - if(stat(device->mnt_special, &deviceStat) != 0) + if (stat(device->mnt_special, &deviceStat) != 0) { return false; + } - //Ignore all devices that are not block devices - if(!S_ISBLK(deviceStat.st_mode)) + // Ignore all devices that are not block devices + if (!S_ISBLK(deviceStat.st_mode)) { return false; + } return true; } -static bool isSubvolume(const FFlist* disks, FFDisk* currentDisk) -{ - if(ffStrbufEqualS(¤tDisk->filesystem, "zfs")) - { - //ZFS subvolumes +static bool isSubvolume(const FFlist* disks, FFDisk* currentDisk) { + if (ffStrbufEqualS(¤tDisk->filesystem, "zfs")) { + // ZFS subvolumes uint32_t index = ffStrbufFirstIndexC(¤tDisk->mountFrom, '/'); - if (index == currentDisk->mountFrom.length) + if (index == currentDisk->mountFrom.length) { return false; + } FF_STRBUF_AUTO_DESTROY zpoolName = ffStrbufCreateNS(index, currentDisk->mountFrom.chars); - for(uint32_t i = 0; i < disks->length - 1; i++) - { + for (uint32_t i = 0; i < disks->length - 1; i++) { const FFDisk* otherDevice = FF_LIST_GET(FFDisk, *disks, i); - if(ffStrbufEqualS(&otherDevice->filesystem, "zfs") && ffStrbufStartsWith(&otherDevice->mountFrom, &zpoolName)) + if (ffStrbufEqualS(&otherDevice->filesystem, "zfs") && ffStrbufStartsWith(&otherDevice->mountFrom, &zpoolName)) { return true; + } } return false; - } - else - { - //Filter all disks which device was already found. This catches BTRFS subvolumes. - for(uint32_t i = 0; i < disks->length - 1; i++) - { + } else { + // Filter all disks which device was already found. This catches BTRFS subvolumes. + for (uint32_t i = 0; i < disks->length - 1; i++) { const FFDisk* otherDevice = FF_LIST_GET(FFDisk, *disks, i); - if(ffStrbufEqual(¤tDisk->mountFrom, &otherDevice->mountFrom)) + if (ffStrbufEqual(¤tDisk->mountFrom, &otherDevice->mountFrom)) { return true; + } } } return false; } -static void detectType(const FFlist* disks, FFDisk* currentDisk, struct mnttab* device) -{ - if(hasmntopt(device, MNTOPT_NOBROWSE)) +static void detectType(const FFlist* disks, FFDisk* currentDisk, struct mnttab* device) { + if (hasmntopt(device, MNTOPT_NOBROWSE)) { currentDisk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT; - else if(isSubvolume(disks, currentDisk)) + } else if (isSubvolume(disks, currentDisk)) { currentDisk->type = FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT; - else + } else { currentDisk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; - if (hasmntopt(device, MNTOPT_RO)) + } + if (hasmntopt(device, MNTOPT_RO)) { currentDisk->type |= FF_DISK_VOLUME_TYPE_READONLY_BIT; + } } -static void detectStats(FFDisk* disk) -{ +static void detectStats(FFDisk* disk) { struct statvfs fs; - if(statvfs(disk->mountpoint.chars, &fs) != 0) + if (statvfs(disk->mountpoint.chars, &fs) != 0) { memset(&fs, 0, sizeof(fs)); + } disk->bytesTotal = fs.f_blocks * fs.f_frsize; disk->bytesFree = fs.f_bfree * fs.f_frsize; @@ -101,31 +104,32 @@ static void detectStats(FFDisk* disk) disk->createTime = 0; } -const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) -{ +const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { FF_AUTO_CLOSE_FILE FILE* mountsFile = fopen(MNTTAB, "r"); - if(mountsFile == NULL) + if (mountsFile == NULL) { return "fopen(\"" MNTTAB "\", \"r\") == NULL"; + } struct mnttab device; - while (getmntent(mountsFile, &device) == 0) - { - if (__builtin_expect(options->folders.length, 0)) - { - if (!ffStrbufSeparatedContainS(&options->folders, device.mnt_mountp, FF_DISK_FOLDER_SEPARATOR)) + while (getmntent(mountsFile, &device) == 0) { + if (__builtin_expect(options->folders.length, 0)) { + if (!ffStrbufSeparatedContainS(&options->folders, device.mnt_mountp, FF_DISK_FOLDER_SEPARATOR)) { continue; + } + } else if (!isPhysicalDevice(&device)) { + continue; } - else if(!isPhysicalDevice(&device)) - continue; - if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, device.mnt_mountp, FF_DISK_FOLDER_SEPARATOR)) + if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, device.mnt_mountp, FF_DISK_FOLDER_SEPARATOR)) { continue; + } - if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, device.mnt_fstype, ':')) + if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, device.mnt_fstype, ':')) { continue; + } - //We have a valid device, add it to the list + // We have a valid device, add it to the list FFDisk* disk = ffListAdd(disks); disk->type = FF_DISK_VOLUME_TYPE_NONE; ffStrbufInitS(&disk->mountFrom, device.mnt_special); diff --git a/src/detection/disk/disk_windows.c b/src/detection/disk/disk_windows.c index 08217be44..89c78d20b 100644 --- a/src/detection/disk/disk_windows.c +++ b/src/detection/disk/disk_windows.c @@ -9,16 +9,15 @@ #include #include -const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) -{ +const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { PROCESS_DEVICEMAP_INFORMATION_EX info = {}; ULONG size = 0; - if(!NT_SUCCESS(NtQueryInformationProcess(NtCurrentProcess(), ProcessDeviceMap, &info, sizeof(info), &size))) + if (!NT_SUCCESS(NtQueryInformationProcess(NtCurrentProcess(), ProcessDeviceMap, &info, sizeof(info), &size))) { return "NtQueryInformationProcess(ProcessDeviceMap) failed"; + } // For cross-platform portability; used by `presets/examples/13.jsonc` - if (options->folders.length == 1 && options->folders.chars[0] == '/') - { + if (options->folders.length == 1 && options->folders.chars[0] == '/') { options->folders.chars[0] = (char) SharedUserData->NtSystemRoot[0]; ffStrbufAppendS(&options->folders, ":\\"); } @@ -26,29 +25,31 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) wchar_t mountpointW[] = L"X:\\"; char mountpointA[] = "X:\\"; - for (wchar_t i = L'A'; i <= L'Z'; i++) - { - if (!(info.Query.DriveMap & (1 << (i - L'A')))) + for (wchar_t i = L'A'; i <= L'Z'; i++) { + if (!(info.Query.DriveMap & (1 << (i - L'A')))) { continue; + } mountpointW[0] = i; mountpointA[0] = (char) i; UINT driveType = info.Query.DriveType[i - L'A']; - if (__builtin_expect((long) options->folders.length, 0)) - { - if (!ffStrbufSeparatedContainNS(&options->folders, 3, mountpointA, FF_DISK_FOLDER_SEPARATOR)) + if (__builtin_expect((long) options->folders.length, 0)) { + if (!ffStrbufSeparatedContainNS(&options->folders, 3, mountpointA, FF_DISK_FOLDER_SEPARATOR)) { continue; + } + } else if (driveType == DRIVE_NO_ROOT_DIR) { + continue; } - else if(driveType == DRIVE_NO_ROOT_DIR) - continue; - if (options->hideFolders.length && ffStrbufSeparatedContainNS(&options->hideFolders, 3, mountpointA, FF_DISK_FOLDER_SEPARATOR)) + if (options->hideFolders.length && ffStrbufSeparatedContainNS(&options->hideFolders, 3, mountpointA, FF_DISK_FOLDER_SEPARATOR)) { continue; + } FF_AUTO_CLOSE_FD HANDLE handle = CreateFileW(mountpointW, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (handle == INVALID_HANDLE_VALUE) + if (handle == INVALID_HANDLE_VALUE) { continue; + } IO_STATUS_BLOCK iosb; @@ -58,11 +59,11 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) : NULL; FF_STRBUF_AUTO_DESTROY diskFileSystemBuf = ffStrbufCreate(); - if (fsAttr) - { + if (fsAttr) { ffStrbufSetNWS(&diskFileSystemBuf, fsAttr->FileSystemNameLength / sizeof(WCHAR), fsAttr->FileSystemName); - if (options->hideFS.length && ffStrbufSeparatedContain(&options->hideFS, &diskFileSystemBuf, ':')) + if (options->hideFS.length && ffStrbufSeparatedContain(&options->hideFS, &diskFileSystemBuf, ':')) { continue; + } } FFDisk* disk = ffListAdd(disks); @@ -81,14 +82,15 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) disk->type = driveType == DRIVE_REMOVABLE || driveType == DRIVE_REMOTE || driveType == DRIVE_CDROM ? FF_DISK_VOLUME_TYPE_EXTERNAL_BIT : driveType == DRIVE_FIXED - ? FF_DISK_VOLUME_TYPE_REGULAR_BIT - : FF_DISK_VOLUME_TYPE_HIDDEN_BIT; + ? FF_DISK_VOLUME_TYPE_REGULAR_BIT + : FF_DISK_VOLUME_TYPE_HIDDEN_BIT; { wchar_t volumeName[MAX_PATH + 1]; mountpointW[2] = L'\0'; - if(QueryDosDeviceW(mountpointW, volumeName, ARRAY_SIZE(volumeName))) + if (QueryDosDeviceW(mountpointW, volumeName, ARRAY_SIZE(volumeName))) { ffStrbufSetWS(&disk->mountFrom, volumeName); + } mountpointW[2] = L'\\'; } @@ -97,24 +99,24 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) ? (FILE_FS_VOLUME_INFORMATION*) bufFsVolume : NULL; - if (fsVolume) - { - if (fsVolume->VolumeLabelLength > 0) + if (fsVolume) { + if (fsVolume->VolumeLabelLength > 0) { ffStrbufSetNWS(&disk->name, fsVolume->VolumeLabelLength / sizeof(WCHAR), fsVolume->VolumeLabel); - if (fsVolume->VolumeCreationTime.QuadPart) + } + if (fsVolume->VolumeCreationTime.QuadPart) { disk->createTime = ffFileTimeToUnixMs((uint64_t) fsVolume->VolumeCreationTime.QuadPart); + } } - if (fsAttr) - { + if (fsAttr) { ffStrbufInitMove(&disk->filesystem, &diskFileSystemBuf); - if(fsAttr->FileSystemAttributes & FILE_READ_ONLY_VOLUME) + if (fsAttr->FileSystemAttributes & FILE_READ_ONLY_VOLUME) { disk->type |= FF_DISK_VOLUME_TYPE_READONLY_BIT; + } } FILE_FS_FULL_SIZE_INFORMATION fsFullSize; - if (NT_SUCCESS(NtQueryVolumeInformationFile(handle, &iosb, &fsFullSize, sizeof(fsFullSize), FileFsFullSizeInformation))) - { + if (NT_SUCCESS(NtQueryVolumeInformationFile(handle, &iosb, &fsFullSize, sizeof(fsFullSize), FileFsFullSizeInformation))) { uint64_t units = fsFullSize.BytesPerSector * fsFullSize.SectorsPerAllocationUnit; disk->bytesTotal = (uint64_t) fsFullSize.TotalAllocationUnits.QuadPart * units; disk->bytesFree = (uint64_t) fsFullSize.ActualAvailableAllocationUnits.QuadPart * units; diff --git a/src/detection/diskio/diskio.c b/src/detection/diskio/diskio.c index 00f7bc244..cbf25e19e 100644 --- a/src/detection/diskio/diskio.c +++ b/src/detection/diskio/diskio.c @@ -7,65 +7,68 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options); static FFlist ioCounters1; static uint64_t time1; -void ffPrepareDiskIO(FFDiskIOOptions* options) -{ - if (options->detectTotal) return; +void ffPrepareDiskIO(FFDiskIOOptions* options) { + if (options->detectTotal) { + return; + } - if (time1 != 0) return; // Already prepared + if (time1 != 0) { + return; // Already prepared + } ffListInit(&ioCounters1, sizeof(FFDiskIOResult)); ffDiskIOGetIoCounters(&ioCounters1, options); time1 = ffTimeGetNow(); } -const char* ffDetectDiskIO(FFlist* result, FFDiskIOOptions* options) -{ +const char* ffDetectDiskIO(FFlist* result, FFDiskIOOptions* options) { const char* error = NULL; - if (options->detectTotal) - { + if (options->detectTotal) { error = ffDiskIOGetIoCounters(result, options); - if (error) + if (error) { return error; + } return NULL; } - if (time1 == 0) - { + if (time1 == 0) { ffListInit(&ioCounters1, sizeof(FFDiskIOResult)); error = ffDiskIOGetIoCounters(&ioCounters1, options); - if (error) + if (error) { return error; + } time1 = ffTimeGetNow(); } - if (ioCounters1.length == 0) + if (ioCounters1.length == 0) { return "No physical disk found"; + } uint64_t time2 = ffTimeGetNow(); - while (time2 - time1 < options->waitTime) - { + while (time2 - time1 < options->waitTime) { ffTimeSleep((uint32_t) (options->waitTime - (time2 - time1))); time2 = ffTimeGetNow(); } error = ffDiskIOGetIoCounters(result, options); - if (error) + if (error) { return error; + } - if (result->length != ioCounters1.length) + if (result->length != ioCounters1.length) { return "Different number of physical disks. Hardware change?"; + } - for (uint32_t i = 0; i < result->length; ++i) - { + for (uint32_t i = 0; i < result->length; ++i) { FFDiskIOResult* icPrev = FF_LIST_GET(FFDiskIOResult, ioCounters1, i); FFDiskIOResult* icCurr = FF_LIST_GET(FFDiskIOResult, *result, i); - if (!ffStrbufEqual(&icPrev->devPath, &icCurr->devPath)) + if (!ffStrbufEqual(&icPrev->devPath, &icCurr->devPath)) { return "Physical disk device path changed"; + } static_assert(sizeof(FFDiskIOResult) - offsetof(FFDiskIOResult, bytesRead) == sizeof(uint64_t) * 4, "Unexpected struct FFDiskIOResult layout"); - for (size_t off = offsetof(FFDiskIOResult, bytesRead); off < sizeof(FFDiskIOResult); off += sizeof(uint64_t)) - { + for (size_t off = offsetof(FFDiskIOResult, bytesRead); off < sizeof(FFDiskIOResult); off += sizeof(uint64_t)) { uint64_t* prevValue = (uint64_t*) ((uint8_t*) icPrev + off); uint64_t* currValue = (uint64_t*) ((uint8_t*) icCurr + off); uint64_t temp = *currValue; diff --git a/src/detection/diskio/diskio.h b/src/detection/diskio/diskio.h index fdaae3b18..39c665a21 100644 --- a/src/detection/diskio/diskio.h +++ b/src/detection/diskio/diskio.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/diskio/option.h" -typedef struct FFDiskIOResult -{ +typedef struct FFDiskIOResult { FFstrbuf name; FFstrbuf devPath; uint64_t bytesRead; diff --git a/src/detection/diskio/diskio_apple.c b/src/detection/diskio/diskio_apple.c index 4cf2ec2aa..d43eccaf0 100644 --- a/src/detection/diskio/diskio_apple.c +++ b/src/detection/diskio/diskio_apple.c @@ -8,34 +8,38 @@ #include #include -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { FF_IOOBJECT_AUTO_RELEASE io_iterator_t iterator = 0; - if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching(kIOMediaClass), &iterator) != KERN_SUCCESS) + if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching(kIOMediaClass), &iterator) != KERN_SUCCESS) { return "IOServiceGetMatchingServices() failed"; + } io_registry_entry_t registryEntry; - while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) - { + while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryPartition = registryEntry; io_name_t deviceName; - if (IORegistryEntryGetName(registryEntry, deviceName) != KERN_SUCCESS) + if (IORegistryEntryGetName(registryEntry, deviceName) != KERN_SUCCESS) { continue; + } - if (options->namePrefix.length && strncmp(deviceName, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(deviceName, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryDriver = 0; - if (IORegistryEntryGetParentEntry(entryPartition, kIOServicePlane, &entryDriver) != KERN_SUCCESS) + if (IORegistryEntryGetParentEntry(entryPartition, kIOServicePlane, &entryDriver) != KERN_SUCCESS) { continue; + } - if (!IOObjectConformsTo(entryDriver, kIOBlockStorageDriverClass)) // physical disk only + if (!IOObjectConformsTo(entryDriver, kIOBlockStorageDriverClass)) { // physical disk only continue; + } FF_CFTYPE_AUTO_RELEASE CFDictionaryRef statistics = IORegistryEntryCreateCFProperty(entryDriver, CFSTR(kIOBlockStorageDriverStatisticsKey), kCFAllocatorDefault, kNilOptions); - if (!statistics) + if (!statistics) { continue; + } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); ffStrbufInitS(&device->name, deviceName); @@ -47,8 +51,7 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) ffCfDictGetInt64(statistics, CFSTR(kIOBlockStorageDriverStatisticsWritesKey), (int64_t*) &device->writeCount); FF_CFTYPE_AUTO_RELEASE CFStringRef bsdName = IORegistryEntryCreateCFProperty(entryPartition, CFSTR(kIOBSDNameKey), kCFAllocatorDefault, kNilOptions); - if (bsdName) - { + if (bsdName) { ffCfStrGetString(bsdName, &device->devPath); ffStrbufPrependS(&device->devPath, "/dev/"); } diff --git a/src/detection/diskio/diskio_bsd.c b/src/detection/diskio/diskio_bsd.c index 563baa4fa..b599f0f36 100644 --- a/src/detection/diskio/diskio_bsd.c +++ b/src/detection/diskio/diskio_bsd.c @@ -2,54 +2,60 @@ #if __has_include() -#include "common/stringUtils.h" +# include "common/stringUtils.h" -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ - __attribute__((__cleanup__(geom_deletetree))) - struct gmesh geomTree = {}; - if (geom_gettree(&geomTree) < 0) +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { + __attribute__((__cleanup__(geom_deletetree))) struct gmesh geomTree = {}; + if (geom_gettree(&geomTree) < 0) { return "geom_gettree() failed"; + } - if (geom_stats_open() < 0) + if (geom_stats_open() < 0) { return "geom_stats_open() failed"; + } void* snap = geom_stats_snapshot_get(); - if (!snap) + if (!snap) { return "geom_stats_snapshot_get() failed"; + } struct devstat* snapIter; - while ((snapIter = geom_stats_snapshot_next(snap)) != NULL) - { - if (snapIter->device_type & DEVSTAT_TYPE_PASS) + while ((snapIter = geom_stats_snapshot_next(snap)) != NULL) { + if (snapIter->device_type & DEVSTAT_TYPE_PASS) { continue; + } struct gident* geomId = geom_lookupid(&geomTree, snapIter->id); - if (geomId == NULL) + if (geomId == NULL) { continue; - if (geomId->lg_what != ISPROVIDER) + } + if (geomId->lg_what != ISPROVIDER) { continue; + } struct gprovider* provider = (struct gprovider*) geomId->lg_ptr; - if (provider->lg_geom->lg_rank != 1) + if (provider->lg_geom->lg_rank != 1) { continue; + } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); - for (struct gconfig* ptr = provider->lg_config.lh_first; ptr; ptr = ptr->lg_config.le_next) - { - if (ffStrEquals(ptr->lg_name, "descr")) + for (struct gconfig* ptr = provider->lg_config.lh_first; ptr; ptr = ptr->lg_config.le_next) { + if (ffStrEquals(ptr->lg_name, "descr")) { ffStrbufSetS(&name, ptr->lg_val); + } } - if (name.length == 0) + if (name.length == 0) { ffStrbufSetS(&name, provider->lg_name); + } - if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) + if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) { continue; + } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); ffStrbufInitF(&device->devPath, "/dev/%s", provider->lg_name); @@ -68,31 +74,33 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) #else -#include -#include +# include +# include -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ - if (checkversion() < 0) +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { + if (checkversion() < 0) { return "checkversion() failed"; + } struct statinfo stats = { - .dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo)), + .dinfo = (struct devinfo*) calloc(1, sizeof(struct devinfo)), }; - if (getdevs(&stats) < 0) + if (getdevs(&stats) < 0) { return "getdevs() failed"; + } - for (int i = 0; i < stats.dinfo->numdevs; i++) - { + for (int i = 0; i < stats.dinfo->numdevs; i++) { struct devstat* current = &stats.dinfo->devices[i]; - if (current->device_type & DEVSTAT_TYPE_PASS) + if (current->device_type & DEVSTAT_TYPE_PASS) { continue; + } char deviceName[128]; snprintf(deviceName, sizeof(deviceName), "%s%d", current->device_name, current->unit_number); - if (options->namePrefix.length && strncmp(deviceName, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(deviceName, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); ffStrbufInitS(&device->name, deviceName); diff --git a/src/detection/diskio/diskio_linux.c b/src/detection/diskio/diskio_linux.c index 1855115ac..90c374405 100644 --- a/src/detection/diskio/diskio_linux.c +++ b/src/detection/diskio/diskio_linux.c @@ -8,48 +8,46 @@ #include #include -static const char* parseDiskIOCounters(int dfd, const char* devName, FFlist* result, FFDiskIOOptions* options) -{ +static const char* parseDiskIOCounters(int dfd, const char* devName, FFlist* result, FFDiskIOOptions* options) { FF_AUTO_CLOSE_FD int devfd = openat(dfd, "device", O_RDONLY | O_CLOEXEC | O_PATH | O_DIRECTORY); - if (devfd < 0) return "virtual device"; + if (devfd < 0) { + return "virtual device"; + } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); { - if (ffAppendFileBufferRelative(devfd, "vendor", &name)) - { + if (ffAppendFileBufferRelative(devfd, "vendor", &name)) { ffStrbufTrimRightSpace(&name); - if (name.length > 0) + if (name.length > 0) { ffStrbufAppendC(&name, ' '); + } } ffAppendFileBufferRelative(devfd, "model", &name); ffStrbufTrimRightSpace(&name); - if (name.length == 0) + if (name.length == 0) { ffStrbufSetS(&name, devName); - else if (ffStrStartsWith(devName, "nvme")) - { + } else if (ffStrStartsWith(devName, "nvme")) { int devid, nsid; - if (sscanf(devName, "nvme%dn%d", &devid, &nsid) == 2) - { + if (sscanf(devName, "nvme%dn%d", &devid, &nsid) == 2) { bool multiNs = nsid > 1; - if (!multiNs) - { + if (!multiNs) { char pathSysBlock[16]; snprintf(pathSysBlock, ARRAY_SIZE(pathSysBlock), "nvme%dn2", devid); multiNs = faccessat(devfd, pathSysBlock, F_OK, 0) == 0; } - if (multiNs) - { + if (multiNs) { // In Asahi Linux, there are multiple namespaces for the same NVMe drive. ffStrbufAppendF(&name, " - %d", nsid); } } } - if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) + if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) { return "ignored"; + } } // I/Os merges sectors ticks ... @@ -57,10 +55,13 @@ static const char* parseDiskIOCounters(int dfd, const char* devName, FFlist* res { char sysBlockStat[PROC_FILE_BUFFSIZ]; ssize_t fileSize = ffReadFileDataRelative(dfd, "stat", ARRAY_SIZE(sysBlockStat) - 1, sysBlockStat); - if (fileSize <= 0) return "failed to read stat file"; + if (fileSize <= 0) { + return "failed to read stat file"; + } sysBlockStat[fileSize] = '\0'; - if (sscanf(sysBlockStat, "%" PRIu64 "%*u%" PRIu64 "%*u%" PRIu64 "%*u%" PRIu64 "%*u", &nRead, §orRead, &nWritten, §orWritten) <= 0) + if (sscanf(sysBlockStat, "%" PRIu64 "%*u%" PRIu64 "%*u%" PRIu64 "%*u%" PRIu64 "%*u", &nRead, §orRead, &nWritten, §orWritten) <= 0) { return "invalid stat file format"; + } } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); @@ -74,21 +75,24 @@ static const char* parseDiskIOCounters(int dfd, const char* devName, FFlist* res return NULL; } -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { FF_AUTO_CLOSE_DIR DIR* sysBlockDirp = opendir("/sys/block/"); - if(sysBlockDirp == NULL) + if (sysBlockDirp == NULL) { return "opendir(\"/sys/block/\") == NULL"; + } struct dirent* sysBlockEntry; - while ((sysBlockEntry = readdir(sysBlockDirp)) != NULL) - { + while ((sysBlockEntry = readdir(sysBlockDirp)) != NULL) { const char* const devName = sysBlockEntry->d_name; - if (devName[0] == '.') continue; + if (devName[0] == '.') { + continue; + } FF_AUTO_CLOSE_FD int dfd = openat(dirfd(sysBlockDirp), devName, O_RDONLY | O_CLOEXEC | O_PATH | O_DIRECTORY); - if (dfd > 0) parseDiskIOCounters(dfd, devName, result, options); + if (dfd > 0) { + parseDiskIOCounters(dfd, devName, result, options); + } } return NULL; diff --git a/src/detection/diskio/diskio_nbsd.c b/src/detection/diskio/diskio_nbsd.c index 8e015fc4e..0a72680ea 100644 --- a/src/detection/diskio/diskio_nbsd.c +++ b/src/detection/diskio/diskio_nbsd.c @@ -5,25 +5,26 @@ #include #include -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { int mib[] = {CTL_HW, HW_IOSTATS, sizeof(struct io_sysctl)}; size_t len; - if (sysctl(mib, ARRAY_SIZE(mib), NULL, &len, NULL, 0) < 0) + if (sysctl(mib, ARRAY_SIZE(mib), NULL, &len, NULL, 0) < 0) { return "sysctl({HW_IOSTATS}, NULL) failed"; + } uint32_t nDrive = (uint32_t) (len / sizeof(struct io_sysctl)); FF_AUTO_FREE struct io_sysctl* stats = malloc(len); - if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, NULL, 0) < 0) + if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, NULL, 0) < 0) { return "sysctl({HW_IOSTATS}, stats) failed"; + } - for (uint32_t i = 0; i < nDrive; ++i) - { + for (uint32_t i = 0; i < nDrive; ++i) { struct io_sysctl* st = &stats[i]; - if (options->namePrefix.length && strncmp(st->name, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(st->name, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); ffStrbufInitF(&device->devPath, "/dev/%s", st->name); diff --git a/src/detection/diskio/diskio_nosupport.c b/src/detection/diskio/diskio_nosupport.c index 338c6e361..c95c8a39a 100644 --- a/src/detection/diskio/diskio_nosupport.c +++ b/src/detection/diskio/diskio_nosupport.c @@ -1,6 +1,5 @@ #include "diskio.h" -const char* ffDiskIOGetIoCounters(FF_MAYBE_UNUSED FFlist* result, FF_MAYBE_UNUSED FFDiskIOOptions* options) -{ +const char* ffDiskIOGetIoCounters(FF_MAYBE_UNUSED FFlist* result, FF_MAYBE_UNUSED FFDiskIOOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/diskio/diskio_obsd.c b/src/detection/diskio/diskio_obsd.c index 9411e030f..6f449d042 100644 --- a/src/detection/diskio/diskio_obsd.c +++ b/src/detection/diskio/diskio_obsd.c @@ -5,25 +5,26 @@ #include #include -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { int mib[] = {CTL_HW, HW_DISKSTATS}; size_t len; - if (sysctl(mib, ARRAY_SIZE(mib), NULL, &len, NULL, 0) < 0) + if (sysctl(mib, ARRAY_SIZE(mib), NULL, &len, NULL, 0) < 0) { return "sysctl({HW_DISKSTATS}, NULL) failed"; + } uint32_t nDrive = (uint32_t) (len / sizeof(struct diskstats)); FF_AUTO_FREE struct diskstats* stats = malloc(len); - if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, NULL, 0) < 0) + if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, NULL, 0) < 0) { return "sysctl({HW_DISKSTATS}, stats) failed"; + } - for (uint32_t i = 0; i < nDrive; ++i) - { + for (uint32_t i = 0; i < nDrive; ++i) { struct diskstats* st = &stats[i]; - if (options->namePrefix.length && strncmp(st->ds_name, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(st->ds_name, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); ffStrbufInitF(&device->devPath, "/dev/%s", st->ds_name); diff --git a/src/detection/diskio/diskio_sunos.c b/src/detection/diskio/diskio_sunos.c index 5147b21b2..ba3ef01e4 100644 --- a/src/detection/diskio/diskio_sunos.c +++ b/src/detection/diskio/diskio_sunos.c @@ -2,29 +2,32 @@ #include "common/stringUtils.h" #include -static inline void kstatFreeWrap(kstat_ctl_t** pkc) -{ +static inline void kstatFreeWrap(kstat_ctl_t** pkc) { assert(pkc); - if (*pkc) + if (*pkc) { kstat_close(*pkc); + } } -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { __attribute__((__cleanup__(kstatFreeWrap))) kstat_ctl_t* kc = kstat_open(); - if (!kc) + if (!kc) { return "kstat_open() failed"; + } - for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next) - { - if (ks->ks_type != KSTAT_TYPE_IO || !ffStrEquals(ks->ks_class, "disk")) continue; - - if (options->namePrefix.length && strncmp(ks->ks_name, options->namePrefix.chars, options->namePrefix.length) != 0) + for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next) { + if (ks->ks_type != KSTAT_TYPE_IO || !ffStrEquals(ks->ks_class, "disk")) { continue; + } + + if (options->namePrefix.length && strncmp(ks->ks_name, options->namePrefix.chars, options->namePrefix.length) != 0) { + continue; + } kstat_io_t kio; - if (kstat_read(kc, ks, &kio) < 0) + if (kstat_read(kc, ks, &kio) < 0) { continue; + } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); ffStrbufInit(&device->devPath); // unlike other platforms, `/dev/ks_name` is not available diff --git a/src/detection/diskio/diskio_windows.c b/src/detection/diskio/diskio_windows.c index 7622e99f9..52be20340 100644 --- a/src/detection/diskio/diskio_windows.c +++ b/src/detection/diskio/diskio_windows.c @@ -5,67 +5,64 @@ #include #include -static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFDiskIOOptions* options) -{ +static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFDiskIOOptions* options) { FF_AUTO_CLOSE_FD HANDLE hDevice = CreateFileW(szDevice, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - if (hDevice == INVALID_HANDLE_VALUE) + if (hDevice == INVALID_HANDLE_VALUE) { return false; + } DWORD retSize; char sddBuffer[4096]; - if(!DeviceIoControl( - hDevice, - IOCTL_STORAGE_QUERY_PROPERTY, - &(STORAGE_PROPERTY_QUERY) { - .PropertyId = StorageDeviceProperty, - .QueryType = PropertyStandardQuery, - }, - sizeof(STORAGE_PROPERTY_QUERY), - &sddBuffer, - ARRAY_SIZE(sddBuffer), - &retSize, - NULL - ) || retSize == 0) + if (!DeviceIoControl( + hDevice, + IOCTL_STORAGE_QUERY_PROPERTY, + &(STORAGE_PROPERTY_QUERY) { + .PropertyId = StorageDeviceProperty, + .QueryType = PropertyStandardQuery, + }, + sizeof(STORAGE_PROPERTY_QUERY), + &sddBuffer, + ARRAY_SIZE(sddBuffer), + &retSize, + NULL) || + retSize == 0) { return true; + } FFDiskIOResult* device = (FFDiskIOResult*) ffListAdd(result); STORAGE_DEVICE_DESCRIPTOR* sdd = (STORAGE_DEVICE_DESCRIPTOR*) sddBuffer; ffStrbufInit(&device->name); - if (sdd->VendorIdOffset != 0) - { + if (sdd->VendorIdOffset != 0) { ffStrbufSetS(&device->name, (const char*) sddBuffer + sdd->VendorIdOffset); ffStrbufTrim(&device->name, ' '); } - if (sdd->ProductIdOffset != 0) - { - if (device->name.length) + if (sdd->ProductIdOffset != 0) { + if (device->name.length) { ffStrbufAppendC(&device->name, ' '); + } ffStrbufAppendS(&device->name, (const char*) sddBuffer + sdd->ProductIdOffset); ffStrbufTrimRight(&device->name, ' '); } - if (!device->name.length) + if (!device->name.length) { ffStrbufSetWS(&device->name, szDevice); + } - if (options->namePrefix.length && !ffStrbufStartsWith(&device->name, &options->namePrefix)) - { + if (options->namePrefix.length && !ffStrbufStartsWith(&device->name, &options->namePrefix)) { ffStrbufDestroy(&device->name); result->length--; return true; } DISK_PERFORMANCE dp = {}; - if (DeviceIoControl(hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &dp, sizeof(dp), &retSize, NULL)) - { + if (DeviceIoControl(hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &dp, sizeof(dp), &retSize, NULL)) { device->bytesRead = (uint64_t) dp.BytesRead.QuadPart; device->readCount = (uint64_t) dp.ReadCount; device->bytesWritten = (uint64_t) dp.BytesWritten.QuadPart; device->writeCount = (uint64_t) dp.WriteCount; - } - else - { + } else { ffStrbufDestroy(&device->name); result->length--; } @@ -75,29 +72,28 @@ static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFDiskIO return true; } -const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) -{ +const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { { wchar_t szPhysicalDrive[32] = L"\\\\.\\PhysicalDrive"; wchar_t* pNum = szPhysicalDrive + strlen("\\\\.\\PhysicalDrive"); - for (uint32_t idev = 0; ; ++idev) - { + for (uint32_t idev = 0;; ++idev) { _ultow(idev, pNum, 10); - if (!detectPhysicalDisk(szPhysicalDrive, result, options)) + if (!detectPhysicalDisk(szPhysicalDrive, result, options)) { break; + } } } { wchar_t szCdrom[32] = L"\\\\.\\CDROM"; wchar_t* pNum = szCdrom + strlen("\\\\.\\CDROM"); - for (uint32_t idev = 0; ; ++idev) - { + for (uint32_t idev = 0;; ++idev) { _ultow(idev, pNum, 10); - if (!detectPhysicalDisk(szCdrom, result, options)) + if (!detectPhysicalDisk(szCdrom, result, options)) { break; + } } } diff --git a/src/detection/displayserver/displayserver.c b/src/detection/displayserver/displayserver.c index d8b7ac3ba..40f7c1261 100644 --- a/src/detection/displayserver/displayserver.c +++ b/src/detection/displayserver/displayserver.c @@ -16,10 +16,10 @@ FFDisplayResult* ffdsAppendDisplay( uint64_t id, uint32_t physicalWidth, uint32_t physicalHeight, - const char* platformApi) -{ - if(width == 0 || height == 0) + const char* platformApi) { + if (width == 0 || height == 0) { return NULL; + } FFDisplayResult* display = (FFDisplayResult*) ffListAdd(&result->displays); display->width = width; @@ -50,11 +50,9 @@ FFDisplayResult* ffdsAppendDisplay( void ffConnectDisplayServerImpl(FFDisplayServerResult* ds); -const FFDisplayServerResult* ffConnectDisplayServer() -{ +const FFDisplayServerResult* ffConnectDisplayServer() { static FFDisplayServerResult result; - if (result.displays.elementSize == 0) - { + if (result.displays.elementSize == 0) { ffStrbufInit(&result.wmProcessName); ffStrbufInit(&result.wmPrettyName); ffStrbufInit(&result.wmProtocolName); diff --git a/src/detection/displayserver/displayserver.h b/src/detection/displayserver/displayserver.h index 81f754bea..05900f5ec 100644 --- a/src/detection/displayserver/displayserver.h +++ b/src/detection/displayserver/displayserver.h @@ -52,35 +52,32 @@ typedef enum __attribute__((__packed__)) FFDisplayType { FF_DISPLAY_TYPE_EXTERNAL, } FFDisplayType; -typedef enum __attribute__((__packed__)) FFDisplayHdrStatus -{ +typedef enum __attribute__((__packed__)) FFDisplayHdrStatus { FF_DISPLAY_HDR_STATUS_UNKNOWN, FF_DISPLAY_HDR_STATUS_UNSUPPORTED, FF_DISPLAY_HDR_STATUS_SUPPORTED, FF_DISPLAY_HDR_STATUS_ENABLED, } FFDisplayHdrStatus; -typedef enum __attribute__((__packed__)) FFDisplayVrrStatus -{ +typedef enum __attribute__((__packed__)) FFDisplayVrrStatus { FF_DISPLAY_DRR_STATUS_UNKNOWN, FF_DISPLAY_DRR_STATUS_DISABLED, FF_DISPLAY_DRR_STATUS_ENABLED, } FFDisplayVrrStatus; -typedef struct FFDisplayResult -{ - uint32_t width; // in px - uint32_t height; // in px - double refreshRate; // in Hz - uint32_t dpi; // Base 96 - uint32_t preferredWidth; // in px - uint32_t preferredHeight; // in px +typedef struct FFDisplayResult { + uint32_t width; // in px + uint32_t height; // in px + double refreshRate; // in Hz + uint32_t dpi; // Base 96 + uint32_t preferredWidth; // in px + uint32_t preferredHeight; // in px double preferredRefreshRate; // in Hz FFstrbuf name; FFDisplayType type; uint32_t rotation; - uint64_t id; // platform dependent - uint32_t physicalWidth; // in mm + uint64_t id; // platform dependent + uint32_t physicalWidth; // in mm uint32_t physicalHeight; // in mm bool primary; const char* platformApi; @@ -92,14 +89,13 @@ typedef struct FFDisplayResult FFDisplayVrrStatus drrStatus; } FFDisplayResult; -typedef struct FFDisplayServerResult -{ +typedef struct FFDisplayServerResult { FFstrbuf wmProcessName; FFstrbuf wmPrettyName; FFstrbuf wmProtocolName; FFstrbuf deProcessName; FFstrbuf dePrettyName; - FFlist displays; //List of FFDisplayResult + FFlist displays; // List of FFDisplayResult } FFDisplayServerResult; const FFDisplayServerResult* ffConnectDisplayServer(); diff --git a/src/detection/displayserver/displayserver_android.c b/src/detection/displayserver/displayserver_android.c index a0eb7192e..9b2848a13 100644 --- a/src/detection/displayserver/displayserver_android.c +++ b/src/detection/displayserver/displayserver_android.c @@ -5,24 +5,20 @@ #include -static bool checkHdrStatus(FFDisplayResult* display) -{ +static bool checkHdrStatus(FFDisplayResult* display) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffSettingsGetAndroidProperty("ro.surface_flinger.has_HDR_display", &buffer)) - { - if (ffStrbufIgnCaseEqualS(&buffer, "true")) - { + if (ffSettingsGetAndroidProperty("ro.surface_flinger.has_HDR_display", &buffer)) { + if (ffStrbufIgnCaseEqualS(&buffer, "true")) { display->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; if (ffSettingsGetAndroidProperty("persist.sys.hdr_mode", &buffer) && - ffStrbufToUInt(&buffer, 0) > 0) + ffStrbufToUInt(&buffer, 0) > 0) { display->hdrStatus = FF_DISPLAY_HDR_STATUS_ENABLED; + } return true; - } - else - { + } else { display->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; return true; } @@ -32,19 +28,19 @@ static bool checkHdrStatus(FFDisplayResult* display) return false; } -static void detectWithDumpsys(FFDisplayServerResult* ds) -{ +static void detectWithDumpsys(FFDisplayServerResult* ds) { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buf, (char* []) { - "/system/bin/dumpsys", - "display", - NULL, - }) != NULL || buf.length == 0) + if (ffProcessAppendStdOut(&buf, (char*[]) { + "/system/bin/dumpsys", + "display", + NULL, + }) != NULL || + buf.length == 0) { return; // Only works in `adb shell`, or when rooted + } uint32_t index = 0; - while ((index = ffStrbufNextIndexS(&buf, index, "DisplayDeviceInfo")) < buf.length) - { + while ((index = ffStrbufNextIndexS(&buf, index, "DisplayDeviceInfo")) < buf.length) { index += strlen("DisplayDeviceInfo"); uint32_t nextIndex = ffStrbufNextIndexC(&buf, index, '\n'); buf.chars[nextIndex] = '\0'; @@ -56,37 +52,34 @@ static void detectWithDumpsys(FFDisplayServerResult* ds) double refreshRate = 0; // {"Builtin display": uniqueId="local:4630947134992368259", 1440 x 3200, modeId 2 int res = sscanf(info, "{\"%63[^\"]\":%*s%u x %u, modeId%u", name.chars, &width, &height, &modeId); - if (res >= 3) - { - if (res == 4) - { + if (res >= 3) { + if (res == 4) { ++info; // skip first '{' - while ((info = strchr(info, '{'))) - { + while ((info = strchr(info, '{'))) { ++info; unsigned id; double fps; // id=1, width=1440, height=3200, fps=60.000004, - if (sscanf(info, "id=%u, %*s%*s fps=%lf", &id, &fps) >= 2) - { - if (id == modeId) - { + if (sscanf(info, "id=%u, %*s%*s fps=%lf", &id, &fps) >= 2) { + if (id == modeId) { refreshRate = fps; break; } - } - else + } else { break; + } } } 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, &name, @@ -95,23 +88,22 @@ static void detectWithDumpsys(FFDisplayServerResult* ds) 0, 0, 0, - "dumpsys" - ); - if (display) display->hdrStatus = checkHdrStatus(display); + "dumpsys"); + if (display) { + display->hdrStatus = checkHdrStatus(display); + } } index = nextIndex + 1; } } -static bool detectWithGetprop(FFDisplayServerResult* ds) -{ +static bool detectWithGetprop(FFDisplayServerResult* ds) { // Only for MiUI FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); if (ffSettingsGetAndroidProperty("persist.sys.miui_resolution", &buffer) && - ffStrbufContainC(&buffer, ',')) - { + ffStrbufContainC(&buffer, ',')) { // 1440,3200,560 => width,height,densityDpi uint32_t width = (uint32_t) ffStrbufToUInt(&buffer, 0); ffStrbufSubstrAfterFirstC(&buffer, ','); @@ -119,10 +111,12 @@ static bool detectWithGetprop(FFDisplayServerResult* ds) ffStrbufSubstrAfterFirstC(&buffer, ','); uint32_t dpi = (uint32_t) ffStrbufToUInt(&buffer, 0) * 96 / 160; FFDisplayResult* display = ffdsAppendDisplay(ds, - width, height, + width, + height, 0, dpi, - 0, 0, + 0, + 0, 0, 0, NULL, @@ -131,17 +125,17 @@ static bool detectWithGetprop(FFDisplayServerResult* ds) 0, 0, 0, - "getprop" - ); - if (display) display->hdrStatus = checkHdrStatus(display); + "getprop"); + if (display) { + display->hdrStatus = checkHdrStatus(display); + } return !!display; } return false; } -static bool detectDE(FFDisplayServerResult* ds) -{ +static bool detectDE(FFDisplayServerResult* ds) { if (ffSettingsGetAndroidProperty("ro.vivo.os.build.display.id", &ds->dePrettyName)) // OriginOS 6 { ffStrbufAppendC(&ds->dePrettyName, ' '); @@ -149,47 +143,41 @@ static bool detectDE(FFDisplayServerResult* ds) return true; } if (ffSettingsGetAndroidProperty("ro.build.version.magic", &ds->dePrettyName) || - ffSettingsGetAndroidProperty("ro.build.version.emui", &ds->dePrettyName)) - { + ffSettingsGetAndroidProperty("ro.build.version.emui", &ds->dePrettyName)) { ffStrbufReplaceAllC(&ds->dePrettyName, '_', ' '); return true; } - if (ffSettingsGetAndroidProperty("ro.mi.os.version.name", &ds->dePrettyName)) - { + if (ffSettingsGetAndroidProperty("ro.mi.os.version.name", &ds->dePrettyName)) { // MiUI like ffStrbufClear(&ds->dePrettyName); ffSettingsGetAndroidProperty("ro.build.version.incremental", &ds->dePrettyName); // Detail version number - if (ffStrbufStartsWithS(&ds->dePrettyName, "OS")) - { + if (ffStrbufStartsWithS(&ds->dePrettyName, "OS")) { ds->dePrettyName.chars[0] = 'S'; ds->dePrettyName.chars[1] = ' '; ffStrbufPrependS(&ds->dePrettyName, "HyperO"); - } - else if (ffStrbufStartsWithS(&ds->dePrettyName, "V")) - { + } else if (ffStrbufStartsWithS(&ds->dePrettyName, "V")) { ds->dePrettyName.chars[0] = ' '; ffStrbufPrependS(&ds->dePrettyName, "MiUI"); - } - else + } else { ffStrbufSetStatic(&ds->dePrettyName, "MiUI"); + } return true; } - if (ffSettingsGetAndroidProperty("ro.build.version.oplusrom", &ds->dePrettyName)) - { - if (ffStrbufStartsWithS(&ds->dePrettyName, "V")) + if (ffSettingsGetAndroidProperty("ro.build.version.oplusrom", &ds->dePrettyName)) { + if (ffStrbufStartsWithS(&ds->dePrettyName, "V")) { ffStrbufSubstrAfter(&ds->dePrettyName, 0); + } ffStrbufPrependS(&ds->dePrettyName, "ColorOS"); return true; } - if (ffSettingsGetAndroidProperty("ro.oxygen.version", &ds->dePrettyName)) - { + if (ffSettingsGetAndroidProperty("ro.oxygen.version", &ds->dePrettyName)) { ffStrbufPrependS(&ds->dePrettyName, "OxygenOS"); return true; } - if (ffSettingsGetAndroidProperty("ro.build.display.id", &ds->dePrettyName)) - { - if (ffStrbufStartsWithS(&ds->dePrettyName, "RedMagicOS")) + if (ffSettingsGetAndroidProperty("ro.build.display.id", &ds->dePrettyName)) { + if (ffStrbufStartsWithS(&ds->dePrettyName, "RedMagicOS")) { ffStrbufInsertNC(&ds->dePrettyName, strlen("RedMagicOS"), 1, ' '); + } // Google Pixel uses native Android return true; @@ -198,13 +186,12 @@ static bool detectDE(FFDisplayServerResult* ds) return false; } -void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) -{ +void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) { const char* error = ffdsConnectXcbRandr(ds); - if (error) + if (error) { error = ffdsConnectXrandr(ds); - if (!error) - { + } + if (!error) { ffdsDetectWMDE(ds); return; } @@ -214,8 +201,9 @@ void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) ffStrbufSetStatic(&ds->wmPrettyName, "WindowManager"); // A system service managed by system_server ffStrbufSetStatic(&ds->wmProtocolName, FF_WM_PROTOCOL_SURFACEFLINGER); - if (!detectWithGetprop(ds)) + if (!detectWithGetprop(ds)) { detectWithDumpsys(ds); + } detectDE(ds); } diff --git a/src/detection/displayserver/displayserver_apple.c b/src/detection/displayserver/displayserver_apple.c index 83444892c..dca985976 100644 --- a/src/detection/displayserver/displayserver_apple.c +++ b/src/detection/displayserver/displayserver_apple.c @@ -15,93 +15,89 @@ extern Boolean CoreDisplay_Display_SupportsHDRMode(CGDirectDisplayID display) __ extern Boolean CoreDisplay_Display_IsHDRModeEnabled(CGDirectDisplayID display) __attribute__((weak_import)); extern CFDictionaryRef CoreDisplay_DisplayCreateInfoDictionary(CGDirectDisplayID display) __attribute__((weak_import)); #else -#include +# include #endif -static void detectDisplays(FFDisplayServerResult* ds) -{ +static void detectDisplays(FFDisplayServerResult* ds) { CGDirectDisplayID screens[128]; uint32_t screenCount; - if(CGGetOnlineDisplayList(ARRAY_SIZE(screens), screens, &screenCount) != kCGErrorSuccess) + if (CGGetOnlineDisplayList(ARRAY_SIZE(screens), screens, &screenCount) != kCGErrorSuccess) { return; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - for(uint32_t i = 0; i < screenCount; i++) - { + for (uint32_t i = 0; i < screenCount; i++) { CGDirectDisplayID screen = screens[i]; CGDisplayModeRef mode = CGDisplayCopyDisplayMode(screen); - if(mode) - { - //https://github.com/glfw/glfw/commit/aab08712dd8142b642e2042e7b7ba563acd07a45 + if (mode) { + // https://github.com/glfw/glfw/commit/aab08712dd8142b642e2042e7b7ba563acd07a45 double refreshRate = CGDisplayModeGetRefreshRate(mode); - if (refreshRate == 0) - { - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (refreshRate == 0) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" CVDisplayLinkRef link; - if(CVDisplayLinkCreateWithCGDisplay(screen, &link) == kCVReturnSuccess) - { + if (CVDisplayLinkCreateWithCGDisplay(screen, &link) == kCVReturnSuccess) { const CVTime time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link); - if (!(time.flags & kCVTimeIsIndefinite)) - refreshRate = time.timeScale / (double) time.timeValue; //59.97... + if (!(time.flags & kCVTimeIsIndefinite)) { + refreshRate = time.timeScale / (double) time.timeValue; // 59.97... + } CVDisplayLinkRelease(link); } - #pragma clang diagnostic pop +#pragma clang diagnostic pop } ffStrbufClear(&buffer); CFDictionaryRef FF_CFTYPE_AUTO_RELEASE displayInfo = NULL; - #ifdef MAC_OS_X_VERSION_10_15 - if(CoreDisplay_DisplayCreateInfoDictionary) +#ifdef MAC_OS_X_VERSION_10_15 + if (CoreDisplay_DisplayCreateInfoDictionary) { displayInfo = CoreDisplay_DisplayCreateInfoDictionary(screen); - #else + } +#else { io_service_t servicePort = CGDisplayIOServicePort(screen); displayInfo = IODisplayCreateInfoDictionary(servicePort, kIODisplayOnlyPreferredName); } - #endif +#endif uint32_t physicalWidth = 0, physicalHeight = 0; uint32_t preferredWidth = 0, preferredHeight = 0; double preferredRefreshRate = 0; - if(displayInfo) - { + if (displayInfo) { CFDictionaryRef productNames; - if(ffCfDictGetDict(displayInfo, CFSTR(kDisplayProductName), &productNames) == NULL) + if (ffCfDictGetDict(displayInfo, CFSTR(kDisplayProductName), &productNames) == NULL) { ffCfDictGetString(productNames, CFSTR("en_US"), &buffer); + } // CGDisplayScreenSize reports invalid result for external displays on old Intel MacBook Pro CFDataRef edidRef = (CFDataRef) CFDictionaryGetValue(displayInfo, CFSTR(kIODisplayEDIDKey)); - if (edidRef && CFGetTypeID(edidRef) == CFDataGetTypeID()) - { + if (edidRef && CFGetTypeID(edidRef) == CFDataGetTypeID()) { const uint8_t* edidData = CFDataGetBytePtr(edidRef); uint32_t edidLength = (uint32_t) CFDataGetLength(edidRef); - if (edidLength >= 128) + if (edidLength >= 128) { ffEdidGetPhysicalSize(edidData, &physicalWidth, &physicalHeight); + } } - if (!physicalWidth || !physicalHeight) - { - if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayHorizontalImageSize), (int*) &physicalWidth) == NULL) + if (!physicalWidth || !physicalHeight) { + if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayHorizontalImageSize), (int*) &physicalWidth) == NULL) { ffCfDictGetInt(displayInfo, CFSTR(kDisplayVerticalImageSize), (int*) &physicalHeight); + } } ffCfDictGetInt(displayInfo, CFSTR("kCGDisplayPixelWidth"), (int*) &preferredWidth); ffCfDictGetInt(displayInfo, CFSTR("kCGDisplayPixelHeight"), (int*) &preferredHeight); - if (preferredWidth && preferredHeight) - { + if (preferredWidth && preferredHeight) { FF_CFTYPE_AUTO_RELEASE CFArrayRef allModes = CGDisplayCopyAllDisplayModes(screen, NULL); - if (allModes) - { - for (CFIndex i = 0, count = CFArrayGetCount(allModes); i < count; i++) - { + if (allModes) { + for (CFIndex i = 0, count = CFArrayGetCount(allModes); i < count; i++) { CGDisplayModeRef modeInfo = (CGDisplayModeRef) CFArrayGetValueAtIndex(allModes, i); - if (CGDisplayModeGetPixelWidth(modeInfo) == preferredWidth && CGDisplayModeGetPixelHeight(modeInfo) == preferredHeight) - { + if (CGDisplayModeGetPixelWidth(modeInfo) == preferredWidth && CGDisplayModeGetPixelHeight(modeInfo) == preferredHeight) { double rr = CGDisplayModeGetRefreshRate(modeInfo); - if (rr > preferredRefreshRate) preferredRefreshRate = rr; + if (rr > preferredRefreshRate) { + preferredRefreshRate = rr; + } break; } } @@ -123,62 +119,63 @@ static void detectDisplays(FFDisplayServerResult* ds) pixelWidth, pixelHeight, refreshRate, - pixelHeight * 96 / (uint32_t)CGDisplayModeGetHeight(mode), + pixelHeight * 96 / (uint32_t) CGDisplayModeGetHeight(mode), preferredWidth, preferredHeight, preferredRefreshRate, - (uint32_t)CGDisplayRotation(screen), + (uint32_t) CGDisplayRotation(screen), &buffer, CGDisplayIsBuiltin(screen) ? FF_DISPLAY_TYPE_BUILTIN : FF_DISPLAY_TYPE_EXTERNAL, CGDisplayIsMain(screen), - (uint64_t)screen, + (uint64_t) screen, physicalWidth, physicalHeight, - "CoreGraphics" - ); - if (display) - { - #ifndef MAC_OS_X_VERSION_10_11 + "CoreGraphics"); + if (display) { +#ifndef MAC_OS_X_VERSION_10_11 FF_CFTYPE_AUTO_RELEASE CFStringRef pe = CGDisplayModeCopyPixelEncoding(mode); - if (pe) display->bitDepth = (uint8_t) (CFStringGetLength(pe) - CFStringFind(pe, CFSTR("B"), 0).location); - #else + if (pe) { + display->bitDepth = (uint8_t) (CFStringGetLength(pe) - CFStringFind(pe, CFSTR("B"), 0).location); + } +#else // https://stackoverflow.com/a/33519316/9976392 // Also shitty, but better than parsing `CFCopyDescription(mode)` - CFDictionaryRef dict = (CFDictionaryRef) *((int64_t *)mode + 2); - if (CFGetTypeID(dict) == CFDictionaryGetTypeID()) - { + CFDictionaryRef dict = (CFDictionaryRef) * ((int64_t*) mode + 2); + if (CFGetTypeID(dict) == CFDictionaryGetTypeID()) { int32_t bitDepth; ffCfDictGetInt(dict, kCGDisplayBitsPerSample, &bitDepth); display->bitDepth = (uint8_t) bitDepth; } - #endif +#endif - if (display->type == FF_DISPLAY_TYPE_BUILTIN && displayInfo) + if (display->type == FF_DISPLAY_TYPE_BUILTIN && displayInfo) { display->hdrStatus = CFDictionaryContainsKey(displayInfo, CFSTR("ReferencePeakHDRLuminance")) - ? FF_DISPLAY_HDR_STATUS_SUPPORTED : FF_DISPLAY_HDR_STATUS_UNSUPPORTED; - #ifdef MAC_OS_X_VERSION_10_15 - else if (CoreDisplay_Display_SupportsHDRMode) - { - if (CoreDisplay_Display_SupportsHDRMode(screen)) - { - display->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; - if (CoreDisplay_Display_IsHDRModeEnabled && CoreDisplay_Display_IsHDRModeEnabled(screen)) - display->hdrStatus = FF_DISPLAY_HDR_STATUS_ENABLED; - } - else - display->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; + ? FF_DISPLAY_HDR_STATUS_SUPPORTED + : FF_DISPLAY_HDR_STATUS_UNSUPPORTED; } - #endif +#ifdef MAC_OS_X_VERSION_10_15 + else if (CoreDisplay_Display_SupportsHDRMode) { + if (CoreDisplay_Display_SupportsHDRMode(screen)) { + display->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; + if (CoreDisplay_Display_IsHDRModeEnabled && CoreDisplay_Display_IsHDRModeEnabled(screen)) { + display->hdrStatus = FF_DISPLAY_HDR_STATUS_ENABLED; + } + } else { + display->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; + } + } +#endif display->serial = CGDisplaySerialNumber(screen); - if (displayInfo) - { + if (displayInfo) { int value; - if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayYearOfManufacture), &value) == NULL) + if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayYearOfManufacture), &value) == NULL) { display->manufactureYear = (uint16_t) value; - if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayWeekOfManufacture), &value) == NULL) + } + if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayWeekOfManufacture), &value) == NULL) { display->manufactureWeek = (uint16_t) value; + } } } CGDisplayModeRelease(mode); @@ -187,12 +184,10 @@ static void detectDisplays(FFDisplayServerResult* ds) } } -void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) -{ +void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) { { FF_CFTYPE_AUTO_RELEASE CFMachPortRef port = CGWindowServerCreateServerPort(); - if (port) - { + if (port) { ffStrbufSetStatic(&ds->wmProcessName, "WindowServer"); ffStrbufSetStatic(&ds->wmPrettyName, "Quartz Compositor"); } diff --git a/src/detection/displayserver/displayserver_haiku.cpp b/src/detection/displayserver/displayserver_haiku.cpp index 05ad64f41..c1ddaf697 100644 --- a/src/detection/displayserver/displayserver_haiku.cpp +++ b/src/detection/displayserver/displayserver_haiku.cpp @@ -9,38 +9,37 @@ extern "C" { extern "C" void ffConnectDisplayServerImpl(FFDisplayServerResult* ds); -static void detectDisplays(FFDisplayServerResult* ds) -{ +static void detectDisplays(FFDisplayServerResult* ds) { // We need a valid be_app to query the app_server here. BApplication app("application/x-vnd.fastfetch-cli-fastfetch"); BScreen s{}; // default screen is the main one bool main = true; - do - { - if (!s.IsValid()) + do { + if (!s.IsValid()) { continue; + } display_mode mode; - if (s.GetMode(&mode) != B_OK) + if (s.GetMode(&mode) != B_OK) { continue; + } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateA(128); monitor_info monitor; // WARNING: This is experimental new Haiku API status_t err = s.GetMonitorInfo(&monitor); - if (err == B_OK) - { + if (err == B_OK) { ffStrbufSetF(&name, "%s %s", monitor.vendor, monitor.name); ffStrbufTrimRightSpace(&name); } uint32_t width = (uint32_t) s.Frame().Width() + 1; - uint32_t height = (uint32_t) (uint32_t)s.Frame().Height() + 1; + uint32_t height = (uint32_t) (uint32_t) s.Frame().Height() + 1; FFDisplayResult* res = ffdsAppendDisplay(ds, width, height, - (double)mode.timing.pixel_clock * 1000 / (mode.timing.v_total * mode.timing.h_total), + (double) mode.timing.pixel_clock * 1000 / (mode.timing.v_total * mode.timing.h_total), 0, 0, 0, @@ -52,10 +51,8 @@ static void detectDisplays(FFDisplayServerResult* ds) (uint64_t) s.ID().id, 0, 0, - "BScreen" - ); - if (err == B_OK) - { + "BScreen"); + if (err == B_OK) { res->manufactureWeek = monitor.produced.week; res->manufactureYear = monitor.produced.year; } @@ -65,8 +62,7 @@ static void detectDisplays(FFDisplayServerResult* ds) return; } -void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) -{ +void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) { ffStrbufSetStatic(&ds->wmProcessName, "app_server"); ffStrbufSetStatic(&ds->wmPrettyName, "Application Server"); ffStrbufSetStatic(&ds->dePrettyName, "Application Kit"); diff --git a/src/detection/displayserver/displayserver_windows.c b/src/detection/displayserver/displayserver_windows.c index 8dd1049c9..98cf572fa 100644 --- a/src/detection/displayserver/displayserver_windows.c +++ b/src/detection/displayserver/displayserver_windows.c @@ -6,10 +6,10 @@ #include #include -static inline void freeArgBuffer(FFArgBuffer* buffer) -{ - if (buffer->data) +static inline void freeArgBuffer(FFArgBuffer* buffer) { + if (buffer->data) { free(buffer->data); + } buffer->data = NULL; buffer->length = 0; } @@ -19,23 +19,20 @@ static inline void freeArgBuffer(FFArgBuffer* buffer) BOOL WINAPI IsThreadDesktopComposited(); BOOL WINAPI GetDpiForMonitorInternal(HMONITOR hmonitor, MONITOR_DPI_TYPE dpiType, UINT* dpiX, UINT* dpiY); -static void detectDisplays(FFDisplayServerResult* ds) -{ +static void detectDisplays(FFDisplayServerResult* ds) { DISPLAYCONFIG_PATH_INFO paths[128]; uint32_t pathCount = ARRAY_SIZE(paths); DISPLAYCONFIG_MODE_INFO modes[256]; uint32_t modeCount = ARRAY_SIZE(modes); if (QueryDisplayConfig( - QDC_ONLY_ACTIVE_PATHS, - &pathCount, - paths, - &modeCount, - modes, - NULL) == ERROR_SUCCESS) - { - for (uint32_t i = 0; i < pathCount; ++i) - { + QDC_ONLY_ACTIVE_PATHS, + &pathCount, + paths, + &modeCount, + modes, + NULL) == ERROR_SUCCESS) { + for (uint32_t i = 0; i < pathCount; ++i) { const DISPLAYCONFIG_PATH_INFO* path = &paths[i]; const DISPLAYCONFIG_SOURCE_MODE* sourceMode = &modes[path->sourceInfo.modeInfoIdx].sourceMode; @@ -51,17 +48,16 @@ static void detectDisplays(FFDisplayServerResult* ds) }, }; FF_AUTO_FREE_ARG_BUFFER FFArgBuffer edid = {}; - if(DisplayConfigGetDeviceInfo(&targetName.header) == ERROR_SUCCESS) - { + if (DisplayConfigGetDeviceInfo(&targetName.header) == ERROR_SUCCESS) { wchar_t regPath[256] = L"SYSTEM\\CurrentControlSet\\Enum"; wchar_t* pRegPath = regPath + strlen("SYSTEM\\CurrentControlSet\\Enum"); wchar_t* pDevPath = targetName.monitorDevicePath + strlen("\\\\?"); - while (*pDevPath && *pDevPath != L'{') - { - if (*pDevPath == L'#') + while (*pDevPath && *pDevPath != L'{') { + if (*pDevPath == L'#') { *pRegPath = L'\\'; - else + } else { *pRegPath = *pDevPath; + } ++pRegPath; ++pDevPath; assert(pRegPath < regPath + ARRAY_SIZE(regPath) + strlen("Device Parameters")); @@ -71,18 +67,14 @@ static void detectDisplays(FFDisplayServerResult* ds) FF_AUTO_CLOSE_FD HANDLE hKey = NULL; if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regPath, &hKey, NULL) && ffRegReadData(hKey, L"EDID", &edid, NULL) && - ffEdidIsValid(edid.data, edid.length)) - { + ffEdidIsValid(edid.data, edid.length)) { ffEdidGetName(edid.data, &name); ffEdidGetPhysicalSize(edid.data, &physicalWidth, &physicalHeight); - } - else - { + } else { edid.length = 0; - if (targetName.flags.friendlyNameFromEdid) + if (targetName.flags.friendlyNameFromEdid) { ffStrbufSetWS(&name, targetName.monitorFriendlyDeviceName); - else - { + } else { ffStrbufSetWS(&name, targetName.monitorDevicePath); ffStrbufSubstrAfterFirstC(&name, '#'); ffStrbufSubstrBeforeFirstC(&name, '#'); @@ -93,12 +85,19 @@ static void detectDisplays(FFDisplayServerResult* ds) uint32_t width = sourceMode->width; uint32_t height = sourceMode->height; uint32_t rotation; - switch (path->targetInfo.rotation) - { - case DISPLAYCONFIG_ROTATION_ROTATE90: rotation = 90; break; - case DISPLAYCONFIG_ROTATION_ROTATE180: rotation = 180; break; - case DISPLAYCONFIG_ROTATION_ROTATE270: rotation = 270; break; - default: rotation = 0; break; + switch (path->targetInfo.rotation) { + case DISPLAYCONFIG_ROTATION_ROTATE90: + rotation = 90; + break; + case DISPLAYCONFIG_ROTATION_ROTATE180: + rotation = 180; + break; + case DISPLAYCONFIG_ROTATION_ROTATE270: + rotation = 270; + break; + default: + rotation = 0; + break; } DISPLAYCONFIG_TARGET_PREFERRED_MODE preferredMode = { @@ -107,34 +106,31 @@ static void detectDisplays(FFDisplayServerResult* ds) .size = sizeof(preferredMode), .adapterId = path->targetInfo.adapterId, .id = path->targetInfo.id, - } - }; + }}; double preferredRefreshRate = 0; - if (DisplayConfigGetDeviceInfo(&preferredMode.header) == ERROR_SUCCESS) - { + if (DisplayConfigGetDeviceInfo(&preferredMode.header) == ERROR_SUCCESS) { DISPLAYCONFIG_RATIONAL freq = preferredMode.targetMode.targetVideoSignalInfo.vSyncFreq; preferredRefreshRate = freq.Numerator / (double) freq.Denominator; } uint32_t systemDpi = 0; - HMONITOR hMonitor = MonitorFromPoint(*(POINT*)&sourceMode->position, MONITOR_DEFAULTTONULL); - if (hMonitor) - { + HMONITOR hMonitor = MonitorFromPoint(*(POINT*) &sourceMode->position, MONITOR_DEFAULTTONULL); + if (hMonitor) { UINT ignored; GetDpiForMonitorInternal(hMonitor, MDT_EFFECTIVE_DPI, &systemDpi, &ignored); } - if (systemDpi == 0) - { + if (systemDpi == 0) { HDC hdc = GetDC(NULL); systemDpi = (uint32_t) GetDeviceCaps(hdc, LOGPIXELSX); - if (systemDpi == 0) systemDpi = 96; + if (systemDpi == 0) { + systemDpi = 96; + } ReleaseDC(NULL, hdc); } if (path->targetInfo.rotation == DISPLAYCONFIG_ROTATION_ROTATE90 || - path->targetInfo.rotation == DISPLAYCONFIG_ROTATION_ROTATE270) - { + path->targetInfo.rotation == DISPLAYCONFIG_ROTATION_ROTATE270) { uint32_t temp = width; width = height; height = temp; @@ -150,78 +146,66 @@ static void detectDisplays(FFDisplayServerResult* ds) preferredRefreshRate, rotation, &name, - path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER ? FF_DISPLAY_TYPE_UNKNOWN : - path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL || - path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EMBEDDED || - path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EMBEDDED - ? FF_DISPLAY_TYPE_BUILTIN : FF_DISPLAY_TYPE_EXTERNAL, + path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER ? FF_DISPLAY_TYPE_UNKNOWN : path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL || path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EMBEDDED || path->targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EMBEDDED ? FF_DISPLAY_TYPE_BUILTIN + : FF_DISPLAY_TYPE_EXTERNAL, sourceMode->position.x == 0 && sourceMode->position.y == 0, (uintptr_t) hMonitor, physicalWidth, physicalHeight, - "GDI" - ); + "GDI"); - if (display) - { + if (display) { DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2 advColorInfo2 = { .header = { .type = DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO_2, .size = sizeof(advColorInfo2), .adapterId = path->targetInfo.adapterId, .id = path->targetInfo.id, - } - }; - if (DisplayConfigGetDeviceInfo(&advColorInfo2.header) == ERROR_SUCCESS) - { - if (advColorInfo2.highDynamicRangeUserEnabled) + }}; + if (DisplayConfigGetDeviceInfo(&advColorInfo2.header) == ERROR_SUCCESS) { + if (advColorInfo2.highDynamicRangeUserEnabled) { display->hdrStatus = FF_DISPLAY_HDR_STATUS_ENABLED; - else if (advColorInfo2.highDynamicRangeSupported) + } else if (advColorInfo2.highDynamicRangeSupported) { display->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; - else + } else { display->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; + } display->bitDepth = (uint8_t) advColorInfo2.bitsPerColorChannel; - } - else - { + } else { DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO advColorInfo = { .header = { .type = DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, .size = sizeof(advColorInfo), .adapterId = path->targetInfo.adapterId, .id = path->targetInfo.id, - } - }; - if (DisplayConfigGetDeviceInfo(&advColorInfo.header) == ERROR_SUCCESS) - { - if (advColorInfo.advancedColorEnabled) + }}; + if (DisplayConfigGetDeviceInfo(&advColorInfo.header) == ERROR_SUCCESS) { + if (advColorInfo.advancedColorEnabled) { display->hdrStatus = FF_DISPLAY_HDR_STATUS_ENABLED; - else if (advColorInfo.advancedColorSupported) + } else if (advColorInfo.advancedColorSupported) { display->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; - else + } else { display->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; + } display->bitDepth = (uint8_t) advColorInfo.bitsPerColorChannel; - } - else + } else { display->hdrStatus = FF_DISPLAY_HDR_STATUS_UNKNOWN; + } } - if (edid.length > 0) + if (edid.length > 0) { ffEdidGetSerialAndManufactureDate(edid.data, &display->serial, &display->manufactureYear, &display->manufactureWeek); + } display->drrStatus = path->flags & DISPLAYCONFIG_PATH_BOOST_REFRESH_RATE ? FF_DISPLAY_DRR_STATUS_ENABLED : FF_DISPLAY_DRR_STATUS_DISABLED; } } } } -void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) -{ - if (IsThreadDesktopComposited()) - { +void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) { + if (IsThreadDesktopComposited()) { ffStrbufSetStatic(&ds->wmProcessName, "dwm.exe"); ffStrbufSetStatic(&ds->wmPrettyName, "Desktop Window Manager"); - } - else - { + } else { // `explorer.exe` only provides a subset of WM functions, as well as the taskbar and desktop icons. // While a window itself is drawn by kernel (GDI). Killing `explorer.exe` won't affect how windows are displayed generally. ffStrbufSetStatic(&ds->wmProcessName, "explorer.exe"); diff --git a/src/detection/displayserver/linux/common.c b/src/detection/displayserver/linux/common.c index ead84a112..cb33b80cd 100644 --- a/src/detection/displayserver/linux/common.c +++ b/src/detection/displayserver/linux/common.c @@ -1,16 +1,16 @@ #include "displayserver_linux.h" #include "common/stringUtils.h" -FFDisplayType ffdsGetDisplayType(const char* name) -{ - if(ffStrStartsWith(name, "eDP-") || ffStrStartsWith(name, "LVDS-")) +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-")) + } 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; } diff --git a/src/detection/displayserver/linux/displayserver_linux.c b/src/detection/displayserver/linux/displayserver_linux.c index 62b3d1fb3..c4aef1404 100644 --- a/src/detection/displayserver/linux/displayserver_linux.c +++ b/src/detection/displayserver/linux/displayserver_linux.c @@ -3,95 +3,89 @@ #include "common/stringUtils.h" #ifdef __FreeBSD__ - #include "common/settings.h" +# include "common/settings.h" #endif -static void getWMProtocolNameFromEnv(FFDisplayServerResult* result) -{ +static void getWMProtocolNameFromEnv(FFDisplayServerResult* result) { const char* env = getenv("XDG_SESSION_TYPE"); - if(env) - { - if(ffStrEqualsIgnCase(env, "wayland")) + if (env) { + if (ffStrEqualsIgnCase(env, "wayland")) { ffStrbufSetS(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND); - else if(ffStrEqualsIgnCase(env, "x11") || ffStrEqualsIgnCase(env, "xorg")) + } else if (ffStrEqualsIgnCase(env, "x11") || ffStrEqualsIgnCase(env, "xorg")) { ffStrbufSetS(&result->wmProtocolName, FF_WM_PROTOCOL_X11); - else if(ffStrEqualsIgnCase(env, "tty")) + } else if (ffStrEqualsIgnCase(env, "tty")) { ffStrbufSetS(&result->wmProtocolName, FF_WM_PROTOCOL_TTY); - else + } else { ffStrbufSetS(&result->wmProtocolName, env); + } return; } - if(getenv("WAYLAND_DISPLAY") != NULL || getenv("WAYLAND_SOCKET") != NULL) - { + if (getenv("WAYLAND_DISPLAY") != NULL || getenv("WAYLAND_SOCKET") != NULL) { ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND); return; } - if(getenv("DISPLAY") != NULL) // XWayland also set this + if (getenv("DISPLAY") != NULL) // XWayland also set this { ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_X11); return; } env = getenv("TERM"); - if(ffStrSet(env) && ffStrEqualsIgnCase(env, "linux")) - { + if (ffStrSet(env) && ffStrEqualsIgnCase(env, "linux")) { ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_TTY); return; } } -void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) -{ - if (instance.config.general.dsForceDrm == FF_DS_FORCE_DRM_TYPE_FALSE) - { - //We try wayland as our preferred display server, as it supports the most features. - //This method can't detect the name of our WM / DE +void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) { + if (instance.config.general.dsForceDrm == FF_DS_FORCE_DRM_TYPE_FALSE) { + // We try wayland as our preferred display server, as it supports the most features. + // This method can't detect the name of our WM / DE ffdsConnectWayland(ds); - //Try the x11 libs, from most feature rich to least. - //We use the display list to detect if a connection is needed. - //They respect wmProtocolName, and only detect display if it is set. - if(ds->displays.length == 0) + // Try the x11 libs, from most feature rich to least. + // We use the display list to detect if a connection is needed. + // They respect wmProtocolName, and only detect display if it is set. + if (ds->displays.length == 0) { ffdsConnectXcbRandr(ds); + } - if(ds->displays.length == 0) + if (ds->displays.length == 0) { ffdsConnectXrandr(ds); + } } - //This display detection method is display server independent. - //Use it if all connections failed - if(ds->displays.length == 0) + // This display detection method is display server independent. + // Use it if all connections failed + if (ds->displays.length == 0) { ffdsConnectDrm(ds); + } - #ifdef __FreeBSD__ - if(ds->displays.length == 0) - { +#ifdef __FreeBSD__ + if (ds->displays.length == 0) { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (ffSettingsGetFreeBSDKenv("screen.width", &buf)) - { + if (ffSettingsGetFreeBSDKenv("screen.width", &buf)) { uint32_t width = (uint32_t) ffStrbufToUInt(&buf, 0); - if (width) - { + if (width) { ffStrbufClear(&buf); - if (ffSettingsGetFreeBSDKenv("screen.height", &buf)) - { + if (ffSettingsGetFreeBSDKenv("screen.height", &buf)) { uint32_t height = (uint32_t) ffStrbufToUInt(&buf, 0); ffdsAppendDisplay(ds, width, height, 0, 0, 0, 0, 0, 0, NULL, FF_DISPLAY_TYPE_UNKNOWN, false, 0, 0, 0, "kenv"); } } } } - #endif +#endif - if (ds->wmProtocolName.length == 0) + if (ds->wmProtocolName.length == 0) { getWMProtocolNameFromEnv(ds); + } - if(!ffStrbufEqualS(&ds->wmProtocolName, FF_WM_PROTOCOL_TTY)) - { - //This fills in missing information about WM / DE by using env vars and iterating processes + if (!ffStrbufEqualS(&ds->wmProtocolName, FF_WM_PROTOCOL_TTY)) { + // This fills in missing information about WM / DE by using env vars and iterating processes ffdsDetectWMDE(ds); } } diff --git a/src/detection/displayserver/linux/drm.c b/src/detection/displayserver/linux/drm.c index ddb80ec93..466094624 100644 --- a/src/detection/displayserver/linux/drm.c +++ b/src/detection/displayserver/linux/drm.c @@ -4,15 +4,15 @@ #include "common/stringUtils.h" #ifdef __linux__ -#include +# include -static const char* drmParseSysfs(FFDisplayServerResult* result) -{ +static const char* drmParseSysfs(FFDisplayServerResult* result) { const char* drmDirPath = "/sys/class/drm/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(drmDirPath); - if(dirp == NULL) + if (dirp == NULL) { return "opendir(drmDirPath) failed"; + } FF_STRBUF_AUTO_DESTROY drmDir = ffStrbufCreateA(64); ffStrbufAppendS(&drmDir, drmDirPath); @@ -20,10 +20,10 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) uint32_t drmDirLength = drmDir.length; struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } ffStrbufAppendS(&drmDir, entry->d_name); uint32_t drmDirWithDnameLength = drmDir.length; @@ -31,16 +31,16 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) char buf; ffStrbufAppendS(&drmDir, "/enabled"); if (ffReadFileData(drmDir.chars, sizeof(buf), &buf) <= 0 || buf != 'e') { - /* read failed or enabled != "enabled" */ - ffStrbufSubstrBefore(&drmDir, drmDirWithDnameLength); - ffStrbufAppendS(&drmDir, "/status"); - buf = 'd'; - ffReadFileData(drmDir.chars, sizeof(buf), &buf); - if (buf != 'c') { - /* read failed or status != "connected" */ - ffStrbufSubstrBefore(&drmDir, drmDirLength); - continue; - } + /* read failed or enabled != "enabled" */ + ffStrbufSubstrBefore(&drmDir, drmDirWithDnameLength); + ffStrbufAppendS(&drmDir, "/status"); + buf = 'd'; + ffReadFileData(drmDir.chars, sizeof(buf), &buf); + if (buf != 'c') { + /* read failed or status != "connected" */ + ffStrbufSubstrBefore(&drmDir, drmDirLength); + continue; + } } unsigned width = 0, height = 0, physicalWidth = 0, physicalHeight = 0; @@ -51,29 +51,26 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) ffStrbufAppendS(&drmDir, "/edid"); const char* plainName = entry->d_name; - if (ffStrStartsWith(plainName, "card")) - { + if (ffStrStartsWith(plainName, "card")) { const char* tmp = strchr(plainName + strlen("card"), '-'); - if (tmp) plainName = tmp + 1; + if (tmp) { + plainName = tmp + 1; + } } uint8_t edidData[512]; ssize_t edidLength = ffReadFileData(drmDir.chars, ARRAY_SIZE(edidData), edidData); - if(edidLength <= 0 || edidLength % 128 != 0) - { + if (edidLength <= 0 || edidLength % 128 != 0) { edidLength = 0; ffStrbufSubstrBefore(&drmDir, drmDirWithDnameLength); ffStrbufAppendS(&drmDir, "/modes"); char modes[32]; - if (ffReadFileData(drmDir.chars, ARRAY_SIZE(modes), modes) >= 3) - { + if (ffReadFileData(drmDir.chars, ARRAY_SIZE(modes), modes) >= 3) { sscanf(modes, "%ux%u", &width, &height); ffStrbufAppendS(&name, plainName); } - } - else - { + } else { ffEdidGetName(edidData, &name); ffEdidGetPreferredResolutionAndRefreshRate(edidData, &width, &height, &refreshRate); ffEdidGetPhysicalSize(edidData, &physicalWidth, &physicalHeight); @@ -81,10 +78,12 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) FFDisplayResult* item = ffdsAppendDisplay( result, - width, height, + width, + height, refreshRate, 0, - 0, 0, + 0, + 0, 0, 0, &name, @@ -93,10 +92,8 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) 0, physicalWidth, physicalHeight, - "sysfs-drm" - ); - if (item && edidLength) - { + "sysfs-drm"); + 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); } @@ -110,74 +107,72 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) #ifdef FF_HAVE_DRM -#include "common/library.h" +# include "common/library.h" -#include -#include -#include +# include +# include +# include // https://gitlab.freedesktop.org/mesa/drm/-/blob/main/xf86drmMode.c#L1785 // It's not supported on Ubuntu 20.04 -static inline const char* drmType2Name(uint32_t connector_type) -{ +static inline const char* drmType2Name(uint32_t connector_type) { /* Keep the strings in sync with the kernel's drm_connector_enum_list in * drm_connector.c. */ - switch (connector_type) - { - case DRM_MODE_CONNECTOR_Unknown: - return "Unknown"; - case DRM_MODE_CONNECTOR_VGA: - return "VGA"; - case DRM_MODE_CONNECTOR_DVII: - return "DVI-I"; - case DRM_MODE_CONNECTOR_DVID: - return "DVI-D"; - case DRM_MODE_CONNECTOR_DVIA: - return "DVI-A"; - case DRM_MODE_CONNECTOR_Composite: - return "Composite"; - case DRM_MODE_CONNECTOR_SVIDEO: - return "SVIDEO"; - case DRM_MODE_CONNECTOR_LVDS: - return "LVDS"; - case DRM_MODE_CONNECTOR_Component: - return "Component"; - case DRM_MODE_CONNECTOR_9PinDIN: - return "DIN"; - case DRM_MODE_CONNECTOR_DisplayPort: - return "DP"; - case DRM_MODE_CONNECTOR_HDMIA: - return "HDMI-A"; - case DRM_MODE_CONNECTOR_HDMIB: - return "HDMI-B"; - case DRM_MODE_CONNECTOR_TV: - return "TV"; - case DRM_MODE_CONNECTOR_eDP: - return "eDP"; - case DRM_MODE_CONNECTOR_VIRTUAL: - return "Virtual"; - case DRM_MODE_CONNECTOR_DSI: - return "DSI"; - case DRM_MODE_CONNECTOR_DPI: - return "DPI"; - case DRM_MODE_CONNECTOR_WRITEBACK: - return "Writeback"; - case 19 /*DRM_MODE_CONNECTOR_SPI*/: - return "SPI"; - case 20 /*DRM_MODE_CONNECTOR_USB*/: - return "USB"; - default: - return "Unsupported"; + switch (connector_type) { + case DRM_MODE_CONNECTOR_Unknown: + return "Unknown"; + case DRM_MODE_CONNECTOR_VGA: + return "VGA"; + case DRM_MODE_CONNECTOR_DVII: + return "DVI-I"; + case DRM_MODE_CONNECTOR_DVID: + return "DVI-D"; + case DRM_MODE_CONNECTOR_DVIA: + return "DVI-A"; + case DRM_MODE_CONNECTOR_Composite: + return "Composite"; + case DRM_MODE_CONNECTOR_SVIDEO: + return "SVIDEO"; + case DRM_MODE_CONNECTOR_LVDS: + return "LVDS"; + case DRM_MODE_CONNECTOR_Component: + return "Component"; + case DRM_MODE_CONNECTOR_9PinDIN: + return "DIN"; + case DRM_MODE_CONNECTOR_DisplayPort: + return "DP"; + case DRM_MODE_CONNECTOR_HDMIA: + return "HDMI-A"; + case DRM_MODE_CONNECTOR_HDMIB: + return "HDMI-B"; + case DRM_MODE_CONNECTOR_TV: + return "TV"; + case DRM_MODE_CONNECTOR_eDP: + return "eDP"; + case DRM_MODE_CONNECTOR_VIRTUAL: + return "Virtual"; + case DRM_MODE_CONNECTOR_DSI: + return "DSI"; + case DRM_MODE_CONNECTOR_DPI: + return "DPI"; + case DRM_MODE_CONNECTOR_WRITEBACK: + return "Writeback"; + case 19 /*DRM_MODE_CONNECTOR_SPI*/: + return "SPI"; + case 20 /*DRM_MODE_CONNECTOR_USB*/: + return "USB"; + default: + return "Unsupported"; } } -FF_MAYBE_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edidData, ssize_t* edidLength) -{ +FF_MAYBE_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edidData, ssize_t* edidLength) { const char* drmDirPath = "/sys/class/drm/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(drmDirPath); - if(dirp == NULL) + if (dirp == NULL) { return "opendir(drmDirPath) failed"; + } FF_STRBUF_AUTO_DESTROY drmDir = ffStrbufCreateA(64); ffStrbufAppendS(&drmDir, drmDirPath); @@ -185,10 +180,10 @@ FF_MAYBE_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* uint32_t drmDirLength = drmDir.length; struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } ffStrbufAppendS(&drmDir, entry->d_name); uint32_t drmDirWithDnameLength = drmDir.length; @@ -197,8 +192,7 @@ FF_MAYBE_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* ffStrbufAppendS(&drmDir, "/connector_id"); ffReadFileData(drmDir.chars, ARRAY_SIZE(connectorId), connectorId); - if (strtoul(connectorId, NULL, 10) != connId) - { + if (strtoul(connectorId, NULL, 10) != connId) { ffStrbufSubstrBefore(&drmDir, drmDirLength); continue; } @@ -212,8 +206,7 @@ FF_MAYBE_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* return "Failed to match connector ID"; } -static const char* drmConnectLibdrm(FFDisplayServerResult* result) -{ +static const char* drmConnectLibdrm(FFDisplayServerResult* result) { FF_LIBRARY_LOAD_MESSAGE(libdrm, "libdrm" FF_LIBRARY_EXTENSION, 2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libdrm, drmGetDevices) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libdrm, drmModeGetResources) @@ -234,64 +227,62 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) drmDevice* devices[64]; int nDevices = ffdrmGetDevices(devices, ARRAY_SIZE(devices)); - if (nDevices <= 0) + if (nDevices <= 0) { return "drmGetDevices() failed"; + } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); - for (int iDev = 0; iDev < nDevices; ++iDev) - { + for (int iDev = 0; iDev < nDevices; ++iDev) { drmDevice* dev = devices[iDev]; - if (!(dev->available_nodes & (1 << DRM_NODE_PRIMARY))) + if (!(dev->available_nodes & (1 << DRM_NODE_PRIMARY))) { continue; + } const char* path = dev->nodes[DRM_NODE_PRIMARY]; - #if __linux__ +# if __linux__ ffStrbufSetF(&name, "/sys/class/drm/%s/device/power/runtime_status", strrchr(path, '/') + 1); char buffer[8] = ""; - if (ffReadFileData(name.chars, strlen("suspend"), buffer) > 0 && ffStrStartsWith(buffer, "suspend")) + if (ffReadFileData(name.chars, strlen("suspend"), buffer) > 0 && ffStrStartsWith(buffer, "suspend")) { continue; - #endif + } +# endif FF_AUTO_CLOSE_FD int primaryFd = open(path, O_RDWR | O_CLOEXEC); - if (primaryFd < 0) + if (primaryFd < 0) { continue; + } drmModeRes* res = ffdrmModeGetResources(primaryFd); - if (!res) + if (!res) { continue; + } - for (int iConn = 0; iConn < res->count_connectors; ++iConn) - { + for (int iConn = 0; iConn < res->count_connectors; ++iConn) { drmModeConnector* conn = ffdrmModeGetConnectorCurrent(primaryFd, res->connectors[iConn]); - if (!conn) + if (!conn) { continue; + } - if (conn->connection != DRM_MODE_DISCONNECTED) - { + if (conn->connection != DRM_MODE_DISCONNECTED) { drmModeEncoder* encoder = ffdrmModeGetEncoder(primaryFd, conn->encoder_id); uint32_t width = 0, height = 0, refreshRate = 0; uint8_t bitDepth = 0; - if (encoder) - { + if (encoder) { drmModeCrtc* crtc = ffdrmModeGetCrtc(primaryFd, encoder->crtc_id); - if (crtc) - { + if (crtc) { width = crtc->mode.hdisplay; height = crtc->mode.vdisplay; refreshRate = crtc->mode.vrefresh; - if (refreshRate == 0) - { + if (refreshRate == 0) { // There are weird cases that we can't get the refresh rate from the CRTC but from the modes - for (int iMode = 0; iMode < conn->count_modes; ++iMode) - { + for (int iMode = 0; iMode < conn->count_modes; ++iMode) { drmModeModeInfo* mode = &conn->modes[iMode]; - if (mode->clock == crtc->mode.clock && mode->htotal == crtc->mode.htotal) - { + if (mode->clock == crtc->mode.clock && mode->htotal == crtc->mode.htotal) { refreshRate = mode->vrefresh; break; } @@ -299,8 +290,7 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) } drmModeFBPtr fb = ffdrmModeGetFB(primaryFd, crtc->buffer_id); - if (fb) - { + if (fb) { bitDepth = (uint8_t) (fb->depth / 3); ffdrmModeFreeFB(fb); } @@ -313,12 +303,10 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) uint32_t preferredWidth = 0, preferredHeight = 0, preferredRefreshRate = 0; - for (int iMode = 0; iMode < conn->count_modes; ++iMode) - { + for (int iMode = 0; iMode < conn->count_modes; ++iMode) { drmModeModeInfo* mode = &conn->modes[iMode]; - if (mode->type & DRM_MODE_TYPE_PREFERRED) - { + if (mode->type & DRM_MODE_TYPE_PREFERRED) { preferredWidth = mode->hdisplay; preferredHeight = mode->vdisplay; preferredRefreshRate = mode->vrefresh; @@ -328,39 +316,35 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) // NVIDIA DRM driver seems incomplete and conn->encoder_id == 0 // Assume preferred resolution is used as what we do in drmParseSys - if (width == 0 || height == 0) - { + if (width == 0 || height == 0) { width = preferredWidth; height = preferredHeight; refreshRate = preferredRefreshRate; } - ffStrbufClear(&name); uint16_t myear = 0, mweak = 0; uint32_t serial = 0; FFDisplayHdrStatus hdrStatus = FF_DISPLAY_HDR_STATUS_UNKNOWN; - for (int iProp = 0; iProp < conn->count_props; ++iProp) - { - drmModePropertyRes *prop = ffdrmModeGetProperty(primaryFd, conn->props[iProp]); - if (!prop) + for (int iProp = 0; iProp < conn->count_props; ++iProp) { + drmModePropertyRes* prop = ffdrmModeGetProperty(primaryFd, conn->props[iProp]); + if (!prop) { continue; + } uint32_t type = prop->flags & (DRM_MODE_PROP_LEGACY_TYPE | DRM_MODE_PROP_EXTENDED_TYPE); - if (type == DRM_MODE_PROP_BLOB && ffStrEquals(prop->name, "EDID")) - { + if (type == DRM_MODE_PROP_BLOB && ffStrEquals(prop->name, "EDID")) { drmModePropertyBlobPtr blob = NULL; - if (prop->count_blobs > 0 && prop->blob_ids != NULL) + if (prop->count_blobs > 0 && prop->blob_ids != NULL) { blob = ffdrmModeGetPropertyBlob(primaryFd, prop->blob_ids[0]); - else + } else { blob = ffdrmModeGetPropertyBlob(primaryFd, (uint32_t) conn->prop_values[iProp]); + } - if (blob) - { - if (blob->length >= 128) - { + if (blob) { + if (blob->length >= 128) { ffEdidGetName(blob->data, &name); hdrStatus = ffEdidGetHdrCompatible(blob->data, blob->length) ? FF_DISPLAY_HDR_STATUS_SUPPORTED : FF_DISPLAY_HDR_STATUS_UNSUPPORTED; ffEdidGetSerialAndManufactureDate(blob->data, &serial, &myear, &mweak); @@ -372,50 +356,49 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) ffdrmModeFreeProperty(prop); } - #if __linux__ - if (name.length == 0) - { +# if __linux__ + if (name.length == 0) { uint8_t edidData[512]; ssize_t edidLength = 0; drmGetEdidByConnId(conn->connector_id, edidData, &edidLength); - if (edidLength > 0 && edidLength % 128 == 0) - { + if (edidLength > 0 && edidLength % 128 == 0) { ffEdidGetName(edidData, &name); hdrStatus = ffEdidGetHdrCompatible(edidData, (uint32_t) edidLength) ? FF_DISPLAY_HDR_STATUS_SUPPORTED : FF_DISPLAY_HDR_STATUS_UNSUPPORTED; ffEdidGetSerialAndManufactureDate(edidData, &serial, &myear, &mweak); } } - #endif +# endif - if (name.length == 0) - { + if (name.length == 0) { const char* connectorTypeName = drmType2Name(conn->connector_type); - if (connectorTypeName == NULL) + if (connectorTypeName == NULL) { connectorTypeName = "Unknown"; + } ffStrbufSetF(&name, "%s-%d", connectorTypeName, iConn + 1); } FFDisplayResult* item = ffdsAppendDisplay(result, - width, height, + width, + height, refreshRate, 0, - preferredWidth, preferredHeight, + preferredWidth, + preferredHeight, preferredRefreshRate, 0, &name, conn->connector_type == DRM_MODE_CONNECTOR_eDP || conn->connector_type == DRM_MODE_CONNECTOR_LVDS ? FF_DISPLAY_TYPE_BUILTIN : conn->connector_type == DRM_MODE_CONNECTOR_HDMIA || conn->connector_type == DRM_MODE_CONNECTOR_HDMIB || conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort - ? FF_DISPLAY_TYPE_EXTERNAL : FF_DISPLAY_TYPE_UNKNOWN, + ? FF_DISPLAY_TYPE_EXTERNAL + : FF_DISPLAY_TYPE_UNKNOWN, false, conn->connector_id, conn->mmWidth, conn->mmHeight, - "libdrm" - ); + "libdrm"); - if (item) - { + if (item) { item->hdrStatus = hdrStatus; item->serial = serial; item->manufactureYear = myear; @@ -437,19 +420,18 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) #endif -const char* ffdsConnectDrm(FF_MAYBE_UNUSED FFDisplayServerResult* result) -{ - #ifdef FF_HAVE_DRM - if (instance.config.general.dsForceDrm != FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY) - { - if (drmConnectLibdrm(result) == NULL) +const char* ffdsConnectDrm(FF_MAYBE_UNUSED FFDisplayServerResult* result) { +#ifdef FF_HAVE_DRM + if (instance.config.general.dsForceDrm != FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY) { + if (drmConnectLibdrm(result) == NULL) { return NULL; + } } - #endif +#endif - #ifdef __linux__ +#ifdef __linux__ return drmParseSysfs(result); - #endif +#endif return "fastfetch was compiled without drm support"; } diff --git a/src/detection/displayserver/linux/wayland/global-output.c b/src/detection/displayserver/linux/wayland/global-output.c index 2e4574464..019f4e216 100644 --- a/src/detection/displayserver/linux/wayland/global-output.c +++ b/src/detection/displayserver/linux/wayland/global-output.c @@ -1,56 +1,49 @@ #ifdef FF_HAVE_WAYLAND -#include "wayland.h" -#include "common/stringUtils.h" -#include "xdg-output-unstable-v1-client-protocol.h" +# include "wayland.h" +# include "common/stringUtils.h" +# include "xdg-output-unstable-v1-client-protocol.h" -static void waylandOutputModeListener(void* data, FF_MAYBE_UNUSED struct wl_output* output, uint32_t flags, int32_t width, int32_t height, int32_t refreshRate) -{ +static void waylandOutputModeListener(void* data, FF_MAYBE_UNUSED struct wl_output* output, uint32_t flags, int32_t width, int32_t height, int32_t refreshRate) { WaylandDisplay* display = data; - if (flags & WL_OUTPUT_MODE_CURRENT) - { + if (flags & WL_OUTPUT_MODE_CURRENT) { display->width = width; display->height = height; display->refreshRate = refreshRate; } - if (flags & WL_OUTPUT_MODE_PREFERRED) - { + if (flags & WL_OUTPUT_MODE_PREFERRED) { display->preferredWidth = width; display->preferredHeight = height; display->preferredRefreshRate = refreshRate; } } -static void waylandOutputScaleListener(void* data, FF_MAYBE_UNUSED struct wl_output* output, int32_t scale) -{ +static void waylandOutputScaleListener(void* data, FF_MAYBE_UNUSED struct wl_output* output, int32_t scale) { WaylandDisplay* display = data; display->dpi = 96 * (uint32_t) scale; } -static void waylandOutputGeometryListener(void *data, - FF_MAYBE_UNUSED struct wl_output *output, +static void waylandOutputGeometryListener(void* data, + FF_MAYBE_UNUSED struct wl_output* output, FF_MAYBE_UNUSED int32_t x, FF_MAYBE_UNUSED int32_t y, int32_t physical_width, int32_t physical_height, FF_MAYBE_UNUSED int32_t subpixel, - FF_MAYBE_UNUSED const char *make, - FF_MAYBE_UNUSED const char *model, - int32_t transform) -{ + FF_MAYBE_UNUSED const char* make, + FF_MAYBE_UNUSED const char* model, + int32_t transform) { WaylandDisplay* display = data; display->physicalWidth = physical_width; display->physicalHeight = physical_height; display->transform = (enum wl_output_transform) transform; } -static void handleXdgLogicalSize(void *data, FF_MAYBE_UNUSED struct zxdg_output_v1 *_, int32_t width, FF_MAYBE_UNUSED int32_t height) -{ +static void handleXdgLogicalSize(void* data, FF_MAYBE_UNUSED struct zxdg_output_v1* _, int32_t width, FF_MAYBE_UNUSED int32_t height) { WaylandDisplay* display = data; // Seems the values are only useful when ractional scale is enabled - if (width < display->width) - { + if (width < display->width) { display->dpi = (uint32_t) (display->width * 96 / width); } } @@ -58,17 +51,16 @@ static void handleXdgLogicalSize(void *data, FF_MAYBE_UNUSED struct zxdg_output_ // Dirty hack for #477 // The order of these callbacks MUST follow `struct wl_output_listener` static void* outputListener[] = { - waylandOutputGeometryListener, // geometry - waylandOutputModeListener, // mode - stubListener, // done - waylandOutputScaleListener, // scale - ffWaylandOutputNameListener, // name + waylandOutputGeometryListener, // geometry + waylandOutputModeListener, // mode + stubListener, // done + waylandOutputScaleListener, // scale + ffWaylandOutputNameListener, // name ffWaylandOutputDescriptionListener, // description }; static_assert( sizeof(outputListener) >= sizeof(struct wl_output_listener), - "sizeof(outputListener) is too small. Please report it to fastfetch github issue" -); + "sizeof(outputListener) is too small. Please report it to fastfetch github issue"); static struct zxdg_output_v1_listener zxdgOutputListener = { .logical_position = (void*) stubListener, @@ -78,11 +70,11 @@ static struct zxdg_output_v1_listener zxdgOutputListener = { .description = (void*) ffWaylandOutputDescriptionListener, }; -const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) -{ +const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, wldata->ffwl_output_interface, version, name, wldata->ffwl_output_interface->name, version, NULL); - if(output == NULL) + if (output == NULL) { return "Failed to create wl_output"; + } WaylandDisplay display = { .parent = wldata, @@ -93,24 +85,20 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* .edidName = ffStrbufCreate(), }; - if (wldata->ffwl_proxy_add_listener(output, (void(**)(void)) &outputListener, &display) < 0) - { + if (wldata->ffwl_proxy_add_listener(output, (void (**)(void)) &outputListener, &display) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to add listener to wl_output"; } - if (wldata->ffwl_display_roundtrip(wldata->display) < 0) - { + if (wldata->ffwl_display_roundtrip(wldata->display) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to roundtrip wl_output"; } - if (wldata->zxdgOutputManager) - { + if (wldata->zxdgOutputManager) { struct wl_proxy* zxdgOutput = wldata->ffwl_proxy_marshal_constructor_versioned(wldata->zxdgOutputManager, ZXDG_OUTPUT_MANAGER_V1_GET_XDG_OUTPUT, &zxdg_output_v1_interface, version, NULL, output); - if (zxdgOutput) - { - wldata->ffwl_proxy_add_listener(zxdgOutput, (void(**)(void)) &zxdgOutputListener, &display); + if (zxdgOutput) { + wldata->ffwl_proxy_add_listener(zxdgOutput, (void (**)(void)) &zxdgOutputListener, &display); wldata->ffwl_display_roundtrip(wldata->display); wldata->ffwl_proxy_destroy(zxdgOutput); } @@ -118,8 +106,9 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* wldata->ffwl_proxy_destroy(output); - if(display.width <= 0 || display.height <= 0) + if (display.width <= 0 || display.height <= 0) { return "Failed to get display information from wl_output"; + } uint32_t rotation = ffWaylandHandleRotation(&display); @@ -136,23 +125,22 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* ? &display.edidName // Try ignoring `eDP-1-unknown`, where `unknown` is localized : display.description.length && !ffStrbufContain(&display.description, &display.name) - ? &display.description - : &display.name, + ? &display.description + : &display.name, display.type, false, display.id, (uint32_t) display.physicalWidth, (uint32_t) display.physicalHeight, - "wayland-global" - ); - if (item) - { - if (display.hdrSupported) + "wayland-global"); + if (item) { + if (display.hdrSupported) { item->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; - else if (display.hdrInfoAvailable) + } else if (display.hdrInfoAvailable) { item->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; - else + } else { item->hdrStatus = FF_DISPLAY_HDR_STATUS_UNKNOWN; + } item->manufactureYear = display.myear; item->manufactureWeek = display.mweek; @@ -166,11 +154,11 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* return NULL; } -const char* ffWaylandHandleZxdgOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) -{ +const char* ffWaylandHandleZxdgOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { struct wl_proxy* manager = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &zxdg_output_manager_v1_interface, version, name, zxdg_output_manager_v1_interface.name, version, NULL); - if(manager == NULL) + if (manager == NULL) { return "Failed to create zxdg_output_manager_v1"; + } wldata->zxdgOutputManager = manager; diff --git a/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h b/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h index 2ed227530..1b47d38af 100644 --- a/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h +++ b/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h @@ -7,7 +7,7 @@ #include #include -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -34,7 +34,7 @@ struct kde_output_device_registry_v2; struct kde_output_device_v2; #ifndef KDE_OUTPUT_DEVICE_REGISTRY_V2_INTERFACE -#define KDE_OUTPUT_DEVICE_REGISTRY_V2_INTERFACE +# define KDE_OUTPUT_DEVICE_REGISTRY_V2_INTERFACE /** * @page page_iface_kde_output_device_registry_v2 kde_output_device_registry_v2 * @section page_iface_kde_output_device_registry_v2_desc Description @@ -57,7 +57,7 @@ struct kde_output_device_v2; extern const struct wl_interface kde_output_device_registry_v2_interface; #endif #ifndef KDE_OUTPUT_DEVICE_V2_INTERFACE -#define KDE_OUTPUT_DEVICE_V2_INTERFACE +# define KDE_OUTPUT_DEVICE_V2_INTERFACE /** * @page page_iface_kde_output_device_v2 kde_output_device_v2 * @section page_iface_kde_output_device_v2_desc Description @@ -114,7 +114,7 @@ extern const struct wl_interface kde_output_device_registry_v2_interface; extern const struct wl_interface kde_output_device_v2_interface; #endif #ifndef KDE_OUTPUT_DEVICE_MODE_V2_INTERFACE -#define KDE_OUTPUT_DEVICE_MODE_V2_INTERFACE +# define KDE_OUTPUT_DEVICE_MODE_V2_INTERFACE /** * @page page_iface_kde_output_device_mode_v2 kde_output_device_mode_v2 * @section page_iface_kde_output_device_mode_v2_desc Description @@ -146,7 +146,7 @@ extern const struct wl_interface kde_output_device_mode_v2_interface; #endif #ifndef KDE_OUTPUT_DEVICE_REGISTRY_V2_ERROR_ENUM -#define KDE_OUTPUT_DEVICE_REGISTRY_V2_ERROR_ENUM +# define KDE_OUTPUT_DEVICE_REGISTRY_V2_ERROR_ENUM /** * @ingroup iface_kde_output_device_registry_v2 * kde_output_device_registry_v2 error values @@ -154,10 +154,10 @@ extern const struct wl_interface kde_output_device_mode_v2_interface; * These errors can be emitted in response to some requests. */ enum kde_output_device_registry_v2_error { - /** - * the registry was bound with an unsupported version - */ - KDE_OUTPUT_DEVICE_REGISTRY_V2_ERROR_UNSUPPORTED_VERSION = 0, + /** + * the registry was bound with an unsupported version + */ + KDE_OUTPUT_DEVICE_REGISTRY_V2_ERROR_UNSUPPORTED_VERSION = 0, }; #endif /* KDE_OUTPUT_DEVICE_REGISTRY_V2_ERROR_ENUM */ @@ -166,37 +166,38 @@ enum kde_output_device_registry_v2_error { * @struct kde_output_device_registry_v2_listener */ struct kde_output_device_registry_v2_listener { - /** - * no new output announcements - * - * This event is sent in response to the stop request. The - * compositor will immediately destroy the object after sending - * this event. - * @since 21 - */ - void (*finished)(void *data, - struct kde_output_device_registry_v2 *kde_output_device_registry_v2); - /** - * new available output - * - * This event is sent when a new output is connected or after - * binding this global to list all available outputs. - * @since 21 - */ - void (*output)(void *data, - struct kde_output_device_registry_v2 *kde_output_device_registry_v2, - struct kde_output_device_v2 *output); + /** + * no new output announcements + * + * This event is sent in response to the stop request. The + * compositor will immediately destroy the object after sending + * this event. + * @since 21 + */ + void (*finished)(void* data, + struct kde_output_device_registry_v2* kde_output_device_registry_v2); + /** + * new available output + * + * This event is sent when a new output is connected or after + * binding this global to list all available outputs. + * @since 21 + */ + void (*output)(void* data, + struct kde_output_device_registry_v2* kde_output_device_registry_v2, + struct kde_output_device_v2* output); }; /** * @ingroup iface_kde_output_device_registry_v2 */ static inline int -kde_output_device_registry_v2_add_listener(struct kde_output_device_registry_v2 *kde_output_device_registry_v2, - const struct kde_output_device_registry_v2_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) kde_output_device_registry_v2, - (void (**)(void)) listener, data); +kde_output_device_registry_v2_add_listener(struct kde_output_device_registry_v2* kde_output_device_registry_v2, + const struct kde_output_device_registry_v2_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) kde_output_device_registry_v2, + (void (**)(void)) listener, + data); } #define KDE_OUTPUT_DEVICE_REGISTRY_V2_STOP 0 @@ -217,29 +218,25 @@ kde_output_device_registry_v2_add_listener(struct kde_output_device_registry_v2 /** @ingroup iface_kde_output_device_registry_v2 */ static inline void -kde_output_device_registry_v2_set_user_data(struct kde_output_device_registry_v2 *kde_output_device_registry_v2, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) kde_output_device_registry_v2, user_data); +kde_output_device_registry_v2_set_user_data(struct kde_output_device_registry_v2* kde_output_device_registry_v2, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) kde_output_device_registry_v2, user_data); } /** @ingroup iface_kde_output_device_registry_v2 */ -static inline void * -kde_output_device_registry_v2_get_user_data(struct kde_output_device_registry_v2 *kde_output_device_registry_v2) -{ - return wl_proxy_get_user_data((struct wl_proxy *) kde_output_device_registry_v2); +static inline void* +kde_output_device_registry_v2_get_user_data(struct kde_output_device_registry_v2* kde_output_device_registry_v2) { + return wl_proxy_get_user_data((struct wl_proxy*) kde_output_device_registry_v2); } static inline uint32_t -kde_output_device_registry_v2_get_version(struct kde_output_device_registry_v2 *kde_output_device_registry_v2) -{ - return wl_proxy_get_version((struct wl_proxy *) kde_output_device_registry_v2); +kde_output_device_registry_v2_get_version(struct kde_output_device_registry_v2* kde_output_device_registry_v2) { + return wl_proxy_get_version((struct wl_proxy*) kde_output_device_registry_v2); } /** @ingroup iface_kde_output_device_registry_v2 */ static inline void -kde_output_device_registry_v2_destroy(struct kde_output_device_registry_v2 *kde_output_device_registry_v2) -{ - wl_proxy_destroy((struct wl_proxy *) kde_output_device_registry_v2); +kde_output_device_registry_v2_destroy(struct kde_output_device_registry_v2* kde_output_device_registry_v2) { + wl_proxy_destroy((struct wl_proxy*) kde_output_device_registry_v2); } /** @@ -259,7 +256,7 @@ kde_output_device_registry_v2_destroy(struct kde_output_device_registry_v2 *kde_ // } #ifndef KDE_OUTPUT_DEVICE_V2_SUBPIXEL_ENUM -#define KDE_OUTPUT_DEVICE_V2_SUBPIXEL_ENUM +# define KDE_OUTPUT_DEVICE_V2_SUBPIXEL_ENUM /** * @ingroup iface_kde_output_device_v2 * subpixel geometry information @@ -268,17 +265,17 @@ kde_output_device_registry_v2_destroy(struct kde_output_device_registry_v2 *kde_ * laid out. */ enum kde_output_device_v2_subpixel { - KDE_OUTPUT_DEVICE_V2_SUBPIXEL_UNKNOWN = 0, - KDE_OUTPUT_DEVICE_V2_SUBPIXEL_NONE = 1, - KDE_OUTPUT_DEVICE_V2_SUBPIXEL_HORIZONTAL_RGB = 2, - KDE_OUTPUT_DEVICE_V2_SUBPIXEL_HORIZONTAL_BGR = 3, - KDE_OUTPUT_DEVICE_V2_SUBPIXEL_VERTICAL_RGB = 4, - KDE_OUTPUT_DEVICE_V2_SUBPIXEL_VERTICAL_BGR = 5, + KDE_OUTPUT_DEVICE_V2_SUBPIXEL_UNKNOWN = 0, + KDE_OUTPUT_DEVICE_V2_SUBPIXEL_NONE = 1, + KDE_OUTPUT_DEVICE_V2_SUBPIXEL_HORIZONTAL_RGB = 2, + KDE_OUTPUT_DEVICE_V2_SUBPIXEL_HORIZONTAL_BGR = 3, + KDE_OUTPUT_DEVICE_V2_SUBPIXEL_VERTICAL_RGB = 4, + KDE_OUTPUT_DEVICE_V2_SUBPIXEL_VERTICAL_BGR = 5, }; #endif /* KDE_OUTPUT_DEVICE_V2_SUBPIXEL_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_TRANSFORM_ENUM -#define KDE_OUTPUT_DEVICE_V2_TRANSFORM_ENUM +# define KDE_OUTPUT_DEVICE_V2_TRANSFORM_ENUM /** * @ingroup iface_kde_output_device_v2 * transform from framebuffer to output @@ -295,19 +292,19 @@ enum kde_output_device_v2_subpixel { * compositor is still able to scan out directly client surfaces. */ enum kde_output_device_v2_transform { - KDE_OUTPUT_DEVICE_V2_TRANSFORM_NORMAL = 0, - KDE_OUTPUT_DEVICE_V2_TRANSFORM_90 = 1, - KDE_OUTPUT_DEVICE_V2_TRANSFORM_180 = 2, - KDE_OUTPUT_DEVICE_V2_TRANSFORM_270 = 3, - KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED = 4, - KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED_90 = 5, - KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED_180 = 6, - KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED_270 = 7, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_NORMAL = 0, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_90 = 1, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_180 = 2, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_270 = 3, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED = 4, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED_90 = 5, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED_180 = 6, + KDE_OUTPUT_DEVICE_V2_TRANSFORM_FLIPPED_270 = 7, }; #endif /* KDE_OUTPUT_DEVICE_V2_TRANSFORM_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_CAPABILITY_ENUM -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_ENUM +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_ENUM /** * @ingroup iface_kde_output_device_v2 * describes capabilities of the outputdevice @@ -315,130 +312,130 @@ enum kde_output_device_v2_transform { * Describes what capabilities this device has. */ enum kde_output_device_v2_capability { - /** - * if this output_device can use overscan - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_OVERSCAN = 0x1, - /** - * if this outputdevice supports variable refresh rate - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_VRR = 0x2, - /** - * if setting the rgb range is possible - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_RGB_RANGE = 0x4, - /** - * if this outputdevice supports high dynamic range - * @since 3 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_HIGH_DYNAMIC_RANGE = 0x8, - /** - * if this outputdevice supports a wide color gamut - * @since 3 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_WIDE_COLOR_GAMUT = 0x10, - /** - * if this outputdevice supports autorotation - * @since 4 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_ROTATE = 0x20, - /** - * if this outputdevice supports icc profiles - * @since 5 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_ICC_PROFILE = 0x40, - /** - * if this outputdevice supports the brightness setting - * @since 9 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_BRIGHTNESS = 0x80, - /** - * if this outputdevice supports the built-in color profile - * @since 12 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_BUILT_IN_COLOR = 0x100, - /** - * if this outputdevice supports DDC/CI - * @since 14 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_DDC_CI = 0x200, - /** - * if this outputdevice supports setting max bpc - * @since 15 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_MAX_BITS_PER_COLOR = 0x400, - /** - * if this outputdevice supports EDR - * @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, - /** - * if this outputdevice supports custom modes - * @since 18 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_CUSTOM_MODES = 0x2000, - /** - * @since 19 - */ - KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_BRIGHTNESS = 0x4000, + /** + * if this output_device can use overscan + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_OVERSCAN = 0x1, + /** + * if this outputdevice supports variable refresh rate + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_VRR = 0x2, + /** + * if setting the rgb range is possible + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_RGB_RANGE = 0x4, + /** + * if this outputdevice supports high dynamic range + * @since 3 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_HIGH_DYNAMIC_RANGE = 0x8, + /** + * if this outputdevice supports a wide color gamut + * @since 3 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_WIDE_COLOR_GAMUT = 0x10, + /** + * if this outputdevice supports autorotation + * @since 4 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_ROTATE = 0x20, + /** + * if this outputdevice supports icc profiles + * @since 5 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_ICC_PROFILE = 0x40, + /** + * if this outputdevice supports the brightness setting + * @since 9 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_BRIGHTNESS = 0x80, + /** + * if this outputdevice supports the built-in color profile + * @since 12 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_BUILT_IN_COLOR = 0x100, + /** + * if this outputdevice supports DDC/CI + * @since 14 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_DDC_CI = 0x200, + /** + * if this outputdevice supports setting max bpc + * @since 15 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_MAX_BITS_PER_COLOR = 0x400, + /** + * if this outputdevice supports EDR + * @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, + /** + * if this outputdevice supports custom modes + * @since 18 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_CUSTOM_MODES = 0x2000, + /** + * @since 19 + */ + KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_BRIGHTNESS = 0x4000, }; /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_HIGH_DYNAMIC_RANGE_SINCE_VERSION 3 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_HIGH_DYNAMIC_RANGE_SINCE_VERSION 3 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_WIDE_COLOR_GAMUT_SINCE_VERSION 3 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_WIDE_COLOR_GAMUT_SINCE_VERSION 3 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_ROTATE_SINCE_VERSION 4 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_ROTATE_SINCE_VERSION 4 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_ICC_PROFILE_SINCE_VERSION 5 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_ICC_PROFILE_SINCE_VERSION 5 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_BRIGHTNESS_SINCE_VERSION 9 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_BRIGHTNESS_SINCE_VERSION 9 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_BUILT_IN_COLOR_SINCE_VERSION 12 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_BUILT_IN_COLOR_SINCE_VERSION 12 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_DDC_CI_SINCE_VERSION 14 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_DDC_CI_SINCE_VERSION 14 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_MAX_BITS_PER_COLOR_SINCE_VERSION 15 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_MAX_BITS_PER_COLOR_SINCE_VERSION 15 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_EDR_SINCE_VERSION 16 +# 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 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_SHARPNESS_SINCE_VERSION 17 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_CUSTOM_MODES_SINCE_VERSION 18 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_CUSTOM_MODES_SINCE_VERSION 18 /** * @ingroup iface_kde_output_device_v2 */ -#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_BRIGHTNESS_SINCE_VERSION 19 +# define KDE_OUTPUT_DEVICE_V2_CAPABILITY_AUTO_BRIGHTNESS_SINCE_VERSION 19 #endif /* KDE_OUTPUT_DEVICE_V2_CAPABILITY_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_VRR_POLICY_ENUM -#define KDE_OUTPUT_DEVICE_V2_VRR_POLICY_ENUM +# define KDE_OUTPUT_DEVICE_V2_VRR_POLICY_ENUM /** * @ingroup iface_kde_output_device_v2 * describes vrr policy @@ -446,14 +443,14 @@ enum kde_output_device_v2_capability { * Describes when the compositor may employ variable refresh rate */ enum kde_output_device_v2_vrr_policy { - KDE_OUTPUT_DEVICE_V2_VRR_POLICY_NEVER = 0, - KDE_OUTPUT_DEVICE_V2_VRR_POLICY_ALWAYS = 1, - KDE_OUTPUT_DEVICE_V2_VRR_POLICY_AUTOMATIC = 2, + KDE_OUTPUT_DEVICE_V2_VRR_POLICY_NEVER = 0, + KDE_OUTPUT_DEVICE_V2_VRR_POLICY_ALWAYS = 1, + KDE_OUTPUT_DEVICE_V2_VRR_POLICY_AUTOMATIC = 2, }; #endif /* KDE_OUTPUT_DEVICE_V2_VRR_POLICY_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_RGB_RANGE_ENUM -#define KDE_OUTPUT_DEVICE_V2_RGB_RANGE_ENUM +# define KDE_OUTPUT_DEVICE_V2_RGB_RANGE_ENUM /** * @ingroup iface_kde_output_device_v2 * describes RGB range policy @@ -461,40 +458,40 @@ enum kde_output_device_v2_vrr_policy { * Whether full or limited color range should be used */ enum kde_output_device_v2_rgb_range { - KDE_OUTPUT_DEVICE_V2_RGB_RANGE_AUTOMATIC = 0, - KDE_OUTPUT_DEVICE_V2_RGB_RANGE_FULL = 1, - KDE_OUTPUT_DEVICE_V2_RGB_RANGE_LIMITED = 2, + KDE_OUTPUT_DEVICE_V2_RGB_RANGE_AUTOMATIC = 0, + KDE_OUTPUT_DEVICE_V2_RGB_RANGE_FULL = 1, + KDE_OUTPUT_DEVICE_V2_RGB_RANGE_LIMITED = 2, }; #endif /* KDE_OUTPUT_DEVICE_V2_RGB_RANGE_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_ENUM -#define KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_ENUM +# define KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_ENUM /** * @ingroup iface_kde_output_device_v2 * describes when auto rotate should be used */ enum kde_output_device_v2_auto_rotate_policy { - KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_NEVER = 0, - KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_IN_TABLET_MODE = 1, - KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_ALWAYS = 2, + KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_NEVER = 0, + KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_IN_TABLET_MODE = 1, + KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_ALWAYS = 2, }; #endif /* KDE_OUTPUT_DEVICE_V2_AUTO_ROTATE_POLICY_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_ENUM -#define KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_ENUM +# define KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_ENUM /** * @ingroup iface_kde_output_device_v2 * which source the compositor should use for the color profile on an output */ enum kde_output_device_v2_color_profile_source { - KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_SRGB = 0, - KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_ICC = 1, - KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_EDID = 2, + KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_SRGB = 0, + KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_ICC = 1, + KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_EDID = 2, }; #endif /* KDE_OUTPUT_DEVICE_V2_COLOR_PROFILE_SOURCE_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_ENUM -#define KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_ENUM +# define KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_ENUM /** * @ingroup iface_kde_output_device_v2 * tradeoff between power and accuracy @@ -505,26 +502,26 @@ enum kde_output_device_v2_color_profile_source { * that tradeoff should be made. */ enum kde_output_device_v2_color_power_tradeoff { - /** - * prefer efficiency and performance - */ - KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_EFFICIENCY = 0, - /** - * prefer accuracy - */ - KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_ACCURACY = 1, + /** + * prefer efficiency and performance + */ + KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_EFFICIENCY = 0, + /** + * prefer accuracy + */ + KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_ACCURACY = 1, }; #endif /* KDE_OUTPUT_DEVICE_V2_COLOR_POWER_TRADEOFF_ENUM */ #ifndef KDE_OUTPUT_DEVICE_V2_EDR_POLICY_ENUM -#define KDE_OUTPUT_DEVICE_V2_EDR_POLICY_ENUM +# define KDE_OUTPUT_DEVICE_V2_EDR_POLICY_ENUM /** * @ingroup iface_kde_output_device_v2 * when the compositor may make use of EDR */ enum kde_output_device_v2_edr_policy { - KDE_OUTPUT_DEVICE_V2_EDR_POLICY_NEVER = 0, - KDE_OUTPUT_DEVICE_V2_EDR_POLICY_ALWAYS = 1, + KDE_OUTPUT_DEVICE_V2_EDR_POLICY_NEVER = 0, + KDE_OUTPUT_DEVICE_V2_EDR_POLICY_ALWAYS = 1, }; #endif /* KDE_OUTPUT_DEVICE_V2_EDR_POLICY_ENUM */ @@ -533,470 +530,471 @@ enum kde_output_device_v2_edr_policy { * @struct kde_output_device_v2_listener */ struct kde_output_device_v2_listener { - /** - * geometric properties of the output - * - * The geometry event describes geometric properties of the - * output. The event is sent when binding to the output object and - * whenever any of the properties change. - * @param x x position within the global compositor space - * @param y y position within the global compositor space - * @param physical_width width in millimeters of the output - * @param physical_height height in millimeters of the output - * @param subpixel subpixel orientation of the output - * @param make textual description of the manufacturer - * @param model textual description of the model - * @param transform transform that maps framebuffer to output - */ - void (*geometry)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - int32_t x, - int32_t y, - int32_t physical_width, - int32_t physical_height, - int32_t subpixel, - const char *make, - const char *model, - int32_t transform); - /** - * current mode - * - * This event describes the mode currently in use for this head. - * It is only sent if the output is enabled. - */ - void (*current_mode)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - struct kde_output_device_mode_v2 *mode); - /** - * advertise available output modes and current one - * - * The mode event describes an available mode for the output. - * - * When the client binds to the output_device object, the server - * sends this event once for every available mode the output_device - * can be operated by. - * - * There will always be at least one event sent out on initial - * binding, which represents the current mode. - * - * Later if an output changes, its mode event is sent again for the - * eventual added modes and lastly the current mode. In other - * words, the current mode is always represented by the latest - * event sent with the current flag set. - * - * The size of a mode is given in physical hardware units of the - * output device. This is not necessarily the same as the output - * size in the global compositor space. For instance, the output - * may be scaled, as described in kde_output_device_v2.scale, or - * transformed, as described in kde_output_device_v2.transform. - */ - void (*mode)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - struct kde_output_device_mode_v2 *mode); - /** - * sent all information about output - * - * This event is sent after all other properties have been sent - * on binding to the output object as well as after any other - * output property change have been applied later on. This allows - * to see changes to the output properties as atomic, even if - * multiple events successively announce them. - */ - void (*done)(void *data, - struct kde_output_device_v2 *kde_output_device_v2); - /** - * output scaling properties - * - * This event contains scaling geometry information that is not - * in the geometry event. It may be sent after binding the output - * object or if the output scale changes later. If it is not sent, - * the client should assume a scale of 1. - * - * A scale larger than 1 means that the compositor will - * automatically scale surface buffers by this amount when - * rendering. This is used for high resolution displays where - * applications rendering at the native resolution would be too - * small to be legible. - * - * It is intended that scaling aware clients track the current - * output of a surface, and if it is on a scaled output it should - * use wl_surface.set_buffer_scale with the scale of the output. - * That way the compositor can avoid scaling the surface, and the - * client can supply a higher detail image. - * @param factor scaling factor of output - */ - void (*scale)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - wl_fixed_t factor); - /** - * advertise EDID data for the output - * - * The edid event encapsulates the EDID data for the - * outputdevice. - * - * The event is sent when binding to the output object. The EDID - * data may be empty, in which case this event is sent anyway. If - * the EDID information is empty, you can fall back to the name et - * al. properties of the outputdevice. - * @param raw base64-encoded EDID string - */ - void (*edid)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - const char *raw); - /** - * output is enabled or disabled - * - * The enabled event notifies whether this output is currently - * enabled and used for displaying content by the server. The event - * is sent when binding to the output object and whenever later on - * an output changes its state by becoming enabled or disabled. - * @param enabled output enabled state - */ - void (*enabled)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - int32_t enabled); - /** - * A unique id for this outputdevice - * - * The uuid can be used to identify the output. It's controlled - * by the server entirely. The server should make sure the uuid is - * persistent across restarts. An empty uuid is considered invalid. - * @param uuid output devices ID - */ - void (*uuid)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - const char *uuid); - /** - * Serial Number - * - * Serial ID of the monitor, sent on startup before the first - * done event. - * @param serialNumber textual representation of serial number - */ - void (*serial_number)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - const char *serialNumber); - /** - * EISA ID - * - * EISA ID of the monitor, sent on startup before the first done - * event. - * @param eisaId textual representation of EISA identifier - */ - void (*eisa_id)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - const char *eisaId); - /** - * capability flags - * - * What capabilities this device has, sent on startup before the - * first done event. - */ - void (*capabilities)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t flags); - /** - * overscan - * - * Overscan value of the monitor in percent, sent on startup - * before the first done event. - * @param overscan amount of overscan of the monitor - */ - void (*overscan)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t overscan); - /** - * Variable Refresh Rate Policy - * - * What policy the compositor will employ regarding its use of - * variable refresh rate. - */ - void (*vrr_policy)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t vrr_policy); - /** - * RGB range - * - * What rgb range the compositor is using for this output - */ - void (*rgb_range)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t rgb_range); - /** - * Output's name - * - * Name of the output, it's useful to cross-reference to an - * zxdg_output_v1 and ultimately QScreen - * @since 2 - */ - void (*name)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - const char *name); - /** - * if HDR is enabled - * - * Whether or not high dynamic range is enabled for this output - * @param hdr_enabled 1 if enabled, 0 if disabled - * @since 3 - */ - void (*high_dynamic_range)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t hdr_enabled); - /** - * the brightness of sdr if hdr is enabled - * - * If high dynamic range is used, this value defines the - * brightness in nits for content that's in standard dynamic range - * format. Note that while the value is in nits, that doesn't - * necessarily translate to the same brightness on the screen. - * @since 3 - */ - void (*sdr_brightness)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t sdr_brightness); - /** - * if WCG is enabled - * - * Whether or not the use of a wide color gamut is enabled for - * this output - * @param wcg_enabled 1 if enabled, 0 if disabled - * @since 3 - */ - void (*wide_color_gamut)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t wcg_enabled); - /** - * describes when auto rotate is used - * - * - * @since 4 - */ - void (*auto_rotate_policy)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t policy); - /** - * describes when auto rotate is used - * - * - * @since 5 - */ - void (*icc_profile_path)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - const char *profile_path); - /** - * metadata about the screen's brightness limits - * - * - * @param max_peak_brightness in nits - * @param max_frame_average_brightness in nits - * @param min_brightness in 0.0001 nits - * @since 6 - */ - void (*brightness_metadata)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t max_peak_brightness, - uint32_t max_frame_average_brightness, - uint32_t min_brightness); - /** - * overrides for the screen's brightness limits - * - * - * @param max_peak_brightness -1 for no override, positive values are the brightness in nits - * @param max_average_brightness -1 for no override, positive values are the brightness in nits - * @param min_brightness -1 for no override, positive values are the brightness in 0.0001 nits - * @since 6 - */ - void (*brightness_overrides)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - int32_t max_peak_brightness, - int32_t max_average_brightness, - int32_t min_brightness); - /** - * describes which gamut is assumed for sRGB applications - * - * This can be used to provide the colors users assume sRGB - * applications should have based on the default experience on many - * modern sRGB screens. - * @param gamut_wideness 0 means rec.709 primaries, 10000 means native primaries - * @since 6 - */ - void (*sdr_gamut_wideness)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t gamut_wideness); - /** - * describes which source the compositor uses for the color profile on an output - * - * - * @since 7 - */ - void (*color_profile_source)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t source); - /** - * brightness multiplier - * - * This is the brightness modifier of the output. It doesn't - * specify any absolute values, but is merely a multiplier on top - * of other brightness values, like sdr_brightness and - * brightness_metadata. 0 is the minimum brightness (not completely - * dark) and 10000 is the maximum brightness. This is currently - * only supported / meaningful while HDR is active. - * @param brightness brightness in 0-10000 - * @since 8 - */ - void (*brightness)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t brightness); - /** - * the preferred color/power tradeoff - * - * - * @since 10 - */ - void (*color_power_tradeoff)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t preference); - /** - * dimming multiplier - * - * This is the dimming multiplier of the output. This is similar - * to the brightness setting, except it's meant to be a temporary - * setting only, not persistent and may be implemented differently - * depending on the display. 0 is the minimum dimming factor (not - * completely dark) and 10000 means the output is not dimmed. - * @param multiplier multiplier in 0-10000 - * @since 11 - */ - void (*dimming)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t multiplier); - /** - * source output for mirroring - * - * - * @param source uuid of the source output - * @since 13 - */ - void (*replication_source)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - const char *source); - /** - * if DDC/CI should be used to control brightness etc. - * - * If the ddc_ci capability is present, this determines if - * settings such as brightness, contrast or others should be set - * using DDC/CI. - * @param allowed 1 if allowed, 0 if disabled - * @since 14 - */ - void (*ddc_ci_allowed)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t allowed); - /** - * override max bpc - * - * This limits the amount of bits per color that are sent to the - * display. - * @param max_bpc 0 for the default / automatic - * @since 15 - */ - void (*max_bits_per_color)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t max_bpc); - /** - * range of max bits per color value - * - * - * @param min_value the minimum supported by the driver - * @param max_value the maximum supported by the driver - * @since 15 - */ - void (*max_bits_per_color_range)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t min_value, - uint32_t max_value); - /** - * if and to what value automatic max bpc is limited - * - * - * @param max_bpc_limit which value automatic bpc gets limited to. 0 if not limited - * @since 15 - */ - void (*automatic_max_bits_per_color_limit)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t max_bpc_limit); - /** - * when the compositor may apply EDR - * - * When EDR is enabled, the compositor may increase the backlight - * beyond the user-specified setting, in order to present HDR - * content on displays without native HDR support. This will - * usually result in better visuals, but also increases battery - * usage. - * @since 16 - */ - 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); - /** - * output priority - * - * Describes the position of the output in the output order list, - * with lower values being earlier in the list. There's no specific - * value the list has to start at, this value is only used in - * sorting outputs. - * - * Note that the output order protocol is not sufficient for this, - * as an output may not be in the output order if it's disabled or - * mirroring another screen. - * @param priority priority - * @since 18 - */ - void (*priority)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t priority); - /** - * whether or not automatic brightness is enabled - * - * - * @param enabled 1 for enabled, 0 for disabled - * @since 20 - */ - void (*auto_brightness)(void *data, - struct kde_output_device_v2 *kde_output_device_v2, - uint32_t enabled); - /** - * the output has been removed - * - * This event is sent when the output device is disconnected and - * no new updates will be sent. The client should call the - * kde_output_device_v2.release request after receiving this event. - * @since 21 - */ - void (*removed)(void *data, - struct kde_output_device_v2 *kde_output_device_v2); + /** + * geometric properties of the output + * + * The geometry event describes geometric properties of the + * output. The event is sent when binding to the output object and + * whenever any of the properties change. + * @param x x position within the global compositor space + * @param y y position within the global compositor space + * @param physical_width width in millimeters of the output + * @param physical_height height in millimeters of the output + * @param subpixel subpixel orientation of the output + * @param make textual description of the manufacturer + * @param model textual description of the model + * @param transform transform that maps framebuffer to output + */ + void (*geometry)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + int32_t x, + int32_t y, + int32_t physical_width, + int32_t physical_height, + int32_t subpixel, + const char* make, + const char* model, + int32_t transform); + /** + * current mode + * + * This event describes the mode currently in use for this head. + * It is only sent if the output is enabled. + */ + void (*current_mode)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + struct kde_output_device_mode_v2* mode); + /** + * advertise available output modes and current one + * + * The mode event describes an available mode for the output. + * + * When the client binds to the output_device object, the server + * sends this event once for every available mode the output_device + * can be operated by. + * + * There will always be at least one event sent out on initial + * binding, which represents the current mode. + * + * Later if an output changes, its mode event is sent again for the + * eventual added modes and lastly the current mode. In other + * words, the current mode is always represented by the latest + * event sent with the current flag set. + * + * The size of a mode is given in physical hardware units of the + * output device. This is not necessarily the same as the output + * size in the global compositor space. For instance, the output + * may be scaled, as described in kde_output_device_v2.scale, or + * transformed, as described in kde_output_device_v2.transform. + */ + void (*mode)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + struct kde_output_device_mode_v2* mode); + /** + * sent all information about output + * + * This event is sent after all other properties have been sent + * on binding to the output object as well as after any other + * output property change have been applied later on. This allows + * to see changes to the output properties as atomic, even if + * multiple events successively announce them. + */ + void (*done)(void* data, + struct kde_output_device_v2* kde_output_device_v2); + /** + * output scaling properties + * + * This event contains scaling geometry information that is not + * in the geometry event. It may be sent after binding the output + * object or if the output scale changes later. If it is not sent, + * the client should assume a scale of 1. + * + * A scale larger than 1 means that the compositor will + * automatically scale surface buffers by this amount when + * rendering. This is used for high resolution displays where + * applications rendering at the native resolution would be too + * small to be legible. + * + * It is intended that scaling aware clients track the current + * output of a surface, and if it is on a scaled output it should + * use wl_surface.set_buffer_scale with the scale of the output. + * That way the compositor can avoid scaling the surface, and the + * client can supply a higher detail image. + * @param factor scaling factor of output + */ + void (*scale)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + wl_fixed_t factor); + /** + * advertise EDID data for the output + * + * The edid event encapsulates the EDID data for the + * outputdevice. + * + * The event is sent when binding to the output object. The EDID + * data may be empty, in which case this event is sent anyway. If + * the EDID information is empty, you can fall back to the name et + * al. properties of the outputdevice. + * @param raw base64-encoded EDID string + */ + void (*edid)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + const char* raw); + /** + * output is enabled or disabled + * + * The enabled event notifies whether this output is currently + * enabled and used for displaying content by the server. The event + * is sent when binding to the output object and whenever later on + * an output changes its state by becoming enabled or disabled. + * @param enabled output enabled state + */ + void (*enabled)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + int32_t enabled); + /** + * A unique id for this outputdevice + * + * The uuid can be used to identify the output. It's controlled + * by the server entirely. The server should make sure the uuid is + * persistent across restarts. An empty uuid is considered invalid. + * @param uuid output devices ID + */ + void (*uuid)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + const char* uuid); + /** + * Serial Number + * + * Serial ID of the monitor, sent on startup before the first + * done event. + * @param serialNumber textual representation of serial number + */ + void (*serial_number)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + const char* serialNumber); + /** + * EISA ID + * + * EISA ID of the monitor, sent on startup before the first done + * event. + * @param eisaId textual representation of EISA identifier + */ + void (*eisa_id)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + const char* eisaId); + /** + * capability flags + * + * What capabilities this device has, sent on startup before the + * first done event. + */ + void (*capabilities)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t flags); + /** + * overscan + * + * Overscan value of the monitor in percent, sent on startup + * before the first done event. + * @param overscan amount of overscan of the monitor + */ + void (*overscan)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t overscan); + /** + * Variable Refresh Rate Policy + * + * What policy the compositor will employ regarding its use of + * variable refresh rate. + */ + void (*vrr_policy)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t vrr_policy); + /** + * RGB range + * + * What rgb range the compositor is using for this output + */ + void (*rgb_range)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t rgb_range); + /** + * Output's name + * + * Name of the output, it's useful to cross-reference to an + * zxdg_output_v1 and ultimately QScreen + * @since 2 + */ + void (*name)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + const char* name); + /** + * if HDR is enabled + * + * Whether or not high dynamic range is enabled for this output + * @param hdr_enabled 1 if enabled, 0 if disabled + * @since 3 + */ + void (*high_dynamic_range)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t hdr_enabled); + /** + * the brightness of sdr if hdr is enabled + * + * If high dynamic range is used, this value defines the + * brightness in nits for content that's in standard dynamic range + * format. Note that while the value is in nits, that doesn't + * necessarily translate to the same brightness on the screen. + * @since 3 + */ + void (*sdr_brightness)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t sdr_brightness); + /** + * if WCG is enabled + * + * Whether or not the use of a wide color gamut is enabled for + * this output + * @param wcg_enabled 1 if enabled, 0 if disabled + * @since 3 + */ + void (*wide_color_gamut)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t wcg_enabled); + /** + * describes when auto rotate is used + * + * + * @since 4 + */ + void (*auto_rotate_policy)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t policy); + /** + * describes when auto rotate is used + * + * + * @since 5 + */ + void (*icc_profile_path)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + const char* profile_path); + /** + * metadata about the screen's brightness limits + * + * + * @param max_peak_brightness in nits + * @param max_frame_average_brightness in nits + * @param min_brightness in 0.0001 nits + * @since 6 + */ + void (*brightness_metadata)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t max_peak_brightness, + uint32_t max_frame_average_brightness, + uint32_t min_brightness); + /** + * overrides for the screen's brightness limits + * + * + * @param max_peak_brightness -1 for no override, positive values are the brightness in nits + * @param max_average_brightness -1 for no override, positive values are the brightness in nits + * @param min_brightness -1 for no override, positive values are the brightness in 0.0001 nits + * @since 6 + */ + void (*brightness_overrides)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + int32_t max_peak_brightness, + int32_t max_average_brightness, + int32_t min_brightness); + /** + * describes which gamut is assumed for sRGB applications + * + * This can be used to provide the colors users assume sRGB + * applications should have based on the default experience on many + * modern sRGB screens. + * @param gamut_wideness 0 means rec.709 primaries, 10000 means native primaries + * @since 6 + */ + void (*sdr_gamut_wideness)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t gamut_wideness); + /** + * describes which source the compositor uses for the color profile on an output + * + * + * @since 7 + */ + void (*color_profile_source)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t source); + /** + * brightness multiplier + * + * This is the brightness modifier of the output. It doesn't + * specify any absolute values, but is merely a multiplier on top + * of other brightness values, like sdr_brightness and + * brightness_metadata. 0 is the minimum brightness (not completely + * dark) and 10000 is the maximum brightness. This is currently + * only supported / meaningful while HDR is active. + * @param brightness brightness in 0-10000 + * @since 8 + */ + void (*brightness)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t brightness); + /** + * the preferred color/power tradeoff + * + * + * @since 10 + */ + void (*color_power_tradeoff)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t preference); + /** + * dimming multiplier + * + * This is the dimming multiplier of the output. This is similar + * to the brightness setting, except it's meant to be a temporary + * setting only, not persistent and may be implemented differently + * depending on the display. 0 is the minimum dimming factor (not + * completely dark) and 10000 means the output is not dimmed. + * @param multiplier multiplier in 0-10000 + * @since 11 + */ + void (*dimming)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t multiplier); + /** + * source output for mirroring + * + * + * @param source uuid of the source output + * @since 13 + */ + void (*replication_source)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + const char* source); + /** + * if DDC/CI should be used to control brightness etc. + * + * If the ddc_ci capability is present, this determines if + * settings such as brightness, contrast or others should be set + * using DDC/CI. + * @param allowed 1 if allowed, 0 if disabled + * @since 14 + */ + void (*ddc_ci_allowed)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t allowed); + /** + * override max bpc + * + * This limits the amount of bits per color that are sent to the + * display. + * @param max_bpc 0 for the default / automatic + * @since 15 + */ + void (*max_bits_per_color)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t max_bpc); + /** + * range of max bits per color value + * + * + * @param min_value the minimum supported by the driver + * @param max_value the maximum supported by the driver + * @since 15 + */ + void (*max_bits_per_color_range)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t min_value, + uint32_t max_value); + /** + * if and to what value automatic max bpc is limited + * + * + * @param max_bpc_limit which value automatic bpc gets limited to. 0 if not limited + * @since 15 + */ + void (*automatic_max_bits_per_color_limit)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t max_bpc_limit); + /** + * when the compositor may apply EDR + * + * When EDR is enabled, the compositor may increase the backlight + * beyond the user-specified setting, in order to present HDR + * content on displays without native HDR support. This will + * usually result in better visuals, but also increases battery + * usage. + * @since 16 + */ + 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); + /** + * output priority + * + * Describes the position of the output in the output order list, + * with lower values being earlier in the list. There's no specific + * value the list has to start at, this value is only used in + * sorting outputs. + * + * Note that the output order protocol is not sufficient for this, + * as an output may not be in the output order if it's disabled or + * mirroring another screen. + * @param priority priority + * @since 18 + */ + void (*priority)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t priority); + /** + * whether or not automatic brightness is enabled + * + * + * @param enabled 1 for enabled, 0 for disabled + * @since 20 + */ + void (*auto_brightness)(void* data, + struct kde_output_device_v2* kde_output_device_v2, + uint32_t enabled); + /** + * the output has been removed + * + * This event is sent when the output device is disconnected and + * no new updates will be sent. The client should call the + * kde_output_device_v2.release request after receiving this event. + * @since 21 + */ + void (*removed)(void* data, + struct kde_output_device_v2* kde_output_device_v2); }; /** * @ingroup iface_kde_output_device_v2 */ static inline int -kde_output_device_v2_add_listener(struct kde_output_device_v2 *kde_output_device_v2, - const struct kde_output_device_v2_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) kde_output_device_v2, - (void (**)(void)) listener, data); +kde_output_device_v2_add_listener(struct kde_output_device_v2* kde_output_device_v2, + const struct kde_output_device_v2_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) kde_output_device_v2, + (void (**)(void)) listener, + data); } #define KDE_OUTPUT_DEVICE_V2_RELEASE 0 @@ -1157,29 +1155,25 @@ kde_output_device_v2_add_listener(struct kde_output_device_v2 *kde_output_device /** @ingroup iface_kde_output_device_v2 */ static inline void -kde_output_device_v2_set_user_data(struct kde_output_device_v2 *kde_output_device_v2, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) kde_output_device_v2, user_data); +kde_output_device_v2_set_user_data(struct kde_output_device_v2* kde_output_device_v2, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) kde_output_device_v2, user_data); } /** @ingroup iface_kde_output_device_v2 */ -static inline void * -kde_output_device_v2_get_user_data(struct kde_output_device_v2 *kde_output_device_v2) -{ - return wl_proxy_get_user_data((struct wl_proxy *) kde_output_device_v2); +static inline void* +kde_output_device_v2_get_user_data(struct kde_output_device_v2* kde_output_device_v2) { + return wl_proxy_get_user_data((struct wl_proxy*) kde_output_device_v2); } static inline uint32_t -kde_output_device_v2_get_version(struct kde_output_device_v2 *kde_output_device_v2) -{ - return wl_proxy_get_version((struct wl_proxy *) kde_output_device_v2); +kde_output_device_v2_get_version(struct kde_output_device_v2* kde_output_device_v2) { + return wl_proxy_get_version((struct wl_proxy*) kde_output_device_v2); } /** @ingroup iface_kde_output_device_v2 */ static inline void -kde_output_device_v2_destroy(struct kde_output_device_v2 *kde_output_device_v2) -{ - wl_proxy_destroy((struct wl_proxy *) kde_output_device_v2); +kde_output_device_v2_destroy(struct kde_output_device_v2* kde_output_device_v2) { + wl_proxy_destroy((struct wl_proxy*) kde_output_device_v2); } /** @@ -1196,14 +1190,14 @@ kde_output_device_v2_destroy(struct kde_output_device_v2 *kde_output_device_v2) // } #ifndef KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_ENUM -#define KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_ENUM +# define KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_ENUM /** * @ingroup iface_kde_output_device_mode_v2 * mode flags */ enum kde_output_device_mode_v2_flags { - KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_CUSTOM = 0x1, - KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_REDUCED_BLANKING = 0x2, + KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_CUSTOM = 0x1, + KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_REDUCED_BLANKING = 0x2, }; #endif /* KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_ENUM */ @@ -1212,66 +1206,67 @@ enum kde_output_device_mode_v2_flags { * @struct kde_output_device_mode_v2_listener */ struct kde_output_device_mode_v2_listener { - /** - * mode size - * - * This event describes the mode size. The size is given in - * physical hardware units of the output device. This is not - * necessarily the same as the output size in the global compositor - * space. For instance, the output may be scaled or transformed. - * @param width width of the mode in hardware units - * @param height height of the mode in hardware units - */ - void (*size)(void *data, - struct kde_output_device_mode_v2 *kde_output_device_mode_v2, - int32_t width, - int32_t height); - /** - * mode refresh rate - * - * This event describes the mode's fixed vertical refresh rate. - * It is only sent if the mode has a fixed refresh rate. - * @param refresh vertical refresh rate in mHz - */ - void (*refresh)(void *data, - struct kde_output_device_mode_v2 *kde_output_device_mode_v2, - int32_t refresh); - /** - * mode is preferred - * - * This event advertises this mode as preferred. - */ - void (*preferred)(void *data, - struct kde_output_device_mode_v2 *kde_output_device_mode_v2); - /** - * the mode has been destroyed - * - * The compositor will destroy the object immediately after - * sending this event, so it will become invalid and the client - * should release any resources associated with it. - */ - void (*removed)(void *data, - struct kde_output_device_mode_v2 *kde_output_device_mode_v2); - /** - * mode flags - * - * This event describes the mode's flags. - * @since 19 - */ - void (*flags)(void *data, - struct kde_output_device_mode_v2 *kde_output_device_mode_v2, - uint32_t flags); + /** + * mode size + * + * This event describes the mode size. The size is given in + * physical hardware units of the output device. This is not + * necessarily the same as the output size in the global compositor + * space. For instance, the output may be scaled or transformed. + * @param width width of the mode in hardware units + * @param height height of the mode in hardware units + */ + void (*size)(void* data, + struct kde_output_device_mode_v2* kde_output_device_mode_v2, + int32_t width, + int32_t height); + /** + * mode refresh rate + * + * This event describes the mode's fixed vertical refresh rate. + * It is only sent if the mode has a fixed refresh rate. + * @param refresh vertical refresh rate in mHz + */ + void (*refresh)(void* data, + struct kde_output_device_mode_v2* kde_output_device_mode_v2, + int32_t refresh); + /** + * mode is preferred + * + * This event advertises this mode as preferred. + */ + void (*preferred)(void* data, + struct kde_output_device_mode_v2* kde_output_device_mode_v2); + /** + * the mode has been destroyed + * + * The compositor will destroy the object immediately after + * sending this event, so it will become invalid and the client + * should release any resources associated with it. + */ + void (*removed)(void* data, + struct kde_output_device_mode_v2* kde_output_device_mode_v2); + /** + * mode flags + * + * This event describes the mode's flags. + * @since 19 + */ + void (*flags)(void* data, + struct kde_output_device_mode_v2* kde_output_device_mode_v2, + uint32_t flags); }; /** * @ingroup iface_kde_output_device_mode_v2 */ static inline int -kde_output_device_mode_v2_add_listener(struct kde_output_device_mode_v2 *kde_output_device_mode_v2, - const struct kde_output_device_mode_v2_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) kde_output_device_mode_v2, - (void (**)(void)) listener, data); +kde_output_device_mode_v2_add_listener(struct kde_output_device_mode_v2* kde_output_device_mode_v2, + const struct kde_output_device_mode_v2_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) kde_output_device_mode_v2, + (void (**)(void)) listener, + data); } /** @@ -1295,35 +1290,30 @@ kde_output_device_mode_v2_add_listener(struct kde_output_device_mode_v2 *kde_out */ #define KDE_OUTPUT_DEVICE_MODE_V2_FLAGS_SINCE_VERSION 19 - /** @ingroup iface_kde_output_device_mode_v2 */ static inline void -kde_output_device_mode_v2_set_user_data(struct kde_output_device_mode_v2 *kde_output_device_mode_v2, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) kde_output_device_mode_v2, user_data); +kde_output_device_mode_v2_set_user_data(struct kde_output_device_mode_v2* kde_output_device_mode_v2, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) kde_output_device_mode_v2, user_data); } /** @ingroup iface_kde_output_device_mode_v2 */ -static inline void * -kde_output_device_mode_v2_get_user_data(struct kde_output_device_mode_v2 *kde_output_device_mode_v2) -{ - return wl_proxy_get_user_data((struct wl_proxy *) kde_output_device_mode_v2); +static inline void* +kde_output_device_mode_v2_get_user_data(struct kde_output_device_mode_v2* kde_output_device_mode_v2) { + return wl_proxy_get_user_data((struct wl_proxy*) kde_output_device_mode_v2); } static inline uint32_t -kde_output_device_mode_v2_get_version(struct kde_output_device_mode_v2 *kde_output_device_mode_v2) -{ - return wl_proxy_get_version((struct wl_proxy *) kde_output_device_mode_v2); +kde_output_device_mode_v2_get_version(struct kde_output_device_mode_v2* kde_output_device_mode_v2) { + return wl_proxy_get_version((struct wl_proxy*) kde_output_device_mode_v2); } /** @ingroup iface_kde_output_device_mode_v2 */ static inline void -kde_output_device_mode_v2_destroy(struct kde_output_device_mode_v2 *kde_output_device_mode_v2) -{ - wl_proxy_destroy((struct wl_proxy *) kde_output_device_mode_v2); +kde_output_device_mode_v2_destroy(struct kde_output_device_mode_v2* kde_output_device_mode_v2) { + wl_proxy_destroy((struct wl_proxy*) kde_output_device_mode_v2); } -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c b/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c index 75d5ac52b..e27af2518 100644 --- a/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c +++ b/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c @@ -12,105 +12,114 @@ * SPDX-License-Identifier: MIT-CMU */ -#include -#include -#include -#include +# include +# include +# include +# include extern const struct wl_interface kde_output_device_mode_v2_interface; extern const struct wl_interface kde_output_device_v2_interface; -static const struct wl_interface *kde_output_device_v2_types[] = { - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - &kde_output_device_v2_interface, - &kde_output_device_mode_v2_interface, - &kde_output_device_mode_v2_interface, +static const struct wl_interface* kde_output_device_v2_types[] = { + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + &kde_output_device_v2_interface, + &kde_output_device_mode_v2_interface, + &kde_output_device_mode_v2_interface, }; static const struct wl_message kde_output_device_registry_v2_requests[] = { - { "stop", "21", kde_output_device_v2_types + 0 }, + {"stop", "21", kde_output_device_v2_types + 0}, }; static const struct wl_message kde_output_device_registry_v2_events[] = { - { "finished", "21", kde_output_device_v2_types + 0 }, - { "output", "21n", kde_output_device_v2_types + 8 }, + {"finished", "21", kde_output_device_v2_types + 0}, + {"output", "21n", kde_output_device_v2_types + 8}, }; WL_EXPORT const struct wl_interface kde_output_device_registry_v2_interface = { - "kde_output_device_registry_v2", 21, - 1, kde_output_device_registry_v2_requests, - 2, kde_output_device_registry_v2_events, + "kde_output_device_registry_v2", + 21, + 1, + kde_output_device_registry_v2_requests, + 2, + kde_output_device_registry_v2_events, }; static const struct wl_message kde_output_device_v2_requests[] = { - { "release", "21", kde_output_device_v2_types + 0 }, + {"release", "21", kde_output_device_v2_types + 0}, }; static const struct wl_message kde_output_device_v2_events[] = { - { "geometry", "iiiiissi", kde_output_device_v2_types + 0 }, - { "current_mode", "o", kde_output_device_v2_types + 9 }, - { "mode", "n", kde_output_device_v2_types + 10 }, - { "done", "", kde_output_device_v2_types + 0 }, - { "scale", "f", kde_output_device_v2_types + 0 }, - { "edid", "s", kde_output_device_v2_types + 0 }, - { "enabled", "i", kde_output_device_v2_types + 0 }, - { "uuid", "s", kde_output_device_v2_types + 0 }, - { "serial_number", "s", kde_output_device_v2_types + 0 }, - { "eisa_id", "s", kde_output_device_v2_types + 0 }, - { "capabilities", "u", kde_output_device_v2_types + 0 }, - { "overscan", "u", kde_output_device_v2_types + 0 }, - { "vrr_policy", "u", kde_output_device_v2_types + 0 }, - { "rgb_range", "u", kde_output_device_v2_types + 0 }, - { "name", "2s", kde_output_device_v2_types + 0 }, - { "high_dynamic_range", "3u", kde_output_device_v2_types + 0 }, - { "sdr_brightness", "3u", kde_output_device_v2_types + 0 }, - { "wide_color_gamut", "3u", kde_output_device_v2_types + 0 }, - { "auto_rotate_policy", "4u", kde_output_device_v2_types + 0 }, - { "icc_profile_path", "5s", kde_output_device_v2_types + 0 }, - { "brightness_metadata", "6uuu", kde_output_device_v2_types + 0 }, - { "brightness_overrides", "6iii", kde_output_device_v2_types + 0 }, - { "sdr_gamut_wideness", "6u", kde_output_device_v2_types + 0 }, - { "color_profile_source", "7u", kde_output_device_v2_types + 0 }, - { "brightness", "8u", kde_output_device_v2_types + 0 }, - { "color_power_tradeoff", "10u", kde_output_device_v2_types + 0 }, - { "dimming", "11u", kde_output_device_v2_types + 0 }, - { "replication_source", "13s", kde_output_device_v2_types + 0 }, - { "ddc_ci_allowed", "14u", kde_output_device_v2_types + 0 }, - { "max_bits_per_color", "15u", kde_output_device_v2_types + 0 }, - { "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 }, - { "priority", "18u", kde_output_device_v2_types + 0 }, - { "auto_brightness", "20u", kde_output_device_v2_types + 0 }, - { "removed", "21", kde_output_device_v2_types + 0 }, + {"geometry", "iiiiissi", kde_output_device_v2_types + 0}, + {"current_mode", "o", kde_output_device_v2_types + 9}, + {"mode", "n", kde_output_device_v2_types + 10}, + {"done", "", kde_output_device_v2_types + 0}, + {"scale", "f", kde_output_device_v2_types + 0}, + {"edid", "s", kde_output_device_v2_types + 0}, + {"enabled", "i", kde_output_device_v2_types + 0}, + {"uuid", "s", kde_output_device_v2_types + 0}, + {"serial_number", "s", kde_output_device_v2_types + 0}, + {"eisa_id", "s", kde_output_device_v2_types + 0}, + {"capabilities", "u", kde_output_device_v2_types + 0}, + {"overscan", "u", kde_output_device_v2_types + 0}, + {"vrr_policy", "u", kde_output_device_v2_types + 0}, + {"rgb_range", "u", kde_output_device_v2_types + 0}, + {"name", "2s", kde_output_device_v2_types + 0}, + {"high_dynamic_range", "3u", kde_output_device_v2_types + 0}, + {"sdr_brightness", "3u", kde_output_device_v2_types + 0}, + {"wide_color_gamut", "3u", kde_output_device_v2_types + 0}, + {"auto_rotate_policy", "4u", kde_output_device_v2_types + 0}, + {"icc_profile_path", "5s", kde_output_device_v2_types + 0}, + {"brightness_metadata", "6uuu", kde_output_device_v2_types + 0}, + {"brightness_overrides", "6iii", kde_output_device_v2_types + 0}, + {"sdr_gamut_wideness", "6u", kde_output_device_v2_types + 0}, + {"color_profile_source", "7u", kde_output_device_v2_types + 0}, + {"brightness", "8u", kde_output_device_v2_types + 0}, + {"color_power_tradeoff", "10u", kde_output_device_v2_types + 0}, + {"dimming", "11u", kde_output_device_v2_types + 0}, + {"replication_source", "13s", kde_output_device_v2_types + 0}, + {"ddc_ci_allowed", "14u", kde_output_device_v2_types + 0}, + {"max_bits_per_color", "15u", kde_output_device_v2_types + 0}, + {"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}, + {"priority", "18u", kde_output_device_v2_types + 0}, + {"auto_brightness", "20u", kde_output_device_v2_types + 0}, + {"removed", "21", kde_output_device_v2_types + 0}, }; WL_EXPORT const struct wl_interface kde_output_device_v2_interface = { - "kde_output_device_v2", 21, - 1, kde_output_device_v2_requests, - 37, kde_output_device_v2_events, + "kde_output_device_v2", + 21, + 1, + kde_output_device_v2_requests, + 37, + kde_output_device_v2_events, }; static const struct wl_message kde_output_device_mode_v2_events[] = { - { "size", "ii", kde_output_device_v2_types + 0 }, - { "refresh", "i", kde_output_device_v2_types + 0 }, - { "preferred", "", kde_output_device_v2_types + 0 }, - { "removed", "", kde_output_device_v2_types + 0 }, - { "flags", "19u", kde_output_device_v2_types + 0 }, + {"size", "ii", kde_output_device_v2_types + 0}, + {"refresh", "i", kde_output_device_v2_types + 0}, + {"preferred", "", kde_output_device_v2_types + 0}, + {"removed", "", kde_output_device_v2_types + 0}, + {"flags", "19u", kde_output_device_v2_types + 0}, }; WL_EXPORT const struct wl_interface kde_output_device_mode_v2_interface = { - "kde_output_device_mode_v2", 21, - 0, NULL, - 5, kde_output_device_mode_v2_events, + "kde_output_device_mode_v2", + 21, + 0, + NULL, + 5, + kde_output_device_mode_v2_events, }; #endif diff --git a/src/detection/displayserver/linux/wayland/kde-output-order-v1-client-protocol.h b/src/detection/displayserver/linux/wayland/kde-output-order-v1-client-protocol.h index 40075998f..2b6fe9875 100644 --- a/src/detection/displayserver/linux/wayland/kde-output-order-v1-client-protocol.h +++ b/src/detection/displayserver/linux/wayland/kde-output-order-v1-client-protocol.h @@ -7,7 +7,7 @@ #include #include "wayland-client.h" -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -26,7 +26,7 @@ extern "C" { struct kde_output_order_v1; #ifndef KDE_OUTPUT_ORDER_V1_INTERFACE -#define KDE_OUTPUT_ORDER_V1_INTERFACE +# define KDE_OUTPUT_ORDER_V1_INTERFACE /** * @page page_iface_kde_output_order_v1 kde_output_order_v1 * @section page_iface_kde_output_order_v1_desc Description @@ -50,34 +50,35 @@ extern const struct wl_interface kde_output_order_v1_interface; * @struct kde_output_order_v1_listener */ struct kde_output_order_v1_listener { - /** - * output name - * - * Specifies the output identified by their wl_output.name. - * @param output_name the name of the output - */ - void (*output)(void *data, - struct kde_output_order_v1 *kde_output_order_v1, - const char *output_name); - /** - * done - * - * Specifies that the output list is complete. On the next output - * event, a new list begins. - */ - void (*done)(void *data, - struct kde_output_order_v1 *kde_output_order_v1); + /** + * output name + * + * Specifies the output identified by their wl_output.name. + * @param output_name the name of the output + */ + void (*output)(void* data, + struct kde_output_order_v1* kde_output_order_v1, + const char* output_name); + /** + * done + * + * Specifies that the output list is complete. On the next output + * event, a new list begins. + */ + void (*done)(void* data, + struct kde_output_order_v1* kde_output_order_v1); }; /** * @ingroup iface_kde_output_order_v1 */ static inline int -kde_output_order_v1_add_listener(struct kde_output_order_v1 *kde_output_order_v1, - const struct kde_output_order_v1_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) kde_output_order_v1, - (void (**)(void)) listener, data); +kde_output_order_v1_add_listener(struct kde_output_order_v1* kde_output_order_v1, + const struct kde_output_order_v1_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) kde_output_order_v1, + (void (**)(void)) listener, + data); } #define KDE_OUTPUT_ORDER_V1_DESTROY 0 @@ -126,7 +127,7 @@ kde_output_order_v1_add_listener(struct kde_output_order_v1 *kde_output_order_v1 // KDE_OUTPUT_ORDER_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) kde_output_order_v1), WL_MARSHAL_FLAG_DESTROY); // } -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/src/detection/displayserver/linux/wayland/kde-output-order-v1-protocol.c b/src/detection/displayserver/linux/wayland/kde-output-order-v1-protocol.c index c7cf90f34..89a76c67b 100644 --- a/src/detection/displayserver/linux/wayland/kde-output-order-v1-protocol.c +++ b/src/detection/displayserver/linux/wayland/kde-output-order-v1-protocol.c @@ -8,28 +8,30 @@ * SPDX-License-Identifier: MIT-CMU */ -#include -#include -#include "wayland-util.h" +# include +# include +# include "wayland-util.h" - -static const struct wl_interface *kde_output_order_v1_types[] = { - NULL, +static const struct wl_interface* kde_output_order_v1_types[] = { + NULL, }; static const struct wl_message kde_output_order_v1_requests[] = { - { "destroy", "", kde_output_order_v1_types + 0 }, + {"destroy", "", kde_output_order_v1_types + 0}, }; static const struct wl_message kde_output_order_v1_events[] = { - { "output", "s", kde_output_order_v1_types + 0 }, - { "done", "", kde_output_order_v1_types + 0 }, + {"output", "s", kde_output_order_v1_types + 0}, + {"done", "", kde_output_order_v1_types + 0}, }; WL_EXPORT const struct wl_interface kde_output_order_v1_interface = { - "kde_output_order_v1", 1, - 1, kde_output_order_v1_requests, - 2, kde_output_order_v1_events, + "kde_output_order_v1", + 1, + 1, + kde_output_order_v1_requests, + 2, + kde_output_order_v1_events, }; #endif diff --git a/src/detection/displayserver/linux/wayland/kde-output.c b/src/detection/displayserver/linux/wayland/kde-output.c index ca7e9a50a..555362ec7 100644 --- a/src/detection/displayserver/linux/wayland/kde-output.c +++ b/src/detection/displayserver/linux/wayland/kde-output.c @@ -1,13 +1,12 @@ #ifdef FF_HAVE_WAYLAND -#include "wayland.h" -#include "kde-output-device-v2-client-protocol.h" -#include "kde-output-order-v1-client-protocol.h" -#include "common/edidHelper.h" -#include "common/base64.h" +# include "wayland.h" +# include "kde-output-device-v2-client-protocol.h" +# include "kde-output-order-v1-client-protocol.h" +# include "common/edidHelper.h" +# include "common/base64.h" -typedef struct WaylandKdeMode -{ +typedef struct WaylandKdeMode { int32_t width; int32_t height; int32_t refreshRate; @@ -15,21 +14,18 @@ typedef struct WaylandKdeMode struct kde_output_device_mode_v2* pMode; } WaylandKdeMode; -static void waylandKdeModeSizeListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_mode_v2 *_, int32_t width, int32_t height) -{ +static void waylandKdeModeSizeListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_mode_v2* _, int32_t width, int32_t height) { WaylandKdeMode* mode = (WaylandKdeMode*) data; mode->width = width; mode->height = height; } -static void waylandKdeModeRefreshListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_mode_v2 *_, int32_t rate) -{ +static void waylandKdeModeRefreshListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_mode_v2* _, int32_t rate) { WaylandKdeMode* mode = (WaylandKdeMode*) data; mode->refreshRate = rate; } -static void waylandKdeModePreferredListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_mode_v2 *_) -{ +static void waylandKdeModePreferredListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_mode_v2* _) { WaylandKdeMode* mode = (WaylandKdeMode*) data; mode->preferred = true; } @@ -42,88 +38,92 @@ static const struct kde_output_device_mode_v2_listener modeListener = { .flags = (void*) stubListener, }; -static void waylandKdeModeListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, struct kde_output_device_mode_v2 *mode) -{ +static void waylandKdeModeListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, struct kde_output_device_mode_v2* mode) { WaylandDisplay* wldata = (WaylandDisplay*) data; - if (!wldata->internal) return; + if (!wldata->internal) { + return; + } WaylandKdeMode* newMode = ffListAdd((FFlist*) wldata->internal); - *newMode = (WaylandKdeMode) { .pMode = mode }; + *newMode = (WaylandKdeMode) {.pMode = mode}; // Strangely, the listener is called only in this function, but not in `waylandKdeCurrentModeListener` - wldata->parent->ffwl_proxy_add_listener((struct wl_proxy *) mode, (void (**)(void)) &modeListener, newMode); + wldata->parent->ffwl_proxy_add_listener((struct wl_proxy*) mode, (void (**)(void)) &modeListener, newMode); } -static void waylandKdeCurrentModeListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2 *_, struct kde_output_device_mode_v2 *mode) -{ +static void waylandKdeCurrentModeListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, struct kde_output_device_mode_v2* mode) { // waylandKdeModeListener is always run before this WaylandDisplay* wldata = (WaylandDisplay*) data; - if (!wldata->internal) return; + if (!wldata->internal) { + return; + } int set = 0; - FF_LIST_FOR_EACH(WaylandKdeMode, m, *(FFlist*) wldata->internal) - { - if (m->pMode == mode) - { + FF_LIST_FOR_EACH (WaylandKdeMode, m, *(FFlist*) wldata->internal) { + if (m->pMode == mode) { wldata->width = m->width; wldata->height = m->height; wldata->refreshRate = m->refreshRate; - if (++set == 2) break; + if (++set == 2) { + break; + } } - if (m->preferred) - { + if (m->preferred) { wldata->preferredWidth = m->width; wldata->preferredHeight = m->height; wldata->preferredRefreshRate = m->refreshRate; - if (++set == 2) break; + if (++set == 2) { + break; + } } } } -static void waylandKdeScaleListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, wl_fixed_t scale) -{ +static void waylandKdeScaleListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, wl_fixed_t scale) { WaylandDisplay* wldata = (WaylandDisplay*) data; wldata->dpi = (uint32_t) scale * 3 / 8; // wl_fixed_to_double(scale) * 96; } -static void waylandKdeEdidListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, const char* raw) -{ - if (!*raw) return; +static void waylandKdeEdidListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, const char* raw) { + if (!*raw) { + return; + } WaylandDisplay* wldata = (WaylandDisplay*) data; FF_STRBUF_AUTO_DESTROY b64 = ffStrbufCreateStatic(raw); FF_STRBUF_AUTO_DESTROY edid = ffBase64DecodeStrbuf(&b64); - if (edid.length < 128) return; + if (edid.length < 128) { + return; + } ffEdidGetName((const uint8_t*) edid.chars, &wldata->edidName); wldata->hdrSupported = ffEdidGetHdrCompatible((const uint8_t*) edid.chars, edid.length); ffEdidGetSerialAndManufactureDate((const uint8_t*) edid.chars, &wldata->serial, &wldata->myear, &wldata->mweek); wldata->hdrInfoAvailable = true; } -static void waylandKdeEnabledListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, int32_t enabled) -{ +static void waylandKdeEnabledListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* _, int32_t enabled) { WaylandDisplay* wldata = (WaylandDisplay*) data; - if (!enabled) wldata->internal = NULL; + if (!enabled) { + wldata->internal = NULL; + } } -static void waylandKdeGeometryListener(void *data, - FF_MAYBE_UNUSED struct kde_output_device_v2 *kde_output_device_v2, +static void waylandKdeGeometryListener(void* data, + FF_MAYBE_UNUSED struct kde_output_device_v2* kde_output_device_v2, FF_MAYBE_UNUSED int32_t x, FF_MAYBE_UNUSED int32_t y, int32_t physical_width, int32_t physical_height, FF_MAYBE_UNUSED int32_t subpixel, - FF_MAYBE_UNUSED const char *make, - FF_MAYBE_UNUSED const char *model, - int32_t transform) -{ + FF_MAYBE_UNUSED const char* make, + FF_MAYBE_UNUSED const char* model, + int32_t transform) { WaylandDisplay* display = data; display->physicalWidth = physical_width; display->physicalHeight = physical_height; display->transform = (enum wl_output_transform) transform; } -static void waylandKdeNameListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* kde_output_device_v2, const char *name) -{ +static void waylandKdeNameListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* kde_output_device_v2, const char* name) { WaylandDisplay* display = data; display->type = ffdsGetDisplayType(name); // As display->id is used as an internal identifier, we don't need it to be NUL terminated @@ -132,14 +132,12 @@ static void waylandKdeNameListener(void* data, FF_MAYBE_UNUSED struct kde_output ffStrbufAppendS(&display->name, name); } -static void waylandKdeHdrListener(void *data, FF_MAYBE_UNUSED struct kde_output_device_v2 *kde_output_device_v2, uint32_t hdr_enabled) -{ +static void waylandKdeHdrListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* kde_output_device_v2, uint32_t hdr_enabled) { WaylandDisplay* display = data; display->hdrEnabled = !!hdr_enabled; } -static void waylandKdeMaxBitsPerColorListener(void *data, FF_MAYBE_UNUSED struct kde_output_device_v2 *kde_output_device_v2, uint32_t max_bpc) -{ +static void waylandKdeMaxBitsPerColorListener(void* data, FF_MAYBE_UNUSED struct kde_output_device_v2* kde_output_device_v2, uint32_t max_bpc) { WaylandDisplay* display = data; display->bitDepth = (uint8_t) max_bpc; } @@ -184,11 +182,11 @@ static struct kde_output_device_v2_listener outputListener = { .removed = (void*) stubListener, }; -const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) -{ +const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &kde_output_device_v2_interface, version, name, kde_output_device_v2_interface.name, version, NULL); - if(output == NULL) + if (output == NULL) { return "Failed to create kde_output_device_v2"; + } FF_LIST_AUTO_DESTROY modes = ffListCreate(sizeof(WaylandKdeMode)); WaylandDisplay display = { @@ -201,21 +199,20 @@ const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* re .internal = &modes, }; - if (wldata->ffwl_proxy_add_listener(output, (void(**)(void)) &outputListener, &display) < 0) - { + if (wldata->ffwl_proxy_add_listener(output, (void (**)(void)) &outputListener, &display) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to add listener to kde_output_device_v2"; } - if (wldata->ffwl_display_roundtrip(wldata->display) < 0) - { + if (wldata->ffwl_display_roundtrip(wldata->display) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to roundtrip kde_output_device_v2"; } wldata->ffwl_proxy_destroy(output); - if(display.width <= 0 || display.height <= 0 || !display.internal) + if (display.width <= 0 || display.height <= 0 || !display.internal) { return "Failed to get display information from kde_output_device_v2"; + } uint32_t rotation = ffWaylandHandleRotation(&display); @@ -236,18 +233,17 @@ const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* re display.id, (uint32_t) display.physicalWidth, (uint32_t) display.physicalHeight, - "wayland-kde" - ); - if (item) - { - if (display.hdrEnabled) + "wayland-kde"); + if (item) { + if (display.hdrEnabled) { item->hdrStatus = FF_DISPLAY_HDR_STATUS_ENABLED; - else if (display.hdrSupported) + } else if (display.hdrSupported) { item->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; - else if (display.hdrInfoAvailable) + } else if (display.hdrInfoAvailable) { item->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; - else + } else { item->hdrStatus = FF_DISPLAY_HDR_STATUS_UNKNOWN; + } item->manufactureYear = display.myear; item->manufactureWeek = display.mweek; @@ -262,32 +258,29 @@ const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* re return NULL; } - -static void waylandKdeOutputOrderListener(void *data, FF_MAYBE_UNUSED struct kde_output_order_v1 *_, const char *output_name) -{ +static void waylandKdeOutputOrderListener(void* data, FF_MAYBE_UNUSED struct kde_output_order_v1* _, const char* output_name) { uint64_t* id = (uint64_t*) data; - if (*id == 0) + if (*id == 0) { *id = ffWaylandGenerateIdFromName(output_name); + } } -const char* ffWaylandHandleKdeOutputOrder(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) -{ +const char* ffWaylandHandleKdeOutputOrder(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &kde_output_order_v1_interface, version, name, kde_output_order_v1_interface.name, version, NULL); - if(output == NULL) + if (output == NULL) { return "Failed to create kde_output_order_v1"; + } struct kde_output_order_v1_listener orderListener = { .output = waylandKdeOutputOrderListener, .done = (void*) stubListener, }; - if (wldata->ffwl_proxy_add_listener(output, (void(**)(void)) &orderListener, &wldata->primaryDisplayId) < 0) - { + if (wldata->ffwl_proxy_add_listener(output, (void (**)(void)) &orderListener, &wldata->primaryDisplayId) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to add listener to kde_output_order_v1"; } - if (wldata->ffwl_display_roundtrip(wldata->display) < 0) - { + if (wldata->ffwl_display_roundtrip(wldata->display) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to roundtrip kde_output_order_v1"; } diff --git a/src/detection/displayserver/linux/wayland/wayland.c b/src/detection/displayserver/linux/wayland/wayland.c index 15198067d..80d8a02ff 100644 --- a/src/detection/displayserver/linux/wayland/wayland.c +++ b/src/detection/displayserver/linux/wayland/wayland.c @@ -8,131 +8,127 @@ #ifdef FF_HAVE_WAYLAND -#include +# include -#include "common/properties.h" +# include "common/properties.h" -#include "wayland.h" -#include "wlr-output-management-unstable-v1-client-protocol.h" -#include "kde-output-device-v2-client-protocol.h" -#include "kde-output-order-v1-client-protocol.h" -#include "xdg-output-unstable-v1-client-protocol.h" +# include "wayland.h" +# include "wlr-output-management-unstable-v1-client-protocol.h" +# include "kde-output-device-v2-client-protocol.h" +# include "kde-output-order-v1-client-protocol.h" +# include "xdg-output-unstable-v1-client-protocol.h" -#if __FreeBSD__ -#include -#include -#include -#endif +# if __FreeBSD__ +# include +# include +# include +# endif -static bool waylandDetectWM(int fd, FFDisplayServerResult* result) -{ -#if __linux__ || __GNU__ || (__FreeBSD__ && !__DragonFly__) +static bool waylandDetectWM(int fd, FFDisplayServerResult* result) { +# if __linux__ || __GNU__ || (__FreeBSD__ && !__DragonFly__) -#if __linux__ || __GNU__ +# if __linux__ || __GNU__ struct ucred ucred = {}; socklen_t len = sizeof(ucred); - if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1 || ucred.pid <= 0) + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1 || ucred.pid <= 0) { return false; + } FF_STRBUF_AUTO_DESTROY procPath = ffStrbufCreate(); - ffStrbufAppendF(&procPath, "/proc/%d/cmdline", ucred.pid); //We check the cmdline for the process name, because it is not trimmed. - if (!ffReadFileBuffer(procPath.chars, &result->wmProcessName)) + ffStrbufAppendF(&procPath, "/proc/%d/cmdline", ucred.pid); // We check the cmdline for the process name, because it is not trimmed. + if (!ffReadFileBuffer(procPath.chars, &result->wmProcessName)) { return false; -#else + } +# else struct xucred ucred = {}; socklen_t len = sizeof(ucred); - if (getsockopt(fd, AF_UNSPEC, LOCAL_PEERCRED, &ucred, &len) == -1 || ucred.cr_pid <= 0) + if (getsockopt(fd, AF_UNSPEC, LOCAL_PEERCRED, &ucred, &len) == -1 || ucred.cr_pid <= 0) { return false; + } size_t size = 4096; ffStrbufEnsureFixedLengthFree(&result->wmProcessName, (uint32_t) size); - if(sysctl((int[]){CTL_KERN, KERN_PROC, KERN_PROC_ARGS, ucred.cr_pid}, 4, result->wmProcessName.chars, &size, NULL, 0 ) != 0) + if (sysctl((int[]) {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, ucred.cr_pid}, 4, result->wmProcessName.chars, &size, NULL, 0) != 0) { return false; + } result->wmProcessName.length = (uint32_t) size - 1; -#endif +# endif // #1135: wl-restart is a special case const char* filename = strrchr(result->wmProcessName.chars, '/'); - if (filename) + if (filename) { filename++; - else + } else { filename = result->wmProcessName.chars; + } - if (ffStrEquals(filename, "wl-restart")) + if (ffStrEquals(filename, "wl-restart")) { ffStrbufSubstrAfterLastC(&result->wmProcessName, '\0'); + } - ffStrbufSubstrBeforeFirstC(&result->wmProcessName, '\0'); //Trim the arguments - ffStrbufSubstrAfterLastC(&result->wmProcessName, '/'); //Trim the path + ffStrbufSubstrBeforeFirstC(&result->wmProcessName, '\0'); // Trim the arguments + ffStrbufSubstrAfterLastC(&result->wmProcessName, '/'); // Trim the path return true; -#else +# else FF_UNUSED(fd, result); return false; -#endif +# endif } -static void waylandGlobalAddListener(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) -{ +static void waylandGlobalAddListener(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) { WaylandData* wldata = data; - if((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_GLOBAL) && ffStrEquals(interface, wldata->ffwl_output_interface->name)) - { + if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_GLOBAL) && ffStrEquals(interface, wldata->ffwl_output_interface->name)) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_GLOBAL; - if (ffWaylandHandleGlobalOutput(wldata, registry, name, version) != NULL) + if (ffWaylandHandleGlobalOutput(wldata, registry, name, version) != NULL) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_NONE; - } - else if((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_ZWLR) && ffStrEquals(interface, zwlr_output_manager_v1_interface.name)) - { + } + } else if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_ZWLR) && ffStrEquals(interface, zwlr_output_manager_v1_interface.name)) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_ZWLR; - if (ffWaylandHandleZwlrOutput(wldata, registry, name, version) != NULL) + if (ffWaylandHandleZwlrOutput(wldata, registry, name, version) != NULL) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_NONE; - } - else if((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_KDE) && ffStrEquals(interface, kde_output_device_v2_interface.name)) - { + } + } else if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_KDE) && ffStrEquals(interface, kde_output_device_v2_interface.name)) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_KDE; - if (ffWaylandHandleKdeOutput(wldata, registry, name, version) != NULL) + if (ffWaylandHandleKdeOutput(wldata, registry, name, version) != NULL) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_NONE; - } - else if(ffStrEquals(interface, kde_output_order_v1_interface.name)) - { + } + } else if (ffStrEquals(interface, kde_output_order_v1_interface.name)) { ffWaylandHandleKdeOutputOrder(wldata, registry, name, version); - } - else if((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_GLOBAL || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE) && ffStrEquals(interface, zxdg_output_manager_v1_interface.name)) - { + } else if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_GLOBAL || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE) && ffStrEquals(interface, zxdg_output_manager_v1_interface.name)) { ffWaylandHandleZxdgOutput(wldata, registry, name, version); } } -static FF_MAYBE_UNUSED bool matchDrmConnector(const char* connName, WaylandDisplay* wldata) -{ +static FF_MAYBE_UNUSED bool matchDrmConnector(const char* connName, WaylandDisplay* wldata) { // https://wayland.freedesktop.org/docs/html/apa.html#protocol-spec-wl_output-event-name // The doc says that "do not assume that the name is a reflection of an underlying DRM connector, X11 connection, etc." // However I can't find a better method to get the edid data const char* drmDirPath = "/sys/class/drm/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(drmDirPath); - if(dirp == NULL) + if (dirp == NULL) { return false; + } struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { + while ((entry = readdir(dirp)) != NULL) { const char* plainName = entry->d_name; - if (ffStrStartsWith(plainName, "card")) - { + if (ffStrStartsWith(plainName, "card")) { const char* tmp = strchr(plainName + strlen("card"), '-'); - if (tmp) plainName = tmp + 1; + if (tmp) { + plainName = tmp + 1; + } } - if (ffStrEquals(plainName, connName)) - { + if (ffStrEquals(plainName, connName)) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateF("%s%s/edid", drmDirPath, entry->d_name); uint8_t edidData[512]; ssize_t edidLength = ffReadFileData(path.chars, ARRAY_SIZE(edidData), edidData); - if (edidLength > 0 && edidLength % 128 == 0) - { + if (edidLength > 0 && edidLength % 128 == 0) { ffEdidGetName(edidData, &wldata->edidName); ffEdidGetHdrCompatible(edidData, (uint32_t) edidLength); ffEdidGetSerialAndManufactureDate(edidData, &wldata->serial, &wldata->myear, &wldata->mweek); @@ -145,35 +141,39 @@ static FF_MAYBE_UNUSED bool matchDrmConnector(const char* connName, WaylandDispl return false; } -void ffWaylandOutputNameListener(void* data, FF_MAYBE_UNUSED void* output, const char *name) -{ +void ffWaylandOutputNameListener(void* data, FF_MAYBE_UNUSED void* output, const char* name) { WaylandDisplay* display = data; - if (display->id) return; + if (display->id) { + return; + } display->type = ffdsGetDisplayType(name); - #if __linux__ - if (!display->edidName.length) +# if __linux__ + if (!display->edidName.length) { matchDrmConnector(name, display); - #endif + } +# endif display->id = ffWaylandGenerateIdFromName(name); ffStrbufAppendS(&display->name, name); } -void ffWaylandOutputDescriptionListener(void* data, FF_MAYBE_UNUSED void* output, const char* description) -{ +void ffWaylandOutputDescriptionListener(void* data, FF_MAYBE_UNUSED void* output, const char* description) { WaylandDisplay* display = data; - if (display->description.length) return; + if (display->description.length) { + return; + } - while (*description == ' ') ++description; - if (!ffStrEquals(description, "Unknown Display") && !ffStrContains(description, "(null)")) + while (*description == ' ') { + ++description; + } + if (!ffStrEquals(description, "Unknown Display") && !ffStrContains(description, "(null)")) { ffStrbufAppendS(&display->description, description); + } } -uint32_t ffWaylandHandleRotation(WaylandDisplay* display) -{ +uint32_t ffWaylandHandleRotation(WaylandDisplay* display) { uint32_t rotation; - switch(display->transform) - { + switch (display->transform) { case WL_OUTPUT_TRANSFORM_FLIPPED_90: case WL_OUTPUT_TRANSFORM_90: rotation = 90; @@ -191,8 +191,7 @@ uint32_t ffWaylandHandleRotation(WaylandDisplay* display) break; } - switch(rotation) - { + switch (rotation) { case 90: case 270: { int32_t temp = display->width; @@ -210,10 +209,10 @@ uint32_t ffWaylandHandleRotation(WaylandDisplay* display) return rotation; } -const char* ffdsConnectWayland(FFDisplayServerResult* result) -{ - if (getenv("XDG_RUNTIME_DIR") == NULL) +const char* ffdsConnectWayland(FFDisplayServerResult* result) { + if (getenv("XDG_RUNTIME_DIR") == NULL) { return "Wayland requires $XDG_RUNTIME_DIR being set"; + } FF_LIBRARY_LOAD_MESSAGE(wayland, "libwayland-client" FF_LIBRARY_EXTENSION, 1) @@ -232,14 +231,14 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(wayland, data, wl_output_interface) data.display = ffwl_display_connect(NULL); - if(data.display == NULL) + if (data.display == NULL) { return "wl_display_connect returned NULL"; + } waylandDetectWM(ffwl_display_get_fd(data.display), result); struct wl_proxy* registry = ffwl_proxy_marshal_constructor((struct wl_proxy*) data.display, WL_DISPLAY_GET_REGISTRY, ffwl_registry_interface, NULL); - if(registry == NULL) - { + if (registry == NULL) { ffwl_display_disconnect(data.display); return "wl_display_get_registry returned NULL"; } @@ -248,37 +247,34 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) struct wl_registry_listener registry_listener = { .global = waylandGlobalAddListener, - .global_remove = (void*) stubListener - }; + .global_remove = (void*) stubListener}; - data.ffwl_proxy_add_listener(registry, (void(**)(void)) ®istry_listener, &data); + data.ffwl_proxy_add_listener(registry, (void (**)(void)) ®istry_listener, &data); data.ffwl_display_roundtrip(data.display); - if (data.zxdgOutputManager) + if (data.zxdgOutputManager) { data.ffwl_proxy_destroy(data.zxdgOutputManager); + } data.ffwl_proxy_destroy(registry); ffwl_display_disconnect(data.display); - if(data.primaryDisplayId == 0 && result->wmProcessName.length > 0) - { + if (data.primaryDisplayId == 0 && result->wmProcessName.length > 0) { const char* fileName = ffStrbufEqualS(&result->wmProcessName, "gnome-shell") ? "monitors.xml" : ffStrbufEqualS(&result->wmProcessName, "cinnamon") - ? "cinnamon-monitors.xml" - : NULL; - if (fileName) - { + ? "cinnamon-monitors.xml" + : NULL; + if (fileName) { FF_STRBUF_AUTO_DESTROY monitorsXml = ffStrbufCreate(); - FF_LIST_FOR_EACH(FFstrbuf, basePath, instance.state.platform.configDirs) - { + FF_LIST_FOR_EACH (FFstrbuf, basePath, instance.state.platform.configDirs) { char path[1024]; snprintf(path, ARRAY_SIZE(path), "%s%s", basePath->chars, fileName); - if (ffReadFileBuffer(path, &monitorsXml)) + if (ffReadFileBuffer(path, &monitorsXml)) { break; + } } - if (monitorsXml.length) - { + if (monitorsXml.length) { // // // @@ -303,14 +299,11 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) // // uint32_t start = ffStrbufFirstIndexS(&monitorsXml, "yes"); - if (start < monitorsXml.length) - { + if (start < monitorsXml.length) { start = ffStrbufNextIndexS(&monitorsXml, start, ""); - if (start < monitorsXml.length) - { + if (start < monitorsXml.length) { uint32_t end = ffStrbufNextIndexS(&monitorsXml, start, ""); - if (end < monitorsXml.length) - { + if (end < monitorsXml.length) { ffStrbufSubstrBefore(&monitorsXml, end); const char* name = monitorsXml.chars + start + strlen(""); data.primaryDisplayId = ffWaylandGenerateIdFromName(name); @@ -321,29 +314,25 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) } } - if(data.primaryDisplayId) - { - FF_LIST_FOR_EACH(FFDisplayResult, d, data.result->displays) - { - if(d->id == data.primaryDisplayId) - { + if (data.primaryDisplayId) { + FF_LIST_FOR_EACH (FFDisplayResult, d, data.result->displays) { + if (d->id == data.primaryDisplayId) { d->primary = true; break; } } } - //We successfully connected to wayland and detected the display. - //So we can set set the session type to wayland. - //This is used as an indicator that we are running wayland by the x11 backends. + // We successfully connected to wayland and detected the display. + // So we can set set the session type to wayland. + // This is used as an indicator that we are running wayland by the x11 backends. ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND); return NULL; } #else -const char* ffdsConnectWayland(FF_MAYBE_UNUSED FFDisplayServerResult* result) -{ +const char* ffdsConnectWayland(FF_MAYBE_UNUSED FFDisplayServerResult* result) { return "Fastfetch was compiled without Wayland support"; } diff --git a/src/detection/displayserver/linux/wayland/wayland.h b/src/detection/displayserver/linux/wayland/wayland.h index 4466bf36a..5531b9ffb 100644 --- a/src/detection/displayserver/linux/wayland/wayland.h +++ b/src/detection/displayserver/linux/wayland/wayland.h @@ -2,23 +2,21 @@ #ifdef FF_HAVE_WAYLAND -#include "common/library.h" -#include "common/stringUtils.h" +# include "common/library.h" +# include "common/stringUtils.h" -#include +# include -#include "../displayserver_linux.h" +# include "../displayserver_linux.h" -typedef enum __attribute__((__packed__)) WaylandProtocolType -{ +typedef enum __attribute__((__packed__)) WaylandProtocolType { FF_WAYLAND_PROTOCOL_TYPE_NONE, FF_WAYLAND_PROTOCOL_TYPE_GLOBAL, FF_WAYLAND_PROTOCOL_TYPE_ZWLR, FF_WAYLAND_PROTOCOL_TYPE_KDE, } WaylandProtocolType; -typedef struct WaylandData -{ +typedef struct WaylandData { FFDisplayServerResult* result; FF_LIBRARY_SYMBOL(wl_proxy_marshal_constructor_versioned) FF_LIBRARY_SYMBOL(wl_proxy_add_listener) @@ -31,8 +29,7 @@ typedef struct WaylandData struct wl_proxy* zxdgOutputManager; } WaylandData; -typedef struct WaylandDisplay -{ +typedef struct WaylandDisplay { WaylandData* parent; void* internal; int32_t width; @@ -59,23 +56,22 @@ typedef struct WaylandDisplay uint8_t bitDepth; } WaylandDisplay; -inline static void stubListener(void* data, ...) -{ +inline static void stubListener(void* data, ...) { (void) data; } -inline static uint64_t ffWaylandGenerateIdFromName(const char* name) -{ +inline static uint64_t ffWaylandGenerateIdFromName(const char* name) { uint64_t id = 0; size_t len = strlen(name); - if (len > sizeof(id)) + if (len > sizeof(id)) { memcpy(&id, name + (len - sizeof(id)), sizeof(id)); // copy the last 8 bytes - else if (len > 0) + } else if (len > 0) { memcpy(&id, name, len); + } return id; } -void ffWaylandOutputNameListener(void* data, FF_MAYBE_UNUSED void* output, const char *name); +void ffWaylandOutputNameListener(void* data, FF_MAYBE_UNUSED void* output, const char* name); void ffWaylandOutputDescriptionListener(void* data, FF_MAYBE_UNUSED void* output, const char* description); // Modifies content of display. Don't call this function when calling ffdsAppendDisplay uint32_t ffWaylandHandleRotation(WaylandDisplay* display); diff --git a/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-client-protocol.h b/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-client-protocol.h index 2f848e6a6..da3a25430 100644 --- a/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-client-protocol.h +++ b/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-client-protocol.h @@ -7,7 +7,7 @@ #include #include -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -69,7 +69,7 @@ struct zwlr_output_manager_v1; struct zwlr_output_mode_v1; #ifndef ZWLR_OUTPUT_MANAGER_V1_INTERFACE -#define ZWLR_OUTPUT_MANAGER_V1_INTERFACE +# define ZWLR_OUTPUT_MANAGER_V1_INTERFACE /** * @page page_iface_zwlr_output_manager_v1 zwlr_output_manager_v1 * @section page_iface_zwlr_output_manager_v1_desc Description @@ -138,7 +138,7 @@ struct zwlr_output_mode_v1; extern const struct wl_interface zwlr_output_manager_v1_interface; #endif #ifndef ZWLR_OUTPUT_HEAD_V1_INTERFACE -#define ZWLR_OUTPUT_HEAD_V1_INTERFACE +# define ZWLR_OUTPUT_HEAD_V1_INTERFACE /** * @page page_iface_zwlr_output_head_v1 zwlr_output_head_v1 * @section page_iface_zwlr_output_head_v1_desc Description @@ -179,7 +179,7 @@ extern const struct wl_interface zwlr_output_manager_v1_interface; extern const struct wl_interface zwlr_output_head_v1_interface; #endif #ifndef ZWLR_OUTPUT_MODE_V1_INTERFACE -#define ZWLR_OUTPUT_MODE_V1_INTERFACE +# define ZWLR_OUTPUT_MODE_V1_INTERFACE /** * @page page_iface_zwlr_output_mode_v1 zwlr_output_mode_v1 * @section page_iface_zwlr_output_mode_v1_desc Description @@ -210,7 +210,7 @@ extern const struct wl_interface zwlr_output_head_v1_interface; extern const struct wl_interface zwlr_output_mode_v1_interface; #endif #ifndef ZWLR_OUTPUT_CONFIGURATION_V1_INTERFACE -#define ZWLR_OUTPUT_CONFIGURATION_V1_INTERFACE +# define ZWLR_OUTPUT_CONFIGURATION_V1_INTERFACE /** * @page page_iface_zwlr_output_configuration_v1 zwlr_output_configuration_v1 * @section page_iface_zwlr_output_configuration_v1_desc Description @@ -245,7 +245,7 @@ extern const struct wl_interface zwlr_output_mode_v1_interface; extern const struct wl_interface zwlr_output_configuration_v1_interface; #endif #ifndef ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_INTERFACE -#define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_INTERFACE +# define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_INTERFACE /** * @page page_iface_zwlr_output_configuration_head_v1 zwlr_output_configuration_head_v1 * @section page_iface_zwlr_output_configuration_head_v1_desc Description @@ -271,58 +271,59 @@ extern const struct wl_interface zwlr_output_configuration_head_v1_interface; * @struct zwlr_output_manager_v1_listener */ struct zwlr_output_manager_v1_listener { - /** - * introduce a new head - * - * This event introduces a new head. This happens whenever a new - * head appears (e.g. a monitor is plugged in) or after the output - * manager is bound. - */ - void (*head)(void *data, - struct zwlr_output_manager_v1 *zwlr_output_manager_v1, - struct zwlr_output_head_v1 *head); - /** - * sent all information about current configuration - * - * This event is sent after all information has been sent after - * binding to the output manager object and after any subsequent - * changes. This applies to child head and mode objects as well. In - * other words, this event is sent whenever a head or mode is - * created or destroyed and whenever one of their properties has - * been changed. Not all state is re-sent each time the current - * configuration changes: only the actual changes are sent. - * - * This allows changes to the output configuration to be seen as - * atomic, even if they happen via multiple events. - * - * A serial is sent to be used in a future create_configuration - * request. - * @param serial current configuration serial - */ - void (*done)(void *data, - struct zwlr_output_manager_v1 *zwlr_output_manager_v1, - uint32_t serial); - /** - * the compositor has finished with the manager - * - * This event indicates that the compositor is done sending - * manager events. The compositor will destroy the object - * immediately after sending this event, so it will become invalid - * and the client should release any resources associated with it. - */ - void (*finished)(void *data, - struct zwlr_output_manager_v1 *zwlr_output_manager_v1); + /** + * introduce a new head + * + * This event introduces a new head. This happens whenever a new + * head appears (e.g. a monitor is plugged in) or after the output + * manager is bound. + */ + void (*head)(void* data, + struct zwlr_output_manager_v1* zwlr_output_manager_v1, + struct zwlr_output_head_v1* head); + /** + * sent all information about current configuration + * + * This event is sent after all information has been sent after + * binding to the output manager object and after any subsequent + * changes. This applies to child head and mode objects as well. In + * other words, this event is sent whenever a head or mode is + * created or destroyed and whenever one of their properties has + * been changed. Not all state is re-sent each time the current + * configuration changes: only the actual changes are sent. + * + * This allows changes to the output configuration to be seen as + * atomic, even if they happen via multiple events. + * + * A serial is sent to be used in a future create_configuration + * request. + * @param serial current configuration serial + */ + void (*done)(void* data, + struct zwlr_output_manager_v1* zwlr_output_manager_v1, + uint32_t serial); + /** + * the compositor has finished with the manager + * + * This event indicates that the compositor is done sending + * manager events. The compositor will destroy the object + * immediately after sending this event, so it will become invalid + * and the client should release any resources associated with it. + */ + void (*finished)(void* data, + struct zwlr_output_manager_v1* zwlr_output_manager_v1); }; /** * @ingroup iface_zwlr_output_manager_v1 */ static inline int -zwlr_output_manager_v1_add_listener(struct zwlr_output_manager_v1 *zwlr_output_manager_v1, - const struct zwlr_output_manager_v1_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) zwlr_output_manager_v1, - (void (**)(void)) listener, data); +zwlr_output_manager_v1_add_listener(struct zwlr_output_manager_v1* zwlr_output_manager_v1, + const struct zwlr_output_manager_v1_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) zwlr_output_manager_v1, + (void (**)(void)) listener, + data); } #define ZWLR_OUTPUT_MANAGER_V1_CREATE_CONFIGURATION 0 @@ -352,29 +353,25 @@ zwlr_output_manager_v1_add_listener(struct zwlr_output_manager_v1 *zwlr_output_m /** @ingroup iface_zwlr_output_manager_v1 */ static inline void -zwlr_output_manager_v1_set_user_data(struct zwlr_output_manager_v1 *zwlr_output_manager_v1, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) zwlr_output_manager_v1, user_data); +zwlr_output_manager_v1_set_user_data(struct zwlr_output_manager_v1* zwlr_output_manager_v1, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) zwlr_output_manager_v1, user_data); } /** @ingroup iface_zwlr_output_manager_v1 */ -static inline void * -zwlr_output_manager_v1_get_user_data(struct zwlr_output_manager_v1 *zwlr_output_manager_v1) -{ - return wl_proxy_get_user_data((struct wl_proxy *) zwlr_output_manager_v1); +static inline void* +zwlr_output_manager_v1_get_user_data(struct zwlr_output_manager_v1* zwlr_output_manager_v1) { + return wl_proxy_get_user_data((struct wl_proxy*) zwlr_output_manager_v1); } static inline uint32_t -zwlr_output_manager_v1_get_version(struct zwlr_output_manager_v1 *zwlr_output_manager_v1) -{ - return wl_proxy_get_version((struct wl_proxy *) zwlr_output_manager_v1); +zwlr_output_manager_v1_get_version(struct zwlr_output_manager_v1* zwlr_output_manager_v1) { + return wl_proxy_get_version((struct wl_proxy*) zwlr_output_manager_v1); } /** @ingroup iface_zwlr_output_manager_v1 */ static inline void -zwlr_output_manager_v1_destroy(struct zwlr_output_manager_v1 *zwlr_output_manager_v1) -{ - wl_proxy_destroy((struct wl_proxy *) zwlr_output_manager_v1); +zwlr_output_manager_v1_destroy(struct zwlr_output_manager_v1* zwlr_output_manager_v1) { + wl_proxy_destroy((struct wl_proxy*) zwlr_output_manager_v1); } // /** @@ -411,16 +408,16 @@ zwlr_output_manager_v1_destroy(struct zwlr_output_manager_v1 *zwlr_output_manage // } #ifndef ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENUM -#define ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENUM +# define ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENUM enum zwlr_output_head_v1_adaptive_sync_state { - /** - * adaptive sync is disabled - */ - ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED = 0, - /** - * adaptive sync is enabled - */ - ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED = 1, + /** + * adaptive sync is disabled + */ + ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED = 0, + /** + * adaptive sync is enabled + */ + ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED = 1, }; #endif /* ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENUM */ @@ -429,253 +426,254 @@ enum zwlr_output_head_v1_adaptive_sync_state { * @struct zwlr_output_head_v1_listener */ struct zwlr_output_head_v1_listener { - /** - * head name - * - * This event describes the head name. - * - * The naming convention is compositor defined, but limited to - * alphanumeric characters and dashes (-). Each name is unique - * among all wlr_output_head objects, but if a wlr_output_head - * object is destroyed the same name may be reused later. The names - * will also remain consistent across sessions with the same - * hardware and software configuration. - * - * Examples of names include 'HDMI-A-1', 'WL-1', 'X11-1', etc. - * However, do not assume that the name is a reflection of an - * underlying DRM connector, X11 connection, etc. - * - * If this head matches a wl_output, the wl_output.name event must - * report the same name. - * - * The name event is sent after a wlr_output_head object is - * created. This event is only sent once per object, and the name - * does not change over the lifetime of the wlr_output_head object. - */ - void (*name)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - const char *name); - /** - * head description - * - * This event describes a human-readable description of the head. - * - * The description is a UTF-8 string with no convention defined for - * its contents. Examples might include 'Foocorp 11" Display' or - * 'Virtual X11 output via :1'. However, do not assume that the - * name is a reflection of the make, model, serial of the - * underlying DRM connector or the display name of the underlying - * X11 connection, etc. - * - * If this head matches a wl_output, the wl_output.description - * event must report the same name. - * - * The description event is sent after a wlr_output_head object is - * created. This event is only sent once per object, and the - * description does not change over the lifetime of the - * wlr_output_head object. - */ - void (*description)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - const char *description); - /** - * head physical size - * - * This event describes the physical size of the head. This event - * is only sent if the head has a physical size (e.g. is not a - * projector or a virtual device). - * - * The physical size event is sent after a wlr_output_head object - * is created. This event is only sent once per object, and the - * physical size does not change over the lifetime of the - * wlr_output_head object. - * @param width width in millimeters of the output - * @param height height in millimeters of the output - */ - void (*physical_size)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - int32_t width, - int32_t height); - /** - * introduce a mode - * - * This event introduces a mode for this head. It is sent once - * per supported mode. - */ - void (*mode)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - struct zwlr_output_mode_v1 *mode); - /** - * head is enabled or disabled - * - * This event describes whether the head is enabled. A disabled - * head is not mapped to a region of the global compositor space. - * - * When a head is disabled, some properties (current_mode, - * position, transform and scale) are irrelevant. - * @param enabled zero if disabled, non-zero if enabled - */ - void (*enabled)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - int32_t enabled); - /** - * current mode - * - * This event describes the mode currently in use for this head. - * It is only sent if the output is enabled. - */ - void (*current_mode)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - struct zwlr_output_mode_v1 *mode); - /** - * current position - * - * This events describes the position of the head in the global - * compositor space. It is only sent if the output is enabled. - * @param x x position within the global compositor space - * @param y y position within the global compositor space - */ - void (*position)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - int32_t x, - int32_t y); - /** - * current transformation - * - * This event describes the transformation currently applied to - * the head. It is only sent if the output is enabled. - */ - void (*transform)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - int32_t transform); - /** - * current scale - * - * This events describes the scale of the head in the global - * compositor space. It is only sent if the output is enabled. - */ - void (*scale)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - wl_fixed_t scale); - /** - * the head has disappeared - * - * This event indicates that the head is no longer available. The - * head object becomes inert. Clients should send a destroy request - * and release any resources associated with it. - */ - void (*finished)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1); - /** - * head manufacturer - * - * This event describes the manufacturer of the head. - * - * Together with the model and serial_number events the purpose is - * to allow clients to recognize heads from previous sessions and - * for example load head-specific configurations back. - * - * It is not guaranteed this event will be ever sent. A reason for - * that can be that the compositor does not have information about - * the make of the head or the definition of a make is not sensible - * in the current setup, for example in a virtual session. Clients - * can still try to identify the head by available information from - * other events but should be aware that there is an increased risk - * of false positives. - * - * If sent, the make event is sent after a wlr_output_head object - * is created and only sent once per object. The make does not - * change over the lifetime of the wlr_output_head object. - * - * It is not recommended to display the make string in UI to users. - * For that the string provided by the description event should be - * preferred. - * @since 2 - */ - void (*make)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - const char *make); - /** - * head model - * - * This event describes the model of the head. - * - * Together with the make and serial_number events the purpose is - * to allow clients to recognize heads from previous sessions and - * for example load head-specific configurations back. - * - * It is not guaranteed this event will be ever sent. A reason for - * that can be that the compositor does not have information about - * the model of the head or the definition of a model is not - * sensible in the current setup, for example in a virtual session. - * Clients can still try to identify the head by available - * information from other events but should be aware that there is - * an increased risk of false positives. - * - * If sent, the model event is sent after a wlr_output_head object - * is created and only sent once per object. The model does not - * change over the lifetime of the wlr_output_head object. - * - * It is not recommended to display the model string in UI to - * users. For that the string provided by the description event - * should be preferred. - * @since 2 - */ - void (*model)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - const char *model); - /** - * head serial number - * - * This event describes the serial number of the head. - * - * Together with the make and model events the purpose is to allow - * clients to recognize heads from previous sessions and for - * example load head- specific configurations back. - * - * It is not guaranteed this event will be ever sent. A reason for - * that can be that the compositor does not have information about - * the serial number of the head or the definition of a serial - * number is not sensible in the current setup. Clients can still - * try to identify the head by available information from other - * events but should be aware that there is an increased risk of - * false positives. - * - * If sent, the serial number event is sent after a wlr_output_head - * object is created and only sent once per object. The serial - * number does not change over the lifetime of the wlr_output_head - * object. - * - * It is not recommended to display the serial_number string in UI - * to users. For that the string provided by the description event - * should be preferred. - * @since 2 - */ - void (*serial_number)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - const char *serial_number); - /** - * current adaptive sync state - * - * This event describes whether adaptive sync is currently - * enabled for the head or not. Adaptive sync is also known as - * Variable Refresh Rate or VRR. - * @since 4 - */ - void (*adaptive_sync)(void *data, - struct zwlr_output_head_v1 *zwlr_output_head_v1, - uint32_t state); + /** + * head name + * + * This event describes the head name. + * + * The naming convention is compositor defined, but limited to + * alphanumeric characters and dashes (-). Each name is unique + * among all wlr_output_head objects, but if a wlr_output_head + * object is destroyed the same name may be reused later. The names + * will also remain consistent across sessions with the same + * hardware and software configuration. + * + * Examples of names include 'HDMI-A-1', 'WL-1', 'X11-1', etc. + * However, do not assume that the name is a reflection of an + * underlying DRM connector, X11 connection, etc. + * + * If this head matches a wl_output, the wl_output.name event must + * report the same name. + * + * The name event is sent after a wlr_output_head object is + * created. This event is only sent once per object, and the name + * does not change over the lifetime of the wlr_output_head object. + */ + void (*name)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + const char* name); + /** + * head description + * + * This event describes a human-readable description of the head. + * + * The description is a UTF-8 string with no convention defined for + * its contents. Examples might include 'Foocorp 11" Display' or + * 'Virtual X11 output via :1'. However, do not assume that the + * name is a reflection of the make, model, serial of the + * underlying DRM connector or the display name of the underlying + * X11 connection, etc. + * + * If this head matches a wl_output, the wl_output.description + * event must report the same name. + * + * The description event is sent after a wlr_output_head object is + * created. This event is only sent once per object, and the + * description does not change over the lifetime of the + * wlr_output_head object. + */ + void (*description)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + const char* description); + /** + * head physical size + * + * This event describes the physical size of the head. This event + * is only sent if the head has a physical size (e.g. is not a + * projector or a virtual device). + * + * The physical size event is sent after a wlr_output_head object + * is created. This event is only sent once per object, and the + * physical size does not change over the lifetime of the + * wlr_output_head object. + * @param width width in millimeters of the output + * @param height height in millimeters of the output + */ + void (*physical_size)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + int32_t width, + int32_t height); + /** + * introduce a mode + * + * This event introduces a mode for this head. It is sent once + * per supported mode. + */ + void (*mode)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + struct zwlr_output_mode_v1* mode); + /** + * head is enabled or disabled + * + * This event describes whether the head is enabled. A disabled + * head is not mapped to a region of the global compositor space. + * + * When a head is disabled, some properties (current_mode, + * position, transform and scale) are irrelevant. + * @param enabled zero if disabled, non-zero if enabled + */ + void (*enabled)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + int32_t enabled); + /** + * current mode + * + * This event describes the mode currently in use for this head. + * It is only sent if the output is enabled. + */ + void (*current_mode)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + struct zwlr_output_mode_v1* mode); + /** + * current position + * + * This events describes the position of the head in the global + * compositor space. It is only sent if the output is enabled. + * @param x x position within the global compositor space + * @param y y position within the global compositor space + */ + void (*position)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + int32_t x, + int32_t y); + /** + * current transformation + * + * This event describes the transformation currently applied to + * the head. It is only sent if the output is enabled. + */ + void (*transform)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + int32_t transform); + /** + * current scale + * + * This events describes the scale of the head in the global + * compositor space. It is only sent if the output is enabled. + */ + void (*scale)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + wl_fixed_t scale); + /** + * the head has disappeared + * + * This event indicates that the head is no longer available. The + * head object becomes inert. Clients should send a destroy request + * and release any resources associated with it. + */ + void (*finished)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1); + /** + * head manufacturer + * + * This event describes the manufacturer of the head. + * + * Together with the model and serial_number events the purpose is + * to allow clients to recognize heads from previous sessions and + * for example load head-specific configurations back. + * + * It is not guaranteed this event will be ever sent. A reason for + * that can be that the compositor does not have information about + * the make of the head or the definition of a make is not sensible + * in the current setup, for example in a virtual session. Clients + * can still try to identify the head by available information from + * other events but should be aware that there is an increased risk + * of false positives. + * + * If sent, the make event is sent after a wlr_output_head object + * is created and only sent once per object. The make does not + * change over the lifetime of the wlr_output_head object. + * + * It is not recommended to display the make string in UI to users. + * For that the string provided by the description event should be + * preferred. + * @since 2 + */ + void (*make)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + const char* make); + /** + * head model + * + * This event describes the model of the head. + * + * Together with the make and serial_number events the purpose is + * to allow clients to recognize heads from previous sessions and + * for example load head-specific configurations back. + * + * It is not guaranteed this event will be ever sent. A reason for + * that can be that the compositor does not have information about + * the model of the head or the definition of a model is not + * sensible in the current setup, for example in a virtual session. + * Clients can still try to identify the head by available + * information from other events but should be aware that there is + * an increased risk of false positives. + * + * If sent, the model event is sent after a wlr_output_head object + * is created and only sent once per object. The model does not + * change over the lifetime of the wlr_output_head object. + * + * It is not recommended to display the model string in UI to + * users. For that the string provided by the description event + * should be preferred. + * @since 2 + */ + void (*model)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + const char* model); + /** + * head serial number + * + * This event describes the serial number of the head. + * + * Together with the make and model events the purpose is to allow + * clients to recognize heads from previous sessions and for + * example load head- specific configurations back. + * + * It is not guaranteed this event will be ever sent. A reason for + * that can be that the compositor does not have information about + * the serial number of the head or the definition of a serial + * number is not sensible in the current setup. Clients can still + * try to identify the head by available information from other + * events but should be aware that there is an increased risk of + * false positives. + * + * If sent, the serial number event is sent after a wlr_output_head + * object is created and only sent once per object. The serial + * number does not change over the lifetime of the wlr_output_head + * object. + * + * It is not recommended to display the serial_number string in UI + * to users. For that the string provided by the description event + * should be preferred. + * @since 2 + */ + void (*serial_number)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + const char* serial_number); + /** + * current adaptive sync state + * + * This event describes whether adaptive sync is currently + * enabled for the head or not. Adaptive sync is also known as + * Variable Refresh Rate or VRR. + * @since 4 + */ + void (*adaptive_sync)(void* data, + struct zwlr_output_head_v1* zwlr_output_head_v1, + uint32_t state); }; /** * @ingroup iface_zwlr_output_head_v1 */ static inline int -zwlr_output_head_v1_add_listener(struct zwlr_output_head_v1 *zwlr_output_head_v1, - const struct zwlr_output_head_v1_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) zwlr_output_head_v1, - (void (**)(void)) listener, data); +zwlr_output_head_v1_add_listener(struct zwlr_output_head_v1* zwlr_output_head_v1, + const struct zwlr_output_head_v1_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) zwlr_output_head_v1, + (void (**)(void)) listener, + data); } #define ZWLR_OUTPUT_HEAD_V1_RELEASE 0 @@ -744,29 +742,25 @@ zwlr_output_head_v1_add_listener(struct zwlr_output_head_v1 *zwlr_output_head_v1 /** @ingroup iface_zwlr_output_head_v1 */ static inline void -zwlr_output_head_v1_set_user_data(struct zwlr_output_head_v1 *zwlr_output_head_v1, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) zwlr_output_head_v1, user_data); +zwlr_output_head_v1_set_user_data(struct zwlr_output_head_v1* zwlr_output_head_v1, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) zwlr_output_head_v1, user_data); } /** @ingroup iface_zwlr_output_head_v1 */ -static inline void * -zwlr_output_head_v1_get_user_data(struct zwlr_output_head_v1 *zwlr_output_head_v1) -{ - return wl_proxy_get_user_data((struct wl_proxy *) zwlr_output_head_v1); +static inline void* +zwlr_output_head_v1_get_user_data(struct zwlr_output_head_v1* zwlr_output_head_v1) { + return wl_proxy_get_user_data((struct wl_proxy*) zwlr_output_head_v1); } static inline uint32_t -zwlr_output_head_v1_get_version(struct zwlr_output_head_v1 *zwlr_output_head_v1) -{ - return wl_proxy_get_version((struct wl_proxy *) zwlr_output_head_v1); +zwlr_output_head_v1_get_version(struct zwlr_output_head_v1* zwlr_output_head_v1) { + return wl_proxy_get_version((struct wl_proxy*) zwlr_output_head_v1); } /** @ingroup iface_zwlr_output_head_v1 */ static inline void -zwlr_output_head_v1_destroy(struct zwlr_output_head_v1 *zwlr_output_head_v1) -{ - wl_proxy_destroy((struct wl_proxy *) zwlr_output_head_v1); +zwlr_output_head_v1_destroy(struct zwlr_output_head_v1* zwlr_output_head_v1) { + wl_proxy_destroy((struct wl_proxy*) zwlr_output_head_v1); } // /** @@ -787,57 +781,58 @@ zwlr_output_head_v1_destroy(struct zwlr_output_head_v1 *zwlr_output_head_v1) * @struct zwlr_output_mode_v1_listener */ struct zwlr_output_mode_v1_listener { - /** - * mode size - * - * This event describes the mode size. The size is given in - * physical hardware units of the output device. This is not - * necessarily the same as the output size in the global compositor - * space. For instance, the output may be scaled or transformed. - * @param width width of the mode in hardware units - * @param height height of the mode in hardware units - */ - void (*size)(void *data, - struct zwlr_output_mode_v1 *zwlr_output_mode_v1, - int32_t width, - int32_t height); - /** - * mode refresh rate - * - * This event describes the mode's fixed vertical refresh rate. - * It is only sent if the mode has a fixed refresh rate. - * @param refresh vertical refresh rate in mHz - */ - void (*refresh)(void *data, - struct zwlr_output_mode_v1 *zwlr_output_mode_v1, - int32_t refresh); - /** - * mode is preferred - * - * This event advertises this mode as preferred. - */ - void (*preferred)(void *data, - struct zwlr_output_mode_v1 *zwlr_output_mode_v1); - /** - * the mode has disappeared - * - * This event indicates that the mode is no longer available. The - * mode object becomes inert. Clients should send a destroy request - * and release any resources associated with it. - */ - void (*finished)(void *data, - struct zwlr_output_mode_v1 *zwlr_output_mode_v1); + /** + * mode size + * + * This event describes the mode size. The size is given in + * physical hardware units of the output device. This is not + * necessarily the same as the output size in the global compositor + * space. For instance, the output may be scaled or transformed. + * @param width width of the mode in hardware units + * @param height height of the mode in hardware units + */ + void (*size)(void* data, + struct zwlr_output_mode_v1* zwlr_output_mode_v1, + int32_t width, + int32_t height); + /** + * mode refresh rate + * + * This event describes the mode's fixed vertical refresh rate. + * It is only sent if the mode has a fixed refresh rate. + * @param refresh vertical refresh rate in mHz + */ + void (*refresh)(void* data, + struct zwlr_output_mode_v1* zwlr_output_mode_v1, + int32_t refresh); + /** + * mode is preferred + * + * This event advertises this mode as preferred. + */ + void (*preferred)(void* data, + struct zwlr_output_mode_v1* zwlr_output_mode_v1); + /** + * the mode has disappeared + * + * This event indicates that the mode is no longer available. The + * mode object becomes inert. Clients should send a destroy request + * and release any resources associated with it. + */ + void (*finished)(void* data, + struct zwlr_output_mode_v1* zwlr_output_mode_v1); }; /** * @ingroup iface_zwlr_output_mode_v1 */ static inline int -zwlr_output_mode_v1_add_listener(struct zwlr_output_mode_v1 *zwlr_output_mode_v1, - const struct zwlr_output_mode_v1_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) zwlr_output_mode_v1, - (void (**)(void)) listener, data); +zwlr_output_mode_v1_add_listener(struct zwlr_output_mode_v1* zwlr_output_mode_v1, + const struct zwlr_output_mode_v1_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) zwlr_output_mode_v1, + (void (**)(void)) listener, + data); } #define ZWLR_OUTPUT_MODE_V1_RELEASE 0 @@ -866,29 +861,25 @@ zwlr_output_mode_v1_add_listener(struct zwlr_output_mode_v1 *zwlr_output_mode_v1 /** @ingroup iface_zwlr_output_mode_v1 */ static inline void -zwlr_output_mode_v1_set_user_data(struct zwlr_output_mode_v1 *zwlr_output_mode_v1, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) zwlr_output_mode_v1, user_data); +zwlr_output_mode_v1_set_user_data(struct zwlr_output_mode_v1* zwlr_output_mode_v1, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) zwlr_output_mode_v1, user_data); } /** @ingroup iface_zwlr_output_mode_v1 */ -static inline void * -zwlr_output_mode_v1_get_user_data(struct zwlr_output_mode_v1 *zwlr_output_mode_v1) -{ - return wl_proxy_get_user_data((struct wl_proxy *) zwlr_output_mode_v1); +static inline void* +zwlr_output_mode_v1_get_user_data(struct zwlr_output_mode_v1* zwlr_output_mode_v1) { + return wl_proxy_get_user_data((struct wl_proxy*) zwlr_output_mode_v1); } static inline uint32_t -zwlr_output_mode_v1_get_version(struct zwlr_output_mode_v1 *zwlr_output_mode_v1) -{ - return wl_proxy_get_version((struct wl_proxy *) zwlr_output_mode_v1); +zwlr_output_mode_v1_get_version(struct zwlr_output_mode_v1* zwlr_output_mode_v1) { + return wl_proxy_get_version((struct wl_proxy*) zwlr_output_mode_v1); } /** @ingroup iface_zwlr_output_mode_v1 */ static inline void -zwlr_output_mode_v1_destroy(struct zwlr_output_mode_v1 *zwlr_output_mode_v1) -{ - wl_proxy_destroy((struct wl_proxy *) zwlr_output_mode_v1); +zwlr_output_mode_v1_destroy(struct zwlr_output_mode_v1* zwlr_output_mode_v1) { + wl_proxy_destroy((struct wl_proxy*) zwlr_output_mode_v1); } // /** @@ -905,20 +896,20 @@ zwlr_output_mode_v1_destroy(struct zwlr_output_mode_v1 *zwlr_output_mode_v1) // } #ifndef ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ENUM -#define ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ENUM +# define ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ENUM enum zwlr_output_configuration_v1_error { - /** - * head has been configured twice - */ - ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_CONFIGURED_HEAD = 1, - /** - * head has not been configured - */ - ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_UNCONFIGURED_HEAD = 2, - /** - * request sent after configuration has been applied or tested - */ - ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_USED = 3, + /** + * head has been configured twice + */ + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_CONFIGURED_HEAD = 1, + /** + * head has not been configured + */ + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_UNCONFIGURED_HEAD = 2, + /** + * request sent after configuration has been applied or tested + */ + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_USED = 3, }; #endif /* ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ENUM */ @@ -927,59 +918,60 @@ enum zwlr_output_configuration_v1_error { * @struct zwlr_output_configuration_v1_listener */ struct zwlr_output_configuration_v1_listener { - /** - * configuration changes succeeded - * - * Sent after the compositor has successfully applied the changes - * or tested them. - * - * Upon receiving this event, the client should destroy this - * object. - * - * If the current configuration has changed, events to describe the - * changes will be sent followed by a wlr_output_manager.done - * event. - */ - void (*succeeded)(void *data, - struct zwlr_output_configuration_v1 *zwlr_output_configuration_v1); - /** - * configuration changes failed - * - * Sent if the compositor rejects the changes or failed to apply - * them. The compositor should revert any changes made by the apply - * request that triggered this event. - * - * Upon receiving this event, the client should destroy this - * object. - */ - void (*failed)(void *data, - struct zwlr_output_configuration_v1 *zwlr_output_configuration_v1); - /** - * configuration has been cancelled - * - * Sent if the compositor cancels the configuration because the - * state of an output changed and the client has outdated - * information (e.g. after an output has been hotplugged). - * - * The client can create a new configuration with a newer serial - * and try again. - * - * Upon receiving this event, the client should destroy this - * object. - */ - void (*cancelled)(void *data, - struct zwlr_output_configuration_v1 *zwlr_output_configuration_v1); + /** + * configuration changes succeeded + * + * Sent after the compositor has successfully applied the changes + * or tested them. + * + * Upon receiving this event, the client should destroy this + * object. + * + * If the current configuration has changed, events to describe the + * changes will be sent followed by a wlr_output_manager.done + * event. + */ + void (*succeeded)(void* data, + struct zwlr_output_configuration_v1* zwlr_output_configuration_v1); + /** + * configuration changes failed + * + * Sent if the compositor rejects the changes or failed to apply + * them. The compositor should revert any changes made by the apply + * request that triggered this event. + * + * Upon receiving this event, the client should destroy this + * object. + */ + void (*failed)(void* data, + struct zwlr_output_configuration_v1* zwlr_output_configuration_v1); + /** + * configuration has been cancelled + * + * Sent if the compositor cancels the configuration because the + * state of an output changed and the client has outdated + * information (e.g. after an output has been hotplugged). + * + * The client can create a new configuration with a newer serial + * and try again. + * + * Upon receiving this event, the client should destroy this + * object. + */ + void (*cancelled)(void* data, + struct zwlr_output_configuration_v1* zwlr_output_configuration_v1); }; /** * @ingroup iface_zwlr_output_configuration_v1 */ static inline int -zwlr_output_configuration_v1_add_listener(struct zwlr_output_configuration_v1 *zwlr_output_configuration_v1, - const struct zwlr_output_configuration_v1_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) zwlr_output_configuration_v1, - (void (**)(void)) listener, data); +zwlr_output_configuration_v1_add_listener(struct zwlr_output_configuration_v1* zwlr_output_configuration_v1, + const struct zwlr_output_configuration_v1_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) zwlr_output_configuration_v1, + (void (**)(void)) listener, + data); } #define ZWLR_OUTPUT_CONFIGURATION_V1_ENABLE_HEAD 0 @@ -1024,22 +1016,19 @@ zwlr_output_configuration_v1_add_listener(struct zwlr_output_configuration_v1 *z /** @ingroup iface_zwlr_output_configuration_v1 */ static inline void -zwlr_output_configuration_v1_set_user_data(struct zwlr_output_configuration_v1 *zwlr_output_configuration_v1, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) zwlr_output_configuration_v1, user_data); +zwlr_output_configuration_v1_set_user_data(struct zwlr_output_configuration_v1* zwlr_output_configuration_v1, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) zwlr_output_configuration_v1, user_data); } /** @ingroup iface_zwlr_output_configuration_v1 */ -static inline void * -zwlr_output_configuration_v1_get_user_data(struct zwlr_output_configuration_v1 *zwlr_output_configuration_v1) -{ - return wl_proxy_get_user_data((struct wl_proxy *) zwlr_output_configuration_v1); +static inline void* +zwlr_output_configuration_v1_get_user_data(struct zwlr_output_configuration_v1* zwlr_output_configuration_v1) { + return wl_proxy_get_user_data((struct wl_proxy*) zwlr_output_configuration_v1); } static inline uint32_t -zwlr_output_configuration_v1_get_version(struct zwlr_output_configuration_v1 *zwlr_output_configuration_v1) -{ - return wl_proxy_get_version((struct wl_proxy *) zwlr_output_configuration_v1); +zwlr_output_configuration_v1_get_version(struct zwlr_output_configuration_v1* zwlr_output_configuration_v1) { + return wl_proxy_get_version((struct wl_proxy*) zwlr_output_configuration_v1); } // /** @@ -1130,38 +1119,38 @@ zwlr_output_configuration_v1_get_version(struct zwlr_output_configuration_v1 *zw // } #ifndef ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_ENUM -#define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_ENUM +# define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_ENUM enum zwlr_output_configuration_head_v1_error { - /** - * property has already been set - */ - ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_ALREADY_SET = 1, - /** - * mode doesn't belong to head - */ - ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_MODE = 2, - /** - * mode is invalid - */ - ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_CUSTOM_MODE = 3, - /** - * transform value outside enum - */ - ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_TRANSFORM = 4, - /** - * scale negative or zero - */ - ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_SCALE = 5, - /** - * invalid enum value used in the set_adaptive_sync request - * @since 4 - */ - ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_ADAPTIVE_SYNC_STATE = 6, + /** + * property has already been set + */ + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_ALREADY_SET = 1, + /** + * mode doesn't belong to head + */ + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_MODE = 2, + /** + * mode is invalid + */ + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_CUSTOM_MODE = 3, + /** + * transform value outside enum + */ + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_TRANSFORM = 4, + /** + * scale negative or zero + */ + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_SCALE = 5, + /** + * invalid enum value used in the set_adaptive_sync request + * @since 4 + */ + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_ADAPTIVE_SYNC_STATE = 6, }; /** * @ingroup iface_zwlr_output_configuration_head_v1 */ -#define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_ADAPTIVE_SYNC_STATE_SINCE_VERSION 4 +# define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_ADAPTIVE_SYNC_STATE_SINCE_VERSION 4 #endif /* ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_ENUM */ #define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_SET_MODE 0 @@ -1171,7 +1160,6 @@ enum zwlr_output_configuration_head_v1_error { #define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_SET_SCALE 4 #define ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_SET_ADAPTIVE_SYNC 5 - /** * @ingroup iface_zwlr_output_configuration_head_v1 */ @@ -1199,29 +1187,25 @@ enum zwlr_output_configuration_head_v1_error { /** @ingroup iface_zwlr_output_configuration_head_v1 */ static inline void -zwlr_output_configuration_head_v1_set_user_data(struct zwlr_output_configuration_head_v1 *zwlr_output_configuration_head_v1, void *user_data) -{ - wl_proxy_set_user_data((struct wl_proxy *) zwlr_output_configuration_head_v1, user_data); +zwlr_output_configuration_head_v1_set_user_data(struct zwlr_output_configuration_head_v1* zwlr_output_configuration_head_v1, void* user_data) { + wl_proxy_set_user_data((struct wl_proxy*) zwlr_output_configuration_head_v1, user_data); } /** @ingroup iface_zwlr_output_configuration_head_v1 */ -static inline void * -zwlr_output_configuration_head_v1_get_user_data(struct zwlr_output_configuration_head_v1 *zwlr_output_configuration_head_v1) -{ - return wl_proxy_get_user_data((struct wl_proxy *) zwlr_output_configuration_head_v1); +static inline void* +zwlr_output_configuration_head_v1_get_user_data(struct zwlr_output_configuration_head_v1* zwlr_output_configuration_head_v1) { + return wl_proxy_get_user_data((struct wl_proxy*) zwlr_output_configuration_head_v1); } static inline uint32_t -zwlr_output_configuration_head_v1_get_version(struct zwlr_output_configuration_head_v1 *zwlr_output_configuration_head_v1) -{ - return wl_proxy_get_version((struct wl_proxy *) zwlr_output_configuration_head_v1); +zwlr_output_configuration_head_v1_get_version(struct zwlr_output_configuration_head_v1* zwlr_output_configuration_head_v1) { + return wl_proxy_get_version((struct wl_proxy*) zwlr_output_configuration_head_v1); } /** @ingroup iface_zwlr_output_configuration_head_v1 */ static inline void -zwlr_output_configuration_head_v1_destroy(struct zwlr_output_configuration_head_v1 *zwlr_output_configuration_head_v1) -{ - wl_proxy_destroy((struct wl_proxy *) zwlr_output_configuration_head_v1); +zwlr_output_configuration_head_v1_destroy(struct zwlr_output_configuration_head_v1* zwlr_output_configuration_head_v1) { + wl_proxy_destroy((struct wl_proxy*) zwlr_output_configuration_head_v1); } // /** @@ -1301,7 +1285,7 @@ zwlr_output_configuration_head_v1_destroy(struct zwlr_output_configuration_head_ // ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_SET_ADAPTIVE_SYNC, NULL, wl_proxy_get_version((struct wl_proxy *) zwlr_output_configuration_head_v1), 0, state); // } -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-protocol.c b/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-protocol.c index 5eb1174ac..77261f0a8 100644 --- a/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-protocol.c +++ b/src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-protocol.c @@ -27,135 +27,150 @@ * THIS SOFTWARE. */ -#include -#include -#include -#include +# include +# include +# include +# include -#ifndef __has_attribute -# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ -#endif +# ifndef __has_attribute +# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ +# endif -#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4) -#define WL_PRIVATE __attribute__ ((visibility("hidden"))) -#else -#define WL_PRIVATE -#endif +# if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4) +# define WL_PRIVATE __attribute__((visibility("hidden"))) +# else +# define WL_PRIVATE +# endif extern const struct wl_interface zwlr_output_configuration_head_v1_interface; extern const struct wl_interface zwlr_output_configuration_v1_interface; extern const struct wl_interface zwlr_output_head_v1_interface; extern const struct wl_interface zwlr_output_mode_v1_interface; -static const struct wl_interface *wlr_output_management_unstable_v1_types[] = { - NULL, - NULL, - NULL, - &zwlr_output_configuration_v1_interface, - NULL, - &zwlr_output_head_v1_interface, - &zwlr_output_mode_v1_interface, - &zwlr_output_mode_v1_interface, - &zwlr_output_configuration_head_v1_interface, - &zwlr_output_head_v1_interface, - &zwlr_output_head_v1_interface, - &zwlr_output_mode_v1_interface, +static const struct wl_interface* wlr_output_management_unstable_v1_types[] = { + NULL, + NULL, + NULL, + &zwlr_output_configuration_v1_interface, + NULL, + &zwlr_output_head_v1_interface, + &zwlr_output_mode_v1_interface, + &zwlr_output_mode_v1_interface, + &zwlr_output_configuration_head_v1_interface, + &zwlr_output_head_v1_interface, + &zwlr_output_head_v1_interface, + &zwlr_output_mode_v1_interface, }; static const struct wl_message zwlr_output_manager_v1_requests[] = { - { "create_configuration", "nu", wlr_output_management_unstable_v1_types + 3 }, - { "stop", "", wlr_output_management_unstable_v1_types + 0 }, + {"create_configuration", "nu", wlr_output_management_unstable_v1_types + 3}, + {"stop", "", wlr_output_management_unstable_v1_types + 0}, }; static const struct wl_message zwlr_output_manager_v1_events[] = { - { "head", "n", wlr_output_management_unstable_v1_types + 5 }, - { "done", "u", wlr_output_management_unstable_v1_types + 0 }, - { "finished", "", wlr_output_management_unstable_v1_types + 0 }, + {"head", "n", wlr_output_management_unstable_v1_types + 5}, + {"done", "u", wlr_output_management_unstable_v1_types + 0}, + {"finished", "", wlr_output_management_unstable_v1_types + 0}, }; WL_PRIVATE const struct wl_interface zwlr_output_manager_v1_interface = { - "zwlr_output_manager_v1", 4, - 2, zwlr_output_manager_v1_requests, - 3, zwlr_output_manager_v1_events, + "zwlr_output_manager_v1", + 4, + 2, + zwlr_output_manager_v1_requests, + 3, + zwlr_output_manager_v1_events, }; static const struct wl_message zwlr_output_head_v1_requests[] = { - { "release", "3", wlr_output_management_unstable_v1_types + 0 }, + {"release", "3", wlr_output_management_unstable_v1_types + 0}, }; static const struct wl_message zwlr_output_head_v1_events[] = { - { "name", "s", wlr_output_management_unstable_v1_types + 0 }, - { "description", "s", wlr_output_management_unstable_v1_types + 0 }, - { "physical_size", "ii", wlr_output_management_unstable_v1_types + 0 }, - { "mode", "n", wlr_output_management_unstable_v1_types + 6 }, - { "enabled", "i", wlr_output_management_unstable_v1_types + 0 }, - { "current_mode", "o", wlr_output_management_unstable_v1_types + 7 }, - { "position", "ii", wlr_output_management_unstable_v1_types + 0 }, - { "transform", "i", wlr_output_management_unstable_v1_types + 0 }, - { "scale", "f", wlr_output_management_unstable_v1_types + 0 }, - { "finished", "", wlr_output_management_unstable_v1_types + 0 }, - { "make", "2s", wlr_output_management_unstable_v1_types + 0 }, - { "model", "2s", wlr_output_management_unstable_v1_types + 0 }, - { "serial_number", "2s", wlr_output_management_unstable_v1_types + 0 }, - { "adaptive_sync", "4u", wlr_output_management_unstable_v1_types + 0 }, + {"name", "s", wlr_output_management_unstable_v1_types + 0}, + {"description", "s", wlr_output_management_unstable_v1_types + 0}, + {"physical_size", "ii", wlr_output_management_unstable_v1_types + 0}, + {"mode", "n", wlr_output_management_unstable_v1_types + 6}, + {"enabled", "i", wlr_output_management_unstable_v1_types + 0}, + {"current_mode", "o", wlr_output_management_unstable_v1_types + 7}, + {"position", "ii", wlr_output_management_unstable_v1_types + 0}, + {"transform", "i", wlr_output_management_unstable_v1_types + 0}, + {"scale", "f", wlr_output_management_unstable_v1_types + 0}, + {"finished", "", wlr_output_management_unstable_v1_types + 0}, + {"make", "2s", wlr_output_management_unstable_v1_types + 0}, + {"model", "2s", wlr_output_management_unstable_v1_types + 0}, + {"serial_number", "2s", wlr_output_management_unstable_v1_types + 0}, + {"adaptive_sync", "4u", wlr_output_management_unstable_v1_types + 0}, }; WL_PRIVATE const struct wl_interface zwlr_output_head_v1_interface = { - "zwlr_output_head_v1", 4, - 1, zwlr_output_head_v1_requests, - 14, zwlr_output_head_v1_events, + "zwlr_output_head_v1", + 4, + 1, + zwlr_output_head_v1_requests, + 14, + zwlr_output_head_v1_events, }; static const struct wl_message zwlr_output_mode_v1_requests[] = { - { "release", "3", wlr_output_management_unstable_v1_types + 0 }, + {"release", "3", wlr_output_management_unstable_v1_types + 0}, }; static const struct wl_message zwlr_output_mode_v1_events[] = { - { "size", "ii", wlr_output_management_unstable_v1_types + 0 }, - { "refresh", "i", wlr_output_management_unstable_v1_types + 0 }, - { "preferred", "", wlr_output_management_unstable_v1_types + 0 }, - { "finished", "", wlr_output_management_unstable_v1_types + 0 }, + {"size", "ii", wlr_output_management_unstable_v1_types + 0}, + {"refresh", "i", wlr_output_management_unstable_v1_types + 0}, + {"preferred", "", wlr_output_management_unstable_v1_types + 0}, + {"finished", "", wlr_output_management_unstable_v1_types + 0}, }; WL_PRIVATE const struct wl_interface zwlr_output_mode_v1_interface = { - "zwlr_output_mode_v1", 3, - 1, zwlr_output_mode_v1_requests, - 4, zwlr_output_mode_v1_events, + "zwlr_output_mode_v1", + 3, + 1, + zwlr_output_mode_v1_requests, + 4, + zwlr_output_mode_v1_events, }; static const struct wl_message zwlr_output_configuration_v1_requests[] = { - { "enable_head", "no", wlr_output_management_unstable_v1_types + 8 }, - { "disable_head", "o", wlr_output_management_unstable_v1_types + 10 }, - { "apply", "", wlr_output_management_unstable_v1_types + 0 }, - { "test", "", wlr_output_management_unstable_v1_types + 0 }, - { "destroy", "", wlr_output_management_unstable_v1_types + 0 }, + {"enable_head", "no", wlr_output_management_unstable_v1_types + 8}, + {"disable_head", "o", wlr_output_management_unstable_v1_types + 10}, + {"apply", "", wlr_output_management_unstable_v1_types + 0}, + {"test", "", wlr_output_management_unstable_v1_types + 0}, + {"destroy", "", wlr_output_management_unstable_v1_types + 0}, }; static const struct wl_message zwlr_output_configuration_v1_events[] = { - { "succeeded", "", wlr_output_management_unstable_v1_types + 0 }, - { "failed", "", wlr_output_management_unstable_v1_types + 0 }, - { "cancelled", "", wlr_output_management_unstable_v1_types + 0 }, + {"succeeded", "", wlr_output_management_unstable_v1_types + 0}, + {"failed", "", wlr_output_management_unstable_v1_types + 0}, + {"cancelled", "", wlr_output_management_unstable_v1_types + 0}, }; WL_PRIVATE const struct wl_interface zwlr_output_configuration_v1_interface = { - "zwlr_output_configuration_v1", 4, - 5, zwlr_output_configuration_v1_requests, - 3, zwlr_output_configuration_v1_events, + "zwlr_output_configuration_v1", + 4, + 5, + zwlr_output_configuration_v1_requests, + 3, + zwlr_output_configuration_v1_events, }; static const struct wl_message zwlr_output_configuration_head_v1_requests[] = { - { "set_mode", "o", wlr_output_management_unstable_v1_types + 11 }, - { "set_custom_mode", "iii", wlr_output_management_unstable_v1_types + 0 }, - { "set_position", "ii", wlr_output_management_unstable_v1_types + 0 }, - { "set_transform", "i", wlr_output_management_unstable_v1_types + 0 }, - { "set_scale", "f", wlr_output_management_unstable_v1_types + 0 }, - { "set_adaptive_sync", "4u", wlr_output_management_unstable_v1_types + 0 }, + {"set_mode", "o", wlr_output_management_unstable_v1_types + 11}, + {"set_custom_mode", "iii", wlr_output_management_unstable_v1_types + 0}, + {"set_position", "ii", wlr_output_management_unstable_v1_types + 0}, + {"set_transform", "i", wlr_output_management_unstable_v1_types + 0}, + {"set_scale", "f", wlr_output_management_unstable_v1_types + 0}, + {"set_adaptive_sync", "4u", wlr_output_management_unstable_v1_types + 0}, }; WL_PRIVATE const struct wl_interface zwlr_output_configuration_head_v1_interface = { - "zwlr_output_configuration_head_v1", 4, - 6, zwlr_output_configuration_head_v1_requests, - 0, NULL, + "zwlr_output_configuration_head_v1", + 4, + 6, + zwlr_output_configuration_head_v1_requests, + 0, + NULL, }; #endif diff --git a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h index c4f6833c2..3edaa641b 100644 --- a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h +++ b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h @@ -7,7 +7,7 @@ #include #include -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -78,7 +78,7 @@ struct zxdg_output_manager_v1; struct zxdg_output_v1; #ifndef ZXDG_OUTPUT_MANAGER_V1_INTERFACE -#define ZXDG_OUTPUT_MANAGER_V1_INTERFACE +# define ZXDG_OUTPUT_MANAGER_V1_INTERFACE /** * @page page_iface_zxdg_output_manager_v1 zxdg_output_manager_v1 * @section page_iface_zxdg_output_manager_v1_desc Description @@ -95,7 +95,7 @@ struct zxdg_output_v1; extern const struct wl_interface zxdg_output_manager_v1_interface; #endif #ifndef ZXDG_OUTPUT_V1_INTERFACE -#define ZXDG_OUTPUT_V1_INTERFACE +# define ZXDG_OUTPUT_V1_INTERFACE /** * @page page_iface_zxdg_output_v1 zxdg_output_v1 * @section page_iface_zxdg_output_v1_desc Description @@ -131,7 +131,6 @@ extern const struct wl_interface zxdg_output_v1_interface; #define ZXDG_OUTPUT_MANAGER_V1_DESTROY 0 #define ZXDG_OUTPUT_MANAGER_V1_GET_XDG_OUTPUT 1 - /** * @ingroup iface_zxdg_output_manager_v1 */ @@ -197,153 +196,154 @@ extern const struct wl_interface zxdg_output_v1_interface; * @struct zxdg_output_v1_listener */ struct zxdg_output_v1_listener { - /** - * position of the output within the global compositor space - * - * The position event describes the location of the wl_output - * within the global compositor space. - * - * The logical_position event is sent after creating an xdg_output - * (see xdg_output_manager.get_xdg_output) and whenever the - * location of the output changes within the global compositor - * space. - * @param x x position within the global compositor space - * @param y y position within the global compositor space - */ - void (*logical_position)(void *data, - struct zxdg_output_v1 *zxdg_output_v1, - int32_t x, - int32_t y); - /** - * size of the output in the global compositor space - * - * The logical_size event describes the size of the output in the - * global compositor space. - * - * Most regular Wayland clients should not pay attention to the - * logical size and would rather rely on xdg_shell interfaces. - * - * Some clients such as Xwayland, however, need this to configure - * their surfaces in the global compositor space as the compositor - * may apply a different scale from what is advertised by the - * output scaling property (to achieve fractional scaling, for - * example). - * - * For example, for a wl_output mode 3840×2160 and a scale factor - * 2: - * - * - A compositor not scaling the monitor viewport in its - * compositing space will advertise a logical size of 3840×2160, - * - * - A compositor scaling the monitor viewport with scale factor 2 - * will advertise a logical size of 1920×1080, - * - * - A compositor scaling the monitor viewport using a fractional - * scale of 1.5 will advertise a logical size of 2560×1440. - * - * For example, for a wl_output mode 1920×1080 and a 90 degree - * rotation, the compositor will advertise a logical size of - * 1080x1920. - * - * The logical_size event is sent after creating an xdg_output (see - * xdg_output_manager.get_xdg_output) and whenever the logical size - * of the output changes, either as a result of a change in the - * applied scale or because of a change in the corresponding output - * mode(see wl_output.mode) or transform (see wl_output.transform). - * @param width width in global compositor space - * @param height height in global compositor space - */ - void (*logical_size)(void *data, - struct zxdg_output_v1 *zxdg_output_v1, - int32_t width, - int32_t height); - /** - * all information about the output have been sent - * - * This event is sent after all other properties of an xdg_output - * have been sent. - * - * This allows changes to the xdg_output properties to be seen as - * atomic, even if they happen via multiple events. - * - * For objects version 3 onwards, this event is deprecated. - * Compositors are not required to send it anymore and must send - * wl_output.done instead. - */ - void (*done)(void *data, - struct zxdg_output_v1 *zxdg_output_v1); - /** - * name of this output - * - * Many compositors will assign names to their outputs, show them - * to the user, allow them to be configured by name, etc. The - * client may wish to know this name as well to offer the user - * similar behaviors. - * - * The naming convention is compositor defined, but limited to - * alphanumeric characters and dashes (-). Each name is unique - * among all wl_output globals, but if a wl_output global is - * destroyed the same name may be reused later. The names will also - * remain consistent across sessions with the same hardware and - * software configuration. - * - * Examples of names include 'HDMI-A-1', 'WL-1', 'X11-1', etc. - * However, do not assume that the name is a reflection of an - * underlying DRM connector, X11 connection, etc. - * - * The name event is sent after creating an xdg_output (see - * xdg_output_manager.get_xdg_output). This event is only sent once - * per xdg_output, and the name does not change over the lifetime - * of the wl_output global. - * - * This event is deprecated, instead clients should use - * wl_output.name. Compositors must still support this event. - * @param name output name - * @since 2 - */ - void (*name)(void *data, - struct zxdg_output_v1 *zxdg_output_v1, - const char *name); - /** - * human-readable description of this output - * - * Many compositors can produce human-readable descriptions of - * their outputs. The client may wish to know this description as - * well, to communicate the user for various purposes. - * - * The description is a UTF-8 string with no convention defined for - * its contents. Examples might include 'Foocorp 11" Display' or - * 'Virtual X11 output via :1'. - * - * The description event is sent after creating an xdg_output (see - * xdg_output_manager.get_xdg_output) and whenever the description - * changes. The description is optional, and may not be sent at - * all. - * - * For objects of version 2 and lower, this event is only sent once - * per xdg_output, and the description does not change over the - * lifetime of the wl_output global. - * - * This event is deprecated, instead clients should use - * wl_output.description. Compositors must still support this - * event. - * @param description output description - * @since 2 - */ - void (*description)(void *data, - struct zxdg_output_v1 *zxdg_output_v1, - const char *description); + /** + * position of the output within the global compositor space + * + * The position event describes the location of the wl_output + * within the global compositor space. + * + * The logical_position event is sent after creating an xdg_output + * (see xdg_output_manager.get_xdg_output) and whenever the + * location of the output changes within the global compositor + * space. + * @param x x position within the global compositor space + * @param y y position within the global compositor space + */ + void (*logical_position)(void* data, + struct zxdg_output_v1* zxdg_output_v1, + int32_t x, + int32_t y); + /** + * size of the output in the global compositor space + * + * The logical_size event describes the size of the output in the + * global compositor space. + * + * Most regular Wayland clients should not pay attention to the + * logical size and would rather rely on xdg_shell interfaces. + * + * Some clients such as Xwayland, however, need this to configure + * their surfaces in the global compositor space as the compositor + * may apply a different scale from what is advertised by the + * output scaling property (to achieve fractional scaling, for + * example). + * + * For example, for a wl_output mode 3840×2160 and a scale factor + * 2: + * + * - A compositor not scaling the monitor viewport in its + * compositing space will advertise a logical size of 3840×2160, + * + * - A compositor scaling the monitor viewport with scale factor 2 + * will advertise a logical size of 1920×1080, + * + * - A compositor scaling the monitor viewport using a fractional + * scale of 1.5 will advertise a logical size of 2560×1440. + * + * For example, for a wl_output mode 1920×1080 and a 90 degree + * rotation, the compositor will advertise a logical size of + * 1080x1920. + * + * The logical_size event is sent after creating an xdg_output (see + * xdg_output_manager.get_xdg_output) and whenever the logical size + * of the output changes, either as a result of a change in the + * applied scale or because of a change in the corresponding output + * mode(see wl_output.mode) or transform (see wl_output.transform). + * @param width width in global compositor space + * @param height height in global compositor space + */ + void (*logical_size)(void* data, + struct zxdg_output_v1* zxdg_output_v1, + int32_t width, + int32_t height); + /** + * all information about the output have been sent + * + * This event is sent after all other properties of an xdg_output + * have been sent. + * + * This allows changes to the xdg_output properties to be seen as + * atomic, even if they happen via multiple events. + * + * For objects version 3 onwards, this event is deprecated. + * Compositors are not required to send it anymore and must send + * wl_output.done instead. + */ + void (*done)(void* data, + struct zxdg_output_v1* zxdg_output_v1); + /** + * name of this output + * + * Many compositors will assign names to their outputs, show them + * to the user, allow them to be configured by name, etc. The + * client may wish to know this name as well to offer the user + * similar behaviors. + * + * The naming convention is compositor defined, but limited to + * alphanumeric characters and dashes (-). Each name is unique + * among all wl_output globals, but if a wl_output global is + * destroyed the same name may be reused later. The names will also + * remain consistent across sessions with the same hardware and + * software configuration. + * + * Examples of names include 'HDMI-A-1', 'WL-1', 'X11-1', etc. + * However, do not assume that the name is a reflection of an + * underlying DRM connector, X11 connection, etc. + * + * The name event is sent after creating an xdg_output (see + * xdg_output_manager.get_xdg_output). This event is only sent once + * per xdg_output, and the name does not change over the lifetime + * of the wl_output global. + * + * This event is deprecated, instead clients should use + * wl_output.name. Compositors must still support this event. + * @param name output name + * @since 2 + */ + void (*name)(void* data, + struct zxdg_output_v1* zxdg_output_v1, + const char* name); + /** + * human-readable description of this output + * + * Many compositors can produce human-readable descriptions of + * their outputs. The client may wish to know this description as + * well, to communicate the user for various purposes. + * + * The description is a UTF-8 string with no convention defined for + * its contents. Examples might include 'Foocorp 11" Display' or + * 'Virtual X11 output via :1'. + * + * The description event is sent after creating an xdg_output (see + * xdg_output_manager.get_xdg_output) and whenever the description + * changes. The description is optional, and may not be sent at + * all. + * + * For objects of version 2 and lower, this event is only sent once + * per xdg_output, and the description does not change over the + * lifetime of the wl_output global. + * + * This event is deprecated, instead clients should use + * wl_output.description. Compositors must still support this + * event. + * @param description output description + * @since 2 + */ + void (*description)(void* data, + struct zxdg_output_v1* zxdg_output_v1, + const char* description); }; /** * @ingroup iface_zxdg_output_v1 */ static inline int -zxdg_output_v1_add_listener(struct zxdg_output_v1 *zxdg_output_v1, - const struct zxdg_output_v1_listener *listener, void *data) -{ - return wl_proxy_add_listener((struct wl_proxy *) zxdg_output_v1, - (void (**)(void)) listener, data); +zxdg_output_v1_add_listener(struct zxdg_output_v1* zxdg_output_v1, + const struct zxdg_output_v1_listener* listener, + void* data) { + return wl_proxy_add_listener((struct wl_proxy*) zxdg_output_v1, + (void (**)(void)) listener, + data); } #define ZXDG_OUTPUT_V1_DESTROY 0 @@ -407,7 +407,7 @@ zxdg_output_v1_add_listener(struct zxdg_output_v1 *zxdg_output_v1, // ZXDG_OUTPUT_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zxdg_output_v1), WL_MARSHAL_FLAG_DESTROY); // } -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c index 1f6abf2d5..67cc522b1 100644 --- a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c +++ b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c @@ -24,47 +24,53 @@ * DEALINGS IN THE SOFTWARE. */ -#include -#include -#include +# include +# include +# include extern const struct wl_interface wl_output_interface; extern const struct wl_interface zxdg_output_v1_interface; -static const struct wl_interface *xdg_output_unstable_v1_types[] = { - NULL, - NULL, - &zxdg_output_v1_interface, - NULL, // &wl_output_interface, +static const struct wl_interface* xdg_output_unstable_v1_types[] = { + NULL, + NULL, + &zxdg_output_v1_interface, + NULL, // &wl_output_interface, }; static const struct wl_message zxdg_output_manager_v1_requests[] = { - { "destroy", "", xdg_output_unstable_v1_types + 0 }, - { "get_xdg_output", "no", xdg_output_unstable_v1_types + 2 }, + {"destroy", "", xdg_output_unstable_v1_types + 0}, + {"get_xdg_output", "no", xdg_output_unstable_v1_types + 2}, }; WL_EXPORT const struct wl_interface zxdg_output_manager_v1_interface = { - "zxdg_output_manager_v1", 3, - 2, zxdg_output_manager_v1_requests, - 0, NULL, + "zxdg_output_manager_v1", + 3, + 2, + zxdg_output_manager_v1_requests, + 0, + NULL, }; static const struct wl_message zxdg_output_v1_requests[] = { - { "destroy", "", xdg_output_unstable_v1_types + 0 }, + {"destroy", "", xdg_output_unstable_v1_types + 0}, }; static const struct wl_message zxdg_output_v1_events[] = { - { "logical_position", "ii", xdg_output_unstable_v1_types + 0 }, - { "logical_size", "ii", xdg_output_unstable_v1_types + 0 }, - { "done", "", xdg_output_unstable_v1_types + 0 }, - { "name", "2s", xdg_output_unstable_v1_types + 0 }, - { "description", "2s", xdg_output_unstable_v1_types + 0 }, + {"logical_position", "ii", xdg_output_unstable_v1_types + 0}, + {"logical_size", "ii", xdg_output_unstable_v1_types + 0}, + {"done", "", xdg_output_unstable_v1_types + 0}, + {"name", "2s", xdg_output_unstable_v1_types + 0}, + {"description", "2s", xdg_output_unstable_v1_types + 0}, }; WL_EXPORT const struct wl_interface zxdg_output_v1_interface = { - "zxdg_output_v1", 3, - 1, zxdg_output_v1_requests, - 5, zxdg_output_v1_events, + "zxdg_output_v1", + 3, + 1, + zxdg_output_v1_requests, + 5, + zxdg_output_v1_events, }; #endif diff --git a/src/detection/displayserver/linux/wayland/zwlr-output.c b/src/detection/displayserver/linux/wayland/zwlr-output.c index d9dfa65f9..9a4797009 100644 --- a/src/detection/displayserver/linux/wayland/zwlr-output.c +++ b/src/detection/displayserver/linux/wayland/zwlr-output.c @@ -1,22 +1,19 @@ #ifdef FF_HAVE_WAYLAND -#include "wayland.h" -#include "wlr-output-management-unstable-v1-client-protocol.h" +# include "wayland.h" +# include "wlr-output-management-unstable-v1-client-protocol.h" -static void waylandZwlrTransformListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1 *zwlr_output_head_v1, int32_t transform) -{ +static void waylandZwlrTransformListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1* zwlr_output_head_v1, int32_t transform) { WaylandDisplay* wldata = (WaylandDisplay*) data; wldata->transform = (enum wl_output_transform) transform; } -static void waylandZwlrScaleListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1 *zwlr_output_head_v1, wl_fixed_t scale) -{ +static void waylandZwlrScaleListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1* zwlr_output_head_v1, wl_fixed_t scale) { WaylandDisplay* wldata = (WaylandDisplay*) data; wldata->dpi = (uint32_t) scale * 3 / 8; // wl_fixed_to_double(scale) * 96; } -typedef struct WaylandZwlrMode -{ +typedef struct WaylandZwlrMode { int32_t width; int32_t height; int32_t refreshRate; @@ -24,21 +21,18 @@ typedef struct WaylandZwlrMode struct zwlr_output_mode_v1* pMode; } WaylandZwlrMode; -static void waylandZwlrModeSizeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_mode_v1 *zwlr_output_mode_v1, int32_t width, int32_t height) -{ +static void waylandZwlrModeSizeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_mode_v1* zwlr_output_mode_v1, int32_t width, int32_t height) { WaylandZwlrMode* mode = (WaylandZwlrMode*) data; mode->width = width; mode->height = height; } -static void waylandZwlrModeRefreshListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_mode_v1 *zwlr_output_mode_v1, int32_t rate) -{ +static void waylandZwlrModeRefreshListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_mode_v1* zwlr_output_mode_v1, int32_t rate) { WaylandZwlrMode* mode = (WaylandZwlrMode*) data; mode->refreshRate = rate; } -static void waylandZwlrModePreferredListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_mode_v1 *zwlr_output_mode_v1) -{ +static void waylandZwlrModePreferredListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_mode_v1* zwlr_output_mode_v1) { WaylandZwlrMode* mode = (WaylandZwlrMode*) data; mode->preferred = true; } @@ -50,55 +44,58 @@ static const struct zwlr_output_mode_v1_listener modeListener = { .finished = (void*) stubListener, }; -static void waylandZwlrModeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1 *zwlr_output_head_v1, struct zwlr_output_mode_v1 *mode) -{ +static void waylandZwlrModeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1* zwlr_output_head_v1, struct zwlr_output_mode_v1* mode) { WaylandDisplay* wldata = (WaylandDisplay*) data; - if (!wldata->internal) return; + if (!wldata->internal) { + return; + } WaylandZwlrMode* newMode = ffListAdd((FFlist*) wldata->internal); - *newMode = (WaylandZwlrMode) { .pMode = mode }; + *newMode = (WaylandZwlrMode) {.pMode = mode}; // Strangely, the listener is called only in this function, but not in `waylandZwlrCurrentModeListener` - wldata->parent->ffwl_proxy_add_listener((struct wl_proxy *) mode, (void (**)(void)) &modeListener, newMode); + wldata->parent->ffwl_proxy_add_listener((struct wl_proxy*) mode, (void (**)(void)) &modeListener, newMode); } -static void waylandZwlrCurrentModeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1 *zwlr_output_head_v1, struct zwlr_output_mode_v1 *mode) -{ +static void waylandZwlrCurrentModeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1* zwlr_output_head_v1, struct zwlr_output_mode_v1* mode) { // waylandZwlrModeListener is always run before this WaylandDisplay* wldata = (WaylandDisplay*) data; - if (!wldata->internal) return; + if (!wldata->internal) { + return; + } int set = 0; - FF_LIST_FOR_EACH(WaylandZwlrMode, m, *(FFlist*) wldata->internal) - { - if (m->pMode == mode) - { + FF_LIST_FOR_EACH (WaylandZwlrMode, m, *(FFlist*) wldata->internal) { + if (m->pMode == mode) { wldata->width = m->width; wldata->height = m->height; wldata->refreshRate = m->refreshRate; - if (++set == 2) break; + if (++set == 2) { + break; + } } - if (m->preferred) - { + if (m->preferred) { wldata->preferredWidth = m->width; wldata->preferredHeight = m->height; wldata->preferredRefreshRate = m->refreshRate; - if (++set == 2) break; + if (++set == 2) { + break; + } } } } -static void waylandZwlrPhysicalSizeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1 *zwlr_output_head_v1, int32_t width, int32_t height) -{ +static void waylandZwlrPhysicalSizeListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1* zwlr_output_head_v1, int32_t width, int32_t height) { WaylandDisplay* wldata = (WaylandDisplay*) data; wldata->physicalWidth = width; wldata->physicalHeight = height; } -static void waylandZwlrEnabledListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1 *zwlr_output_head_v1, bool enabled) -{ +static void waylandZwlrEnabledListener(void* data, FF_MAYBE_UNUSED struct zwlr_output_head_v1* zwlr_output_head_v1, bool enabled) { WaylandDisplay* wldata = (WaylandDisplay*) data; - if (!enabled) wldata->internal = NULL; + if (!enabled) { + wldata->internal = NULL; + } } static const struct zwlr_output_head_v1_listener headListener = { @@ -118,8 +115,7 @@ static const struct zwlr_output_head_v1_listener headListener = { .adaptive_sync = (void*) stubListener, }; -static void waylandHandleZwlrHead(void *data, FF_MAYBE_UNUSED struct zwlr_output_manager_v1 *zwlr_output_manager_v1, struct zwlr_output_head_v1 *head) -{ +static void waylandHandleZwlrHead(void* data, FF_MAYBE_UNUSED struct zwlr_output_manager_v1* zwlr_output_manager_v1, struct zwlr_output_head_v1* head) { WaylandData* wldata = data; FF_LIST_AUTO_DESTROY modes = ffListCreate(sizeof(WaylandZwlrMode)); @@ -133,11 +129,12 @@ static void waylandHandleZwlrHead(void *data, FF_MAYBE_UNUSED struct zwlr_output .internal = &modes, }; - wldata->ffwl_proxy_add_listener((struct wl_proxy*) head, (void(**)(void)) &headListener, &display); + wldata->ffwl_proxy_add_listener((struct wl_proxy*) head, (void (**)(void)) &headListener, &display); wldata->ffwl_display_roundtrip(wldata->display); - if(display.width <= 0 || display.height <= 0 || !display.internal) + if (display.width <= 0 || display.height <= 0 || !display.internal) { return; + } uint32_t rotation = ffWaylandHandleRotation(&display); @@ -153,23 +150,22 @@ static void waylandHandleZwlrHead(void *data, FF_MAYBE_UNUSED struct zwlr_output display.edidName.length ? &display.edidName : display.description.length && !ffStrbufContain(&display.description, &display.name) - ? &display.description - : &display.name, + ? &display.description + : &display.name, display.type, false, display.id, (uint32_t) display.physicalWidth, (uint32_t) display.physicalHeight, - "wayland-zwlr" - ); - if (item) - { - if (display.hdrSupported) + "wayland-zwlr"); + if (item) { + if (display.hdrSupported) { item->hdrStatus = FF_DISPLAY_HDR_STATUS_SUPPORTED; - else if (display.hdrInfoAvailable) + } else if (display.hdrInfoAvailable) { item->hdrStatus = FF_DISPLAY_HDR_STATUS_UNSUPPORTED; - else + } else { item->hdrStatus = FF_DISPLAY_HDR_STATUS_UNKNOWN; + } item->manufactureYear = display.myear; item->manufactureWeek = display.mweek; @@ -181,16 +177,17 @@ static void waylandHandleZwlrHead(void *data, FF_MAYBE_UNUSED struct zwlr_output ffStrbufDestroy(&display.edidName); // These must be released manually - FF_LIST_FOR_EACH(WaylandZwlrMode, m, modes) + FF_LIST_FOR_EACH (WaylandZwlrMode, m, modes) { wldata->ffwl_proxy_destroy((void*) m->pMode); + } wldata->ffwl_proxy_destroy((void*) head); } -const char* ffWaylandHandleZwlrOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) -{ +const char* ffWaylandHandleZwlrOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &zwlr_output_manager_v1_interface, version, name, zwlr_output_manager_v1_interface.name, version, NULL); - if(output == NULL) + if (output == NULL) { return "Failed to bind zwlr_output_manager_v1"; + } const struct zwlr_output_manager_v1_listener outputListener = { .head = waylandHandleZwlrHead, @@ -198,13 +195,11 @@ const char* ffWaylandHandleZwlrOutput(WaylandData* wldata, struct wl_registry* r .finished = (void*) stubListener, }; - if (wldata->ffwl_proxy_add_listener(output, (void(**)(void)) &outputListener, wldata) < 0) - { + if (wldata->ffwl_proxy_add_listener(output, (void (**)(void)) &outputListener, wldata) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to add listener to zwlr_output_manager_v1"; } - if (wldata->ffwl_display_roundtrip(wldata->display) < 0) - { + if (wldata->ffwl_display_roundtrip(wldata->display) < 0) { wldata->ffwl_proxy_destroy(output); return "Failed to roundtrip display"; } diff --git a/src/detection/displayserver/linux/wmde.c b/src/detection/displayserver/linux/wmde.c index 78ae1bc82..4932c3b89 100644 --- a/src/detection/displayserver/linux/wmde.c +++ b/src/detection/displayserver/linux/wmde.c @@ -9,319 +9,326 @@ #include #if __FreeBSD__ - #include - #include - #include +# include +# include +# include #elif __OpenBSD__ - #include - #include - #include +# include +# include +# include #elif __sun - #include +# include #elif __NetBSD__ - #include - #include +# include +# include #endif -static const char* parseEnv(void) -{ +static const char* parseEnv(void) { const char* env; env = getenv("XDG_CURRENT_DESKTOP"); - if(ffStrSet(env)) + if (ffStrSet(env)) { return env; + } env = getenv("XDG_SESSION_DESKTOP"); - if(ffStrSet(env)) + if (ffStrSet(env)) { return env; + } env = getenv("CURRENT_DESKTOP"); - if(ffStrSet(env)) + if (ffStrSet(env)) { return env; + } env = getenv("SESSION_DESKTOP"); - if(ffStrSet(env)) + if (ffStrSet(env)) { return env; + } env = getenv("DESKTOP_SESSION"); - if(ffStrSet(env)) + if (ffStrSet(env)) { return env; + } - if(getenv("KDE_FULL_SESSION") != NULL || getenv("KDE_SESSION_UID") != NULL || getenv("KDE_SESSION_VERSION") != NULL) + if (getenv("KDE_FULL_SESSION") != NULL || getenv("KDE_SESSION_UID") != NULL || getenv("KDE_SESSION_VERSION") != NULL) { return "KDE"; + } - if(getenv("GNOME_DESKTOP_SESSION_ID") != NULL) + if (getenv("GNOME_DESKTOP_SESSION_ID") != NULL) { return "GNOME"; + } - if(getenv("MATE_DESKTOP_SESSION_ID") != NULL) + if (getenv("MATE_DESKTOP_SESSION_ID") != NULL) { return "Mate"; + } - if(getenv("TDE_FULL_SESSION") != NULL) + if (getenv("TDE_FULL_SESSION") != NULL) { return "Trinity"; + } - if(getenv("HYPRLAND_CMD") != NULL) + if (getenv("HYPRLAND_CMD") != NULL) { return "Hyprland"; + } - if(getenv("SWAYSOCK") != NULL) + if (getenv("SWAYSOCK") != NULL) { return "Sway"; + } - #if __linux__ && !__ANDROID__ - if( +#if __linux__ && !__ANDROID__ + if ( getenv("WAYLAND_DISPLAY") != NULL && - ffPathExists("/mnt/wslg/", FF_PATHTYPE_DIRECTORY) - ) return "WSLg"; - #endif + ffPathExists("/mnt/wslg/", FF_PATHTYPE_DIRECTORY)) { + return "WSLg"; + } +#endif return NULL; } -static void applyPrettyNameIfWM(FFDisplayServerResult* result, const char* name) -{ - if(!ffStrSet(name)) +static void applyPrettyNameIfWM(FFDisplayServerResult* result, const char* name) { + if (!ffStrSet(name)) { return; + } - if( + if ( ffStrEqualsIgnCase(name, "kwin") || ffStrStartsWithIgnCase(name, "kwin_") || ffStrEndsWithIgnCase(name, "-kwin_wayland") || - ffStrEndsWithIgnCase(name, "-kwin_x11") - ) ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_KWIN); - else if( + ffStrEndsWithIgnCase(name, "-kwin_x11")) { + ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_KWIN); + } else if ( ffStrEqualsIgnCase(name, "gnome-shell") || ffStrEqualsIgnCase(name, "gnome shell") || ffStrEqualsIgnCase(name, "gnome-session-binary") || - ffStrEqualsIgnCase(name, "Mutter") - ) ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_MUTTER); - else if( + ffStrEqualsIgnCase(name, "Mutter")) { + ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_MUTTER); + } else if ( ffStrEqualsIgnCase(name, "cinnamon") || ffStrStartsWithIgnCase(name, "cinnamon-") || ffStrEqualsIgnCase(name, "Muffin") || - ffStrEqualsIgnCase(name, "Mutter (Muffin)") - ) ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_MUFFIN); - else if(ffStrEqualsIgnCase(name, "sway")) + ffStrEqualsIgnCase(name, "Mutter (Muffin)")) { + ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_MUFFIN); + } else if (ffStrEqualsIgnCase(name, "sway")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_SWAY); - else if(ffStrEqualsIgnCase(name, "weston")) + } else if (ffStrEqualsIgnCase(name, "weston")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_WESTON); - else if(ffStrEqualsIgnCase(name, "wayfire")) + } else if (ffStrEqualsIgnCase(name, "wayfire")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_WAYFIRE); - else if(ffStrEqualsIgnCase(name, "openbox")) + } else if (ffStrEqualsIgnCase(name, "openbox")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_OPENBOX); - else if(ffStrEqualsIgnCase(name, "xfwm4")) + } else if (ffStrEqualsIgnCase(name, "xfwm4")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_XFWM4); - else if(ffStrEqualsIgnCase(name, "Marco") || - ffStrEqualsIgnCase(name, "Metacity (Marco)")) + } else if (ffStrEqualsIgnCase(name, "Marco") || + ffStrEqualsIgnCase(name, "Metacity (Marco)")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_MARCO); - else if(ffStrEqualsIgnCase(name, "xmonad")) + } else if (ffStrEqualsIgnCase(name, "xmonad")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_XMONAD); - else if(ffStrEqualsIgnCase(name, "WSLg")) + } else if (ffStrEqualsIgnCase(name, "WSLg")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_WSLG); - else if(ffStrEqualsIgnCase(name, "dwm")) + } else if (ffStrEqualsIgnCase(name, "dwm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_DWM); - else if(ffStrEqualsIgnCase(name, "bspwm")) + } else if (ffStrEqualsIgnCase(name, "bspwm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_BSPWM); - else if(ffStrEqualsIgnCase(name, "tinywm")) + } else if (ffStrEqualsIgnCase(name, "tinywm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_TINYWM); - else if(ffStrEqualsIgnCase(name, "qtile")) + } else if (ffStrEqualsIgnCase(name, "qtile")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_QTILE); - else if(ffStrEqualsIgnCase(name, "herbstluftwm")) + } else if (ffStrEqualsIgnCase(name, "herbstluftwm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_HERBSTLUFTWM); - else if(ffStrEqualsIgnCase(name, "icewm")) + } else if (ffStrEqualsIgnCase(name, "icewm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_ICEWM); - else if(ffStrEqualsIgnCase(name, "dtwm")) + } else if (ffStrEqualsIgnCase(name, "dtwm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_DTWM); - else if(ffStrEqualsIgnCase(name, "fvwm")) + } else if (ffStrEqualsIgnCase(name, "fvwm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_FVWM); - else if(ffStrEqualsIgnCase(name, "ctwm")) + } else if (ffStrEqualsIgnCase(name, "ctwm")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_CTWM); - else if(ffStrEqualsIgnCase(name, "hyprland")) + } else if (ffStrEqualsIgnCase(name, "hyprland")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_HYPRLAND); - else if(ffStrEqualsIgnCase(name, "ratpoison")) + } else if (ffStrEqualsIgnCase(name, "ratpoison")) { ffStrbufSetS(&result->wmPrettyName, FF_WM_PRETTY_RATPOISON); + } } -static void applyNameIfWM(FFDisplayServerResult* result, const char* processName) -{ +static void applyNameIfWM(FFDisplayServerResult* result, const char* processName) { applyPrettyNameIfWM(result, processName); - if(result->wmPrettyName.length > 0) + if (result->wmPrettyName.length > 0) { ffStrbufSetS(&result->wmProcessName, processName); + } } -static void applyBetterWM(FFDisplayServerResult* result, const char* processName) -{ - if(!ffStrSet(processName)) +static void applyBetterWM(FFDisplayServerResult* result, const char* processName) { + if (!ffStrSet(processName)) { return; + } ffStrbufSetS(&result->wmProcessName, processName); - //If it is a known wm, this will set the pretty name + // If it is a known wm, this will set the pretty name applyPrettyNameIfWM(result, processName); - //If it isn't a known wm, set the pretty name to the process name - if(result->wmPrettyName.length == 0) + // If it isn't a known wm, set the pretty name to the process name + if (result->wmPrettyName.length == 0) { ffStrbufAppend(&result->wmPrettyName, &result->wmProcessName); + } } -static void applyPrettyNameIfDE(FFDisplayServerResult* result, const char* name) -{ - if(!ffStrSet(name)) +static void applyPrettyNameIfDE(FFDisplayServerResult* result, const char* name) { + if (!ffStrSet(name)) { return; + } - else if( + else if ( ffStrEqualsIgnCase(name, "KDE") || ffStrEqualsIgnCase(name, "plasma") || ffStrEqualsIgnCase(name, "plasmashell") || - ffStrEqualsIgnCase(name, "plasmawayland") - ) { + ffStrEqualsIgnCase(name, "plasmawayland")) { ffStrbufSetStatic(&result->deProcessName, "plasmashell"); ffStrbufSetStatic(&result->dePrettyName, FF_DE_PRETTY_PLASMA); applyBetterWM(result, getenv("KDEWM")); } - else if( + else if ( ffStrEqualsIgnCase(name, "GNOME") || ffStrEqualsIgnCase(name, "ubuntu:GNOME") || ffStrEqualsIgnCase(name, "ubuntu") || - ffStrEqualsIgnCase(name, "gnome-shell") - ) { + ffStrEqualsIgnCase(name, "gnome-shell")) { ffStrbufSetStatic(&result->deProcessName, "gnome-shell"); const char* sessionMode = getenv("GNOME_SHELL_SESSION_MODE"); - if (sessionMode && ffStrEquals(sessionMode, "classic")) + if (sessionMode && ffStrEquals(sessionMode, "classic")) { ffStrbufSetStatic(&result->dePrettyName, FF_DE_PRETTY_GNOME_CLASSIC); - else + } else { ffStrbufSetStatic(&result->dePrettyName, FF_DE_PRETTY_GNOME); + } } - else if( + else if ( ffStrEqualsIgnCase(name, "X-Cinnamon") || - ffStrEqualsIgnCase(name, "Cinnamon") - ) { + ffStrEqualsIgnCase(name, "Cinnamon")) { ffStrbufSetS(&result->deProcessName, "cinnamon"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_CINNAMON); } - else if( + else if ( ffStrEqualsIgnCase(name, "XFCE") || ffStrEqualsIgnCase(name, "X-XFCE") || ffStrEqualsIgnCase(name, "XFCE4") || ffStrEqualsIgnCase(name, "X-XFCE4") || - ffStrEqualsIgnCase(name, "xfce4-session") - ) { + ffStrEqualsIgnCase(name, "xfce4-session")) { ffStrbufSetS(&result->deProcessName, "xfce4-session"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_XFCE4); } - else if( + else if ( ffStrEqualsIgnCase(name, "MATE") || ffStrEqualsIgnCase(name, "X-MATE") || - ffStrEqualsIgnCase(name, "mate-session") - ) { + ffStrEqualsIgnCase(name, "mate-session")) { ffStrbufSetS(&result->deProcessName, "mate-session"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_MATE); } - else if( + else if ( ffStrEqualsIgnCase(name, "LXQt") || ffStrEqualsIgnCase(name, "X-LXQt") || - ffStrEqualsIgnCase(name, "lxqt-session") - ) { + ffStrEqualsIgnCase(name, "lxqt-session")) { ffStrbufSetS(&result->deProcessName, "lxqt-session"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_LXQT); - if (result->wmProcessName.length == 0) - { + if (result->wmProcessName.length == 0) { FF_STRBUF_AUTO_DESTROY wmProcessNameBuffer = ffStrbufCreate(); ffParsePropFileConfig("lxqt/session.conf", "window_manager =", &wmProcessNameBuffer); applyBetterWM(result, wmProcessNameBuffer.chars); } } - else if( + else if ( ffStrEqualsIgnCase(name, "Budgie") || ffStrEqualsIgnCase(name, "X-Budgie") || ffStrEqualsIgnCase(name, "budgie-desktop") || - ffStrEqualsIgnCase(name, "Budgie:GNOME") - ) { + ffStrEqualsIgnCase(name, "Budgie:GNOME")) { ffStrbufSetS(&result->deProcessName, "budgie-desktop"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_BUDGIE); } - else if( - ffStrEqualsIgnCase(name, "dtsession") - ) { + else if ( + ffStrEqualsIgnCase(name, "dtsession")) { ffStrbufSetS(&result->deProcessName, "dtsession"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_CDE); } - else if( - ffStrEqualsIgnCase(name, "ukui-session") - ) { + else if ( + ffStrEqualsIgnCase(name, "ukui-session")) { ffStrbufSetS(&result->deProcessName, "ukui-session"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_UKUI); } - else if( - ffStrStartsWithIgnCase(name, "Unity:Unity") - ) { + else if ( + ffStrStartsWithIgnCase(name, "Unity:Unity")) { ffStrbufSetS(&result->deProcessName, "unity-session"); ffStrbufSetS(&result->dePrettyName, FF_DE_PRETTY_UNITY); } } - -static const char* getFromProcesses(FFDisplayServerResult* result) -{ +static const char* getFromProcesses(FFDisplayServerResult* result) { uint32_t userId = instance.state.platform.uid; #if __FreeBSD__ - #ifdef __DragonFly__ - #define ki_comm kp_comm - #endif +# ifdef __DragonFly__ +# define ki_comm kp_comm +# endif int request[] = {CTL_KERN, KERN_PROC, KERN_PROC_UID, (int) userId}; size_t length = 0; - if(sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) + if (sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) { return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_UID}, NULL) failed"; + } FF_AUTO_FREE struct kinfo_proc* procs = (struct kinfo_proc*) malloc(length); - if(sysctl(request, ARRAY_SIZE(request), procs, &length, NULL, 0) != 0) + if (sysctl(request, ARRAY_SIZE(request), procs, &length, NULL, 0) != 0) { return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_UID}, procs) failed"; + } length /= sizeof(*procs); - for (struct kinfo_proc* proc = procs; proc < procs + length; ++proc) - { - if(result->dePrettyName.length == 0) + for (struct kinfo_proc* proc = procs; proc < procs + length; ++proc) { + if (result->dePrettyName.length == 0) { applyPrettyNameIfDE(result, proc->ki_comm); + } - if(result->wmPrettyName.length == 0) + if (result->wmPrettyName.length == 0) { applyNameIfWM(result, proc->ki_comm); + } - if(result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) + if (result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) { break; + } } #elif __OpenBSD__ kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); int count = 0; const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_UID, (int) userId, sizeof(*proc), &count); - if (proc) - { - for (int i = 0; i < count; ++i) - { - if(result->dePrettyName.length == 0) + if (proc) { + for (int i = 0; i < count; ++i) { + if (result->dePrettyName.length == 0) { applyPrettyNameIfDE(result, proc[i].p_comm); + } - if(result->wmPrettyName.length == 0) + if (result->wmPrettyName.length == 0) { applyNameIfWM(result, proc[i].p_comm); + } - if(result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) + if (result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) { break; + } } } kvm_close(kd); #elif __sun FF_AUTO_CLOSE_DIR DIR* procdir = opendir("/proc"); - if(procdir == NULL) + if (procdir == NULL) { return "opendir(\"/proc\") failed"; + } FF_STRBUF_AUTO_DESTROY procPath = ffStrbufCreateA(64); ffStrbufAppendS(&procPath, "/proc/"); @@ -329,35 +336,39 @@ static const char* getFromProcesses(FFDisplayServerResult* result) uint32_t procPathLength = procPath.length; struct dirent* dirent; - while((dirent = readdir(procdir)) != NULL) - { - if (!ffCharIsDigit(dirent->d_name[0])) + while ((dirent = readdir(procdir)) != NULL) { + if (!ffCharIsDigit(dirent->d_name[0])) { continue; + } ffStrbufAppendS(&procPath, dirent->d_name); ffStrbufAppendS(&procPath, "/psinfo"); psinfo_t proc; - if (ffReadFileData(procPath.chars, sizeof(proc), &proc) == sizeof(proc)) - { + if (ffReadFileData(procPath.chars, sizeof(proc), &proc) == sizeof(proc)) { ffStrbufSubstrBefore(&procPath, procPathLength); - if (proc.pr_uid != userId) + if (proc.pr_uid != userId) { continue; + } - if(result->dePrettyName.length == 0) + if (result->dePrettyName.length == 0) { applyPrettyNameIfDE(result, proc.pr_fname); + } - if(result->wmPrettyName.length == 0) + if (result->wmPrettyName.length == 0) { applyNameIfWM(result, proc.pr_fname); + } - if(result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) + if (result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) { break; + } } } #elif __linux__ || __GNU__ FF_AUTO_CLOSE_DIR DIR* procdir = opendir("/proc"); - if(procdir == NULL) + if (procdir == NULL) { return "opendir(\"/proc\") failed"; + } FF_STRBUF_AUTO_DESTROY procPath = ffStrbufCreateA(64); ffStrbufAppendS(&procPath, "/proc/"); @@ -365,139 +376,142 @@ static const char* getFromProcesses(FFDisplayServerResult* result) uint32_t procPathLength = procPath.length; FF_STRBUF_AUTO_DESTROY loginuid = ffStrbufCreate(); - FF_STRBUF_AUTO_DESTROY processName = ffStrbufCreateA(256); //Some processes have large command lines (looking at you chrome) + FF_STRBUF_AUTO_DESTROY processName = ffStrbufCreateA(256); // Some processes have large command lines (looking at you chrome) struct dirent* dirent; - while((dirent = readdir(procdir)) != NULL) - { - //Match only folders starting with a number (the pid folders) - if(dirent->d_type != DT_DIR || !ffCharIsDigit(dirent->d_name[0])) + while ((dirent = readdir(procdir)) != NULL) { + // Match only folders starting with a number (the pid folders) + if (dirent->d_type != DT_DIR || !ffCharIsDigit(dirent->d_name[0])) { continue; + } ffStrbufAppendS(&procPath, dirent->d_name); uint32_t procFolderPathLength = procPath.length; - //Don't check for processes not owned by the current user. + // Don't check for processes not owned by the current user. ffStrbufAppendS(&procPath, "/loginuid"); ffReadFileBuffer(procPath.chars, &loginuid); - if(ffStrbufToUInt(&loginuid, (uint64_t) -1) != userId) - { + if (ffStrbufToUInt(&loginuid, (uint64_t) -1) != userId) { ffStrbufSubstrBefore(&procPath, procPathLength); continue; } ffStrbufSubstrBefore(&procPath, procFolderPathLength); - //We check the cmdline for the process name, because it is not trimmed. + // We check the cmdline for the process name, because it is not trimmed. ffStrbufAppendS(&procPath, "/cmdline"); ffReadFileBuffer(procPath.chars, &processName); ffStrbufTrimRightSpace(&processName); - ffStrbufSubstrBeforeFirstC(&processName, '\0'); //Trim the arguments + ffStrbufSubstrBeforeFirstC(&processName, '\0'); // Trim the arguments ffStrbufSubstrAfterLastC(&processName, '/'); ffStrbufSubstrBefore(&procPath, procPathLength); - if(result->dePrettyName.length == 0) + if (result->dePrettyName.length == 0) { applyPrettyNameIfDE(result, processName.chars); + } - if(result->wmPrettyName.length == 0) + if (result->wmPrettyName.length == 0) { applyNameIfWM(result, processName.chars); + } - if(result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) + if (result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) { break; + } } #elif __NetBSD__ int request[] = {CTL_KERN, KERN_PROC2, KERN_PROC_UID, (int) userId, sizeof(struct kinfo_proc2), INT_MAX}; size_t size = 0; - if(sysctl(request, ARRAY_SIZE(request), NULL, &size, NULL, 0) != 0) + if (sysctl(request, ARRAY_SIZE(request), NULL, &size, NULL, 0) != 0) { return "sysctl(KERN_PROC_UID, NULL) failed"; + } FF_AUTO_FREE struct kinfo_proc2* procs = malloc(size); - if(sysctl(request, ARRAY_SIZE(request), procs, &size, NULL, 0) != 0) + if (sysctl(request, ARRAY_SIZE(request), procs, &size, NULL, 0) != 0) { return "sysctl(KERN_PROC_UID, procs) failed"; + } - for(struct kinfo_proc2* proc = procs; proc < procs + (size / sizeof(struct kinfo_proc2)); proc++) - { - if(result->dePrettyName.length == 0) + for (struct kinfo_proc2* proc = procs; proc < procs + (size / sizeof(struct kinfo_proc2)); proc++) { + if (result->dePrettyName.length == 0) { applyPrettyNameIfDE(result, proc->p_comm); + } - if(result->wmPrettyName.length == 0) + if (result->wmPrettyName.length == 0) { applyNameIfWM(result, proc->p_comm); + } - if(result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) + if (result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) { break; + } } #endif return NULL; } -void ffdsDetectWMDE(FFDisplayServerResult* result) -{ - #if __ANDROID__ - if(ffStrbufIgnCaseEqualS(&result->wmProtocolName, FF_WM_PROTOCOL_SURFACEFLINGER)) +void ffdsDetectWMDE(FFDisplayServerResult* result) { +#if __ANDROID__ + if (ffStrbufIgnCaseEqualS(&result->wmProtocolName, FF_WM_PROTOCOL_SURFACEFLINGER)) { return; // Only supported when connected to X11 - #endif + } +#endif const char* env = parseEnv(); - if(result->wmProcessName.length > 0) - { - //If we found the processName via display server, use it. - //This will set the pretty name if it is a known WM, otherwise the prettyName to the processName + if (result->wmProcessName.length > 0) { + // If we found the processName via display server, use it. + // This will set the pretty name if it is a known WM, otherwise the prettyName to the processName applyPrettyNameIfWM(result, result->wmProcessName.chars); - if(result->wmPrettyName.length == 0) + if (result->wmPrettyName.length == 0) { ffStrbufSet(&result->wmPrettyName, &result->wmProcessName); - } - else - { - //if env is a known WM, use it + } + } else { + // if env is a known WM, use it applyNameIfWM(result, env); } - //Connecting to a display server only gives WM results, not DE results. - //If we find it in the environment, use that. + // Connecting to a display server only gives WM results, not DE results. + // If we find it in the environment, use that. applyPrettyNameIfDE(result, env); - //If WM was found by connection to the sever, and DE in the environment, we can return - //This way we never call getFromProcDir(), which has slow initialization time - if(result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) + // If WM was found by connection to the sever, and DE in the environment, we can return + // This way we never call getFromProcDir(), which has slow initialization time + if (result->dePrettyName.length > 0 && result->wmPrettyName.length > 0) { return; + } - //Get missing WM / DE from processes. + // Get missing WM / DE from processes. getFromProcesses(result); - //Return if both wm and de are set, or if env doesn't contain anything - if( + // Return if both wm and de are set, or if env doesn't contain anything + if ( (result->wmPrettyName.length > 0 && result->dePrettyName.length > 0) || - !ffStrSet(env) - ) return; + !ffStrSet(env)) { + return; + } - //If nothing is set, use env as WM - else if(result->wmPrettyName.length == 0 && result->dePrettyName.length == 0) - { + // If nothing is set, use env as WM + else if (result->wmPrettyName.length == 0 && result->dePrettyName.length == 0) { ffStrbufSetS(&result->wmProcessName, env); ffStrbufSetS(&result->wmPrettyName, env); } - //If only WM is not set, and DE doesn't equal env, use env as WM - else if( + // If only WM is not set, and DE doesn't equal env, use env as WM + else if ( result->wmPrettyName.length == 0 && ffStrbufIgnCaseCompS(&result->deProcessName, env) != 0 && - ffStrbufIgnCaseCompS(&result->dePrettyName, env) != 0 - ) { + ffStrbufIgnCaseCompS(&result->dePrettyName, env) != 0) { ffStrbufSetS(&result->wmProcessName, env); ffStrbufSetS(&result->wmPrettyName, env); } - //If only DE is not set, and WM doesn't equal env, use env as DE - else if( + // If only DE is not set, and WM doesn't equal env, use env as DE + else if ( result->dePrettyName.length == 0 && ffStrbufIgnCaseCompS(&result->wmProcessName, env) != 0 && - ffStrbufIgnCaseCompS(&result->wmPrettyName, env) != 0 - ) { + ffStrbufIgnCaseCompS(&result->wmPrettyName, env) != 0) { ffStrbufSetS(&result->deProcessName, env); ffStrbufSetS(&result->dePrettyName, env); } diff --git a/src/detection/displayserver/linux/xcb.c b/src/detection/displayserver/linux/xcb.c index 007c52b94..3627dd386 100644 --- a/src/detection/displayserver/linux/xcb.c +++ b/src/detection/displayserver/linux/xcb.c @@ -2,19 +2,18 @@ #ifdef FF_HAVE_XCB_RANDR -#include "common/library.h" -#include "common/properties.h" -#include "common/edidHelper.h" -#include "common/mallocHelper.h" -#include "common/stringUtils.h" +# include "common/library.h" +# include "common/properties.h" +# include "common/edidHelper.h" +# include "common/mallocHelper.h" +# include "common/stringUtils.h" -#include -#include -#include -#include +# include +# include +# include +# include -typedef struct XcbRandrData -{ +typedef struct XcbRandrData { FF_LIBRARY_SYMBOL(xcb_randr_get_screen_resources_current) FF_LIBRARY_SYMBOL(xcb_randr_get_screen_resources_current_reply) FF_LIBRARY_SYMBOL(xcb_randr_get_screen_resources_current_modes_iterator) @@ -49,74 +48,77 @@ typedef struct XcbRandrData FF_LIBRARY_SYMBOL(xcb_setup_vendor) FF_LIBRARY_SYMBOL(xcb_setup_vendor_length) - //init once + // init once xcb_connection_t* connection; FFDisplayServerResult* result; } XcbRandrData; -static void* xcbGetProperty(XcbRandrData* data, xcb_window_t window, const char* request) -{ +static void* xcbGetProperty(XcbRandrData* data, xcb_window_t window, const char* request) { xcb_intern_atom_cookie_t requestAtomCookie = data->ffxcb_intern_atom(data->connection, true, (uint16_t) strlen(request), request); FF_AUTO_FREE xcb_intern_atom_reply_t* requestAtomReply = data->ffxcb_intern_atom_reply(data->connection, requestAtomCookie, NULL); - if(requestAtomReply == NULL) + if (requestAtomReply == NULL) { return NULL; + } xcb_get_property_cookie_t propertyCookie = data->ffxcb_get_property(data->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(data->connection, propertyCookie, NULL); - if(propertyReply == NULL) + if (propertyReply == NULL) { return NULL; + } int length = data->ffxcb_get_property_value_length(propertyReply); - if(length <= 0) + if (length <= 0) { return NULL; + } - //Why are xcb property strings not null terminated??? - void* replyValue = malloc((size_t)length + 1); + // Why are xcb property strings not null terminated??? + void* replyValue = malloc((size_t) length + 1); memcpy(replyValue, data->ffxcb_get_property_value(propertyReply), (size_t) length); ((char*) replyValue)[length] = '\0'; return replyValue; } -static xcb_randr_get_output_property_reply_t* xcbRandrGetProperty(XcbRandrData* data, xcb_randr_output_t output, const char* name) -{ +static xcb_randr_get_output_property_reply_t* xcbRandrGetProperty(XcbRandrData* data, xcb_randr_output_t output, const char* name) { xcb_intern_atom_cookie_t requestAtomCookie = data->ffxcb_intern_atom(data->connection, true, (uint16_t) strlen(name), name); FF_AUTO_FREE xcb_intern_atom_reply_t* requestAtomReply = data->ffxcb_intern_atom_reply(data->connection, requestAtomCookie, NULL); - if(requestAtomReply) - { + if (requestAtomReply) { xcb_randr_get_output_property_cookie_t outputPropertyCookie = data->ffxcb_randr_get_output_property(data->connection, output, requestAtomReply->atom, XCB_GET_PROPERTY_TYPE_ANY, 0, 100, false, false); return data->ffxcb_randr_get_output_property_reply(data->connection, outputPropertyCookie, NULL); } return NULL; } -static void xcbDetectWMfromEWMH(XcbRandrData* data, xcb_window_t rootWindow, FFDisplayServerResult* result) -{ - if(result->wmProcessName.length > 0 || ffStrbufEqualS(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND)) +static void xcbDetectWMfromEWMH(XcbRandrData* data, xcb_window_t rootWindow, FFDisplayServerResult* result) { + if (result->wmProcessName.length > 0 || ffStrbufEqualS(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND)) { return; + } FF_AUTO_FREE xcb_window_t* wmWindow = (xcb_window_t*) xcbGetProperty(data, rootWindow, "_NET_SUPPORTING_WM_CHECK"); - if(wmWindow == NULL) + if (wmWindow == NULL) { return; + } FF_AUTO_FREE char* wmName = (char*) xcbGetProperty(data, *wmWindow, "WM_NAME"); - if(!ffStrSet(wmName)) + if (!ffStrSet(wmName)) { wmName = (char*) xcbGetProperty(data, *wmWindow, "_NET_WM_NAME"); + } - if(!ffStrSet(wmName)) + if (!ffStrSet(wmName)) { return; + } ffStrbufSetS(&result->wmProcessName, wmName); } -static void xcbFetchServerVendor(XcbRandrData* data, FFDisplayServerResult* result) -{ +static void xcbFetchServerVendor(XcbRandrData* data, FFDisplayServerResult* result) { const xcb_setup_t* setup = data->ffxcb_get_setup(data->connection); int length = data->ffxcb_setup_vendor_length(setup); - if(length <= 0) + if (length <= 0) { return; + } FF_STRBUF_AUTO_DESTROY serverVendor = ffStrbufCreateNS((uint32_t) length, data->ffxcb_setup_vendor(setup)); @@ -127,49 +129,46 @@ static void xcbFetchServerVendor(XcbRandrData* data, FFDisplayServerResult* resu } } -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, uint32_t dpi) -{ +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, uint32_t dpi) { 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); - if(outputInfoReply == NULL) + if (outputInfoReply == NULL) { return false; + } FF_AUTO_FREE xcb_randr_get_output_property_reply_t* edidReply = xcbRandrGetProperty(data, output, "EDID"); uint8_t* edidData = NULL; uint32_t edidLength = 0; - if(edidReply) - { + if (edidReply) { int len = data->ffxcb_randr_get_output_property_data_length(edidReply); - if(len >= 128) - { + if (len >= 128) { edidData = data->ffxcb_randr_get_output_property_data(edidReply); edidLength = (uint32_t) len; } } - if(edidData) - { + if (edidData) { ffStrbufClear(name); ffEdidGetName(edidData, name); } bool randrEmulation = false; FF_AUTO_FREE xcb_randr_get_output_property_reply_t* randrEmulationReply = xcbRandrGetProperty(data, output, "RANDR Emulation"); - if(randrEmulationReply) - { + if (randrEmulationReply) { int len = data->ffxcb_randr_get_output_property_data_length(randrEmulationReply); - if(len >= 1) + if (len >= 1) { randrEmulation = !!data->ffxcb_randr_get_output_property_data(randrEmulationReply)[0]; + } } 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) + if (crtcInfoReply == NULL) { return false; + } uint32_t rotation; - switch (crtcInfoReply->rotation) - { + switch (crtcInfoReply->rotation) { case XCB_RANDR_ROTATION_ROTATE_90: rotation = 90; break; @@ -187,17 +186,15 @@ static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, xcb_randr_mode_info_t* currentMode = NULL; xcb_randr_mode_info_t* preferredMode = NULL; - if(screenResources) - { + if (screenResources) { xcb_randr_mode_info_iterator_t modesIterator = data->ffxcb_randr_get_screen_resources_current_modes_iterator(screenResources); - if (outputInfoReply->num_preferred > 0) + if (outputInfoReply->num_preferred > 0) { preferredMode = modesIterator.data; + } - while (modesIterator.rem > 0) - { - if (modesIterator.data->id == crtcInfoReply->mode) - { + while (modesIterator.rem > 0) { + if (modesIterator.data->id == crtcInfoReply->mode) { currentMode = modesIterator.data; break; } @@ -227,16 +224,13 @@ static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, : (currentMode ? "xcb-randr-mode" : "xcb-randr-crtc") ); - if (item) - { - if (edidData && edidLength >= 128) - { + if (item) { + if (edidData && edidLength >= 128) { 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; - if ((rotation == 90 || rotation == 180) && !randrEmulation) - { + if ((rotation == 90 || rotation == 180) && !randrEmulation) { // In XWayland mode, width / height has been swapped out of box uint32_t tmp = item->width; item->width = item->height; @@ -247,36 +241,34 @@ static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, return !!item; } -static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* monitor, struct xcb_randr_get_screen_resources_current_reply_t* screenResources, uint8_t bitDepth, uint32_t dpi) -{ - //for some reasons, we have to construct this our self +static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* monitor, struct xcb_randr_get_screen_resources_current_reply_t* screenResources, uint8_t bitDepth, uint32_t dpi) { + // for some reasons, we have to construct this our self xcb_randr_output_iterator_t outputIterator = { .index = 0, .data = data->ffxcb_randr_monitor_info_outputs(monitor), - .rem = data->ffxcb_randr_monitor_info_outputs_length(monitor) - }; + .rem = data->ffxcb_randr_monitor_info_outputs_length(monitor)}; FF_AUTO_FREE xcb_get_atom_name_reply_t* nameReply = data->ffxcb_get_atom_name_reply( data->connection, data->ffxcb_get_atom_name(data->connection, monitor->name), - NULL - ); + NULL); FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateNS( (uint32_t) data->ffxcb_get_atom_name_name_length(nameReply), - data->ffxcb_get_atom_name_name(nameReply) - ); + data->ffxcb_get_atom_name_name(nameReply)); const FFDisplayType displayType = ffdsGetDisplayType(name.chars); bool foundOutput = false; - while(outputIterator.rem > 0) - { - if(xcbRandrHandleOutput(data, *outputIterator.data, &name, monitor->primary, displayType, screenResources, bitDepth, dpi)) + while (outputIterator.rem > 0) { + if (xcbRandrHandleOutput(data, *outputIterator.data, &name, monitor->primary, displayType, screenResources, bitDepth, dpi)) { foundOutput = true; + } data->ffxcb_randr_output_next(&outputIterator); } - if (foundOutput) return true; + if (foundOutput) { + return true; + } FFDisplayResult* display = ffdsAppendDisplay( data->result, @@ -284,7 +276,9 @@ static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* (uint32_t) monitor->height, 0, dpi, - 0, 0, 0, + 0, + 0, + 0, 0, &name, displayType, @@ -292,30 +286,31 @@ static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* 0, (uint32_t) monitor->width_in_millimeters, (uint32_t) monitor->height_in_millimeters, - "xcb-randr-monitor" - ); - if (display) display->bitDepth = bitDepth; + "xcb-randr-monitor"); + if (display) { + display->bitDepth = bitDepth; + } return !!display; } -static bool xcbRandrHandleMonitors(XcbRandrData* data, xcb_screen_t* screen) -{ +static bool xcbRandrHandleMonitors(XcbRandrData* data, xcb_screen_t* screen) { xcb_randr_get_monitors_cookie_t monitorsCookie = data->ffxcb_randr_get_monitors(data->connection, screen->root, true); FF_AUTO_FREE xcb_randr_get_monitors_reply_t* monitorsReply = data->ffxcb_randr_get_monitors_reply(data->connection, monitorsCookie, NULL); - if(monitorsReply == NULL) + 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. + // 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); uint32_t dpi = 0; FF_AUTO_FREE const char* resourceManager = xcbGetProperty(data, screen->root, "RESOURCE_MANAGER"); - if (resourceManager) - { + if (resourceManager) { FF_STRBUF_AUTO_DESTROY dpiStr = ffStrbufCreate(); - if (ffParsePropLines(resourceManager, "Xft.dpi:", &dpiStr)) + if (ffParsePropLines(resourceManager, "Xft.dpi:", &dpiStr)) { dpi = (uint32_t) ffStrbufToUInt(&dpiStr, 96); + } } uint8_t bitDepth = (uint8_t) (screen->root_depth / 3); @@ -323,30 +318,32 @@ static bool xcbRandrHandleMonitors(XcbRandrData* data, xcb_screen_t* screen) bool foundMonitor = false; - while(monitorInfoIterator.rem > 0) - { - if(xcbRandrHandleMonitor(data, monitorInfoIterator.data, screenResources, bitDepth, dpi)) + while (monitorInfoIterator.rem > 0) { + if (xcbRandrHandleMonitor(data, monitorInfoIterator.data, screenResources, bitDepth, dpi)) { foundMonitor = true; + } data->ffxcb_randr_monitor_info_next(&monitorInfoIterator); } return foundMonitor; } -static void xcbRandrHandleScreen(XcbRandrData* data, xcb_screen_t* screen) -{ - //With all the initialisation done, start the detection - if(xcbRandrHandleMonitors(data, screen)) +static void xcbRandrHandleScreen(XcbRandrData* data, xcb_screen_t* screen) { + // With all the initialisation done, start the detection + if (xcbRandrHandleMonitors(data, screen)) { return; + } - //If detetction failed, fallback to screen = monitor, like in the libxcb.so implementation + // If detetction failed, fallback to screen = monitor, like in the libxcb.so implementation ffdsAppendDisplay( data->result, (uint32_t) screen->width_in_pixels, (uint32_t) screen->height_in_pixels, 0, 0, - 0, 0, 0, + 0, + 0, + 0, 0, NULL, FF_DISPLAY_TYPE_UNKNOWN, @@ -354,12 +351,10 @@ static void xcbRandrHandleScreen(XcbRandrData* data, xcb_screen_t* screen) (uint64_t) screen->root, (uint32_t) screen->width_in_millimeters, (uint32_t) screen->height_in_millimeters, - "xcb-randr-screen" - ); + "xcb-randr-screen"); } -const char* ffdsConnectXcbRandr(FFDisplayServerResult* result) -{ +const char* ffdsConnectXcbRandr(FFDisplayServerResult* result) { FF_LIBRARY_LOAD_MESSAGE(xcbRandr, "libxcb-randr" FF_LIBRARY_EXTENSION, 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(xcbRandr, xcb_connect) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(xcbRandr, xcb_connection_has_error) @@ -404,47 +399,40 @@ const char* ffdsConnectXcbRandr(FFDisplayServerResult* result) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(xcbRandr, data, xcb_randr_get_crtc_info) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(xcbRandr, data, xcb_randr_get_crtc_info_reply) - data.connection = ffxcb_connect(NULL, NULL); - if(ffxcb_connection_has_error(data.connection) > 0) - { + if (ffxcb_connection_has_error(data.connection) > 0) { ffxcb_disconnect(data.connection); return "xcb_connect() failed"; } - data.result = result; xcb_screen_iterator_t iterator = ffxcb_setup_roots_iterator(ffxcb_get_setup(data.connection)); - - if(iterator.rem > 0) { + if (iterator.rem > 0) { xcbDetectWMfromEWMH(&data, iterator.data->root, result); xcbFetchServerVendor(&data, result); } - - while(iterator.rem > 0) - { + while (iterator.rem > 0) { xcbRandrHandleScreen(&data, iterator.data); ffxcb_screen_next(&iterator); } ffxcb_disconnect(data.connection); - - //If wayland hasn't set this, connection failed for it. So we are running only a X Server, not XWayland. - if(result->wmProtocolName.length == 0) + // If wayland hasn't set this, connection failed for it. So we are running only a X Server, not XWayland. + if (result->wmProtocolName.length == 0) { ffStrbufSetS(&result->wmProtocolName, FF_WM_PROTOCOL_X11); + } return NULL; } #else -const char* ffdsConnectXcbRandr(FFDisplayServerResult* result) -{ - //Do nothing. There are other implementations coming +const char* ffdsConnectXcbRandr(FFDisplayServerResult* result) { + // Do nothing. There are other implementations coming FF_UNUSED(result) return "Fastfetch was compiled without libxcb-randr support"; } diff --git a/src/detection/displayserver/linux/xlib.c b/src/detection/displayserver/linux/xlib.c index ed3179b1d..bc69329a7 100644 --- a/src/detection/displayserver/linux/xlib.c +++ b/src/detection/displayserver/linux/xlib.c @@ -2,16 +2,15 @@ #ifdef FF_HAVE_XRANDR -#include "common/library.h" -#include "common/properties.h" -#include "common/edidHelper.h" -#include "common/stringUtils.h" +# include "common/library.h" +# include "common/properties.h" +# include "common/edidHelper.h" +# include "common/stringUtils.h" -#include -#include +# include +# include -typedef struct XrandrData -{ +typedef struct XrandrData { FF_LIBRARY_SYMBOL(XInternAtom) FF_LIBRARY_SYMBOL(XGetAtomName) FF_LIBRARY_SYMBOL(XGetWindowProperty) @@ -27,45 +26,43 @@ typedef struct XrandrData FF_LIBRARY_SYMBOL(XRRFreeScreenResources) FF_LIBRARY_SYMBOL(XRRFreeMonitors) - //Init once + // Init once Display* display; FFDisplayServerResult* result; } XrandrData; -static unsigned char* x11GetProperty(XrandrData* data, Display* display, Window window, const char* request) -{ +static unsigned char* x11GetProperty(XrandrData* data, Display* display, Window window, const char* request) { Atom requestAtom = data->ffXInternAtom(display, request, False); - if(requestAtom == None) + if (requestAtom == None) { return NULL; + } Atom actualType; unsigned long unused; unsigned char* result = NULL; - if(data->ffXGetWindowProperty(display, window, requestAtom, 0, 64, False, AnyPropertyType, &actualType, (int*) &unused, &unused, &unused, &result) != Success) + if (data->ffXGetWindowProperty(display, window, requestAtom, 0, 64, False, AnyPropertyType, &actualType, (int*) &unused, &unused, &unused, &result) != Success) { return NULL; + } return result; } -static uint8_t* xrandrGetProperty(XrandrData* data, RROutput output, const char* name, uint32_t* bufSize) -{ +static uint8_t* xrandrGetProperty(XrandrData* data, RROutput output, const char* name, uint32_t* bufSize) { unsigned long size = 0; uint8_t* result = NULL; Atom atomEdid = data->ffXInternAtom(data->display, name, true); - if (atomEdid != None) - { + if (atomEdid != None) { int actual_format = 0; unsigned long bytes_after = 0; Atom actual_type = None; - if (data->ffXRRGetOutputProperty(data->display, output, atomEdid, 0, 100, false, false, AnyPropertyType, &actual_type, &actual_format, &size, &bytes_after, &result) == Success) - { - if (size == 0) + if (data->ffXRRGetOutputProperty(data->display, output, atomEdid, 0, 100, false, false, AnyPropertyType, &actual_type, &actual_format, &size, &bytes_after, &result) == Success) { + if (size == 0) { data->ffXFree(result); - else - { - if (bufSize) + } else { + if (bufSize) { *bufSize = (uint32_t) size; + } return result; } } @@ -74,46 +71,49 @@ static uint8_t* xrandrGetProperty(XrandrData* data, RROutput output, const char* return NULL; } -static void x11DetectWMFromEWMH(XrandrData* data, FFDisplayServerResult* result) -{ - if(result->wmProcessName.length > 0 || ffStrbufEqualS(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND)) +static void x11DetectWMFromEWMH(XrandrData* data, FFDisplayServerResult* result) { + if (result->wmProcessName.length > 0 || ffStrbufEqualS(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND)) { return; + } Window* wmWindow = (Window*) x11GetProperty(data, data->display, DefaultRootWindow(data->display), "_NET_SUPPORTING_WM_CHECK"); - if(wmWindow == NULL) + if (wmWindow == NULL) { return; + } char* wmName = (char*) x11GetProperty(data, data->display, *wmWindow, "WM_NAME"); - if(!ffStrSet(wmName)) + if (!ffStrSet(wmName)) { wmName = (char*) x11GetProperty(data, data->display, *wmWindow, "_NET_WM_NAME"); + } - if(ffStrSet(wmName)) + if (ffStrSet(wmName)) { ffStrbufSetS(&result->wmProcessName, wmName); + } data->ffXFree(wmName); data->ffXFree(wmWindow); } -static void x11FetchServerVendor(XrandrData* data, FFDisplayServerResult* result) -{ +static void x11FetchServerVendor(XrandrData* data, FFDisplayServerResult* result) { const char* serverVendor = data->ffXServerVendor(data->display); - if (serverVendor && !ffStrEquals(serverVendor, "The X.Org Foundation")) + if (serverVendor && !ffStrEquals(serverVendor, "The X.Org Foundation")) { ffStrbufSetS(&result->wmProtocolName, serverVendor); + } } -static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* name, bool primary, FFDisplayType displayType, uint8_t* edidData, uint32_t edidLength, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi, bool randrEmulation) -{ - //We do the check here, because we want the best fallback display if this call failed - if(screenResources == NULL) +static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* name, bool primary, FFDisplayType displayType, uint8_t* edidData, uint32_t edidLength, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi, bool randrEmulation) { + // We do the check here, because we want the best fallback display if this call failed + if (screenResources == NULL) { return false; + } XRRCrtcInfo* crtcInfo = data->ffXRRGetCrtcInfo(data->display, screenResources, output->crtc); - if(crtcInfo == NULL) + if (crtcInfo == NULL) { return false; + } uint32_t rotation; - switch (crtcInfo->rotation) - { + switch (crtcInfo->rotation) { case RR_Rotate_90: rotation = 90; break; @@ -129,10 +129,8 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* } XRRModeInfo* currentMode = NULL; - for(int i = 0; i < screenResources->nmode; i++) - { - if(screenResources->modes[i].id == crtcInfo->mode) - { + for (int i = 0; i < screenResources->nmode; i++) { + if (screenResources->modes[i].id == crtcInfo->mode) { currentMode = &screenResources->modes[i]; break; } @@ -158,19 +156,15 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* (uint32_t) output->mm_height, randrEmulation ? (currentMode ? "xlib-randr-emu-mode" : "xlib-randr-emu-crtc") - : (currentMode ? "xlib-randr-mode" : "xlib-randr-crtc") - ); + : (currentMode ? "xlib-randr-mode" : "xlib-randr-crtc")); - if (item) - { - if (edidLength) - { + if (item) { + 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; - if ((rotation == 90 || rotation == 180) && !randrEmulation) - { + if ((rotation == 90 || rotation == 180) && !randrEmulation) { // In XWayland mode, width / height has been swapped out of box uint32_t tmp = item->width; item->width = item->height; @@ -182,50 +176,52 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* return !!item; } -static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name, bool primary, FFDisplayType displayType, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi) -{ +static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name, bool primary, FFDisplayType displayType, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi) { XRROutputInfo* outputInfo = data->ffXRRGetOutputInfo(data->display, screenResources, output); - if(outputInfo == NULL) + if (outputInfo == NULL) { return false; + } uint32_t edidLength = 0; uint8_t* edidData = xrandrGetProperty(data, output, RR_PROPERTY_RANDR_EDID, &edidLength); - if (edidLength >= 128) - { + if (edidLength >= 128) { ffStrbufClear(name); ffEdidGetName(edidData, name); - } - else + } else { edidLength = 0; + } uint8_t* randrEmulation = xrandrGetProperty(data, output, "RANDR Emulation", NULL); bool res = xrandrHandleCrtc(data, outputInfo, name, primary, displayType, edidData, edidLength, screenResources, bitDepth, dpi, randrEmulation ? !!randrEmulation[0] : false); - if (edidData) + if (edidData) { data->ffXFree(edidData); - if (randrEmulation) + } + if (randrEmulation) { data->ffXFree(randrEmulation); + } data->ffXRRFreeOutputInfo(outputInfo); return res; } -static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi) -{ +static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi) { bool foundOutput = false; char* xname = data->ffXGetAtomName(data->display, monitorInfo->name); FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateS(xname); data->ffXFree(xname); FFDisplayType displayType = ffdsGetDisplayType(name.chars); - for(int i = 0; i < monitorInfo->noutput; i++) - { - if(xrandrHandleOutput(data, monitorInfo->outputs[i], &name, monitorInfo->primary, displayType, screenResources, bitDepth, dpi)) + for (int i = 0; i < monitorInfo->noutput; i++) { + if (xrandrHandleOutput(data, monitorInfo->outputs[i], &name, monitorInfo->primary, displayType, screenResources, bitDepth, dpi)) { foundOutput = true; + } } - if (foundOutput) return true; + if (foundOutput) { + return true; + } FFDisplayResult* display = ffdsAppendDisplay( data->result, @@ -233,7 +229,9 @@ static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo, X (uint32_t) monitorInfo->height, 0, dpi, - 0, 0, 0, + 0, + 0, + 0, 0, &name, displayType, @@ -241,38 +239,39 @@ static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo, X 0, (uint32_t) monitorInfo->mwidth, (uint32_t) monitorInfo->mheight, - "xlib-randr-monitor" - ); - if (display) display->bitDepth = bitDepth; + "xlib-randr-monitor"); + if (display) { + display->bitDepth = bitDepth; + } return !!display; } -static bool xrandrHandleMonitors(XrandrData* data, Screen* screen) -{ +static bool xrandrHandleMonitors(XrandrData* data, Screen* screen) { int numberOfMonitors; XRRMonitorInfo* monitorInfos = data->ffXRRGetMonitors(data->display, RootWindowOfScreen(screen), True, &numberOfMonitors); - if(monitorInfos == NULL) + if (monitorInfos == NULL) { return false; + } XRRScreenResources* screenResources = data->ffXRRGetScreenResourcesCurrent(data->display, RootWindowOfScreen(screen)); uint32_t dpi = 1; char* resourceManager = (char*) x11GetProperty(data, data->display, screen->root, "RESOURCE_MANAGER"); - if (resourceManager) - { + if (resourceManager) { FF_STRBUF_AUTO_DESTROY dpiStr = ffStrbufCreate(); - if (ffParsePropLines(resourceManager, "Xft.dpi:", &dpiStr)) + if (ffParsePropLines(resourceManager, "Xft.dpi:", &dpiStr)) { dpi = (uint32_t) ffStrbufToUInt(&dpiStr, 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], screenResources, bitDepth, dpi)) + for (int i = 0; i < numberOfMonitors; i++) { + if (xrandrHandleMonitor(data, &monitorInfos[i], screenResources, bitDepth, dpi)) { foundAMonitor = true; + } } data->ffXRRFreeMonitors(monitorInfos); @@ -281,19 +280,21 @@ static bool xrandrHandleMonitors(XrandrData* data, Screen* screen) return foundAMonitor; } -static void xrandrHandleScreen(XrandrData* data, Screen* screen) -{ - if(xrandrHandleMonitors(data, screen)) +static void xrandrHandleScreen(XrandrData* data, Screen* screen) { + if (xrandrHandleMonitors(data, screen)) { return; + } - //Fallback to screen + // Fallback to screen ffdsAppendDisplay( data->result, (uint32_t) WidthOfScreen(screen), (uint32_t) HeightOfScreen(screen), 0, 0, - 0, 0, 0, + 0, + 0, + 0, 0, NULL, FF_DISPLAY_TYPE_UNKNOWN, @@ -301,12 +302,10 @@ static void xrandrHandleScreen(XrandrData* data, Screen* screen) RootWindowOfScreen(screen), (uint32_t) WidthMMOfScreen(screen), (uint32_t) HeightMMOfScreen(screen), - "xlib-randr-screen" - ); + "xlib-randr-screen"); } -const char* ffdsConnectXrandr(FFDisplayServerResult* result) -{ +const char* ffdsConnectXrandr(FFDisplayServerResult* result) { FF_LIBRARY_LOAD_MESSAGE(xrandr, "libXrandr" FF_LIBRARY_EXTENSION, 3) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(xrandr, XOpenDisplay) @@ -330,33 +329,35 @@ const char* ffdsConnectXrandr(FFDisplayServerResult* result) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(xrandr, data, XRRFreeMonitors); data.display = ffXOpenDisplay(NULL); - if(data.display == NULL) + if (data.display == NULL) { return "XOpenDisplay() failed"; + } - if(ScreenCount(data.display) > 0) { + if (ScreenCount(data.display) > 0) { x11DetectWMFromEWMH(&data, result); x11FetchServerVendor(&data, result); } data.result = result; - for(int i = 0; i < ScreenCount(data.display); i++) + for (int i = 0; i < ScreenCount(data.display); i++) { xrandrHandleScreen(&data, ScreenOfDisplay(data.display, i)); + } ffXCloseDisplay(data.display); - //If wayland hasn't set this, connection failed for it. So we are running only a X Server, not XWayland. - if(result->wmProtocolName.length == 0) + // If wayland hasn't set this, connection failed for it. So we are running only a X Server, not XWayland. + if (result->wmProtocolName.length == 0) { ffStrbufSetS(&result->wmProtocolName, FF_WM_PROTOCOL_X11); + } return NULL; } #else -const char* ffdsConnectXrandr(FFDisplayServerResult* result) -{ - //Do nothing here. There are more x11 implementations to come. +const char* ffdsConnectXrandr(FFDisplayServerResult* result) { + // Do nothing here. There are more x11 implementations to come. FF_UNUSED(result); return "Fastfetch was compiled without libXrandr support"; } diff --git a/src/detection/dns/dns_apple.c b/src/detection/dns/dns_apple.c index 30a4cc362..10ea519b8 100644 --- a/src/detection/dns/dns_apple.c +++ b/src/detection/dns/dns_apple.c @@ -8,43 +8,45 @@ #include -static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FFlist* results) -{ +static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FFlist* results) { FF_DEBUG("Attempting to read DNS config from %s", path); FF_AUTO_CLOSE_FILE FILE* file = fopen(path, "r"); - if (!file) - { + if (!file) { FF_DEBUG("Failed to open %s: %s", path, strerror(errno)); return "fopen(path, r) failed"; } - if (results->length > 0) - { + if (results->length > 0) { FF_DEBUG("Clearing existing DNS entries (%u entries)", results->length); - FF_LIST_FOR_EACH(FFstrbuf, item, *results) + FF_LIST_FOR_EACH (FFstrbuf, item, *results) { ffStrbufDestroy(item); + } ffListClear(results); } FF_AUTO_FREE char* line = NULL; size_t len = 0; - while (getline(&line, &len, file) != -1) - { - if (ffStrStartsWith(line, "nameserver")) - { + while (getline(&line, &len, file) != -1) { + if (ffStrStartsWith(line, "nameserver")) { char* nameserver = line + strlen("nameserver"); - while (*nameserver == ' ' || *nameserver == '\t') + while (*nameserver == ' ' || *nameserver == '\t') { nameserver++; - if (*nameserver == '\0') continue; + } + if (*nameserver == '\0') { + continue; + } char* comment = strchr(nameserver, '#'); - if (comment) *comment = '\0'; + if (comment) { + *comment = '\0'; + } if ((ffStrContainsC(nameserver, ':') && !(options->showType & FF_DNS_TYPE_IPV6_BIT)) || - (ffStrContainsC(nameserver, '.') && !(options->showType & FF_DNS_TYPE_IPV4_BIT))) + (ffStrContainsC(nameserver, '.') && !(options->showType & FF_DNS_TYPE_IPV4_BIT))) { continue; + } FFstrbuf* item = (FFstrbuf*) ffListAdd(results); ffStrbufInitS(item, nameserver); @@ -57,36 +59,30 @@ static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FF return NULL; } -const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) -{ +const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { // Handle macOS-specific DNS configurations FF_DEBUG("Using SystemConfiguration framework for macOS"); // Create a reference to the dynamic store FF_CFTYPE_AUTO_RELEASE SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("fastfetch"), NULL, NULL); - if (store) - { + if (store) { // Get the network global IPv4 and IPv6 configuration FF_CFTYPE_AUTO_RELEASE CFStringRef key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetDNS); - if (key) - { + if (key) { FF_CFTYPE_AUTO_RELEASE CFDictionaryRef dict = SCDynamicStoreCopyValue(store, key); - if (dict) - { + if (dict) { // Get the DNS server addresses array CFArrayRef dnsServers = CFDictionaryGetValue(dict, kSCPropNetDNSServerAddresses); - if (dnsServers) - { + if (dnsServers) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - for (CFIndex i = 0; i < CFArrayGetCount(dnsServers); i++) - { - if (ffCfStrGetString(CFArrayGetValueAtIndex(dnsServers, i), &buffer) == NULL) - { + for (CFIndex i = 0; i < CFArrayGetCount(dnsServers); i++) { + if (ffCfStrGetString(CFArrayGetValueAtIndex(dnsServers, i), &buffer) == NULL) { // Check if the address matches our filter if ((ffStrbufContainC(&buffer, ':') && !(options->showType & FF_DNS_TYPE_IPV6_BIT)) || - (ffStrbufContainC(&buffer, '.') && !(options->showType & FF_DNS_TYPE_IPV4_BIT))) + (ffStrbufContainC(&buffer, '.') && !(options->showType & FF_DNS_TYPE_IPV4_BIT))) { continue; + } // Add to results FFstrbuf* item = (FFstrbuf*) ffListAdd(results); @@ -100,8 +96,9 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) } // If we didn't find any servers, try resolv.conf as fallback - if (results->length > 0) + if (results->length > 0) { return NULL; + } FF_DEBUG("No DNS servers found via SystemConfiguration, trying resolv.conf"); // Try standard resolv.conf location on macOS as a fallback diff --git a/src/detection/dns/dns_linux.c b/src/detection/dns/dns_linux.c index 988b6faa9..6897c9c69 100644 --- a/src/detection/dns/dns_linux.c +++ b/src/detection/dns/dns_linux.c @@ -6,48 +6,50 @@ #include "common/debug.h" #ifdef __HAIKU__ -#define RESOLV_CONF "/system/settings/network/resolv.conf" +# define RESOLV_CONF "/system/settings/network/resolv.conf" #else -#define RESOLV_CONF "/etc/resolv.conf" +# define RESOLV_CONF "/etc/resolv.conf" #endif -static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FFlist* results) -{ +static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FFlist* results) { FF_DEBUG("Attempting to read DNS config from %s", path); FF_AUTO_CLOSE_FILE FILE* file = fopen(path, "r"); - if (!file) - { + if (!file) { FF_DEBUG("Failed to open %s: %s", path, strerror(errno)); return "fopen(path, r) failed"; } - if (results->length > 0) - { + if (results->length > 0) { FF_DEBUG("Clearing existing DNS entries (%u entries)", results->length); - FF_LIST_FOR_EACH(FFstrbuf, item, *results) + FF_LIST_FOR_EACH (FFstrbuf, item, *results) { ffStrbufDestroy(item); + } ffListClear(results); } FF_AUTO_FREE char* line = NULL; size_t len = 0; - while (getline(&line, &len, file) != -1) - { - if (ffStrStartsWith(line, "nameserver")) - { + while (getline(&line, &len, file) != -1) { + if (ffStrStartsWith(line, "nameserver")) { char* nameserver = line + strlen("nameserver"); - while (*nameserver == ' ' || *nameserver == '\t') + while (*nameserver == ' ' || *nameserver == '\t') { nameserver++; - if (*nameserver == '\0') continue; + } + if (*nameserver == '\0') { + continue; + } char* comment = strchr(nameserver, '#'); - if (comment) *comment = '\0'; + if (comment) { + *comment = '\0'; + } if ((ffStrContainsC(nameserver, ':') && !(options->showType & FF_DNS_TYPE_IPV6_BIT)) || - (ffStrContainsC(nameserver, '.') && !(options->showType & FF_DNS_TYPE_IPV4_BIT))) + (ffStrContainsC(nameserver, '.') && !(options->showType & FF_DNS_TYPE_IPV4_BIT))) { continue; + } FFstrbuf* item = (FFstrbuf*) ffListAdd(results); ffStrbufInitS(item, nameserver); @@ -60,81 +62,81 @@ static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FF return NULL; } -const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) -{ +const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { FF_DEBUG("Starting DNS detection"); const char* error = detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT RESOLV_CONF, options, results); - if (error != NULL) - { + if (error != NULL) { FF_DEBUG("Error detecting DNS: %s", error); return error; } - #if __linux__ && !__ANDROID__ +#if __linux__ && !__ANDROID__ // Handle different DNS management services - if (results->length == 1) - { + if (results->length == 1) { const FFstrbuf* firstEntry = FF_LIST_FIRST(FFstrbuf, *results); - if (ffStrbufEqualS(firstEntry, "127.0.0.53")) - { + if (ffStrbufEqualS(firstEntry, "127.0.0.53")) { FF_DEBUG("Detected systemd-resolved (127.0.0.53), checking actual DNS servers"); // Managed by systemd-resolved - if (detectDnsFromConf("/run/systemd/resolve/resolv.conf", options, results) == NULL) + if (detectDnsFromConf("/run/systemd/resolve/resolv.conf", options, results) == NULL) { return NULL; - } - else if (ffStrbufEqualS(firstEntry, "127.0.0.1")) - { + } + } else if (ffStrbufEqualS(firstEntry, "127.0.0.1")) { FF_DEBUG("Detected possible NetworkManager (127.0.0.1), checking actual DNS servers"); // Managed by NetworkManager - if (detectDnsFromConf("/var/run/NetworkManager/resolv.conf", options, results) == NULL) + if (detectDnsFromConf("/var/run/NetworkManager/resolv.conf", options, results) == NULL) { return NULL; + } } } // Check other possible DNS configuration files - if (results->length == 0) - { + if (results->length == 0) { FF_DEBUG("No DNS servers found, trying alternative config files"); // Try resolvconf FF_DEBUG("Trying resolvconf configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/run/resolvconf/resolv.conf", options, results) == NULL && results->length > 0) + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/run/resolvconf/resolv.conf", options, results) == NULL && results->length > 0) { return NULL; + } // Try dnsmasq FF_DEBUG("Trying dnsmasq configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/dnsmasq/resolv.conf", options, results) == NULL && results->length > 0) + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/dnsmasq/resolv.conf", options, results) == NULL && results->length > 0) { return NULL; + } // Try openresolv FF_DEBUG("Trying openresolv configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/resolv.conf.openresolv", options, results) == NULL && results->length > 0) + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/resolv.conf.openresolv", options, results) == NULL && results->length > 0) { return NULL; + } } - #elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) || defined(__OpenBSD__) +#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) || defined(__OpenBSD__) // Handle BSD-specific DNS configurations - if (results->length == 0) - { + if (results->length == 0) { FF_DEBUG("No DNS servers found, trying BSD-specific config files"); // FreeBSD and other BSDs may use resolvconf service FF_DEBUG("Trying BSD resolvconf configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/resolvconf/resolv.conf", options, results) == NULL && results->length > 0) + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/resolvconf/resolv.conf", options, results) == NULL && results->length > 0) { return NULL; + } // Some BSDs store DNS configuration here FF_DEBUG("Trying BSD nameserver configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/nameserver", options, results) == NULL && results->length > 0) + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/nameserver", options, results) == NULL && results->length > 0) { return NULL; + } // Try common BSD paths FF_DEBUG("Trying BSD common paths"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/nameserver", options, results) == NULL && results->length > 0) + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/nameserver", options, results) == NULL && results->length > 0) { return NULL; + } } - #endif +#endif FF_DEBUG("DNS detection completed with %u servers found", results->length); return NULL; diff --git a/src/detection/dns/dns_windows.c b/src/detection/dns/dns_windows.c index 5acd31248..5c3c05f04 100644 --- a/src/detection/dns/dns_windows.c +++ b/src/detection/dns/dns_windows.c @@ -5,18 +5,15 @@ #include #include -const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) -{ +const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { IP_ADAPTER_ADDRESSES* FF_AUTO_FREE adapter_addresses = NULL; // Multiple attempts in case interfaces change while // we are in the middle of querying them. DWORD adapter_addresses_buffer_size = 0; - for (int attempts = 0;; ++attempts) - { - if (adapter_addresses_buffer_size) - { - adapter_addresses = (IP_ADAPTER_ADDRESSES*)realloc(adapter_addresses, adapter_addresses_buffer_size); + for (int attempts = 0;; ++attempts) { + if (adapter_addresses_buffer_size) { + adapter_addresses = (IP_ADAPTER_ADDRESSES*) realloc(adapter_addresses, adapter_addresses_buffer_size); assert(adapter_addresses); } @@ -29,32 +26,32 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) adapter_addresses, &adapter_addresses_buffer_size); - if (error == ERROR_SUCCESS) + if (error == ERROR_SUCCESS) { break; - else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4) + } else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4) { continue; - else + } else { return "GetAdaptersAddresses() failed"; + } } uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteV4()->ifIndex; // Iterate through all of the adapters - for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next) - { - if (adapter->IfIndex != defaultRouteIfIndex) continue; - if (adapter->OperStatus != IfOperStatusUp) continue; + for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next) { + if (adapter->IfIndex != defaultRouteIfIndex) { + continue; + } + if (adapter->OperStatus != IfOperStatusUp) { + continue; + } - for (IP_ADAPTER_DNS_SERVER_ADDRESS_XP * ifa = adapter->FirstDnsServerAddress; ifa; ifa = ifa->Next) - { + for (IP_ADAPTER_DNS_SERVER_ADDRESS_XP* ifa = adapter->FirstDnsServerAddress; ifa; ifa = ifa->Next) { FFstrbuf* item = (FFstrbuf*) ffListAdd(results); - if (ifa->Address.lpSockaddr->sa_family == AF_INET) - { + if (ifa->Address.lpSockaddr->sa_family == AF_INET) { SOCKADDR_IN* ipv4 = (SOCKADDR_IN*) ifa->Address.lpSockaddr; ffStrbufInitA(item, INET_ADDRSTRLEN); item->length = (uint32_t) (RtlIpv4AddressToStringA(&ipv4->sin_addr, item->chars) - item->chars); - } - else if (ifa->Address.lpSockaddr->sa_family == AF_INET6) - { + } else if (ifa->Address.lpSockaddr->sa_family == AF_INET6) { SOCKADDR_IN6* ipv6 = (SOCKADDR_IN6*) ifa->Address.lpSockaddr; ffStrbufInitA(item, INET6_ADDRSTRLEN); item->length = (uint32_t) (RtlIpv6AddressToStringA(&ipv6->sin6_addr, item->chars) - item->chars); diff --git a/src/detection/editor/editor.c b/src/detection/editor/editor.c index 9b0fe6070..99410f551 100644 --- a/src/detection/editor/editor.c +++ b/src/detection/editor/editor.c @@ -7,93 +7,105 @@ #include -static bool extractNvimVersionFromBinary(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) -{ - if (!ffStrStartsWith(str, "NVIM v")) return true; +static bool extractNvimVersionFromBinary(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrStartsWith(str, "NVIM v")) { + return true; + } ffStrbufSetS((FFstrbuf*) userdata, str + strlen("NVIM v")); return false; } -static bool extractVimVersionFromBinary(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) -{ - if (!ffStrStartsWith(str, "VIM - Vi IMproved ")) return true; +static bool extractVimVersionFromBinary(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrStartsWith(str, "VIM - Vi IMproved ")) { + return true; + } ffStrbufSetS((FFstrbuf*) userdata, str + strlen("VIM - Vi IMproved ")); ffStrbufSubstrBeforeFirstC(userdata, ' '); return false; } -static bool extractNanoVersionFromBinary(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) -{ - if (!ffStrStartsWith(str, "GNU nano ")) return true; +static bool extractNanoVersionFromBinary(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrStartsWith(str, "GNU nano ")) { + return true; + } ffStrbufSetS((FFstrbuf*) userdata, str + strlen("GNU nano ")); return false; } -const char* ffDetectEditor(FFEditorResult* result) -{ +const char* ffDetectEditor(FFEditorResult* result) { ffStrbufSetS(&result->name, getenv("VISUAL")); - if (result->name.length) + if (result->name.length) { result->type = "Visual"; - else - { + } else { ffStrbufSetS(&result->name, getenv("EDITOR")); - if (result->name.length) + if (result->name.length) { result->type = "Editor"; - else + } else { return "$VISUAL or $EDITOR not set"; + } } - if (ffIsAbsolutePath(result->name.chars)) + if (ffIsAbsolutePath(result->name.chars)) { ffStrbufSet(&result->path, &result->name); - else - { + } else { const char* error = ffFindExecutableInPath(result->name.chars, &result->path); - if (error) return NULL; + if (error) { + return NULL; + } } { char buf[PATH_MAX + 1]; - if (!realpath(result->path.chars, buf)) + if (!realpath(result->path.chars, buf)) { return NULL; + } // WIN32: Should we handle scoop shim exe here? - #ifdef __linux__ +#ifdef __linux__ if (!ffStrEndsWith(buf, "/snap")) - #endif +#endif ffStrbufSetS(&result->path, buf); } { uint32_t index = ffStrbufLastIndexC(&result->path, - #ifndef _WIN32 +#ifndef _WIN32 '/' - #else +#else '\\' - #endif +#endif ); - if (index == result->path.length) + if (index == result->path.length) { return NULL; + } ffStrbufSetS(&result->exe, &result->path.chars[index + 1]); - if (!result->exe.length) + if (!result->exe.length) { return NULL; + } - #ifdef _WIN32 - if (ffStrbufEndsWithS(&result->exe, ".exe")) +#ifdef _WIN32 + if (ffStrbufEndsWithS(&result->exe, ".exe")) { ffStrbufSubstrBefore(&result->exe, result->exe.length - 4); - #endif + } +#endif } - if (!instance.config.general.detectVersion) return NULL; + if (!instance.config.general.detectVersion) { + return NULL; + } - if (ffStrbufEqualS(&result->exe, "nvim")) + if (ffStrbufEqualS(&result->exe, "nvim")) { ffBinaryExtractStrings(result->path.chars, extractNvimVersionFromBinary, &result->version, (uint32_t) strlen("NVIM v0.0.0")); - else if (ffStrbufEqualS(&result->exe, "vim") || ffStrbufStartsWithS(&result->exe, "vim.")) + } else if (ffStrbufEqualS(&result->exe, "vim") || ffStrbufStartsWithS(&result->exe, "vim.")) { ffBinaryExtractStrings(result->path.chars, extractVimVersionFromBinary, &result->version, (uint32_t) strlen("VIM - Vi IMproved 0.0")); - else if (ffStrbufEqualS(&result->exe, "nano")) + } else if (ffStrbufEqualS(&result->exe, "nano")) { ffBinaryExtractStrings(result->path.chars, extractNanoVersionFromBinary, &result->version, (uint32_t) strlen("GNU nano 0.0")); + } - if (result->version.length > 0) return NULL; + if (result->version.length > 0) { + return NULL; + } const char* param = NULL; if ( @@ -108,35 +120,40 @@ const char* ffDetectEditor(FFEditorResult* result) ffStrbufEqualS(&result->exe, "code") || ffStrbufEqualS(&result->exe, "pluma") || ffStrbufEqualS(&result->exe, "sublime_text") || - ffStrbufEqualS(&result->exe, "zeditor") - ) param = "--version"; - else if ( + ffStrbufEqualS(&result->exe, "zeditor")) { + param = "--version"; + } else if ( ffStrbufEqualS(&result->exe, "kak") || - ffStrbufEqualS(&result->exe, "pico") - ) param = "-version"; - else if ( - ffStrbufEqualS(&result->exe, "ne") - ) param = "-h"; - else return NULL; - - ffProcessAppendStdOut(&result->version, (char* const[]){ - result->path.chars, - (char*) param, - NULL, - }); - - if (result->version.length == 0) + ffStrbufEqualS(&result->exe, "pico")) { + param = "-version"; + } else if ( + ffStrbufEqualS(&result->exe, "ne")) { + param = "-h"; + } else { return NULL; + } + + ffProcessAppendStdOut(&result->version, (char* const[]) { + result->path.chars, + (char*) param, + NULL, + }); + + if (result->version.length == 0) { + return NULL; + } ffStrbufSubstrBeforeFirstC(&result->version, '\n'); const char* versionStart = strpbrk(result->version.chars, "0123456789"); if (versionStart != NULL) { const char* versionEnd = strpbrk(versionStart, " \t\v\f\r"); - if (versionEnd != NULL) - ffStrbufSubstrBefore(&result->version, (uint32_t)(versionEnd - result->version.chars)); + if (versionEnd != NULL) { + ffStrbufSubstrBefore(&result->version, (uint32_t) (versionEnd - result->version.chars)); + } - if (versionStart != result->version.chars) - ffStrbufSubstrAfter(&result->version, (uint32_t)(versionStart - result->version.chars - 1)); + if (versionStart != result->version.chars) { + ffStrbufSubstrAfter(&result->version, (uint32_t) (versionStart - result->version.chars - 1)); + } } return NULL; diff --git a/src/detection/editor/editor.h b/src/detection/editor/editor.h index d130c43bd..ae315c0bc 100644 --- a/src/detection/editor/editor.h +++ b/src/detection/editor/editor.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/editor/option.h" -typedef struct FFEditorResult -{ +typedef struct FFEditorResult { const char* type; FFstrbuf name; FFstrbuf exe; diff --git a/src/detection/font/font.c b/src/detection/font/font.c index c0cced9a6..c651f29bd 100644 --- a/src/detection/font/font.c +++ b/src/detection/font/font.c @@ -2,16 +2,17 @@ const char* ffDetectFontImpl(FFFontResult* font); -const char* ffDetectFont(FFFontResult* font) -{ +const char* ffDetectFont(FFFontResult* font) { const char* error = ffDetectFontImpl(font); - if(error) return error; + if (error) { + return error; + } - for(uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) - { - if(font->fonts[i].length > 0) + for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { + if (font->fonts[i].length > 0) { return NULL; + } } return "No fonts found"; diff --git a/src/detection/font/font.h b/src/detection/font/font.h index ed05d1d8c..af04c6df9 100644 --- a/src/detection/font/font.h +++ b/src/detection/font/font.h @@ -5,8 +5,7 @@ enum { FF_DETECT_FONT_NUM_FONTS = 4 }; -typedef struct FFFontResult -{ +typedef struct FFFontResult { /** * Linux / BSD: Qt, GTK2, GTK3, GTK4 * MacOS: System, User, System Mono, User Mono diff --git a/src/detection/font/font_haiku.cpp b/src/detection/font/font_haiku.cpp index 0e0eb6751..a7827d932 100644 --- a/src/detection/font/font_haiku.cpp +++ b/src/detection/font/font_haiku.cpp @@ -7,22 +7,18 @@ extern "C" { #include extern "C" { - const char* ffDetectFontImpl(FFFontResult* result); +const char* ffDetectFontImpl(FFFontResult* result); } -static void generateString(FFFontResult* font) -{ - const char* types[] = { "Plain", "Menu", "Bold", "Mono" }; - for(uint32_t i = 0; i < ARRAY_SIZE(types); ++i) - { - if(i == 0 || !ffStrbufEqual(&font->fonts[i - 1], &font->fonts[i])) - { - if(i > 0) +static void generateString(FFFontResult* font) { + const char* types[] = {"Plain", "Menu", "Bold", "Mono"}; + for (uint32_t i = 0; i < ARRAY_SIZE(types); ++i) { + if (i == 0 || !ffStrbufEqual(&font->fonts[i - 1], &font->fonts[i])) { + if (i > 0) { ffStrbufAppendS(&font->display, "], "); + } ffStrbufAppendF(&font->display, "%s [%s", font->fonts[i].chars, types[i]); - } - else - { + } else { ffStrbufAppendS(&font->display, " / "); ffStrbufAppendS(&font->display, types[i]); } @@ -30,31 +26,26 @@ static void generateString(FFFontResult* font) ffStrbufAppendC(&font->display, ']'); } -const char* ffDetectFontImpl(FFFontResult* result) -{ +const char* ffDetectFontImpl(FFFontResult* result) { struct menu_info menuInfo; - const BFont *f; + const BFont* f; // We need a valid be_app to query the app_server here. BApplication app("application/x-vnd.fastfetch-cli-fastfetch"); - if ((f = be_plain_font) != NULL) - { + if ((f = be_plain_font) != NULL) { f->GetFamilyAndStyle(&menuInfo.f_family, &menuInfo.f_style); - ffStrbufAppendF(&result->fonts[0], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int)f->Size()); + ffStrbufAppendF(&result->fonts[0], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) f->Size()); } - if (get_menu_info(&menuInfo) == B_OK) - { - ffStrbufAppendF(&result->fonts[1], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int)menuInfo.font_size); + if (get_menu_info(&menuInfo) == B_OK) { + ffStrbufAppendF(&result->fonts[1], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) menuInfo.font_size); } - if ((f = be_bold_font) != NULL) - { + if ((f = be_bold_font) != NULL) { f->GetFamilyAndStyle(&menuInfo.f_family, &menuInfo.f_style); - ffStrbufAppendF(&result->fonts[2], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int)f->Size()); + ffStrbufAppendF(&result->fonts[2], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) f->Size()); } - if ((f = be_fixed_font) != NULL) - { + if ((f = be_fixed_font) != NULL) { f->GetFamilyAndStyle(&menuInfo.f_family, &menuInfo.f_style); - ffStrbufAppendF(&result->fonts[3], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int)f->Size()); + ffStrbufAppendF(&result->fonts[3], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) f->Size()); } generateString(result); diff --git a/src/detection/font/font_linux.c b/src/detection/font/font_linux.c index e3253379c..5e82b682c 100644 --- a/src/detection/font/font_linux.c +++ b/src/detection/font/font_linux.c @@ -4,17 +4,13 @@ #include "detection/gtk_qt/gtk_qt.h" #include "font.h" -static void generateString(FFFontResult* font) -{ - if(font->fonts[0].length > 0) - { +static void generateString(FFFontResult* font) { + if (font->fonts[0].length > 0) { ffStrbufAppend(&font->display, &font->fonts[0]); ffStrbufAppendS(&font->display, " [Qt]"); - for(uint8_t i = 1; i < ARRAY_SIZE(font->fonts); i++) - { - if(font->fonts[i].length > 0) - { + for (uint8_t i = 1; i < ARRAY_SIZE(font->fonts); i++) { + if (font->fonts[i].length > 0) { ffStrbufAppendS(&font->display, ", "); break; } @@ -24,12 +20,12 @@ static void generateString(FFFontResult* font) ffParseGTK(&font->display, &font->fonts[1], &font->fonts[2], &font->fonts[3]); } -const char* ffDetectFontImpl(FFFontResult* result) -{ +const char* ffDetectFontImpl(FFFontResult* result) { const FFDisplayServerResult* wmde = ffConnectDisplayServer(); - if(ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) + if (ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) { return "Font isn't supported in TTY"; + } FFfont qt; ffFontInitQt(&qt, ffDetectQt()->font.chars); diff --git a/src/detection/font/font_nosupport.c b/src/detection/font/font_nosupport.c index cce3904ff..861e00a8a 100644 --- a/src/detection/font/font_nosupport.c +++ b/src/detection/font/font_nosupport.c @@ -1,8 +1,7 @@ #include "fastfetch.h" #include "font.h" -const char* ffDetectFontImpl(FF_MAYBE_UNUSED FFFontResult* result) -{ +const char* ffDetectFontImpl(FF_MAYBE_UNUSED FFFontResult* result) { FF_UNUSED(result); return "Not supported on this platform"; } diff --git a/src/detection/font/font_windows.c b/src/detection/font/font_windows.c index 3075defaf..e3e890175 100644 --- a/src/detection/font/font_windows.c +++ b/src/detection/font/font_windows.c @@ -4,19 +4,15 @@ #include -static void generateString(FFFontResult* font) -{ - const char* types[] = { "Caption", "Menu", "Message", "Status" }; - for(uint32_t i = 0; i < ARRAY_SIZE(types); ++i) - { - if(i == 0 || !ffStrbufEqual(&font->fonts[i - 1], &font->fonts[i])) - { - if(i > 0) +static void generateString(FFFontResult* font) { + const char* types[] = {"Caption", "Menu", "Message", "Status"}; + for (uint32_t i = 0; i < ARRAY_SIZE(types); ++i) { + if (i == 0 || !ffStrbufEqual(&font->fonts[i - 1], &font->fonts[i])) { + if (i > 0) { ffStrbufAppendS(&font->display, "], "); + } ffStrbufAppendF(&font->display, "%s [%s", font->fonts[i].chars, types[i]); - } - else - { + } else { ffStrbufAppendS(&font->display, " / "); ffStrbufAppendS(&font->display, types[i]); } @@ -24,38 +20,41 @@ static void generateString(FFFontResult* font) ffStrbufAppendC(&font->display, ']'); } -const char* ffDetectFontImpl(FFFontResult* result) -{ +const char* ffDetectFontImpl(FFFontResult* result) { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop\\WindowMetrics", &hKey, NULL)) + if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop\\WindowMetrics", &hKey, NULL)) { return "ffRegOpenKeyForRead(HKEY_CURRENT_USER\\Control Panel\\Desktop\\WindowMetrics) failed"; + } LOGFONTW fonts[4]; FFArgBuffer fontBuffers[4] = { - { .data = &fonts[0], .length = sizeof(fonts[0]) }, - { .data = &fonts[1], .length = sizeof(fonts[1]) }, - { .data = &fonts[2], .length = sizeof(fonts[2]) }, - { .data = &fonts[3], .length = sizeof(fonts[3]) }, + {.data = &fonts[0], .length = sizeof(fonts[0])}, + {.data = &fonts[1], .length = sizeof(fonts[1])}, + {.data = &fonts[2], .length = sizeof(fonts[2])}, + {.data = &fonts[3], .length = sizeof(fonts[3])}, }; if (!ffRegReadValues(hKey, 4, (FFRegValueArg[]) { - FF_ARG(fontBuffers[0], L"CaptionFont"), - FF_ARG(fontBuffers[1], L"MenuFont"), - FF_ARG(fontBuffers[2], L"MessageFont"), - FF_ARG(fontBuffers[3], L"StatusFont"), - }, NULL)) + FF_ARG(fontBuffers[0], L"CaptionFont"), + FF_ARG(fontBuffers[1], L"MenuFont"), + FF_ARG(fontBuffers[2], L"MessageFont"), + FF_ARG(fontBuffers[3], L"StatusFont"), + }, + NULL)) { return "ffRegReadValues(HKEY_CURRENT_USER\\Control Panel\\Desktop\\WindowMetrics) failed"; + } - for (uint32_t i = 0; i < ARRAY_SIZE(fonts); ++i) - { - if (fontBuffers[i].length != sizeof(LOGFONTW)) + for (uint32_t i = 0; i < ARRAY_SIZE(fonts); ++i) { + if (fontBuffers[i].length != sizeof(LOGFONTW)) { continue; // Invalid data, skip + } LOGFONTW* logFont = &fonts[i]; ffStrbufSetWS(&result->fonts[i], logFont->lfFaceName); - if (logFont->lfHeight < 0) - ffStrbufAppendF(&result->fonts[i], " (%dpt)", (int)-logFont->lfHeight); + if (logFont->lfHeight < 0) { + ffStrbufAppendF(&result->fonts[i], " (%dpt)", (int) -logFont->lfHeight); + } } generateString(result); diff --git a/src/detection/gamepad/gamepad.h b/src/detection/gamepad/gamepad.h index 3caed4cc7..f26def9ca 100644 --- a/src/detection/gamepad/gamepad.h +++ b/src/detection/gamepad/gamepad.h @@ -2,8 +2,7 @@ #include "fastfetch.h" -typedef struct FFGamepadDevice -{ +typedef struct FFGamepadDevice { FFstrbuf serial; FFstrbuf name; uint8_t battery; // 0-100% diff --git a/src/detection/gamepad/gamepad_apple.c b/src/detection/gamepad/gamepad_apple.c index 3651717f4..758722d00 100644 --- a/src/detection/gamepad/gamepad_apple.c +++ b/src/detection/gamepad/gamepad_apple.c @@ -5,8 +5,7 @@ #include #include -static void enumSet(IOHIDDeviceRef value, FFlist* results) -{ +static void enumSet(IOHIDDeviceRef value, FFlist* results) { FFGamepadDevice* device = (FFGamepadDevice*) ffListAdd(results); ffStrbufInit(&device->serial); ffStrbufInit(&device->name); @@ -16,14 +15,11 @@ static void enumSet(IOHIDDeviceRef value, FFlist* results) ffCfStrGetString(manufacturer, &device->name); CFStringRef product = IOHIDDeviceGetProperty(value, CFSTR(kIOHIDProductKey)); - if (device->name.length) - { + if (device->name.length) { ffCfStrGetString(product, &device->serial); ffStrbufAppendC(&device->name, ' '); ffStrbufAppend(&device->name, &device->serial); - } - else - { + } else { ffCfStrGetString(product, &device->name); } @@ -31,34 +27,21 @@ static void enumSet(IOHIDDeviceRef value, FFlist* results) ffCfStrGetString(serialNumber, &device->serial); } -const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) -{ +const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { IOHIDManagerRef FF_CFTYPE_AUTO_RELEASE manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) + if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { return "IOHIDManagerOpen() failed"; + } - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void **)(CFStringRef[]){ - CFSTR(kIOHIDDeviceUsagePageKey), - CFSTR(kIOHIDDeviceUsageKey) - }, (const void **)(CFNumberRef[]){ - ffCfCreateInt(kHIDPage_GenericDesktop), - ffCfCreateInt(kHIDUsage_GD_Joystick) - }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching2 = CFDictionaryCreate(kCFAllocatorDefault, (const void **)(CFStringRef[]){ - CFSTR(kIOHIDDeviceUsagePageKey), - CFSTR(kIOHIDDeviceUsageKey) - }, (const void **)(CFNumberRef[]){ - ffCfCreateInt(kHIDPage_GenericDesktop), - ffCfCreateInt(kHIDUsage_GD_GamePad) - }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFArrayRef FF_CFTYPE_AUTO_RELEASE matchings = CFArrayCreate(kCFAllocatorDefault, (const void **)(CFTypeRef[]){ - matching1, matching2 - }, 2, &kCFTypeArrayCallBacks); + CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) {CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey)}, (const void**) (CFNumberRef[]) {ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Joystick)}, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching2 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) {CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey)}, (const void**) (CFNumberRef[]) {ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_GamePad)}, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFArrayRef FF_CFTYPE_AUTO_RELEASE matchings = CFArrayCreate(kCFAllocatorDefault, (const void**) (CFTypeRef[]) {matching1, matching2}, 2, &kCFTypeArrayCallBacks); IOHIDManagerSetDeviceMatchingMultiple(manager, matchings); CFSetRef FF_CFTYPE_AUTO_RELEASE set = IOHIDManagerCopyDevices(manager); - if (set) + if (set) { CFSetApplyFunction(set, (CFSetApplierFunction) &enumSet, devices); + } IOHIDManagerClose(manager, kIOHIDOptionsTypeNone); return NULL; diff --git a/src/detection/gamepad/gamepad_bsd.c b/src/detection/gamepad/gamepad_bsd.c index 469e49e03..b39446a03 100644 --- a/src/detection/gamepad/gamepad_bsd.c +++ b/src/detection/gamepad/gamepad_bsd.c @@ -6,40 +6,39 @@ #include #if __has_include() -#include // FreeBSD +# include // FreeBSD #else -#include // DragonFly +# include // DragonFly #endif #define MAX_UHID_JOYS 64 -const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) -{ +const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { char path[16]; - for (int i = 0; i < MAX_UHID_JOYS; i++) - { + for (int i = 0; i < MAX_UHID_JOYS; i++) { snprintf(path, ARRAY_SIZE(path), "/dev/uhid%d", i); FF_AUTO_CLOSE_FD int fd = open(path, O_RDONLY | O_CLOEXEC); - if (fd < 0) - { - if (errno == ENOENT) + if (fd < 0) { + if (errno == ENOENT) { break; // No more devices + } continue; // Device not found } report_desc_t repDesc = hid_get_report_desc(fd); - if (!repDesc) continue; + if (!repDesc) { + continue; + } int reportId = hid_get_report_id(fd); struct hid_data* hData = hid_start_parse(repDesc, 0, reportId); - if (hData) - { + if (hData) { struct hid_item hItem; - while (hid_get_item(hData, &hItem) > 0) - { - if (HID_PAGE(hItem.usage) != 1) continue; - switch (HID_USAGE(hItem.usage)) - { + while (hid_get_item(hData, &hItem) > 0) { + if (HID_PAGE(hItem.usage) != 1) { + continue; + } + switch (HID_USAGE(hItem.usage)) { case 1: // Pointer. FreeBSD returns 1 for my Pro Controller for some reason case 4: // Joystick case 5: // Gamepad @@ -49,8 +48,7 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) } struct usb_device_info di; - if (ioctl(fd, USB_GET_DEVICEINFO, &di) != -1) - { + if (ioctl(fd, USB_GET_DEVICEINFO, &di) != -1) { FFGamepadDevice* device = (FFGamepadDevice*) ffListAdd(devices); ffStrbufInitS(&device->serial, di.udi_serial); ffStrbufInitF(&device->name, "%s %s", di.udi_vendor, di.udi_product); diff --git a/src/detection/gamepad/gamepad_haiku.cpp b/src/detection/gamepad/gamepad_haiku.cpp index 820836f07..8051f19fd 100644 --- a/src/detection/gamepad/gamepad_haiku.cpp +++ b/src/detection/gamepad/gamepad_haiku.cpp @@ -3,14 +3,11 @@ extern "C" { } #include -const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) -{ +const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { BJoystick js; - for (int32 i = 0, n = js.CountDevices(); i < n; ++i) - { + for (int32 i = 0, n = js.CountDevices(); i < n; ++i) { char name[B_OS_NAME_LENGTH]; - if (js.GetDeviceName(i, name) == B_OK) - { + if (js.GetDeviceName(i, name) == B_OK) { FFGamepadDevice* device = (FFGamepadDevice*) ffListAdd(devices); ffStrbufInit(&device->serial); ffStrbufInitS(&device->name, name); diff --git a/src/detection/gamepad/gamepad_linux.c b/src/detection/gamepad/gamepad_linux.c index 1fd44e89b..f7c9276ba 100644 --- a/src/detection/gamepad/gamepad_linux.c +++ b/src/detection/gamepad/gamepad_linux.c @@ -2,8 +2,7 @@ #include "common/io.h" #include "common/stringUtils.h" -static void detectGamepad(FFlist* devices, FFstrbuf* name, FFstrbuf* path) -{ +static void detectGamepad(FFlist* devices, FFstrbuf* name, FFstrbuf* path) { uint32_t baseLen = path->length; FFGamepadDevice* device = (FFGamepadDevice*) ffListAdd(devices); ffStrbufInit(&device->serial); @@ -11,20 +10,20 @@ static void detectGamepad(FFlist* devices, FFstrbuf* name, FFstrbuf* path) device->battery = 0; ffStrbufAppendS(path, "uniq"); - if (ffAppendFileBuffer(path->chars, &device->serial)) + if (ffAppendFileBuffer(path->chars, &device->serial)) { ffStrbufTrimRightSpace(&device->serial); + } ffStrbufSubstrBefore(path, baseLen); ffStrbufAppendS(path, "device/power_supply/"); // /sys/class/input/jsX/device/device/power_supply FF_AUTO_CLOSE_DIR DIR* dirp = opendir(path->chars); - if (dirp) - { + if (dirp) { struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.' || (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN)) + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.' || (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN)) { continue; + } ffStrbufAppendS(path, entry->d_name); ffStrbufAppendS(path, "/capacity"); // /sys/class/input/jsX/device/device/power_supply/XXX/capacity char capacity[32]; @@ -41,42 +40,51 @@ static void detectGamepad(FFlist* devices, FFstrbuf* name, FFstrbuf* path) if (nRead > 0) // Tested with a NS Pro controller { // https://github.com/torvalds/linux/blob/52b1853b080a082ec3749c3a9577f6c71b1d4a90/drivers/power/supply/power_supply_sysfs.c#L124 - switch (capacity[0]) - { - case 'C': device->battery = 1; break; // Critical - case 'L': device->battery = 25; break; // Low - case 'N': device->battery = 50; break; // Normal - case 'H': device->battery = 75; break; // High - case 'F': device->battery = 100; break; // Full + switch (capacity[0]) { + case 'C': + device->battery = 1; + break; // Critical + case 'L': + device->battery = 25; + break; // Low + case 'N': + device->battery = 50; + break; // Normal + case 'H': + device->battery = 75; + break; // High + case 'F': + device->battery = 100; + break; // Full } } } } } -const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) -{ +const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/input/"); - if (dirp == NULL) + if (dirp == NULL) { return "opendir(\"/sys/class/input/\") == NULL"; + } FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/sys/class/input/"); uint32_t baseLen = path.length; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (!ffStrStartsWith(entry->d_name, "js")) + while ((entry = readdir(dirp)) != NULL) { + if (!ffStrStartsWith(entry->d_name, "js")) { continue; - if (!ffCharIsDigit(entry->d_name[strlen("js")])) + } + if (!ffCharIsDigit(entry->d_name[strlen("js")])) { continue; + } ffStrbufAppendS(&path, entry->d_name); ffStrbufAppendS(&path, "/device/name"); FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); - if (ffAppendFileBuffer(path.chars, &name)) - { + if (ffAppendFileBuffer(path.chars, &name)) { ffStrbufTrimRightSpace(&name); ffStrbufSubstrBefore(&path, path.length - 4); detectGamepad(devices, &name, &path); diff --git a/src/detection/gamepad/gamepad_nosupport.c b/src/detection/gamepad/gamepad_nosupport.c index 7c323142a..de104273f 100644 --- a/src/detection/gamepad/gamepad_nosupport.c +++ b/src/detection/gamepad/gamepad_nosupport.c @@ -1,6 +1,5 @@ #include "gamepad.h" -const char* ffDetectGamepad(FF_MAYBE_UNUSED FFlist* devices /* List of FFGamepadDevice */) -{ +const char* ffDetectGamepad(FF_MAYBE_UNUSED FFlist* devices /* List of FFGamepadDevice */) { return "Not supported on this platform"; } diff --git a/src/detection/gamepad/gamepad_windows.c b/src/detection/gamepad/gamepad_windows.c index da7e280fa..93e6495cc 100644 --- a/src/detection/gamepad/gamepad_windows.c +++ b/src/detection/gamepad/gamepad_windows.c @@ -6,93 +6,112 @@ #include #include -static const char* detectKnownDeviceName(uint32_t vendorId, uint32_t productId) -{ - switch (vendorId) - { +static const char* detectKnownDeviceName(uint32_t vendorId, uint32_t productId) { + switch (vendorId) { // Nintendo - case 0x057E: - { - switch (productId) - { - case 0x2006: return "Nintendo Switch Joycon L"; - case 0x2007: return "Nintendo Switch Joycon R"; - case 0x2009: return "Nintendo Switch Pro Controller"; - case 0x200E: return "Nintendo Switch Charging Grip"; - case 0x2017: return "Nintendo Switch SNES Controller"; + case 0x057E: { + switch (productId) { + case 0x2006: + return "Nintendo Switch Joycon L"; + case 0x2007: + return "Nintendo Switch Joycon R"; + case 0x2009: + return "Nintendo Switch Pro Controller"; + case 0x200E: + return "Nintendo Switch Charging Grip"; + case 0x2017: + return "Nintendo Switch SNES Controller"; - default: return NULL; + default: + return NULL; } } // Sony - case 0x054C: - { - switch (productId) - { - case 0x0268: return "Sony DualShock 3 / Six Axis"; + case 0x054C: { + switch (productId) { + case 0x0268: + return "Sony DualShock 3 / Six Axis"; - case 0x05C4: return "Sony DualShock 4 Gen1"; - case 0x09CC: return "Sony DualShock 4 Gen2"; - case 0x0BA0: return "Sony DualShock 4 USB receiver"; + case 0x05C4: + return "Sony DualShock 4 Gen1"; + case 0x09CC: + return "Sony DualShock 4 Gen2"; + case 0x0BA0: + return "Sony DualShock 4 USB receiver"; - case 0x0CE6: return "Sony DualSense"; - case 0x0DF2: return "Sony DualSense Edge"; + case 0x0CE6: + return "Sony DualSense"; + case 0x0DF2: + return "Sony DualSense Edge"; - default: return NULL; + default: + return NULL; } } // Logitech - case 0x046D: - { - switch (productId) - { - case 0xC216: return "Logitech F310, DirectInput"; - case 0xC218: return "Logitech F510, DirectInput"; - case 0xC219: return "Logitech F710, DirectInput"; - case 0xC21D: return "Logitech F310"; - case 0xC21E: return "Logitech F510"; - case 0xC21F: return "Logitech F710"; + case 0x046D: { + switch (productId) { + case 0xC216: + return "Logitech F310, DirectInput"; + case 0xC218: + return "Logitech F510, DirectInput"; + case 0xC219: + return "Logitech F710, DirectInput"; + case 0xC21D: + return "Logitech F310"; + case 0xC21E: + return "Logitech F510"; + case 0xC21F: + return "Logitech F710"; - default: return NULL; + default: + return NULL; } } case 0x045E: // Microsoft Xbox compatible controllers should be handled by Windows without problems - default: return NULL; + default: + return NULL; } } -const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) -{ +const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { UINT nDevices = 0; - if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) + if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) { return "GetRawInputDeviceList(NULL) failed"; - if (nDevices == 0) + } + if (nDevices == 0) { return "No HID devices found"; + } RAWINPUTDEVICELIST* FF_AUTO_FREE pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); - if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) + if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) { return "GetRawInputDeviceList(pRawInputDeviceList) failed"; + } - for (UINT i = 0; i < nDevices; ++i) - { - if (pRawInputDeviceList[i].dwType != RIM_TYPEHID) continue; + for (UINT i = 0; i < nDevices; ++i) { + if (pRawInputDeviceList[i].dwType != RIM_TYPEHID) { + continue; + } HANDLE hDevice = pRawInputDeviceList[i].hDevice; RID_DEVICE_INFO rdi; UINT rdiSize = sizeof(rdi); - if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == (UINT) -1) + if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == (UINT) -1) { continue; + } - if (rdi.hid.usUsagePage != 1 || (rdi.hid.usUsage != 4/*Joystick*/ && rdi.hid.usUsage != 5/*Gamepad*/)) + if (rdi.hid.usUsagePage != 1 || (rdi.hid.usUsage != 4 /*Joystick*/ && rdi.hid.usUsage != 5 /*Gamepad*/)) { continue; + } WCHAR devName[MAX_PATH] = L""; UINT nameSize = MAX_PATH; - if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, devName, &nameSize) == (UINT) -1) + if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, devName, &nameSize) == (UINT) -1) { continue; + } FFGamepadDevice* device = (FFGamepadDevice*) ffListAdd(devices); ffStrbufInit(&device->serial); @@ -100,88 +119,80 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) device->battery = 0; const char* knownGamepad = detectKnownDeviceName(rdi.hid.dwVendorId, rdi.hid.dwProductId); - if (knownGamepad) + if (knownGamepad) { ffStrbufSetS(&device->name, knownGamepad); + } HANDLE FF_AUTO_CLOSE_FD hHidFile = CreateFileW(devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); - if (hHidFile == INVALID_HANDLE_VALUE) - { - if (!knownGamepad) + if (hHidFile == INVALID_HANDLE_VALUE) { + if (!knownGamepad) { ffStrbufSetF(&device->name, "Unknown gamepad %04X-%04X", (unsigned) rdi.hid.dwVendorId, (unsigned) rdi.hid.dwProductId); + } continue; } - if (!knownGamepad) - { + if (!knownGamepad) { wchar_t displayName[126]; - if (HidD_GetProductString(hHidFile, displayName, sizeof(displayName) /*in bytes*/)) - { + if (HidD_GetProductString(hHidFile, displayName, sizeof(displayName) /*in bytes*/)) { wchar_t manufacturer[126]; - if (HidD_GetManufacturerString(hHidFile, manufacturer, sizeof(manufacturer) /*in bytes*/)) - { + if (HidD_GetManufacturerString(hHidFile, manufacturer, sizeof(manufacturer) /*in bytes*/)) { ffStrbufSetWS(&device->name, manufacturer); FF_STRBUF_AUTO_DESTROY displayNameStr = ffStrbufCreateWS(displayName); ffStrbufAppendC(&device->name, ' '); ffStrbufAppend(&device->name, &displayNameStr); - } - else - { + } else { ffStrbufSetWS(&device->name, displayName); } } } wchar_t serialNumber[127] = L""; - if (HidD_GetSerialNumberString(hHidFile, serialNumber, sizeof(serialNumber) /*in bytes*/)) + if (HidD_GetSerialNumberString(hHidFile, serialNumber, sizeof(serialNumber) /*in bytes*/)) { ffStrbufSetWS(&device->serial, serialNumber); + } PHIDP_PREPARSED_DATA preparsedData = NULL; - if (HidD_GetPreparsedData(hHidFile, &preparsedData)) - { + if (HidD_GetPreparsedData(hHidFile, &preparsedData)) { HIDP_CAPS caps; NTSTATUS capsResult = HidP_GetCaps(preparsedData, &caps); HidD_FreePreparsedData(preparsedData); - if (!NT_SUCCESS(capsResult)) + if (!NT_SUCCESS(capsResult)) { continue; + } if ( - (rdi.hid.dwVendorId == 0x054C && ( - rdi.hid.dwProductId == 0x05C4 || // PS4 Gen1 - rdi.hid.dwProductId == 0x09CC // PS4 Gen2 - )) || - (rdi.hid.dwVendorId == 0x057E && ( - rdi.hid.dwProductId == 0x2009 // NS Pro - )) - ) - { + (rdi.hid.dwVendorId == 0x054C && (rdi.hid.dwProductId == 0x05C4 || // PS4 Gen1 + rdi.hid.dwProductId == 0x09CC // PS4 Gen2 + )) || + (rdi.hid.dwVendorId == 0x057E && (rdi.hid.dwProductId == 0x2009 // NS Pro + ))) { // Controller must be connected by other programs FF_AUTO_FREE uint8_t* reportBuffer = malloc(caps.InputReportByteLength); - OVERLAPPED overlapped = { }; + OVERLAPPED overlapped = {}; DWORD nBytes; if (ReadFile(hHidFile, reportBuffer, caps.InputReportByteLength, &nBytes, &overlapped) || - GetOverlappedResultEx(hHidFile, &overlapped, &nBytes, FF_IO_TERM_RESP_WAIT_MS, TRUE)) - { - if (rdi.hid.dwVendorId == 0x054C) - { - if (nBytes > 31) - { + GetOverlappedResultEx(hHidFile, &overlapped, &nBytes, FF_IO_TERM_RESP_WAIT_MS, TRUE)) { + if (rdi.hid.dwVendorId == 0x054C) { + if (nBytes > 31) { uint8_t batteryInfo = reportBuffer[caps.InputReportByteLength == 64 /*USB?*/ ? 30 : 32]; device->battery = (uint8_t) ((batteryInfo & 0x0f) * 100 / (batteryInfo & 0x10 /*charging?*/ ? 11 /*BATTERY_MAX_USB*/ : 8 /*BATTERY_MAX*/)); - if (device->battery > 100) device->battery = 100; + if (device->battery > 100) { + device->battery = 100; + } } - } - else - { - if (nBytes > 3 && reportBuffer[0] == 0x30) - { + } else { + if (nBytes > 3 && reportBuffer[0] == 0x30) { uint8_t batteryInfo = reportBuffer[2]; device->battery = (uint8_t) (((batteryInfo & 0xE0) >> 4) * 100 / 8); - if (device->battery == 0) device->battery = 1; - else if (device->battery > 100) device->battery = 100; + if (device->battery == 0) { + device->battery = 1; + } else if (device->battery > 100) { + device->battery = 100; + } } } - } - else + } else { CancelIo(hHidFile); + } } } } diff --git a/src/detection/gpu/adl.h b/src/detection/gpu/adl.h index ddf948ec6..346eece87 100644 --- a/src/detection/gpu/adl.h +++ b/src/detection/gpu/adl.h @@ -26,11 +26,9 @@ extern int ADL2_Adapter_DedicatedVRAMUsage_Get(ADL_CONTEXT_HANDLE context, int i // Function to get the ASICFamilyType from the adapter. extern int ADL2_Adapter_ASICFamilyType_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, int* lpAsicTypes, int* lpValids); - // Function to retrieve current power management capabilities. extern int ADL2_Overdrive_Caps(ADL_CONTEXT_HANDLE context, int iAdapterIndex, int* iSupported, int* iEnabled, int* iVersion); - /////////// Overdrive 6 functions // Function to retrieve current Overdrive and performance-related activity. @@ -42,7 +40,6 @@ extern int ADL2_Overdrive6_Temperature_Get(ADL_CONTEXT_HANDLE context, int iAdap // Function to retrieve the current or default Overdrive clock ranges. extern int ADL2_Overdrive6_StateInfo_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, int iStateType, ADLOD6StateInfo* lpStateInfo); - /// Overdrive N functions // Despite the name (N means Next), this is actually Overdrive7 API @@ -52,19 +49,18 @@ extern int ADL2_Overdrive6_StateInfo_Get(ADL_CONTEXT_HANDLE context, int iAdapte extern int ADL2_OverdriveN_CapabilitiesX2_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLODNCapabilitiesX2* lpODCapabilities); // Function to retrieve the current OD performance status. -extern int ADL2_OverdriveN_PerformanceStatus_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLODNPerformanceStatus *lpODPerformanceStatus); +extern int ADL2_OverdriveN_PerformanceStatus_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLODNPerformanceStatus* lpODPerformanceStatus); // Function to retrieve the current temperature. -extern int ADL2_OverdriveN_Temperature_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, int iTemperatureType, int *iTemperature); +extern int ADL2_OverdriveN_Temperature_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, int iTemperatureType, int* iTemperature); // Function to retrieve the current GPU clocks settings. -extern int ADL2_OverdriveN_SystemClocksX2_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLODNPerformanceLevelsX2 *lpODPerformanceLevels); - +extern int ADL2_OverdriveN_SystemClocksX2_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLODNPerformanceLevelsX2* lpODPerformanceLevels); /// Overdrive 8 functions // Function to retrieve the Overdrive8 current settings. -extern int ADL2_Overdrive8_Current_Setting_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLOD8CurrentSetting *lpCurrentSetting); +extern int ADL2_Overdrive8_Current_Setting_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLOD8CurrentSetting* lpCurrentSetting); // Function to retrieve the Overdrive8 current settings. -extern int ADL2_New_QueryPMLogData_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLPMLogDataOutput *lpDataOutput); +extern int ADL2_New_QueryPMLogData_Get(ADL_CONTEXT_HANDLE context, int iAdapterIndex, ADLPMLogDataOutput* lpDataOutput); diff --git a/src/detection/gpu/asahi_drm.h b/src/detection/gpu/asahi_drm.h index 01a5ed2a3..69b537b75 100644 --- a/src/detection/gpu/asahi_drm.h +++ b/src/detection/gpu/asahi_drm.h @@ -58,44 +58,44 @@ extern "C" { * definitions instead. */ enum drm_asahi_ioctl_id { - /** @DRM_ASAHI_GET_PARAMS: Query device properties. */ - DRM_ASAHI_GET_PARAMS = 0, + /** @DRM_ASAHI_GET_PARAMS: Query device properties. */ + DRM_ASAHI_GET_PARAMS = 0, - /** @DRM_ASAHI_GET_TIME: Query device time. */ - DRM_ASAHI_GET_TIME, + /** @DRM_ASAHI_GET_TIME: Query device time. */ + DRM_ASAHI_GET_TIME, - /** @DRM_ASAHI_VM_CREATE: Create a GPU VM address space. */ - DRM_ASAHI_VM_CREATE, + /** @DRM_ASAHI_VM_CREATE: Create a GPU VM address space. */ + DRM_ASAHI_VM_CREATE, - /** @DRM_ASAHI_VM_DESTROY: Destroy a VM. */ - DRM_ASAHI_VM_DESTROY, + /** @DRM_ASAHI_VM_DESTROY: Destroy a VM. */ + DRM_ASAHI_VM_DESTROY, - /** @DRM_ASAHI_VM_BIND: Bind/unbind memory to a VM. */ - DRM_ASAHI_VM_BIND, + /** @DRM_ASAHI_VM_BIND: Bind/unbind memory to a VM. */ + DRM_ASAHI_VM_BIND, - /** @DRM_ASAHI_GEM_CREATE: Create a buffer object. */ - DRM_ASAHI_GEM_CREATE, + /** @DRM_ASAHI_GEM_CREATE: Create a buffer object. */ + DRM_ASAHI_GEM_CREATE, - /** - * @DRM_ASAHI_GEM_MMAP_OFFSET: Get offset to pass to mmap() to map a - * given GEM handle. - */ - DRM_ASAHI_GEM_MMAP_OFFSET, + /** + * @DRM_ASAHI_GEM_MMAP_OFFSET: Get offset to pass to mmap() to map a + * given GEM handle. + */ + DRM_ASAHI_GEM_MMAP_OFFSET, - /** @DRM_ASAHI_GEM_BIND_OBJECT: Bind memory as a special object */ - DRM_ASAHI_GEM_BIND_OBJECT, + /** @DRM_ASAHI_GEM_BIND_OBJECT: Bind memory as a special object */ + DRM_ASAHI_GEM_BIND_OBJECT, - /** @DRM_ASAHI_QUEUE_CREATE: Create a scheduling queue. */ - DRM_ASAHI_QUEUE_CREATE, + /** @DRM_ASAHI_QUEUE_CREATE: Create a scheduling queue. */ + DRM_ASAHI_QUEUE_CREATE, - /** @DRM_ASAHI_QUEUE_DESTROY: Destroy a scheduling queue. */ - DRM_ASAHI_QUEUE_DESTROY, + /** @DRM_ASAHI_QUEUE_DESTROY: Destroy a scheduling queue. */ + DRM_ASAHI_QUEUE_DESTROY, - /** @DRM_ASAHI_SUBMIT: Submit commands to a queue. */ - DRM_ASAHI_SUBMIT, + /** @DRM_ASAHI_SUBMIT: Submit commands to a queue. */ + DRM_ASAHI_SUBMIT, }; -#define DRM_ASAHI_MAX_CLUSTERS 64 +#define DRM_ASAHI_MAX_CLUSTERS 64 /** * struct drm_asahi_params_global - Global parameters. @@ -103,94 +103,94 @@ enum drm_asahi_ioctl_id { * This struct may be queried by drm_asahi_get_params. */ struct drm_asahi_params_global { - /** @features: Feature bits from drm_asahi_feature */ - __u64 features; + /** @features: Feature bits from drm_asahi_feature */ + __u64 features; - /** @gpu_generation: GPU generation, e.g. 13 for G13G */ - __u32 gpu_generation; + /** @gpu_generation: GPU generation, e.g. 13 for G13G */ + __u32 gpu_generation; - /** @gpu_variant: GPU variant as a character, e.g. 'C' for G13C */ - __u32 gpu_variant; + /** @gpu_variant: GPU variant as a character, e.g. 'C' for G13C */ + __u32 gpu_variant; - /** - * @gpu_revision: GPU revision in BCD, e.g. 0x00 for 'A0' or - * 0x21 for 'C1' - */ - __u32 gpu_revision; + /** + * @gpu_revision: GPU revision in BCD, e.g. 0x00 for 'A0' or + * 0x21 for 'C1' + */ + __u32 gpu_revision; - /** @chip_id: Chip ID in BCD, e.g. 0x8103 for T8103 */ - __u32 chip_id; + /** @chip_id: Chip ID in BCD, e.g. 0x8103 for T8103 */ + __u32 chip_id; - /** @num_dies: Number of dies in the SoC */ - __u32 num_dies; + /** @num_dies: Number of dies in the SoC */ + __u32 num_dies; - /** @num_clusters_total: Number of GPU clusters (across all dies) */ - __u32 num_clusters_total; + /** @num_clusters_total: Number of GPU clusters (across all dies) */ + __u32 num_clusters_total; - /** - * @num_cores_per_cluster: Number of logical cores per cluster - * (including inactive/nonexistent) - */ - __u32 num_cores_per_cluster; + /** + * @num_cores_per_cluster: Number of logical cores per cluster + * (including inactive/nonexistent) + */ + __u32 num_cores_per_cluster; - /** @max_frequency_khz: Maximum GPU core clock frequency */ - __u32 max_frequency_khz; + /** @max_frequency_khz: Maximum GPU core clock frequency */ + __u32 max_frequency_khz; - /** @core_masks: Bitmask of present/enabled cores per cluster */ - __u64 core_masks[DRM_ASAHI_MAX_CLUSTERS]; + /** @core_masks: Bitmask of present/enabled cores per cluster */ + __u64 core_masks[DRM_ASAHI_MAX_CLUSTERS]; - /** - * @vm_start: VM range start VMA. Together with @vm_end, this defines - * the window of valid GPU VAs. Userspace is expected to subdivide VAs - * out of this window. - * - * This window contains all virtual addresses that userspace needs to - * know about. There may be kernel-internal GPU VAs outside this range, - * but that detail is not relevant here. - */ - __u64 vm_start; + /** + * @vm_start: VM range start VMA. Together with @vm_end, this defines + * the window of valid GPU VAs. Userspace is expected to subdivide VAs + * out of this window. + * + * This window contains all virtual addresses that userspace needs to + * know about. There may be kernel-internal GPU VAs outside this range, + * but that detail is not relevant here. + */ + __u64 vm_start; - /** @vm_end: VM range end VMA */ - __u64 vm_end; + /** @vm_end: VM range end VMA */ + __u64 vm_end; - /** - * @vm_kernel_min_size: Minimum kernel VMA window size. - * - * When creating a VM, userspace is required to carve out a section of - * virtual addresses (within the range given by @vm_start and - * @vm_end). The kernel will allocate various internal structures - * within the specified VA range. - * - * Allowing userspace to choose the VA range for the kernel, rather than - * the kernel reserving VAs and requiring userspace to cope, can assist - * in implementing SVM. - */ - __u64 vm_kernel_min_size; + /** + * @vm_kernel_min_size: Minimum kernel VMA window size. + * + * When creating a VM, userspace is required to carve out a section of + * virtual addresses (within the range given by @vm_start and + * @vm_end). The kernel will allocate various internal structures + * within the specified VA range. + * + * Allowing userspace to choose the VA range for the kernel, rather than + * the kernel reserving VAs and requiring userspace to cope, can assist + * in implementing SVM. + */ + __u64 vm_kernel_min_size; - /** - * @max_commands_per_submission: Maximum number of supported commands - * per submission. This mirrors firmware limits. Userspace must split up - * larger command buffers, which may require inserting additional - * synchronization. - */ - __u32 max_commands_per_submission; + /** + * @max_commands_per_submission: Maximum number of supported commands + * per submission. This mirrors firmware limits. Userspace must split up + * larger command buffers, which may require inserting additional + * synchronization. + */ + __u32 max_commands_per_submission; - /** - * @max_attachments: Maximum number of drm_asahi_attachment's per - * command - */ - __u32 max_attachments; + /** + * @max_attachments: Maximum number of drm_asahi_attachment's per + * command + */ + __u32 max_attachments; - /** - * @command_timestamp_frequency_hz: Timebase frequency for timestamps - * written during command exeuction, specified via drm_asahi_timestamp - * structures. As this rate is controlled by the firmware, it is a - * queryable parameter. - * - * Userspace must divide by this frequency to convert timestamps to - * seconds, rather than hardcoding a particular firmware's rate. - */ - __u64 command_timestamp_frequency_hz; + /** + * @command_timestamp_frequency_hz: Timebase frequency for timestamps + * written during command exeuction, specified via drm_asahi_timestamp + * structures. As this rate is controlled by the firmware, it is a + * queryable parameter. + * + * Userspace must divide by this frequency to convert timestamps to + * seconds, rather than hardcoding a particular firmware's rate. + */ + __u64 command_timestamp_frequency_hz; }; /** @@ -200,123 +200,123 @@ struct drm_asahi_params_global { * version. Most features don't need to be here. */ enum drm_asahi_feature { - /** - * @DRM_ASAHI_FEATURE_SOFT_FAULTS: GPU has "soft fault" enabled. Shader - * loads of unmapped memory will return zero. Shader stores to unmapped - * memory will be silently discarded. Note that only shader load/store - * is affected. Other hardware units are not affected, notably including - * texture sampling. - * - * Soft fault is set when initializing the GPU and cannot be runtime - * toggled. Therefore, it is exposed as a feature bit and not a - * userspace-settable flag on the VM. When soft fault is enabled, - * userspace can speculate memory accesses more aggressively. - */ - DRM_ASAHI_FEATURE_SOFT_FAULTS = (1UL) << 0, + /** + * @DRM_ASAHI_FEATURE_SOFT_FAULTS: GPU has "soft fault" enabled. Shader + * loads of unmapped memory will return zero. Shader stores to unmapped + * memory will be silently discarded. Note that only shader load/store + * is affected. Other hardware units are not affected, notably including + * texture sampling. + * + * Soft fault is set when initializing the GPU and cannot be runtime + * toggled. Therefore, it is exposed as a feature bit and not a + * userspace-settable flag on the VM. When soft fault is enabled, + * userspace can speculate memory accesses more aggressively. + */ + DRM_ASAHI_FEATURE_SOFT_FAULTS = (1UL) << 0, }; /** * struct drm_asahi_get_params - Arguments passed to DRM_IOCTL_ASAHI_GET_PARAMS */ struct drm_asahi_get_params { - /** @param_group: Parameter group to fetch (MBZ) */ - __u32 param_group; + /** @param_group: Parameter group to fetch (MBZ) */ + __u32 param_group; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; - /** @pointer: User pointer to write parameter struct */ - __u64 pointer; + /** @pointer: User pointer to write parameter struct */ + __u64 pointer; - /** - * @size: Size of the user buffer. In case of older userspace, this may - * be less than sizeof(struct drm_asahi_params_global). The kernel will - * not write past the length specified here, allowing extensibility. - */ - __u64 size; + /** + * @size: Size of the user buffer. In case of older userspace, this may + * be less than sizeof(struct drm_asahi_params_global). The kernel will + * not write past the length specified here, allowing extensibility. + */ + __u64 size; }; /** * struct drm_asahi_vm_create - Arguments passed to DRM_IOCTL_ASAHI_VM_CREATE */ struct drm_asahi_vm_create { - /** - * @kernel_start: Start of the kernel-reserved address range. See - * drm_asahi_params_global::vm_kernel_min_size. - * - * Both @kernel_start and @kernel_end must be within the range of - * valid VAs given by drm_asahi_params_global::vm_start and - * drm_asahi_params_global::vm_end. The size of the kernel range - * (@kernel_end - @kernel_start) must be at least - * drm_asahi_params_global::vm_kernel_min_size. - * - * Userspace must not bind any memory on this VM into this reserved - * range, it is for kernel use only. - */ - __u64 kernel_start; + /** + * @kernel_start: Start of the kernel-reserved address range. See + * drm_asahi_params_global::vm_kernel_min_size. + * + * Both @kernel_start and @kernel_end must be within the range of + * valid VAs given by drm_asahi_params_global::vm_start and + * drm_asahi_params_global::vm_end. The size of the kernel range + * (@kernel_end - @kernel_start) must be at least + * drm_asahi_params_global::vm_kernel_min_size. + * + * Userspace must not bind any memory on this VM into this reserved + * range, it is for kernel use only. + */ + __u64 kernel_start; - /** - * @kernel_end: End of the kernel-reserved address range. See - * @kernel_start. - */ - __u64 kernel_end; + /** + * @kernel_end: End of the kernel-reserved address range. See + * @kernel_start. + */ + __u64 kernel_end; - /** @vm_id: Returned VM ID */ - __u32 vm_id; + /** @vm_id: Returned VM ID */ + __u32 vm_id; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; }; /** * struct drm_asahi_vm_destroy - Arguments passed to DRM_IOCTL_ASAHI_VM_DESTROY */ struct drm_asahi_vm_destroy { - /** @vm_id: VM ID to be destroyed */ - __u32 vm_id; + /** @vm_id: VM ID to be destroyed */ + __u32 vm_id; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; }; /** * enum drm_asahi_gem_flags - Flags for GEM creation */ enum drm_asahi_gem_flags { - /** - * @DRM_ASAHI_GEM_WRITEBACK: BO should be CPU-mapped as writeback. - * - * Map as writeback instead of write-combine. This optimizes for CPU - * reads. - */ - DRM_ASAHI_GEM_WRITEBACK = (1L << 0), + /** + * @DRM_ASAHI_GEM_WRITEBACK: BO should be CPU-mapped as writeback. + * + * Map as writeback instead of write-combine. This optimizes for CPU + * reads. + */ + DRM_ASAHI_GEM_WRITEBACK = (1L << 0), - /** - * @DRM_ASAHI_GEM_VM_PRIVATE: BO is private to this GPU VM (no exports). - */ - DRM_ASAHI_GEM_VM_PRIVATE = (1L << 1), + /** + * @DRM_ASAHI_GEM_VM_PRIVATE: BO is private to this GPU VM (no exports). + */ + DRM_ASAHI_GEM_VM_PRIVATE = (1L << 1), }; /** * struct drm_asahi_gem_create - Arguments passed to DRM_IOCTL_ASAHI_GEM_CREATE */ struct drm_asahi_gem_create { - /** @size: Size of the BO */ - __u64 size; + /** @size: Size of the BO */ + __u64 size; - /** @flags: Combination of drm_asahi_gem_flags flags. */ - __u32 flags; + /** @flags: Combination of drm_asahi_gem_flags flags. */ + __u32 flags; - /** - * @vm_id: VM ID to assign to the BO, if DRM_ASAHI_GEM_VM_PRIVATE is set - */ - __u32 vm_id; + /** + * @vm_id: VM ID to assign to the BO, if DRM_ASAHI_GEM_VM_PRIVATE is set + */ + __u32 vm_id; - /** @handle: Returned GEM handle for the BO */ - __u32 handle; + /** @handle: Returned GEM handle for the BO */ + __u32 handle; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; }; /** @@ -324,78 +324,78 @@ struct drm_asahi_gem_create { * DRM_IOCTL_ASAHI_GEM_MMAP_OFFSET */ struct drm_asahi_gem_mmap_offset { - /** @handle: Handle for the object being mapped. */ - __u32 handle; + /** @handle: Handle for the object being mapped. */ + __u32 handle; - /** @flags: Must be zero */ - __u32 flags; + /** @flags: Must be zero */ + __u32 flags; - /** @offset: The fake offset to use for subsequent mmap call */ - __u64 offset; + /** @offset: The fake offset to use for subsequent mmap call */ + __u64 offset; }; /** * enum drm_asahi_bind_flags - Flags for GEM binding */ enum drm_asahi_bind_flags { - /** - * @DRM_ASAHI_BIND_UNBIND: Instead of binding a GEM object to the range, - * simply unbind the GPU VMA range. - */ - DRM_ASAHI_BIND_UNBIND = (1L << 0), + /** + * @DRM_ASAHI_BIND_UNBIND: Instead of binding a GEM object to the range, + * simply unbind the GPU VMA range. + */ + DRM_ASAHI_BIND_UNBIND = (1L << 0), - /** @DRM_ASAHI_BIND_READ: Map BO with GPU read permission */ - DRM_ASAHI_BIND_READ = (1L << 1), + /** @DRM_ASAHI_BIND_READ: Map BO with GPU read permission */ + DRM_ASAHI_BIND_READ = (1L << 1), - /** @DRM_ASAHI_BIND_WRITE: Map BO with GPU write permission */ - DRM_ASAHI_BIND_WRITE = (1L << 2), + /** @DRM_ASAHI_BIND_WRITE: Map BO with GPU write permission */ + DRM_ASAHI_BIND_WRITE = (1L << 2), - /** - * @DRM_ASAHI_BIND_SINGLE_PAGE: Map a single page of the BO repeatedly - * across the VA range. - * - * This is useful to fill a VA range with scratch pages or zero pages. - * It is intended as a mechanism to accelerate sparse. - */ - DRM_ASAHI_BIND_SINGLE_PAGE = (1L << 3), + /** + * @DRM_ASAHI_BIND_SINGLE_PAGE: Map a single page of the BO repeatedly + * across the VA range. + * + * This is useful to fill a VA range with scratch pages or zero pages. + * It is intended as a mechanism to accelerate sparse. + */ + DRM_ASAHI_BIND_SINGLE_PAGE = (1L << 3), }; /** * struct drm_asahi_gem_bind_op - Description of a single GEM bind operation. */ struct drm_asahi_gem_bind_op { - /** @flags: Combination of drm_asahi_bind_flags flags. */ - __u32 flags; + /** @flags: Combination of drm_asahi_bind_flags flags. */ + __u32 flags; - /** @handle: GEM object to bind (except for UNBIND) */ - __u32 handle; + /** @handle: GEM object to bind (except for UNBIND) */ + __u32 handle; - /** - * @offset: Offset into the object (except for UNBIND). - * - * For a regular bind, this is the beginning of the region of the GEM - * object to bind. - * - * For a single-page bind, this is the offset to the single page that - * will be repeatedly bound. - * - * Must be page-size aligned. - */ - __u64 offset; + /** + * @offset: Offset into the object (except for UNBIND). + * + * For a regular bind, this is the beginning of the region of the GEM + * object to bind. + * + * For a single-page bind, this is the offset to the single page that + * will be repeatedly bound. + * + * Must be page-size aligned. + */ + __u64 offset; - /** - * @range: Number of bytes to bind/unbind to @addr. - * - * Must be page-size aligned. - */ - __u64 range; + /** + * @range: Number of bytes to bind/unbind to @addr. + * + * Must be page-size aligned. + */ + __u64 range; - /** - * @addr: Address to bind to. - * - * Must be page-size aligned. - */ - __u64 addr; + /** + * @addr: Address to bind to. + * + * Must be page-size aligned. + */ + __u64 addr; }; /** @@ -403,48 +403,48 @@ struct drm_asahi_gem_bind_op { * DRM_IOCTL_ASAHI_VM_BIND */ struct drm_asahi_vm_bind { - /** @vm_id: The ID of the VM to bind to */ - __u32 vm_id; + /** @vm_id: The ID of the VM to bind to */ + __u32 vm_id; - /** @num_binds: number of binds in this IOCTL. */ - __u32 num_binds; + /** @num_binds: number of binds in this IOCTL. */ + __u32 num_binds; - /** - * @stride: Stride in bytes between consecutive binds. This allows - * extensibility of drm_asahi_gem_bind_op. - */ - __u32 stride; + /** + * @stride: Stride in bytes between consecutive binds. This allows + * extensibility of drm_asahi_gem_bind_op. + */ + __u32 stride; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; - /** - * @userptr: User pointer to an array of @num_binds structures of type - * @drm_asahi_gem_bind_op and size @stride bytes. - */ - __u64 userptr; + /** + * @userptr: User pointer to an array of @num_binds structures of type + * @drm_asahi_gem_bind_op and size @stride bytes. + */ + __u64 userptr; }; /** * enum drm_asahi_bind_object_op - Special object bind operation */ enum drm_asahi_bind_object_op { - /** @DRM_ASAHI_BIND_OBJECT_OP_BIND: Bind a BO as a special GPU object */ - DRM_ASAHI_BIND_OBJECT_OP_BIND = 0, + /** @DRM_ASAHI_BIND_OBJECT_OP_BIND: Bind a BO as a special GPU object */ + DRM_ASAHI_BIND_OBJECT_OP_BIND = 0, - /** @DRM_ASAHI_BIND_OBJECT_OP_UNBIND: Unbind a special GPU object */ - DRM_ASAHI_BIND_OBJECT_OP_UNBIND = 1, + /** @DRM_ASAHI_BIND_OBJECT_OP_UNBIND: Unbind a special GPU object */ + DRM_ASAHI_BIND_OBJECT_OP_UNBIND = 1, }; /** * enum drm_asahi_bind_object_flags - Special object bind flags */ enum drm_asahi_bind_object_flags { - /** - * @DRM_ASAHI_BIND_OBJECT_USAGE_TIMESTAMPS: Map a BO as a timestamp - * buffer. - */ - DRM_ASAHI_BIND_OBJECT_USAGE_TIMESTAMPS = (1L << 0), + /** + * @DRM_ASAHI_BIND_OBJECT_USAGE_TIMESTAMPS: Map a BO as a timestamp + * buffer. + */ + DRM_ASAHI_BIND_OBJECT_USAGE_TIMESTAMPS = (1L << 0), }; /** @@ -452,73 +452,73 @@ enum drm_asahi_bind_object_flags { * DRM_IOCTL_ASAHI_GEM_BIND_OBJECT */ struct drm_asahi_gem_bind_object { - /** @op: Bind operation (enum drm_asahi_bind_object_op) */ - __u32 op; + /** @op: Bind operation (enum drm_asahi_bind_object_op) */ + __u32 op; - /** @flags: Combination of drm_asahi_bind_object_flags flags. */ - __u32 flags; + /** @flags: Combination of drm_asahi_bind_object_flags flags. */ + __u32 flags; - /** @handle: GEM object to bind/unbind (BIND) */ - __u32 handle; + /** @handle: GEM object to bind/unbind (BIND) */ + __u32 handle; - /** @vm_id: The ID of the VM to operate on (MBZ currently) */ - __u32 vm_id; + /** @vm_id: The ID of the VM to operate on (MBZ currently) */ + __u32 vm_id; - /** @offset: Offset into the object (BIND only) */ - __u64 offset; + /** @offset: Offset into the object (BIND only) */ + __u64 offset; - /** @range: Number of bytes to bind/unbind (BIND only) */ - __u64 range; + /** @range: Number of bytes to bind/unbind (BIND only) */ + __u64 range; - /** @object_handle: Object handle (out for BIND, in for UNBIND) */ - __u32 object_handle; + /** @object_handle: Object handle (out for BIND, in for UNBIND) */ + __u32 object_handle; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; }; /** * enum drm_asahi_cmd_type - Command type */ enum drm_asahi_cmd_type { - /** - * @DRM_ASAHI_CMD_RENDER: Render command, executing on the render - * subqueue. Combined vertex and fragment operation. - * - * Followed by a @drm_asahi_cmd_render payload. - */ - DRM_ASAHI_CMD_RENDER = 0, + /** + * @DRM_ASAHI_CMD_RENDER: Render command, executing on the render + * subqueue. Combined vertex and fragment operation. + * + * Followed by a @drm_asahi_cmd_render payload. + */ + DRM_ASAHI_CMD_RENDER = 0, - /** - * @DRM_ASAHI_CMD_COMPUTE: Compute command on the compute subqueue. - * - * Followed by a @drm_asahi_cmd_compute payload. - */ - DRM_ASAHI_CMD_COMPUTE = 1, + /** + * @DRM_ASAHI_CMD_COMPUTE: Compute command on the compute subqueue. + * + * Followed by a @drm_asahi_cmd_compute payload. + */ + DRM_ASAHI_CMD_COMPUTE = 1, - /** - * @DRM_ASAHI_SET_VERTEX_ATTACHMENTS: Software command to set - * attachments for subsequent vertex shaders in the same submit. - * - * Followed by (possibly multiple) @drm_asahi_attachment payloads. - */ - DRM_ASAHI_SET_VERTEX_ATTACHMENTS = 2, + /** + * @DRM_ASAHI_SET_VERTEX_ATTACHMENTS: Software command to set + * attachments for subsequent vertex shaders in the same submit. + * + * Followed by (possibly multiple) @drm_asahi_attachment payloads. + */ + DRM_ASAHI_SET_VERTEX_ATTACHMENTS = 2, - /** - * @DRM_ASAHI_SET_FRAGMENT_ATTACHMENTS: Software command to set - * attachments for subsequent fragment shaders in the same submit. - * - * Followed by (possibly multiple) @drm_asahi_attachment payloads. - */ - DRM_ASAHI_SET_FRAGMENT_ATTACHMENTS = 3, + /** + * @DRM_ASAHI_SET_FRAGMENT_ATTACHMENTS: Software command to set + * attachments for subsequent fragment shaders in the same submit. + * + * Followed by (possibly multiple) @drm_asahi_attachment payloads. + */ + DRM_ASAHI_SET_FRAGMENT_ATTACHMENTS = 3, - /** - * @DRM_ASAHI_SET_COMPUTE_ATTACHMENTS: Software command to set - * attachments for subsequent compute shaders in the same submit. - * - * Followed by (possibly multiple) @drm_asahi_attachment payloads. - */ - DRM_ASAHI_SET_COMPUTE_ATTACHMENTS = 4, + /** + * @DRM_ASAHI_SET_COMPUTE_ATTACHMENTS: Software command to set + * attachments for subsequent compute shaders in the same submit. + * + * Followed by (possibly multiple) @drm_asahi_attachment payloads. + */ + DRM_ASAHI_SET_COMPUTE_ATTACHMENTS = 4, }; /** @@ -529,25 +529,25 @@ enum drm_asahi_cmd_type { * these enums allow userspace to communicate the intentions. */ enum drm_asahi_priority { - /** @DRM_ASAHI_PRIORITY_LOW: Low priority queue. */ - DRM_ASAHI_PRIORITY_LOW = 0, + /** @DRM_ASAHI_PRIORITY_LOW: Low priority queue. */ + DRM_ASAHI_PRIORITY_LOW = 0, - /** @DRM_ASAHI_PRIORITY_MEDIUM: Medium priority queue. */ - DRM_ASAHI_PRIORITY_MEDIUM = 1, + /** @DRM_ASAHI_PRIORITY_MEDIUM: Medium priority queue. */ + DRM_ASAHI_PRIORITY_MEDIUM = 1, - /** - * @DRM_ASAHI_PRIORITY_HIGH: High priority queue. - * - * Reserved for future extension. - */ - DRM_ASAHI_PRIORITY_HIGH = 2, + /** + * @DRM_ASAHI_PRIORITY_HIGH: High priority queue. + * + * Reserved for future extension. + */ + DRM_ASAHI_PRIORITY_HIGH = 2, - /** - * @DRM_ASAHI_PRIORITY_REALTIME: Real-time priority queue. - * - * Reserved for future extension. - */ - DRM_ASAHI_PRIORITY_REALTIME = 3, + /** + * @DRM_ASAHI_PRIORITY_REALTIME: Real-time priority queue. + * + * Reserved for future extension. + */ + DRM_ASAHI_PRIORITY_REALTIME = 3, }; /** @@ -555,33 +555,33 @@ enum drm_asahi_priority { * DRM_IOCTL_ASAHI_QUEUE_CREATE */ struct drm_asahi_queue_create { - /** @flags: MBZ */ - __u32 flags; + /** @flags: MBZ */ + __u32 flags; - /** @vm_id: The ID of the VM this queue is bound to */ - __u32 vm_id; + /** @vm_id: The ID of the VM this queue is bound to */ + __u32 vm_id; - /** @priority: One of drm_asahi_priority */ - __u32 priority; + /** @priority: One of drm_asahi_priority */ + __u32 priority; - /** @queue_id: The returned queue ID */ - __u32 queue_id; + /** @queue_id: The returned queue ID */ + __u32 queue_id; - /** - * @usc_exec_base: GPU base address for all USC binaries (shaders) on - * this queue. USC addresses are 32-bit relative to this 64-bit base. - * - * This sets the following registers on all queue commands: - * - * USC_EXEC_BASE_TA (vertex) - * USC_EXEC_BASE_ISP (fragment) - * USC_EXEC_BASE_CP (compute) - * - * While the hardware lets us configure these independently per command, - * we do not have a use case for this. Instead, we expect userspace to - * fix a 4GiB VA carveout for USC memory and pass its base address here. - */ - __u64 usc_exec_base; + /** + * @usc_exec_base: GPU base address for all USC binaries (shaders) on + * this queue. USC addresses are 32-bit relative to this 64-bit base. + * + * This sets the following registers on all queue commands: + * + * USC_EXEC_BASE_TA (vertex) + * USC_EXEC_BASE_ISP (fragment) + * USC_EXEC_BASE_CP (compute) + * + * While the hardware lets us configure these independently per command, + * we do not have a use case for this. Instead, we expect userspace to + * fix a 4GiB VA carveout for USC memory and pass its base address here. + */ + __u64 usc_exec_base; }; /** @@ -589,36 +589,36 @@ struct drm_asahi_queue_create { * DRM_IOCTL_ASAHI_QUEUE_DESTROY */ struct drm_asahi_queue_destroy { - /** @queue_id: The queue ID to be destroyed */ - __u32 queue_id; + /** @queue_id: The queue ID to be destroyed */ + __u32 queue_id; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; }; /** * enum drm_asahi_sync_type - Sync item type */ enum drm_asahi_sync_type { - /** @DRM_ASAHI_SYNC_SYNCOBJ: Binary sync object */ - DRM_ASAHI_SYNC_SYNCOBJ = 0, + /** @DRM_ASAHI_SYNC_SYNCOBJ: Binary sync object */ + DRM_ASAHI_SYNC_SYNCOBJ = 0, - /** @DRM_ASAHI_SYNC_TIMELINE_SYNCOBJ: Timeline sync object */ - DRM_ASAHI_SYNC_TIMELINE_SYNCOBJ = 1, + /** @DRM_ASAHI_SYNC_TIMELINE_SYNCOBJ: Timeline sync object */ + DRM_ASAHI_SYNC_TIMELINE_SYNCOBJ = 1, }; /** * struct drm_asahi_sync - Sync item */ struct drm_asahi_sync { - /** @sync_type: One of drm_asahi_sync_type */ - __u32 sync_type; + /** @sync_type: One of drm_asahi_sync_type */ + __u32 sync_type; - /** @handle: The sync object handle */ - __u32 handle; + /** @handle: The sync object handle */ + __u32 handle; - /** @timeline_value: Timeline value for timeline sync objects */ - __u64 timeline_value; + /** @timeline_value: Timeline value for timeline sync objects */ + __u64 timeline_value; }; /** @@ -637,108 +637,108 @@ struct drm_asahi_sync { * extensible. */ struct drm_asahi_cmd_header { - /** @cmd_type: One of drm_asahi_cmd_type */ - __u16 cmd_type; + /** @cmd_type: One of drm_asahi_cmd_type */ + __u16 cmd_type; - /** - * @size: Size of this command, not including this header. - * - * For hardware commands, this enables extensibility of commands without - * requiring extra command types. Passing a command that is shorter - * than expected is explicitly allowed for backwards-compatibility. - * Truncated fields will be zeroed. - * - * For the synthetic attachment setting commands, this implicitly - * encodes the number of attachments. These commands take multiple - * fixed-size @drm_asahi_attachment structures as their payload, so size - * equals number of attachments * sizeof(struct drm_asahi_attachment). - */ - __u16 size; + /** + * @size: Size of this command, not including this header. + * + * For hardware commands, this enables extensibility of commands without + * requiring extra command types. Passing a command that is shorter + * than expected is explicitly allowed for backwards-compatibility. + * Truncated fields will be zeroed. + * + * For the synthetic attachment setting commands, this implicitly + * encodes the number of attachments. These commands take multiple + * fixed-size @drm_asahi_attachment structures as their payload, so size + * equals number of attachments * sizeof(struct drm_asahi_attachment). + */ + __u16 size; - /** - * @vdm_barrier: VDM (render) command index to wait on. - * - * Barriers are indices relative to the beginning of a given submit. A - * barrier of 0 waits on commands submitted to the respective subqueue - * in previous submit ioctls. A barrier of N waits on N previous - * commands on the subqueue within the current submit ioctl. As a - * special case, passing @DRM_ASAHI_BARRIER_NONE avoids waiting on any - * commands in the subqueue. - * - * Examples: - * - * 0: This waits on all previous work. - * - * NONE: This does not wait for anything on this subqueue. - * - * 1: This waits on the first render command in the submit. - * This is valid only if there are multiple render commands in the - * same submit. - * - * Barriers are valid only for hardware commands. Synthetic software - * commands to set attachments must pass NONE here. - */ - __u16 vdm_barrier; + /** + * @vdm_barrier: VDM (render) command index to wait on. + * + * Barriers are indices relative to the beginning of a given submit. A + * barrier of 0 waits on commands submitted to the respective subqueue + * in previous submit ioctls. A barrier of N waits on N previous + * commands on the subqueue within the current submit ioctl. As a + * special case, passing @DRM_ASAHI_BARRIER_NONE avoids waiting on any + * commands in the subqueue. + * + * Examples: + * + * 0: This waits on all previous work. + * + * NONE: This does not wait for anything on this subqueue. + * + * 1: This waits on the first render command in the submit. + * This is valid only if there are multiple render commands in the + * same submit. + * + * Barriers are valid only for hardware commands. Synthetic software + * commands to set attachments must pass NONE here. + */ + __u16 vdm_barrier; - /** - * @cdm_barrier: CDM (compute) command index to wait on. - * - * See @vdm_barrier, and replace VDM/render with CDM/compute. - */ - __u16 cdm_barrier; + /** + * @cdm_barrier: CDM (compute) command index to wait on. + * + * See @vdm_barrier, and replace VDM/render with CDM/compute. + */ + __u16 cdm_barrier; }; /** * struct drm_asahi_submit - Arguments passed to DRM_IOCTL_ASAHI_SUBMIT */ struct drm_asahi_submit { - /** - * @syncs: An optional pointer to an array of drm_asahi_sync. The first - * @in_sync_count elements are in-syncs, then the remaining - * @out_sync_count elements are out-syncs. Using a single array with - * explicit partitioning simplifies handling. - */ - __u64 syncs; + /** + * @syncs: An optional pointer to an array of drm_asahi_sync. The first + * @in_sync_count elements are in-syncs, then the remaining + * @out_sync_count elements are out-syncs. Using a single array with + * explicit partitioning simplifies handling. + */ + __u64 syncs; - /** - * @cmdbuf: Pointer to the command buffer to submit. - * - * This is a flat command buffer. By design, it contains no CPU - * pointers, which makes it suitable for a virtgpu wire protocol without - * requiring any serializing/deserializing step. - * - * It consists of a series of commands. Each command begins with a - * fixed-size @drm_asahi_cmd_header header and is followed by a - * variable-length payload according to the type and size in the header. - * - * The combined count of "real" hardware commands must be nonzero and at - * most drm_asahi_params_global::max_commands_per_submission. - */ - __u64 cmdbuf; + /** + * @cmdbuf: Pointer to the command buffer to submit. + * + * This is a flat command buffer. By design, it contains no CPU + * pointers, which makes it suitable for a virtgpu wire protocol without + * requiring any serializing/deserializing step. + * + * It consists of a series of commands. Each command begins with a + * fixed-size @drm_asahi_cmd_header header and is followed by a + * variable-length payload according to the type and size in the header. + * + * The combined count of "real" hardware commands must be nonzero and at + * most drm_asahi_params_global::max_commands_per_submission. + */ + __u64 cmdbuf; - /** @flags: Flags for command submission (MBZ) */ - __u32 flags; + /** @flags: Flags for command submission (MBZ) */ + __u32 flags; - /** @queue_id: The queue ID to be submitted to */ - __u32 queue_id; + /** @queue_id: The queue ID to be submitted to */ + __u32 queue_id; - /** - * @in_sync_count: Number of sync objects to wait on before starting - * this job. - */ - __u32 in_sync_count; + /** + * @in_sync_count: Number of sync objects to wait on before starting + * this job. + */ + __u32 in_sync_count; - /** - * @out_sync_count: Number of sync objects to signal upon completion of - * this job. - */ - __u32 out_sync_count; + /** + * @out_sync_count: Number of sync objects to signal upon completion of + * this job. + */ + __u32 out_sync_count; - /** @cmdbuf_size: Command buffer size in bytes */ - __u32 cmdbuf_size; + /** @cmdbuf_size: Command buffer size in bytes */ + __u32 cmdbuf_size; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; }; /** @@ -754,54 +754,54 @@ struct drm_asahi_submit { * This struct is implicitly sized and therefore is not extensible. */ struct drm_asahi_attachment { - /** @pointer: Base address of the attachment */ - __u64 pointer; + /** @pointer: Base address of the attachment */ + __u64 pointer; - /** @size: Size of the attachment in bytes */ - __u64 size; + /** @size: Size of the attachment in bytes */ + __u64 size; - /** @pad: MBZ */ - __u32 pad; + /** @pad: MBZ */ + __u32 pad; - /** @flags: MBZ */ - __u32 flags; + /** @flags: MBZ */ + __u32 flags; }; enum drm_asahi_render_flags { - /** - * @DRM_ASAHI_RENDER_VERTEX_SCRATCH: A vertex stage shader uses scratch - * memory. - */ - DRM_ASAHI_RENDER_VERTEX_SCRATCH = (1U << 0), + /** + * @DRM_ASAHI_RENDER_VERTEX_SCRATCH: A vertex stage shader uses scratch + * memory. + */ + DRM_ASAHI_RENDER_VERTEX_SCRATCH = (1U << 0), - /** - * @DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES: Process even empty tiles. - * This must be set when clearing render targets. - */ - DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES = (1U << 1), + /** + * @DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES: Process even empty tiles. + * This must be set when clearing render targets. + */ + DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES = (1U << 1), - /** - * @DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING: Run vertex stage on a single - * cluster (on multi-cluster GPUs) - * - * This harms performance but can workaround certain sync/coherency - * bugs, and therefore is useful for debugging. - */ - DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING = (1U << 2), + /** + * @DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING: Run vertex stage on a single + * cluster (on multi-cluster GPUs) + * + * This harms performance but can workaround certain sync/coherency + * bugs, and therefore is useful for debugging. + */ + DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING = (1U << 2), - /** - * @DRM_ASAHI_RENDER_DBIAS_IS_INT: Use integer depth bias formula. - * - * Graphics specifications contain two alternate formulas for depth - * bias, a float formula used with floating-point depth buffers and an - * integer formula using with unorm depth buffers. This flag specifies - * that the integer formula should be used. If omitted, the float - * formula is used instead. - * - * This corresponds to bit 18 of the relevant hardware control register, - * so we match that here for efficiency. - */ - DRM_ASAHI_RENDER_DBIAS_IS_INT = (1U << 18), + /** + * @DRM_ASAHI_RENDER_DBIAS_IS_INT: Use integer depth bias formula. + * + * Graphics specifications contain two alternate formulas for depth + * bias, a float formula used with floating-point depth buffers and an + * integer formula using with unorm depth buffers. This flag specifies + * that the integer formula should be used. If omitted, the float + * formula is used instead. + * + * This corresponds to bit 18 of the relevant hardware control register, + * so we match that here for efficiency. + */ + DRM_ASAHI_RENDER_DBIAS_IS_INT = (1U << 18), }; /** @@ -816,26 +816,26 @@ enum drm_asahi_render_flags { * This struct is embedded in other structs and therefore is not extensible. */ struct drm_asahi_zls_buffer { - /** @base: Base address of the buffer */ - __u64 base; + /** @base: Base address of the buffer */ + __u64 base; - /** - * @comp_base: If the load buffer is compressed, address of the - * compression metadata section. - */ - __u64 comp_base; + /** + * @comp_base: If the load buffer is compressed, address of the + * compression metadata section. + */ + __u64 comp_base; - /** - * @stride: If layered rendering is enabled, the number of bytes - * between each layer of the buffer. - */ - __u32 stride; + /** + * @stride: If layered rendering is enabled, the number of bytes + * between each layer of the buffer. + */ + __u32 stride; - /** - * @comp_stride: If layered rendering is enabled, the number of bytes - * between each layer of the compression metadata. - */ - __u32 comp_stride; + /** + * @comp_stride: If layered rendering is enabled, the number of bytes + * between each layer of the compression metadata. + */ + __u32 comp_stride; }; /** @@ -849,15 +849,15 @@ struct drm_asahi_zls_buffer { * This struct is embedded in other structs and therefore is not extensible. */ struct drm_asahi_timestamp { - /** - * @handle: Handle of the timestamp buffer, or 0 to skip this - * timestamp. If nonzero, this must equal the value returned in - * drm_asahi_gem_bind_object::object_handle. - */ - __u32 handle; + /** + * @handle: Handle of the timestamp buffer, or 0 to skip this + * timestamp. If nonzero, this must equal the value returned in + * drm_asahi_gem_bind_object::object_handle. + */ + __u32 handle; - /** @offset: Offset to write into the timestamp buffer */ - __u32 offset; + /** @offset: Offset to write into the timestamp buffer */ + __u32 offset; }; /** @@ -870,11 +870,11 @@ struct drm_asahi_timestamp { * This struct is embedded in other structs and therefore is not extensible. */ struct drm_asahi_timestamps { - /** @start: Timestamp recorded at the start of the operation */ - struct drm_asahi_timestamp start; + /** @start: Timestamp recorded at the start of the operation */ + struct drm_asahi_timestamp start; - /** @end: Timestamp recorded at the end of the operation */ - struct drm_asahi_timestamp end; + /** @end: Timestamp recorded at the end of the operation */ + struct drm_asahi_timestamp end; }; /** @@ -889,25 +889,25 @@ struct drm_asahi_timestamps { * This struct is embedded in other structs and therefore is not extensible. */ struct drm_asahi_helper_program { - /** - * @binary: USC address to the helper program binary. This is a tagged - * pointer with configuration in the bottom bits. - */ - __u32 binary; + /** + * @binary: USC address to the helper program binary. This is a tagged + * pointer with configuration in the bottom bits. + */ + __u32 binary; - /** @cfg: Additional configuration bits for the helper program. */ - __u32 cfg; + /** @cfg: Additional configuration bits for the helper program. */ + __u32 cfg; - /** - * @data: Data passed to the helper program. This value is not - * interpreted by the kernel, firmware, or hardware in any way. It is - * simply a sideband for userspace, set with the submit ioctl and read - * via special registers inside the helper program. - * - * In practice, userspace will pass a 64-bit GPU VA here pointing to the - * actual arguments, which presumably don't fit in 64-bits. - */ - __u64 data; + /** + * @data: Data passed to the helper program. This value is not + * interpreted by the kernel, firmware, or hardware in any way. It is + * simply a sideband for userspace, set with the submit ioctl and read + * via special registers inside the helper program. + * + * In practice, userspace will pass a 64-bit GPU VA here pointing to the + * actual arguments, which presumably don't fit in 64-bits. + */ + __u64 data; }; /** @@ -923,21 +923,21 @@ struct drm_asahi_helper_program { * This struct is embedded in other structs and therefore is not extensible. */ struct drm_asahi_bg_eot { - /** - * @usc: USC address of the hardware USC words binding resources - * (including images and uniforms) and the program itself. Note this is - * an additional layer of indirection compared to the helper program, - * avoiding the need for a sideband for data. This is a tagged pointer - * with additional configuration in the bottom bits. - */ - __u32 usc; + /** + * @usc: USC address of the hardware USC words binding resources + * (including images and uniforms) and the program itself. Note this is + * an additional layer of indirection compared to the helper program, + * avoiding the need for a sideband for data. This is a tagged pointer + * with additional configuration in the bottom bits. + */ + __u32 usc; - /** - * @rsrc_spec: Resource specifier for the program. This is a packed - * hardware data structure describing the required number of registers, - * uniforms, bound textures, and bound samplers. - */ - __u32 rsrc_spec; + /** + * @rsrc_spec: Resource specifier for the program. This is a packed + * hardware data structure describing the required number of registers, + * uniforms, bound textures, and bound samplers. + */ + __u32 rsrc_spec; }; /** @@ -970,143 +970,143 @@ struct drm_asahi_bg_eot { * compatible with old userspace. */ struct drm_asahi_cmd_render { - /** @flags: Combination of drm_asahi_render_flags flags. */ - __u32 flags; + /** @flags: Combination of drm_asahi_render_flags flags. */ + __u32 flags; - /** - * @isp_zls_pixels: ISP_ZLS_PIXELS register value. This contains the - * depth/stencil width/height, which may differ from the framebuffer - * width/height. - */ - __u32 isp_zls_pixels; + /** + * @isp_zls_pixels: ISP_ZLS_PIXELS register value. This contains the + * depth/stencil width/height, which may differ from the framebuffer + * width/height. + */ + __u32 isp_zls_pixels; - /** - * @vdm_ctrl_stream_base: VDM_CTRL_STREAM_BASE register value. GPU - * address to the beginning of the VDM control stream. - */ - __u64 vdm_ctrl_stream_base; + /** + * @vdm_ctrl_stream_base: VDM_CTRL_STREAM_BASE register value. GPU + * address to the beginning of the VDM control stream. + */ + __u64 vdm_ctrl_stream_base; - /** @vertex_helper: Helper program used for the vertex shader */ - struct drm_asahi_helper_program vertex_helper; + /** @vertex_helper: Helper program used for the vertex shader */ + struct drm_asahi_helper_program vertex_helper; - /** @fragment_helper: Helper program used for the fragment shader */ - struct drm_asahi_helper_program fragment_helper; + /** @fragment_helper: Helper program used for the fragment shader */ + struct drm_asahi_helper_program fragment_helper; - /** - * @isp_scissor_base: ISP_SCISSOR_BASE register value. GPU address of an - * array of scissor descriptors indexed in the render pass. - */ - __u64 isp_scissor_base; + /** + * @isp_scissor_base: ISP_SCISSOR_BASE register value. GPU address of an + * array of scissor descriptors indexed in the render pass. + */ + __u64 isp_scissor_base; - /** - * @isp_dbias_base: ISP_DBIAS_BASE register value. GPU address of an - * array of depth bias values indexed in the render pass. - */ - __u64 isp_dbias_base; + /** + * @isp_dbias_base: ISP_DBIAS_BASE register value. GPU address of an + * array of depth bias values indexed in the render pass. + */ + __u64 isp_dbias_base; - /** - * @isp_oclqry_base: ISP_OCLQRY_BASE register value. GPU address of an - * array of occlusion query results written by the render pass. - */ - __u64 isp_oclqry_base; + /** + * @isp_oclqry_base: ISP_OCLQRY_BASE register value. GPU address of an + * array of occlusion query results written by the render pass. + */ + __u64 isp_oclqry_base; - /** @depth: Depth buffer */ - struct drm_asahi_zls_buffer depth; + /** @depth: Depth buffer */ + struct drm_asahi_zls_buffer depth; - /** @stencil: Stencil buffer */ - struct drm_asahi_zls_buffer stencil; + /** @stencil: Stencil buffer */ + struct drm_asahi_zls_buffer stencil; - /** @zls_ctrl: ZLS_CTRL register value */ - __u64 zls_ctrl; + /** @zls_ctrl: ZLS_CTRL register value */ + __u64 zls_ctrl; - /** @ppp_multisamplectl: PPP_MULTISAMPLECTL register value */ - __u64 ppp_multisamplectl; + /** @ppp_multisamplectl: PPP_MULTISAMPLECTL register value */ + __u64 ppp_multisamplectl; - /** - * @sampler_heap: Base address of the sampler heap. This heap is used - * for both vertex shaders and fragment shaders. The registers are - * per-stage, but there is no known use case for separate heaps. - */ - __u64 sampler_heap; + /** + * @sampler_heap: Base address of the sampler heap. This heap is used + * for both vertex shaders and fragment shaders. The registers are + * per-stage, but there is no known use case for separate heaps. + */ + __u64 sampler_heap; - /** @ppp_ctrl: PPP_CTRL register value */ - __u32 ppp_ctrl; + /** @ppp_ctrl: PPP_CTRL register value */ + __u32 ppp_ctrl; - /** @width_px: Framebuffer width in pixels */ - __u16 width_px; + /** @width_px: Framebuffer width in pixels */ + __u16 width_px; - /** @height_px: Framebuffer height in pixels */ - __u16 height_px; + /** @height_px: Framebuffer height in pixels */ + __u16 height_px; - /** @layers: Number of layers in the framebuffer */ - __u16 layers; + /** @layers: Number of layers in the framebuffer */ + __u16 layers; - /** @sampler_count: Number of samplers in the sampler heap. */ - __u16 sampler_count; + /** @sampler_count: Number of samplers in the sampler heap. */ + __u16 sampler_count; - /** @utile_width_px: Width of a logical tilebuffer tile in pixels */ - __u8 utile_width_px; + /** @utile_width_px: Width of a logical tilebuffer tile in pixels */ + __u8 utile_width_px; - /** @utile_height_px: Height of a logical tilebuffer tile in pixels */ - __u8 utile_height_px; + /** @utile_height_px: Height of a logical tilebuffer tile in pixels */ + __u8 utile_height_px; - /** @samples: # of samples in the framebuffer. Must be 1, 2, or 4. */ - __u8 samples; + /** @samples: # of samples in the framebuffer. Must be 1, 2, or 4. */ + __u8 samples; - /** @sample_size_B: # of bytes in the tilebuffer required per sample. */ - __u8 sample_size_B; + /** @sample_size_B: # of bytes in the tilebuffer required per sample. */ + __u8 sample_size_B; - /** - * @isp_merge_upper_x: 32-bit float used in the hardware triangle - * merging. Calculate as: tan(60 deg) * width. - * - * Making these values UAPI avoids requiring floating-point calculations - * in the kernel in the hot path. - */ - __u32 isp_merge_upper_x; + /** + * @isp_merge_upper_x: 32-bit float used in the hardware triangle + * merging. Calculate as: tan(60 deg) * width. + * + * Making these values UAPI avoids requiring floating-point calculations + * in the kernel in the hot path. + */ + __u32 isp_merge_upper_x; - /** - * @isp_merge_upper_y: 32-bit float. Calculate as: tan(60 deg) * height. - * See @isp_merge_upper_x. - */ - __u32 isp_merge_upper_y; + /** + * @isp_merge_upper_y: 32-bit float. Calculate as: tan(60 deg) * height. + * See @isp_merge_upper_x. + */ + __u32 isp_merge_upper_y; - /** @bg: Background program run for each tile at the start */ - struct drm_asahi_bg_eot bg; + /** @bg: Background program run for each tile at the start */ + struct drm_asahi_bg_eot bg; - /** @eot: End-of-tile program ran for each tile at the end */ - struct drm_asahi_bg_eot eot; + /** @eot: End-of-tile program ran for each tile at the end */ + struct drm_asahi_bg_eot eot; - /** - * @partial_bg: Background program ran at the start of each tile when - * resuming the render pass during a partial render. - */ - struct drm_asahi_bg_eot partial_bg; + /** + * @partial_bg: Background program ran at the start of each tile when + * resuming the render pass during a partial render. + */ + struct drm_asahi_bg_eot partial_bg; - /** - * @partial_eot: End-of-tile program ran at the end of each tile when - * pausing the render pass during a partial render. - */ - struct drm_asahi_bg_eot partial_eot; + /** + * @partial_eot: End-of-tile program ran at the end of each tile when + * pausing the render pass during a partial render. + */ + struct drm_asahi_bg_eot partial_eot; - /** - * @isp_bgobjdepth: ISP_BGOBJDEPTH register value. This is the depth - * buffer clear value, encoded in the depth buffer's format: either a - * 32-bit float or a 16-bit unorm (with upper bits zeroed). - */ - __u32 isp_bgobjdepth; + /** + * @isp_bgobjdepth: ISP_BGOBJDEPTH register value. This is the depth + * buffer clear value, encoded in the depth buffer's format: either a + * 32-bit float or a 16-bit unorm (with upper bits zeroed). + */ + __u32 isp_bgobjdepth; - /** - * @isp_bgobjvals: ISP_BGOBJVALS register value. The bottom 8-bits - * contain the stencil buffer clear value. - */ - __u32 isp_bgobjvals; + /** + * @isp_bgobjvals: ISP_BGOBJVALS register value. The bottom 8-bits + * contain the stencil buffer clear value. + */ + __u32 isp_bgobjvals; - /** @ts_vtx: Timestamps for the vertex portion of the render */ - struct drm_asahi_timestamps ts_vtx; + /** @ts_vtx: Timestamps for the vertex portion of the render */ + struct drm_asahi_timestamps ts_vtx; - /** @ts_frag: Timestamps for the fragment portion of the render */ - struct drm_asahi_timestamps ts_frag; + /** @ts_frag: Timestamps for the fragment portion of the render */ + struct drm_asahi_timestamps ts_frag; }; /** @@ -1117,44 +1117,44 @@ struct drm_asahi_cmd_render { * single compute command, although timestamps are at command granularity. */ struct drm_asahi_cmd_compute { - /** @flags: MBZ */ - __u32 flags; + /** @flags: MBZ */ + __u32 flags; - /** @sampler_count: Number of samplers in the sampler heap. */ - __u32 sampler_count; + /** @sampler_count: Number of samplers in the sampler heap. */ + __u32 sampler_count; - /** - * @cdm_ctrl_stream_base: CDM_CTRL_STREAM_BASE register value. GPU - * address to the beginning of the CDM control stream. - */ - __u64 cdm_ctrl_stream_base; + /** + * @cdm_ctrl_stream_base: CDM_CTRL_STREAM_BASE register value. GPU + * address to the beginning of the CDM control stream. + */ + __u64 cdm_ctrl_stream_base; - /** - * @cdm_ctrl_stream_end: GPU base address to the end of the hardware - * control stream. Note this only considers the first contiguous segment - * of the control stream, as the stream might jump elsewhere. - */ - __u64 cdm_ctrl_stream_end; + /** + * @cdm_ctrl_stream_end: GPU base address to the end of the hardware + * control stream. Note this only considers the first contiguous segment + * of the control stream, as the stream might jump elsewhere. + */ + __u64 cdm_ctrl_stream_end; - /** @sampler_heap: Base address of the sampler heap. */ - __u64 sampler_heap; + /** @sampler_heap: Base address of the sampler heap. */ + __u64 sampler_heap; - /** @helper: Helper program used for this compute command */ - struct drm_asahi_helper_program helper; + /** @helper: Helper program used for this compute command */ + struct drm_asahi_helper_program helper; - /** @ts: Timestamps for the compute command */ - struct drm_asahi_timestamps ts; + /** @ts: Timestamps for the compute command */ + struct drm_asahi_timestamps ts; }; /** * struct drm_asahi_get_time - Arguments passed to DRM_IOCTL_ASAHI_GET_TIME */ struct drm_asahi_get_time { - /** @flags: MBZ. */ - __u64 flags; + /** @flags: MBZ. */ + __u64 flags; - /** @gpu_timestamp: On return, the GPU timestamp in nanoseconds. */ - __u64 gpu_timestamp; + /** @gpu_timestamp: On return, the GPU timestamp in nanoseconds. */ + __u64 gpu_timestamp; }; /** @@ -1168,23 +1168,23 @@ struct drm_asahi_get_time { * * Return: An IOCTL number to be passed to ioctl() from userspace. */ -#define DRM_IOCTL_ASAHI(__access, __id, __type) \ - DRM_IO ## __access(DRM_COMMAND_BASE + DRM_ASAHI_ ## __id, \ - struct drm_asahi_ ## __type) +#define DRM_IOCTL_ASAHI(__access, __id, __type) \ + DRM_IO##__access(DRM_COMMAND_BASE + DRM_ASAHI_##__id, \ + struct drm_asahi_##__type) /* Note: this is an enum so that it can be resolved by Rust bindgen. */ enum { - DRM_IOCTL_ASAHI_GET_PARAMS = DRM_IOCTL_ASAHI(W, GET_PARAMS, get_params), - DRM_IOCTL_ASAHI_GET_TIME = DRM_IOCTL_ASAHI(WR, GET_TIME, get_time), - DRM_IOCTL_ASAHI_VM_CREATE = DRM_IOCTL_ASAHI(WR, VM_CREATE, vm_create), - DRM_IOCTL_ASAHI_VM_DESTROY = DRM_IOCTL_ASAHI(W, VM_DESTROY, vm_destroy), - DRM_IOCTL_ASAHI_VM_BIND = DRM_IOCTL_ASAHI(W, VM_BIND, vm_bind), - DRM_IOCTL_ASAHI_GEM_CREATE = DRM_IOCTL_ASAHI(WR, GEM_CREATE, gem_create), - DRM_IOCTL_ASAHI_GEM_MMAP_OFFSET = DRM_IOCTL_ASAHI(WR, GEM_MMAP_OFFSET, gem_mmap_offset), - DRM_IOCTL_ASAHI_GEM_BIND_OBJECT = DRM_IOCTL_ASAHI(WR, GEM_BIND_OBJECT, gem_bind_object), - DRM_IOCTL_ASAHI_QUEUE_CREATE = DRM_IOCTL_ASAHI(WR, QUEUE_CREATE, queue_create), - DRM_IOCTL_ASAHI_QUEUE_DESTROY = DRM_IOCTL_ASAHI(W, QUEUE_DESTROY, queue_destroy), - DRM_IOCTL_ASAHI_SUBMIT = DRM_IOCTL_ASAHI(W, SUBMIT, submit), + DRM_IOCTL_ASAHI_GET_PARAMS = DRM_IOCTL_ASAHI(W, GET_PARAMS, get_params), + DRM_IOCTL_ASAHI_GET_TIME = DRM_IOCTL_ASAHI(WR, GET_TIME, get_time), + DRM_IOCTL_ASAHI_VM_CREATE = DRM_IOCTL_ASAHI(WR, VM_CREATE, vm_create), + DRM_IOCTL_ASAHI_VM_DESTROY = DRM_IOCTL_ASAHI(W, VM_DESTROY, vm_destroy), + DRM_IOCTL_ASAHI_VM_BIND = DRM_IOCTL_ASAHI(W, VM_BIND, vm_bind), + DRM_IOCTL_ASAHI_GEM_CREATE = DRM_IOCTL_ASAHI(WR, GEM_CREATE, gem_create), + DRM_IOCTL_ASAHI_GEM_MMAP_OFFSET = DRM_IOCTL_ASAHI(WR, GEM_MMAP_OFFSET, gem_mmap_offset), + DRM_IOCTL_ASAHI_GEM_BIND_OBJECT = DRM_IOCTL_ASAHI(WR, GEM_BIND_OBJECT, gem_bind_object), + DRM_IOCTL_ASAHI_QUEUE_CREATE = DRM_IOCTL_ASAHI(WR, QUEUE_CREATE, queue_create), + DRM_IOCTL_ASAHI_QUEUE_DESTROY = DRM_IOCTL_ASAHI(W, QUEUE_DESTROY, queue_destroy), + DRM_IOCTL_ASAHI_SUBMIT = DRM_IOCTL_ASAHI(W, SUBMIT, submit), }; #if defined(__cplusplus) diff --git a/src/detection/gpu/d3dkmthk.h b/src/detection/gpu/d3dkmthk.h index 90b10fff8..06a89b756 100644 --- a/src/detection/gpu/d3dkmthk.h +++ b/src/detection/gpu/d3dkmthk.h @@ -5,11 +5,11 @@ #include #if _WIN32 -#include -#include +# include +# include #else -#include -#include +# include +# include typedef struct _LUID { uint32_t LowPart; @@ -38,106 +38,96 @@ typedef union { int64_t QuadPart; } LARGE_INTEGER; typedef int32_t NTSTATUS; // 0 for success, -1 for failure -#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0) +# define NT_SUCCESS(Status) ((NTSTATUS) (Status) >= 0) #endif #define D3DKMT_ALIGN64 __attribute__((aligned(8))) -#define MAX_ENUM_ADAPTERS 16 +#define MAX_ENUM_ADAPTERS 16 -typedef struct D3DKMT_HANDLE -{ +typedef struct D3DKMT_HANDLE { union { struct { - uint32_t Instance : 6; - uint32_t Index : 24; - uint32_t Unique : 2; + uint32_t Instance : 6; + uint32_t Index : 24; + uint32_t Unique : 2; }; uint32_t Value; }; } D3DKMT_HANDLE; -typedef struct _D3DKMT_OPENADAPTERFROMLUID -{ - LUID AdapterLuid; - D3DKMT_HANDLE hAdapter; +typedef struct _D3DKMT_OPENADAPTERFROMLUID { + LUID AdapterLuid; + D3DKMT_HANDLE hAdapter; } D3DKMT_OPENADAPTERFROMLUID; -typedef struct _D3DKMT_ADAPTERINFO -{ - D3DKMT_HANDLE hAdapter; - LUID AdapterLuid; - ULONG NumOfSources; - BOOL bPrecisePresentRegionsPreferred; +typedef struct _D3DKMT_ADAPTERINFO { + D3DKMT_HANDLE hAdapter; + LUID AdapterLuid; + ULONG NumOfSources; + BOOL bPrecisePresentRegionsPreferred; } D3DKMT_ADAPTERINFO; -typedef struct _D3DKMT_ENUMADAPTERS2 -{ - ULONG NumAdapters; // in/out: On input, the count of the pAdapters array buffer. On output, the number of adapters enumerated. - D3DKMT_ADAPTERINFO* pAdapters; // out: Array of enumerated adapters containing NumAdapters elements +typedef struct _D3DKMT_ENUMADAPTERS2 { + ULONG NumAdapters; // in/out: On input, the count of the pAdapters array buffer. On output, the number of adapters enumerated. + D3DKMT_ADAPTERINFO* pAdapters; // out: Array of enumerated adapters containing NumAdapters elements } D3DKMT_ENUMADAPTERS2; static_assert(sizeof(D3DKMT_ENUMADAPTERS2) == - #if SIZE_MAX == UINT64_MAX - 0x10 - #else - 0x08 - #endif -, "D3DKMT_ENUMADAPTERS2 structure size mismatch"); +#if SIZE_MAX == UINT64_MAX + 0x10 +#else + 0x08 +#endif + , + "D3DKMT_ENUMADAPTERS2 structure size mismatch"); -typedef struct _D3DKMT_ADAPTERREGISTRYINFO -{ - WCHAR AdapterString[260]; - WCHAR BiosString[260]; - WCHAR DacType[260]; - WCHAR ChipType[260]; +typedef struct _D3DKMT_ADAPTERREGISTRYINFO { + WCHAR AdapterString[260]; + WCHAR BiosString[260]; + WCHAR DacType[260]; + WCHAR ChipType[260]; } D3DKMT_ADAPTERREGISTRYINFO; -typedef struct _D3DKMT_CLOSEADAPTER -{ - D3DKMT_HANDLE hAdapter; // in: adapter handle +typedef struct _D3DKMT_CLOSEADAPTER { + D3DKMT_HANDLE hAdapter; // in: adapter handle } D3DKMT_CLOSEADAPTER; -typedef struct _D3DKMT_SEGMENTSIZEINFO -{ - D3DKMT_ALIGN64 ULONGLONG DedicatedVideoMemorySize; - D3DKMT_ALIGN64 ULONGLONG DedicatedSystemMemorySize; - D3DKMT_ALIGN64 ULONGLONG SharedSystemMemorySize; +typedef struct _D3DKMT_SEGMENTSIZEINFO { + D3DKMT_ALIGN64 ULONGLONG DedicatedVideoMemorySize; + D3DKMT_ALIGN64 ULONGLONG DedicatedSystemMemorySize; + D3DKMT_ALIGN64 ULONGLONG SharedSystemMemorySize; } D3DKMT_SEGMENTSIZEINFO; -typedef struct _D3DKMT_ADAPTERTYPE -{ - union - { +typedef struct _D3DKMT_ADAPTERTYPE { + union { struct { - UINT RenderSupported : 1; // WDDM 1.2, Windows 8 - UINT DisplaySupported : 1; - UINT SoftwareDevice : 1; - UINT PostDevice : 1; - UINT HybridDiscrete : 1; // WDDM 1.3, Windows 8.1 - UINT HybridIntegrated : 1; - UINT IndirectDisplayDevice : 1; - UINT Paravirtualized : 1; // WDDM 2.3, Windows 10 Fall Creators Update (version 1709) - UINT ACGSupported : 1; - UINT SupportSetTimingsFromVidPn : 1; - UINT Detachable : 1; - UINT ComputeOnly : 1; // WDDM 2.6, Windows 10 May 2019 Update (Version 1903) - UINT Prototype : 1; - UINT RuntimePowerManagement : 1; // WDDM 2.9, Windows 10 Insider Preview "Iron" - UINT Reserved : 18; + UINT RenderSupported : 1; // WDDM 1.2, Windows 8 + UINT DisplaySupported : 1; + UINT SoftwareDevice : 1; + UINT PostDevice : 1; + UINT HybridDiscrete : 1; // WDDM 1.3, Windows 8.1 + UINT HybridIntegrated : 1; + UINT IndirectDisplayDevice : 1; + UINT Paravirtualized : 1; // WDDM 2.3, Windows 10 Fall Creators Update (version 1709) + UINT ACGSupported : 1; + UINT SupportSetTimingsFromVidPn : 1; + UINT Detachable : 1; + UINT ComputeOnly : 1; // WDDM 2.6, Windows 10 May 2019 Update (Version 1903) + UINT Prototype : 1; + UINT RuntimePowerManagement : 1; // WDDM 2.9, Windows 10 Insider Preview "Iron" + UINT Reserved : 18; }; UINT Value; }; } D3DKMT_ADAPTERTYPE; -typedef struct _D3DKMT_ADAPTERADDRESS -{ - UINT BusNumber; // Bus number on which the physical device is located. - UINT DeviceNumber; // Index of the physical device on the bus. - UINT FunctionNumber; // Function number of the adapter on the physical device. +typedef struct _D3DKMT_ADAPTERADDRESS { + UINT BusNumber; // Bus number on which the physical device is located. + UINT DeviceNumber; // Index of the physical device on the bus. + UINT FunctionNumber; // Function number of the adapter on the physical device. } D3DKMT_ADAPTERADDRESS; -typedef struct _D3DKMT_DEVICE_IDS -{ +typedef struct _D3DKMT_DEVICE_IDS { UINT VendorID; UINT DeviceID; UINT SubVendorID; @@ -146,160 +136,144 @@ typedef struct _D3DKMT_DEVICE_IDS UINT BusType; } D3DKMT_DEVICE_IDS; -typedef struct _D3DKMT_UMD_DRIVER_VERSION -{ +typedef struct _D3DKMT_UMD_DRIVER_VERSION { D3DKMT_ALIGN64 LARGE_INTEGER DriverVersion; } D3DKMT_UMD_DRIVER_VERSION; -typedef struct _D3DKMT_QUERY_DEVICE_IDS -{ - UINT PhysicalAdapterIndex; // in: - D3DKMT_DEVICE_IDS DeviceIds; // out: +typedef struct _D3DKMT_QUERY_DEVICE_IDS { + UINT PhysicalAdapterIndex; // in: + D3DKMT_DEVICE_IDS DeviceIds; // out: } D3DKMT_QUERY_DEVICE_IDS; -typedef enum _QAI_DRIVERVERSION -{ - KMT_DRIVERVERSION_WDDM_1_0 = 1000, // Windows Vista +typedef enum _QAI_DRIVERVERSION { + KMT_DRIVERVERSION_WDDM_1_0 = 1000, // Windows Vista KMT_DRIVERVERSION_WDDM_1_1_PRERELEASE = 1102, // Windows Vista with prereleased Win7 features - KMT_DRIVERVERSION_WDDM_1_1 = 1105, // Windows 7 - KMT_DRIVERVERSION_WDDM_1_2 = 1200, // Windows 8 - KMT_DRIVERVERSION_WDDM_1_3 = 1300, // Windows 8.1 - KMT_DRIVERVERSION_WDDM_2_0 = 2000, // Windows 10 - KMT_DRIVERVERSION_WDDM_2_1 = 2100, // Windows 10 (1607) - KMT_DRIVERVERSION_WDDM_2_2 = 2200, // Windows 10 (1703) - KMT_DRIVERVERSION_WDDM_2_3 = 2300, // Windows 10 (1709) - KMT_DRIVERVERSION_WDDM_2_4 = 2400, // Windows 10 (1803) - KMT_DRIVERVERSION_WDDM_2_5 = 2500, // Windows 10 (1809) - KMT_DRIVERVERSION_WDDM_2_6 = 2600, // Windows 10 (1903) - KMT_DRIVERVERSION_WDDM_2_7 = 2700, // Windows 10 (2004) - KMT_DRIVERVERSION_WDDM_2_8 = 2800, // Windows 11 Insider Preview Manganese - KMT_DRIVERVERSION_WDDM_2_9 = 2900, // Windows 11 Insider Preview Iron - KMT_DRIVERVERSION_WDDM_3_0 = 3000, // Windows 11 (21H2) - KMT_DRIVERVERSION_WDDM_3_1 = 3100, // Windows 11 (22H2) - KMT_DRIVERVERSION_WDDM_3_2 = 3200, // Windows 11 (24H2) + KMT_DRIVERVERSION_WDDM_1_1 = 1105, // Windows 7 + KMT_DRIVERVERSION_WDDM_1_2 = 1200, // Windows 8 + KMT_DRIVERVERSION_WDDM_1_3 = 1300, // Windows 8.1 + KMT_DRIVERVERSION_WDDM_2_0 = 2000, // Windows 10 + KMT_DRIVERVERSION_WDDM_2_1 = 2100, // Windows 10 (1607) + KMT_DRIVERVERSION_WDDM_2_2 = 2200, // Windows 10 (1703) + KMT_DRIVERVERSION_WDDM_2_3 = 2300, // Windows 10 (1709) + KMT_DRIVERVERSION_WDDM_2_4 = 2400, // Windows 10 (1803) + KMT_DRIVERVERSION_WDDM_2_5 = 2500, // Windows 10 (1809) + KMT_DRIVERVERSION_WDDM_2_6 = 2600, // Windows 10 (1903) + KMT_DRIVERVERSION_WDDM_2_7 = 2700, // Windows 10 (2004) + KMT_DRIVERVERSION_WDDM_2_8 = 2800, // Windows 11 Insider Preview Manganese + KMT_DRIVERVERSION_WDDM_2_9 = 2900, // Windows 11 Insider Preview Iron + KMT_DRIVERVERSION_WDDM_3_0 = 3000, // Windows 11 (21H2) + KMT_DRIVERVERSION_WDDM_3_1 = 3100, // Windows 11 (22H2) + KMT_DRIVERVERSION_WDDM_3_2 = 3200, // Windows 11 (24H2) } D3DKMT_DRIVERVERSION; -typedef struct _D3DKMT_QUERY_ADAPTER_UNIQUE_GUID -{ +typedef struct _D3DKMT_QUERY_ADAPTER_UNIQUE_GUID { WCHAR AdapterUniqueGUID[40]; } D3DKMT_QUERY_ADAPTER_UNIQUE_GUID; -typedef enum _KMTQUERYADAPTERINFOTYPE -{ - KMTQAITYPE_GETSEGMENTSIZE = 3, - KMTQAITYPE_ADAPTERGUID = 4, - KMTQAITYPE_ADAPTERADDRESS = 6, - KMTQAITYPE_ADAPTERREGISTRYINFO = 8, - KMTQAITYPE_DRIVERVERSION = 13, - KMTQAITYPE_ADAPTERTYPE = 15, // WDDM 1.2, Windows 8 - KMTQAITYPE_UMD_DRIVER_VERSION = 18, - KMTQAITYPE_NODEMETADATA = 25, // WDDM 2.0, Windows 10 - KMTQAITYPE_PHYSICALADAPTERDEVICEIDS = 31, - KMTQAITYPE_QUERY_ADAPTER_UNIQUE_GUID = 60, // WDDM 2.4, Windows 10 (1803) - // This reports the GUID string used by the adapter's registry key (DirectX and Video) +typedef enum _KMTQUERYADAPTERINFOTYPE { + KMTQAITYPE_GETSEGMENTSIZE = 3, + KMTQAITYPE_ADAPTERGUID = 4, + KMTQAITYPE_ADAPTERADDRESS = 6, + KMTQAITYPE_ADAPTERREGISTRYINFO = 8, + KMTQAITYPE_DRIVERVERSION = 13, + KMTQAITYPE_ADAPTERTYPE = 15, // WDDM 1.2, Windows 8 + KMTQAITYPE_UMD_DRIVER_VERSION = 18, + KMTQAITYPE_NODEMETADATA = 25, // WDDM 2.0, Windows 10 + KMTQAITYPE_PHYSICALADAPTERDEVICEIDS = 31, + KMTQAITYPE_QUERY_ADAPTER_UNIQUE_GUID = 60, // WDDM 2.4, Windows 10 (1803) + // This reports the GUID string used by the adapter's registry key (DirectX and Video) } KMTQUERYADAPTERINFOTYPE; -typedef struct _D3DKMT_QUERYADAPTERINFO -{ - D3DKMT_HANDLE hAdapter; +typedef struct _D3DKMT_QUERYADAPTERINFO { + D3DKMT_HANDLE hAdapter; KMTQUERYADAPTERINFOTYPE Type; - VOID* pPrivateDriverData; - UINT PrivateDriverDataSize; + VOID* pPrivateDriverData; + UINT PrivateDriverDataSize; } D3DKMT_QUERYADAPTERINFO; #define D3DKMT_MAX_SEGMENT_COUNT 32 -typedef enum _D3DKMT_MEMORY_SEGMENT_GROUP -{ +typedef enum _D3DKMT_MEMORY_SEGMENT_GROUP { D3DKMT_MEMORY_SEGMENT_GROUP_LOCAL = 0, D3DKMT_MEMORY_SEGMENT_GROUP_NON_LOCAL = 1 } D3DKMT_MEMORY_SEGMENT_GROUP; -typedef enum _D3DKMT_QUERYSTATISTICS_TYPE -{ - D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER = 10, // WDDM 2.4, Windows 10 April 2018 Update (version 1803) - D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE = 17, // WDDM 3.1, Windows 11 2022 Update (version 22H2) - D3DKMT_QUERYSTATISTICS_NODE2 = 18, +typedef enum _D3DKMT_QUERYSTATISTICS_TYPE { + D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER = 10, // WDDM 2.4, Windows 10 April 2018 Update (version 1803) + D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE = 17, // WDDM 3.1, Windows 11 2022 Update (version 22H2) + D3DKMT_QUERYSTATISTICS_NODE2 = 18, } D3DKMT_QUERYSTATISTICS_TYPE; -typedef struct _D3DKMT_QUERYSTATISTICS_QUERY_PHYSICAL_ADAPTER -{ +typedef struct _D3DKMT_QUERYSTATISTICS_QUERY_PHYSICAL_ADAPTER { ULONG PhysicalAdapterIndex; } D3DKMT_QUERYSTATISTICS_QUERY_PHYSICAL_ADAPTER; -typedef struct _D3DKMT_QUERYSTATISTICS_QUERY_NODE2 -{ +typedef struct _D3DKMT_QUERYSTATISTICS_QUERY_NODE2 { UINT16 PhysicalAdapterIndex; UINT16 NodeOrdinal; } D3DKMT_QUERYSTATISTICS_QUERY_NODE2; -typedef struct _D3DKMT_ADAPTER_PERFDATA -{ - UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain - D3DKMT_ALIGN64 ULONGLONG MemoryFrequency; // out: Clock frequency of the memory in hertz - D3DKMT_ALIGN64 ULONGLONG MaxMemoryFrequency; // out: Max memory clock frequency - D3DKMT_ALIGN64 ULONGLONG MaxMemoryFrequencyOC; // out: Clock frequency of the memory while overclocked in hertz. - D3DKMT_ALIGN64 ULONGLONG MemoryBandwidth; // out: Amount of memory transferred in bytes - D3DKMT_ALIGN64 ULONGLONG PCIEBandwidth; // out: Amount of memory transferred over PCI-E in bytes - ULONG FanRPM; // out: Fan rpm - ULONG Power; // out: Power draw of the adapter in tenths of a percentage - ULONG Temperature; // out: Temperature in deci-Celsius 1 = 0.1C - UCHAR PowerStateOverride; // out: Overrides dxgkrnls power view of linked adapters. +typedef struct _D3DKMT_ADAPTER_PERFDATA { + UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain + D3DKMT_ALIGN64 ULONGLONG MemoryFrequency; // out: Clock frequency of the memory in hertz + D3DKMT_ALIGN64 ULONGLONG MaxMemoryFrequency; // out: Max memory clock frequency + D3DKMT_ALIGN64 ULONGLONG MaxMemoryFrequencyOC; // out: Clock frequency of the memory while overclocked in hertz. + D3DKMT_ALIGN64 ULONGLONG MemoryBandwidth; // out: Amount of memory transferred in bytes + D3DKMT_ALIGN64 ULONGLONG PCIEBandwidth; // out: Amount of memory transferred over PCI-E in bytes + ULONG FanRPM; // out: Fan rpm + ULONG Power; // out: Power draw of the adapter in tenths of a percentage + ULONG Temperature; // out: Temperature in deci-Celsius 1 = 0.1C + UCHAR PowerStateOverride; // out: Overrides dxgkrnls power view of linked adapters. } D3DKMT_ADAPTER_PERFDATA; -typedef struct _D3DKMT_ADAPTER_PERFDATACAPS -{ - UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain - D3DKMT_ALIGN64 ULONGLONG MaxMemoryBandwidth; // out: Max memory bandwidth in bytes for 1 second - D3DKMT_ALIGN64 ULONGLONG MaxPCIEBandwidth; // out: Max pcie bandwidth in bytes for 1 second - ULONG MaxFanRPM; // out: Max fan rpm - ULONG TemperatureMax; // out: Max temperature before damage levels - ULONG TemperatureWarning; // out: The temperature level where throttling begins. +typedef struct _D3DKMT_ADAPTER_PERFDATACAPS { + UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain + D3DKMT_ALIGN64 ULONGLONG MaxMemoryBandwidth; // out: Max memory bandwidth in bytes for 1 second + D3DKMT_ALIGN64 ULONGLONG MaxPCIEBandwidth; // out: Max pcie bandwidth in bytes for 1 second + ULONG MaxFanRPM; // out: Max fan rpm + ULONG TemperatureMax; // out: Max temperature before damage levels + ULONG TemperatureWarning; // out: The temperature level where throttling begins. } D3DKMT_ADAPTER_PERFDATACAPS; #define DXGK_MAX_GPUVERSION_NAME_LENGTH 32 -typedef struct _D3DKMT_GPUVERSION -{ - UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain - WCHAR BiosVersion[DXGK_MAX_GPUVERSION_NAME_LENGTH]; //out: The gpu bios version - WCHAR GpuArchitecture[DXGK_MAX_GPUVERSION_NAME_LENGTH]; //out: The gpu architectures name. +typedef struct _D3DKMT_GPUVERSION { + UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain + WCHAR BiosVersion[DXGK_MAX_GPUVERSION_NAME_LENGTH]; // out: The gpu bios version + WCHAR GpuArchitecture[DXGK_MAX_GPUVERSION_NAME_LENGTH]; // out: The gpu architectures name. } D3DKMT_GPUVERSION; -typedef struct _D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER_INFORMATION -{ - D3DKMT_ADAPTER_PERFDATA AdapterPerfData; - D3DKMT_ADAPTER_PERFDATACAPS AdapterPerfDataCaps; - D3DKMT_GPUVERSION GpuVersion; +typedef struct _D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER_INFORMATION { + D3DKMT_ADAPTER_PERFDATA AdapterPerfData; + D3DKMT_ADAPTER_PERFDATACAPS AdapterPerfDataCaps; + D3DKMT_GPUVERSION GpuVersion; } D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER_INFORMATION; typedef struct _D3DKMT_QUERYSTATISTICS_PROCESS_NODE_INFORMATION { - D3DKMT_ALIGN64 UINT64 Reserved[34]; + D3DKMT_ALIGN64 UINT64 Reserved[34]; } D3DKMT_QUERYSTATISTICS_PROCESS_NODE_INFORMATION; -typedef struct _D3DKMT_NODE_PERFDATA -{ - UINT32 NodeOrdinal; // in: Node ordinal of the requested engine. - UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain - D3DKMT_ALIGN64 ULONGLONG Frequency; // out: Clock frequency of the engine in hertz - D3DKMT_ALIGN64 ULONGLONG MaxFrequency; // out: Max engine clock frequency - D3DKMT_ALIGN64 ULONGLONG MaxFrequencyOC;// out: Max engine over clock frequency - ULONG Voltage; // out: Voltage of the engine in milli volts mV - ULONG VoltageMax; // out: Max voltage levels in milli volts. - ULONG VoltageMaxOC; // out: Max voltage level while overclocked in milli volts. +typedef struct _D3DKMT_NODE_PERFDATA { + UINT32 NodeOrdinal; // in: Node ordinal of the requested engine. + UINT32 PhysicalAdapterIndex; // in: The physical adapter index, in an LDA chain + D3DKMT_ALIGN64 ULONGLONG Frequency; // out: Clock frequency of the engine in hertz + D3DKMT_ALIGN64 ULONGLONG MaxFrequency; // out: Max engine clock frequency + D3DKMT_ALIGN64 ULONGLONG MaxFrequencyOC; // out: Max engine over clock frequency + ULONG Voltage; // out: Voltage of the engine in milli volts mV + ULONG VoltageMax; // out: Max voltage levels in milli volts. + ULONG VoltageMaxOC; // out: Max voltage level while overclocked in milli volts. // WDDM 2.5 - D3DKMT_ALIGN64 ULONGLONG MaxTransitionLatency; // out: Max transition latency to change the frequency in 100 nanoseconds + D3DKMT_ALIGN64 ULONGLONG MaxTransitionLatency; // out: Max transition latency to change the frequency in 100 nanoseconds } D3DKMT_NODE_PERFDATA; typedef struct _D3DKMT_QUERYSTATISTICS_NODE_INFORMATION { - D3DKMT_QUERYSTATISTICS_PROCESS_NODE_INFORMATION GlobalInformation; //Global statistics - D3DKMT_QUERYSTATISTICS_PROCESS_NODE_INFORMATION SystemInformation; //Statistics for system thread - D3DKMT_NODE_PERFDATA NodePerfData; - UINT32 Reserved[3]; + D3DKMT_QUERYSTATISTICS_PROCESS_NODE_INFORMATION GlobalInformation; // Global statistics + D3DKMT_QUERYSTATISTICS_PROCESS_NODE_INFORMATION SystemInformation; // Statistics for system thread + D3DKMT_NODE_PERFDATA NodePerfData; + UINT32 Reserved[3]; } D3DKMT_QUERYSTATISTICS_NODE_INFORMATION; -typedef struct _D3DKMT_QUERYSTATISTICS_MEMORY_USAGE -{ +typedef struct _D3DKMT_QUERYSTATISTICS_MEMORY_USAGE { D3DKMT_ALIGN64 UINT64 AllocatedBytes; D3DKMT_ALIGN64 UINT64 FreeBytes; D3DKMT_ALIGN64 UINT64 ZeroBytes; @@ -307,45 +281,41 @@ typedef struct _D3DKMT_QUERYSTATISTICS_MEMORY_USAGE D3DKMT_ALIGN64 UINT64 StandbyBytes; } D3DKMT_QUERYSTATISTICS_MEMORY_USAGE; -typedef union _D3DKMT_QUERYSTATISTICS_RESULT -{ +typedef union _D3DKMT_QUERYSTATISTICS_RESULT { D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER_INFORMATION PhysAdapterInformation; D3DKMT_QUERYSTATISTICS_NODE_INFORMATION NodeInformation; D3DKMT_QUERYSTATISTICS_MEMORY_USAGE SegmentGroupUsageInformation; uint8_t Padding[776]; } D3DKMT_QUERYSTATISTICS_RESULT; -typedef struct _D3DKMT_QUERYSTATISTICS_QUERY_SEGMENT_GROUP_USAGE -{ +typedef struct _D3DKMT_QUERYSTATISTICS_QUERY_SEGMENT_GROUP_USAGE { UINT16 PhysicalAdapterIndex; UINT16 SegmentGroup; // D3DKMT_MEMORY_SEGMENT_GROUP } D3DKMT_QUERYSTATISTICS_QUERY_SEGMENT_GROUP_USAGE; -typedef struct _D3DKMT_QUERYSTATISTICS -{ - D3DKMT_QUERYSTATISTICS_TYPE Type; // in: type of data requested - LUID AdapterLuid; // in: adapter to get export / statistics from - HANDLE* hProcess; // in: process to get statistics for, if required for this query type +typedef struct _D3DKMT_QUERYSTATISTICS { + D3DKMT_QUERYSTATISTICS_TYPE Type; // in: type of data requested + LUID AdapterLuid; // in: adapter to get export / statistics from + HANDLE* hProcess; // in: process to get statistics for, if required for this query type D3DKMT_QUERYSTATISTICS_RESULT QueryResult; // out: requested data - union - { + union { D3DKMT_QUERYSTATISTICS_QUERY_PHYSICAL_ADAPTER QueryPhysAdapter; // in: id of physical adapter to get statistics for D3DKMT_QUERYSTATISTICS_QUERY_SEGMENT_GROUP_USAGE QuerySegmentGroupUsage; D3DKMT_QUERYSTATISTICS_QUERY_NODE2 QueryNode2; // in: id of node to get statistics for }; } D3DKMT_QUERYSTATISTICS; static_assert(sizeof(D3DKMT_QUERYSTATISTICS) == - #if SIZE_MAX == UINT64_MAX - 0x328 - #else - 0x320 - #endif -, "D3DKMT_QUERYSTATISTICS structure size mismatch"); +#if SIZE_MAX == UINT64_MAX + 0x328 +#else + 0x320 +#endif + , + "D3DKMT_QUERYSTATISTICS structure size mismatch"); #define DXGK_MAX_METADATA_NAME_LENGTH 32 -typedef enum -{ +typedef enum { DXGK_ENGINE_TYPE_OTHER, DXGK_ENGINE_TYPE_3D, DXGK_ENGINE_TYPE_VIDEO_DECODE, @@ -358,38 +328,34 @@ typedef enum DXGK_ENGINE_TYPE_VIDEO_CODEC, DXGK_ENGINE_TYPE_MAX } DXGK_ENGINE_TYPE; -typedef struct _DXGK_NODEMETADATA_FLAGS -{ - union - { +typedef struct _DXGK_NODEMETADATA_FLAGS { + union { struct { - UINT ContextSchedulingSupported : 1; // WDDM 2.2 - UINT RingBufferFenceRelease : 1; // WDDM 2.5 - UINT SupportTrackedWorkload : 1; - UINT UserModeSubmission : 1; - UINT SupportBuildTestCommandBuffer : 1; // WDDM 3.2 - UINT Reserved : 11; - UINT MaxInFlightHwQueueBuffers : 16; + UINT ContextSchedulingSupported : 1; // WDDM 2.2 + UINT RingBufferFenceRelease : 1; // WDDM 2.5 + UINT SupportTrackedWorkload : 1; + UINT UserModeSubmission : 1; + UINT SupportBuildTestCommandBuffer : 1; // WDDM 3.2 + UINT Reserved : 11; + UINT MaxInFlightHwQueueBuffers : 16; }; UINT32 Value; }; } DXGK_NODEMETADATA_FLAGS; -typedef struct _DXGK_NODEMETADATA -{ +typedef struct _DXGK_NODEMETADATA { DXGK_ENGINE_TYPE EngineType; - WCHAR FriendlyName[DXGK_MAX_METADATA_NAME_LENGTH]; + WCHAR FriendlyName[DXGK_MAX_METADATA_NAME_LENGTH]; DXGK_NODEMETADATA_FLAGS Flags; // WDDM 2.2 - BOOLEAN GpuMmuSupported; // WDDM 2.0 ??? - BOOLEAN IoMmuSupported; -} __attribute__((packed)) DXGK_NODEMETADATA; + BOOLEAN GpuMmuSupported; // WDDM 2.0 ??? + BOOLEAN IoMmuSupported; +} __attribute__((packed)) DXGK_NODEMETADATA; -typedef struct _D3DKMT_NODEMETADATA -{ - UINT NodeOrdinalAndAdapterIndex; // WDDMv2: High word is physical adapter index, low word is node ordinal +typedef struct _D3DKMT_NODEMETADATA { + UINT NodeOrdinalAndAdapterIndex; // WDDMv2: High word is physical adapter index, low word is node ordinal DXGK_NODEMETADATA NodeData; -} __attribute__((packed)) D3DKMT_NODEMETADATA; +} __attribute__((packed)) D3DKMT_NODEMETADATA; static_assert(sizeof(D3DKMT_NODEMETADATA) == 0x4E, "D3DKMT_NODEMETADATA structure size mismatch"); // Functions @@ -405,34 +371,29 @@ EXTERN_C _Check_return_ NTSTATUS APIENTRY D3DKMTQueryStatistics(_In_ CONST D3DKM #else // Ref: https://github.com/microsoft/WSL2-Linux-Kernel/blob/linux-msft-wsl-6.6.y/include/uapi/misc/d3dkmthk.h -#define LX_DXOPENADAPTERFROMLUID _IOWR(0x47, 0x01, D3DKMT_OPENADAPTERFROMLUID) -#define LX_DXQUERYADAPTERINFO _IOWR(0x47, 0x09, D3DKMT_QUERYADAPTERINFO) -#define LX_DXENUMADAPTERS2 _IOWR(0x47, 0x14, D3DKMT_ENUMADAPTERS2) -#define LX_DXCLOSEADAPTER _IOWR(0x47, 0x15, D3DKMT_CLOSEADAPTER) -#define LX_DXQUERYSTATISTICS _IOWR(0x47, 0x43, D3DKMT_QUERYSTATISTICS) +# define LX_DXOPENADAPTERFROMLUID _IOWR(0x47, 0x01, D3DKMT_OPENADAPTERFROMLUID) +# define LX_DXQUERYADAPTERINFO _IOWR(0x47, 0x09, D3DKMT_QUERYADAPTERINFO) +# define LX_DXENUMADAPTERS2 _IOWR(0x47, 0x14, D3DKMT_ENUMADAPTERS2) +# define LX_DXCLOSEADAPTER _IOWR(0x47, 0x15, D3DKMT_CLOSEADAPTER) +# define LX_DXQUERYSTATISTICS _IOWR(0x47, 0x43, D3DKMT_QUERYSTATISTICS) -static inline NTSTATUS D3DKMTOpenAdapterFromLuid(int dxgfd, const D3DKMT_OPENADAPTERFROMLUID* params) -{ +static inline NTSTATUS D3DKMTOpenAdapterFromLuid(int dxgfd, const D3DKMT_OPENADAPTERFROMLUID* params) { return ioctl(dxgfd, LX_DXOPENADAPTERFROMLUID, params); } -static inline NTSTATUS D3DKMTQueryAdapterInfo(int dxgfd, const D3DKMT_QUERYADAPTERINFO* params) -{ +static inline NTSTATUS D3DKMTQueryAdapterInfo(int dxgfd, const D3DKMT_QUERYADAPTERINFO* params) { return ioctl(dxgfd, LX_DXQUERYADAPTERINFO, params); } -static inline NTSTATUS D3DKMTCloseAdapter(int dxgfd, const D3DKMT_CLOSEADAPTER* params) -{ +static inline NTSTATUS D3DKMTCloseAdapter(int dxgfd, const D3DKMT_CLOSEADAPTER* params) { return ioctl(dxgfd, LX_DXCLOSEADAPTER, params); } -static inline NTSTATUS D3DKMTEnumAdapters2(int dxgfd, D3DKMT_ENUMADAPTERS2* params) -{ +static inline NTSTATUS D3DKMTEnumAdapters2(int dxgfd, D3DKMT_ENUMADAPTERS2* params) { return ioctl(dxgfd, LX_DXENUMADAPTERS2, params); } -static inline NTSTATUS D3DKMTQueryStatistics(int dxgfd, const D3DKMT_QUERYSTATISTICS* params) -{ +static inline NTSTATUS D3DKMTQueryStatistics(int dxgfd, const D3DKMT_QUERYSTATISTICS* params) { return ioctl(dxgfd, LX_DXQUERYSTATISTICS, params); } diff --git a/src/detection/gpu/gpu.c b/src/detection/gpu/gpu.c index b2130d56d..2687bd0ea 100644 --- a/src/detection/gpu/gpu.c +++ b/src/detection/gpu/gpu.c @@ -23,34 +23,57 @@ const char* FF_GPU_VENDOR_NAME_JINGJIA_MICRO = "Jingjia Micro"; const char* FF_GPU_VENDOR_NAME_HUAWEI = "Huawei"; const char* FF_GPU_VENDOR_NAME_ZHAOXIN = "Zhaoxin"; -const char* ffGPUGetVendorString(unsigned vendorId) -{ +const char* ffGPUGetVendorString(unsigned vendorId) { // https://devicehunt.com/all-pci-vendors - switch (vendorId) - { - case 0x106b: return FF_GPU_VENDOR_NAME_APPLE; - case 0x1002: case 0x1022: case 0x1dd8: return FF_GPU_VENDOR_NAME_AMD; - case 0x8086: case 0x8087: case 0x03e7: return FF_GPU_VENDOR_NAME_INTEL; - case 0x0955: case 0x10de: case 0x12d2: return FF_GPU_VENDOR_NAME_NVIDIA; - case 0x1ed5: return FF_GPU_VENDOR_NAME_MTHREADS; - case 0x17cb: case 0x5143: return FF_GPU_VENDOR_NAME_QUALCOMM; - case 0x14c3: return FF_GPU_VENDOR_NAME_MTK; - case 0x15ad: return FF_GPU_VENDOR_NAME_VMWARE; - case 0x1af4: return FF_GPU_VENDOR_NAME_REDHAT; - case 0x1ab8: return FF_GPU_VENDOR_NAME_PARALLEL; - case 0x1414: return FF_GPU_VENDOR_NAME_MICROSOFT; - case 0x108e: return FF_GPU_VENDOR_NAME_ORACLE; - case 0x182f: case 0x14e4: return FF_GPU_VENDOR_NAME_BROADCOM; - case 0x0014: return FF_GPU_VENDOR_NAME_LOONGSON; - case 0x0731: return FF_GPU_VENDOR_NAME_JINGJIA_MICRO; - case 0x19e5: return FF_GPU_VENDOR_NAME_HUAWEI; - case 0x1d17: return FF_GPU_VENDOR_NAME_ZHAOXIN; - default: return NULL; + switch (vendorId) { + case 0x106b: + return FF_GPU_VENDOR_NAME_APPLE; + case 0x1002: + case 0x1022: + case 0x1dd8: + return FF_GPU_VENDOR_NAME_AMD; + case 0x8086: + case 0x8087: + case 0x03e7: + return FF_GPU_VENDOR_NAME_INTEL; + case 0x0955: + case 0x10de: + case 0x12d2: + return FF_GPU_VENDOR_NAME_NVIDIA; + case 0x1ed5: + return FF_GPU_VENDOR_NAME_MTHREADS; + case 0x17cb: + case 0x5143: + return FF_GPU_VENDOR_NAME_QUALCOMM; + case 0x14c3: + return FF_GPU_VENDOR_NAME_MTK; + case 0x15ad: + return FF_GPU_VENDOR_NAME_VMWARE; + case 0x1af4: + return FF_GPU_VENDOR_NAME_REDHAT; + case 0x1ab8: + return FF_GPU_VENDOR_NAME_PARALLEL; + case 0x1414: + return FF_GPU_VENDOR_NAME_MICROSOFT; + case 0x108e: + return FF_GPU_VENDOR_NAME_ORACLE; + case 0x182f: + case 0x14e4: + return FF_GPU_VENDOR_NAME_BROADCOM; + case 0x0014: + return FF_GPU_VENDOR_NAME_LOONGSON; + case 0x0731: + return FF_GPU_VENDOR_NAME_JINGJIA_MICRO; + case 0x19e5: + return FF_GPU_VENDOR_NAME_HUAWEI; + case 0x1d17: + return FF_GPU_VENDOR_NAME_ZHAOXIN; + default: + return NULL; } } -const char* detectByOpenGL(FFlist* gpus) -{ +const char* detectByOpenGL(FFlist* gpus) { FF_DEBUG("Starting OpenGL GPU detection fallback"); FFOpenGLResult result; @@ -65,8 +88,7 @@ const char* detectByOpenGL(FFlist* gpus) const char* error = ffDetectOpenGL(&options, &result); FF_DEBUG("OpenGL detection returns: %s", error ?: "success"); - if (!error) - { + if (!error) { FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); gpu->type = FF_GPU_TYPE_UNKNOWN; ffStrbufInitMove(&gpu->vendor, &result.vendor); @@ -79,7 +101,7 @@ const char* detectByOpenGL(FFlist* gpus) gpu->coreCount = FF_GPU_CORE_COUNT_UNSET; gpu->frequency = FF_GPU_FREQUENCY_UNSET; gpu->coreUsage = FF_GPU_CORE_USAGE_UNSET; - gpu->dedicated = gpu->shared = (FFGPUMemory){0, 0}; + gpu->dedicated = gpu->shared = (FFGPUMemory) {0, 0}; gpu->deviceId = 0; FF_DEBUG("OpenGL reported renderer='%s', vendor='%s', version='%s'", @@ -87,25 +109,23 @@ const char* detectByOpenGL(FFlist* gpus) gpu->vendor.chars, result.version.chars); - if (ffStrbufContainS(&gpu->name, "Apple")) - { + if (ffStrbufContainS(&gpu->name, "Apple")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_APPLE); gpu->type = FF_GPU_TYPE_INTEGRATED; - } - else if (ffStrbufContainS(&gpu->name, "Intel")) + } else if (ffStrbufContainS(&gpu->name, "Intel")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_INTEL); - else if (ffStrbufContainS(&gpu->name, "AMD") || ffStrbufContainS(&gpu->name, "ATI")) + } else if (ffStrbufContainS(&gpu->name, "AMD") || ffStrbufContainS(&gpu->name, "ATI")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_AMD); - else if (ffStrbufContainS(&gpu->name, "NVIDIA")) + } else if (ffStrbufContainS(&gpu->name, "NVIDIA")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_NVIDIA); - else if (ffStrbufContainS(&gpu->name, "MTT")) + } else if (ffStrbufContainS(&gpu->name, "MTT")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_MTHREADS); + } FF_DEBUG("OpenGL fallback produced GPU: name='%s', vendor='%s', type=%u", gpu->name.chars, gpu->vendor.chars, gpu->type); - } ffStrbufDestroy(&result.version); @@ -116,16 +136,13 @@ const char* detectByOpenGL(FFlist* gpus) return error; } -const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) -{ +const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) { FF_DEBUG("Starting GPU detection with method=%d", (int) options->detectionMethod); - if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_PCI) - { + if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_PCI) { FF_DEBUG("Trying PCI/native GPU detection"); const char* error = ffDetectGPUImpl(options, result); - if (!error && result->length > 0) - { + if (!error && result->length > 0) { FF_DEBUG("PCI/native GPU detection succeeded with %u GPU(s)", result->length); return NULL; } @@ -134,24 +151,21 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) error ?: "none", result->length); } - if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_VULKAN) - { + if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_VULKAN) { FF_DEBUG("Trying Vulkan GPU detection fallback"); FFVulkanResult* vulkan = ffDetectVulkan(); - if (!vulkan->error && vulkan->gpus.length > 0) - { + if (!vulkan->error && vulkan->gpus.length > 0) { FF_DEBUG("Vulkan detection succeeded with %u GPU(s)", vulkan->gpus.length); ffListDestroy(result); ffListInitMove(result, &vulkan->gpus); - #ifdef __ANDROID__ +#ifdef __ANDROID__ double ffGPUDetectTempFromTZ(void); - if (options->temp && result->length == 1) - { + if (options->temp && result->length == 1) { FF_DEBUG("Applying Android thermal-zone temperature to single Vulkan GPU"); FF_LIST_GET(FFGPUResult, *result, 0)->temperature = ffGPUDetectTempFromTZ(); } - #endif +#endif return NULL; } @@ -160,12 +174,10 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) vulkan->error ?: "none", vulkan->gpus.length); } - if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_OPENCL) - { + if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_OPENCL) { FF_DEBUG("Trying OpenCL GPU detection fallback"); FFOpenCLResult* opencl = ffDetectOpenCL(); - if (!opencl->error && opencl->gpus.length > 0) - { + if (!opencl->error && opencl->gpus.length > 0) { FF_DEBUG("OpenCL detection succeeded with %u GPU(s)", opencl->gpus.length); ffListDestroy(result); ffListInitMove(result, &opencl->gpus); @@ -176,12 +188,10 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) opencl->error ?: "none", opencl->gpus.length); } - if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_OPENGL) - { + if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_OPENGL) { FF_DEBUG("Trying OpenGL GPU detection fallback"); const char* error = detectByOpenGL(result); - if (error == NULL) - { + if (error == NULL) { FF_DEBUG("OpenGL fallback succeeded with %u GPU(s)", result->length); return NULL; } diff --git a/src/detection/gpu/gpu.h b/src/detection/gpu/gpu.h index 350614152..5b6073040 100644 --- a/src/detection/gpu/gpu.h +++ b/src/detection/gpu/gpu.h @@ -5,10 +5,10 @@ #define FF_GPU_TEMP_UNSET (-DBL_MAX) #define FF_GPU_CORE_COUNT_UNSET -1 -#define FF_GPU_VMEM_SIZE_UNSET ((uint64_t)-1) +#define FF_GPU_VMEM_SIZE_UNSET ((uint64_t) -1) #define FF_GPU_FREQUENCY_UNSET 0 #define FF_GPU_CORE_USAGE_UNSET (-DBL_MAX) -#define FF_GPU_INDEX_UNSET ((uint32_t)-1) +#define FF_GPU_INDEX_UNSET ((uint32_t) -1) extern const char* FF_GPU_VENDOR_NAME_APPLE; extern const char* FF_GPU_VENDOR_NAME_AMD; @@ -28,14 +28,12 @@ extern const char* FF_GPU_VENDOR_NAME_JINGJIA_MICRO; extern const char* FF_GPU_VENDOR_NAME_HUAWEI; extern const char* FF_GPU_VENDOR_NAME_ZHAOXIN; -typedef struct FFGPUMemory -{ +typedef struct FFGPUMemory { uint64_t total; uint64_t used; } FFGPUMemory; -typedef struct FFGPUResult -{ +typedef struct FFGPUResult { uint32_t index; FFGPUType type; FFstrbuf vendor; @@ -57,8 +55,7 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus); const char* ffGPUGetVendorString(unsigned vendorId); -typedef struct FFGpuDriverPciBusId -{ +typedef struct FFGpuDriverPciBusId { uint32_t domain; uint32_t bus; uint32_t device; @@ -69,25 +66,23 @@ typedef struct FFGpuDriverPciBusId void ffGPUFillVendorAndName(uint8_t subclass, uint16_t vendor, uint16_t device, FFGPUResult* gpu); void ffGPUQueryAmdGpuName(uint16_t deviceId, uint8_t revisionId, FFGPUResult* gpu); -#if FF_HAVE_DRM +# if FF_HAVE_DRM const char* ffDrmDetectRadeon(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath); const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath); const char* ffDrmDetectI915(FFGPUResult* gpu, int fd); const char* ffDrmDetectXe(FFGPUResult* gpu, int fd); const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd); const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd); -#endif // FF_HAVE_DRM +# endif // FF_HAVE_DRM const char* ffGPUDetectDriverSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFGpuDriverPciBusId pciBusId); #endif // defined(XXX) -static inline uint64_t ffGPUPciAddr2Id(uint64_t domain, uint64_t bus, uint64_t device, uint64_t function) -{ +static inline uint64_t ffGPUPciAddr2Id(uint64_t domain, uint64_t bus, uint64_t device, uint64_t function) { return (domain << 16) | (bus << 8) | (device << 3) | function; } -static inline uint64_t ffGPUGeneral2Id(uint64_t originalId) -{ +static inline uint64_t ffGPUGeneral2Id(uint64_t originalId) { // Note: originalId may already have the MSB set return (1ULL << 63) | originalId; } diff --git a/src/detection/gpu/gpu_amd.c b/src/detection/gpu/gpu_amd.c index 428367944..5fcb45fe0 100644 --- a/src/detection/gpu/gpu_amd.c +++ b/src/detection/gpu/gpu_amd.c @@ -8,7 +8,9 @@ // Helper function to convert ADL status code to string FF_MAYBE_UNUSED static const char* ffAdlStatusToString(int status) { switch (status) { - #define FF_ADL_STATUS_CASE(name) case name: return #name; +#define FF_ADL_STATUS_CASE(name) \ + case name: \ + return #name; FF_ADL_STATUS_CASE(ADL_OK) FF_ADL_STATUS_CASE(ADL_OK_WARNING) FF_ADL_STATUS_CASE(ADL_OK_MODE_CHANGE) @@ -32,14 +34,14 @@ FF_MAYBE_UNUSED static const char* ffAdlStatusToString(int status) { FF_ADL_STATUS_CASE(ADL_ERR_NO_ADMINISTRATOR_PRIVILEGES) FF_ADL_STATUS_CASE(ADL_ERR_FEATURESYNC_NOT_STARTED) FF_ADL_STATUS_CASE(ADL_ERR_INVALID_POWER_STATE) - #undef FF_ADL_STATUS_CASE - default: return "Unknown ADL error"; +#undef FF_ADL_STATUS_CASE + default: + return "Unknown ADL error"; } } // Memory allocation function -static void* __attribute__((__stdcall__)) ffAdlMainMemoryAlloc(int iSize) -{ +static void* __attribute__((__stdcall__)) ffAdlMainMemoryAlloc(int iSize) { return malloc((size_t) iSize); } @@ -65,25 +67,21 @@ struct FFAdlData { ADL_CONTEXT_HANDLE apiHandle; } adlData; -static void shutdownAdl() -{ - if (adlData.apiHandle) - { +static void shutdownAdl() { + if (adlData.apiHandle) { FF_DEBUG("Destroying ADL context"); adlData.ffADL2_Main_Control_Destroy(adlData.apiHandle); adlData.apiHandle = NULL; } } -const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName) -{ +const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName) { FF_DEBUG("Attempting to detect AMD GPU info using '%s'", soName); - if (!adlData.inited) - { + if (!adlData.inited) { adlData.inited = true; FF_DEBUG("Initializing ADL library"); - FF_LIBRARY_LOAD(atiadl, "dlopen atiadlxx failed", soName , 1); + FF_LIBRARY_LOAD(atiadl, "dlopen atiadlxx failed", soName, 1); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(atiadl, ADL2_Main_Control_Create) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(atiadl, adlData, ADL2_Main_Control_Destroy) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(atiadl, adlData, ADL2_Adapter_AdapterInfoX3_Get) @@ -105,16 +103,16 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu int result = ffADL2_Main_Control_Create(ffAdlMainMemoryAlloc, 1 /*iEnumConnectedAdapters*/, &adlData.apiHandle); FF_DEBUG("ADL2_Main_Control_Create returned %s (%d)", ffAdlStatusToString(result), result); - if (result != ADL_OK) + if (result != ADL_OK) { return "ffADL2_Main_Control_Create() failed"; + } atexit(shutdownAdl); atiadl = NULL; // don't close atiadl FF_DEBUG("ADL initialization complete"); } - if (!adlData.apiHandle) - { + if (!adlData.apiHandle) { FF_DEBUG("ADL context not initialized"); return "ffADL2_Main_Control_Create() failed"; } @@ -124,30 +122,29 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu int adapterResult = adlData.ffADL2_Adapter_AdapterInfoX3_Get(adlData.apiHandle, -1, &numDevices, &devices); FF_DEBUG("ADL2_Adapter_AdapterInfoX3_Get returned %s (%d)", ffAdlStatusToString(adapterResult), adapterResult); - if (adapterResult == ADL_OK) - { + if (adapterResult == ADL_OK) { FF_DEBUG("found %d adapters", numDevices); - } - else - { + } else { FF_DEBUG("ffADL2_Adapter_AdapterInfoX3_Get() failed"); return "ffADL2_Adapter_AdapterInfoX3_Get() failed"; } const AdapterInfo* device = NULL; - for (int iDev = 0; iDev < numDevices; iDev++) - { - if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) - { + for (int iDev = 0; iDev < numDevices; iDev++) { + if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) { FF_DEBUG("Checking device %d: bus=%d, device=%d, func=%d against requested bus=%u, device=%u, func=%u", - iDev, devices[iDev].iBusNumber, devices[iDev].iDeviceNumber, devices[iDev].iFunctionNumber, - cond->pciBusId.bus, cond->pciBusId.device, cond->pciBusId.func); + iDev, + devices[iDev].iBusNumber, + devices[iDev].iDeviceNumber, + devices[iDev].iFunctionNumber, + cond->pciBusId.bus, + cond->pciBusId.device, + cond->pciBusId.func); if ( cond->pciBusId.bus == (uint32_t) devices[iDev].iBusNumber && cond->pciBusId.device == (uint32_t) devices[iDev].iDeviceNumber && - cond->pciBusId.func == (uint32_t) devices[iDev].iFunctionNumber) - { + cond->pciBusId.func == (uint32_t) devices[iDev].iFunctionNumber) { device = &devices[iDev]; FF_DEBUG("Found matching device: %s (index: %d)", device->strAdapterName, device->iAdapterIndex); break; @@ -155,36 +152,32 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu } } - if (!device) - { + if (!device) { FF_DEBUG("Device not found"); return "Device not found"; } - if (result.coreCount) - { + if (result.coreCount) { ADLGraphicCoreInfo coreInfo; int status = adlData.ffADL2_Adapter_Graphic_Core_Info_Get(adlData.apiHandle, device->iAdapterIndex, &coreInfo); FF_DEBUG("ADL2_Adapter_Graphic_Core_Info_Get returned %s (%d)", ffAdlStatusToString(status), status); - if (status == ADL_OK) - { + if (status == ADL_OK) { FF_DEBUG("Core info - NumCUs: %d, NumPEsPerCU: %d", coreInfo.iNumCUs, coreInfo.iNumPEsPerCU); *result.coreCount = (uint32_t) coreInfo.iNumCUs * (uint32_t) coreInfo.iNumPEsPerCU; FF_DEBUG("Got core count: %u", *result.coreCount); - } - else - { + } else { FF_DEBUG("Failed to get core count"); } } - if (result.memory) - { + if (result.memory) { int vramUsage = 0; int status = adlData.ffADL2_Adapter_DedicatedVRAMUsage_Get(adlData.apiHandle, device->iAdapterIndex, &vramUsage); FF_DEBUG("ADL2_Adapter_DedicatedVRAMUsage_Get returned %s (%d), usage: %d MB", - ffAdlStatusToString(status), status, vramUsage); + ffAdlStatusToString(status), + status, + vramUsage); if (status == ADL_OK && vramUsage >= 0) { result.memory->used = (uint64_t) vramUsage * 1024 * 1024; @@ -194,53 +187,48 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu } } - if (result.memoryType) - { + if (result.memoryType) { ADLMemoryInfo2 memoryInfo; int status = adlData.ffADL2_Adapter_MemoryInfo2_Get(adlData.apiHandle, device->iAdapterIndex, &memoryInfo); FF_DEBUG("ADL2_Adapter_MemoryInfo2_Get returned %s (%d)", ffAdlStatusToString(status), status); - if (status == ADL_OK) - { + if (status == ADL_OK) { FF_DEBUG("Memory info - Type: %s, Size: %lld MB", memoryInfo.strMemoryType, memoryInfo.iMemorySize / 1024 / 1024); ffStrbufSetS(result.memoryType, memoryInfo.strMemoryType); FF_DEBUG("Got memory type: %s", memoryInfo.strMemoryType); - } - else - { + } else { FF_DEBUG("Failed to get memory type"); } } - if (result.type) - { + if (result.type) { int asicTypes = 0; int valids = 0; int status = adlData.ffADL2_Adapter_ASICFamilyType_Get(adlData.apiHandle, device->iAdapterIndex, &asicTypes, &valids); FF_DEBUG("ADL2_Adapter_ASICFamilyType_Get returned %s (%d), asicTypes: 0x%x, valids: 0x%x", - ffAdlStatusToString(status), status, asicTypes, valids); + ffAdlStatusToString(status), + status, + asicTypes, + valids); - if (status == ADL_OK) - { + if (status == ADL_OK) { asicTypes &= valids; // This design is strange *result.type = asicTypes & ADL_ASIC_INTEGRATED ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; FF_DEBUG("GPU type: %s (asicTypes: 0x%x, valids: 0x%x)", - *result.type == FF_GPU_TYPE_INTEGRATED ? "Integrated" : "Discrete", asicTypes, valids); - } - else - { + *result.type == FF_GPU_TYPE_INTEGRATED ? "Integrated" : "Discrete", + asicTypes, + valids); + } else { FF_DEBUG("Failed to get GPU type"); } } - if (result.index) - { + if (result.index) { *result.index = (uint32_t) device->iAdapterIndex; FF_DEBUG("Setting adapter index: %u", *result.index); } - if (result.name) - { + if (result.name) { ffStrbufSetS(result.name, device->strAdapterName); FF_DEBUG("Setting adapter name: %s; UDID: %s, Present: %d, Exist: %d", device->strAdapterName, device->strUDID, device->iPresent, device->iExist); } @@ -252,121 +240,94 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu int odEnabled = 0; int status = adlData.ffADL2_Overdrive_Caps(adlData.apiHandle, device->iAdapterIndex, &odSupported, &odEnabled, &odVersion); FF_DEBUG("ADL2_Overdrive_Caps returned %s (%d); supported %d, enabled %d; version %d", - ffAdlStatusToString(status), status, odSupported, odEnabled, odVersion); - if (status != ADL_OK) - { + ffAdlStatusToString(status), + status, + odSupported, + odEnabled, + odVersion); + if (status != ADL_OK) { FF_DEBUG("Overdrive not supported, results may be inaccurate"); // Note even if Overdrive is not supported, we can still get the OD version } } - - if (odVersion == 8) - { + if (odVersion == 8) { FF_DEBUG("Using Overdrive8 API (odVersion=%d)", odVersion); - if (result.frequency) - { - ADLOD8CurrentSetting currentSetting = { .count = OD8_COUNT }; + if (result.frequency) { + ADLOD8CurrentSetting currentSetting = {.count = OD8_COUNT}; int status = adlData.ffADL2_Overdrive8_Current_Setting_Get(adlData.apiHandle, device->iAdapterIndex, ¤tSetting); FF_DEBUG("ADL2_Overdrive8_Current_Setting_Get returned %s (%d)", ffAdlStatusToString(status), status); - if (status == ADL_OK) - { + if (status == ADL_OK) { FF_DEBUG("OD8 Settings count: %d", currentSetting.count); *result.frequency = (uint32_t) currentSetting.Od8SettingTable[OD8_GFXCLK_FMAX]; FF_DEBUG("Got max engine clock (OD8_GFXCLK_FMAX): %u MHz", *result.frequency); - } - else - { + } else { FF_DEBUG("Failed to get max frequency information"); } } - if (result.temp || result.coreUsage) - { + if (result.temp || result.coreUsage) { ADLPMLogDataOutput pmLogDataOutput = {}; int status = adlData.ffADL2_New_QueryPMLogData_Get(adlData.apiHandle, device->iAdapterIndex, &pmLogDataOutput); FF_DEBUG("ADL2_New_QueryPMLogData_Get returned %s (%d)", ffAdlStatusToString(status), status); - if (status == ADL_OK) - { - if (result.temp) - { + if (status == ADL_OK) { + if (result.temp) { ADLSingleSensorData* sensor = &pmLogDataOutput.sensors[ADL_PMLOG_TEMPERATURE_HOTSPOT]; FF_DEBUG("Sensor %d: %s, supported: %d, value: %d", ADL_PMLOG_TEMPERATURE_HOTSPOT, "ADL_PMLOG_TEMPERATURE_HOTSPOT", sensor->supported, sensor->value); - if (sensor->supported) - { + if (sensor->supported) { *result.temp = sensor->value; FF_DEBUG("Temperature: %.1f°C (HOTSPOT)", *result.temp); - } - else - { + } else { sensor = &pmLogDataOutput.sensors[ADL_PMLOG_TEMPERATURE_GFX]; FF_DEBUG("Sensor %d: %s, supported: %d, value: %d", ADL_PMLOG_TEMPERATURE_GFX, "ADL_PMLOG_TEMPERATURE_GFX", sensor->supported, sensor->value); - if (sensor->supported) - { + if (sensor->supported) { *result.temp = sensor->value; FF_DEBUG("Temperature: %.1f°C (GFX)", *result.temp); - } - else - { + } else { sensor = &pmLogDataOutput.sensors[ADL_PMLOG_TEMPERATURE_SOC]; FF_DEBUG("Sensor %d: %s, supported: %d, value: %d", ADL_PMLOG_TEMPERATURE_SOC, "ADL_PMLOG_TEMPERATURE_SOC", sensor->supported, sensor->value); - if (sensor->supported) - { + if (sensor->supported) { *result.temp = sensor->value; FF_DEBUG("Temperature: %.1f°C (SOC)", *result.temp); - } - else - { + } else { FF_DEBUG("No supported temp sensor found, temp detection failed"); } } } } - if (result.coreUsage) - { + if (result.coreUsage) { ADLSingleSensorData* activity = &pmLogDataOutput.sensors[ADL_PMLOG_INFO_ACTIVITY_GFX]; FF_DEBUG("Sensor %d: %s, supported: %d, value: %d", ADL_PMLOG_INFO_ACTIVITY_GFX, "ADL_PMLOG_INFO_ACTIVITY_GFX", activity->supported, activity->value); - if (activity->supported) - { + if (activity->supported) { *result.coreUsage = activity->value; FF_DEBUG("Core usage: %.1f%%", *result.coreUsage); - } - else - { + } else { FF_DEBUG("Sensor %d not supported, GPU usage detection failed", ADL_PMLOG_INFO_ACTIVITY_GFX); } } - } - else - { + } else { FF_DEBUG("Failed to get temperature / GPU activity"); } } - } - else if (odVersion == 7) - { + } else if (odVersion == 7) { FF_DEBUG("Using OverdriveN API (odVersion=%d)", odVersion); - if (result.frequency) - { + if (result.frequency) { // https://github.com/MaynardMiner/odvii/blob/master/OverdriveN.cpp#L176 ADLODNCapabilitiesX2 odCapabilities = {}; int status = adlData.ffADL2_OverdriveN_CapabilitiesX2_Get(adlData.apiHandle, device->iAdapterIndex, &odCapabilities); FF_DEBUG("ADL2_OverdriveN_CapabilitiesX2_Get returned %s (%d)", ffAdlStatusToString(status), status); - if (status == ADL_OK) - { - if (odCapabilities.iMaximumNumberOfPerformanceLevels == 0) - { + if (status == ADL_OK) { + if (odCapabilities.iMaximumNumberOfPerformanceLevels == 0) { FF_DEBUG("ADL2_OverdriveN_CapabilitiesX2_Get: no performance levels available"); - } - else - { + } else { FF_DEBUG("ODN Capabilities - MaxPerformanceLevels: %d, GPU Clock Range: [%d - %d]", - odCapabilities.iMaximumNumberOfPerformanceLevels, - odCapabilities.sEngineClockRange.iMin, odCapabilities.sEngineClockRange.iMax); + odCapabilities.iMaximumNumberOfPerformanceLevels, + odCapabilities.sEngineClockRange.iMin, + odCapabilities.sEngineClockRange.iMax); size_t size = sizeof(ADLODNPerformanceLevelsX2) + sizeof(ADLODNPerformanceLevelX2) * ((unsigned) odCapabilities.iMaximumNumberOfPerformanceLevels - 1); FF_AUTO_FREE ADLODNPerformanceLevelsX2* odPerfLevels = calloc(size, 1); @@ -376,21 +337,18 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu int status = adlData.ffADL2_OverdriveN_SystemClocksX2_Get(adlData.apiHandle, device->iAdapterIndex, odPerfLevels); FF_DEBUG("ADL2_OverdriveN_SystemClocksX2_Get returned %s (%d), levels: %d", - ffAdlStatusToString(status), status, odPerfLevels->iNumberOfPerformanceLevels); + ffAdlStatusToString(status), + status, + odPerfLevels->iNumberOfPerformanceLevels); - if (status != ADL_OK) - { + if (status != ADL_OK) { FF_DEBUG("Failed to get frequency information"); - } - else - { + } else { // lowest to highest - for (int i = odPerfLevels->iNumberOfPerformanceLevels - 1; i >= 0 ; i--) - { + for (int i = odPerfLevels->iNumberOfPerformanceLevels - 1; i >= 0; i--) { ADLODNPerformanceLevelX2* level = &odPerfLevels->aLevels[i]; FF_DEBUG("Performance level %d: enabled: %d, engine clock = %d", i, level->iEnabled, level->iClock); - if (level->iEnabled) - { + if (level->iEnabled) { *result.frequency = (uint32_t) level->iClock / 100; // in 10 kHz FF_DEBUG("Got max engine clock: %u MHz", *result.frequency); break; @@ -398,126 +356,102 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu } } } - } - else - { + } else { FF_DEBUG("Failed to get frequency information"); } } - if (result.coreUsage) - { + if (result.coreUsage) { ADLODNPerformanceStatus performanceStatus = {}; int status = adlData.ffADL2_OverdriveN_PerformanceStatus_Get(adlData.apiHandle, device->iAdapterIndex, &performanceStatus); FF_DEBUG("ADL2_OverdriveN_PerformanceStatus_Get returned %s (%d)", ffAdlStatusToString(status), status); - if (status == ADL_OK) - { + if (status == ADL_OK) { FF_DEBUG("Performance Status - Activity: %d%%, CoreClock: %dMHz, MemoryClock: %dMHz", - performanceStatus.iGPUActivityPercent, - performanceStatus.iCoreClock, - performanceStatus.iMemoryClock); + performanceStatus.iGPUActivityPercent, + performanceStatus.iCoreClock, + performanceStatus.iMemoryClock); *result.coreUsage = performanceStatus.iGPUActivityPercent; FF_DEBUG("Got GPU activity: %d%%", performanceStatus.iGPUActivityPercent); - } - else - { + } else { FF_DEBUG("Failed to get GPU activity"); } } - if (result.temp) - { + if (result.temp) { int milliDegrees = 0; int status = adlData.ffADL2_OverdriveN_Temperature_Get(adlData.apiHandle, device->iAdapterIndex, 1, &milliDegrees); FF_DEBUG("ADL2_OverdriveN_Temperature_Get returned %s (%d)", ffAdlStatusToString(status), status); - if (status == ADL_OK) - { + if (status == ADL_OK) { *result.temp = milliDegrees / 1000.0; FF_DEBUG("Temperature: %.1f°C (raw: %d milliC)", *result.temp, milliDegrees); - } - else - { + } else { FF_DEBUG("Failed to get temperature"); } } - } - else if (odVersion == 6) - { + } else if (odVersion == 6) { FF_DEBUG("Using Overdrive6 API (odVersion=%d)", odVersion); - if (result.frequency) - { + if (result.frequency) { FF_AUTO_FREE ADLOD6StateInfo* stateInfo = calloc(sizeof(ADLOD6StateInfo) + sizeof(ADLOD6PerformanceLevel), 1); stateInfo->iNumberOfPerformanceLevels = 2; int status = adlData.ffADL2_Overdrive6_StateInfo_Get(adlData.apiHandle, device->iAdapterIndex, ADL_OD6_GETSTATEINFO_CUSTOM_PERFORMANCE, stateInfo); FF_DEBUG("ADL2_Overdrive6_StateInfo_Get returned %s (%d), performance levels: %d", - ffAdlStatusToString(status), status, stateInfo->iNumberOfPerformanceLevels); + ffAdlStatusToString(status), + status, + stateInfo->iNumberOfPerformanceLevels); - if (status == ADL_OK) - { + if (status == ADL_OK) { // OD6 uses clock ranges instead of discrete performance levels. // iNumberOfPerformanceLevels is always 2. // The 1st level indicates the minimum clocks in the range. // The 2nd level indicates the maximum clocks in the range. - if (stateInfo->iNumberOfPerformanceLevels != 2) - { + if (stateInfo->iNumberOfPerformanceLevels != 2) { FF_DEBUG("ADL2_Overdrive6_StateInfo_Get: unexpected number of performance levels: %d", stateInfo->iNumberOfPerformanceLevels); - } - else - { + } else { FF_DEBUG("OD6 Settings - MinPerformanceLevels: %d, MaxPerformanceLevels: %d", - stateInfo->aLevels[0].iEngineClock, stateInfo->aLevels[1].iEngineClock); + stateInfo->aLevels[0].iEngineClock, + stateInfo->aLevels[1].iEngineClock); *result.frequency = (uint32_t) stateInfo->aLevels[1].iEngineClock / 100; // in 10 kHz FF_DEBUG("Got max engine clock: %u MHz", *result.frequency); } - } - else - { + } else { FF_DEBUG("Failed to get frequency information"); } } - if (result.coreUsage) - { + if (result.coreUsage) { ADLOD6CurrentStatus status = {}; int apiStatus = adlData.ffADL2_Overdrive6_CurrentStatus_Get(adlData.apiHandle, device->iAdapterIndex, &status); FF_DEBUG("ADL2_Overdrive6_CurrentStatus_Get returned %s (%d)", ffAdlStatusToString(apiStatus), apiStatus); - if (apiStatus == ADL_OK) - { + if (apiStatus == ADL_OK) { *result.coreUsage = status.iActivityPercent; FF_DEBUG("Got GPU activity: %d%%", status.iActivityPercent); - } - else - { + } else { FF_DEBUG("Failed to get GPU activity"); } } - if (result.temp) - { + if (result.temp) { int milliDegrees = 0; int status = adlData.ffADL2_Overdrive6_Temperature_Get(adlData.apiHandle, device->iAdapterIndex, &milliDegrees); FF_DEBUG("ADL2_Overdrive6_Temperature_Get returned %s (%d), temperature: %d milliC", - ffAdlStatusToString(status), status, milliDegrees); + ffAdlStatusToString(status), + status, + milliDegrees); - if (status == ADL_OK) - { + if (status == ADL_OK) { *result.temp = milliDegrees / 1000.0; FF_DEBUG("Temperature: %.1f°C", *result.temp); - } - else - { + } else { FF_DEBUG("Failed to get temperature"); } } - } - else - { + } else { FF_DEBUG("Unknown Overdrive version: %d", odVersion); return "Unknown Overdrive version"; } diff --git a/src/detection/gpu/gpu_android.c b/src/detection/gpu/gpu_android.c index 029649f44..baf8a8d9e 100644 --- a/src/detection/gpu/gpu_android.c +++ b/src/detection/gpu/gpu_android.c @@ -4,50 +4,52 @@ #include -static double parseTZDir(int dfd, FFstrbuf* buffer) -{ - if (!ffReadFileBufferRelative(dfd, "type", buffer) || !ffStrbufStartsWithS(buffer, "gpu")) +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)) + 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) + 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) -{ +double ffGPUDetectTempFromTZ(void) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/thermal/"); - if(dirp) - { + 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] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; - if(!ffStrStartsWith(entry->d_name, "thermal_zone")) + } + 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) + if (subfd < 0) { continue; + } double result = parseTZDir(subfd, &buffer); - if (result != FF_GPU_TEMP_UNSET) + if (result != FF_GPU_TEMP_UNSET) { return result; + } } } return FF_GPU_TEMP_UNSET; } -const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { FF_UNUSED(options, gpus); return "No permission. Fallbacks to Vulkan, OpenCL or OpenGL instead"; } diff --git a/src/detection/gpu/gpu_apple.c b/src/detection/gpu/gpu_apple.c index 24bba84e2..bc613be74 100644 --- a/src/detection/gpu/gpu_apple.c +++ b/src/detection/gpu/gpu_apple.c @@ -7,95 +7,107 @@ const char* ffGpuDetectMetal(FFlist* gpus); const char* ffGpuDetectDriverVersion(FFlist* gpus); -static double detectGpuTemp(const FFstrbuf* gpuName) -{ +static double detectGpuTemp(const FFstrbuf* gpuName) { double result = 0; const char* error = NULL; - if (ffStrbufStartsWithS(gpuName, "Apple M")) - { - switch (strtol(gpuName->chars + strlen("Apple M"), NULL, 10)) - { - case 0: error = "Invalid Apple Silicon GPU"; break; - case 1: error = ffDetectSmcTemps(FF_TEMP_GPU_M1X, &result); break; - case 2: error = ffDetectSmcTemps(FF_TEMP_GPU_M2X, &result); break; - case 3: error = ffDetectSmcTemps(FF_TEMP_GPU_M3X, &result); break; - case 4: error = ffDetectSmcTemps(FF_TEMP_GPU_M4X, &result); break; - default: error = "Unsupported Apple Silicon GPU"; break; + if (ffStrbufStartsWithS(gpuName, "Apple M")) { + switch (strtol(gpuName->chars + strlen("Apple M"), NULL, 10)) { + case 0: + error = "Invalid Apple Silicon GPU"; + break; + case 1: + error = ffDetectSmcTemps(FF_TEMP_GPU_M1X, &result); + break; + case 2: + error = ffDetectSmcTemps(FF_TEMP_GPU_M2X, &result); + break; + case 3: + error = ffDetectSmcTemps(FF_TEMP_GPU_M3X, &result); + break; + case 4: + error = ffDetectSmcTemps(FF_TEMP_GPU_M4X, &result); + break; + default: + error = "Unsupported Apple Silicon GPU"; + break; } - } - else if (ffStrbufStartsWithS(gpuName, "Intel")) + } else if (ffStrbufStartsWithS(gpuName, "Intel")) { error = ffDetectSmcTemps(FF_TEMP_GPU_INTEL, &result); - else if (ffStrbufStartsWithS(gpuName, "Radeon") || ffStrbufStartsWithS(gpuName, "AMD")) + } else if (ffStrbufStartsWithS(gpuName, "Radeon") || ffStrbufStartsWithS(gpuName, "AMD")) { error = ffDetectSmcTemps(FF_TEMP_GPU_AMD, &result); - else + } else { error = ffDetectSmcTemps(FF_TEMP_GPU_UNKNOWN, &result); + } - if (error) + if (error) { return FF_GPU_TEMP_UNSET; + } return result; } #ifdef __aarch64__ -#include "common/apple/cf_helpers.h" +# include "common/apple/cf_helpers.h" -#include +# include -static const char* detectFrequency(FFGPUResult* gpu) -{ +static const char* detectFrequency(FFGPUResult* gpu) { // https://github.com/giampaolo/psutil/pull/2222/files FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryDevice = IOServiceGetMatchingService(MACH_PORT_NULL, IOServiceNameMatching("pmgr")); - if (!entryDevice) + if (!entryDevice) { return "IOServiceGetMatchingServices() failed"; + } - if (!IOObjectConformsTo(entryDevice, "AppleARMIODevice")) + if (!IOObjectConformsTo(entryDevice, "AppleARMIODevice")) { return "\"pmgr\" should conform to \"AppleARMIODevice\""; + } FF_CFTYPE_AUTO_RELEASE CFDataRef freqProperty = (CFDataRef) IORegistryEntryCreateCFProperty(entryDevice, CFSTR("voltage-states9-sram"), kCFAllocatorDefault, kNilOptions); - if (!freqProperty || CFGetTypeID(freqProperty) != CFDataGetTypeID()) + if (!freqProperty || CFGetTypeID(freqProperty) != CFDataGetTypeID()) { return "\"voltage-states9-sram\" in \"pmgr\" is not found"; + } // voltage-states9-sram stores supported pairs of gpu from the lowest to the highest CFIndex propLength = CFDataGetLength(freqProperty); - if (propLength == 0 || propLength % (CFIndex) sizeof(uint32_t) * 2 != 0) + if (propLength == 0 || propLength % (CFIndex) sizeof(uint32_t) * 2 != 0) { return "Invalid \"voltage-states9-sram\" length"; + } uint32_t* pStart = (uint32_t*) CFDataGetBytePtr(freqProperty); uint32_t pMax = *pStart; - for (CFIndex i = 2; i < propLength / (CFIndex) sizeof(uint32_t) && pStart[i] > 0; i += 2 /* skip voltage */) + for (CFIndex i = 2; i < propLength / (CFIndex) sizeof(uint32_t) && pStart[i] > 0; i += 2 /* skip voltage */) { pMax = pMax > pStart[i] ? pMax : pStart[i]; + } - if (pMax > 0) - { + if (pMax > 0) { // While this is not necessary for now (seems), we add this logic just in case. See cpu_apple.c - if (pMax > 100000000) // Assume that pMax is in Hz + if (pMax > 100000000) { // Assume that pMax is in Hz gpu->frequency = pMax / 1000 / 1000; - else // Assume that pMax is in kHz + } else { // Assume that pMax is in kHz gpu->frequency = pMax / 1000; + } } return NULL; } #endif -const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { FF_IOOBJECT_AUTO_RELEASE io_iterator_t iterator = IO_OBJECT_NULL; { CFMutableDictionaryRef matches = IOServiceMatching(kIOAcceleratorClassName); CFDictionaryAddValue(matches, CFSTR("IOMatchCategory"), CFSTR(kIOAcceleratorClassName)); - if (IOServiceGetMatchingServices(MACH_PORT_NULL, matches, &iterator) != kIOReturnSuccess) + if (IOServiceGetMatchingServices(MACH_PORT_NULL, matches, &iterator) != kIOReturnSuccess) { return "IOServiceGetMatchingServices() failed"; + } } io_registry_entry_t registryEntry; - while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) - { + while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { CFMutableDictionaryRef properties; - if(IORegistryEntryCreateCFProperties(registryEntry, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) - { + if (IORegistryEntryCreateCFProperties(registryEntry, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { IOObjectRelease(registryEntry); continue; } @@ -112,46 +124,44 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) ffStrbufInit(&gpu->driver); // Ok for both Apple and Intel ffCfDictGetString(properties, CFSTR("CFBundleIdentifier"), &gpu->driver); - if(ffCfDictGetInt(properties, CFSTR("gpu-core-count"), &gpu->coreCount) != NULL) // For Apple + if (ffCfDictGetInt(properties, CFSTR("gpu-core-count"), &gpu->coreCount) != NULL) { // For Apple gpu->coreCount = FF_GPU_CORE_COUNT_UNSET; + } gpu->coreUsage = FF_GPU_CORE_USAGE_UNSET; CFDictionaryRef perfStatistics = NULL; uint64_t vramUsed = 0, vramTotal = 0; - if (ffCfDictGetDict(properties, CFSTR("PerformanceStatistics"), &perfStatistics) == NULL) - { + if (ffCfDictGetDict(properties, CFSTR("PerformanceStatistics"), &perfStatistics) == NULL) { int64_t utilization; - if (ffCfDictGetInt64(perfStatistics, CFSTR("Device Utilization %"), &utilization) == NULL) + if (ffCfDictGetInt64(perfStatistics, CFSTR("Device Utilization %"), &utilization) == NULL) { gpu->coreUsage = (double) utilization; - else if (ffCfDictGetInt64(perfStatistics, CFSTR("GPU Core Utilization"), &utilization) == NULL) + } else if (ffCfDictGetInt64(perfStatistics, CFSTR("GPU Core Utilization"), &utilization) == NULL) { gpu->coreUsage = (double) utilization / 10000000.; // Nvidia? - - if (ffCfDictGetInt64(perfStatistics, CFSTR("Alloc system memory"), (int64_t*) &vramTotal) == NULL) - { - if (ffCfDictGetInt64(perfStatistics, CFSTR("In use system memory"), (int64_t*) &vramUsed) != NULL) - vramTotal = 0; } - else if (ffCfDictGetInt64(perfStatistics, CFSTR("vramFreeBytes"), (int64_t*) &vramTotal) == NULL) - { - if (ffCfDictGetInt64(perfStatistics, CFSTR("vramUsedBytes"), (int64_t*) &vramUsed) == NULL) - vramTotal += vramUsed; - else + + if (ffCfDictGetInt64(perfStatistics, CFSTR("Alloc system memory"), (int64_t*) &vramTotal) == NULL) { + if (ffCfDictGetInt64(perfStatistics, CFSTR("In use system memory"), (int64_t*) &vramUsed) != NULL) { vramTotal = 0; + } + } else if (ffCfDictGetInt64(perfStatistics, CFSTR("vramFreeBytes"), (int64_t*) &vramTotal) == NULL) { + if (ffCfDictGetInt64(perfStatistics, CFSTR("vramUsedBytes"), (int64_t*) &vramUsed) == NULL) { + vramTotal += vramUsed; + } else { + vramTotal = 0; + } } } ffStrbufInit(&gpu->name); - //IOAccelerator returns model / vendor-id properties for Apple Silicon, but not for Intel Iris GPUs. - //Still needs testing for AMD's - if(ffCfDictGetString(properties, CFSTR("model"), &gpu->name) != NULL) - { + // IOAccelerator returns model / vendor-id properties for Apple Silicon, but not for Intel Iris GPUs. + // Still needs testing for AMD's + if (ffCfDictGetString(properties, CFSTR("model"), &gpu->name) != NULL) { CFRelease(properties); properties = NULL; FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t parentEntry = 0; - if(IORegistryEntryGetParentEntry(registryEntry, kIOServicePlane, &parentEntry) != kIOReturnSuccess || - IORegistryEntryCreateCFProperties(parentEntry, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) - { + if (IORegistryEntryGetParentEntry(registryEntry, kIOServicePlane, &parentEntry) != kIOReturnSuccess || + IORegistryEntryCreateCFProperties(parentEntry, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { IOObjectRelease(registryEntry); continue; } @@ -160,27 +170,25 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) ffStrbufInit(&gpu->vendor); int vendorId; - if(ffCfDictGetInt(properties, CFSTR("vendor-id"), &vendorId) == NULL) - { + if (ffCfDictGetInt(properties, CFSTR("vendor-id"), &vendorId) == NULL) { const char* vendorStr = ffGPUGetVendorString((unsigned) vendorId); ffStrbufAppendS(&gpu->vendor, vendorStr); - if (vendorStr == FF_GPU_VENDOR_NAME_APPLE || vendorStr == FF_GPU_VENDOR_NAME_INTEL) + if (vendorStr == FF_GPU_VENDOR_NAME_APPLE || vendorStr == FF_GPU_VENDOR_NAME_INTEL) { gpu->type = FF_GPU_TYPE_INTEGRATED; - else if (vendorStr == FF_GPU_VENDOR_NAME_NVIDIA || vendorStr == FF_GPU_VENDOR_NAME_AMD) + } else if (vendorStr == FF_GPU_VENDOR_NAME_NVIDIA || vendorStr == FF_GPU_VENDOR_NAME_AMD) { gpu->type = FF_GPU_TYPE_DISCRETE; + } - #ifdef __aarch64__ - if (vendorStr == FF_GPU_VENDOR_NAME_APPLE) +#ifdef __aarch64__ + if (vendorStr == FF_GPU_VENDOR_NAME_APPLE) { detectFrequency(gpu); - #endif + } +#endif - if (gpu->type == FF_GPU_TYPE_INTEGRATED) - { + if (gpu->type == FF_GPU_TYPE_INTEGRATED) { gpu->shared.total = vramTotal; gpu->shared.used = vramUsed; - } - else if (gpu->type == FF_GPU_TYPE_DISCRETE) - { + } else if (gpu->type == FF_GPU_TYPE_DISCRETE) { gpu->dedicated.total = vramTotal; gpu->dedicated.used = vramUsed; } @@ -193,7 +201,8 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) } ffGpuDetectMetal(gpus); - if (instance.config.general.detectVersion) + if (instance.config.general.detectVersion) { ffGpuDetectDriverVersion(gpus); + } return NULL; } diff --git a/src/detection/gpu/gpu_bsd.c b/src/detection/gpu/gpu_bsd.c index 99737cac1..57e97cbad 100644 --- a/src/detection/gpu/gpu_bsd.c +++ b/src/detection/gpu/gpu_bsd.c @@ -6,29 +6,24 @@ #include #include #if __has_include() - #include // FreeBSD +# include // FreeBSD #else - #include // DragonFly +# include // DragonFly #endif -static void fillGPUTypeGeneric(FFGPUResult* gpu) -{ - if (gpu->type == FF_GPU_TYPE_UNKNOWN) - { - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) - { +static void fillGPUTypeGeneric(FFGPUResult* gpu) { + if (gpu->type == FF_GPU_TYPE_UNKNOWN) { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) { if (ffStrbufStartsWithIgnCaseS(&gpu->name, "GeForce") || ffStrbufStartsWithIgnCaseS(&gpu->name, "Quadro") || - ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) + ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) { gpu->type = FF_GPU_TYPE_DISCRETE; - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) - { - if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) { + if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) { gpu->type = FF_GPU_TYPE_DISCRETE; - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) - { + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) { // 0000:00:02.0 is reserved for Intel integrated graphics gpu->type = gpu->deviceId == ffGPUPciAddr2Id(0, 0, 2, 0) ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; } @@ -36,32 +31,32 @@ static void fillGPUTypeGeneric(FFGPUResult* gpu) } #if FF_HAVE_DRM -#include "common/library.h" -#include "common/stringUtils.h" +# include "common/library.h" +# include "common/stringUtils.h" -#include +# include -static const char* detectByDrm(const FFGPUOptions* options, FFlist* gpus) -{ +static const char* detectByDrm(const FFGPUOptions* options, FFlist* gpus) { FF_LIBRARY_LOAD_MESSAGE(libdrm, "libdrm" FF_LIBRARY_EXTENSION, 2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libdrm, drmGetDevices) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libdrm, drmFreeDevices) drmDevicePtr devices[64]; int nDevices = ffdrmGetDevices(devices, ARRAY_SIZE(devices)); - if (nDevices < 0) + if (nDevices < 0) { return "drmGetDevices() failed"; + } - for (int iDev = 0; iDev < nDevices; ++iDev) - { + for (int iDev = 0; iDev < nDevices; ++iDev) { drmDevice* dev = devices[iDev]; - if (!(dev->available_nodes & (1 << DRM_NODE_PRIMARY))) + if (!(dev->available_nodes & (1 << DRM_NODE_PRIMARY))) { continue; + } const char* path = dev->nodes[DRM_NODE_PRIMARY]; - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInit(&gpu->vendor); ffStrbufInit(&gpu->name); ffStrbufInit(&gpu->driver); @@ -76,28 +71,29 @@ static const char* detectByDrm(const FFGPUOptions* options, FFlist* gpus) gpu->deviceId = 0; gpu->frequency = FF_GPU_FREQUENCY_UNSET; - switch (dev->bustype) - { - case DRM_BUS_PCI: - ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString(dev->deviceinfo.pci->vendor_id)); - gpu->deviceId = ffGPUPciAddr2Id(dev->businfo.pci->domain, dev->businfo.pci->bus, dev->businfo.pci->dev, dev->businfo.pci->func); - break; - case DRM_BUS_HOST1X: - ffStrbufSetS(&gpu->name, dev->deviceinfo.host1x->compatible[0]); - gpu->type = FF_GPU_TYPE_INTEGRATED; - break; - case DRM_BUS_PLATFORM: - ffStrbufSetS(&gpu->name, dev->deviceinfo.platform->compatible[0]); - gpu->type = FF_GPU_TYPE_INTEGRATED; - break; - case DRM_BUS_USB: - ffStrbufSetF(&gpu->name, "USB Device (%u-%u)", dev->deviceinfo.usb->vendor, dev->deviceinfo.usb->product); - gpu->type = FF_GPU_TYPE_DISCRETE; - break; + switch (dev->bustype) { + case DRM_BUS_PCI: + ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString(dev->deviceinfo.pci->vendor_id)); + gpu->deviceId = ffGPUPciAddr2Id(dev->businfo.pci->domain, dev->businfo.pci->bus, dev->businfo.pci->dev, dev->businfo.pci->func); + break; + case DRM_BUS_HOST1X: + ffStrbufSetS(&gpu->name, dev->deviceinfo.host1x->compatible[0]); + gpu->type = FF_GPU_TYPE_INTEGRATED; + break; + case DRM_BUS_PLATFORM: + ffStrbufSetS(&gpu->name, dev->deviceinfo.platform->compatible[0]); + gpu->type = FF_GPU_TYPE_INTEGRATED; + break; + case DRM_BUS_USB: + ffStrbufSetF(&gpu->name, "USB Device (%u-%u)", dev->deviceinfo.usb->vendor, dev->deviceinfo.usb->product); + gpu->type = FF_GPU_TYPE_DISCRETE; + break; } FF_AUTO_CLOSE_FD int fd = open(path, O_RDONLY | O_CLOEXEC); - if (fd < 0) continue; + if (fd < 0) { + continue; + } char driverName[64]; driverName[0] = '\0'; @@ -105,40 +101,39 @@ static const char* detectByDrm(const FFGPUOptions* options, FFlist* gpus) .name = driverName, .name_len = ARRAY_SIZE(driverName), }; - if (ioctl(fd, DRM_IOCTL_VERSION, &ver) == 0) - { + if (ioctl(fd, DRM_IOCTL_VERSION, &ver) == 0) { driverName[ver.name_len] = '\0'; ffStrbufSetF(&gpu->driver, "%s %d.%d.%d", ver.name, ver.version_major, ver.version_minor, ver.version_patchlevel); } - if (ffStrStartsWith(driverName, "i915")) + if (ffStrStartsWith(driverName, "i915")) { ffDrmDetectI915(gpu, fd); - else if (ffStrStartsWith(driverName, "amdgpu")) + } else if (ffStrStartsWith(driverName, "amdgpu")) { ffDrmDetectAmdgpu(options, gpu, dev->nodes[DRM_NODE_RENDER]); - else if (ffStrStartsWith(driverName, "radeon")) + } else if (ffStrStartsWith(driverName, "radeon")) { ffDrmDetectRadeon(options, gpu, dev->nodes[DRM_NODE_RENDER]); - else if (ffStrStartsWith(driverName, "xe")) + } else if (ffStrStartsWith(driverName, "xe")) { ffDrmDetectXe(gpu, fd); - else if (ffStrStartsWith(driverName, "asahi")) + } else if (ffStrStartsWith(driverName, "asahi")) { ffDrmDetectAsahi(gpu, fd); - else if (ffStrStartsWith(driverName, "nouveau")) + } else if (ffStrStartsWith(driverName, "nouveau")) { ffDrmDetectNouveau(gpu, fd); - else if (dev->bustype == DRM_BUS_PCI) - { + } else if (dev->bustype == DRM_BUS_PCI) { ffGPUDetectDriverSpecific(options, gpu, (FFGpuDriverPciBusId) { - .domain = (uint32_t) dev->businfo.pci->domain, - .bus = dev->businfo.pci->bus, - .device = dev->businfo.pci->dev, - .func = dev->businfo.pci->func, - }); + .domain = (uint32_t) dev->businfo.pci->domain, + .bus = dev->businfo.pci->bus, + .device = dev->businfo.pci->dev, + .func = dev->businfo.pci->func, + }); } - if (gpu->name.length == 0) - { - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) + if (gpu->name.length == 0) { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { ffGPUQueryAmdGpuName(dev->deviceinfo.pci->device_id, dev->deviceinfo.pci->revision_id, gpu); - if (gpu->name.length == 0) + } + if (gpu->name.length == 0) { ffGPUFillVendorAndName(0, dev->deviceinfo.pci->vendor_id, dev->deviceinfo.pci->device_id, gpu); + } } fillGPUTypeGeneric(gpu); @@ -150,11 +145,11 @@ static const char* detectByDrm(const FFGPUOptions* options, FFlist* gpus) } #endif -static const char* detectByPci(const FFGPUOptions* options, FFlist* gpus) -{ +static const char* detectByPci(const FFGPUOptions* options, FFlist* gpus) { FF_AUTO_CLOSE_FD int fd = open("/dev/pci", O_RDONLY | O_CLOEXEC); - if (fd < 0) + if (fd < 0) { return "open(\"/dev/pci\", O_RDONLY | O_CLOEXEC, 0) failed"; + } struct pci_conf confs[128]; struct pci_match_conf match = { @@ -169,20 +164,22 @@ static const char* detectByPci(const FFGPUOptions* options, FFlist* gpus) .matches = confs, }; - if (ioctl(fd, PCIOCGETCONF, &pcio) < 0) + if (ioctl(fd, PCIOCGETCONF, &pcio) < 0) { return "ioctl(fd, PCIOCGETCONF, &pc) failed"; + } - if (pcio.status == PCI_GETCONF_ERROR) + if (pcio.status == PCI_GETCONF_ERROR) { return "ioctl(fd, PCIOCGETCONF, &pc) returned error"; + } - for (uint32_t i = 0; i < pcio.num_matches; ++i) - { + for (uint32_t i = 0; i < pcio.num_matches; ++i) { struct pci_conf* pc = &confs[i]; - if (pc->pc_sel.pc_func > 0 && pc->pc_subclass == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) + if (pc->pc_sel.pc_func > 0 && pc->pc_subclass == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) { continue; // Likely an auxiliary display controller (#2034) + } - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString(pc->pc_vendor)); ffStrbufInit(&gpu->name); ffStrbufInitS(&gpu->driver, pc->pd_name); @@ -198,18 +195,19 @@ static const char* detectByPci(const FFGPUOptions* options, FFlist* gpus) gpu->frequency = FF_GPU_FREQUENCY_UNSET; ffGPUDetectDriverSpecific(options, gpu, (FFGpuDriverPciBusId) { - .domain = (uint32_t) pc->pc_sel.pc_domain, - .bus = pc->pc_sel.pc_bus, - .device = pc->pc_sel.pc_dev, - .func = pc->pc_sel.pc_func, - }); + .domain = (uint32_t) pc->pc_sel.pc_domain, + .bus = pc->pc_sel.pc_bus, + .device = pc->pc_sel.pc_dev, + .func = pc->pc_sel.pc_func, + }); - if (gpu->name.length == 0) - { - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) + if (gpu->name.length == 0) { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { ffGPUQueryAmdGpuName(pc->pc_device, pc->pc_revid, gpu); - if (gpu->name.length == 0) + } + if (gpu->name.length == 0) { ffGPUFillVendorAndName(pc->pc_subclass, pc->pc_vendor, pc->pc_device, gpu); + } } fillGPUTypeGeneric(gpu); @@ -218,15 +216,15 @@ static const char* detectByPci(const FFGPUOptions* options, FFlist* gpus) return NULL; } -const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) -{ - #if FF_HAVE_DRM - if (options->detectionMethod == FF_GPU_DETECTION_METHOD_AUTO) - { +const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { +#if FF_HAVE_DRM + if (options->detectionMethod == FF_GPU_DETECTION_METHOD_AUTO) { detectByDrm(options, gpus); - if (gpus->length > 0) return NULL; + if (gpus->length > 0) { + return NULL; + } } - #endif +#endif return detectByPci(options, gpus); } diff --git a/src/detection/gpu/gpu_driver_specific.h b/src/detection/gpu/gpu_driver_specific.h index 37b4a6728..ade0940ce 100644 --- a/src/detection/gpu/gpu_driver_specific.h +++ b/src/detection/gpu/gpu_driver_specific.h @@ -2,16 +2,14 @@ #include "gpu.h" -typedef enum __attribute__((__packed__)) FFGpuDriverConditionType -{ +typedef enum __attribute__((__packed__)) FFGpuDriverConditionType { FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID = 1 << 0, FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID = 1 << 1, FF_GPU_DRIVER_CONDITION_TYPE_LUID = 1 << 2, FF_GPU_DRIVER_CONDITION_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFGpuDriverConditionType; -typedef struct FFGpuDriverPciDeviceId -{ +typedef struct FFGpuDriverPciDeviceId { uint32_t deviceId; uint32_t vendorId; uint32_t subSystemId; @@ -19,8 +17,7 @@ typedef struct FFGpuDriverPciDeviceId } FFGpuDriverPciDeviceId; // Use pciBusId if not NULL; use pciDeviceId otherwise -typedef struct FFGpuDriverCondition -{ +typedef struct FFGpuDriverCondition { FFGpuDriverConditionType type; FFGpuDriverPciBusId pciBusId; FFGpuDriverPciDeviceId pciDeviceId; @@ -28,8 +25,7 @@ typedef struct FFGpuDriverCondition } FFGpuDriverCondition; // detect x if not NULL -typedef struct FFGpuDriverResult -{ +typedef struct FFGpuDriverResult { uint32_t* index; double* temp; FFGPUMemory* memory; @@ -47,48 +43,40 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName); const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName); -FF_MAYBE_UNUSED static inline bool getDriverSpecificDetectionFn(const char* vendor, __typeof__(&ffDetectNvidiaGpuInfo)* pDetectFn, const char** pDllName) -{ - if (vendor == FF_GPU_VENDOR_NAME_NVIDIA) - { +FF_MAYBE_UNUSED static inline bool getDriverSpecificDetectionFn(const char* vendor, __typeof__(&ffDetectNvidiaGpuInfo)* pDetectFn, const char** pDllName) { + if (vendor == FF_GPU_VENDOR_NAME_NVIDIA) { *pDetectFn = ffDetectNvidiaGpuInfo; - #ifdef _WIN32 +#ifdef _WIN32 *pDllName = "nvml.dll"; - #else +#else *pDllName = "libnvidia-ml.so"; - #endif - } - else if (vendor == FF_GPU_VENDOR_NAME_MTHREADS) - { +#endif + } else if (vendor == FF_GPU_VENDOR_NAME_MTHREADS) { *pDetectFn = ffDetectMthreadsGpuInfo; - #ifdef _WIN32 +#ifdef _WIN32 *pDllName = "mtml.dll"; - #else +#else *pDllName = "libmtml.so"; - #endif +#endif } - #ifdef _WIN32 - else if (vendor == FF_GPU_VENDOR_NAME_INTEL) - { +#ifdef _WIN32 + else if (vendor == FF_GPU_VENDOR_NAME_INTEL) { *pDetectFn = ffDetectIntelGpuInfo; - #ifdef _WIN64 - *pDllName = "ControlLib.dll"; - #else - *pDllName = "ControlLib32.dll"; - #endif - } - else if (vendor == FF_GPU_VENDOR_NAME_AMD) - { +# ifdef _WIN64 + *pDllName = "ControlLib.dll"; +# else + *pDllName = "ControlLib32.dll"; +# endif + } else if (vendor == FF_GPU_VENDOR_NAME_AMD) { *pDetectFn = ffDetectAmdGpuInfo; - #ifdef _WIN64 - *pDllName = "atiadlxx.dll"; - #else - *pDllName = "atiadlxy.dll"; - #endif +# ifdef _WIN64 + *pDllName = "atiadlxx.dll"; +# else + *pDllName = "atiadlxy.dll"; +# endif } - #endif - else - { +#endif + else { *pDetectFn = NULL; *pDllName = NULL; return false; diff --git a/src/detection/gpu/gpu_drm.c b/src/detection/gpu/gpu_drm.c index 4e0477440..7e2fd651d 100644 --- a/src/detection/gpu/gpu_drm.c +++ b/src/detection/gpu/gpu_drm.c @@ -1,84 +1,87 @@ #include "gpu.h" #if FF_HAVE_DRM -#include -#include -#include +# include +# include +# include -#include "common/io.h" -#include "common/library.h" -#include "common/mallocHelper.h" -#include "common/stringUtils.h" +# include "common/io.h" +# include "common/library.h" +# include "common/mallocHelper.h" +# include "common/stringUtils.h" -#include "intel_drm.h" -#include "asahi_drm.h" -#include -#include +# include "intel_drm.h" +# include "asahi_drm.h" +# include +# include -const char* ffDrmDetectRadeon(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath) -{ +const char* ffDrmDetectRadeon(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath) { FF_AUTO_CLOSE_FD int fd = open(renderPath, O_RDONLY | O_CLOEXEC); - if (fd < 0) return "Failed to open DRM render device"; + if (fd < 0) { + return "Failed to open DRM render device"; + } uint32_t value; // https://github.com/torvalds/linux/blob/fb4d33ab452ea254e2c319bac5703d1b56d895bf/drivers/gpu/drm/radeon/radeon_kms.c#L231 if (ioctl(fd, DRM_IOCTL_RADEON_INFO, &(struct drm_radeon_info) { - .request = RADEON_INFO_ACTIVE_CU_COUNT, - .value = (uintptr_t) &value, - }) >= 0) + .request = RADEON_INFO_ACTIVE_CU_COUNT, + .value = (uintptr_t) &value, + }) >= 0) { gpu->coreCount = (int32_t) value; + } - if (options->temp) - { + if (options->temp) { if (ioctl(fd, DRM_IOCTL_RADEON_INFO, &(struct drm_radeon_info) { - .request = RADEON_INFO_CURRENT_GPU_TEMP, // millidegrees C - .value = (uintptr_t) &value, - }) >= 0 && value != 0) // 0 means unavailable + .request = RADEON_INFO_CURRENT_GPU_TEMP, // millidegrees C + .value = (uintptr_t) &value, + }) >= 0 && + value != 0) { // 0 means unavailable gpu->temperature = (double) value / 1000.0; + } } if (ioctl(fd, DRM_IOCTL_RADEON_INFO, &(struct drm_radeon_info) { - .request = RADEON_INFO_MAX_SCLK, // MHz - .value = (uintptr_t) &value, - }) >= 0) + .request = RADEON_INFO_MAX_SCLK, // MHz + .value = (uintptr_t) &value, + }) >= 0) { gpu->frequency = (uint32_t) (value / 1000u); + } - if (options->driverSpecific) - { + if (options->driverSpecific) { struct drm_radeon_gem_info gemInfo; - if (ioctl(fd, DRM_IOCTL_RADEON_GEM_INFO, &gemInfo) >= 0) - { + if (ioctl(fd, DRM_IOCTL_RADEON_GEM_INFO, &gemInfo) >= 0) { // vram_usage can be bigger than vram_usage, so we use vram_size here gpu->dedicated.total = gemInfo.vram_size; gpu->shared.total = gemInfo.gart_size; uint64_t memSize; if (ioctl(fd, DRM_IOCTL_RADEON_INFO, &(struct drm_radeon_info) { - .request = RADEON_INFO_VRAM_USAGE, // uint64_t - .value = (uintptr_t) &memSize, - }) >= 0) + .request = RADEON_INFO_VRAM_USAGE, // uint64_t + .value = (uintptr_t) &memSize, + }) >= 0) { gpu->dedicated.used = memSize; + } if (ioctl(fd, DRM_IOCTL_RADEON_INFO, &(struct drm_radeon_info) { - .request = RADEON_INFO_GTT_USAGE, // uint64_t - .value = (uintptr_t) &memSize, - }) >= 0) + .request = RADEON_INFO_GTT_USAGE, // uint64_t + .value = (uintptr_t) &memSize, + }) >= 0) { gpu->shared.used = memSize; + } } } return NULL; } -#ifdef FF_HAVE_DRM_AMDGPU -#include -#include +# ifdef FF_HAVE_DRM_AMDGPU +# include +# include -const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath) -{ -#if FF_HAVE_DRM_AMDGPU +const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath) { +# if FF_HAVE_DRM_AMDGPU FF_LIBRARY_LOAD_MESSAGE(libdrm, "libdrm_amdgpu" FF_LIBRARY_EXTENSION, 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libdrm, amdgpu_device_initialize) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libdrm, amdgpu_get_marketing_name) @@ -88,33 +91,37 @@ const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, con FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libdrm, amdgpu_device_deinitialize) FF_AUTO_CLOSE_FD int fd = open(renderPath, O_RDONLY | O_CLOEXEC); - if (fd < 0) return "Failed to open DRM render device"; + if (fd < 0) { + return "Failed to open DRM render device"; + } amdgpu_device_handle handle; uint32_t majorVersion, minorVersion; - if (ffamdgpu_device_initialize(fd, &majorVersion, &minorVersion, &handle) < 0) + if (ffamdgpu_device_initialize(fd, &majorVersion, &minorVersion, &handle) < 0) { return "Failed to initialize AMDGPU device"; + } uint32_t value; - if (options->temp) - { - if (ffamdgpu_query_sensor_info(handle, AMDGPU_INFO_SENSOR_GPU_TEMP, sizeof(value), &value) >= 0) + if (options->temp) { + if (ffamdgpu_query_sensor_info(handle, AMDGPU_INFO_SENSOR_GPU_TEMP, sizeof(value), &value) >= 0) { gpu->temperature = value / 1000.; + } } ffStrbufSetS(&gpu->name, ffamdgpu_get_marketing_name(handle)); struct amdgpu_gpu_info gpuInfo; - if (ffamdgpu_query_gpu_info(handle, &gpuInfo) >= 0) - { + if (ffamdgpu_query_gpu_info(handle, &gpuInfo) >= 0) { gpu->coreCount = (int32_t) gpuInfo.cu_active_number; gpu->frequency = (uint32_t) (gpuInfo.max_engine_clk / 1000u); gpu->index = FF_GPU_INDEX_UNSET; gpu->type = gpuInfo.ids_flags & AMDGPU_IDS_FLAGS_FUSION ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; -#define FF_VRAM_CASE(name, value) case value /* AMDGPU_VRAM_TYPE_ ## name */: ffStrbufSetStatic(&gpu->memoryType, #name); break - switch (gpuInfo.vram_type) - { +# define FF_VRAM_CASE(name, value) \ + case value /* AMDGPU_VRAM_TYPE_ ## name */: \ + ffStrbufSetStatic(&gpu->memoryType, #name); \ + break + switch (gpuInfo.vram_type) { FF_VRAM_CASE(UNKNOWN, 0); FF_VRAM_CASE(GDDR1, 1); FF_VRAM_CASE(DDR2, 2); @@ -128,44 +135,43 @@ const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, con FF_VRAM_CASE(DDR5, 10); FF_VRAM_CASE(LPDDR4, 11); FF_VRAM_CASE(LPDDR5, 12); - default: - ffStrbufAppendF(&gpu->memoryType, "Unknown (%u)", gpuInfo.vram_type); - break; + default: + ffStrbufAppendF(&gpu->memoryType, "Unknown (%u)", gpuInfo.vram_type); + break; } struct amdgpu_heap_info heapInfo; - if (ffamdgpu_query_heap_info(handle, AMDGPU_GEM_DOMAIN_VRAM, 0, &heapInfo) >= 0) - { + if (ffamdgpu_query_heap_info(handle, AMDGPU_GEM_DOMAIN_VRAM, 0, &heapInfo) >= 0) { gpu->dedicated.total = heapInfo.heap_size; gpu->dedicated.used = heapInfo.heap_usage; } - if (ffamdgpu_query_heap_info(handle, AMDGPU_GEM_DOMAIN_GTT, 0, &heapInfo) >= 0) - { + if (ffamdgpu_query_heap_info(handle, AMDGPU_GEM_DOMAIN_GTT, 0, &heapInfo) >= 0) { gpu->shared.total = heapInfo.heap_size; gpu->shared.used = heapInfo.heap_usage; } } - if (ffamdgpu_query_sensor_info(handle, AMDGPU_INFO_SENSOR_GPU_LOAD, sizeof(value), &value) >= 0) + if (ffamdgpu_query_sensor_info(handle, AMDGPU_INFO_SENSOR_GPU_LOAD, sizeof(value), &value) >= 0) { gpu->coreUsage = value; + } ffamdgpu_device_deinitialize(handle); return NULL; -#else +# else FF_UNUSED(options, gpu, renderPath); return "Fastfetch is compiled without libdrm support"; -#endif +# endif } -#endif +# endif -const char* ffDrmDetectI915(FFGPUResult* gpu, int fd) -{ +const char* ffDrmDetectI915(FFGPUResult* gpu, int fd) { { int value; - drm_i915_getparam_t getparam = { .param = I915_PARAM_EU_TOTAL, .value = &value }; - if (ioctl(fd, DRM_IOCTL_I915_GETPARAM, &getparam) >= 0) + drm_i915_getparam_t getparam = {.param = I915_PARAM_EU_TOTAL, .value = &value}; + if (ioctl(fd, DRM_IOCTL_I915_GETPARAM, &getparam) >= 0) { gpu->coreCount = value; + } } { struct drm_i915_query_item queryItem = { @@ -175,27 +181,23 @@ const char* ffDrmDetectI915(FFGPUResult* gpu, int fd) .items_ptr = (uintptr_t) &queryItem, .num_items = 1, }; - if (ioctl(fd, DRM_IOCTL_I915_QUERY, &query) >= 0 ) - { + if (ioctl(fd, DRM_IOCTL_I915_QUERY, &query) >= 0) { FF_AUTO_FREE uint8_t* buffer = calloc(1, (size_t) queryItem.length); queryItem.data_ptr = (uintptr_t) buffer; - if (ioctl(fd, DRM_IOCTL_I915_QUERY, &query) >= 0) - { + if (ioctl(fd, DRM_IOCTL_I915_QUERY, &query) >= 0) { gpu->dedicated.total = gpu->shared.total = gpu->dedicated.used = gpu->shared.used = 0; struct drm_i915_query_memory_regions* regionInfo = (void*) buffer; - for (uint32_t i = 0; i < regionInfo->num_regions; i++) - { + for (uint32_t i = 0; i < regionInfo->num_regions; i++) { struct drm_i915_memory_region_info* region = regionInfo->regions + i; - switch (region->region.memory_class) - { - case I915_MEMORY_CLASS_SYSTEM: - gpu->shared.total += region->probed_size; - gpu->shared.used += region->probed_size - region->unallocated_size; - break; - case I915_MEMORY_CLASS_DEVICE: - gpu->dedicated.total += region->probed_size; - gpu->dedicated.used += region->probed_size - region->unallocated_size; - break; + switch (region->region.memory_class) { + case I915_MEMORY_CLASS_SYSTEM: + gpu->shared.total += region->probed_size; + gpu->shared.used += region->probed_size - region->unallocated_size; + break; + case I915_MEMORY_CLASS_DEVICE: + gpu->dedicated.total += region->probed_size; + gpu->dedicated.used += region->probed_size - region->unallocated_size; + break; } } } @@ -204,54 +206,44 @@ const char* ffDrmDetectI915(FFGPUResult* gpu, int fd) return NULL; } -static inline int popcountBytes(uint8_t* bytes, uint32_t length) -{ +static inline int popcountBytes(uint8_t* bytes, uint32_t length) { int count = 0; - while (length >= 8) - { + while (length >= 8) { count += __builtin_popcountll(*(uint64_t*) bytes); bytes += 8; length -= 8; } - if (length >= 4) - { + if (length >= 4) { count += __builtin_popcountl(*(uint32_t*) bytes); bytes += 4; length -= 4; } - if (length >= 2) - { + if (length >= 2) { count += __builtin_popcountl(*(uint16_t*) bytes); bytes += 2; length -= 2; } - if (length) - { + if (length) { count += __builtin_popcountl(*(uint8_t*) bytes); } return count; } -const char* ffDrmDetectXe(FFGPUResult* gpu, int fd) -{ +const char* ffDrmDetectXe(FFGPUResult* gpu, int fd) { bool flag = false; { struct drm_xe_device_query query = { .query = DRM_XE_DEVICE_QUERY_GT_TOPOLOGY, }; - if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) - { + if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) { FF_AUTO_FREE uint8_t* buffer = malloc(query.size); query.data = (uintptr_t) buffer; - if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) - { + if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) { int dssCount = 0, euPerDssCount = 0; for (struct drm_xe_query_topology_mask* topo = (void*) buffer; (uint8_t*) topo < buffer + query.size; - topo = (void*) (topo->mask + topo->num_bytes) - ) { - switch (topo->type) - { + topo = (void*) (topo->mask + topo->num_bytes)) { + switch (topo->type) { case DRM_XE_TOPO_DSS_COMPUTE: case DRM_XE_TOPO_DSS_GEOMETRY: dssCount += popcountBytes(topo->mask, topo->num_bytes); @@ -271,19 +263,15 @@ const char* ffDrmDetectXe(FFGPUResult* gpu, int fd) struct drm_xe_device_query query = { .query = DRM_XE_DEVICE_QUERY_MEM_REGIONS, }; - if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) - { + if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) { FF_AUTO_FREE uint8_t* buffer = malloc(query.size); query.data = (uintptr_t) buffer; - if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) - { + if (ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query) >= 0) { gpu->dedicated.total = gpu->shared.total = gpu->dedicated.used = gpu->shared.used = 0; struct drm_xe_query_mem_regions* regionInfo = (void*) buffer; - for (uint32_t i = 0; i < regionInfo->num_mem_regions; i++) - { + for (uint32_t i = 0; i < regionInfo->num_mem_regions; i++) { struct drm_xe_mem_region* region = regionInfo->mem_regions + i; - switch (region->mem_class) - { + switch (region->mem_class) { case DRM_XE_MEM_REGION_CLASS_SYSMEM: gpu->shared.total += region->total_size; gpu->shared.used += region->used; @@ -301,41 +289,35 @@ const char* ffDrmDetectXe(FFGPUResult* gpu, int fd) return flag ? NULL : "Failed to query Xe GPU information"; } -const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd) -{ +const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd) { struct drm_asahi_params_global paramsGlobal = {}; if (ioctl(fd, DRM_IOCTL_ASAHI_GET_PARAMS, &(struct drm_asahi_get_params) { - .param_group = DRM_ASAHI_GET_PARAMS, - .pointer = (uintptr_t) ¶msGlobal, - .size = sizeof(paramsGlobal), - }) >= 0) - { + .param_group = DRM_ASAHI_GET_PARAMS, + .pointer = (uintptr_t) ¶msGlobal, + .size = sizeof(paramsGlobal), + }) >= 0) { // They removed `unstable_uabi_version` from the struct. Hopefully they won't introduce new ABI changes. gpu->coreCount = (int32_t) (paramsGlobal.num_clusters_total * paramsGlobal.num_cores_per_cluster); gpu->frequency = paramsGlobal.max_frequency_khz / 1000; gpu->deviceId = ffGPUGeneral2Id(paramsGlobal.chip_id); - if (!gpu->name.length) - { + if (!gpu->name.length) { const char* variant = " Unknown"; switch (paramsGlobal.gpu_variant) { - case 'G': - variant = ""; - break; - case 'S': - variant = " Pro"; - break; - case 'C': - variant = " Max"; - break; - case 'D': - variant = " Ultra"; - break; + case 'G': + variant = ""; + break; + case 'S': + variant = " Pro"; + break; + case 'C': + variant = " Max"; + break; + case 'D': + variant = " Ultra"; + break; } - ffStrbufSetF(&gpu->name, "Apple M%d%s (G%d%c %02X)", - paramsGlobal.gpu_generation - 12, variant, - paramsGlobal.gpu_generation, paramsGlobal.gpu_variant, - paramsGlobal.gpu_revision + 0xA0); + ffStrbufSetF(&gpu->name, "Apple M%d%s (G%d%c %02X)", paramsGlobal.gpu_generation - 12, variant, paramsGlobal.gpu_generation, paramsGlobal.gpu_variant, paramsGlobal.gpu_revision + 0xA0); } return NULL; @@ -344,25 +326,27 @@ const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd) return "Failed to query Asahi GPU information"; } -#ifndef DRM_IOCTL_NOUVEAU_GETPARAM -#define DRM_IOCTL_NOUVEAU_GETPARAM DRM_IOWR(DRM_COMMAND_BASE + DRM_NOUVEAU_GETPARAM, struct drm_nouveau_getparam) -#endif +# ifndef DRM_IOCTL_NOUVEAU_GETPARAM +# define DRM_IOCTL_NOUVEAU_GETPARAM DRM_IOWR(DRM_COMMAND_BASE + DRM_NOUVEAU_GETPARAM, struct drm_nouveau_getparam) +# endif -const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd) -{ - struct drm_nouveau_getparam getparam = { }; +const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd) { + struct drm_nouveau_getparam getparam = {}; getparam.param = NOUVEAU_GETPARAM_FB_SIZE; - if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0) + if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0) { gpu->dedicated.total = getparam.value; + } getparam.param = NOUVEAU_GETPARAM_AGP_SIZE; - if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0) + if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0) { gpu->shared.total = getparam.value; + } getparam.param = NOUVEAU_GETPARAM_GRAPH_UNITS; - if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0 && getparam.value < INT32_MAX) + if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0 && getparam.value < INT32_MAX) { gpu->coreCount = (int32_t) getparam.value; + } return NULL; } @@ -371,25 +355,25 @@ const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd) #include "gpu_driver_specific.h" -const char* ffGPUDetectDriverSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFGpuDriverPciBusId pciBusId) -{ +const char* ffGPUDetectDriverSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFGpuDriverPciBusId pciBusId) { __typeof__(&ffDetectNvidiaGpuInfo) detectFn; const char* soName; - if (getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &soName) && (options->temp || options->driverSpecific)) - { + if (getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &soName) && (options->temp || options->driverSpecific)) { return detectFn(&(FFGpuDriverCondition) { - .type = FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID, - .pciBusId = pciBusId, - }, (FFGpuDriverResult) { - .index = &gpu->index, - .temp = options->temp ? &gpu->temperature : NULL, - .memory = options->driverSpecific ? &gpu->dedicated : NULL, - .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : NULL, - .coreUsage = options->driverSpecific ? &gpu->coreUsage : NULL, - .type = &gpu->type, - .frequency = options->driverSpecific ? &gpu->frequency : NULL, - .name = &gpu->name, - }, soName); + .type = FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID, + .pciBusId = pciBusId, + }, + (FFGpuDriverResult) { + .index = &gpu->index, + .temp = options->temp ? &gpu->temperature : NULL, + .memory = options->driverSpecific ? &gpu->dedicated : NULL, + .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : NULL, + .coreUsage = options->driverSpecific ? &gpu->coreUsage : NULL, + .type = &gpu->type, + .frequency = options->driverSpecific ? &gpu->frequency : NULL, + .name = &gpu->name, + }, + soName); } return "No driver-specific detection function found for the GPU vendor"; diff --git a/src/detection/gpu/gpu_gnu.c b/src/detection/gpu/gpu_gnu.c index be1eedba8..91822b90d 100644 --- a/src/detection/gpu/gpu_gnu.c +++ b/src/detection/gpu/gpu_gnu.c @@ -6,69 +6,87 @@ #include enum { - PCI_VENDOR_ID = 0x00, - PCI_DEVICE_ID = 0x02, - PCI_REVISION_ID = 0x08, - PCI_CLASS_PROG = 0x09, - PCI_SUBCLASS = 0x0a, + PCI_VENDOR_ID = 0x00, + PCI_DEVICE_ID = 0x02, + PCI_REVISION_ID = 0x08, + PCI_CLASS_PROG = 0x09, + PCI_SUBCLASS = 0x0a, PCI_CLASS_DEVICE = 0x0b, - PCI_CONF_SIZE = 0x40, + PCI_CONF_SIZE = 0x40, }; -const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) { int dDomainFd = open(_SERVERS_BUS "/pci/0000", O_RDONLY | O_CLOEXEC); - if (dDomainFd < 0) return "open(_SERVERS_BUS \"/pci/0000\") failed"; + if (dDomainFd < 0) { + return "open(_SERVERS_BUS \"/pci/0000\") failed"; + } FF_AUTO_CLOSE_DIR DIR* dirDomain = fdopendir(dDomainFd); - if (dirDomain == NULL) return "fdopendir(domain) failed"; + if (dirDomain == NULL) { + return "fdopendir(domain) failed"; + } struct dirent* busEntry; - while ((busEntry = readdir(dirDomain)) != NULL) - { - if (busEntry->d_type != DT_DIR || busEntry->d_name[0] == '.') + while ((busEntry = readdir(dirDomain)) != NULL) { + if (busEntry->d_type != DT_DIR || busEntry->d_name[0] == '.') { continue; + } char* endptr; uint16_t pciBus = (uint16_t) strtoul(busEntry->d_name, &endptr, 16); - if (*endptr != '\0') continue; + if (*endptr != '\0') { + continue; + } int dBusFd = openat(dDomainFd, busEntry->d_name, O_RDONLY | O_CLOEXEC); - if (dBusFd < 0) continue; + if (dBusFd < 0) { + continue; + } FF_AUTO_CLOSE_DIR DIR* dirBus = fdopendir(dBusFd); - if (dirBus == NULL) continue; + if (dirBus == NULL) { + continue; + } struct dirent* devEntry; - while ((devEntry = readdir(dirBus)) != NULL) - { - if (devEntry->d_type != DT_DIR || devEntry->d_name[0] == '.') + while ((devEntry = readdir(dirBus)) != NULL) { + if (devEntry->d_type != DT_DIR || devEntry->d_name[0] == '.') { continue; + } uint8_t pciDev = (uint8_t) strtoul(devEntry->d_name, &endptr, 16); - if (*endptr != '\0') continue; + if (*endptr != '\0') { + continue; + } int dDevFd = openat(dBusFd, devEntry->d_name, O_RDONLY | O_CLOEXEC); - if (dDevFd < 0) continue; + if (dDevFd < 0) { + continue; + } FF_AUTO_CLOSE_DIR DIR* dirDev = fdopendir(dDevFd); - if (dirDev == NULL) continue; + if (dirDev == NULL) { + continue; + } struct dirent* funcEntry; - while ((funcEntry = readdir(dirDev)) != NULL) - { - if (funcEntry->d_type != DT_DIR || funcEntry->d_name[0] == '.') + while ((funcEntry = readdir(dirDev)) != NULL) { + if (funcEntry->d_type != DT_DIR || funcEntry->d_name[0] == '.') { continue; + } uint8_t pciFunc = (uint8_t) strtoul(funcEntry->d_name, &endptr, 16); - if (*endptr != '\0') continue; + if (*endptr != '\0') { + continue; + } char subpath[PATH_MAX]; snprintf(subpath, ARRAY_SIZE(subpath), "%s/%s/%s/%s/config", _SERVERS_BUS "/pci/0000", busEntry->d_name, devEntry->d_name, funcEntry->d_name); mach_port_t devicePort = file_name_lookup(subpath, 0, 0); - if (devicePort == MACH_PORT_NULL) + if (devicePort == MACH_PORT_NULL) { continue; + } mach_msg_type_number_t nread = 0; @@ -76,27 +94,30 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* data_t pData = (data_t) data; kern_return_t kr = pci_conf_read(devicePort, 0, &pData, &nread, PCI_CONF_SIZE); mach_port_deallocate(mach_task_self(), devicePort); - if (kr != KERN_SUCCESS || nread < PCI_CONF_SIZE) continue; + if (kr != KERN_SUCCESS || nread < PCI_CONF_SIZE) { + continue; + } - if (pData != (data_t) data) - { + if (pData != (data_t) data) { memcpy(data, pData, PCI_CONF_SIZE); - vm_deallocate(mach_task_self(), (vm_address_t)pData, nread); + vm_deallocate(mach_task_self(), (vm_address_t) pData, nread); } uint8_t classBase = data[PCI_CLASS_DEVICE]; - if (classBase != 0x03 /*PCI_BASE_CLASS_DISPLAY*/) + if (classBase != 0x03 /*PCI_BASE_CLASS_DISPLAY*/) { continue; + } uint8_t classSub = data[PCI_SUBCLASS]; - if (pciFunc > 0 && classSub == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) // Likely an auxiliary display controller (#2034) + if (pciFunc > 0 && classSub == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) { // Likely an auxiliary display controller (#2034) continue; + } uint8_t revision = data[PCI_REVISION_ID]; uint16_t vendorId = data[PCI_VENDOR_ID] | (data[PCI_VENDOR_ID + 1] << 8); uint16_t deviceId = data[PCI_DEVICE_ID] | (data[PCI_DEVICE_ID + 1] << 8); - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString(vendorId)); ffStrbufInit(&gpu->name); ffStrbufInit(&gpu->driver); @@ -110,11 +131,13 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpu->deviceId = ffGPUPciAddr2Id(0, pciBus, pciDev, pciFunc); gpu->frequency = FF_GPU_FREQUENCY_UNSET; - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { ffGPUQueryAmdGpuName(deviceId, revision, gpu); + } - if (gpu->name.length == 0) + if (gpu->name.length == 0) { ffGPUFillVendorAndName(classSub, vendorId, deviceId, gpu); + } } } } diff --git a/src/detection/gpu/gpu_haiku.c b/src/detection/gpu/gpu_haiku.c index dd7a449c9..de4f3efe4 100644 --- a/src/detection/gpu/gpu_haiku.c +++ b/src/detection/gpu/gpu_haiku.c @@ -3,10 +3,11 @@ #include -const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) { FF_AUTO_CLOSE_FD int pokefd = open(POKE_DEVICE_FULLNAME, O_RDWR | O_CLOEXEC); - if (pokefd < 0) return "open(POKE_DEVICE_FULLNAME) failed"; + if (pokefd < 0) { + return "open(POKE_DEVICE_FULLNAME) failed"; + } pci_info dev; pci_info_args cmd = { @@ -14,15 +15,16 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* .info = &dev, }; - for (cmd.index = 0; ioctl(pokefd, POKE_GET_NTH_PCI_INFO, &cmd, sizeof(cmd)) == B_OK && cmd.status == B_OK; ++cmd.index) - { - if (dev.class_base != 0x03 /*PCI_BASE_CLASS_DISPLAY*/) + for (cmd.index = 0; ioctl(pokefd, POKE_GET_NTH_PCI_INFO, &cmd, sizeof(cmd)) == B_OK && cmd.status == B_OK; ++cmd.index) { + if (dev.class_base != 0x03 /*PCI_BASE_CLASS_DISPLAY*/) { continue; + } - if (dev.function > 0 && dev.class_sub == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) + if (dev.function > 0 && dev.class_sub == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) { continue; // Likely an auxiliary display controller (#2034) + } - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString(dev.vendor_id)); ffStrbufInit(&gpu->name); ffStrbufInit(&gpu->driver); @@ -36,11 +38,13 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpu->deviceId = ffGPUPciAddr2Id(0, dev.bus, dev.device, dev.function); gpu->frequency = FF_GPU_FREQUENCY_UNSET; - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { ffGPUQueryAmdGpuName(dev.device_id, dev.revision, gpu); + } - if (gpu->name.length == 0) + if (gpu->name.length == 0) { ffGPUFillVendorAndName(dev.class_sub, dev.vendor_id, dev.device_id, gpu); + } } return NULL; diff --git a/src/detection/gpu/gpu_intel.c b/src/detection/gpu/gpu_intel.c index a255a160c..1ea67a596 100644 --- a/src/detection/gpu/gpu_intel.c +++ b/src/detection/gpu/gpu_intel.c @@ -21,21 +21,17 @@ struct FFIgclData { ctl_api_handle_t apiHandle; } igclData; -static void shutdownIgcl() -{ - if (igclData.apiHandle) - { +static void shutdownIgcl() { + if (igclData.apiHandle) { igclData.ffctlClose(igclData.apiHandle); igclData.apiHandle = NULL; } } -const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName) -{ - if (!igclData.inited) - { +const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName) { + if (!igclData.inited) { igclData.inited = true; - FF_LIBRARY_LOAD(libigcl, "dlopen igcl (ControlLib) failed", soName , 1); + FF_LIBRARY_LOAD(libigcl, "dlopen igcl (ControlLib) failed", soName, 1); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libigcl, ctlInit) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlClose) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlEnumerateDevices) @@ -49,28 +45,34 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlFrequencyGetProperties) if (ffctlInit(&(ctl_init_args_t) { - .AppVersion = CTL_IMPL_VERSION, - .flags = CTL_INIT_FLAG_USE_LEVEL_ZERO, - .Size = sizeof(ctl_init_args_t), - .Version = 0, - }, &igclData.apiHandle) != CTL_RESULT_SUCCESS) + .AppVersion = CTL_IMPL_VERSION, + .flags = CTL_INIT_FLAG_USE_LEVEL_ZERO, + .Size = sizeof(ctl_init_args_t), + .Version = 0, + }, + &igclData.apiHandle) != CTL_RESULT_SUCCESS) { return "loading igcl library failed"; + } atexit(shutdownIgcl); libigcl = NULL; // don't close igcl } - if (!igclData.apiHandle) + if (!igclData.apiHandle) { return "loading igcl library failed"; + } uint32_t deviceCount = 0; - if (igclData.ffctlEnumerateDevices(igclData.apiHandle, &deviceCount, NULL)) + if (igclData.ffctlEnumerateDevices(igclData.apiHandle, &deviceCount, NULL)) { return "ctlEnumerateDevices(NULL) failed"; - if (deviceCount == 0) + } + if (deviceCount == 0) { return "No Intel graphics adapter found"; + } FF_AUTO_FREE ctl_device_adapter_handle_t* devices = malloc(deviceCount * sizeof(*devices)); - if (igclData.ffctlEnumerateDevices(igclData.apiHandle, &deviceCount, devices)) + if (igclData.ffctlEnumerateDevices(igclData.apiHandle, &deviceCount, devices)) { return "ctlEnumerateDevices(devices) failed"; + } ctl_device_adapter_handle_t device = NULL; @@ -81,73 +83,65 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe .device_id_size = sizeof(deviceId), .Version = 2, }; - for (uint32_t iDev = 0; iDev < deviceCount; iDev++) - { - if (igclData.ffctlGetDeviceProperties(devices[iDev], &properties) != CTL_RESULT_SUCCESS) + for (uint32_t iDev = 0; iDev < deviceCount; iDev++) { + if (igclData.ffctlGetDeviceProperties(devices[iDev], &properties) != CTL_RESULT_SUCCESS) { continue; + } - if (properties.device_type != CTL_DEVICE_TYPE_GRAPHICS) + if (properties.device_type != CTL_DEVICE_TYPE_GRAPHICS) { continue; + } - if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) - { + if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) { if (cond->pciBusId.bus == properties.adapter_bdf.bus && cond->pciBusId.device == properties.adapter_bdf.device && - cond->pciBusId.func == properties.adapter_bdf.function) - { + cond->pciBusId.func == properties.adapter_bdf.function) { device = devices[iDev]; break; } - } - else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_LUID) - { - if (cond->luid == deviceId) - { + } else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_LUID) { + if (cond->luid == deviceId) { device = devices[iDev]; break; } - } - else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID) - { + } else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID) { if ( cond->pciDeviceId.deviceId == properties.pci_device_id && cond->pciDeviceId.vendorId == properties.pci_vendor_id && cond->pciDeviceId.subSystemId == (uint32_t) ((properties.pci_subsys_id << 16u) | properties.pci_subsys_vendor_id) && - cond->pciDeviceId.revId == properties.rev_id) - { + cond->pciDeviceId.revId == properties.rev_id) { device = devices[iDev]; break; } } } - if (!device) + if (!device) { return "Device not found"; + } - if (result.coreCount) + if (result.coreCount) { *result.coreCount = properties.num_slices * properties.num_sub_slices_per_slice * properties.num_eus_per_sub_slice; + } - if (result.memory) - { + if (result.memory) { ctl_mem_handle_t memoryModules[16]; uint32_t memoryCount = ARRAY_SIZE(memoryModules); - if (igclData.ffctlEnumMemoryModules(device, &memoryCount, memoryModules) == CTL_RESULT_SUCCESS && memoryCount > 0) - { + if (igclData.ffctlEnumMemoryModules(device, &memoryCount, memoryModules) == CTL_RESULT_SUCCESS && memoryCount > 0) { result.memory->used = 0; result.memory->total = 0; - for (uint32_t iMem = 0; iMem < memoryCount; iMem++) - { + for (uint32_t iMem = 0; iMem < memoryCount; iMem++) { ctl_mem_properties_t memoryProperties = { .Size = sizeof(memoryProperties), .Version = 0, }; - if (igclData.ffctlMemoryGetProperties(memoryModules[iMem], &memoryProperties) == CTL_RESULT_SUCCESS) - { - if (memoryProperties.location == CTL_MEM_LOC_DEVICE && result.memoryType) - { - switch (memoryProperties.type) - { - #define FF_ICTL_MEM_TYPE_CASE(type) case CTL_MEM_TYPE_##type: ffStrbufSetStatic(result.memoryType, #type); break + if (igclData.ffctlMemoryGetProperties(memoryModules[iMem], &memoryProperties) == CTL_RESULT_SUCCESS) { + if (memoryProperties.location == CTL_MEM_LOC_DEVICE && result.memoryType) { + switch (memoryProperties.type) { +#define FF_ICTL_MEM_TYPE_CASE(type) \ + case CTL_MEM_TYPE_##type: \ + ffStrbufSetStatic(result.memoryType, #type); \ + break FF_ICTL_MEM_TYPE_CASE(HBM); FF_ICTL_MEM_TYPE_CASE(DDR); FF_ICTL_MEM_TYPE_CASE(DDR3); @@ -163,7 +157,7 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe FF_ICTL_MEM_TYPE_CASE(GDDR6); FF_ICTL_MEM_TYPE_CASE(GDDR6X); FF_ICTL_MEM_TYPE_CASE(GDDR7); - #undef FF_ICTL_MEM_TYPE_CASE +#undef FF_ICTL_MEM_TYPE_CASE default: ffStrbufSetF(result.memoryType, "Unknown (%u)", memoryProperties.type); break; @@ -174,15 +168,11 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe .Size = sizeof(ctl_mem_state_t), .Version = 0, }; - if (igclData.ffctlMemoryGetState(memoryModules[iMem], &memoryState) == CTL_RESULT_SUCCESS) - { - if (memoryProperties.location == CTL_MEM_LOC_DEVICE) - { + if (igclData.ffctlMemoryGetState(memoryModules[iMem], &memoryState) == CTL_RESULT_SUCCESS) { + if (memoryProperties.location == CTL_MEM_LOC_DEVICE) { result.memory->total += memoryState.size; result.memory->used += memoryState.size - memoryState.free; - } - else if (result.sharedMemory && memoryProperties.location == CTL_MEM_LOC_SYSTEM) - { + } else if (result.sharedMemory && memoryProperties.location == CTL_MEM_LOC_SYSTEM) { result.sharedMemory->total += memoryState.size; result.sharedMemory->used += memoryState.size - memoryState.free; } @@ -192,27 +182,22 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe } } - if (result.type) - { + if (result.type) { *result.type = properties.graphics_adapter_properties & CTL_ADAPTER_PROPERTIES_FLAG_INTEGRATED - ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; + ? FF_GPU_TYPE_INTEGRATED + : FF_GPU_TYPE_DISCRETE; } - if (result.temp) - { + if (result.temp) { ctl_temp_handle_t sensors[16]; uint32_t sensorCount = ARRAY_SIZE(sensors); - if (igclData.ffctlEnumTemperatureSensors(device, &sensorCount, sensors) == CTL_RESULT_SUCCESS && sensorCount > 0) - { - for (uint32_t iSensor = 0; iSensor < sensorCount; iSensor++) - { - ctl_temp_properties_t props = { .Size = sizeof(props) }; + if (igclData.ffctlEnumTemperatureSensors(device, &sensorCount, sensors) == CTL_RESULT_SUCCESS && sensorCount > 0) { + for (uint32_t iSensor = 0; iSensor < sensorCount; iSensor++) { + ctl_temp_properties_t props = {.Size = sizeof(props)}; // The official sample code does not set Version // https://github.com/intel/drivers.gpu.control-library/blob/1bbacbf3814f2fd0d2b930cdf42fad83f3628db9/Samples/Telemetry_Samples/Sample_TelemetryAPP.cpp#L256 - if (igclData.ffctlTemperatureGetProperties(sensors[iSensor], &props) == CTL_RESULT_SUCCESS) - { - if (props.type == CTL_TEMP_SENSORS_GPU) - { + if (igclData.ffctlTemperatureGetProperties(sensors[iSensor], &props) == CTL_RESULT_SUCCESS) { + if (props.type == CTL_TEMP_SENSORS_GPU) { *result.temp = props.maxTemperature; break; } @@ -221,28 +206,26 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe } } - if (result.frequency) - { + if (result.frequency) { ctl_freq_handle_t domains[16]; uint32_t domainCount = ARRAY_SIZE(domains); - if (igclData.ffctlEnumFrequencyDomains(device, &domainCount, domains) == CTL_RESULT_SUCCESS && domainCount > 0) - { + if (igclData.ffctlEnumFrequencyDomains(device, &domainCount, domains) == CTL_RESULT_SUCCESS && domainCount > 0) { double maxValue = 0; - ctl_freq_properties_t props = { .Size = sizeof(props), .Version = 0 }; - for (uint32_t iDomain = 0; iDomain < domainCount; iDomain++) - { - if (igclData.ffctlFrequencyGetProperties(domains[iDomain], &props) == CTL_RESULT_SUCCESS) - { - if (props.type == CTL_FREQ_DOMAIN_GPU && props.max > maxValue) + ctl_freq_properties_t props = {.Size = sizeof(props), .Version = 0}; + for (uint32_t iDomain = 0; iDomain < domainCount; iDomain++) { + if (igclData.ffctlFrequencyGetProperties(domains[iDomain], &props) == CTL_RESULT_SUCCESS) { + if (props.type == CTL_FREQ_DOMAIN_GPU && props.max > maxValue) { maxValue = props.max; + } } } *result.frequency = (uint32_t) (maxValue + 0.5); } } - if (result.name) + if (result.name) { ffStrbufSetS(result.name, properties.name); + } return NULL; } diff --git a/src/detection/gpu/gpu_linux.c b/src/detection/gpu/gpu_linux.c index 637f6e99a..dae9895f6 100644 --- a/src/detection/gpu/gpu_linux.c +++ b/src/detection/gpu/gpu_linux.c @@ -13,69 +13,63 @@ #include #ifdef FF_HAVE_DRM_AMDGPU - #include - #include - #include +# include +# include +# include #endif #ifdef FF_HAVE_DRM - #include "intel_drm.h" - #include - #include +# include "intel_drm.h" +# include +# include #endif #if defined(FF_HAVE_DRM) && defined(__aarch64__) - // https://github.com/alyssarosenzweig/linux/blob/agx-uapi-v7/include/uapi/drm/asahi_drm.h - // Found in kernel-headers-6.14.4-400.asahi.fc42.aarch64 - #if __has_include() - #include - #else - #include "asahi_drm.h" - #endif - #define FF_HAVE_DRM_ASAHI 1 +// https://github.com/alyssarosenzweig/linux/blob/agx-uapi-v7/include/uapi/drm/asahi_drm.h +// Found in kernel-headers-6.14.4-400.asahi.fc42.aarch64 +# if __has_include() +# include +# else +# include "asahi_drm.h" +# endif +# define FF_HAVE_DRM_ASAHI 1 #endif -static bool pciDetectDriver(FFstrbuf* result, FFstrbuf* pciDir, FFstrbuf* buffer, FF_MAYBE_UNUSED const char* drmKey) -{ +static bool pciDetectDriver(FFstrbuf* result, FFstrbuf* pciDir, FFstrbuf* buffer, FF_MAYBE_UNUSED const char* drmKey) { uint32_t pciDirLength = pciDir->length; ffStrbufAppendS(pciDir, "/driver"); char pathBuf[PATH_MAX]; ssize_t resultLength = readlink(pciDir->chars, pathBuf, ARRAY_SIZE(pathBuf)); - if(resultLength <= 0) return false; + if (resultLength <= 0) { + return false; + } const char* slash = memrchr(pathBuf, '/', (size_t) resultLength); - if (slash) - { + if (slash) { slash++; ffStrbufSetNS(result, (uint32_t) (resultLength - (slash - pathBuf)), slash); } - if (ffStrbufEqualS(result, "nvidia")) - { - if (ffReadFileBuffer("/proc/driver/nvidia/version", buffer)) - { - if (ffStrbufContainS(buffer, " Open ")) + if (ffStrbufEqualS(result, "nvidia")) { + if (ffReadFileBuffer("/proc/driver/nvidia/version", buffer)) { + if (ffStrbufContainS(buffer, " Open ")) { ffStrbufAppendS(result, " (open source)"); - else + } else { ffStrbufAppendS(result, " (proprietary)"); + } } } - if (instance.config.general.detectVersion) - { + if (instance.config.general.detectVersion) { ffStrbufAppendS(pciDir, "/module/version"); - if (ffReadFileBuffer(pciDir->chars, buffer)) - { + if (ffReadFileBuffer(pciDir->chars, buffer)) { ffStrbufTrimRightSpace(buffer); ffStrbufAppendC(result, ' '); ffStrbufAppend(result, buffer); - } - else if (ffStrbufEqualS(result, "zx")) - { + } else if (ffStrbufEqualS(result, "zx")) { ffStrbufSubstrBefore(pciDir, pciDirLength); ffStrbufAppendS(pciDir, "/zx_info/driver_version"); - if (ffReadFileBuffer(pciDir->chars, buffer)) - { + if (ffReadFileBuffer(pciDir->chars, buffer)) { ffStrbufTrimRightSpace(buffer); ffStrbufAppendC(result, ' '); ffStrbufAppend(result, buffer); @@ -86,18 +80,17 @@ static bool pciDetectDriver(FFstrbuf* result, FFstrbuf* pciDir, FFstrbuf* buffer return true; } -FF_MAYBE_UNUSED static const char* drmFindRenderFromCard(const char* drmCardKey, FFstrbuf* result) -{ +FF_MAYBE_UNUSED static const char* drmFindRenderFromCard(const char* drmCardKey, FFstrbuf* result) { char path[PATH_MAX]; sprintf(path, "/sys/class/drm/%s/device/drm", drmCardKey); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(path); - if (!dirp) return "Failed to open `/sys/class/drm/{drmCardKey}/device/drm`"; + if (!dirp) { + return "Failed to open `/sys/class/drm/{drmCardKey}/device/drm`"; + } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (ffStrStartsWith(entry->d_name, "render")) - { + while ((entry = readdir(dirp)) != NULL) { + if (ffStrStartsWith(entry->d_name, "render")) { ffStrbufSetS(result, "/dev/dri/"); ffStrbufAppendS(result, entry->d_name); return NULL; @@ -106,137 +99,142 @@ FF_MAYBE_UNUSED static const char* drmFindRenderFromCard(const char* drmCardKey, return "Failed to find render device"; } -static const char* drmDetectAmdSpecific(const FFGPUOptions* options, FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer) -{ - #if FF_HAVE_DRM +static const char* drmDetectAmdSpecific(const FFGPUOptions* options, FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer) { +#if FF_HAVE_DRM const char* error = drmFindRenderFromCard(drmKey, buffer); - if (error) return error; - if (ffStrbufEqualS(&gpu->driver, "radeon")) + if (error) { + return error; + } + if (ffStrbufEqualS(&gpu->driver, "radeon")) { return ffDrmDetectRadeon(options, gpu, buffer->chars); - else - { - #if FF_HAVE_DRM_AMDGPU + } else { +# if FF_HAVE_DRM_AMDGPU return ffDrmDetectAmdgpu(options, gpu, buffer->chars); - #else +# else FF_UNUSED(options, gpu, drmKey, buffer); return "Fastfetch is not compiled with libdrm_amdgpu support"; - #endif +# endif } - #else +#else FF_UNUSED(options, gpu, drmKey, buffer); return "Fastfetch is not compiled with drm support"; - #endif +#endif } -static void pciDetectAmdSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer) -{ +static void pciDetectAmdSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer) { // https://www.kernel.org/doc/html/v5.10/gpu/amdgpu.html#mem-info-vis-vram-total const uint32_t pciDirLen = pciDir->length; ffStrbufAppendS(pciDir, "/hwmon/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pciDir->chars); - if (!dirp) return; + if (!dirp) { + return; + } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.') continue; + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { + continue; + } break; } - if (!entry) return; + if (!entry) { + return; + } ffStrbufAppendS(pciDir, entry->d_name); ffStrbufAppendC(pciDir, '/'); const uint32_t hwmonLen = pciDir->length; uint64_t value = 0; - if (options->temp) - { + if (options->temp) { ffStrbufAppendS(pciDir, "temp1_input"); // The on die GPU temperature in millidegrees Celsius - if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) + if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) { gpu->temperature = (double) value / 1000; + } } if (ffStrbufEqualS(&gpu->driver, "amdgpu")) // Ancient radeon drivers don't have these files { ffStrbufSubstrBefore(pciDir, hwmonLen); ffStrbufAppendS(pciDir, "in1_input"); // Northbridge voltage in millivolts (APUs only) - if (ffPathExists(pciDir->chars, FF_PATHTYPE_ANY)) + if (ffPathExists(pciDir->chars, FF_PATHTYPE_ANY)) { gpu->type = FF_GPU_TYPE_INTEGRATED; - else + } else { gpu->type = FF_GPU_TYPE_DISCRETE; + } - if (options->driverSpecific) - { + if (options->driverSpecific) { ffStrbufSubstrBefore(pciDir, pciDirLen); ffStrbufAppendS(pciDir, "/mem_info_vis_vram_total"); - if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) - { - if (gpu->type == FF_GPU_TYPE_DISCRETE) + if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) { + if (gpu->type == FF_GPU_TYPE_DISCRETE) { gpu->dedicated.total = value; - else + } else { gpu->shared.total = value; + } ffStrbufSubstrBefore(pciDir, pciDir->length - (uint32_t) strlen("/mem_info_vis_vram_total")); ffStrbufAppendS(pciDir, "/mem_info_vis_vram_used"); - if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) - { - if (gpu->type == FF_GPU_TYPE_DISCRETE) + if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) { + if (gpu->type == FF_GPU_TYPE_DISCRETE) { gpu->dedicated.used = value; - else + } else { gpu->shared.used = value; + } } } ffStrbufSubstrBefore(pciDir, pciDirLen); ffStrbufAppendS(pciDir, "/gpu_busy_percent"); - if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) + if (ffReadFileBuffer(pciDir->chars, buffer) && (value = ffStrbufToUInt(buffer, 0))) { gpu->coreUsage = (double) value; + } } } } -static void pciDetectIntelSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer, const char* drmKey) -{ +static void pciDetectIntelSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer, const char* drmKey) { // Works for Intel GPUs // https://patchwork.kernel.org/project/intel-gfx/patch/1422039866-11572-3-git-send-email-ville.syrjala@linux.intel.com/ // 0000:00:02.0 is reserved for Intel integrated graphics gpu->type = gpu->deviceId == ffGPUPciAddr2Id(0, 0, 2, 0) ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; - if (!drmKey) return; + if (!drmKey) { + return; + } const uint32_t pciDirLen = pciDir->length; bool isXE = ffStrbufEqualS(&gpu->driver, "xe"); - if (isXE) + if (isXE) { ffStrbufAppendS(pciDir, "/tile0/gt0/freq0/max_freq"); - else + } else { ffStrbufAppendF(pciDir, "/drm/%s/gt_max_freq_mhz", drmKey); - if (ffReadFileBuffer(pciDir->chars, buffer)) + } + if (ffReadFileBuffer(pciDir->chars, buffer)) { gpu->frequency = (uint32_t) ffStrbufToUInt(buffer, 0); + } ffStrbufSubstrBefore(pciDir, pciDirLen); - if (options->temp) - { + if (options->temp) { ffStrbufAppendS(pciDir, "/hwmon/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pciDir->chars); - if (dirp) - { + if (dirp) { struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.') continue; + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { + continue; + } ffStrbufSubstrBefore(pciDir, pciDirLen + strlen("/hwmon/")); ffStrbufAppendS(pciDir, entry->d_name); // https://github.com/Syllo/nvtop/blob/73291884d926445e499d6b9b71cb7a9bdbc7c393/src/extract_gpuinfo_intel.c#L279-L281 ffStrbufAppendS(pciDir, isXE ? "/temp2_input" : "/temp1_input"); - if (ffReadFileBuffer(pciDir->chars, buffer)) - { + if (ffReadFileBuffer(pciDir->chars, buffer)) { uint64_t value = ffStrbufToUInt(buffer, 0); - if (value > 0) - { + if (value > 0) { gpu->temperature = (double) value / 1000; break; } @@ -247,44 +245,45 @@ static void pciDetectIntelSpecific(const FFGPUOptions* options, FFGPUResult* gpu } } -static const char* drmDetectIntelSpecific(FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer) -{ - #if FF_HAVE_DRM +static const char* drmDetectIntelSpecific(FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer) { +#if FF_HAVE_DRM ffStrbufSetS(buffer, "/dev/dri/"); ffStrbufAppendS(buffer, drmKey); FF_AUTO_CLOSE_FD int fd = open(buffer->chars, O_RDONLY | O_CLOEXEC); - if (fd < 0) return "Failed to open drm device"; + if (fd < 0) { + return "Failed to open drm device"; + } - if (ffStrbufEqualS(&gpu->driver, "xe")) + if (ffStrbufEqualS(&gpu->driver, "xe")) { return ffDrmDetectXe(gpu, fd); - else if (ffStrbufEqualS(&gpu->driver, "i915")) + } else if (ffStrbufEqualS(&gpu->driver, "i915")) { return ffDrmDetectI915(gpu, fd); + } return "Unknown Intel GPU driver"; - #else +#else FF_UNUSED(gpu, drmKey, buffer); return "Fastfetch is not compiled with drm support"; - #endif +#endif } -static const char* pciDetectTempGeneral(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer) -{ - if (options->temp) - { +static const char* pciDetectTempGeneral(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer) { + if (options->temp) { const uint32_t pciDirLen = pciDir->length; ffStrbufAppendS(pciDir, "/hwmon/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pciDir->chars); - if (dirp) - { + if (dirp) { struct dirent* entry; - while ((entry = readdir(dirp))) - { - if (entry->d_name[0] == '.') continue; + while ((entry = readdir(dirp))) { + if (entry->d_name[0] == '.') { + continue; + } ffStrbufAppendS(pciDir, entry->d_name); ffStrbufAppendS(pciDir, "/temp1_input"); - if (ffReadFileBuffer(pciDir->chars, buffer)) - { + if (ffReadFileBuffer(pciDir->chars, buffer)) { uint64_t value = ffStrbufToUInt(buffer, 0); - if (value > 0) gpu->temperature = (double) value / 1000.0; + if (value > 0) { + gpu->temperature = (double) value / 1000.0; + } } break; } @@ -294,54 +293,55 @@ static const char* pciDetectTempGeneral(const FFGPUOptions* options, FFGPUResult return NULL; } -static const char* drmDetectNouveauSpecific(FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer) -{ - #if FF_HAVE_DRM +static const char* drmDetectNouveauSpecific(FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer) { +#if FF_HAVE_DRM ffStrbufSetS(buffer, "/dev/dri/"); ffStrbufAppendS(buffer, drmKey); FF_AUTO_CLOSE_FD int fd = open(buffer->chars, O_RDONLY | O_CLOEXEC); - if (fd < 0) return "Failed to open drm device"; + if (fd < 0) { + return "Failed to open drm device"; + } return ffDrmDetectNouveau(gpu, fd); - #else +#else FF_UNUSED(gpu, drmKey, buffer); return "Fastfetch is not compiled with drm support"; - #endif +#endif } -static const char* pciDetectZxSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer) -{ +static const char* pciDetectZxSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer) { gpu->type = FF_GPU_TYPE_INTEGRATED; const uint32_t pciDirLen = pciDir->length; ffStrbufAppendS(pciDir, "/zx_info/eclk"); - if (ffReadFileBuffer(pciDir->chars, buffer)) + if (ffReadFileBuffer(pciDir->chars, buffer)) { gpu->frequency = (uint32_t) ffStrbufToUInt(buffer, FF_GPU_FREQUENCY_UNSET); + } ffStrbufSubstrBefore(pciDir, pciDirLen); - if (options->driverSpecific) - { + if (options->driverSpecific) { ffStrbufAppendS(pciDir, "/zx_info/engine_3d_usage"); - if (ffReadFileBuffer(pciDir->chars, buffer)) + if (ffReadFileBuffer(pciDir->chars, buffer)) { gpu->coreUsage = ffStrbufToDouble(buffer, FF_GPU_CORE_USAGE_UNSET); + } ffStrbufSubstrBefore(pciDir, pciDirLen); ffStrbufAppendS(pciDir, "/zx_info/fb_size"); - if (ffReadFileBuffer(pciDir->chars, buffer)) + if (ffReadFileBuffer(pciDir->chars, buffer)) { gpu->shared.total = ffStrbufToUInt(buffer, FF_GPU_VMEM_SIZE_UNSET); + } ffStrbufSubstrBefore(pciDir, pciDirLen); - if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) - { + if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) { gpu->shared.total *= 1024 * 1024; ffStrbufAppendS(pciDir, "/zx_info/free_fb_mem"); - if (ffReadFileBuffer(pciDir->chars, buffer)) + if (ffReadFileBuffer(pciDir->chars, buffer)) { gpu->shared.used = ffStrbufToUInt(buffer, FF_GPU_VMEM_SIZE_UNSET); + } ffStrbufSubstrBefore(pciDir, pciDirLen); - if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) - { + if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) { gpu->shared.used *= 1024 * 1024; gpu->shared.used = gpu->shared.total - gpu->shared.used; } @@ -351,46 +351,48 @@ static const char* pciDetectZxSpecific(const FFGPUOptions* options, FFGPUResult* return NULL; } -static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf* buffer, FFstrbuf* deviceDir, const char* drmKey) -{ +static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf* buffer, FFstrbuf* deviceDir, const char* drmKey) { const uint32_t drmDirPathLength = deviceDir->length; uint32_t vendorId, deviceId, subVendorId, subDeviceId; uint8_t classId, subclassId; - if (sscanf(buffer->chars + strlen("pci:"), "v%8" SCNx32 "d%8" SCNx32 "sv%8" SCNx32 "sd%8" SCNx32 "bc%2" SCNx8 "sc%2" SCNx8, &vendorId, &deviceId, &subVendorId, &subDeviceId, &classId, &subclassId) != 6) + if (sscanf(buffer->chars + strlen("pci:"), "v%8" SCNx32 "d%8" SCNx32 "sv%8" SCNx32 "sd%8" SCNx32 "bc%2" SCNx8 "sc%2" SCNx8, &vendorId, &deviceId, &subVendorId, &subDeviceId, &classId, &subclassId) != 6) { return "Failed to parse pci modalias"; + } - if (classId != 0x03 /*PCI_BASE_CLASS_DISPLAY*/) + if (classId != 0x03 /*PCI_BASE_CLASS_DISPLAY*/) { return "Not a GPU device"; + } char pciPath[PATH_MAX]; const char* pPciPath = NULL; - if (drmKey) - { + if (drmKey) { ssize_t pathLength = readlink(deviceDir->chars, pciPath, ARRAY_SIZE(pciPath) - 1); - if (pathLength <= 0) + if (pathLength <= 0) { return "Unable to get PCI device path"; + } pciPath[pathLength] = '\0'; pPciPath = strrchr(pciPath, '/'); - if (__builtin_expect(pPciPath != NULL, true)) + if (__builtin_expect(pPciPath != NULL, true)) { pPciPath++; - else + } else { pPciPath = pciPath; - } - else - { + } + } else { pPciPath = memrchr(deviceDir->chars, '/', deviceDir->length); assert(pPciPath); pPciPath++; } uint32_t pciDomain, pciBus, pciDevice, pciFunc; - if (sscanf(pPciPath, "%" SCNx32 ":%" SCNx32 ":%" SCNx32 ".%" SCNx32, &pciDomain, &pciBus, &pciDevice, &pciFunc) != 4) + if (sscanf(pPciPath, "%" SCNx32 ":%" SCNx32 ":%" SCNx32 ".%" SCNx32, &pciDomain, &pciBus, &pciDevice, &pciFunc) != 4) { return "Invalid PCI device path"; + } - if (pciFunc > 0 && subclassId == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) + if (pciFunc > 0 && subclassId == 0x80 /*PCI_CLASS_DISPLAY_OTHER*/) { return "Likely an auxiliary display controller"; // #2034 + } - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString((uint16_t) vendorId)); ffStrbufInit(&gpu->name); ffStrbufInit(&gpu->driver); @@ -406,17 +408,13 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf gpu->frequency = FF_GPU_FREQUENCY_UNSET; char drmKeyBuffer[8]; - if (!drmKey) - { + if (!drmKey) { ffStrbufAppendS(deviceDir, "/drm"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(deviceDir->chars); - if (dirp) - { + if (dirp) { struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (ffStrStartsWith(entry->d_name, "card")) - { + while ((entry = readdir(dirp)) != NULL) { + if (ffStrStartsWith(entry->d_name, "card")) { ffStrCopy(drmKeyBuffer, entry->d_name, ARRAY_SIZE(drmKeyBuffer)); drmKey = drmKeyBuffer; break; @@ -426,77 +424,71 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf ffStrbufSubstrBefore(deviceDir, drmDirPathLength); } - if (drmKey) ffStrbufSetF(&gpu->platformApi, "DRM (%s)", drmKey); + if (drmKey) { + ffStrbufSetF(&gpu->platformApi, "DRM (%s)", drmKey); + } pciDetectDriver(&gpu->driver, deviceDir, buffer, drmKey); ffStrbufSubstrBefore(deviceDir, drmDirPathLength); - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) - { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { bool ok = false; - if (drmKey && options->driverSpecific) + if (drmKey && options->driverSpecific) { ok = drmDetectAmdSpecific(options, gpu, drmKey, buffer) == NULL; + } - if (!ok) - { + if (!ok) { pciDetectAmdSpecific(options, gpu, deviceDir, buffer); ffStrbufSubstrBefore(deviceDir, drmDirPathLength); ffStrbufAppendS(deviceDir, "/revision"); - if (ffReadFileBuffer(deviceDir->chars, buffer)) - { + if (ffReadFileBuffer(deviceDir->chars, buffer)) { char* pend; uint64_t revision = strtoul(buffer->chars, &pend, 16); - if (pend != buffer->chars) + if (pend != buffer->chars) { ffGPUQueryAmdGpuName((uint16_t) deviceId, (uint8_t) revision, gpu); + } } ffStrbufSubstrBefore(deviceDir, drmDirPathLength); } - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) - { + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) { pciDetectIntelSpecific(options, gpu, deviceDir, buffer, drmKey); ffStrbufSubstrBefore(deviceDir, drmDirPathLength); - if (options->driverSpecific && drmKey) + if (options->driverSpecific && drmKey) { drmDetectIntelSpecific(gpu, drmKey, buffer); - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA && ffStrbufEqualS(&gpu->driver, "nouveau")) - { + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA && ffStrbufEqualS(&gpu->driver, "nouveau")) { pciDetectTempGeneral(options, gpu, deviceDir, buffer); - if (options->driverSpecific && drmKey) + if (options->driverSpecific && drmKey) { drmDetectNouveauSpecific(gpu, drmKey, buffer); - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_ZHAOXIN && ffStrbufStartsWithS(&gpu->driver, "zx")) - { + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_ZHAOXIN && ffStrbufStartsWithS(&gpu->driver, "zx")) { pciDetectTempGeneral(options, gpu, deviceDir, buffer); pciDetectZxSpecific(options, gpu, deviceDir, buffer); - } - else - { + } else { ffGPUDetectDriverSpecific(options, gpu, (FFGpuDriverPciBusId) { - .domain = pciDomain, - .bus = pciBus, - .device = pciDevice, - .func = pciFunc, - }); + .domain = pciDomain, + .bus = pciBus, + .device = pciDevice, + .func = pciFunc, + }); } - if (gpu->name.length == 0) + if (gpu->name.length == 0) { ffGPUFillVendorAndName(subclassId, (uint16_t) vendorId, (uint16_t) deviceId, gpu); + } - if (gpu->type == FF_GPU_TYPE_UNKNOWN) - { - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) - { + if (gpu->type == FF_GPU_TYPE_UNKNOWN) { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) { if (ffStrbufStartsWithIgnCaseS(&gpu->name, "GeForce") || ffStrbufStartsWithIgnCaseS(&gpu->name, "Quadro") || - ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) + ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) { gpu->type = FF_GPU_TYPE_DISCRETE; - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) - { - if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) { + if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) { gpu->type = FF_GPU_TYPE_DISCRETE; + } } } @@ -505,38 +497,38 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf #if __aarch64__ -FF_MAYBE_UNUSED static const char* drmDetectAsahiSpecific(FFGPUResult* gpu, const char* name, FF_MAYBE_UNUSED FFstrbuf* buffer, FF_MAYBE_UNUSED const char* drmKey) -{ - if (sscanf(name, "agx-t%lu", &gpu->deviceId) == 1) +FF_MAYBE_UNUSED static const char* drmDetectAsahiSpecific(FFGPUResult* gpu, const char* name, FF_MAYBE_UNUSED FFstrbuf* buffer, FF_MAYBE_UNUSED const char* drmKey) { + if (sscanf(name, "agx-t%lu", &gpu->deviceId) == 1) { ffStrbufSetStatic(&gpu->name, ffCPUAppleCodeToName((uint32_t) gpu->deviceId)); + } ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_APPLE); - #if FF_HAVE_DRM_ASAHI +# if FF_HAVE_DRM_ASAHI ffStrbufSetS(buffer, "/dev/dri/"); ffStrbufAppendS(buffer, drmKey); FF_AUTO_CLOSE_FD int fd = open(buffer->chars, O_RDONLY | O_CLOEXEC); - if (fd >= 0) + if (fd >= 0) { return ffDrmDetectAsahi(gpu, fd); - #endif + } +# endif return NULL; } #endif -static const char* detectOf(FFlist* gpus, FFstrbuf* buffer, FFstrbuf* drmDir, const char* drmKey) -{ +static const char* detectOf(FFlist* gpus, FFstrbuf* buffer, FFstrbuf* drmDir, const char* drmKey) { char compatible[256]; // vendor,model-name - if (sscanf(buffer->chars + strlen("of:"), "NgpuT%*[^C]C%255[^C]", compatible) != 1) + if (sscanf(buffer->chars + strlen("of:"), "NgpuT%*[^C]C%255[^C]", compatible) != 1) { return "Failed to parse of modalias or not a GPU device"; + } char* name = strchr(compatible, ','); - if (name) - { + if (name) { *name = '\0'; ++name; } - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); gpu->index = FF_GPU_INDEX_UNSET; gpu->deviceId = 0; ffStrbufInit(&gpu->name); @@ -553,22 +545,20 @@ static const char* detectOf(FFlist* gpus, FFstrbuf* buffer, FFstrbuf* drmDir, co pciDetectDriver(&gpu->driver, drmDir, buffer, drmKey); - #ifdef __aarch64__ - if (ffStrbufEqualS(&gpu->driver, "asahi")) +#ifdef __aarch64__ + if (ffStrbufEqualS(&gpu->driver, "asahi")) { drmDetectAsahiSpecific(gpu, name, buffer, drmKey); - #endif + } +#endif - if (!gpu->name.length) - { + if (!gpu->name.length) { ffStrbufSetS(&gpu->name, name ?: compatible); ffStrbufTrimRightSpace(&gpu->name); } - if (!gpu->vendor.length && name) - { - if (ffStrEquals(compatible, "brcm")) + if (!gpu->vendor.length && name) { + if (ffStrEquals(compatible, "brcm")) { ffStrbufSetStatic(&gpu->vendor, "Broadcom"); // Raspberry Pi - else - { + } else { ffStrbufSetS(&gpu->vendor, compatible); gpu->vendor.chars[0] = (char) toupper(compatible[0]); } @@ -577,36 +567,38 @@ static const char* detectOf(FFlist* gpus, FFstrbuf* buffer, FFstrbuf* drmDir, co return NULL; } -static const char* drmDetectGPUs(const FFGPUOptions* options, FFlist* gpus) -{ +static const char* drmDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { FF_STRBUF_AUTO_DESTROY drmDir = ffStrbufCreateA(64); ffStrbufAppendS(&drmDir, "/sys/class/drm/"); const uint32_t drmDirLength = drmDir.length; FF_AUTO_CLOSE_DIR DIR* dir = opendir(drmDir.chars); - if(dir == NULL) + if (dir == NULL) { return "Failed to open `/sys/class/drm/`"; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while ((entry = readdir(dir)) != NULL) - { + while ((entry = readdir(dir)) != NULL) { if (!ffStrStartsWith(entry->d_name, "card") || - strchr(entry->d_name + 4, '-') != NULL) + strchr(entry->d_name + 4, '-') != NULL) { continue; + } ffStrbufAppendS(&drmDir, entry->d_name); ffStrbufAppendS(&drmDir, "/device/modalias"); - if (!ffReadFileBuffer(drmDir.chars, &buffer)) + if (!ffReadFileBuffer(drmDir.chars, &buffer)) { continue; + } ffStrbufSubstrBefore(&drmDir, drmDir.length - (uint32_t) strlen("/modalias")); - if (ffStrbufStartsWithS(&buffer, "pci:")) + if (ffStrbufStartsWithS(&buffer, "pci:")) { detectPci(options, gpus, &buffer, &drmDir, entry->d_name); - else if (ffStrbufStartsWithS(&buffer, "of:")) // Open Firmware + } else if (ffStrbufStartsWithS(&buffer, "of:")) { // Open Firmware detectOf(gpus, &buffer, &drmDir, entry->d_name); + } ffStrbufSubstrBefore(&drmDir, drmDirLength); } @@ -614,15 +606,14 @@ static const char* drmDetectGPUs(const FFGPUOptions* options, FFlist* gpus) return NULL; } - -static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) -{ - //https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-pci +static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { + // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-pci const char* pciDirPath = "/sys/bus/pci/devices/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pciDirPath); - if(dirp == NULL) + if (dirp == NULL) { return "Failed to open `/sys/bus/pci/devices/`"; + } FF_STRBUF_AUTO_DESTROY pciDir = ffStrbufCreateA(64); ffStrbufAppendS(&pciDir, pciDirPath); @@ -632,18 +623,19 @@ static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } ffStrbufSubstrBefore(&pciDir, pciBaseDirLength); ffStrbufAppendS(&pciDir, entry->d_name); const uint32_t pciDevDirLength = pciDir.length; ffStrbufAppendS(&pciDir, "/modalias"); - if (!ffReadFileBuffer(pciDir.chars, &buffer)) + if (!ffReadFileBuffer(pciDir.chars, &buffer)) { continue; + } ffStrbufSubstrBefore(&pciDir, pciDevDirLength); assert(ffStrbufStartsWithS(&buffer, "pci:")); @@ -654,18 +646,18 @@ static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) return NULL; } -const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) -{ - #if __x86_64__ || __aarch64__ +const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { +#if __x86_64__ || __aarch64__ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus); - if (ffGPUDetectWsl2(options, gpus) == NULL) + if (ffGPUDetectWsl2(options, gpus) == NULL) { return NULL; - #endif + } +#endif - if (options->detectionMethod == FF_GPU_DETECTION_METHOD_AUTO) - { - if (drmDetectGPUs(options, gpus) == NULL && gpus->length > 0) + if (options->detectionMethod == FF_GPU_DETECTION_METHOD_AUTO) { + if (drmDetectGPUs(options, gpus) == NULL && gpus->length > 0) { return NULL; + } } return pciDetectGPUs(options, gpus); } diff --git a/src/detection/gpu/gpu_mthreads.c b/src/detection/gpu/gpu_mthreads.c index ff1347851..aae858c21 100644 --- a/src/detection/gpu/gpu_mthreads.c +++ b/src/detection/gpu/gpu_mthreads.c @@ -3,8 +3,7 @@ #include "common/library.h" #include "mtml.h" -struct FFMtmlData -{ +struct FFMtmlData { FF_LIBRARY_SYMBOL(mtmlDeviceCountGpuCores) FF_LIBRARY_SYMBOL(mtmlDeviceGetBrand) FF_LIBRARY_SYMBOL(mtmlDeviceGetIndex) @@ -26,21 +25,18 @@ struct FFMtmlData FF_LIBRARY_SYMBOL(mtmlLibraryShutDown) bool inited; - MtmlLibrary *lib; - MtmlSystem *sys; + MtmlLibrary* lib; + MtmlSystem* sys; } mtmlData; -FF_MAYBE_UNUSED static void shutdownMtml(void) -{ +FF_MAYBE_UNUSED static void shutdownMtml(void) { mtmlData.ffmtmlLibraryShutDown(mtmlData.lib); } -const char *ffDetectMthreadsGpuInfo(const FFGpuDriverCondition *cond, FFGpuDriverResult result, const char *soName) -{ +const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName) { #ifndef FF_DISABLE_DLOPEN - if (!mtmlData.inited) - { + if (!mtmlData.inited) { mtmlData.inited = true; FF_LIBRARY_LOAD(libmtml, "dlopen mtml failed", soName, 1); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libmtml, mtmlLibraryInit) @@ -64,13 +60,11 @@ const char *ffDetectMthreadsGpuInfo(const FFGpuDriverCondition *cond, FFGpuDrive FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libmtml, mtmlData, mtmlMemoryGetUtilization) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libmtml, mtmlData, mtmlLibraryShutDown) - if (ffmtmlLibraryInit(&mtmlData.lib) != MTML_SUCCESS) - { + if (ffmtmlLibraryInit(&mtmlData.lib) != MTML_SUCCESS) { mtmlData.ffmtmlLibraryInitSystem = NULL; return "mtmlLibraryInit failed"; } - if (mtmlData.ffmtmlLibraryInitSystem(mtmlData.lib, &mtmlData.sys) != MTML_SUCCESS) - { + if (mtmlData.ffmtmlLibraryInitSystem(mtmlData.lib, &mtmlData.sys) != MTML_SUCCESS) { mtmlData.ffmtmlLibraryShutDown(mtmlData.lib); mtmlData.ffmtmlLibraryInitSystem = NULL; return "mtmlLibraryInitSystem failed"; @@ -79,124 +73,121 @@ const char *ffDetectMthreadsGpuInfo(const FFGpuDriverCondition *cond, FFGpuDrive libmtml = NULL; // don't close mtml } - if (mtmlData.ffmtmlLibraryInitSystem == NULL) + if (mtmlData.ffmtmlLibraryInitSystem == NULL) { return "loading mtml library failed"; + } - MtmlDevice *device = NULL; - if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) - { + MtmlDevice* device = NULL; + if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) { char pciBusIdStr[32]; snprintf(pciBusIdStr, ARRAY_SIZE(pciBusIdStr) - 1, "%04x:%02x:%02x.%d", cond->pciBusId.domain, cond->pciBusId.bus, cond->pciBusId.device, cond->pciBusId.func); MtmlReturn ret = mtmlData.ffmtmlLibraryInitDeviceByPciSbdf(mtmlData.lib, pciBusIdStr, &device); - if (ret != MTML_SUCCESS) + if (ret != MTML_SUCCESS) { return "mtmlLibraryInitDeviceByPciSbdf() failed"; - } - else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID) - { + } + } else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID) { uint32_t count; - if (mtmlData.ffmtmlLibraryCountDevice(mtmlData.lib, &count) != MTML_SUCCESS) + if (mtmlData.ffmtmlLibraryCountDevice(mtmlData.lib, &count) != MTML_SUCCESS) { return "mtmlLibraryCountDevice() failed"; + } - for (uint32_t i = 0; i < count; i++, device = NULL) - { - if (mtmlData.ffmtmlLibraryInitDeviceByIndex(mtmlData.lib, i, &device) != MTML_SUCCESS) + for (uint32_t i = 0; i < count; i++, device = NULL) { + if (mtmlData.ffmtmlLibraryInitDeviceByIndex(mtmlData.lib, i, &device) != MTML_SUCCESS) { continue; + } MtmlPciInfo pciInfo; - if (mtmlData.ffmtmlDeviceGetPciInfo(device, &pciInfo) != MTML_SUCCESS) + if (mtmlData.ffmtmlDeviceGetPciInfo(device, &pciInfo) != MTML_SUCCESS) { continue; + } if (pciInfo.pciDeviceId != ((cond->pciDeviceId.deviceId << 16u) | cond->pciDeviceId.vendorId) || - pciInfo.pciSubsystemId != cond->pciDeviceId.subSystemId) + pciInfo.pciSubsystemId != cond->pciDeviceId.subSystemId) { continue; + } break; } - if (!device) + if (!device) { return "Device not found"; - } - else - { + } + } else { return "Unknown condition type"; } MtmlBrandType brand; - if (mtmlData.ffmtmlDeviceGetBrand(device, &brand) == MTML_SUCCESS) - { - switch (brand) - { - case MTML_BRAND_MTT: - *result.type = FF_GPU_TYPE_DISCRETE; - break; - default: - break; + if (mtmlData.ffmtmlDeviceGetBrand(device, &brand) == MTML_SUCCESS) { + switch (brand) { + case MTML_BRAND_MTT: + *result.type = FF_GPU_TYPE_DISCRETE; + break; + default: + break; } } - if (result.index) - { + if (result.index) { unsigned int value; - if (mtmlData.ffmtmlDeviceGetIndex(device, &value) == MTML_SUCCESS) + if (mtmlData.ffmtmlDeviceGetIndex(device, &value) == MTML_SUCCESS) { *result.index = value; - } - - if (result.temp) - { - MtmlGpu *gpu = NULL; - if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) - { - uint32_t value; - if (mtmlData.ffmtmlGpuGetTemperature(gpu, &value) == MTML_SUCCESS) - *result.temp = value; } } - if (result.memory) - { - MtmlMemory *mem = NULL; - if (mtmlData.ffmtmlDeviceInitMemory(device, &mem) == MTML_SUCCESS) - { + if (result.temp) { + MtmlGpu* gpu = NULL; + if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) { + uint32_t value; + if (mtmlData.ffmtmlGpuGetTemperature(gpu, &value) == MTML_SUCCESS) { + *result.temp = value; + } + } + } + + if (result.memory) { + MtmlMemory* mem = NULL; + if (mtmlData.ffmtmlDeviceInitMemory(device, &mem) == MTML_SUCCESS) { unsigned long long total; - if (mtmlData.ffmtmlMemoryGetTotal(mem, &total) == MTML_SUCCESS) + if (mtmlData.ffmtmlMemoryGetTotal(mem, &total) == MTML_SUCCESS) { result.memory->total = total; + } unsigned long long used; - if (mtmlData.ffmtmlMemoryGetUsed(mem, &used) == MTML_SUCCESS) + if (mtmlData.ffmtmlMemoryGetUsed(mem, &used) == MTML_SUCCESS) { result.memory->used = used; + } } } - if (result.coreCount) + if (result.coreCount) { mtmlData.ffmtmlDeviceCountGpuCores(device, result.coreCount); + } - if (result.frequency) - { - MtmlGpu *gpu = NULL; - if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) - { + if (result.frequency) { + MtmlGpu* gpu = NULL; + if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) { uint32_t clockMHz; - if (mtmlData.ffmtmlGpuGetMaxClock(gpu, &clockMHz) == MTML_SUCCESS) + if (mtmlData.ffmtmlGpuGetMaxClock(gpu, &clockMHz) == MTML_SUCCESS) { *result.frequency = clockMHz; + } } } - if (result.coreUsage) - { - MtmlGpu *gpu = NULL; - if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) - { + if (result.coreUsage) { + MtmlGpu* gpu = NULL; + if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) { unsigned int utilization; - if (mtmlData.ffmtmlGpuGetUtilization(gpu, &utilization) == MTML_SUCCESS) + if (mtmlData.ffmtmlGpuGetUtilization(gpu, &utilization) == MTML_SUCCESS) { *result.coreUsage = utilization; + } } } - if (result.name) - { + if (result.name) { char name[MTML_DEVICE_NAME_BUFFER_SIZE]; - if (mtmlData.ffmtmlDeviceGetName(device, name, ARRAY_SIZE(name)) == MTML_SUCCESS) + if (mtmlData.ffmtmlDeviceGetName(device, name, ARRAY_SIZE(name)) == MTML_SUCCESS) { ffStrbufSetS(result.name, name); + } } return NULL; diff --git a/src/detection/gpu/gpu_nbsd.c b/src/detection/gpu/gpu_nbsd.c index aed284925..49db29b41 100644 --- a/src/detection/gpu/gpu_nbsd.c +++ b/src/detection/gpu/gpu_nbsd.c @@ -8,8 +8,7 @@ #include #include -static inline int pciReadConf(int fd, uint32_t bus, uint32_t device, uint32_t func, uint32_t reg, uint32_t* result) -{ +static inline int pciReadConf(int fd, uint32_t bus, uint32_t device, uint32_t func, uint32_t reg, uint32_t* result) { struct pciio_bdf_cfgreg bdfr = { .bus = bus, .device = device, @@ -19,67 +18,72 @@ static inline int pciReadConf(int fd, uint32_t bus, uint32_t device, uint32_t fu }, }; - if (ioctl(fd, PCI_IOC_BDF_CFGREAD, &bdfr) == -1) + if (ioctl(fd, PCI_IOC_BDF_CFGREAD, &bdfr) == -1) { return -1; + } *result = bdfr.cfgreg.val; return 0; } -const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) { char pciDevPath[] = "/dev/pciXXX"; - for (uint32_t idev = 0; idev <= 255; idev++) - { + for (uint32_t idev = 0; idev <= 255; idev++) { snprintf(pciDevPath + strlen("/dev/pci"), 4, "%u", idev); FF_AUTO_CLOSE_FD int pcifd = open(pciDevPath, O_RDONLY | O_CLOEXEC); - if (pcifd < 0) - { - if (errno == ENOENT) + if (pcifd < 0) { + if (errno == ENOENT) { break; // No more /dev/pciN devices + } return "open(\"/dev/pciN\", O_RDONLY | O_CLOEXEC) failed"; } struct pciio_businfo businfo; - if (ioctl(pcifd, PCI_IOC_BUSINFO, &businfo) != 0) + if (ioctl(pcifd, PCI_IOC_BUSINFO, &businfo) != 0) { continue; + } uint32_t bus = businfo.busno; - for (uint32_t dev = 0; dev < businfo.maxdevs; dev++) - { + for (uint32_t dev = 0; dev < businfo.maxdevs; dev++) { uint32_t maxfuncs = 0; - for (uint32_t func = 0; func <= maxfuncs; func++) - { + for (uint32_t func = 0; func <= maxfuncs; func++) { uint32_t pciid, pciclass; - if (pciReadConf(pcifd, bus, dev, func, PCI_ID_REG, &pciid) != 0) + if (pciReadConf(pcifd, bus, dev, func, PCI_ID_REG, &pciid) != 0) { continue; + } - if (PCI_VENDOR(pciid) == PCI_VENDOR_INVALID || PCI_VENDOR(pciid) == 0) + if (PCI_VENDOR(pciid) == PCI_VENDOR_INVALID || PCI_VENDOR(pciid) == 0) { continue; + } - if (pciReadConf(pcifd, bus, dev, func, PCI_CLASS_REG, &pciclass) != 0) + if (pciReadConf(pcifd, bus, dev, func, PCI_CLASS_REG, &pciclass) != 0) { continue; + } - if (func == 0) - { + if (func == 0) { // For some reason, pciReadConf returns success even for non-existing devices. // So we need to check for `PCI_VENDOR(pciid) == PCI_VENDOR_INVALID` above to filter them out. uint32_t bhlcr; - if (pciReadConf(pcifd, bus, dev, 0, PCI_BHLC_REG, &bhlcr) != 0) + if (pciReadConf(pcifd, bus, dev, 0, PCI_BHLC_REG, &bhlcr) != 0) { continue; + } - if (PCI_HDRTYPE_MULTIFN(bhlcr)) maxfuncs = 7; + if (PCI_HDRTYPE_MULTIFN(bhlcr)) { + maxfuncs = 7; + } } - if (PCI_CLASS(pciclass) != PCI_CLASS_DISPLAY) + if (PCI_CLASS(pciclass) != PCI_CLASS_DISPLAY) { continue; + } - if (func > 0 && PCI_SUBCLASS(pciclass) == PCI_SUBCLASS_DISPLAY_MISC) + if (func > 0 && PCI_SUBCLASS(pciclass) == PCI_SUBCLASS_DISPLAY_MISC) { continue; // Likely an auxiliary display controller (#2034) + } - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString(PCI_VENDOR(pciid))); ffStrbufInit(&gpu->name); ffStrbufInit(&gpu->driver); @@ -94,17 +98,20 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpu->deviceId = ffGPUPciAddr2Id(0, bus, dev, func); gpu->frequency = FF_GPU_FREQUENCY_UNSET; - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { ffGPUQueryAmdGpuName(PCI_PRODUCT(pciid), PCI_REVISION(pciid), gpu); - if (gpu->name.length == 0) + } + if (gpu->name.length == 0) { ffGPUFillVendorAndName(PCI_SUBCLASS(pciclass), PCI_VENDOR(pciid), PCI_PRODUCT(pciid), gpu); + } struct pciio_drvname drvname = { .device = dev, .function = func, }; - if (ioctl(pcifd, PCI_IOC_DRVNAME, &drvname) == 0) + if (ioctl(pcifd, PCI_IOC_DRVNAME, &drvname) == 0) { ffStrbufInitS(&gpu->driver, drvname.name); + } } } } diff --git a/src/detection/gpu/gpu_nosupport.c b/src/detection/gpu/gpu_nosupport.c index 28daf5fa6..95fb2f350 100644 --- a/src/detection/gpu/gpu_nosupport.c +++ b/src/detection/gpu/gpu_nosupport.c @@ -1,7 +1,6 @@ #include "gpu.h" -const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { FF_UNUSED(options, gpus); return "Not supported on this platform"; } diff --git a/src/detection/gpu/gpu_nvidia.c b/src/detection/gpu/gpu_nvidia.c index 983fb326c..28a2913d2 100644 --- a/src/detection/gpu/gpu_nvidia.c +++ b/src/detection/gpu/gpu_nvidia.c @@ -23,7 +23,7 @@ struct FFNvmlData { #if defined(_WIN32) && !defined(FF_DISABLE_DLOPEN) -#include "nvapi.h" +# include "nvapi.h" struct FFNvapiData { FF_LIBRARY_SYMBOL(nvapi_Unload) @@ -34,33 +34,33 @@ struct FFNvapiData { bool inited; } nvapiData; -static const char* detectMoreByNvapi(FFGpuDriverResult* result) -{ - if (!nvapiData.inited) - { +static const char* detectMoreByNvapi(FFGpuDriverResult* result) { + if (!nvapiData.inited) { nvapiData.inited = true; FF_LIBRARY_LOAD_MESSAGE(libnvapi, - #ifdef _WIN64 +# ifdef _WIN64 "nvapi64.dll" - #else +# else "nvapi.dll" - #endif - , 1); +# endif + , + 1); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libnvapi, nvapi_QueryInterface) - #define FF_NVAPI_INTERFACE(iName, iOffset) \ - __typeof__(&iName) ff ## iName = ffnvapi_QueryInterface(iOffset); \ - if (ff ## iName == NULL) return "nvapi_QueryInterface " #iName " failed"; +# define FF_NVAPI_INTERFACE(iName, iOffset) \ + __typeof__(&iName) ff##iName = ffnvapi_QueryInterface(iOffset); \ + if (ff##iName == NULL) return "nvapi_QueryInterface " #iName " failed"; FF_NVAPI_INTERFACE(nvapi_Initialize, NVAPI_INTERFACE_OFFSET_INITIALIZE) FF_NVAPI_INTERFACE(nvapi_Unload, NVAPI_INTERFACE_OFFSET_UNLOAD) FF_NVAPI_INTERFACE(nvapi_EnumPhysicalGPUs, NVAPI_INTERFACE_OFFSET_ENUM_PHYSICAL_GPUS) FF_NVAPI_INTERFACE(nvapi_GPU_GetRamType, NVAPI_INTERFACE_OFFSET_GPU_GET_RAM_TYPE) FF_NVAPI_INTERFACE(nvapi_GPU_GetGPUType, NVAPI_INTERFACE_OFFSET_GPU_GET_GPU_TYPE) - #undef FF_NVAPI_INTERFACE +# undef FF_NVAPI_INTERFACE - if (ffnvapi_Initialize() < 0) + if (ffnvapi_Initialize() < 0) { return "NvAPI_Initialize() failed"; + } nvapiData.ffnvapi_EnumPhysicalGPUs = ffnvapi_EnumPhysicalGPUs; nvapiData.ffnvapi_GPU_GetRamType = ffnvapi_GPU_GetRamType; @@ -71,32 +71,33 @@ static const char* detectMoreByNvapi(FFGpuDriverResult* result) libnvapi = NULL; // don't close nvapi } - if (nvapiData.ffnvapi_EnumPhysicalGPUs == NULL) + if (nvapiData.ffnvapi_EnumPhysicalGPUs == NULL) { return "loading nvapi library failed"; + } NvPhysicalGpuHandle handles[32]; int gpuCount = 0; - if (nvapiData.ffnvapi_EnumPhysicalGPUs(handles, &gpuCount) < 0) + if (nvapiData.ffnvapi_EnumPhysicalGPUs(handles, &gpuCount) < 0) { return "NvAPI_EnumPhysicalGPUs() failed"; + } uint32_t gpuIndex = *result->index; - if (gpuIndex >= (uint32_t) gpuCount) + if (gpuIndex >= (uint32_t) gpuCount) { return "GPU index out of range"; + } // Not very sure. Need to check in multi-GPU system NvPhysicalGpuHandle gpuHandle = handles[gpuIndex]; NvApiGPUMemoryType memType; - if (result->memoryType && nvapiData.ffnvapi_GPU_GetRamType(gpuHandle, &memType) == 0) - { - switch (memType) - { - #define FF_NVAPI_MEMORY_TYPE(type) \ - case NVAPI_GPU_MEMORY_TYPE_##type: \ - ffStrbufSetStatic(result->memoryType, #type); \ - break; + if (result->memoryType && nvapiData.ffnvapi_GPU_GetRamType(gpuHandle, &memType) == 0) { + switch (memType) { +# define FF_NVAPI_MEMORY_TYPE(type) \ + case NVAPI_GPU_MEMORY_TYPE_##type: \ + ffStrbufSetStatic(result->memoryType, #type); \ + break; FF_NVAPI_MEMORY_TYPE(UNKNOWN) FF_NVAPI_MEMORY_TYPE(SDRAM) FF_NVAPI_MEMORY_TYPE(DDR1) @@ -114,7 +115,7 @@ static const char* detectMoreByNvapi(FFGpuDriverResult* result) FF_NVAPI_MEMORY_TYPE(GDDR6) FF_NVAPI_MEMORY_TYPE(GDDR6X) FF_NVAPI_MEMORY_TYPE(GDDR7) - #undef FF_NVAPI_MEMORY_TYPE +# undef FF_NVAPI_MEMORY_TYPE default: ffStrbufSetF(result->memoryType, "Unknown (%d)", memType); break; @@ -122,10 +123,8 @@ static const char* detectMoreByNvapi(FFGpuDriverResult* result) } NvApiGPUType gpuType; - if (result->type && nvapiData.ffnvapi_GPU_GetGPUType(gpuHandle, &gpuType) == 0) - { - switch (gpuType) - { + if (result->type && nvapiData.ffnvapi_GPU_GetGPUType(gpuHandle, &gpuType) == 0) { + switch (gpuType) { case NV_SYSTEM_TYPE_IGPU: *result->type = FF_GPU_TYPE_INTEGRATED; break; @@ -143,14 +142,12 @@ static const char* detectMoreByNvapi(FFGpuDriverResult* result) #endif -const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName) -{ +const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResult result, const char* soName) { #ifndef FF_DISABLE_DLOPEN - if (!nvmlData.inited) - { + if (!nvmlData.inited) { nvmlData.inited = true; - FF_LIBRARY_LOAD(libnvml, "dlopen nvml failed", soName , 1); + FF_LIBRARY_LOAD(libnvml, "dlopen nvml failed", soName, 1); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libnvml, nvmlInit_v2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libnvml, nvmlShutdown) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libnvml, nvmlData, nvmlDeviceGetCount_v2) @@ -167,8 +164,7 @@ const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverR FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libnvml, nvmlData, nvmlDeviceGetIndex) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libnvml, nvmlData, nvmlDeviceGetName) - if (ffnvmlInit_v2() != NVML_SUCCESS) - { + if (ffnvmlInit_v2() != NVML_SUCCESS) { nvmlData.ffnvmlDeviceGetNumGpuCores = NULL; return "nvmlInit_v2() failed"; } @@ -176,51 +172,52 @@ const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverR libnvml = NULL; // don't close nvml } - if (nvmlData.ffnvmlDeviceGetNumGpuCores == NULL) + if (nvmlData.ffnvmlDeviceGetNumGpuCores == NULL) { return "loading nvml library failed"; + } nvmlDevice_t device = NULL; - if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) - { + if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) { char pciBusIdStr[32]; snprintf(pciBusIdStr, ARRAY_SIZE(pciBusIdStr), "%04x:%02x:%02x.%d", cond->pciBusId.domain, cond->pciBusId.bus, cond->pciBusId.device, cond->pciBusId.func); nvmlReturn_t ret = nvmlData.ffnvmlDeviceGetHandleByPciBusId_v2(pciBusIdStr, &device); - if (ret != NVML_SUCCESS) + if (ret != NVML_SUCCESS) { return "nvmlDeviceGetHandleByPciBusId_v2() failed"; - } - else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID) - { + } + } else if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID) { uint32_t count; - if (nvmlData.ffnvmlDeviceGetCount_v2(&count) != NVML_SUCCESS) + if (nvmlData.ffnvmlDeviceGetCount_v2(&count) != NVML_SUCCESS) { return "nvmlDeviceGetCount_v2() failed"; + } - for (uint32_t i = 0; i < count; i++, device = NULL) - { - if (nvmlData.ffnvmlDeviceGetHandleByIndex_v2(i, &device) != NVML_SUCCESS) + for (uint32_t i = 0; i < count; i++, device = NULL) { + if (nvmlData.ffnvmlDeviceGetHandleByIndex_v2(i, &device) != NVML_SUCCESS) { continue; + } nvmlPciInfo_t pciInfo; - if (nvmlData.ffnvmlDeviceGetPciInfo_v3(device, &pciInfo) != NVML_SUCCESS) + if (nvmlData.ffnvmlDeviceGetPciInfo_v3(device, &pciInfo) != NVML_SUCCESS) { continue; + } if (pciInfo.pciDeviceId != ((cond->pciDeviceId.deviceId << 16u) | cond->pciDeviceId.vendorId) || - pciInfo.pciSubSystemId != cond->pciDeviceId.subSystemId) + pciInfo.pciSubSystemId != cond->pciDeviceId.subSystemId) { continue; + } break; } } - if (!device) return "Device not found"; + if (!device) { + return "Device not found"; + } - if (result.type) - { + if (result.type) { nvmlBrandType_t brand; - if (nvmlData.ffnvmlDeviceGetBrand(device, &brand) == NVML_SUCCESS) - { - switch (brand) - { + if (nvmlData.ffnvmlDeviceGetBrand(device, &brand) == NVML_SUCCESS) { + switch (brand) { case NVML_BRAND_NVIDIA_RTX: case NVML_BRAND_QUADRO_RTX: case NVML_BRAND_GEFORCE: @@ -235,64 +232,60 @@ const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverR } } - if (result.index) - { + if (result.index) { unsigned int value; - if (nvmlData.ffnvmlDeviceGetIndex(device, &value) == NVML_SUCCESS) - { + if (nvmlData.ffnvmlDeviceGetIndex(device, &value) == NVML_SUCCESS) { *result.index = value; - #ifdef _WIN32 +# ifdef _WIN32 // Don't bother loading nvapi for GPU type detection only - if (result.memoryType) + if (result.memoryType) { detectMoreByNvapi(&result); - #endif + } +# endif } } - if (result.temp) - { + if (result.temp) { uint32_t value; - if (nvmlData.ffnvmlDeviceGetTemperature(device, NVML_TEMPERATURE_GPU, &value) == NVML_SUCCESS) + if (nvmlData.ffnvmlDeviceGetTemperature(device, NVML_TEMPERATURE_GPU, &value) == NVML_SUCCESS) { *result.temp = value; + } } - if (result.memory) - { - nvmlMemory_v2_t memory = { .version = nvmlMemory_v2 }; - if (nvmlData.ffnvmlDeviceGetMemoryInfo_v2(device, &memory) == NVML_SUCCESS) - { + if (result.memory) { + nvmlMemory_v2_t memory = {.version = nvmlMemory_v2}; + if (nvmlData.ffnvmlDeviceGetMemoryInfo_v2(device, &memory) == NVML_SUCCESS) { result.memory->total = memory.used + memory.free; result.memory->used = memory.used; - } - else - { + } else { nvmlMemory_t memory_v1; - if (nvmlData.ffnvmlDeviceGetMemoryInfo(device, &memory_v1) == NVML_SUCCESS) - { + if (nvmlData.ffnvmlDeviceGetMemoryInfo(device, &memory_v1) == NVML_SUCCESS) { result.memory->total = memory_v1.total; result.memory->used = memory_v1.used; } } } - if (result.coreCount) + if (result.coreCount) { nvmlData.ffnvmlDeviceGetNumGpuCores(device, result.coreCount); - - if (result.frequency) - nvmlData.ffnvmlDeviceGetMaxClockInfo(device, NVML_CLOCK_GRAPHICS, result.frequency); - - if (result.coreUsage) - { - nvmlUtilization_t utilization; - if (nvmlData.ffnvmlDeviceGetUtilizationRates(device, &utilization) == NVML_SUCCESS) - *result.coreUsage = utilization.gpu; } - if (result.name) - { + if (result.frequency) { + nvmlData.ffnvmlDeviceGetMaxClockInfo(device, NVML_CLOCK_GRAPHICS, result.frequency); + } + + if (result.coreUsage) { + nvmlUtilization_t utilization; + if (nvmlData.ffnvmlDeviceGetUtilizationRates(device, &utilization) == NVML_SUCCESS) { + *result.coreUsage = utilization.gpu; + } + } + + if (result.name) { char name[NVML_DEVICE_NAME_V2_BUFFER_SIZE]; - if (nvmlData.ffnvmlDeviceGetName(device, name, ARRAY_SIZE(name)) == NVML_SUCCESS) + if (nvmlData.ffnvmlDeviceGetName(device, name, ARRAY_SIZE(name)) == NVML_SUCCESS) { ffStrbufSetS(result.name, name); + } } return NULL; diff --git a/src/detection/gpu/gpu_obsd.c b/src/detection/gpu/gpu_obsd.c index 83c6c81a6..9349bcf68 100644 --- a/src/detection/gpu/gpu_obsd.c +++ b/src/detection/gpu/gpu_obsd.c @@ -8,8 +8,7 @@ #include #include -static inline int pciReadConf(int fd, uint8_t bus, uint8_t device, uint8_t func, uint8_t reg, uint32_t* result) -{ +static inline int pciReadConf(int fd, uint8_t bus, uint8_t device, uint8_t func, uint8_t reg, uint32_t* result) { struct pci_io bdfr = { .pi_sel = { .pc_bus = bus, @@ -20,55 +19,60 @@ static inline int pciReadConf(int fd, uint8_t bus, uint8_t device, uint8_t func, .pi_width = 4, }; - if (ioctl(fd, PCIOCREAD, &bdfr) == -1) + if (ioctl(fd, PCIOCREAD, &bdfr) == -1) { return -1; + } *result = bdfr.pi_data; return 0; } -const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) { char pciDevPath[] = "/dev/pci0"; FF_AUTO_CLOSE_FD int pcifd = open(pciDevPath, O_RDONLY | O_CLOEXEC); - if (pcifd < 0) + if (pcifd < 0) { return "open(\"/dev/pci0\", O_RDONLY | O_CLOEXEC) failed"; + } - for (uint16_t bus = 0; bus <= 255; bus++) - { - for (uint8_t dev = 0; dev < 32; dev++) - { + for (uint16_t bus = 0; bus <= 255; bus++) { + for (uint8_t dev = 0; dev < 32; dev++) { uint8_t maxfuncs = 0; - for (uint8_t func = 0; func <= maxfuncs; func++) - { + for (uint8_t func = 0; func <= maxfuncs; func++) { uint32_t pciid, pciclass; - if (pciReadConf(pcifd, (uint8_t) bus, dev, func, PCI_ID_REG, &pciid) != 0) + if (pciReadConf(pcifd, (uint8_t) bus, dev, func, PCI_ID_REG, &pciid) != 0) { continue; + } - if (PCI_VENDOR(pciid) == PCI_VENDOR_INVALID || PCI_VENDOR(pciid) == 0) + if (PCI_VENDOR(pciid) == PCI_VENDOR_INVALID || PCI_VENDOR(pciid) == 0) { continue; + } - if (pciReadConf(pcifd, (uint8_t) bus, dev, func, PCI_CLASS_REG, &pciclass) != 0) + if (pciReadConf(pcifd, (uint8_t) bus, dev, func, PCI_CLASS_REG, &pciclass) != 0) { continue; + } - if (func == 0) - { + if (func == 0) { // For some reason, pciReadConf returns success even for non-existing devices. // So we need to check for `PCI_VENDOR(pciid) == PCI_VENDOR_INVALID` above to filter them out. uint32_t bhlcr; - if (pciReadConf(pcifd, (uint8_t) bus, dev, 0, PCI_BHLC_REG, &bhlcr) != 0) + if (pciReadConf(pcifd, (uint8_t) bus, dev, 0, PCI_BHLC_REG, &bhlcr) != 0) { continue; + } - if (PCI_HDRTYPE_MULTIFN(bhlcr)) maxfuncs = 7; + if (PCI_HDRTYPE_MULTIFN(bhlcr)) { + maxfuncs = 7; + } } - if (PCI_CLASS(pciclass) != PCI_CLASS_DISPLAY) + if (PCI_CLASS(pciclass) != PCI_CLASS_DISPLAY) { continue; + } - if (func > 0 && PCI_SUBCLASS(pciclass) == PCI_SUBCLASS_DISPLAY_MISC) + if (func > 0 && PCI_SUBCLASS(pciclass) == PCI_SUBCLASS_DISPLAY_MISC) { continue; // Likely an auxiliary display controller (#2034) + } - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInitStatic(&gpu->vendor, ffGPUGetVendorString(PCI_VENDOR(pciid))); ffStrbufInit(&gpu->name); ffStrbufInit(&gpu->driver); @@ -83,10 +87,12 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpu->deviceId = ffGPUPciAddr2Id(0, bus, dev, func); gpu->frequency = FF_GPU_FREQUENCY_UNSET; - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { ffGPUQueryAmdGpuName(PCI_PRODUCT(pciid), PCI_REVISION(pciid), gpu); - if (gpu->name.length == 0) + } + if (gpu->name.length == 0) { ffGPUFillVendorAndName(PCI_SUBCLASS(pciclass), PCI_VENDOR(pciid), PCI_PRODUCT(pciid), gpu); + } } } } diff --git a/src/detection/gpu/gpu_pci.c b/src/detection/gpu/gpu_pci.c index a6ca9bbeb..5ae93b471 100644 --- a/src/detection/gpu/gpu_pci.c +++ b/src/detection/gpu/gpu_pci.c @@ -5,131 +5,135 @@ #include #ifdef __FreeBSD__ - #include - #ifndef _PATH_LOCALBASE - #define _PATH_LOCALBASE "/usr/local" - #endif +# include +# ifndef _PATH_LOCALBASE +# define _PATH_LOCALBASE "/usr/local" +# endif #elif __OpenBSD__ - #define _PATH_LOCALBASE "/usr/local" +# define _PATH_LOCALBASE "/usr/local" #elif __NetBSD__ - #define _PATH_LOCALBASE "/usr/pkg" +# define _PATH_LOCALBASE "/usr/pkg" #endif #if FF_HAVE_EMBEDDED_PCIIDS -#include "fastfetch_pciids.c.inc" +# include "fastfetch_pciids.c.inc" #endif #if FF_HAVE_EMBEDDED_AMDGPUIDS -#include "fastfetch_amdgpuids.c.inc" +# include "fastfetch_amdgpuids.c.inc" #endif #define FF_STR_INDIR(x) #x #define FF_STR(x) FF_STR_INDIR(x) -static const FFstrbuf* loadPciIds() -{ +static const FFstrbuf* loadPciIds() { static FFstrbuf pciids; - if (pciids.chars) return &pciids; + if (pciids.chars) { + return &pciids; + } ffStrbufInit(&pciids); - #ifdef FF_CUSTOM_PCI_IDS_PATH +#ifdef FF_CUSTOM_PCI_IDS_PATH - ffReadFileBuffer(FF_STR(FF_CUSTOM_PCI_IDS_PATH), &pciids); + ffReadFileBuffer(FF_STR(FF_CUSTOM_PCI_IDS_PATH), &pciids); - #else // FF_CUSTOM_PCI_IDS_PATH +#else // FF_CUSTOM_PCI_IDS_PATH - #if __linux__ - ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/share/hwdata/pci.ids", &pciids); - if (pciids.length == 0) - { - ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/share/misc/pci.ids", &pciids); // debian? - if (pciids.length == 0) - ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/local/share/hwdata/pci.ids", &pciids); +# if __linux__ + ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/share/hwdata/pci.ids", &pciids); + if (pciids.length == 0) { + ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/share/misc/pci.ids", &pciids); // debian? + if (pciids.length == 0) { + ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/local/share/hwdata/pci.ids", &pciids); } - #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__ - ffReadFileBuffer(FASTFETCH_TARGET_DIR_ROOT "/system/data/hwdata/pci.ids", &pciids); - #endif + } +# 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__ + ffReadFileBuffer(FASTFETCH_TARGET_DIR_ROOT "/system/data/hwdata/pci.ids", &pciids); +# endif - #endif // FF_CUSTOM_PCI_IDS_PATH +#endif // FF_CUSTOM_PCI_IDS_PATH return &pciids; } -static void parsePciIdsFile(const FFstrbuf* content, uint8_t subclass, uint16_t vendor, uint16_t device, FFGPUResult* gpu) -{ - if (content->length) - { +static void parsePciIdsFile(const FFstrbuf* content, uint8_t subclass, uint16_t vendor, uint16_t device, FFGPUResult* gpu) { + if (content->length) { char buffer[32]; // Search for vendor uint32_t len = (uint32_t) snprintf(buffer, ARRAY_SIZE(buffer), "\n%04x ", vendor); char* start = (char*) memmem(content->chars, content->length, buffer, len); char* end = content->chars + content->length; - if (start) - { + if (start) { start += len; end = memchr(start, '\n', (uint32_t) (end - start)); - if (!end) + if (!end) { end = content->chars + content->length; - if (!gpu->vendor.length) + } + if (!gpu->vendor.length) { ffStrbufSetNS(&gpu->vendor, (uint32_t) (end - start), start); + } - start = end; // point to '\n' of vendor + start = end; // point to '\n' of vendor end = start + 1; // point to start of devices // find the start of next vendor - while (end[0] == '\t' || end[0] == '#') - { + while (end[0] == '\t' || end[0] == '#') { end = strchr(end, '\n'); - if (!end) - { + if (!end) { end = content->chars + content->length; break; - } - else + } else { end++; + } } // Search for device len = (uint32_t) snprintf(buffer, ARRAY_SIZE(buffer), "\n\t%04x ", device); start = memmem(start, (size_t) (end - start), buffer, len); - if (start) - { + if (start) { start += len; end = memchr(start, '\n', (uint32_t) (end - start)); - if (!end) + if (!end) { end = content->chars + content->length; + } char* closingBracket = end - 1; - if (*closingBracket == ']') - { + if (*closingBracket == ']') { char* openingBracket = memrchr(start, '[', (size_t) (closingBracket - start)); - if (openingBracket) - { + if (openingBracket) { openingBracket++; ffStrbufSetNS(&gpu->name, (uint32_t) (closingBracket - openingBracket), openingBracket); } } - if (!gpu->name.length) + if (!gpu->name.length) { ffStrbufSetNS(&gpu->name, (uint32_t) (end - start), start); + } } } } - if (!gpu->name.length) - { + if (!gpu->name.length) { const char* subclassStr; - switch (subclass) - { - case 0 /*PCI_CLASS_DISPLAY_VGA*/: subclassStr = " (VGA compatible)"; break; - case 1 /*PCI_CLASS_DISPLAY_XGA*/: subclassStr = " (XGA compatible)"; break; - case 2 /*PCI_CLASS_DISPLAY_3D*/: subclassStr = " (3D)"; break; - default: subclassStr = ""; break; + switch (subclass) { + case 0 /*PCI_CLASS_DISPLAY_VGA*/: + subclassStr = " (VGA compatible)"; + break; + case 1 /*PCI_CLASS_DISPLAY_XGA*/: + subclassStr = " (XGA compatible)"; + break; + case 2 /*PCI_CLASS_DISPLAY_3D*/: + subclassStr = " (3D)"; + break; + default: + subclassStr = ""; + break; } ffStrbufSetF(&gpu->name, "%s Device %04X%s", gpu->vendor.length ? gpu->vendor.chars : "Unknown", device, subclassStr); @@ -137,49 +141,53 @@ static void parsePciIdsFile(const FFstrbuf* content, uint8_t subclass, uint16_t } #if FF_HAVE_EMBEDDED_PCIIDS -static inline int pciDeviceCmp(const uint16_t* key, const FFPciDevice* element) -{ +static inline int pciDeviceCmp(const uint16_t* key, const FFPciDevice* element) { return (int) *key - (int) element->id; } -static bool loadPciidsInc(uint8_t subclass, uint16_t vendor, uint16_t device, FFGPUResult* gpu) -{ - for (const FFPciVendor* pvendor = ffPciVendors; pvendor->name; pvendor++) - { - if (pvendor->id != vendor) continue; +static bool loadPciidsInc(uint8_t subclass, uint16_t vendor, uint16_t device, FFGPUResult* gpu) { + for (const FFPciVendor* pvendor = ffPciVendors; pvendor->name; pvendor++) { + if (pvendor->id != vendor) { + continue; + } - if (!gpu->vendor.length) + if (!gpu->vendor.length) { ffStrbufSetS(&gpu->vendor, pvendor->name); + } const FFPciDevice* pdevice = (const FFPciDevice*) bsearch(&device, pvendor->devices, pvendor->nDevices, sizeof(*pdevice), (void*) pciDeviceCmp); - if (pdevice) - { + if (pdevice) { uint32_t nameLen = (uint32_t) strlen(pdevice->name); const char* closingBracket = pdevice->name + nameLen - 1; - if (*closingBracket == ']') - { + if (*closingBracket == ']') { const char* openingBracket = memrchr(pdevice->name, '[', nameLen - 1); - if (openingBracket) - { + if (openingBracket) { openingBracket++; ffStrbufSetNS(&gpu->name, (uint32_t) (closingBracket - openingBracket), openingBracket); } } - if (!gpu->name.length) + if (!gpu->name.length) { ffStrbufSetNS(&gpu->name, nameLen, pdevice->name); + } return true; } - if (!gpu->name.length) - { + if (!gpu->name.length) { const char* subclassStr; - switch (subclass) - { - case 0 /*PCI_CLASS_DISPLAY_VGA*/: subclassStr = " (VGA compatible)"; break; - case 1 /*PCI_CLASS_DISPLAY_XGA*/: subclassStr = " (XGA compatible)"; break; - case 2 /*PCI_CLASS_DISPLAY_3D*/: subclassStr = " (3D)"; break; - default: subclassStr = ""; break; + switch (subclass) { + case 0 /*PCI_CLASS_DISPLAY_VGA*/: + subclassStr = " (VGA compatible)"; + break; + case 1 /*PCI_CLASS_DISPLAY_XGA*/: + subclassStr = " (XGA compatible)"; + break; + case 2 /*PCI_CLASS_DISPLAY_3D*/: + subclassStr = " (3D)"; + break; + default: + subclassStr = ""; + break; } ffStrbufSetF(&gpu->name, "%s Device %04X%s", gpu->vendor.length ? gpu->vendor.chars : "Unknown", device, subclassStr); @@ -190,28 +198,26 @@ static bool loadPciidsInc(uint8_t subclass, uint16_t vendor, uint16_t device, FF } #endif -void ffGPUFillVendorAndName(uint8_t subclass, uint16_t vendor, uint16_t device, FFGPUResult* gpu) -{ - #if FF_HAVE_EMBEDDED_PCIIDS +void ffGPUFillVendorAndName(uint8_t subclass, uint16_t vendor, uint16_t device, FFGPUResult* gpu) { +#if FF_HAVE_EMBEDDED_PCIIDS bool ok = loadPciidsInc(subclass, vendor, device, gpu); - if (ok) return; - #endif + if (ok) { + return; + } +#endif return parsePciIdsFile(loadPciIds(), subclass, vendor, device, gpu); } #if FF_HAVE_EMBEDDED_AMDGPUIDS -static inline int amdGpuCmp(const uint32_t* key, const FFArmGpuProduct* element) -{ +static inline int amdGpuCmp(const uint32_t* key, const FFArmGpuProduct* element) { // Maximum value of *key is 0x00FFFFFF. `(int) *key` should never overflow return (int) *key - (int) element->id; } -static bool loadAmdGpuIdsInc(uint16_t deviceId, uint8_t revision, FFGPUResult* gpu) -{ +static bool loadAmdGpuIdsInc(uint16_t deviceId, uint8_t revision, FFGPUResult* gpu) { uint32_t key = (deviceId << 8u) | revision; FFArmGpuProduct* product = bsearch(&key, ffAmdGpuProducts, ARRAY_SIZE(ffAmdGpuProducts), sizeof(*ffAmdGpuProducts), (void*) amdGpuCmp); - if (product) - { + if (product) { ffStrbufSetS(&gpu->name, product->name); return true; } @@ -219,22 +225,22 @@ static bool loadAmdGpuIdsInc(uint16_t deviceId, uint8_t revision, FFGPUResult* g } #endif -static void parseAmdGpuIdsFile(uint16_t deviceId, uint8_t revision, FFGPUResult* gpu) -{ +static void parseAmdGpuIdsFile(uint16_t deviceId, uint8_t revision, FFGPUResult* gpu) { char query[32]; snprintf(query, ARRAY_SIZE(query), "%X,\t%X,", (unsigned) deviceId, (unsigned) revision); - #ifdef FF_CUSTOM_AMDGPU_IDS_PATH +#ifdef FF_CUSTOM_AMDGPU_IDS_PATH ffParsePropFile(FF_STR(FF_CUSTOM_AMDGPU_IDS_PATH), query, &gpu->name); - #else +#else ffParsePropFileData("libdrm/amdgpu.ids", query, &gpu->name); - #endif +#endif } -void ffGPUQueryAmdGpuName(uint16_t deviceId, uint8_t revisionId, FFGPUResult* gpu) -{ - #if FF_HAVE_EMBEDDED_AMDGPUIDS +void ffGPUQueryAmdGpuName(uint16_t deviceId, uint8_t revisionId, FFGPUResult* gpu) { +#if FF_HAVE_EMBEDDED_AMDGPUIDS bool ok = loadAmdGpuIdsInc(deviceId, revisionId, gpu); - if (ok) return; - #endif + if (ok) { + return; + } +#endif return parseAmdGpuIdsFile(deviceId, revisionId, gpu); } diff --git a/src/detection/gpu/gpu_sunos.c b/src/detection/gpu/gpu_sunos.c index da2bcd0ba..e9842ec93 100644 --- a/src/detection/gpu/gpu_sunos.c +++ b/src/detection/gpu/gpu_sunos.c @@ -3,14 +3,11 @@ #include -static int walkDevTree(di_node_t node, FF_MAYBE_UNUSED di_minor_t minor, FFlist* gpus) -{ +static int walkDevTree(di_node_t node, FF_MAYBE_UNUSED di_minor_t minor, FFlist* gpus) { int* vendorId; int* deviceId; - if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "vendor-id", &vendorId) > 0 - && di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-id", &deviceId) > 0) - { - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "vendor-id", &vendorId) > 0 && di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-id", &deviceId) > 0) { + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); ffStrbufInitS(&gpu->vendor, ffGPUGetVendorString((uint16_t) *vendorId)); ffStrbufInit(&gpu->name); ffStrbufInitS(&gpu->driver, di_driver_name(node)); @@ -25,19 +22,19 @@ static int walkDevTree(di_node_t node, FF_MAYBE_UNUSED di_minor_t minor, FFlist* gpu->deviceId = strtoul(di_bus_addr(node), NULL, 16); gpu->frequency = FF_GPU_FREQUENCY_UNSET; - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) - { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { int* revId; - if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "revision-id", &revId) > 0) + if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "revision-id", &revId) > 0) { ffGPUQueryAmdGpuName((uint16_t) *deviceId, (uint8_t) *revId, gpu); + } } - if (gpu->name.length == 0) - { + if (gpu->name.length == 0) { uint8_t subclass = 0; // assume VGA int* classCode; - if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "class-code", &classCode) > 0) + if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "class-code", &classCode) > 0) { subclass = (uint8_t) (*classCode & 0xFFFF); + } ffGPUFillVendorAndName(subclass, (uint16_t) *vendorId, (uint16_t) *deviceId, gpu); } } @@ -45,11 +42,11 @@ static int walkDevTree(di_node_t node, FF_MAYBE_UNUSED di_minor_t minor, FFlist* return DI_WALK_CONTINUE; } -const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) { di_node_t rootNode = di_init("/", DINFOCPYALL); - if (rootNode == DI_NODE_NIL) + if (rootNode == DI_NODE_NIL) { return "di_init() failed"; + } di_walk_minor(rootNode, DDI_NT_DISPLAY, DI_WALK_CLDFIRST, gpus, (void*) walkDevTree); di_fini(rootNode); diff --git a/src/detection/gpu/gpu_windows.c b/src/detection/gpu/gpu_windows.c index acfc609b6..7dcc8b16a 100644 --- a/src/detection/gpu/gpu_windows.c +++ b/src/detection/gpu/gpu_windows.c @@ -20,20 +20,18 @@ const uint32_t regDriverKeyPrefixLength = (uint32_t) __builtin_strlen("SYSTEM\\C #define GUID_DEVCLASS_DISPLAY_STRING L"{4d36e968-e325-11ce-bfc1-08002be10318}" // Found in -static inline void wrapRegCloseKey(HKEY* phKey) -{ - if(*phKey) +static inline void wrapRegCloseKey(HKEY* phKey) { + if (*phKey) { RegCloseKey(*phKey); + } } #define FF_HKEY_AUTO_DESTROY __attribute__((__cleanup__(wrapRegCloseKey))) -const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus) { FF_DEBUG("Starting GPU detection"); ULONG devIdListSize = 0; - if (CM_Get_Device_ID_List_SizeW(&devIdListSize, GUID_DEVCLASS_DISPLAY_STRING, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT) != CR_SUCCESS || devIdListSize <= 1) - { + if (CM_Get_Device_ID_List_SizeW(&devIdListSize, GUID_DEVCLASS_DISPLAY_STRING, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT) != CR_SUCCESS || devIdListSize <= 1) { FF_DEBUG("No display devices found, list size: %lu", devIdListSize); return "No display devices found"; } @@ -42,33 +40,30 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* FF_AUTO_FREE DEVINSTID_W devIdList = malloc(devIdListSize * sizeof(*devIdList)); - if (CM_Get_Device_ID_ListW(GUID_DEVCLASS_DISPLAY_STRING, devIdList, devIdListSize, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT) != CR_SUCCESS) - { + if (CM_Get_Device_ID_ListW(GUID_DEVCLASS_DISPLAY_STRING, devIdList, devIdListSize, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT) != CR_SUCCESS) { FF_DEBUG("CM_Get_Device_ID_ListW failed"); return "CM_Get_Device_ID_ListW failed"; } FF_MAYBE_UNUSED int deviceCount = 0; - for (wchar_t* devId = devIdList; *devId; devId += wcslen(devId) + 1) - { + for (wchar_t* devId = devIdList; *devId; devId += wcslen(devId) + 1) { FF_DEBUG("Processing device ID: %ls", devId); DEVINST devInst = 0; - if (CM_Locate_DevNodeW(&devInst, devId, CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS) - { + if (CM_Locate_DevNodeW(&devInst, devId, CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS) { FF_DEBUG("Failed to get device instance ID or locate device node"); continue; } FF_DEBUG("Device instance ID: %lu", devInst); - for (wchar_t* p = devId; *p; p++) - { - if (*p >= L'a' && *p <= L'z') + for (wchar_t* p = devId; *p; p++) { + if (*p >= L'a' && *p <= L'z') { *p -= L'a' - L'A'; + } } - FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus); + FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus); deviceCount++; FF_DEBUG("Added GPU #%d to list", deviceCount); @@ -87,37 +82,28 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpu->frequency = FF_GPU_FREQUENCY_UNSET; unsigned vendorId = 0, deviceId = 0, subSystemId = 0, revId = 0; - if (swscanf(devId, L"PCI\\VEN_%x&DEV_%x&SUBSYS_%x&REV_%x", &vendorId, &deviceId, &subSystemId, &revId) == 4) - { + if (swscanf(devId, L"PCI\\VEN_%x&DEV_%x&SUBSYS_%x&REV_%x", &vendorId, &deviceId, &subSystemId, &revId) == 4) { FF_DEBUG("Parsed PCI IDs - Vendor: 0x%x, Device: 0x%x, SubSystem: 0x%x, Rev: 0x%x", vendorId, deviceId, subSystemId, revId); ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(vendorId)); - } - else - { + } else { FF_DEBUG("Failed to parse PCI device information from instance ID"); } uint32_t pciBus = 0, pciAddr = 0, pciDev = 0, pciFunc = 0; ULONG pciBufLen = sizeof(pciBus); - if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_BUSNUMBER, NULL, &pciBus, &pciBufLen, 0) == CR_SUCCESS) - { + if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_BUSNUMBER, NULL, &pciBus, &pciBufLen, 0) == CR_SUCCESS) { pciBufLen = sizeof(pciAddr); - if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_ADDRESS, NULL, &pciAddr, &pciBufLen, 0) == CR_SUCCESS) - { + if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_ADDRESS, NULL, &pciAddr, &pciBufLen, 0) == CR_SUCCESS) { pciDev = (pciAddr >> 16) & 0xFFFF; pciFunc = pciAddr & 0xFFFF; gpu->deviceId = ffGPUPciAddr2Id(0, pciBus, pciDev, pciFunc); pciAddr = 1; // Set to 1 to indicate that the device is a PCI device FF_DEBUG("PCI location - Bus: %u, Device: %u, Function: %u, DeviceID: %llu", pciBus, pciDev, pciFunc, gpu->deviceId); - } - else - { + } else { FF_DEBUG("Failed to get PCI address"); } - } - else - { + } else { FF_DEBUG("Failed to get PCI bus number"); } @@ -130,164 +116,130 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* 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) - { + 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 - { + } else { FF_DEBUG("Failed to get device description"); } - if (wcsncmp(devId, L"SWD\\", 4) == 0 || wcsncmp(devId, L"ROOT\\DISPLAY\\", 13) == 0) - { + 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) - { + 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"); bufferLen = sizeof(buffer); if (RegGetValueW(hVideoIdKey, NULL, L"VideoID", RRF_RT_REG_SZ, NULL, buffer, &bufferLen) == ERROR_SUCCESS && - bufferLen == (FF_GUID_STRLEN + 1) * sizeof(wchar_t)) - { + bufferLen == (FF_GUID_STRLEN + 1) * sizeof(wchar_t)) { FF_DEBUG("Found VideoID: %ls", buffer); wmemcpy(regDirectxKey + regDirectxKeyPrefixLength, buffer, FF_GUID_STRLEN); FF_AUTO_CLOSE_FD HANDLE hDirectxKey = NULL; - if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regDirectxKey, &hDirectxKey, NULL)) - { + if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regDirectxKey, &hDirectxKey, NULL)) { FF_DEBUG("Opened DirectX registry key"); - if (gpu->vendor.length == 0) - { + if (gpu->vendor.length == 0) { uint32_t vendorId = 0; - if(ffRegReadUint(hDirectxKey, L"VendorId", &vendorId, NULL) && vendorId) - { + if (ffRegReadUint(hDirectxKey, L"VendorId", &vendorId, NULL) && vendorId) { FF_DEBUG("Found vendor ID from DirectX registry: 0x%x", vendorId); ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(vendorId)); } } - if (gpu->name.length == 0) - { + if (gpu->name.length == 0) { FF_DEBUG("Trying to get GPU name from DirectX registry"); - if (ffRegReadStrbuf(hDirectxKey, L"Description", &gpu->name, NULL)) + 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)) + if (ffRegReadUint64(hDirectxKey, L"DedicatedVideoMemory", &gpu->dedicated.total, NULL)) { FF_DEBUG("Found dedicated video memory: %llu bytes", gpu->dedicated.total); + } - if (ffRegReadUint64(hDirectxKey, L"DedicatedSystemMemory", &gpu->shared.total, NULL)) - { + if (ffRegReadUint64(hDirectxKey, L"DedicatedSystemMemory", &gpu->shared.total, NULL)) { FF_DEBUG("Found dedicated system memory: %llu bytes", gpu->shared.total); uint64_t sharedSystemMemory = 0; - if (ffRegReadUint64(hDirectxKey, L"SharedSystemMemory", &sharedSystemMemory, NULL)) - { + if (ffRegReadUint64(hDirectxKey, L"SharedSystemMemory", &sharedSystemMemory, NULL)) { gpu->shared.total += sharedSystemMemory; FF_DEBUG("Added shared system memory: %llu bytes, total shared: %llu bytes", sharedSystemMemory, gpu->shared.total); } } - if (ffRegReadUint64(hDirectxKey, L"AdapterLuid", &adapterLuid, NULL)) - { + if (ffRegReadUint64(hDirectxKey, L"AdapterLuid", &adapterLuid, NULL)) { FF_DEBUG("Found adapter LUID: %llu", adapterLuid); - if (!gpu->deviceId) gpu->deviceId = ffGPUGeneral2Id(adapterLuid); + if (!gpu->deviceId) { + gpu->deviceId = ffGPUGeneral2Id(adapterLuid); + } } uint32_t featureLevel = 0; - if(ffRegReadUint(hDirectxKey, L"MaxD3D12FeatureLevel", &featureLevel, NULL) && featureLevel) - { + if (ffRegReadUint(hDirectxKey, L"MaxD3D12FeatureLevel", &featureLevel, NULL) && featureLevel) { FF_DEBUG("Found D3D12 feature level: 0x%x", featureLevel); ffStrbufSetF(&gpu->platformApi, "Direct3D 12.%u", (featureLevel & 0x0F00) >> 8); - } - else if(ffRegReadUint(hDirectxKey, L"MaxD3D11FeatureLevel", &featureLevel, NULL) && featureLevel) - { + } else if (ffRegReadUint(hDirectxKey, L"MaxD3D11FeatureLevel", &featureLevel, NULL) && featureLevel) { FF_DEBUG("Found D3D11 feature level: 0x%x", featureLevel); ffStrbufSetF(&gpu->platformApi, "Direct3D 11.%u", (featureLevel & 0x0F00) >> 8); } uint64_t driverVersion = 0; - if(ffRegReadUint64(hDirectxKey, L"DriverVersion", &driverVersion, NULL) && driverVersion) - { + if (ffRegReadUint64(hDirectxKey, L"DriverVersion", &driverVersion, NULL) && driverVersion) { FF_DEBUG("Found driver version: %llu", driverVersion); - ffStrbufSetF(&gpu->driver, "%u.%u.%u.%u", - (unsigned) (driverVersion >> 48) & 0xFFFF, - (unsigned) (driverVersion >> 32) & 0xFFFF, - (unsigned) (driverVersion >> 16) & 0xFFFF, - (unsigned) (driverVersion >> 0) & 0xFFFF - ); + ffStrbufSetF(&gpu->driver, "%u.%u.%u.%u", (unsigned) (driverVersion >> 48) & 0xFFFF, (unsigned) (driverVersion >> 32) & 0xFFFF, (unsigned) (driverVersion >> 16) & 0xFFFF, (unsigned) (driverVersion >> 0) & 0xFFFF); } - } - else - { + } else { FF_DEBUG("Failed to open DirectX registry key"); } - } - else - { + } else { FF_DEBUG("Failed to get VideoID or invalid buffer length"); } - } - else - { + } else { FF_DEBUG("Failed to open device node registry key"); } - if (gpu->vendor.length == 0 || gpu->name.length == 0 || gpu->driver.length == 0 || gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET) - { + if (gpu->vendor.length == 0 || gpu->name.length == 0 || gpu->driver.length == 0 || gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET) { FF_DEBUG("Trying fallback registry method for vendor/name etc."); bufferLen = sizeof(buffer); if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_DRIVER, NULL, buffer, &bufferLen, 0) == CR_SUCCESS && - bufferLen == (FF_GUID_STRLEN + strlen("\\0000") + 1) * 2) - { + bufferLen == (FF_GUID_STRLEN + strlen("\\0000") + 1) * 2) { FF_DEBUG("Found driver GUID: %ls", buffer); wmemcpy(regDriverKey + regDriverKeyPrefixLength, buffer, FF_GUID_STRLEN + strlen("\\0000")); FF_AUTO_CLOSE_FD HANDLE hRegDriverKey = NULL; - if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regDriverKey, &hRegDriverKey, NULL)) - { + if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regDriverKey, &hRegDriverKey, NULL)) { FF_DEBUG("Opened driver registry key"); - if (gpu->vendor.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"ProviderName", &gpu->vendor, NULL)) - { + if (gpu->vendor.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"ProviderName", &gpu->vendor, NULL)) { FF_DEBUG("Found provider name: %s", gpu->vendor.chars); - if (ffStrbufContainS(&gpu->vendor, "Intel")) + if (ffStrbufContainS(&gpu->vendor, "Intel")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_INTEL); - else if (ffStrbufContainS(&gpu->vendor, "NVIDIA")) + } else if (ffStrbufContainS(&gpu->vendor, "NVIDIA")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_NVIDIA); - else if (ffStrbufContainS(&gpu->vendor, "AMD") || ffStrbufContainS(&gpu->vendor, "ATI")) + } else if (ffStrbufContainS(&gpu->vendor, "AMD") || ffStrbufContainS(&gpu->vendor, "ATI")) { ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_AMD); + } } - if (gpu->name.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"DriverDesc", &gpu->name, NULL)) + if (gpu->name.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"DriverDesc", &gpu->name, NULL)) { FF_DEBUG("Found driver description: %s", gpu->name.chars); - if (gpu->driver.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"DriverVersion", &gpu->driver, NULL)) + } + if (gpu->driver.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"DriverVersion", &gpu->driver, NULL)) { FF_DEBUG("Found driver version: %s", gpu->driver.chars); - if (gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET) - { - if (!ffRegReadUint64(hRegDriverKey, L"HardwareInformation.qwMemorySize", &gpu->dedicated.total, NULL)) - { + } + if (gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET) { + if (!ffRegReadUint64(hRegDriverKey, L"HardwareInformation.qwMemorySize", &gpu->dedicated.total, NULL)) { uint32_t memorySize = 0; - if (ffRegReadUint(hRegDriverKey, L"HardwareInformation.MemorySize", &memorySize, NULL)) - { + if (ffRegReadUint(hRegDriverKey, L"HardwareInformation.MemorySize", &memorySize, NULL)) { gpu->dedicated.total = memorySize; FF_DEBUG("Found memory size from hardware info: %u bytes", memorySize); } - } - else - { + } else { FF_DEBUG("Found qwMemorySize from hardware info: %llu bytes", gpu->dedicated.total); } } - } - else - { + } else { FF_DEBUG("Failed to open driver registry key"); } - } - else - { + } else { FF_DEBUG("Failed to get driver GUID or invalid buffer length"); } } @@ -295,14 +247,11 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* __typeof__(&ffDetectNvidiaGpuInfo) detectFn; const char* dllName; - if (options->driverSpecific && getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &dllName)) - { + if (options->driverSpecific && getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &dllName)) { FF_DEBUG("Calling driver-specific detection function for vendor: %s, DLL: %s", gpu->vendor.chars, dllName); FF_MAYBE_UNUSED const char* error = detectFn( &(FFGpuDriverCondition) { - .type = (deviceId > 0 ? FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID : 0) - | (adapterLuid > 0 ? FF_GPU_DRIVER_CONDITION_TYPE_LUID : 0) - | (pciAddr > 0 ? FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID : 0), + .type = (deviceId > 0 ? FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID : 0) | (adapterLuid > 0 ? FF_GPU_DRIVER_CONDITION_TYPE_LUID : 0) | (pciAddr > 0 ? FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID : 0), .pciDeviceId = { .deviceId = deviceId, .vendorId = vendorId, @@ -317,7 +266,7 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* }, .luid = adapterLuid, }, - (FFGpuDriverResult){ + (FFGpuDriverResult) { .index = &gpu->index, .temp = options->temp ? &gpu->temperature : NULL, .memory = options->driverSpecific ? &gpu->dedicated : NULL, @@ -329,21 +278,16 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* .name = &gpu->name, .frequency = options->driverSpecific ? &gpu->frequency : NULL, }, - dllName - ); + dllName); FF_DEBUG("Driver-specific detection completed: %s", error ?: "Success"); - } - else if (options->driverSpecific) - { + } else if (options->driverSpecific) { FF_DEBUG("No driver-specific detection function found for vendor: %s", gpu->vendor.chars); } - if (gpu->type == FF_GPU_TYPE_UNKNOWN && adapterLuid > 0) - { + if (gpu->type == FF_GPU_TYPE_UNKNOWN && adapterLuid > 0) { FF_DEBUG("Trying to determine GPU type using D3DKMT APIs"); - D3DKMT_OPENADAPTERFROMLUID openAdapterFromLuid = { .AdapterLuid = *(LUID*)&adapterLuid }; - if (NT_SUCCESS(D3DKMTOpenAdapterFromLuid(&openAdapterFromLuid))) - { + D3DKMT_OPENADAPTERFROMLUID openAdapterFromLuid = {.AdapterLuid = *(LUID*) &adapterLuid}; + if (NT_SUCCESS(D3DKMTOpenAdapterFromLuid(&openAdapterFromLuid))) { FF_DEBUG("Successfully opened adapter from LUID"); D3DKMT_ADAPTERTYPE adapterType = {}; @@ -353,24 +297,20 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* .pPrivateDriverData = &adapterType, .PrivateDriverDataSize = sizeof(adapterType), }; - if (NT_SUCCESS(D3DKMTQueryAdapterInfo(&queryAdapterInfo))) - { + if (NT_SUCCESS(D3DKMTQueryAdapterInfo(&queryAdapterInfo))) { FF_DEBUG("Queried adapter type - HybridDiscrete: %d, HybridIntegrated: %d", adapterType.HybridDiscrete, adapterType.HybridIntegrated); - if (adapterType.HybridDiscrete) + if (adapterType.HybridDiscrete) { gpu->type = FF_GPU_TYPE_DISCRETE; - else if (adapterType.HybridIntegrated) + } else if (adapterType.HybridIntegrated) { gpu->type = FF_GPU_TYPE_INTEGRATED; - } - else - { + } + } else { FF_DEBUG("Failed to query adapter type"); } - if (gpu->frequency == FF_GPU_FREQUENCY_UNSET && ffIsWindows11OrGreater()) - { + if (gpu->frequency == FF_GPU_FREQUENCY_UNSET && ffIsWindows11OrGreater()) { FF_DEBUG("Trying to get GPU frequency information"); - for (ULONG nodeIdx = 0; ; nodeIdx++) - { + for (ULONG nodeIdx = 0;; nodeIdx++) { D3DKMT_NODEMETADATA nodeMetadata = { .NodeOrdinalAndAdapterIndex = (0 << 16) | nodeIdx, }; @@ -380,78 +320,65 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* .pPrivateDriverData = &nodeMetadata, .PrivateDriverDataSize = sizeof(nodeMetadata), }; - if (!NT_SUCCESS(D3DKMTQueryAdapterInfo(&queryAdapterInfo))) - { + if (!NT_SUCCESS(D3DKMTQueryAdapterInfo(&queryAdapterInfo))) { FF_DEBUG("No more nodes to query (index %lu)", nodeIdx); break; } - if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D) - { + if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D) { FF_DEBUG("Skipping node %lu (not 3D engine)", nodeIdx); continue; } D3DKMT_QUERYSTATISTICS queryStatistics = { .Type = D3DKMT_QUERYSTATISTICS_NODE2, // Windows 11 (22H2) and later - .AdapterLuid = *(LUID*)&adapterLuid, - .QueryNode2 = { .PhysicalAdapterIndex = 0, .NodeOrdinal = (UINT16) nodeIdx }, + .AdapterLuid = *(LUID*) &adapterLuid, + .QueryNode2 = {.PhysicalAdapterIndex = 0, .NodeOrdinal = (UINT16) nodeIdx}, }; - if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics))) - { + if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics))) { gpu->frequency = (uint32_t) (queryStatistics.QueryResult.NodeInformation.NodePerfData.MaxFrequency / 1000 / 1000); FF_DEBUG("Found GPU frequency: %u MHz", gpu->frequency); break; - } - else - { + } else { FF_DEBUG("Failed to query node statistics for node %lu", nodeIdx); } } } - D3DKMT_CLOSEADAPTER closeAdapter = { .hAdapter = openAdapterFromLuid.hAdapter }; + D3DKMT_CLOSEADAPTER closeAdapter = {.hAdapter = openAdapterFromLuid.hAdapter}; (void) D3DKMTCloseAdapter(&closeAdapter); openAdapterFromLuid.hAdapter = (D3DKMT_HANDLE) {}; FF_DEBUG("Closed adapter handle"); - } - else - { + } else { FF_DEBUG("Failed to open adapter from LUID"); } - if (options->temp && gpu->temperature == FF_GPU_TEMP_UNSET && ffIsWindows10OrGreater()) - { + if (options->temp && gpu->temperature == FF_GPU_TEMP_UNSET && ffIsWindows10OrGreater()) { FF_DEBUG("Trying to get GPU temperature"); D3DKMT_QUERYSTATISTICS queryStatistics = { .Type = D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER, // Windows 10 (1803) and later - .AdapterLuid = *(LUID*)&adapterLuid, - .QueryPhysAdapter = { .PhysicalAdapterIndex = 0 }, + .AdapterLuid = *(LUID*) &adapterLuid, + .QueryPhysAdapter = {.PhysicalAdapterIndex = 0}, }; if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics)) && - queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature != 0) - { + queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature != 0) { gpu->temperature = queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature / 10.0; FF_DEBUG("Found GPU temperature: %.1f°C", gpu->temperature); - } - else - { + } else { FF_DEBUG("Failed to get GPU temperature or temperature is 0"); } } - if (options->driverSpecific && gpu->dedicated.used == FF_GPU_VMEM_SIZE_UNSET && ffIsWindows11OrGreater()) - { + if (options->driverSpecific && gpu->dedicated.used == FF_GPU_VMEM_SIZE_UNSET && ffIsWindows11OrGreater()) { FF_DEBUG("Trying to get used video memory from D3DKMT method"); D3DKMT_QUERYSTATISTICS queryStatistics = { .Type = D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE, - .AdapterLuid = *(LUID*)&adapterLuid, + .AdapterLuid = *(LUID*) &adapterLuid, .QuerySegmentGroupUsage = { .PhysicalAdapterIndex = 0, .SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_LOCAL, }, }; - if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics))) - { + if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics))) { D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; uint64_t total = used + info->FreeBytes + info->ZeroBytes; @@ -459,15 +386,12 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpu->dedicated.total = total; FF_DEBUG("Found local memory size %llu / %llu", used, total); - } - else - { + } else { FF_DEBUG("Failed to query segment group usage for local memory"); } queryStatistics.QuerySegmentGroupUsage.SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_NON_LOCAL; - if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics))) - { + if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics))) { D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; uint64_t total = used + info->FreeBytes + info->ZeroBytes; @@ -475,45 +399,38 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpu->shared.total = total; FF_DEBUG("Found non-local memory size %llu / %llu", used, total); - } - else - { + } else { FF_DEBUG("Failed to query segment group usage for non-local memory"); } } } - if (gpu->type == FF_GPU_TYPE_UNKNOWN) - { + if (gpu->type == FF_GPU_TYPE_UNKNOWN) { FF_DEBUG("Using fallback GPU type detection"); - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) - { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) { if (ffStrbufStartsWithIgnCaseS(&gpu->name, "GeForce") || ffStrbufStartsWithIgnCaseS(&gpu->name, "Quadro") || - ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) + ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) { gpu->type = FF_GPU_TYPE_DISCRETE; - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) - { - if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) { + if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) { gpu->type = FF_GPU_TYPE_DISCRETE; - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) - { + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) { // 0000:00:02.0 is reserved for Intel integrated graphics gpu->type = gpu->deviceId == ffGPUPciAddr2Id(0, 0, 2, 0) ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; } - if (gpu->type != FF_GPU_TYPE_UNKNOWN) + if (gpu->type != FF_GPU_TYPE_UNKNOWN) { FF_DEBUG("Determined GPU type based on vendor (%s) and name: %u", gpu->vendor.chars, gpu->type); - else if (ffIsWindows10OrGreater()) - { - const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult* gpu); - FF_MAYBE_UNUSED const char* error = ffGPUDetectTypeWithDXCore(*(LUID*)&adapterLuid, gpu); + } else if (ffIsWindows10OrGreater()) { + const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult * gpu); + FF_MAYBE_UNUSED const char* error = ffGPUDetectTypeWithDXCore(*(LUID*) &adapterLuid, gpu); FF_DEBUG("DXCore GPU type detection result: %s", error ?: "Success"); - } - else + } else { FF_DEBUG("Unable to determine GPU type by any method for this adapter"); + } } FF_DEBUG("Completed processing GPU #%d - Vendor: %s, Name: %s, Type: %d", deviceCount, gpu->vendor.chars, gpu->name.chars, gpu->type); diff --git a/src/detection/gpu/gpu_windows.cpp b/src/detection/gpu/gpu_windows.cpp index b123c5b7f..c22112aa8 100644 --- a/src/detection/gpu/gpu_windows.cpp +++ b/src/detection/gpu/gpu_windows.cpp @@ -1,5 +1,4 @@ -extern "C" -{ +extern "C" { #include "gpu.h" #include "common/library.h" #include "common/debug.h" @@ -7,16 +6,16 @@ extern "C" #if __has_include() && __has_include() -#include -#include -#include "common/windows/util.hpp" +# include +# include +# include "common/windows/util.hpp" -static IDXCoreAdapterFactory* loadDxCoreFactory() -{ +static IDXCoreAdapterFactory* loadDxCoreFactory() { static bool initialized = false; static IDXCoreAdapterFactory* factory = nullptr; - if (initialized) + if (initialized) { return factory; // Already loaded + } initialized = true; FF_LIBRARY_LOAD(dxcore, NULL, "dxcore" FF_LIBRARY_EXTENSION, 1) @@ -24,16 +23,17 @@ static IDXCoreAdapterFactory* loadDxCoreFactory() // DXCoreCreateAdapterFactory is a reloaded function, so we can't use FF_LIBRARY_LOAD_SYMBOL_MESSAGE here typedef HRESULT (*DXCoreCreateAdapterFactory_t)(REFIID riid, void** ppvFactory); - #ifndef FF_DISABLE_DLOPEN - auto ffDXCoreCreateAdapterFactory = (DXCoreCreateAdapterFactory_t) dlsym(dxcore, "DXCoreCreateAdapterFactory"); - if (ffDXCoreCreateAdapterFactory == nullptr) return NULL; - #else - auto ffDXCoreCreateAdapterFactory = (DXCoreCreateAdapterFactory_t) DXCoreCreateAdapterFactory; - #endif +# ifndef FF_DISABLE_DLOPEN + auto ffDXCoreCreateAdapterFactory = (DXCoreCreateAdapterFactory_t) dlsym(dxcore, "DXCoreCreateAdapterFactory"); + if (ffDXCoreCreateAdapterFactory == nullptr) { + return NULL; + } +# else + auto ffDXCoreCreateAdapterFactory = (DXCoreCreateAdapterFactory_t) DXCoreCreateAdapterFactory; +# endif HRESULT hr = ffDXCoreCreateAdapterFactory(IID_PPV_ARGS(&factory)); - if (FAILED(hr)) - { + if (FAILED(hr)) { FF_DEBUG("DXCoreCreateAdapterFactory failed with HRESULT: 0x%08lX (%s)", hr, ffDebugHResult(hr)); return NULL; } @@ -42,27 +42,24 @@ static IDXCoreAdapterFactory* loadDxCoreFactory() return factory; } -extern "C" -const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult* gpu) -{ +extern "C" const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult* gpu) { auto* factory = loadDxCoreFactory(); - if (!factory) + if (!factory) { return "Failed to load DXCore library or create adapter factory"; + } - IDXCoreAdapter *adapter = nullptr; + IDXCoreAdapter* adapter = nullptr; HRESULT hr = factory->GetAdapterByLuid(adapterLuid, IID_PPV_ARGS(&adapter)); - if (FAILED(hr)) - { + if (FAILED(hr)) { FF_DEBUG("GetAdapterByLuid failed with HRESULT: 0x%08lX (%s)", hr, ffDebugHResult(hr)); return "Failed to get adapter by LUID"; } - on_scope_exit releaseAdapter {[adapter] { adapter->Release(); }}; + on_scope_exit releaseAdapter{[adapter] { adapter->Release(); }}; bool isIntegrated = false; hr = adapter->GetProperty(DXCoreAdapterProperty::IsIntegrated, sizeof(isIntegrated), &isIntegrated); - if (FAILED(hr)) - { + if (FAILED(hr)) { FF_DEBUG("GetProperty(IsIntegrated) failed with HRESULT: 0x%08lX (%s)", hr, ffDebugHResult(hr)); return "Failed to get adapter properties"; } @@ -75,11 +72,9 @@ const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult* gpu) #else -#warning "DXCore headers not available, GPU type detection may be less accurate" +# warning "DXCore headers not available, GPU type detection may be less accurate" -extern "C" -const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult* gpu) -{ +extern "C" const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult* gpu) { FF_UNUSED(adapterLuid, gpu); FF_DEBUG("DXCore not available, skipping GPU type detection with DXCore"); return "DXCore not available"; diff --git a/src/detection/gpu/gpu_wsl.c b/src/detection/gpu/gpu_wsl.c index 5ea44782c..654e6b104 100644 --- a/src/detection/gpu/gpu_wsl.c +++ b/src/detection/gpu/gpu_wsl.c @@ -1,43 +1,37 @@ #if __x86_64__ || __aarch64__ // WSL2 only supports x86_64 and aarch64 -#include "detection/gpu/gpu.h" -#include "detection/gpu/gpu_driver_specific.h" -#include "common/io.h" -#include "common/debug.h" +# include "detection/gpu/gpu.h" +# include "detection/gpu/gpu_driver_specific.h" +# include "common/io.h" +# include "common/debug.h" -#include "d3dkmthk.h" -#include -#include -#include -#include +# include "d3dkmthk.h" +# include +# include +# include +# include -static void ffStrbufAppendUtf16(FFstrbuf* strbuf, const char16_t* str) -{ +static void ffStrbufAppendUtf16(FFstrbuf* strbuf, const char16_t* str) { mbstate_t state = {}; - while (*str) - { + while (*str) { char buf[5]; size_t len = c16rtomb(buf, *str, &state); - if (len == (size_t) -1) + if (len == (size_t) -1) { ffStrbufAppendS(strbuf, "�"); // U+FFFD REPLACEMENT CHARACTER - else if (len > 0) + } else if (len > 0) { ffStrbufAppendNS(strbuf, (uint32_t) len, buf); + } str++; } } -const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) -{ +const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) { FF_AUTO_CLOSE_FD int dxg = open("/dev/dxg", O_RDWR); // Windows DXCore/D3DKMT adapter driver for WSL - if (dxg < 0) - { - if (errno == ENOENT) - { + if (dxg < 0) { + if (errno == ENOENT) { FF_DEBUG("/dev/dxg is not available, WSL DXCore GPU driver not detected"); return "No DXCore GPU driver detected (no /dev/dxg)"; - } - else - { + } else { FF_DEBUG("Failed to open /dev/dxg: %s", strerror(errno)); return "Failed to open /dev/dxg"; } @@ -50,32 +44,28 @@ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) .NumAdapters = ARRAY_SIZE(adapters), .pAdapters = adapters, }; - if (!NT_SUCCESS(D3DKMTEnumAdapters2(dxg, &enumAdapters))) - { + if (!NT_SUCCESS(D3DKMTEnumAdapters2(dxg, &enumAdapters))) { FF_DEBUG("D3DKMTEnumAdapters2 failed: %s", strerror(errno)); return "Failed to enumerate adapters with D3DKMTEnumAdapters2"; } FF_DEBUG("D3DKMTEnumAdapters2 succeeded, adapter count: %u", enumAdapters.NumAdapters); - for (uint32_t i = 0; i < enumAdapters.NumAdapters; i++) - { + for (uint32_t i = 0; i < enumAdapters.NumAdapters; i++) { const D3DKMT_ADAPTERINFO* adapter = &adapters[i]; FF_DEBUG("Processing adapter #%u", i); D3DKMT_ADAPTERTYPE adapterType; if (!NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_ADAPTERTYPE, - .pPrivateDriverData = &adapterType, - .PrivateDriverDataSize = sizeof(adapterType), - }))) - { + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_ADAPTERTYPE, + .pPrivateDriverData = &adapterType, + .PrivateDriverDataSize = sizeof(adapterType), + }))) { FF_DEBUG("KMTQAITYPE_ADAPTERTYPE query failed for adapter #%u: %s", i, strerror(errno)); continue; } - if (adapterType.SoftwareDevice) - { + if (adapterType.SoftwareDevice) { FF_DEBUG("Skipping software adapter #%u", i); continue; } @@ -96,100 +86,83 @@ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) gpu->type = adapterType.HybridIntegrated ? FF_GPU_TYPE_INTEGRATED : adapterType.HybridDiscrete - ? FF_GPU_TYPE_DISCRETE - : FF_GPU_TYPE_UNKNOWN; + ? FF_GPU_TYPE_DISCRETE + : FF_GPU_TYPE_UNKNOWN; const char* vendorStr = NULL; - D3DKMT_QUERY_DEVICE_IDS deviceIds = { .PhysicalAdapterIndex = 0 }; + D3DKMT_QUERY_DEVICE_IDS deviceIds = {.PhysicalAdapterIndex = 0}; if (NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_PHYSICALADAPTERDEVICEIDS, - .pPrivateDriverData = &deviceIds, - .PrivateDriverDataSize = sizeof(deviceIds), - }))) - { + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_PHYSICALADAPTERDEVICEIDS, + .pPrivateDriverData = &deviceIds, + .PrivateDriverDataSize = sizeof(deviceIds), + }))) { vendorStr = ffGPUGetVendorString(deviceIds.DeviceIds.VendorID); ffStrbufSetStatic(&gpu->vendor, vendorStr); FF_DEBUG("Adapter #%u vendor/device IDs: vendor=0x%04x device=0x%04x", i, deviceIds.DeviceIds.VendorID, deviceIds.DeviceIds.DeviceID); - } - else + } else { FF_DEBUG("KMTQAITYPE_PHYSICALADAPTERDEVICEIDS query failed for adapter #%u: %s", i, strerror(errno)); + } D3DKMT_ADAPTERADDRESS adapterAddress; if (NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_ADAPTERADDRESS, - .pPrivateDriverData = &adapterAddress, - .PrivateDriverDataSize = sizeof(adapterAddress), - }))) - { + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_ADAPTERADDRESS, + .pPrivateDriverData = &adapterAddress, + .PrivateDriverDataSize = sizeof(adapterAddress), + }))) { gpu->deviceId = ffGPUPciAddr2Id(0, adapterAddress.BusNumber, adapterAddress.DeviceNumber, adapterAddress.FunctionNumber); FF_DEBUG("Adapter #%u PCI address: bus=%u device=%u function=%u", i, adapterAddress.BusNumber, adapterAddress.DeviceNumber, adapterAddress.FunctionNumber); - } - else - { + } else { adapterAddress.BusNumber = -1u; - gpu->deviceId = ffGPUGeneral2Id(((uint64_t)adapter->AdapterLuid.HighPart << 32) | (uint64_t)adapter->AdapterLuid.LowPart); + gpu->deviceId = ffGPUGeneral2Id(((uint64_t) adapter->AdapterLuid.HighPart << 32) | (uint64_t) adapter->AdapterLuid.LowPart); FF_DEBUG("KMTQAITYPE_ADAPTERADDRESS query failed for adapter #%u, fallback to LUID-based deviceId: %s", i, strerror(errno)); } D3DKMT_UMD_DRIVER_VERSION umdDriverVersion; if (NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_UMD_DRIVER_VERSION, - .pPrivateDriverData = &umdDriverVersion, - .PrivateDriverDataSize = sizeof(umdDriverVersion), - }))) - { - ffStrbufSetF(&gpu->driver, "%lu.%lu.%lu.%lu", - umdDriverVersion.DriverVersion.QuadPart >> 48ul & 0xFFFF, - umdDriverVersion.DriverVersion.QuadPart >> 32ul & 0xFFFF, - umdDriverVersion.DriverVersion.QuadPart >> 16ul & 0xFFFF, - umdDriverVersion.DriverVersion.QuadPart >> 0ul & 0xFFFF); + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_UMD_DRIVER_VERSION, + .pPrivateDriverData = &umdDriverVersion, + .PrivateDriverDataSize = sizeof(umdDriverVersion), + }))) { + ffStrbufSetF(&gpu->driver, "%lu.%lu.%lu.%lu", umdDriverVersion.DriverVersion.QuadPart >> 48ul & 0xFFFF, umdDriverVersion.DriverVersion.QuadPart >> 32ul & 0xFFFF, umdDriverVersion.DriverVersion.QuadPart >> 16ul & 0xFFFF, umdDriverVersion.DriverVersion.QuadPart >> 0ul & 0xFFFF); FF_DEBUG("Adapter #%u UMD driver version: %08lX", i, (unsigned long) umdDriverVersion.DriverVersion.QuadPart); - } - else - { + } else { FF_DEBUG("KMTQAITYPE_UMD_DRIVER_VERSION query failed for adapter #%u: %s", i, strerror(errno)); } D3DKMT_DRIVERVERSION wddmVersion = KMT_DRIVERVERSION_WDDM_3_0; if (NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_DRIVERVERSION, - .pPrivateDriverData = &wddmVersion, - .PrivateDriverDataSize = sizeof(wddmVersion), - }))) - { + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_DRIVERVERSION, + .pPrivateDriverData = &wddmVersion, + .PrivateDriverDataSize = sizeof(wddmVersion), + }))) { ffStrbufSetF(&gpu->platformApi, "WDDM %u.%u", wddmVersion / 1000, (wddmVersion % 1000) / 100); FF_DEBUG("Adapter #%u WDDM version: %u", i, wddmVersion); - } - else - { + } else { ffStrbufSetStatic(&gpu->platformApi, "WDDM"); FF_DEBUG("KMTQAITYPE_DRIVERVERSION query failed for adapter #%u", i); } - if (gpu->name.length == 0) - { + if (gpu->name.length == 0) { D3DKMT_ADAPTERREGISTRYINFO registryInfo; if (NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_ADAPTERREGISTRYINFO, - .pPrivateDriverData = ®istryInfo, - .PrivateDriverDataSize = sizeof(registryInfo), - }))) - { + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_ADAPTERREGISTRYINFO, + .pPrivateDriverData = ®istryInfo, + .PrivateDriverDataSize = sizeof(registryInfo), + }))) { ffStrbufAppendUtf16(&gpu->name, registryInfo.AdapterString); FF_DEBUG("Adapter #%u adapter string: %s", i, gpu->name.chars); - } - else + } else { FF_DEBUG("KMTQAITYPE_ADAPTERREGISTRYINFO query failed for adapter #%u: %s", i, strerror(errno)); + } } - if (vendorStr == FF_GPU_VENDOR_NAME_NVIDIA && options->driverSpecific) - { + if (vendorStr == FF_GPU_VENDOR_NAME_NVIDIA && options->driverSpecific) { FF_DEBUG("Trying NVIDIA driver-specific detection for adapter #%u", i); FFGpuDriverCondition cond = { .type = FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID | (adapterAddress.DeviceNumber != -1u ? FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID : 0), @@ -206,26 +179,26 @@ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) .func = adapterAddress.FunctionNumber, }, }; - const char* error = ffDetectNvidiaGpuInfo(&cond, (FFGpuDriverResult){ - .index = &gpu->index, - .temp = options->temp ? &gpu->temperature : NULL, - .memory = options->driverSpecific ? &gpu->dedicated : NULL, - .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : NULL, - .coreUsage = options->driverSpecific ? &gpu->coreUsage : NULL, - .type = &gpu->type, - .frequency = options->driverSpecific ? &gpu->frequency : NULL, - .name = &gpu->name, - }, "/usr/lib/wsl/lib/libnvidia-ml.so"); - if (error) + const char* error = ffDetectNvidiaGpuInfo(&cond, (FFGpuDriverResult) { + .index = &gpu->index, + .temp = options->temp ? &gpu->temperature : NULL, + .memory = options->driverSpecific ? &gpu->dedicated : NULL, + .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : NULL, + .coreUsage = options->driverSpecific ? &gpu->coreUsage : NULL, + .type = &gpu->type, + .frequency = options->driverSpecific ? &gpu->frequency : NULL, + .name = &gpu->name, + }, + "/usr/lib/wsl/lib/libnvidia-ml.so"); + if (error) { FF_DEBUG("NVIDIA driver-specific detection failed for adapter #%u: %s", i, error); - else + } else { FF_DEBUG("NVIDIA driver-specific detection succeeded for adapter #%u", i); + } } - if (gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET && gpu->shared.total == FF_GPU_VMEM_SIZE_UNSET) - { - if (wddmVersion >= KMT_DRIVERVERSION_WDDM_3_1 && options->driverSpecific) - { + if (gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET && gpu->shared.total == FF_GPU_VMEM_SIZE_UNSET) { + if (wddmVersion >= KMT_DRIVERVERSION_WDDM_3_1 && options->driverSpecific) { // Supports memory usage query; requires Windows 11 (22H2) or later D3DKMT_QUERYSTATISTICS queryStatistics = { .Type = D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE, @@ -235,33 +208,29 @@ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) .SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_LOCAL, }, }; - if (NT_SUCCESS(D3DKMTQueryStatistics(dxg, &queryStatistics))) - { + if (NT_SUCCESS(D3DKMTQueryStatistics(dxg, &queryStatistics))) { D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; uint64_t total = used + info->FreeBytes + info->ZeroBytes; gpu->dedicated.used = used; gpu->dedicated.total = total; FF_DEBUG("Adapter #%u local memory usage: used=%lu total=%lu", i, (unsigned long) used, (unsigned long) total); - } - else + } else { FF_DEBUG("D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE (LOCAL) failed for adapter #%u: %s", i, strerror(errno)); + } queryStatistics.QuerySegmentGroupUsage.SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_NON_LOCAL; - if (NT_SUCCESS(D3DKMTQueryStatistics(dxg, &queryStatistics))) - { + if (NT_SUCCESS(D3DKMTQueryStatistics(dxg, &queryStatistics))) { D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; uint64_t total = used + info->FreeBytes + info->ZeroBytes; gpu->shared.used = used; gpu->shared.total = total; FF_DEBUG("Adapter #%u non-local memory usage: used=%lu total=%lu", i, (unsigned long) used, (unsigned long) total); - } - else + } else { FF_DEBUG("D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE (NON_LOCAL) failed for adapter #%u: %s", i, strerror(errno)); - } - else - { + } + } else { // Supports basic segment (total) size query D3DKMT_SEGMENTSIZEINFO segmentSizeInfo = {}; D3DKMT_QUERYADAPTERINFO queryAdapterInfo = { @@ -270,87 +239,80 @@ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) .pPrivateDriverData = &segmentSizeInfo, .PrivateDriverDataSize = sizeof(segmentSizeInfo), }; - if (NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &queryAdapterInfo))) - { + if (NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &queryAdapterInfo))) { FF_DEBUG("Adapter #%u segment size - DedicatedVideoMemorySize: %lu, DedicatedSystemMemorySize: %lu, SharedSystemMemorySize: %lu", - i, segmentSizeInfo.DedicatedVideoMemorySize, segmentSizeInfo.DedicatedSystemMemorySize, segmentSizeInfo.SharedSystemMemorySize); + i, + segmentSizeInfo.DedicatedVideoMemorySize, + segmentSizeInfo.DedicatedSystemMemorySize, + segmentSizeInfo.SharedSystemMemorySize); gpu->dedicated.total = segmentSizeInfo.DedicatedVideoMemorySize; gpu->shared.total = segmentSizeInfo.DedicatedSystemMemorySize + segmentSizeInfo.SharedSystemMemorySize; - } - else - { + } else { FF_DEBUG("Failed to query segment size information for adapter #%u: %s", i, strerror(errno)); } } } - if (gpu->frequency == FF_GPU_FREQUENCY_UNSET && wddmVersion >= KMT_DRIVERVERSION_WDDM_3_1) - { - for (ULONG nodeIdx = 0; ; nodeIdx++) - { + if (gpu->frequency == FF_GPU_FREQUENCY_UNSET && wddmVersion >= KMT_DRIVERVERSION_WDDM_3_1) { + for (ULONG nodeIdx = 0;; nodeIdx++) { D3DKMT_NODEMETADATA nodeMetadata = { .NodeOrdinalAndAdapterIndex = (0 << 16) | nodeIdx, }; if (!NT_SUCCESS(D3DKMTQueryAdapterInfo(dxg, &(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_NODEMETADATA, - .pPrivateDriverData = &nodeMetadata, - .PrivateDriverDataSize = sizeof(nodeMetadata), - }))) + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_NODEMETADATA, + .pPrivateDriverData = &nodeMetadata, + .PrivateDriverDataSize = sizeof(nodeMetadata), + }))) { break; + } - if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D) + if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D) { continue; + } D3DKMT_QUERYSTATISTICS queryStatistics = { .Type = D3DKMT_QUERYSTATISTICS_NODE2, .AdapterLuid = adapter->AdapterLuid, - .QueryNode2 = { .PhysicalAdapterIndex = 0, .NodeOrdinal = (UINT16) nodeIdx }, + .QueryNode2 = {.PhysicalAdapterIndex = 0, .NodeOrdinal = (UINT16) nodeIdx}, }; - if (NT_SUCCESS(D3DKMTQueryStatistics(dxg, &queryStatistics))) - { + if (NT_SUCCESS(D3DKMTQueryStatistics(dxg, &queryStatistics))) { gpu->frequency = (uint32_t) (queryStatistics.QueryResult.NodeInformation.NodePerfData.MaxFrequency / 1000 / 1000); FF_DEBUG("Adapter #%u max graphics frequency: %u MHz", i, gpu->frequency); break; - } - else + } else { FF_DEBUG("Failed to query node performance data for adapter #%u node #%u: %s", i, nodeIdx, strerror(errno)); + } } } - if (options->temp && gpu->temperature == FF_GPU_TEMP_UNSET) - { + if (options->temp && gpu->temperature == FF_GPU_TEMP_UNSET) { D3DKMT_QUERYSTATISTICS queryStatistics = { .Type = D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER, .AdapterLuid = adapter->AdapterLuid, - .QueryPhysAdapter = { .PhysicalAdapterIndex = 0 }, + .QueryPhysAdapter = {.PhysicalAdapterIndex = 0}, }; if (NT_SUCCESS(D3DKMTQueryStatistics(dxg, &queryStatistics)) && - queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature != 0) - { + queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature != 0) { gpu->temperature = queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature / 10.0; FF_DEBUG("Adapter #%u temperature: %.1f°C", i, gpu->temperature); - } - else + } else { FF_DEBUG("Failed to query temperature for adapter #%u: %s", i, strerror(errno)); + } } - if (gpu->type == FF_GPU_TYPE_UNKNOWN) - { - if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) - { + if (gpu->type == FF_GPU_TYPE_UNKNOWN) { + if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA) { if (ffStrbufStartsWithIgnCaseS(&gpu->name, "GeForce") || ffStrbufStartsWithIgnCaseS(&gpu->name, "Quadro") || - ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) + ffStrbufStartsWithIgnCaseS(&gpu->name, "Tesla")) { gpu->type = FF_GPU_TYPE_DISCRETE; - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) - { - if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_MTHREADS) { + if (ffStrbufStartsWithIgnCaseS(&gpu->name, "MTT ")) { gpu->type = FF_GPU_TYPE_DISCRETE; - } - else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) - { + } + } else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) { // 0000:00:02.0 is reserved for Intel integrated graphics gpu->type = gpu->deviceId == ffGPUPciAddr2Id(0, 0, 2, 0) ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; } @@ -363,12 +325,11 @@ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus) (unsigned) gpu->type, (unsigned long) gpu->deviceId); - if (NT_SUCCESS(D3DKMTCloseAdapter(dxg, &(D3DKMT_CLOSEADAPTER) { - .hAdapter = adapter->hAdapter - }))) + if (NT_SUCCESS(D3DKMTCloseAdapter(dxg, &(D3DKMT_CLOSEADAPTER) {.hAdapter = adapter->hAdapter}))) { FF_DEBUG("Closed adapter #%u successfully", i); - else + } else { FF_DEBUG("Failed to close adapter #%u: %s", i, strerror(errno)); + } } return NULL; diff --git a/src/detection/gpu/igcl.h b/src/detection/gpu/igcl.h index 8e8ff6f96..6bf4ffe73 100644 --- a/src/detection/gpu/igcl.h +++ b/src/detection/gpu/igcl.h @@ -7,25 +7,22 @@ #include // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv412ctl_result_t -typedef enum ctl_result_t -{ +typedef enum ctl_result_t { CTL_RESULT_SUCCESS = 0, } ctl_result_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv420ctl_application_id_t -typedef struct ctl_application_id_t -{ +typedef struct ctl_application_id_t { uint32_t Data1; uint16_t Data2; uint16_t Data3; uint8_t Data4[8]; } ctl_application_id_t; -#define CTL_IMPL_VERSION (( 1 /*major*/ << 16 )|( 1 /*minor*/ & 0x0000ffff)) +#define CTL_IMPL_VERSION ((1 /*major*/ << 16) | (1 /*minor*/ & 0x0000ffff)) // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv415ctl_init_flag_t -typedef enum ctl_init_flag_t -{ +typedef enum ctl_init_flag_t { CTL_INIT_FLAG_USE_LEVEL_ZERO = 1, CTL_INIT_FLAG_MAX } ctl_init_flag_t; @@ -33,8 +30,7 @@ typedef enum ctl_init_flag_t typedef uint32_t ctl_version_info_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv415ctl_init_args_t -typedef struct ctl_init_args_t -{ +typedef struct ctl_init_args_t { uint32_t Size; uint8_t Version; ctl_version_info_t AppVersion; @@ -46,34 +42,31 @@ typedef struct ctl_init_args_t typedef struct ctl_api_handle_t* ctl_api_handle_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv47ctlInitP15ctl_init_args_tP16ctl_api_handle_t -extern ctl_result_t ctlInit(ctl_init_args_t *pInitDesc, ctl_api_handle_t *phAPIHandle); +extern ctl_result_t ctlInit(ctl_init_args_t* pInitDesc, ctl_api_handle_t* phAPIHandle); // https://intel.github.io/drivers.gpu.control-library/Control/api.html#ctlclose extern ctl_result_t ctlClose(ctl_api_handle_t hAPIHandle); typedef struct ctl_device_adapter_handle_t* ctl_device_adapter_handle_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv419ctlEnumerateDevices16ctl_api_handle_tP8uint32_tP27ctl_device_adapter_handle_t -extern ctl_result_t ctlEnumerateDevices(ctl_api_handle_t hAPIHandle, uint32_t *pCount, ctl_device_adapter_handle_t* phDevices); +extern ctl_result_t ctlEnumerateDevices(ctl_api_handle_t hAPIHandle, uint32_t* pCount, ctl_device_adapter_handle_t* phDevices); // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv417ctl_device_type_t -typedef enum ctl_device_type_t -{ +typedef enum ctl_device_type_t { CTL_DEVICE_TYPE_GRAPHICS = 1, CTL_DEVICE_TYPE_SYSTEM = 2, CTL_DEVICE_TYPE_MAX } ctl_device_type_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv422ctl_firmware_version_t -typedef struct ctl_firmware_version_t -{ +typedef struct ctl_firmware_version_t { uint64_t major_version; uint64_t minor_version; uint64_t build_number; } ctl_firmware_version_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv417ctl_adapter_bdf_t -typedef struct ctl_adapter_bdf_t -{ +typedef struct ctl_adapter_bdf_t { uint8_t bus; uint8_t device; uint8_t function; @@ -82,14 +75,12 @@ typedef struct ctl_adapter_bdf_t #define IGCL_CTL_MAX_DEVICE_NAME_LEN 100 #define IGCL_CTL_MAX_RESERVED_SIZE 112 -typedef enum ctl_adapter_properties_flag_t -{ +typedef enum ctl_adapter_properties_flag_t { CTL_ADAPTER_PROPERTIES_FLAG_INTEGRATED = 1, } ctl_adapter_properties_flag_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv431ctl_device_adapter_properties_t -typedef struct ctl_device_adapter_properties_t -{ +typedef struct ctl_device_adapter_properties_t { uint32_t Size; uint8_t Version; void* pDeviceID; @@ -122,8 +113,7 @@ typedef struct ctl_temp_handle_t* ctl_temp_handle_t; extern ctl_result_t ctlEnumTemperatureSensors(ctl_device_adapter_handle_t hDAhandle, uint32_t* pCount, ctl_temp_handle_t* phTemperature); // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv427ctlTemperatureGetProperties17ctl_temp_handle_tP21ctl_temp_properties_t -typedef enum ctl_temp_sensors_t -{ +typedef enum ctl_temp_sensors_t { CTL_TEMP_SENSORS_GLOBAL = 0, CTL_TEMP_SENSORS_GPU = 1, CTL_TEMP_SENSORS_MEMORY = 2, @@ -133,8 +123,7 @@ typedef enum ctl_temp_sensors_t CTL_TEMP_SENSORS_MAX } ctl_temp_sensors_t; -typedef struct _ctl_temp_properties_t -{ +typedef struct _ctl_temp_properties_t { uint32_t Size; uint8_t Version; ctl_temp_sensors_t type; @@ -147,11 +136,10 @@ extern ctl_result_t ctlTemperatureGetProperties(ctl_temp_handle_t hTemperature, typedef struct ctl_mem_handle_t* ctl_mem_handle_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv420ctlEnumMemoryModules27ctl_device_adapter_handle_tP8uint32_tP16ctl_mem_handle_t -extern ctl_result_t ctlEnumMemoryModules(ctl_device_adapter_handle_t hDAhandle, uint32_t *pCount, ctl_mem_handle_t* phMemory); +extern ctl_result_t ctlEnumMemoryModules(ctl_device_adapter_handle_t hDAhandle, uint32_t* pCount, ctl_mem_handle_t* phMemory); // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv415ctl_mem_state_t -typedef struct ctl_mem_state_t -{ +typedef struct ctl_mem_state_t { uint32_t Size; uint8_t Version; uint64_t free; @@ -159,11 +147,10 @@ typedef struct ctl_mem_state_t } ctl_mem_state_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv417ctlMemoryGetState16ctl_mem_handle_tP15ctl_mem_state_t -extern ctl_result_t ctlMemoryGetState(ctl_mem_handle_t hMemory, ctl_mem_state_t *pState); +extern ctl_result_t ctlMemoryGetState(ctl_mem_handle_t hMemory, ctl_mem_state_t* pState); // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv414ctl_mem_type_t -typedef enum ctl_mem_type_t -{ +typedef enum ctl_mem_type_t { CTL_MEM_TYPE_HBM = 0, CTL_MEM_TYPE_DDR = 1, CTL_MEM_TYPE_DDR3 = 2, @@ -183,16 +170,14 @@ typedef enum ctl_mem_type_t } ctl_mem_type_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv413ctl_mem_loc_t -typedef enum ctl_mem_loc_t -{ +typedef enum ctl_mem_loc_t { CTL_MEM_LOC_SYSTEM = 0, CTL_MEM_LOC_DEVICE = 1, CTL_MEM_LOC_MAX } ctl_mem_loc_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv420ctl_mem_properties_t -typedef struct ctl_mem_properties_t -{ +typedef struct ctl_mem_properties_t { uint32_t Size; uint8_t Version; ctl_mem_type_t type; @@ -203,7 +188,7 @@ typedef struct ctl_mem_properties_t } ctl_mem_properties_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv422ctlMemoryGetProperties16ctl_mem_handle_tP20ctl_mem_properties_t -extern ctl_result_t ctlMemoryGetProperties(ctl_mem_handle_t hMemory, ctl_mem_properties_t *pProperties); +extern ctl_result_t ctlMemoryGetProperties(ctl_mem_handle_t hMemory, ctl_mem_properties_t* pProperties); typedef struct ctl_freq_handle_t* ctl_freq_handle_t; @@ -211,16 +196,14 @@ typedef struct ctl_freq_handle_t* ctl_freq_handle_t; extern ctl_result_t ctlEnumFrequencyDomains(ctl_device_adapter_handle_t hDAhandle, uint32_t* pCount, ctl_freq_handle_t* phFrequency); // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv417ctl_freq_domain_t -typedef enum ctl_freq_domain_t -{ +typedef enum ctl_freq_domain_t { CTL_FREQ_DOMAIN_GPU = 0, CTL_FREQ_DOMAIN_MEMORY = 1, CTL_FREQ_DOMAIN_MAX } ctl_freq_domain_t; // https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv421ctl_freq_properties_t -typedef struct ctl_freq_properties_t -{ +typedef struct ctl_freq_properties_t { uint32_t Size; uint8_t Version; ctl_freq_domain_t type; diff --git a/src/detection/gpu/intel_drm.h b/src/detection/gpu/intel_drm.h index 97b3b07bd..3e2574822 100644 --- a/src/detection/gpu/intel_drm.h +++ b/src/detection/gpu/intel_drm.h @@ -9,52 +9,52 @@ * Copyright © 2023 Intel Corporation */ -#define DRM_XE_DEVICE_QUERY 0x00 +#define DRM_XE_DEVICE_QUERY 0x00 -#define DRM_IOCTL_XE_DEVICE_QUERY DRM_IOWR(DRM_COMMAND_BASE + DRM_XE_DEVICE_QUERY, struct drm_xe_device_query) +#define DRM_IOCTL_XE_DEVICE_QUERY DRM_IOWR(DRM_COMMAND_BASE + DRM_XE_DEVICE_QUERY, struct drm_xe_device_query) enum drm_xe_memory_class { - DRM_XE_MEM_REGION_CLASS_SYSMEM = 0, - DRM_XE_MEM_REGION_CLASS_VRAM + DRM_XE_MEM_REGION_CLASS_SYSMEM = 0, + DRM_XE_MEM_REGION_CLASS_VRAM }; struct drm_xe_mem_region { - __u16 mem_class; - __u16 instance; - __u32 min_page_size; - __u64 total_size; - __u64 used; - __u64 cpu_visible_size; - __u64 cpu_visible_used; - __u64 reserved[6]; + __u16 mem_class; + __u16 instance; + __u32 min_page_size; + __u64 total_size; + __u64 used; + __u64 cpu_visible_size; + __u64 cpu_visible_used; + __u64 reserved[6]; }; struct drm_xe_query_mem_regions { - __u32 num_mem_regions; - __u32 pad; - struct drm_xe_mem_region mem_regions[]; + __u32 num_mem_regions; + __u32 pad; + struct drm_xe_mem_region mem_regions[]; }; struct drm_xe_query_topology_mask { - __u16 gt_id; + __u16 gt_id; -#define DRM_XE_TOPO_DSS_GEOMETRY 1 -#define DRM_XE_TOPO_DSS_COMPUTE 2 -#define DRM_XE_TOPO_EU_PER_DSS 4 - __u16 type; - __u32 num_bytes; - __u8 mask[]; +#define DRM_XE_TOPO_DSS_GEOMETRY 1 +#define DRM_XE_TOPO_DSS_COMPUTE 2 +#define DRM_XE_TOPO_EU_PER_DSS 4 + __u16 type; + __u32 num_bytes; + __u8 mask[]; }; struct drm_xe_device_query { - __u64 extensions; + __u64 extensions; -#define DRM_XE_DEVICE_QUERY_MEM_REGIONS 1 -#define DRM_XE_DEVICE_QUERY_GT_TOPOLOGY 5 - __u32 query; - __u32 size; - __u64 data; - __u64 reserved[2]; +#define DRM_XE_DEVICE_QUERY_MEM_REGIONS 1 +#define DRM_XE_DEVICE_QUERY_GT_TOPOLOGY 5 + __u32 query; + __u32 size; + __u64 data; + __u64 reserved[2]; }; // i915_drm.h @@ -64,62 +64,62 @@ struct drm_xe_device_query { * All Rights Reserved. */ -#define DRM_IOCTL_I915_GETPARAM DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GETPARAM, drm_i915_getparam_t) +#define DRM_IOCTL_I915_GETPARAM DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GETPARAM, drm_i915_getparam_t) struct drm_i915_getparam { - __s32 param; - int *value; + __s32 param; + int* value; }; typedef struct drm_i915_getparam drm_i915_getparam_t; -#define DRM_I915_GETPARAM 0x06 -#define DRM_I915_QUERY 0x39 -#define DRM_I915_QUERY_MEMORY_REGIONS 4 -#define DRM_IOCTL_I915_QUERY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_QUERY, struct drm_i915_query) -#define I915_PARAM_EU_TOTAL 34 +#define DRM_I915_GETPARAM 0x06 +#define DRM_I915_QUERY 0x39 +#define DRM_I915_QUERY_MEMORY_REGIONS 4 +#define DRM_IOCTL_I915_QUERY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_QUERY, struct drm_i915_query) +#define I915_PARAM_EU_TOTAL 34 struct drm_i915_query_item { - __u64 query_id; -#define DRM_I915_QUERY_MEMORY_REGIONS 4 + __u64 query_id; +#define DRM_I915_QUERY_MEMORY_REGIONS 4 - __s32 length; - __u32 flags; - __u64 data_ptr; + __s32 length; + __u32 flags; + __u64 data_ptr; }; struct drm_i915_query { - __u32 num_items; - __u32 flags; - __u64 items_ptr; + __u32 num_items; + __u32 flags; + __u64 items_ptr; }; enum drm_i915_gem_memory_class { - I915_MEMORY_CLASS_SYSTEM = 0, - I915_MEMORY_CLASS_DEVICE, + I915_MEMORY_CLASS_SYSTEM = 0, + I915_MEMORY_CLASS_DEVICE, }; struct drm_i915_gem_memory_class_instance { - __u16 memory_class; - __u16 memory_instance; + __u16 memory_class; + __u16 memory_instance; }; struct drm_i915_memory_region_info { - struct drm_i915_gem_memory_class_instance region; - __u32 rsvd0; - __u64 probed_size; - __u64 unallocated_size; + struct drm_i915_gem_memory_class_instance region; + __u32 rsvd0; + __u64 probed_size; + __u64 unallocated_size; - union { - __u64 rsvd1[8]; - struct { - __u64 probed_cpu_visible_size; - __u64 unallocated_cpu_visible_size; - }; - }; + union { + __u64 rsvd1[8]; + struct { + __u64 probed_cpu_visible_size; + __u64 unallocated_cpu_visible_size; + }; + }; }; struct drm_i915_query_memory_regions { - __u32 num_regions; - __u32 rsvd[3]; - struct drm_i915_memory_region_info regions[]; + __u32 num_regions; + __u32 rsvd[3]; + struct drm_i915_memory_region_info regions[]; }; diff --git a/src/detection/gpu/mtml.h b/src/detection/gpu/mtml.h index 008f83ae2..9f62fc326 100644 --- a/src/detection/gpu/mtml.h +++ b/src/detection/gpu/mtml.h @@ -10,16 +10,14 @@ /** * Return values for MTML API calls. */ -typedef enum -{ +typedef enum { MTML_SUCCESS = 0, } MtmlReturn; /** * The brand of the device. */ -typedef enum -{ +typedef enum { MTML_BRAND_MTT = 0, //!< MTT series. } MtmlBrandType; @@ -53,60 +51,60 @@ typedef struct // Retrieves the number of cores of a device. MtmlReturn mtmlDeviceCountGpuCores(const MtmlDevice* device, unsigned int* numCores); // Retrieves the brand of a device. -MtmlReturn mtmlDeviceGetBrand(const MtmlDevice *dev, MtmlBrandType *type); +MtmlReturn mtmlDeviceGetBrand(const MtmlDevice* dev, MtmlBrandType* type); // Retrieves the index associated with the specified device. -MtmlReturn mtmlDeviceGetIndex(const MtmlDevice *dev, unsigned int *index); +MtmlReturn mtmlDeviceGetIndex(const MtmlDevice* dev, unsigned int* index); // Retrieves the name of a device. -MtmlReturn mtmlDeviceGetName(const MtmlDevice *dev, char *name, unsigned int length); +MtmlReturn mtmlDeviceGetName(const MtmlDevice* dev, char* name, unsigned int length); // Retrieves the PCI attributes of a device. -MtmlReturn mtmlDeviceGetPciInfo(const MtmlDevice *dev, MtmlPciInfo *pci); +MtmlReturn mtmlDeviceGetPciInfo(const MtmlDevice* dev, MtmlPciInfo* pci); /** * Retrieves the UUID of a specified device. The UUID is a hexadecimal string in the * form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where each 'x' is an ASCII character that represents a hexadecimal * digit. The UUID is globally unique for every single device thus can be used to identify different devices * physically. */ -MtmlReturn mtmlDeviceGetUUID(const MtmlDevice *dev, char *uuid, unsigned int length); +MtmlReturn mtmlDeviceGetUUID(const MtmlDevice* dev, char* uuid, unsigned int length); // Initializes a GPU opaque object to represent a specific graphic core on the target device that is designated by its index. -MtmlReturn mtmlDeviceInitGpu(const MtmlDevice *dev, MtmlGpu **gpu); +MtmlReturn mtmlDeviceInitGpu(const MtmlDevice* dev, MtmlGpu** gpu); // Initializes a memory opaque object to represent the memory on the target device. -MtmlReturn mtmlDeviceInitMemory(const MtmlDevice *dev, MtmlMemory **mem); +MtmlReturn mtmlDeviceInitMemory(const MtmlDevice* dev, MtmlMemory** mem); // Retrieves the maximum supported clock speed for the device's graphic core. -MtmlReturn mtmlGpuGetMaxClock(const MtmlGpu *gpu, unsigned int *clockMhz); +MtmlReturn mtmlGpuGetMaxClock(const MtmlGpu* gpu, unsigned int* clockMhz); // Retrieves the current temperature readings for the device's graphic core, in degrees Celsius. -MtmlReturn mtmlGpuGetTemperature(const MtmlGpu *gpu, unsigned int *temp); +MtmlReturn mtmlGpuGetTemperature(const MtmlGpu* gpu, unsigned int* temp); // Retrieves the current utilization rate for the device's graphic core. -MtmlReturn mtmlGpuGetUtilization(const MtmlGpu *gpu, unsigned int *utilization); +MtmlReturn mtmlGpuGetUtilization(const MtmlGpu* gpu, unsigned int* utilization); // Retrieves the number of devices that can be accessed by the library opaque object. -MtmlReturn mtmlLibraryCountDevice(const MtmlLibrary *lib, unsigned int *count); +MtmlReturn mtmlLibraryCountDevice(const MtmlLibrary* lib, unsigned int* count); /** * Initializes a device opaque object to represent a device that is designated by its index. * The index ranges from (0) to (deviceCount - 1), where deviceCount is retrieved from \ref mtmlLibraryCountDevice(). */ -MtmlReturn mtmlLibraryInit(MtmlLibrary **lib); +MtmlReturn mtmlLibraryInit(MtmlLibrary** lib); /** * Initializes a device opaque object to represent a device that is designated by its index. * The index ranges from (0) to (deviceCount - 1), where deviceCount is retrieved from \ref mtmlLibraryCountDevice(). */ -MtmlReturn mtmlLibraryInitDeviceByIndex(const MtmlLibrary *lib, unsigned int index, MtmlDevice **dev); +MtmlReturn mtmlLibraryInitDeviceByIndex(const MtmlLibrary* lib, unsigned int index, MtmlDevice** dev); /** * Initializes a device opaque object to represent a device that is designated by its PCI Sbdf. * The PCI Sbdf format like 00000000:3a:00.0 refer to \ref MtmlPciInfo::sbdf. */ -MtmlReturn mtmlLibraryInitDeviceByPciSbdf(const MtmlLibrary *lib, const char *pciSbdf, MtmlDevice **dev); +MtmlReturn mtmlLibraryInitDeviceByPciSbdf(const MtmlLibrary* lib, const char* pciSbdf, MtmlDevice** dev); // Initializes a MtmlSystem opaque pointer that is bound to a library opaque object. -MtmlReturn mtmlLibraryInitSystem(const MtmlLibrary *lib, MtmlSystem **sys); +MtmlReturn mtmlLibraryInitSystem(const MtmlLibrary* lib, MtmlSystem** sys); /** * Shuts down the library opaque object that is previously initialized by \ref mtmlLibraryInit() and releases its resources. * The \a lib pointer cannot be used anymore after this function returns. */ -MtmlReturn mtmlLibraryShutDown(MtmlLibrary *lib); +MtmlReturn mtmlLibraryShutDown(MtmlLibrary* lib); // Retrieves the amount of total memory available on the device, in bytes. -MtmlReturn mtmlMemoryGetTotal(const MtmlMemory *mem, unsigned long long *total); +MtmlReturn mtmlMemoryGetTotal(const MtmlMemory* mem, unsigned long long* total); // Retrieves the amount of used memory on the device, in bytes. -MtmlReturn mtmlMemoryGetUsed(const MtmlMemory *mem, unsigned long long *used); +MtmlReturn mtmlMemoryGetUsed(const MtmlMemory* mem, unsigned long long* used); // Retrieves the current memory utilization rate for the device. -MtmlReturn mtmlMemoryGetUtilization(const MtmlMemory *mem, unsigned int *utilization); +MtmlReturn mtmlMemoryGetUtilization(const MtmlMemory* mem, unsigned int* utilization); diff --git a/src/detection/gpu/nvapi.h b/src/detection/gpu/nvapi.h index bd9ac7724..102d57a0b 100644 --- a/src/detection/gpu/nvapi.h +++ b/src/detection/gpu/nvapi.h @@ -2,8 +2,7 @@ // https://github.com/NVIDIA/nvapi (MIT License) // https://github.com/deathcamp/NVOC/blob/master/nvoc.c (Public Domain) -typedef enum NvApiGPUMemoryType -{ +typedef enum NvApiGPUMemoryType { NVAPI_GPU_MEMORY_TYPE_UNKNOWN = 0, NVAPI_GPU_MEMORY_TYPE_SDRAM, NVAPI_GPU_MEMORY_TYPE_DDR1, @@ -23,18 +22,16 @@ typedef enum NvApiGPUMemoryType NVAPI_GPU_MEMORY_TYPE_GDDR7, } NvApiGPUMemoryType; -typedef enum -{ - NV_SYSTEM_TYPE_GPU_UNKNOWN = 0, - NV_SYSTEM_TYPE_IGPU = 1, // Integrated - NV_SYSTEM_TYPE_DGPU = 2, // Discrete +typedef enum { + NV_SYSTEM_TYPE_GPU_UNKNOWN = 0, + NV_SYSTEM_TYPE_IGPU = 1, // Integrated + NV_SYSTEM_TYPE_DGPU = 2, // Discrete } NvApiGPUType; typedef int NvAPI_Status; // 0 = success; < 0 = error typedef struct NvPhysicalGpuHandle* NvPhysicalGpuHandle; -typedef enum -{ +typedef enum { NVAPI_INTERFACE_OFFSET_INITIALIZE = 0x0150E828, NVAPI_INTERFACE_OFFSET_UNLOAD = 0xD22BDD7E, NVAPI_INTERFACE_OFFSET_ENUM_PHYSICAL_GPUS = 0xE5AC921F, diff --git a/src/detection/gpu/nvml.h b/src/detection/gpu/nvml.h index 40ff3a495..74b184050 100644 --- a/src/detection/gpu/nvml.h +++ b/src/detection/gpu/nvml.h @@ -54,7 +54,7 @@ typedef struct { unsigned long long used; } nvmlMemory_v2_t; // https://github.com/NVIDIA/nvidia-settings/issues/78#issuecomment-1012837988 -enum { nvmlMemory_v2 = (unsigned int)(sizeof(nvmlMemory_v2_t) | (2 << 24U)) }; +enum { nvmlMemory_v2 = (unsigned int) (sizeof(nvmlMemory_v2_t) | (2 << 24U)) }; // https://docs.nvidia.com/deploy/nvml-api/structnvmlMemory__t.html#structnvmlMemory__t // Memory allocation information for a device (v1) @@ -137,7 +137,7 @@ extern nvmlReturn_t nvmlDeviceGetTemperature(nvmlDevice_t device, nvmlTemperatur // Retrieves the amount of used, free, reserved and total memory available on the device, in bytes. The reserved amount is supported on version 2 only extern nvmlReturn_t nvmlDeviceGetMemoryInfo_v2(nvmlDevice_t device, nvmlMemory_v2_t* memory); // Retrieves the amount of used, free, total memory available on the device, in bytes. -extern nvmlReturn_t nvmlDeviceGetMemoryInfo(nvmlDevice_t device, nvmlMemory_t *memory); +extern nvmlReturn_t nvmlDeviceGetMemoryInfo(nvmlDevice_t device, nvmlMemory_t* memory); // Gets the device's core count extern nvmlReturn_t nvmlDeviceGetNumGpuCores(nvmlDevice_t device, unsigned int* numCores); // Retrieves the maximum clock speeds for the device @@ -145,8 +145,8 @@ extern nvmlReturn_t nvmlDeviceGetMaxClockInfo(nvmlDevice_t device, nvmlClockType // Retrieves the brand of this device extern nvmlReturn_t nvmlDeviceGetBrand(nvmlDevice_t device, nvmlBrandType_t* type); // Retrieves the current utilization rates for the device -extern nvmlReturn_t nvmlDeviceGetUtilizationRates(nvmlDevice_t device, nvmlUtilization_t *utilization); +extern nvmlReturn_t nvmlDeviceGetUtilizationRates(nvmlDevice_t device, nvmlUtilization_t* utilization); // Retrieves the globally unique immutable UUID associated with this device, as a 5 part hexadecimal string, that augments the immutable, board serial identifier. -extern nvmlReturn_t nvmlDeviceGetIndex(nvmlDevice_t device, unsigned int *index); +extern nvmlReturn_t nvmlDeviceGetIndex(nvmlDevice_t device, unsigned int* index); // Retrieves the name of this device. -extern nvmlReturn_t nvmlDeviceGetName(nvmlDevice_t device, char *name, unsigned int length); +extern nvmlReturn_t nvmlDeviceGetName(nvmlDevice_t device, char* name, unsigned int length); diff --git a/src/detection/gtk_qt/gtk.c b/src/detection/gtk_qt/gtk.c index 0f5e344cc..bfe602b51 100644 --- a/src/detection/gtk_qt/gtk.c +++ b/src/detection/gtk_qt/gtk.c @@ -5,44 +5,45 @@ #include "detection/gtk_qt/gtk_qt.h" #include "detection/displayserver/displayserver.h" -static inline bool allPropertiesSet(FFGTKResult* result) -{ - return - result->theme.length > 0 && +static inline bool allPropertiesSet(FFGTKResult* result) { + return result->theme.length > 0 && result->icons.length > 0 && result->font.length > 0; } -static inline void applyGTKSettings(FFGTKResult* result, const char* themeName, const char* iconsName, const char* fontName, const char* cursorTheme, int cursorSize, const char* wallpaper) -{ - if(result->theme.length == 0) +static inline void applyGTKSettings(FFGTKResult* result, const char* themeName, const char* iconsName, const char* fontName, const char* cursorTheme, int cursorSize, const char* wallpaper) { + if (result->theme.length == 0) { ffStrbufAppendS(&result->theme, themeName); + } - if(result->icons.length == 0) + if (result->icons.length == 0) { ffStrbufAppendS(&result->icons, iconsName); + } - if(result->font.length == 0) + if (result->font.length == 0) { ffStrbufAppendS(&result->font, fontName); + } - if(result->cursor.length == 0) + if (result->cursor.length == 0) { ffStrbufAppendS(&result->cursor, cursorTheme); + } - if(result->cursorSize.length == 0 && cursorSize > 0) + if (result->cursorSize.length == 0 && cursorSize > 0) { ffStrbufAppendF(&result->cursorSize, "%i", cursorSize); + } - if(result->wallpaper.length == 0) + if (result->wallpaper.length == 0) { ffStrbufAppendS(&result->wallpaper, wallpaper); + } } -static bool testXfconfWallpaperPropKey(FF_MAYBE_UNUSED void* data, const char* key) -{ +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 void detectGTKFromSettings(FFGTKResult* result) { static const char* themeName = NULL; static const char* iconsName = NULL; static const char* fontName = NULL; @@ -52,8 +53,7 @@ static void detectGTKFromSettings(FFGTKResult* result) static bool init = false; - if(init) - { + if (init) { applyGTKSettings(result, themeName, iconsName, fontName, cursorTheme, cursorSize, wallpaper); return; } @@ -62,39 +62,32 @@ static void detectGTKFromSettings(FFGTKResult* result) const FFDisplayServerResult* wmde = ffConnectDisplayServer(); - if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_XFCE4)) - { + 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 = ffSettingsGetXFConfFirstMatch("xfce4-desktop", "/backdrop/screen0", FF_VARIANT_TYPE_STRING, NULL, testXfconfWallpaperPropKey).strValue; - } - else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_CINNAMON)) - { + } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_CINNAMON)) { 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(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_MATE)) - { + } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_MATE)) { 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( + } else if ( 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) - ) { + ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_BUDGIE)) { 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; @@ -106,19 +99,11 @@ static void detectGTKFromSettings(FFGTKResult* result) applyGTKSettings(result, themeName, iconsName, fontName, cursorTheme, cursorSize, wallpaper); } -static void detectGTKFromConfigFile(const char* filename, FFGTKResult* result) -{ - ffParsePropFileValues(filename, 5, (FFpropquery[]) { - {"gtk-theme-name =", &result->theme}, - {"gtk-icon-theme-name =", &result->icons}, - {"gtk-font-name =", &result->font}, - {"gtk-cursor-theme-name =", &result->cursor}, - {"gtk-cursor-theme-size =", &result->cursorSize} - }); +static void detectGTKFromConfigFile(const char* filename, FFGTKResult* result) { + ffParsePropFileValues(filename, 5, (FFpropquery[]) {{"gtk-theme-name =", &result->theme}, {"gtk-icon-theme-name =", &result->icons}, {"gtk-font-name =", &result->font}, {"gtk-cursor-theme-name =", &result->cursor}, {"gtk-cursor-theme-size =", &result->cursorSize}}); } -static void detectGTKFromConfigDir(FFstrbuf* configDir, const char* version, FFGTKResult* result) -{ +static void detectGTKFromConfigDir(FFstrbuf* configDir, const char* version, FFGTKResult* result) { uint32_t configDirLength = configDir->length; // /gtk-.0/settings.ini @@ -127,8 +112,9 @@ static void detectGTKFromConfigDir(FFstrbuf* configDir, const char* version, FFG ffStrbufAppendS(configDir, ".0/settings.ini"); detectGTKFromConfigFile(configDir->chars, result); ffStrbufSubstrBefore(configDir, configDirLength); - if(allPropertiesSet(result)) + if (allPropertiesSet(result)) { return; + } // /gtk-.0/gtkrc ffStrbufAppendS(configDir, "gtk-"); @@ -136,8 +122,9 @@ static void detectGTKFromConfigDir(FFstrbuf* configDir, const char* version, FFG ffStrbufAppendS(configDir, ".0/gtkrc"); detectGTKFromConfigFile(configDir->chars, result); ffStrbufSubstrBefore(configDir, configDirLength); - if(allPropertiesSet(result)) + if (allPropertiesSet(result)) { return; + } // /gtkrc-.0 ffStrbufAppendS(configDir, "gtkrc-"); @@ -145,8 +132,9 @@ static void detectGTKFromConfigDir(FFstrbuf* configDir, const char* version, FFG ffStrbufAppendS(configDir, ".0"); detectGTKFromConfigFile(configDir->chars, result); ffStrbufSubstrBefore(configDir, configDirLength); - if(allPropertiesSet(result)) + if (allPropertiesSet(result)) { return; + } // /.gtkrc-.0 ffStrbufAppendS(configDir, ".gtkrc-"); @@ -156,53 +144,50 @@ static void detectGTKFromConfigDir(FFstrbuf* configDir, const char* version, FFG ffStrbufSubstrBefore(configDir, configDirLength); } -static void detectGTK(const char* version, FFGTKResult* result) -{ - //Mate, Cinnamon, GNOME, Unity, Budgie use dconf to save theme config - //On other DEs, this will do nothing +static void detectGTK(const char* version, FFGTKResult* result) { + // Mate, Cinnamon, GNOME, Unity, Budgie use dconf to save theme config + // On other DEs, this will do nothing detectGTKFromSettings(result); - if(allPropertiesSet(result)) + if (allPropertiesSet(result)) { return; + } - //We need to do this because we use multiple threads on configDirs + // We need to do this because we use multiple threads on configDirs FF_STRBUF_AUTO_DESTROY baseDir = ffStrbufCreateA(64); - FF_LIST_FOR_EACH(FFstrbuf, configDir, instance.state.platform.configDirs) - { + FF_LIST_FOR_EACH (FFstrbuf, configDir, instance.state.platform.configDirs) { ffStrbufSet(&baseDir, configDir); detectGTKFromConfigDir(&baseDir, version, result); - if(allPropertiesSet(result)) + if (allPropertiesSet(result)) { break; + } } } -#define FF_DETECT_GTK_IMPL(version) \ - static FFGTKResult result; \ - static bool init = false; \ - if(init) \ - return &result; \ - init = true; \ - ffStrbufInit(&result.theme); \ - ffStrbufInit(&result.icons); \ - ffStrbufInit(&result.font); \ - ffStrbufInit(&result.cursor); \ +#define FF_DETECT_GTK_IMPL(version) \ + static FFGTKResult result; \ + static bool init = false; \ + if (init) \ + return &result; \ + init = true; \ + ffStrbufInit(&result.theme); \ + ffStrbufInit(&result.icons); \ + ffStrbufInit(&result.font); \ + ffStrbufInit(&result.cursor); \ ffStrbufInit(&result.cursorSize); \ - ffStrbufInit(&result.wallpaper); \ - detectGTK(#version, &result); \ + ffStrbufInit(&result.wallpaper); \ + detectGTK(#version, &result); \ return &result; -const FFGTKResult* ffDetectGTK2(void) -{ +const FFGTKResult* ffDetectGTK2(void) { FF_DETECT_GTK_IMPL(2) } -const FFGTKResult* ffDetectGTK3(void) -{ +const FFGTKResult* ffDetectGTK3(void) { FF_DETECT_GTK_IMPL(3) } -const FFGTKResult* ffDetectGTK4(void) -{ +const FFGTKResult* ffDetectGTK4(void) { FF_DETECT_GTK_IMPL(4) } diff --git a/src/detection/gtk_qt/gtk_qt.h b/src/detection/gtk_qt/gtk_qt.h index 58b373b8e..b831bb62c 100644 --- a/src/detection/gtk_qt/gtk_qt.h +++ b/src/detection/gtk_qt/gtk_qt.h @@ -2,8 +2,7 @@ #include "fastfetch.h" -typedef struct FFGTKResult -{ +typedef struct FFGTKResult { FFstrbuf theme; FFstrbuf icons; FFstrbuf font; @@ -12,8 +11,7 @@ typedef struct FFGTKResult FFstrbuf wallpaper; } FFGTKResult; -typedef struct FFQtResult -{ +typedef struct FFQtResult { FFstrbuf widgetStyle; FFstrbuf colorScheme; FFstrbuf icons; diff --git a/src/detection/gtk_qt/qt.c b/src/detection/gtk_qt/qt.c index 3683b534b..260e5a701 100644 --- a/src/detection/gtk_qt/qt.c +++ b/src/detection/gtk_qt/qt.c @@ -8,69 +8,67 @@ #include #include -static inline bool allValuesSet(const FFQtResult* result) -{ - return - result->widgetStyle.length > 0 && +static inline bool allValuesSet(const FFQtResult* result) { + return result->widgetStyle.length > 0 && result->colorScheme.length > 0 && result->icons.length > 0 && result->font.length > 0 && result->wallpaper.length > 0; } -typedef enum __attribute__((__packed__)) PlasmaCategory -{ +typedef enum __attribute__((__packed__)) PlasmaCategory { PLASMA_CATEGORY_GENERAL, PLASMA_CATEGORY_KDE, PLASMA_CATEGORY_ICONS, PLASMA_CATEGORY_OTHER } PlasmaCategory; -static bool detectPlasmaFromFile(const char* filename, FFQtResult* result) -{ +static bool detectPlasmaFromFile(const char* filename, FFQtResult* result) { FILE* kdeglobals = fopen(filename, "r"); - if(kdeglobals == NULL) + if (kdeglobals == NULL) { return false; + } char* line = NULL; size_t len = 0; PlasmaCategory category = PLASMA_CATEGORY_OTHER; - while(getline(&line, &len, kdeglobals) != -1) - { - if(line[0] == '[') - { + while (getline(&line, &len, kdeglobals) != -1) { + if (line[0] == '[') { char categoryName[32]; sscanf(line, "[%31[^]]", categoryName); - if(ffStrEqualsIgnCase(categoryName, "General")) + if (ffStrEqualsIgnCase(categoryName, "General")) { category = PLASMA_CATEGORY_GENERAL; - else if(ffStrEqualsIgnCase(categoryName, "KDE")) + } else if (ffStrEqualsIgnCase(categoryName, "KDE")) { category = PLASMA_CATEGORY_KDE; - else if(ffStrEqualsIgnCase(categoryName, "Icons")) + } else if (ffStrEqualsIgnCase(categoryName, "Icons")) { category = PLASMA_CATEGORY_ICONS; - else + } else { category = PLASMA_CATEGORY_OTHER; + } continue; } - if(category == PLASMA_CATEGORY_KDE && result->widgetStyle.length == 0) + if (category == PLASMA_CATEGORY_KDE && result->widgetStyle.length == 0) { ffParsePropLine(line, "widgetStyle =", &result->widgetStyle); - else if(category == PLASMA_CATEGORY_ICONS && result->icons.length == 0) + } else if (category == PLASMA_CATEGORY_ICONS && result->icons.length == 0) { ffParsePropLine(line, "Theme =", &result->icons); - else if(category == PLASMA_CATEGORY_GENERAL) - { - if(result->colorScheme.length == 0) + } else if (category == PLASMA_CATEGORY_GENERAL) { + if (result->colorScheme.length == 0) { ffParsePropLine(line, "ColorScheme =", &result->colorScheme); + } - if(result->font.length == 0) + if (result->font.length == 0) { ffParsePropLine(line, "font =", &result->font); + } - //Before plasma 5.23, "Font" was the key instead of "font". Since a lot of distros ship older versions, we test for both. - if(result->font.length == 0) + // Before plasma 5.23, "Font" was the key instead of "font". Since a lot of distros ship older versions, we test for both. + if (result->font.length == 0) { ffParsePropLine(line, "Font =", &result->font); + } } } @@ -81,61 +79,60 @@ static bool detectPlasmaFromFile(const char* filename, FFQtResult* result) return true; } -static void detectPlasma(FFQtResult* result) -{ +static void detectPlasma(FFQtResult* result) { bool foundAFile = false; - //We need to do this because we use multiple threads on configDirs + // We need to do this because we use multiple threads on configDirs FF_STRBUF_AUTO_DESTROY baseDir = ffStrbufCreateA(64); - FF_LIST_FOR_EACH(FFstrbuf, configDir, instance.state.platform.configDirs) - { + FF_LIST_FOR_EACH (FFstrbuf, configDir, instance.state.platform.configDirs) { ffStrbufSet(&baseDir, configDir); ffStrbufAppendS(&baseDir, "kdeglobals"); - if(detectPlasmaFromFile(baseDir.chars, result)) + if (detectPlasmaFromFile(baseDir.chars, result)) { foundAFile = true; + } ffStrbufSet(&baseDir, configDir); ffStrbufAppendS(&baseDir, "plasma-org.kde.plasma.desktop-appletsrc"); ffParsePropFile(baseDir.chars, "Image=", &result->wallpaper); - if(allValuesSet(result)) + if (allValuesSet(result)) { return; + } } - if(!foundAFile) + if (!foundAFile) { return; + } - //In Plasma the default value is never set in the config file, but the whole key-value is discarded. - ///We must set these values by our self if the file exists (it always does here) - if(result->widgetStyle.length == 0) + // In Plasma the default value is never set in the config file, but the whole key-value is discarded. + /// We must set these values by our self if the file exists (it always does here) + if (result->widgetStyle.length == 0) { ffStrbufAppendS(&result->widgetStyle, "Breeze"); + } - if(result->colorScheme.length == 0) + if (result->colorScheme.length == 0) { ffStrbufAppendS(&result->colorScheme, "BreezeLight"); + } - if(result->icons.length == 0) + if (result->icons.length == 0) { ffStrbufAppendS(&result->icons, "Breeze"); + } - if(result->font.length == 0) + if (result->font.length == 0) { ffStrbufAppendS(&result->font, "Noto Sans, 10"); + } } -static void detectLXQt(FFQtResult* result) -{ - ffParsePropFileConfigValues("lxqt/lxqt.conf", 3, (FFpropquery[]) { - {"style = ", &result->widgetStyle}, - {"icon_theme = ", &result->icons}, - {"font = ", &result->font} - }); +static void detectLXQt(FFQtResult* result) { + ffParsePropFileConfigValues("lxqt/lxqt.conf", 3, (FFpropquery[]) {{"style = ", &result->widgetStyle}, {"icon_theme = ", &result->icons}, {"font = ", &result->font}}); ffParsePropFileConfig("pcmanfm-qt/lxqt/settings.conf", "Wallpaper=", &result->wallpaper); } -static void detectQtCt(char qver, FFQtResult* result) -{ +static void detectQtCt(char qver, FFQtResult* result) { // qt5ct and qt6ct are technically separate applications, but they're both // by the same author and qt6ct understands qt5ct in qt6 applications as well. char file[] = "qtXct/qtXct.conf"; @@ -143,59 +140,45 @@ static void detectQtCt(char qver, FFQtResult* result) FF_STRBUF_AUTO_DESTROY font = ffStrbufCreate(); - ffParsePropFileConfigValues(file, 3, (FFpropquery[]) { - {"style=", &result->widgetStyle}, - {"icon_theme=", &result->icons}, - {"general=", &font} - }); + ffParsePropFileConfigValues(file, 3, (FFpropquery[]) {{"style=", &result->widgetStyle}, {"icon_theme=", &result->icons}, {"general=", &font}}); - if (ffStrbufStartsWithC(&font, '@')) - { + if (ffStrbufStartsWithC(&font, '@')) { // See QVariant notes on https://doc.qt.io/qt-5/qsettings.html and // https://github.com/fastfetch-cli/fastfetch/issues/1053#issuecomment-2197254769 // Thankfully, newer versions use the more common font encoding. ffStrbufSetNS(&font, 5, file); - } - else if (qver == '5') - { + } else if (qver == '5') { // #1864 - const char *p = font.chars; + const char* p = font.chars; - while (*p) - { - if (p[0] == '\\' && p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3]) && isxdigit(p[4]) && isxdigit(p[5])) - { - uint32_t codepoint = (uint32_t)strtoul((char[]) { p[2], p[3], p[4], p[5], '\0' }, NULL, 16); + while (*p) { + if (p[0] == '\\' && p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3]) && isxdigit(p[4]) && isxdigit(p[5])) { + uint32_t codepoint = (uint32_t) strtoul((char[]) {p[2], p[3], p[4], p[5], '\0'}, NULL, 16); ffStrbufAppendUtf32CodePoint(&result->font, codepoint); p += 6; - } - else - { + } else { ffStrbufAppendC(&result->font, *p++); } } - } - else - { + } else { ffStrbufDestroy(&result->font); ffStrbufInitMove(&result->font, &font); } } -static void detectKvantum(FFQtResult* result) -{ +static void detectKvantum(FFQtResult* result) { ffParsePropFileConfigValues("Kvantum/kvantum.kvconfig", 1, (FFpropquery[]) { - {"theme=", &result->widgetStyle}, - }); + {"theme=", &result->widgetStyle}, + }); } -const FFQtResult* ffDetectQt(void) -{ +const FFQtResult* ffDetectQt(void) { static FFQtResult result; static bool init = false; - if(init) + if (init) { return &result; + } init = true; ffStrbufInit(&result.widgetStyle); @@ -206,19 +189,18 @@ const FFQtResult* ffDetectQt(void) const FFDisplayServerResult* wmde = ffConnectDisplayServer(); - if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_PLASMA)) + if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_PLASMA)) { detectPlasma(&result); - else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_LXQT)) + } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_LXQT)) { detectLXQt(&result); - else - { - const char *qPlatformTheme = getenv("QT_QPA_PLATFORMTHEME"); - if(qPlatformTheme && (ffStrEquals(qPlatformTheme, "qt5ct") || ffStrEquals(qPlatformTheme, "qt6ct"))) + } else { + const char* qPlatformTheme = getenv("QT_QPA_PLATFORMTHEME"); + if (qPlatformTheme && (ffStrEquals(qPlatformTheme, "qt5ct") || ffStrEquals(qPlatformTheme, "qt6ct"))) { detectQtCt(qPlatformTheme[2], &result); + } } - if(ffStrbufEqualS(&result.widgetStyle, "kvantum") || ffStrbufEqualS(&result.widgetStyle, "kvantum-dark")) - { + if (ffStrbufEqualS(&result.widgetStyle, "kvantum") || ffStrbufEqualS(&result.widgetStyle, "kvantum-dark")) { ffStrbufClear(&result.widgetStyle); detectKvantum(&result); } diff --git a/src/detection/host/host.h b/src/detection/host/host.h index bd76e434e..a6fe3fbae 100644 --- a/src/detection/host/host.h +++ b/src/detection/host/host.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/host/option.h" -typedef struct FFHostResult -{ +typedef struct FFHostResult { FFstrbuf family; FFstrbuf name; FFstrbuf version; diff --git a/src/detection/host/host_android.c b/src/detection/host/host_android.c index 186d467e4..1157a92f0 100644 --- a/src/detection/host/host_android.c +++ b/src/detection/host/host_android.c @@ -3,26 +3,14 @@ #include -const char* ffDetectHost(FFHostResult* host) -{ +const char* ffDetectHost(FFHostResult* host) { // http://newandroidbook.com/ddb/ ffSettingsGetAndroidProperty("ro.product.device", &host->family); - ffSettingsGetAndroidProperty("ro.product.marketname", &host->name) - || ffSettingsGetAndroidProperty("ro.vendor.product.display", &host->name) - || ffSettingsGetAndroidProperty("ro.vivo.market.name", &host->name) - || ffSettingsGetAndroidProperty("ro.product.oppo_model", &host->name) - || ffSettingsGetAndroidProperty("ro.oppo.market.name", &host->name) - || ffSettingsGetAndroidProperty("ro.vendor.oplus.market.enname", &host->name) - || ffSettingsGetAndroidProperty("ro.config.devicename", &host->name) - || ffSettingsGetAndroidProperty("ro.config.marketing_name", &host->name) - || ffSettingsGetAndroidProperty("ro.product.vendor.model", &host->name) - || ffSettingsGetAndroidProperty("ro.product.brand", &host->name); + ffSettingsGetAndroidProperty("ro.product.marketname", &host->name) || ffSettingsGetAndroidProperty("ro.vendor.product.display", &host->name) || ffSettingsGetAndroidProperty("ro.vivo.market.name", &host->name) || ffSettingsGetAndroidProperty("ro.product.oppo_model", &host->name) || ffSettingsGetAndroidProperty("ro.oppo.market.name", &host->name) || ffSettingsGetAndroidProperty("ro.vendor.oplus.market.enname", &host->name) || ffSettingsGetAndroidProperty("ro.config.devicename", &host->name) || ffSettingsGetAndroidProperty("ro.config.marketing_name", &host->name) || ffSettingsGetAndroidProperty("ro.product.vendor.model", &host->name) || ffSettingsGetAndroidProperty("ro.product.brand", &host->name); - if (ffSettingsGetAndroidProperty("ro.product.model", &host->version)) - { - if (ffStrbufStartsWithIgnCase(&host->version, &host->name)) - { + if (ffSettingsGetAndroidProperty("ro.product.model", &host->version)) { + if (ffStrbufStartsWithIgnCase(&host->version, &host->name)) { ffStrbufSubstrAfter(&host->version, host->name.length); ffStrbufTrimLeft(&host->version, ' '); } @@ -30,8 +18,7 @@ const char* ffDetectHost(FFHostResult* host) ffSettingsGetAndroidProperty("ro.product.manufacturer", &host->vendor); - if(host->vendor.length && !ffStrbufStartsWithIgnCase(&host->name, &host->vendor)) - { + if (host->vendor.length && !ffStrbufStartsWithIgnCase(&host->name, &host->vendor)) { ffStrbufPrependS(&host->name, " "); ffStrbufPrepend(&host->name, &host->vendor); } diff --git a/src/detection/host/host_apple.c b/src/detection/host/host_apple.c index a340ab35f..a177bf405 100644 --- a/src/detection/host/host_apple.c +++ b/src/detection/host/host_apple.c @@ -4,55 +4,65 @@ #include -const char* getProductNameWithIokit(FFstrbuf* result) -{ +const char* getProductNameWithIokit(FFstrbuf* result) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t registryEntry = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/product"); - if (!registryEntry) + if (!registryEntry) { return "IOServiceGetMatchingService() failed"; + } FF_CFTYPE_AUTO_RELEASE CFStringRef productName = IORegistryEntryCreateCFProperty(registryEntry, CFSTR("product-name"), kCFAllocatorDefault, kNilOptions); - if (!productName) + if (!productName) { return "IORegistryEntryCreateCFProperty() failed"; + } return ffCfStrGetString(productName, result); } -const char* getOthersByIokit(FFHostResult* host) -{ +const char* getOthersByIokit(FFHostResult* host) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t registryEntry = IOServiceGetMatchingService(MACH_PORT_NULL, IOServiceMatching("IOPlatformExpertDevice")); - if (!registryEntry) + if (!registryEntry) { return "IOServiceGetMatchingService() failed"; + } FF_CFTYPE_AUTO_RELEASE CFStringRef serialNumber = IORegistryEntryCreateCFProperty(registryEntry, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, kNilOptions); - if (serialNumber) + if (serialNumber) { ffCfStrGetString(serialNumber, &host->serial); + } FF_CFTYPE_AUTO_RELEASE CFStringRef uuid = IORegistryEntryCreateCFProperty(registryEntry, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, kNilOptions); - if (uuid) + if (uuid) { ffCfStrGetString(uuid, &host->uuid); + } FF_CFTYPE_AUTO_RELEASE CFStringRef manufacturer = IORegistryEntryCreateCFProperty(registryEntry, CFSTR("manufacturer"), kCFAllocatorDefault, kNilOptions); - if (manufacturer) + if (manufacturer) { ffCfStrGetString(manufacturer, &host->vendor); + } FF_CFTYPE_AUTO_RELEASE CFStringRef version = IORegistryEntryCreateCFProperty(registryEntry, CFSTR("version"), kCFAllocatorDefault, kNilOptions); - if (version) + if (version) { ffCfStrGetString(version, &host->version); + } return NULL; } -const char* ffDetectHost(FFHostResult* host) -{ +const char* ffDetectHost(FFHostResult* host) { const char* error = ffSysctlGetString("hw.product", &host->family); - if (error) error = ffSysctlGetString("hw.model", &host->family); - if (error) return error; + if (error) { + error = ffSysctlGetString("hw.model", &host->family); + } + if (error) { + return error; + } ffStrbufSetStatic(&host->name, ffHostGetMacProductNameWithHwModel(&host->family)); - if (host->name.length == 0) + if (host->name.length == 0) { getProductNameWithIokit(&host->name); - if (host->name.length == 0) + } + if (host->name.length == 0) { ffStrbufSet(&host->name, &host->family); + } getOthersByIokit(host); return NULL; } diff --git a/src/detection/host/host_bsd.c b/src/detection/host/host_bsd.c index 86ca7664f..f6941307c 100644 --- a/src/detection/host/host_bsd.c +++ b/src/detection/host/host_bsd.c @@ -2,8 +2,7 @@ #include "common/settings.h" #include "common/smbiosHelper.h" -const char* ffDetectHost(FFHostResult* host) -{ +const char* ffDetectHost(FFHostResult* host) { ffSettingsGetFreeBSDKenv("smbios.system.product", &host->name); ffCleanUpSmbiosValue(&host->name); ffSettingsGetFreeBSDKenv("smbios.system.family", &host->family); @@ -19,9 +18,9 @@ const char* ffDetectHost(FFHostResult* host) ffSettingsGetFreeBSDKenv("smbios.system.maker", &host->vendor); ffCleanUpSmbiosValue(&host->vendor); - #ifdef __x86_64__ +#ifdef __x86_64__ ffHostDetectMac(host); - #endif +#endif return NULL; } diff --git a/src/detection/host/host_linux.c b/src/detection/host/host_linux.c index 17182f48f..1cbc467cd 100644 --- a/src/detection/host/host_linux.c +++ b/src/detection/host/host_linux.c @@ -5,114 +5,98 @@ #include -static bool getHostProductName(FFstrbuf* name) -{ +static bool getHostProductName(FFstrbuf* name) { if (ffReadFileBuffer("/sys/firmware/devicetree/base/model", name) || - ffReadFileBuffer("/sys/firmware/devicetree/base/banner-name", name)) - { + ffReadFileBuffer("/sys/firmware/devicetree/base/banner-name", name)) { ffStrbufTrimRight(name, '\0'); return true; } - if (ffReadFileBuffer("/tmp/sysinfo/model", name)) - { + if (ffReadFileBuffer("/tmp/sysinfo/model", name)) { ffStrbufTrimRightSpace(name); ffStrbufTrimRight(name, '\0'); - if(ffIsSmbiosValueSet(name)) + if (ffIsSmbiosValueSet(name)) { return true; + } } return false; } -static bool getHostSerialNumber(FFstrbuf* serial) -{ +static bool getHostSerialNumber(FFstrbuf* serial) { if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/system/serial", serial) || - ffReadFileBuffer("/sys/firmware/devicetree/base/serial-number", serial)) - { + ffReadFileBuffer("/sys/firmware/devicetree/base/serial-number", serial)) { ffStrbufTrimRight(serial, '\0'); return true; } return false; } -static bool getHostProductFamily(FFstrbuf* family) -{ +static bool getHostProductFamily(FFstrbuf* family) { if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/system/family", family) || - ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/system/product", family)) - { + ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/system/product", family)) { ffStrbufTrimRight(family, '\0'); return true; } return false; } -static bool getHostVendor(FFstrbuf* vendor) -{ - if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/system/manufacturer", vendor)) - { +static bool getHostVendor(FFstrbuf* vendor) { + if (ffReadFileBuffer("/sys/firmware/devicetree/base/smbios/smbios/system/manufacturer", vendor)) { ffStrbufTrimRight(vendor, '\0'); return true; } return false; } -const char* ffDetectHost(FFHostResult* host) -{ +const char* ffDetectHost(FFHostResult* host) { // This is a hack for Asahi Linux, whose product_family is empty - if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/product_family", "/sys/class/dmi/id/product_family", &host->family)) - { + if (ffGetSmbiosValue("/sys/devices/virtual/dmi/id/product_family", "/sys/class/dmi/id/product_family", &host->family)) { ffGetSmbiosValue("/sys/devices/virtual/dmi/id/product_name", "/sys/class/dmi/id/product_name", &host->name); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/product_version", "/sys/class/dmi/id/product_version", &host->version); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/product_sku", "/sys/class/dmi/id/product_sku", &host->sku); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/product_serial", "/sys/class/dmi/id/product_serial", &host->serial); ffGetSmbiosValue("/sys/devices/virtual/dmi/id/sys_vendor", "/sys/class/dmi/id/sys_vendor", &host->vendor); - } - else - { + } else { getHostProductFamily(&host->family); getHostProductName(&host->name); getHostSerialNumber(&host->serial); getHostVendor(&host->vendor); } - #ifdef __x86_64__ +#ifdef __x86_64__ ffHostDetectMac(host); - #endif +#endif - //KVM/Qemu virtual machine - if(ffStrbufStartsWithS(&host->name, "Standard PC")) + // KVM/Qemu virtual machine + if (ffStrbufStartsWithS(&host->name, "Standard PC")) { ffStrbufPrependS(&host->name, "KVM/QEMU "); + } - if(host->family.length == 0 && host->name.length == 0) - { + if (host->family.length == 0 && host->name.length == 0) { const char* wslDistroName = getenv("WSL_DISTRO_NAME"); - //On WSL, the real host can't be detected. Instead use WSL as host. - if(wslDistroName != NULL || getenv("WSL_DISTRO") != NULL || getenv("WSL_INTEROP") != NULL) - { + // On WSL, the real host can't be detected. Instead use WSL as host. + if (wslDistroName != NULL || getenv("WSL_DISTRO") != NULL || getenv("WSL_INTEROP") != NULL) { ffStrbufSetStatic(&host->name, "Windows Subsystem for Linux"); - if (wslDistroName) + if (wslDistroName) { ffStrbufAppendF(&host->name, " - %s", wslDistroName); + } ffStrbufSetStatic(&host->family, "WSL"); ffStrbufSetStatic(&host->vendor, "Microsoft Corporation"); - if (instance.config.general.detectVersion) - { - ffProcessAppendStdOut(&host->version, (char* const[]){ - "wslinfo", - "--wsl-version", - "-n", - NULL, - }); // supported in 2.2.3 and later + if (instance.config.general.detectVersion) { + ffProcessAppendStdOut(&host->version, (char* const[]) { + "wslinfo", + "--wsl-version", + "-n", + NULL, + }); // supported in 2.2.3 and later } - } - else if (ffStrbufStartsWithS(&instance.state.platform.sysinfo.version, "FreeBSD ")) - { + } else if (ffStrbufStartsWithS(&instance.state.platform.sysinfo.version, "FreeBSD ")) { ffStrbufSetStatic(&host->name, "Linux Binary Compatibility on FreeBSD"); ffStrbufSetStatic(&host->family, "FreeBSD"); ffStrbufSetStatic(&host->vendor, "FreeBSD Foundation"); - if (instance.config.general.detectVersion) - { + if (instance.config.general.detectVersion) { ffStrbufSetS(&host->version, instance.state.platform.sysinfo.version.chars + strlen("FreeBSD ")); ffStrbufSubstrBeforeFirstC(&host->version, ' '); } diff --git a/src/detection/host/host_mac.c b/src/detection/host/host_mac.c index f2c5075d0..7efa18a9b 100644 --- a/src/detection/host/host_mac.c +++ b/src/detection/host/host_mac.c @@ -1,8 +1,7 @@ #include "host.h" #include "common/stringUtils.h" -const char* ffHostGetMacProductNameWithHwModel(const FFstrbuf* hwModel) -{ +const char* ffHostGetMacProductNameWithHwModel(const FFstrbuf* hwModel) { // Macbook Pro: https://support.apple.com/en-us/HT201300 // Macbook Air: https://support.apple.com/en-us/HT201862 // Mac mini: https://support.apple.com/en-us/HT201894 @@ -10,190 +9,430 @@ const char* ffHostGetMacProductNameWithHwModel(const FFstrbuf* hwModel) // Mac Pro: https://support.apple.com/en-us/HT202888 // Mac Studio: https://support.apple.com/en-us/HT213073 - if(ffStrbufStartsWithS(hwModel, "MacBookPro")) - { + if (ffStrbufStartsWithS(hwModel, "MacBookPro")) { const char* version = hwModel->chars + strlen("MacBookPro"); - if(ffStrEquals(version, "18,3") || - ffStrEquals(version, "18,4")) return "MacBook Pro (14-inch, 2021)"; - if(ffStrEquals(version, "18,1") || - ffStrEquals(version, "18,2")) return "MacBook Pro (16-inch, 2021)"; - if(ffStrEquals(version, "17,1")) return "MacBook Pro (13-inch, M1, 2020)"; - if(ffStrEquals(version, "16,3")) return "MacBook Pro (13-inch, 2020, Two Thunderbolt 3 ports)"; - if(ffStrEquals(version, "16,2")) return "MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)"; - if(ffStrEquals(version, "16,4") || - ffStrEquals(version, "16,1")) return "MacBook Pro (16-inch, 2019)"; - if(ffStrEquals(version, "15,4")) return "MacBook Pro (13-inch, 2019, Two Thunderbolt 3 ports)"; - if(ffStrEquals(version, "15,3")) return "MacBook Pro (15-inch, 2019)"; - if(ffStrEquals(version, "15,2")) return "MacBook Pro (13-inch, 2018/2019, Four Thunderbolt 3 ports)"; - if(ffStrEquals(version, "15,1")) return "MacBook Pro (15-inch, 2018/2019)"; - if(ffStrEquals(version, "14,3")) return "MacBook Pro (15-inch, 2017)"; - if(ffStrEquals(version, "14,2")) return "MacBook Pro (13-inch, 2017, Four Thunderbolt 3 ports)"; - if(ffStrEquals(version, "14,1")) return "MacBook Pro (13-inch, 2017, Two Thunderbolt 3 ports)"; - if(ffStrEquals(version, "13,3")) return "MacBook Pro (15-inch, 2016)"; - if(ffStrEquals(version, "13,2")) return "MacBook Pro (13-inch, 2016, Four Thunderbolt 3 ports)"; - if(ffStrEquals(version, "13,1")) return "MacBook Pro (13-inch, 2016, Two Thunderbolt 3 ports)"; - if(ffStrEquals(version, "12,1")) return "MacBook Pro (Retina, 13-inch, Early 2015)"; - if(ffStrEquals(version, "11,4") || - ffStrEquals(version, "11,5")) return "MacBook Pro (Retina, 15-inch, Mid 2015)"; - if(ffStrEquals(version, "11,2") || - ffStrEquals(version, "11,3")) return "MacBook Pro (Retina, 15-inch, Late 2013/Mid 2014)"; - if(ffStrEquals(version, "11,1")) return "MacBook Pro (Retina, 13-inch, Late 2013/Mid 2014)"; - if(ffStrEquals(version, "10,2")) return "MacBook Pro (Retina, 13-inch, Late 2012/Early 2013)"; - if(ffStrEquals(version, "10,1")) return "MacBook Pro (Retina, 15-inch, Mid 2012/Early 2013)"; - if(ffStrEquals(version, "9,2")) return "MacBook Pro (13-inch, Mid 2012)"; - if(ffStrEquals(version, "9,1")) return "MacBook Pro (15-inch, Mid 2012)"; - if(ffStrEquals(version, "8,3")) return "MacBook Pro (17-inch, 2011)"; - if(ffStrEquals(version, "8,2")) return "MacBook Pro (15-inch, 2011)"; - if(ffStrEquals(version, "8,1")) return "MacBook Pro (13-inch, 2011)"; - if(ffStrEquals(version, "7,1")) return "MacBook Pro (13-inch, Mid 2010)"; - if(ffStrEquals(version, "6,2")) return "MacBook Pro (15-inch, Mid 2010)"; - if(ffStrEquals(version, "6,1")) return "MacBook Pro (17-inch, Mid 2010)"; - if(ffStrEquals(version, "5,5")) return "MacBook Pro (13-inch, Mid 2009)"; - if(ffStrEquals(version, "5,3")) return "MacBook Pro (15-inch, Mid 2009)"; - if(ffStrEquals(version, "5,2")) return "MacBook Pro (17-inch, Mid/Early 2009)"; - if(ffStrEquals(version, "5,1")) return "MacBook Pro (15-inch, Late 2008)"; - if(ffStrEquals(version, "4,1")) return "MacBook Pro (17/15-inch, Early 2008)"; - } - else if(ffStrbufStartsWithS(hwModel, "MacBookAir")) - { + if (ffStrEquals(version, "18,3") || + ffStrEquals(version, "18,4")) { + return "MacBook Pro (14-inch, 2021)"; + } + if (ffStrEquals(version, "18,1") || + ffStrEquals(version, "18,2")) { + return "MacBook Pro (16-inch, 2021)"; + } + if (ffStrEquals(version, "17,1")) { + return "MacBook Pro (13-inch, M1, 2020)"; + } + if (ffStrEquals(version, "16,3")) { + return "MacBook Pro (13-inch, 2020, Two Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "16,2")) { + return "MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "16,4") || + ffStrEquals(version, "16,1")) { + return "MacBook Pro (16-inch, 2019)"; + } + if (ffStrEquals(version, "15,4")) { + return "MacBook Pro (13-inch, 2019, Two Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "15,3")) { + return "MacBook Pro (15-inch, 2019)"; + } + if (ffStrEquals(version, "15,2")) { + return "MacBook Pro (13-inch, 2018/2019, Four Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "15,1")) { + return "MacBook Pro (15-inch, 2018/2019)"; + } + if (ffStrEquals(version, "14,3")) { + return "MacBook Pro (15-inch, 2017)"; + } + if (ffStrEquals(version, "14,2")) { + return "MacBook Pro (13-inch, 2017, Four Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "14,1")) { + return "MacBook Pro (13-inch, 2017, Two Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "13,3")) { + return "MacBook Pro (15-inch, 2016)"; + } + if (ffStrEquals(version, "13,2")) { + return "MacBook Pro (13-inch, 2016, Four Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "13,1")) { + return "MacBook Pro (13-inch, 2016, Two Thunderbolt 3 ports)"; + } + if (ffStrEquals(version, "12,1")) { + return "MacBook Pro (Retina, 13-inch, Early 2015)"; + } + if (ffStrEquals(version, "11,4") || + ffStrEquals(version, "11,5")) { + return "MacBook Pro (Retina, 15-inch, Mid 2015)"; + } + if (ffStrEquals(version, "11,2") || + ffStrEquals(version, "11,3")) { + return "MacBook Pro (Retina, 15-inch, Late 2013/Mid 2014)"; + } + if (ffStrEquals(version, "11,1")) { + return "MacBook Pro (Retina, 13-inch, Late 2013/Mid 2014)"; + } + if (ffStrEquals(version, "10,2")) { + return "MacBook Pro (Retina, 13-inch, Late 2012/Early 2013)"; + } + if (ffStrEquals(version, "10,1")) { + return "MacBook Pro (Retina, 15-inch, Mid 2012/Early 2013)"; + } + if (ffStrEquals(version, "9,2")) { + return "MacBook Pro (13-inch, Mid 2012)"; + } + if (ffStrEquals(version, "9,1")) { + return "MacBook Pro (15-inch, Mid 2012)"; + } + if (ffStrEquals(version, "8,3")) { + return "MacBook Pro (17-inch, 2011)"; + } + if (ffStrEquals(version, "8,2")) { + return "MacBook Pro (15-inch, 2011)"; + } + if (ffStrEquals(version, "8,1")) { + return "MacBook Pro (13-inch, 2011)"; + } + if (ffStrEquals(version, "7,1")) { + return "MacBook Pro (13-inch, Mid 2010)"; + } + if (ffStrEquals(version, "6,2")) { + return "MacBook Pro (15-inch, Mid 2010)"; + } + if (ffStrEquals(version, "6,1")) { + return "MacBook Pro (17-inch, Mid 2010)"; + } + if (ffStrEquals(version, "5,5")) { + return "MacBook Pro (13-inch, Mid 2009)"; + } + if (ffStrEquals(version, "5,3")) { + return "MacBook Pro (15-inch, Mid 2009)"; + } + if (ffStrEquals(version, "5,2")) { + return "MacBook Pro (17-inch, Mid/Early 2009)"; + } + if (ffStrEquals(version, "5,1")) { + return "MacBook Pro (15-inch, Late 2008)"; + } + if (ffStrEquals(version, "4,1")) { + return "MacBook Pro (17/15-inch, Early 2008)"; + } + } else if (ffStrbufStartsWithS(hwModel, "MacBookAir")) { const char* version = hwModel->chars + strlen("MacBookAir"); - if(ffStrEquals(version, "10,1")) return "MacBook Air (M1, 2020)"; - if(ffStrEquals(version, "9,1")) return "MacBook Air (Retina, 13-inch, 2020)"; - if(ffStrEquals(version, "8,2")) return "MacBook Air (Retina, 13-inch, 2019)"; - if(ffStrEquals(version, "8,1")) return "MacBook Air (Retina, 13-inch, 2018)"; - if(ffStrEquals(version, "7,2")) return "MacBook Air (13-inch, Early 2015/2017)"; - if(ffStrEquals(version, "7,1")) return "MacBook Air (11-inch, Early 2015)"; - if(ffStrEquals(version, "6,2")) return "MacBook Air (13-inch, Mid 2013/Early 2014)"; - if(ffStrEquals(version, "6,1")) return "MacBook Air (11-inch, Mid 2013/Early 2014)"; - if(ffStrEquals(version, "5,2")) return "MacBook Air (13-inch, Mid 2012)"; - if(ffStrEquals(version, "5,1")) return "MacBook Air (11-inch, Mid 2012)"; - if(ffStrEquals(version, "4,2")) return "MacBook Air (13-inch, Mid 2011)"; - if(ffStrEquals(version, "4,1")) return "MacBook Air (11-inch, Mid 2011)"; - if(ffStrEquals(version, "3,2")) return "MacBook Air (13-inch, Late 2010)"; - if(ffStrEquals(version, "3,1")) return "MacBook Air (11-inch, Late 2010)"; - if(ffStrEquals(version, "2,1")) return "MacBook Air (Mid 2009)"; - } - else if(ffStrbufStartsWithS(hwModel, "Macmini")) - { + if (ffStrEquals(version, "10,1")) { + return "MacBook Air (M1, 2020)"; + } + if (ffStrEquals(version, "9,1")) { + return "MacBook Air (Retina, 13-inch, 2020)"; + } + if (ffStrEquals(version, "8,2")) { + return "MacBook Air (Retina, 13-inch, 2019)"; + } + if (ffStrEquals(version, "8,1")) { + return "MacBook Air (Retina, 13-inch, 2018)"; + } + if (ffStrEquals(version, "7,2")) { + return "MacBook Air (13-inch, Early 2015/2017)"; + } + if (ffStrEquals(version, "7,1")) { + return "MacBook Air (11-inch, Early 2015)"; + } + if (ffStrEquals(version, "6,2")) { + return "MacBook Air (13-inch, Mid 2013/Early 2014)"; + } + if (ffStrEquals(version, "6,1")) { + return "MacBook Air (11-inch, Mid 2013/Early 2014)"; + } + if (ffStrEquals(version, "5,2")) { + return "MacBook Air (13-inch, Mid 2012)"; + } + if (ffStrEquals(version, "5,1")) { + return "MacBook Air (11-inch, Mid 2012)"; + } + if (ffStrEquals(version, "4,2")) { + return "MacBook Air (13-inch, Mid 2011)"; + } + if (ffStrEquals(version, "4,1")) { + return "MacBook Air (11-inch, Mid 2011)"; + } + if (ffStrEquals(version, "3,2")) { + return "MacBook Air (13-inch, Late 2010)"; + } + if (ffStrEquals(version, "3,1")) { + return "MacBook Air (11-inch, Late 2010)"; + } + if (ffStrEquals(version, "2,1")) { + return "MacBook Air (Mid 2009)"; + } + } else if (ffStrbufStartsWithS(hwModel, "Macmini")) { const char* version = hwModel->chars + strlen("Macmini"); - if(ffStrEquals(version, "9,1")) return "Mac mini (M1, 2020)"; - if(ffStrEquals(version, "8,1")) return "Mac mini (2018)"; - if(ffStrEquals(version, "7,1")) return "Mac mini (Mid 2014)"; - if(ffStrEquals(version, "6,1") || - ffStrEquals(version, "6,2")) return "Mac mini (Late 2012)"; - if(ffStrEquals(version, "5,1") || - ffStrEquals(version, "5,2")) return "Mac mini (Mid 2011)"; - if(ffStrEquals(version, "4,1")) return "Mac mini (Mid 2010)"; - if(ffStrEquals(version, "3,1")) return "Mac mini (Early/Late 2009)"; - } - else if(ffStrbufStartsWithS(hwModel, "MacBook")) - { + if (ffStrEquals(version, "9,1")) { + return "Mac mini (M1, 2020)"; + } + if (ffStrEquals(version, "8,1")) { + return "Mac mini (2018)"; + } + if (ffStrEquals(version, "7,1")) { + return "Mac mini (Mid 2014)"; + } + if (ffStrEquals(version, "6,1") || + ffStrEquals(version, "6,2")) { + return "Mac mini (Late 2012)"; + } + if (ffStrEquals(version, "5,1") || + ffStrEquals(version, "5,2")) { + return "Mac mini (Mid 2011)"; + } + if (ffStrEquals(version, "4,1")) { + return "Mac mini (Mid 2010)"; + } + if (ffStrEquals(version, "3,1")) { + return "Mac mini (Early/Late 2009)"; + } + } else if (ffStrbufStartsWithS(hwModel, "MacBook")) { const char* version = hwModel->chars + strlen("MacBook"); - if(ffStrEquals(version, "10,1")) return "MacBook (Retina, 12-inch, 2017)"; - if(ffStrEquals(version, "9,1")) return "MacBook (Retina, 12-inch, Early 2016)"; - if(ffStrEquals(version, "8,1")) return "MacBook (Retina, 12-inch, Early 2015)"; - if(ffStrEquals(version, "7,1")) return "MacBook (13-inch, Mid 2010)"; - if(ffStrEquals(version, "6,1")) return "MacBook (13-inch, Late 2009)"; - if(ffStrEquals(version, "5,2")) return "MacBook (13-inch, Early/Mid 2009)"; - } - else if(ffStrbufStartsWithS(hwModel, "MacPro")) - { + if (ffStrEquals(version, "10,1")) { + return "MacBook (Retina, 12-inch, 2017)"; + } + if (ffStrEquals(version, "9,1")) { + return "MacBook (Retina, 12-inch, Early 2016)"; + } + if (ffStrEquals(version, "8,1")) { + return "MacBook (Retina, 12-inch, Early 2015)"; + } + if (ffStrEquals(version, "7,1")) { + return "MacBook (13-inch, Mid 2010)"; + } + if (ffStrEquals(version, "6,1")) { + return "MacBook (13-inch, Late 2009)"; + } + if (ffStrEquals(version, "5,2")) { + return "MacBook (13-inch, Early/Mid 2009)"; + } + } else if (ffStrbufStartsWithS(hwModel, "MacPro")) { const char* version = hwModel->chars + strlen("MacPro"); - if(ffStrEquals(version, "7,1")) return "Mac Pro (2019)"; - if(ffStrEquals(version, "6,1")) return "Mac Pro (Late 2013)"; - if(ffStrEquals(version, "5,1")) return "Mac Pro (Mid 2010 - Mid 2012)"; - if(ffStrEquals(version, "4,1")) return "Mac Pro (Early 2009)"; - } - else if(ffStrbufStartsWithS(hwModel, "Mac")) - { + if (ffStrEquals(version, "7,1")) { + return "Mac Pro (2019)"; + } + if (ffStrEquals(version, "6,1")) { + return "Mac Pro (Late 2013)"; + } + if (ffStrEquals(version, "5,1")) { + return "Mac Pro (Mid 2010 - Mid 2012)"; + } + if (ffStrEquals(version, "4,1")) { + return "Mac Pro (Early 2009)"; + } + } else if (ffStrbufStartsWithS(hwModel, "Mac")) { const char* version = hwModel->chars + strlen("Mac"); - if(ffStrEquals(version, "17,9")) return "MacBook Pro (14-inch, M5 Pro, 2026)"; - if(ffStrEquals(version, "17,8")) return "MacBook Pro (16-inch, M5 Pro, 2026)"; - if(ffStrEquals(version, "17,7")) return "MacBook Pro (14-inch, M5 Max, 2026)"; - if(ffStrEquals(version, "17,6")) return "MacBook Pro (16-inch, M5 Max, 2026)"; - if(ffStrEquals(version, "17,5")) return "MacBook Neo (13-inch, A18 Pro, 2026)"; - if(ffStrEquals(version, "17,4")) return "MacBook Air (15-inch, M5, 2026)"; - if(ffStrEquals(version, "17,3")) return "MacBook Air (13-inch, M5, 2026)"; - if(ffStrEquals(version, "17,2")) return "MacBook Pro (14-inch, M5, 2025)"; - if(ffStrEquals(version, "16,13")) return "MacBook Air (15-inch, M4, 2025)"; - if(ffStrEquals(version, "16,12")) return "MacBook Air (13-inch, M4, 2025)"; - if(ffStrEquals(version, "16,11") || - ffStrEquals(version, "16,10")) return "Mac Mini (2024)"; - if(ffStrEquals(version, "16,9")) return "Mac Studio (M4 Max, 2025)"; - if(ffStrEquals(version, "16,3")) return "iMac (24-inch, 2024, Four Thunderbolt / USB 4 ports)"; - if(ffStrEquals(version, "16,2")) return "iMac (24-inch, 2024, Two Thunderbolt / USB 4 ports)"; - if(ffStrEquals(version, "16,1")) return "MacBook Pro (14-inch, 2024, Three Thunderbolt 4 ports)"; - if(ffStrEquals(version, "16,6") || - ffStrEquals(version, "16,8")) return "MacBook Pro (14-inch, 2024, Three Thunderbolt 5 ports)"; - if(ffStrEquals(version, "16,7") || - ffStrEquals(version, "16,5")) return "MacBook Pro (16-inch, 2024, Three Thunderbolt 5 ports)"; - if(ffStrEquals(version, "15,14")) return "Mac Studio (M3 Ultra, 2025)"; - if(ffStrEquals(version, "15,13")) return "MacBook Air (15-inch, M3, 2024)"; - if(ffStrEquals(version, "15,12")) return "MacBook Air (13-inch, M3, 2024)"; - if(ffStrEquals(version, "15,3")) return "MacBook Pro (14-inch, Nov 2023, Two Thunderbolt / USB 4 ports)"; - if(ffStrEquals(version, "15,4")) return "iMac (24-inch, 2023, Two Thunderbolt / USB 4 ports)"; - if(ffStrEquals(version, "15,5")) return "iMac (24-inch, 2023, Two Thunderbolt / USB 4 ports, Two USB 3 ports)"; - if(ffStrEquals(version, "15,6") || - ffStrEquals(version, "15,8") || - ffStrEquals(version, "15,10")) return "MacBook Pro (14-inch, Nov 2023, Three Thunderbolt 4 ports)"; - if(ffStrEquals(version, "15,7") || - ffStrEquals(version, "15,9") || - ffStrEquals(version, "15,11")) return "MacBook Pro (16-inch, Nov 2023, Three Thunderbolt 4 ports)"; - if(ffStrEquals(version, "14,15")) return "MacBook Air (15-inch, M2, 2023)"; - if(ffStrEquals(version, "14,14")) return "Mac Studio (M2 Ultra, 2023, Two Thunderbolt 4 front ports)"; - if(ffStrEquals(version, "14,13")) return "Mac Studio (M2 Max, 2023, Two USB-C front ports)"; - if(ffStrEquals(version, "14,8")) return "Mac Pro (2023)"; - if(ffStrEquals(version, "14,6") || - ffStrEquals(version, "14,10")) return "MacBook Pro (16-inch, 2023)"; - 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 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)"; - if(ffStrEquals(version, "13,2")) return "Mac Studio (M1 Ultra, 2022, Two Thunderbolt 4 front ports)"; - } - else if(ffStrbufStartsWithS(hwModel, "iMac")) - { + if (ffStrEquals(version, "17,9")) { + return "MacBook Pro (14-inch, M5 Pro, 2026)"; + } + if (ffStrEquals(version, "17,8")) { + return "MacBook Pro (16-inch, M5 Pro, 2026)"; + } + if (ffStrEquals(version, "17,7")) { + return "MacBook Pro (14-inch, M5 Max, 2026)"; + } + if (ffStrEquals(version, "17,6")) { + return "MacBook Pro (16-inch, M5 Max, 2026)"; + } + if (ffStrEquals(version, "17,5")) { + return "MacBook Neo (13-inch, A18 Pro, 2026)"; + } + if (ffStrEquals(version, "17,4")) { + return "MacBook Air (15-inch, M5, 2026)"; + } + if (ffStrEquals(version, "17,3")) { + return "MacBook Air (13-inch, M5, 2026)"; + } + if (ffStrEquals(version, "17,2")) { + return "MacBook Pro (14-inch, M5, 2025)"; + } + if (ffStrEquals(version, "16,13")) { + return "MacBook Air (15-inch, M4, 2025)"; + } + if (ffStrEquals(version, "16,12")) { + return "MacBook Air (13-inch, M4, 2025)"; + } + if (ffStrEquals(version, "16,11") || + ffStrEquals(version, "16,10")) { + return "Mac Mini (2024)"; + } + if (ffStrEquals(version, "16,9")) { + return "Mac Studio (M4 Max, 2025)"; + } + if (ffStrEquals(version, "16,3")) { + return "iMac (24-inch, 2024, Four Thunderbolt / USB 4 ports)"; + } + if (ffStrEquals(version, "16,2")) { + return "iMac (24-inch, 2024, Two Thunderbolt / USB 4 ports)"; + } + if (ffStrEquals(version, "16,1")) { + return "MacBook Pro (14-inch, 2024, Three Thunderbolt 4 ports)"; + } + if (ffStrEquals(version, "16,6") || + ffStrEquals(version, "16,8")) { + return "MacBook Pro (14-inch, 2024, Three Thunderbolt 5 ports)"; + } + if (ffStrEquals(version, "16,7") || + ffStrEquals(version, "16,5")) { + return "MacBook Pro (16-inch, 2024, Three Thunderbolt 5 ports)"; + } + if (ffStrEquals(version, "15,14")) { + return "Mac Studio (M3 Ultra, 2025)"; + } + if (ffStrEquals(version, "15,13")) { + return "MacBook Air (15-inch, M3, 2024)"; + } + if (ffStrEquals(version, "15,12")) { + return "MacBook Air (13-inch, M3, 2024)"; + } + if (ffStrEquals(version, "15,3")) { + return "MacBook Pro (14-inch, Nov 2023, Two Thunderbolt / USB 4 ports)"; + } + if (ffStrEquals(version, "15,4")) { + return "iMac (24-inch, 2023, Two Thunderbolt / USB 4 ports)"; + } + if (ffStrEquals(version, "15,5")) { + return "iMac (24-inch, 2023, Two Thunderbolt / USB 4 ports, Two USB 3 ports)"; + } + if (ffStrEquals(version, "15,6") || + ffStrEquals(version, "15,8") || + ffStrEquals(version, "15,10")) { + return "MacBook Pro (14-inch, Nov 2023, Three Thunderbolt 4 ports)"; + } + if (ffStrEquals(version, "15,7") || + ffStrEquals(version, "15,9") || + ffStrEquals(version, "15,11")) { + return "MacBook Pro (16-inch, Nov 2023, Three Thunderbolt 4 ports)"; + } + if (ffStrEquals(version, "14,15")) { + return "MacBook Air (15-inch, M2, 2023)"; + } + if (ffStrEquals(version, "14,14")) { + return "Mac Studio (M2 Ultra, 2023, Two Thunderbolt 4 front ports)"; + } + if (ffStrEquals(version, "14,13")) { + return "Mac Studio (M2 Max, 2023, Two USB-C front ports)"; + } + if (ffStrEquals(version, "14,8")) { + return "Mac Pro (2023)"; + } + if (ffStrEquals(version, "14,6") || + ffStrEquals(version, "14,10")) { + return "MacBook Pro (16-inch, 2023)"; + } + 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 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)"; + } + if (ffStrEquals(version, "13,2")) { + return "Mac Studio (M1 Ultra, 2022, Two Thunderbolt 4 front ports)"; + } + } else if (ffStrbufStartsWithS(hwModel, "iMac")) { const char* version = hwModel->chars + strlen("iMac"); - if(ffStrEquals(version, "21,1")) return "iMac (24-inch, M1, 2021, Two Thunderbolt / USB 4 ports, Two USB 3 ports)"; - if(ffStrEquals(version, "21,2")) return "iMac (24-inch, M1, 2021, Two Thunderbolt / USB 4 ports)"; - if(ffStrEquals(version, "20,1") || - ffStrEquals(version, "20,2")) return "iMac (Retina 5K, 27-inch, 2020)"; - if(ffStrEquals(version, "19,1")) return "iMac (Retina 5K, 27-inch, 2019)"; - if(ffStrEquals(version, "19,2")) return "iMac (Retina 4K, 21.5-inch, 2019)"; - if(ffStrEquals(version, "Pro1,1")) return "iMac Pro (2017)"; - if(ffStrEquals(version, "18,3")) return "iMac (Retina 5K, 27-inch, 2017)"; - if(ffStrEquals(version, "18,2")) return "iMac (Retina 4K, 21.5-inch, 2017)"; - if(ffStrEquals(version, "18,1")) return "iMac (21.5-inch, 2017)"; - if(ffStrEquals(version, "17,1")) return "iMac (Retina 5K, 27-inch, Late 2015)"; - if(ffStrEquals(version, "16,2")) return "iMac (Retina 4K, 21.5-inch, Late 2015)"; - if(ffStrEquals(version, "16,1")) return "iMac (21.5-inch, Late 2015)"; - if(ffStrEquals(version, "15,1")) return "iMac (Retina 5K, 27-inch, Late 2014 - Mid 2015)"; - if(ffStrEquals(version, "14,4")) return "iMac (21.5-inch, Mid 2014)"; - if(ffStrEquals(version, "14,2")) return "iMac (27-inch, Late 2013)"; - if(ffStrEquals(version, "14,1")) return "iMac (21.5-inch, Late 2013)"; - if(ffStrEquals(version, "13,2")) return "iMac (27-inch, Late 2012)"; - if(ffStrEquals(version, "13,1")) return "iMac (21.5-inch, Late 2012)"; - if(ffStrEquals(version, "12,2")) return "iMac (27-inch, Mid 2011)"; - if(ffStrEquals(version, "12,1")) return "iMac (21.5-inch, Mid 2011)"; - if(ffStrEquals(version, "11,3")) return "iMac (27-inch, Mid 2010)"; - if(ffStrEquals(version, "11,2")) return "iMac (21.5-inch, Mid 2010)"; - if(ffStrEquals(version, "10,1")) return "iMac (27/21.5-inch, Late 2009)"; - if(ffStrEquals(version, "9,1")) return "iMac (24/20-inch, Early 2009)"; + if (ffStrEquals(version, "21,1")) { + return "iMac (24-inch, M1, 2021, Two Thunderbolt / USB 4 ports, Two USB 3 ports)"; + } + if (ffStrEquals(version, "21,2")) { + return "iMac (24-inch, M1, 2021, Two Thunderbolt / USB 4 ports)"; + } + if (ffStrEquals(version, "20,1") || + ffStrEquals(version, "20,2")) { + return "iMac (Retina 5K, 27-inch, 2020)"; + } + if (ffStrEquals(version, "19,1")) { + return "iMac (Retina 5K, 27-inch, 2019)"; + } + if (ffStrEquals(version, "19,2")) { + return "iMac (Retina 4K, 21.5-inch, 2019)"; + } + if (ffStrEquals(version, "Pro1,1")) { + return "iMac Pro (2017)"; + } + if (ffStrEquals(version, "18,3")) { + return "iMac (Retina 5K, 27-inch, 2017)"; + } + if (ffStrEquals(version, "18,2")) { + return "iMac (Retina 4K, 21.5-inch, 2017)"; + } + if (ffStrEquals(version, "18,1")) { + return "iMac (21.5-inch, 2017)"; + } + if (ffStrEquals(version, "17,1")) { + return "iMac (Retina 5K, 27-inch, Late 2015)"; + } + if (ffStrEquals(version, "16,2")) { + return "iMac (Retina 4K, 21.5-inch, Late 2015)"; + } + if (ffStrEquals(version, "16,1")) { + return "iMac (21.5-inch, Late 2015)"; + } + if (ffStrEquals(version, "15,1")) { + return "iMac (Retina 5K, 27-inch, Late 2014 - Mid 2015)"; + } + if (ffStrEquals(version, "14,4")) { + return "iMac (21.5-inch, Mid 2014)"; + } + if (ffStrEquals(version, "14,2")) { + return "iMac (27-inch, Late 2013)"; + } + if (ffStrEquals(version, "14,1")) { + return "iMac (21.5-inch, Late 2013)"; + } + if (ffStrEquals(version, "13,2")) { + return "iMac (27-inch, Late 2012)"; + } + if (ffStrEquals(version, "13,1")) { + return "iMac (21.5-inch, Late 2012)"; + } + if (ffStrEquals(version, "12,2")) { + return "iMac (27-inch, Mid 2011)"; + } + if (ffStrEquals(version, "12,1")) { + return "iMac (21.5-inch, Mid 2011)"; + } + if (ffStrEquals(version, "11,3")) { + return "iMac (27-inch, Mid 2010)"; + } + if (ffStrEquals(version, "11,2")) { + return "iMac (21.5-inch, Mid 2010)"; + } + if (ffStrEquals(version, "10,1")) { + return "iMac (27/21.5-inch, Late 2009)"; + } + if (ffStrEquals(version, "9,1")) { + return "iMac (24/20-inch, Early 2009)"; + } } return NULL; } #ifdef __x86_64__ -bool ffHostDetectMac(FFHostResult* host) -{ - if (ffStrbufStartsWithS(&host->family, "Mac") && ffStrbufEqualS(&host->vendor, "Apple Inc.")) - { +bool ffHostDetectMac(FFHostResult* host) { + if (ffStrbufStartsWithS(&host->family, "Mac") && ffStrbufEqualS(&host->vendor, "Apple Inc.")) { const char* productName = ffHostGetMacProductNameWithHwModel(&host->name); - if (productName) - { + if (productName) { ffStrbufDestroy(&host->family); ffStrbufInitMove(&host->family, &host->name); ffStrbufSetStatic(&host->name, productName); diff --git a/src/detection/host/host_nbsd.c b/src/detection/host/host_nbsd.c index 6a1de3216..47dc24561 100644 --- a/src/detection/host/host_nbsd.c +++ b/src/detection/host/host_nbsd.c @@ -2,20 +2,24 @@ #include "common/sysctl.h" #include "common/smbiosHelper.h" -const char* ffDetectHost(FFHostResult* host) -{ +const char* ffDetectHost(FFHostResult* host) { const char* error = NULL; - if ((error = ffSysctlGetString("machdep.dmi.system-product", &host->name))) + if ((error = ffSysctlGetString("machdep.dmi.system-product", &host->name))) { return error; + } ffCleanUpSmbiosValue(&host->name); - if (ffSysctlGetString("machdep.dmi.system-vendor", &host->vendor) == NULL) + if (ffSysctlGetString("machdep.dmi.system-vendor", &host->vendor) == NULL) { ffCleanUpSmbiosValue(&host->vendor); - if (ffSysctlGetString("machdep.dmi.system-version", &host->version) == NULL) + } + if (ffSysctlGetString("machdep.dmi.system-version", &host->version) == NULL) { ffCleanUpSmbiosValue(&host->version); - if (ffSysctlGetString("machdep.dmi.system-serial", &host->serial) == NULL) + } + if (ffSysctlGetString("machdep.dmi.system-serial", &host->serial) == NULL) { ffCleanUpSmbiosValue(&host->serial); - if (ffSysctlGetString("machdep.dmi.system-uuid", &host->uuid) == NULL) + } + if (ffSysctlGetString("machdep.dmi.system-uuid", &host->uuid) == NULL) { ffCleanUpSmbiosValue(&host->uuid); + } return NULL; } diff --git a/src/detection/host/host_nosupport.c b/src/detection/host/host_nosupport.c index 29a54ebc9..0a95f156c 100644 --- a/src/detection/host/host_nosupport.c +++ b/src/detection/host/host_nosupport.c @@ -1,6 +1,5 @@ #include "host.h" -const char* ffDetectHost(FF_MAYBE_UNUSED FFHostResult* host) -{ +const char* ffDetectHost(FF_MAYBE_UNUSED FFHostResult* host) { return "Not supported on this platform"; } diff --git a/src/detection/host/host_obsd.c b/src/detection/host/host_obsd.c index 79ef15b62..c51765e87 100644 --- a/src/detection/host/host_obsd.c +++ b/src/detection/host/host_obsd.c @@ -2,18 +2,21 @@ #include "common/sysctl.h" #include "common/smbiosHelper.h" -const char* ffDetectHost(FFHostResult* host) -{ +const char* ffDetectHost(FFHostResult* host) { const char* error = NULL; - if ((error = ffSysctlGetString(CTL_HW, HW_PRODUCT, &host->name))) + if ((error = ffSysctlGetString(CTL_HW, HW_PRODUCT, &host->name))) { return error; + } ffCleanUpSmbiosValue(&host->name); - if (ffSysctlGetString(CTL_HW, HW_VENDOR, &host->vendor) == NULL) + if (ffSysctlGetString(CTL_HW, HW_VENDOR, &host->vendor) == NULL) { ffCleanUpSmbiosValue(&host->vendor); - if (ffSysctlGetString(CTL_HW, HW_VERSION, &host->version) == NULL) + } + if (ffSysctlGetString(CTL_HW, HW_VERSION, &host->version) == NULL) { ffCleanUpSmbiosValue(&host->version); - if (ffSysctlGetString(CTL_HW, HW_SERIALNO, &host->serial) == NULL) + } + if (ffSysctlGetString(CTL_HW, HW_SERIALNO, &host->serial) == NULL) { ffCleanUpSmbiosValue(&host->serial); + } return NULL; } diff --git a/src/detection/host/host_windows.c b/src/detection/host/host_windows.c index a9c14e6ca..e04125ecd 100644 --- a/src/detection/host/host_windows.c +++ b/src/detection/host/host_windows.c @@ -1,13 +1,12 @@ #include "host.h" #include "common/smbiosHelper.h" -typedef struct FFSmbiosSystemInfo -{ +typedef struct FFSmbiosSystemInfo { FFSmbiosHeader Header; uint8_t Manufacturer; // string - uint8_t ProductName; // string - uint8_t Version; // string + uint8_t ProductName; // string + uint8_t Version; // string uint8_t SerialNumber; // string // 2.1+ @@ -19,25 +18,26 @@ typedef struct FFSmbiosSystemInfo uint8_t ClockSeqLow; uint8_t Node[6]; } __attribute__((__packed__)) UUID; // varies - uint8_t WakeUpType; // enum + uint8_t WakeUpType; // enum // 2.4+ uint8_t SKUNumber; // string - uint8_t Family; // string + uint8_t Family; // string } __attribute__((__packed__)) FFSmbiosSystemInfo; static_assert(offsetof(FFSmbiosSystemInfo, Family) == 0x1A, "FFSmbiosSystemInfo: Wrong struct alignment"); -const char* ffDetectHost(FFHostResult* host) -{ +const char* ffDetectHost(FFHostResult* host) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosSystemInfo* data = (const FFSmbiosSystemInfo*) (*smbiosTable)[FF_SMBIOS_TYPE_SYSTEM_INFO]; - if (!data) + if (!data) { return "System information is not found in SMBIOS data"; + } const char* strings = (const char*) data + data->Header.Length; @@ -51,30 +51,24 @@ const char* ffDetectHost(FFHostResult* host) ffCleanUpSmbiosValue(&host->serial); static_assert(offsetof(FFSmbiosSystemInfo, UUID) == 0x08, "FFSmbiosSystemInfo.UUID offset is wrong"); - if (data->Header.Length > offsetof(FFSmbiosSystemInfo, UUID)) - { - ffStrbufSetF(&host->uuid, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", - data->UUID.TimeLow, data->UUID.TimeMid, data->UUID.TimeHighAndVersion, - data->UUID.ClockSeqHiAndReserved, data->UUID.ClockSeqLow, - data->UUID.Node[0], data->UUID.Node[1], data->UUID.Node[2], data->UUID.Node[3], data->UUID.Node[4], data->UUID.Node[5]); + if (data->Header.Length > offsetof(FFSmbiosSystemInfo, UUID)) { + ffStrbufSetF(&host->uuid, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", data->UUID.TimeLow, data->UUID.TimeMid, data->UUID.TimeHighAndVersion, data->UUID.ClockSeqHiAndReserved, data->UUID.ClockSeqLow, data->UUID.Node[0], data->UUID.Node[1], data->UUID.Node[2], data->UUID.Node[3], data->UUID.Node[4], data->UUID.Node[5]); } static_assert(offsetof(FFSmbiosSystemInfo, SKUNumber) == 0x19, "FFSmbiosSystemInfo.SKUNumber offset is wrong"); - if (data->Header.Length > offsetof(FFSmbiosSystemInfo, SKUNumber)) - { + if (data->Header.Length > offsetof(FFSmbiosSystemInfo, SKUNumber)) { ffStrbufSetStatic(&host->sku, ffSmbiosLocateString(strings, data->SKUNumber)); ffCleanUpSmbiosValue(&host->sku); } - if (data->Header.Length > offsetof(FFSmbiosSystemInfo, Family)) - { + if (data->Header.Length > offsetof(FFSmbiosSystemInfo, Family)) { ffStrbufSetStatic(&host->family, ffSmbiosLocateString(strings, data->Family)); ffCleanUpSmbiosValue(&host->family); } - #if __x86_64__ +#if __x86_64__ ffHostDetectMac(host); - #endif +#endif return NULL; } diff --git a/src/detection/icons/icons.h b/src/detection/icons/icons.h index 4c96304aa..7f3f20edb 100644 --- a/src/detection/icons/icons.h +++ b/src/detection/icons/icons.h @@ -3,11 +3,9 @@ #include "fastfetch.h" #include "modules/icons/option.h" -typedef struct FFIconsResult -{ +typedef struct FFIconsResult { FFstrbuf icons1; FFstrbuf icons2; } FFIconsResult; - const char* ffDetectIcons(FFIconsResult* result); diff --git a/src/detection/icons/icons_linux.c b/src/detection/icons/icons_linux.c index e5727b195..0ecaa0704 100644 --- a/src/detection/icons/icons_linux.c +++ b/src/detection/icons/icons_linux.c @@ -3,25 +3,25 @@ #include "detection/gtk_qt/gtk_qt.h" #include "detection/displayserver/displayserver.h" -const char* ffDetectIcons(FFIconsResult* result) -{ +const char* ffDetectIcons(FFIconsResult* result) { const FFDisplayServerResult* wmde = ffConnectDisplayServer(); - if(ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) + if (ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) { return "Icons aren't supported in TTY"; + } const FFstrbuf* plasma = &ffDetectQt()->icons; const FFstrbuf* gtk2 = &ffDetectGTK2()->icons; const FFstrbuf* gtk3 = &ffDetectGTK3()->icons; const FFstrbuf* gtk4 = &ffDetectGTK4()->icons; - if(plasma->length == 0 && gtk2->length == 0 && gtk3->length == 0 && gtk4->length == 0) + if (plasma->length == 0 && gtk2->length == 0 && gtk3->length == 0 && gtk4->length == 0) { return "No icons could be found"; + } ffParseGTK(&result->icons2, gtk2, gtk3, gtk4); - if(plasma->length > 0) - { + if (plasma->length > 0) { ffStrbufAppend(&result->icons1, plasma); ffStrbufAppendS(&result->icons1, " [Qt]"); } diff --git a/src/detection/icons/icons_nosupport.c b/src/detection/icons/icons_nosupport.c index da6ef936e..692dd33fe 100644 --- a/src/detection/icons/icons_nosupport.c +++ b/src/detection/icons/icons_nosupport.c @@ -1,6 +1,5 @@ #include "icons.h" -const char* ffDetectIcons(FF_MAYBE_UNUSED FFIconsResult* result) -{ +const char* ffDetectIcons(FF_MAYBE_UNUSED FFIconsResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/icons/icons_windows.c b/src/detection/icons/icons_windows.c index 79f6cfe09..e19943265 100644 --- a/src/detection/icons/icons_windows.c +++ b/src/detection/icons/icons_windows.c @@ -1,12 +1,10 @@ #include "icons.h" #include "common/windows/registry.h" -const char* ffDetectIcons(FFIconsResult* result) -{ +const char* ffDetectIcons(FFIconsResult* result) { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\NewStartPanel", &hKey, NULL) && - !ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\ClassicStartMenu", &hKey, NULL)) - { + if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\NewStartPanel", &hKey, NULL) && + !ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\ClassicStartMenu", &hKey, NULL)) { // If the key doesn't exist, it means that the user never changed the default settings. ffStrbufSetStatic(&result->icons2, "Recycle Bin"); return NULL; @@ -20,22 +18,28 @@ const char* ffDetectIcons(FFIconsResult* result) ffRegReadUint(hKey, L"{645FF040-5081-101B-9F08-00AA002F954E}", &RecycleBin, NULL); ffRegReadUint(hKey, L"{5399E694-6CE5-4D6C-8FCE-1D8870FDCBA0}", &ControlPanel, NULL); - if (ThisPC && UsersFiles && RemoteNetwork && RecycleBin && ControlPanel) + if (ThisPC && UsersFiles && RemoteNetwork && RecycleBin && ControlPanel) { return "All icons are hidden"; + } - if (!ThisPC) + if (!ThisPC) { ffStrbufAppendS(&result->icons1, "This PC, "); - if (!UsersFiles) + } + if (!UsersFiles) { ffStrbufAppendS(&result->icons1, "User's Files"); + } ffStrbufTrimRight(&result->icons1, ' '); ffStrbufTrimRight(&result->icons1, ','); - if (!RemoteNetwork) + if (!RemoteNetwork) { ffStrbufAppendS(&result->icons2, "Remote Network, "); - if (!RecycleBin) + } + if (!RecycleBin) { ffStrbufAppendS(&result->icons2, "Recycle Bin, "); - if (!ControlPanel) + } + if (!ControlPanel) { ffStrbufAppendS(&result->icons2, "Control Panel"); + } ffStrbufTrimRight(&result->icons2, ' '); ffStrbufTrimRight(&result->icons2, ','); diff --git a/src/detection/initsystem/initsystem.h b/src/detection/initsystem/initsystem.h index 7103616bf..3c59cf05d 100644 --- a/src/detection/initsystem/initsystem.h +++ b/src/detection/initsystem/initsystem.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/initsystem/option.h" -typedef struct FFInitSystemResult -{ +typedef struct FFInitSystemResult { FFstrbuf name; FFstrbuf exe; FFstrbuf version; diff --git a/src/detection/initsystem/initsystem_haiku.c b/src/detection/initsystem/initsystem_haiku.c index f3f367c09..bae9f851b 100644 --- a/src/detection/initsystem/initsystem_haiku.c +++ b/src/detection/initsystem/initsystem_haiku.c @@ -6,13 +6,13 @@ #include #include -const char* ffDetectInitSystem(FFInitSystemResult* result) -{ +const char* ffDetectInitSystem(FFInitSystemResult* result) { // Since it runs first, registrar does not know about it, // so we can't query be_roster for it. const char* path = "/boot/system/servers/launch_daemon"; - if (!ffPathExists(path, FF_PATHTYPE_FILE)) + if (!ffPathExists(path, FF_PATHTYPE_FILE)) { return "launch_daemon is not found"; + } ffStrbufSetStatic(&result->exe, path); ffStrbufSetStatic(&result->name, "launch_daemon"); @@ -20,17 +20,16 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) team_info teamInfo; int32 cookie = 0; - while (get_next_team_info(&cookie, &teamInfo) == B_OK) - { - if (ffStrEquals(teamInfo.args, path)) - { + while (get_next_team_info(&cookie, &teamInfo) == B_OK) { + if (ffStrEquals(teamInfo.args, path)) { result->pid = (uint32_t) teamInfo.team; break; } } - if (instance.config.general.detectVersion) + if (instance.config.general.detectVersion) { ffGetFileVersion(path, &result->version); + } return NULL; } diff --git a/src/detection/initsystem/initsystem_linux.c b/src/detection/initsystem/initsystem_linux.c index 408becbcf..d8fa3ca9b 100644 --- a/src/detection/initsystem/initsystem_linux.c +++ b/src/detection/initsystem/initsystem_linux.c @@ -6,113 +6,102 @@ #include #include -FF_MAYBE_UNUSED static bool extractSystemdVersion(const char* str, uint32_t len, void* userdata) -{ - if (!ffStrStartsWith(str, "systemd ")) return true; +FF_MAYBE_UNUSED static bool extractSystemdVersion(const char* str, uint32_t len, void* userdata) { + if (!ffStrStartsWith(str, "systemd ")) { + return true; + } const char* pstart = str + strlen("systemd "); const char* pend = memmem(pstart, len - strlen("systemd "), " running in ", strlen(" running in ")); - if (!pend) return true; + if (!pend) { + return true; + } ffStrbufSetNS((FFstrbuf*) userdata, (uint32_t) (pend - pstart), pstart); return false; } -const char* ffDetectInitSystem(FFInitSystemResult* result) -{ +const char* ffDetectInitSystem(FFInitSystemResult* result) { const char* error = ffProcessGetBasicInfoLinux((int) result->pid, &result->name, NULL, NULL); - if (error) - { - #ifdef __ANDROID__ - if (access("/system/bin/init", F_OK) == 0) - { + if (error) { +#ifdef __ANDROID__ + if (access("/system/bin/init", F_OK) == 0) { ffStrbufSetStatic(&result->exe, "/system/bin/init"); ffStrbufSetStatic(&result->name, "init"); return NULL; } - #endif +#endif return error; } const char* _; // In linux /proc/1/exe is not readable ffProcessGetInfoLinux((int) result->pid, &result->name, &result->exe, &_, NULL); - if (result->exe.chars[0] == '/') - { + if (result->exe.chars[0] == '/') { // In some old system, /sbin/init is a symlink char buf[PATH_MAX]; - if (realpath(result->exe.chars, buf)) - { + if (realpath(result->exe.chars, buf)) { ffStrbufSetS(&result->exe, buf); ffStrbufSetS(&result->name, basename(result->exe.chars)); } } - if (instance.config.general.detectVersion) - { - #if (defined(__linux__) && !defined(__ANDROID__)) || defined(__GNU__) - if (ffStrbufEqualS(&result->name, "systemd")) - { + if (instance.config.general.detectVersion) { +#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")); - if (result->version.length == 0) - { + if (result->version.length == 0) { if (ffProcessAppendStdOut(&result->version, (char* const[]) { - ffStrbufEndsWithS(&result->exe, "/systemd") ? result->exe.chars : "systemctl", // use exe path in case users have another systemd installed - "--version", - NULL, - }) == NULL && result->version.length) - { + ffStrbufEndsWithS(&result->exe, "/systemd") ? result->exe.chars : "systemctl", // use exe path in case users have another systemd installed + "--version", + NULL, + }) == NULL && + result->version.length) { uint32_t iStart = ffStrbufFirstIndexC(&result->version, '('); - if (iStart < result->version.length) - { + if (iStart < result->version.length) { uint32_t iEnd = ffStrbufNextIndexC(&result->version, iStart + 1, ')'); ffStrbufSubstrBefore(&result->version, iEnd); ffStrbufSubstrAfter(&result->version, iStart); } } } - } - else if (ffStrbufEqualS(&result->name, "dinit")) - { + } else if (ffStrbufEqualS(&result->name, "dinit")) { if (ffProcessAppendStdOut(&result->version, (char* const[]) { - ffStrbufEndsWithS(&result->exe, "/dinit") ? result->exe.chars : "dinit", - "--version", - NULL, - }) == NULL && result->version.length) - { + ffStrbufEndsWithS(&result->exe, "/dinit") ? result->exe.chars : "dinit", + "--version", + NULL, + }) == NULL && + result->version.length) { // Dinit version 0.18.0. ffStrbufSubstrBeforeFirstC(&result->version, '\n'); ffStrbufTrimRight(&result->version, '.'); 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) - { + } 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")) + if (!ffStrbufStartsWithS(&result->version, "shepherd")) { ffStrbufSubstrAfterFirstC(&result->version, '\n'); + } ffStrbufSubstrBeforeFirstC(&result->version, '\n'); ffStrbufSubstrAfterLastC(&result->version, ' '); } } - #elif __APPLE__ - if (ffStrbufEqualS(&result->name, "launchd")) - { +#elif __APPLE__ + if (ffStrbufEqualS(&result->name, "launchd")) { if (ffProcessAppendStdOut(&result->version, (char* const[]) { - "/bin/launchctl", - "version", - NULL, - }) == NULL && result->version.length) - { + "/bin/launchctl", + "version", + NULL, + }) == NULL && + result->version.length) { uint32_t iStart = ffStrbufFirstIndexS(&result->version, "Version "); - if (iStart < result->version.length) - { + if (iStart < result->version.length) { iStart += (uint32_t) strlen("Version"); uint32_t iEnd = ffStrbufNextIndexC(&result->version, iStart + 1, ':'); ffStrbufSubstrBefore(&result->version, iEnd); @@ -120,7 +109,7 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) } } } - #endif +#endif } return NULL; diff --git a/src/detection/initsystem/initsystem_nosupport.c b/src/detection/initsystem/initsystem_nosupport.c index b22a6b33d..431fa4c44 100644 --- a/src/detection/initsystem/initsystem_nosupport.c +++ b/src/detection/initsystem/initsystem_nosupport.c @@ -1,6 +1,5 @@ #include "initsystem.h" -const char* ffDetectInitSystem(FF_MAYBE_UNUSED FFInitSystemResult* result) -{ +const char* ffDetectInitSystem(FF_MAYBE_UNUSED FFInitSystemResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/keyboard/keyboard.h b/src/detection/keyboard/keyboard.h index 8f0a8a85e..6838a9cae 100644 --- a/src/detection/keyboard/keyboard.h +++ b/src/detection/keyboard/keyboard.h @@ -1,7 +1,6 @@ #include "fastfetch.h" -typedef struct FFKeyboardDevice -{ +typedef struct FFKeyboardDevice { FFstrbuf serial; FFstrbuf name; } FFKeyboardDevice; diff --git a/src/detection/keyboard/keyboard_apple.c b/src/detection/keyboard/keyboard_apple.c index 152fc18e2..a2b9292a0 100644 --- a/src/detection/keyboard/keyboard_apple.c +++ b/src/detection/keyboard/keyboard_apple.c @@ -5,8 +5,7 @@ #include #include -static void enumSet(IOHIDDeviceRef value, FFlist* results) -{ +static void enumSet(IOHIDDeviceRef value, FFlist* results) { FFKeyboardDevice* device = (FFKeyboardDevice*) ffListAdd(results); ffStrbufInit(&device->serial); ffStrbufInit(&device->name); @@ -18,24 +17,19 @@ static void enumSet(IOHIDDeviceRef value, FFlist* results) ffCfStrGetString(serialNumber, &device->serial); } -const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) -{ +const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { IOHIDManagerRef FF_CFTYPE_AUTO_RELEASE manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) + if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { return "IOHIDManagerOpen() failed"; + } - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void **)(CFStringRef[]){ - CFSTR(kIOHIDDeviceUsagePageKey), - CFSTR(kIOHIDDeviceUsageKey) - }, (const void **)(CFNumberRef[]){ - ffCfCreateInt(kHIDPage_GenericDesktop), - ffCfCreateInt(kHIDUsage_GD_Keyboard) - }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) {CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey)}, (const void**) (CFNumberRef[]) {ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Keyboard)}, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); IOHIDManagerSetDeviceMatching(manager, matching1); CFSetRef FF_CFTYPE_AUTO_RELEASE set = IOHIDManagerCopyDevices(manager); - if (set) + if (set) { CFSetApplyFunction(set, (CFSetApplierFunction) &enumSet, devices); + } IOHIDManagerClose(manager, kIOHIDOptionsTypeNone); return NULL; diff --git a/src/detection/keyboard/keyboard_bsd.c b/src/detection/keyboard/keyboard_bsd.c index 4e792b672..f18a79515 100644 --- a/src/detection/keyboard/keyboard_bsd.c +++ b/src/detection/keyboard/keyboard_bsd.c @@ -7,16 +7,16 @@ #include #if __has_include() - #include // FreeBSD +# include // FreeBSD #else - #include // DragonFly +# include // DragonFly #endif -static const char* detectByIoctl(FFlist* devices) -{ +static const char* detectByIoctl(FFlist* devices) { keyboard_info_t kbdInfo; - if (ioctl(STDIN_FILENO, KDGKBINFO, &kbdInfo) != 0) + if (ioctl(STDIN_FILENO, KDGKBINFO, &kbdInfo) != 0) { return "ioctl(KDGKBINFO) failed"; + } FFKeyboardDevice* device = (FFKeyboardDevice*) ffListAdd(devices); @@ -40,36 +40,35 @@ static const char* detectByIoctl(FFlist* devices) #define MAX_UHID_KBDS 64 -static const char* detectByUsbhid(FFlist* devices) -{ +static const char* detectByUsbhid(FFlist* devices) { char path[16]; - for (int i = 0; i < MAX_UHID_KBDS; i++) - { + for (int i = 0; i < MAX_UHID_KBDS; i++) { snprintf(path, ARRAY_SIZE(path), "/dev/uhid%d", i); FF_AUTO_CLOSE_FD int fd = open(path, O_RDONLY | O_CLOEXEC); - if (fd < 0) - { - if (errno == ENOENT) + if (fd < 0) { + if (errno == ENOENT) { break; // No more devices + } continue; // Device not found } report_desc_t repDesc = hid_get_report_desc(fd); - if (!repDesc) continue; + if (!repDesc) { + continue; + } int reportId = hid_get_report_id(fd); struct hid_data* hData = hid_start_parse(repDesc, 0, reportId); - if (hData) - { + if (hData) { struct hid_item hItem; - while (hid_get_item(hData, &hItem) > 0) - { - if (HID_PAGE(hItem.usage) != 1 || HID_USAGE(hItem.usage) != 6) continue; + while (hid_get_item(hData, &hItem) > 0) { + if (HID_PAGE(hItem.usage) != 1 || HID_USAGE(hItem.usage) != 6) { + continue; + } struct usb_device_info di; - if (ioctl(fd, USB_GET_DEVICEINFO, &di) != -1) - { + if (ioctl(fd, USB_GET_DEVICEINFO, &di) != -1) { FFKeyboardDevice* device = (FFKeyboardDevice*) ffListAdd(devices); ffStrbufInitS(&device->serial, di.udi_serial); ffStrbufInitS(&device->name, di.udi_product); @@ -84,10 +83,10 @@ static const char* detectByUsbhid(FFlist* devices) return NULL; } -const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) -{ +const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { detectByUsbhid(devices); - if (devices->length > 0) + if (devices->length > 0) { return NULL; + } return detectByIoctl(devices); } diff --git a/src/detection/keyboard/keyboard_haiku.cpp b/src/detection/keyboard/keyboard_haiku.cpp index f165b00fd..644dbc87b 100644 --- a/src/detection/keyboard/keyboard_haiku.cpp +++ b/src/detection/keyboard/keyboard_haiku.cpp @@ -5,18 +5,18 @@ extern "C" { #include #include -const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) -{ +const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { BList list; - if (get_input_devices(&list) != B_OK) + if (get_input_devices(&list) != B_OK) { return "get_input_devices() failed"; + } - for (int32 i = 0, n = list.CountItems(); i < n; i++) - { - BInputDevice *device = (BInputDevice *) list.ItemAt(i); - if (device->Type() != B_KEYBOARD_DEVICE || !device->IsRunning()) + for (int32 i = 0, n = list.CountItems(); i < n; i++) { + BInputDevice* device = (BInputDevice*) list.ItemAt(i); + if (device->Type() != B_KEYBOARD_DEVICE || !device->IsRunning()) { continue; + } FFKeyboardDevice* item = (FFKeyboardDevice*) ffListAdd(devices); ffStrbufInit(&item->serial); diff --git a/src/detection/keyboard/keyboard_linux.c b/src/detection/keyboard/keyboard_linux.c index e88e3ab44..47e8abeed 100644 --- a/src/detection/keyboard/keyboard_linux.c +++ b/src/detection/keyboard/keyboard_linux.c @@ -4,30 +4,29 @@ #include -const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) -{ +const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { // Parse /proc/bus/input/devices to find keyboards with a "kbd" handler. // This detects both wired and Bluetooth keyboards uniformly. FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); - if (!ffAppendFileBuffer("/proc/bus/input/devices", &content)) + if (!ffAppendFileBuffer("/proc/bus/input/devices", &content)) { return "ffAppendFileBuffer(\"/proc/bus/input/devices\") == NULL"; + } FFstrbuf kbd = ffStrbufCreateStatic("kbd"); FFKeyboardDevice device = { .name = ffStrbufCreate(), - .serial = ffStrbufCreate() - }; + .serial = ffStrbufCreate()}; char* line = NULL; size_t len = 0; - while (ffStrbufGetline(&line, &len, &content)) - { - switch (line[0]) - { + while (ffStrbufGetline(&line, &len, &content)) { + switch (line[0]) { case 'N': { const uint32_t prefixLen = strlen("N: Name="); - if (__builtin_expect(len <= prefixLen, false)) continue; + if (__builtin_expect(len <= prefixLen, false)) { + continue; + } const char* name = line + prefixLen; const uint32_t nameLen = (uint32_t) len - prefixLen; ffStrbufSetNS(&device.name, nameLen, name); @@ -36,25 +35,26 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) } case 'H': { const uint32_t prefixLen = strlen("H: Handlers="); - if (__builtin_expect(len <= prefixLen, false)) continue; + if (__builtin_expect(len <= prefixLen, false)) { + continue; + } const char* handlers = line + prefixLen; const uint32_t handlersLen = (uint32_t) len - prefixLen; - if (!ffStrbufMatchSeparatedNS(&kbd, handlersLen, handlers, ' ')) + if (!ffStrbufMatchSeparatedNS(&kbd, handlersLen, handlers, ' ')) { goto skipDevice; + } continue; } case 'B': { const char* bits = line + strlen("B: "); - if (ffStrStartsWith(bits, "EV=")) - { + if (ffStrStartsWith(bits, "EV=")) { // Check EV_REP (auto-repeat, bit 20) to filter pseudo-keyboards (Power Button, PC Speaker). const char* evBits = bits + strlen("EV="); uint64_t val = strtoull(evBits, NULL, 16); - if (!(val & (1ULL << EV_REP))) + if (!(val & (1ULL << EV_REP))) { goto skipDevice; - } - else if (ffStrStartsWith(bits, "KEY=")) - { + } + } else if (ffStrStartsWith(bits, "KEY=")) { // Check KEY_A (bit 30) to filter media remotes and headset controls. // The key capability bitmap is space-separated hex longs, MSB first; // KEY_A falls in the last (least significant) word on all architectures. @@ -63,23 +63,25 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) lastWord = lastWord ? lastWord + 1 : keyBits; uint64_t val = strtoull(lastWord, NULL, 16); - if (!(val & (1ULL << KEY_A))) + if (!(val & (1ULL << KEY_A))) { goto skipDevice; + } } continue; } case 'U': { const uint32_t prefixLen = strlen("U: Uniq="); - if (__builtin_expect(len <= prefixLen, false)) continue; + if (__builtin_expect(len <= prefixLen, false)) { + continue; + } const char* uniq = line + prefixLen; - const uint32_t uniqLen = (uint32_t) len - prefixLen; + const uint32_t uniqLen = (uint32_t) len - prefixLen; ffStrbufSetNS(&device.serial, uniqLen, uniq); continue; } case '\0': // End of device entry; add to list if it has a name. - if (device.name.length > 0) - { + if (device.name.length > 0) { FFKeyboardDevice* added = (FFKeyboardDevice*) ffListAdd(devices); ffStrbufInitMove(&added->name, &device.name); ffStrbufInitMove(&added->serial, &device.serial); @@ -89,13 +91,12 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) continue; } - skipDevice: - // Skip to the end of the current device entry. - while (line[0] != '\0' && ffStrbufGetline(&line, &len, &content)) - ; - // Despite the fn name, it resets the string buffer to initial state - ffStrbufDestroy(&device.name); - ffStrbufDestroy(&device.serial); + skipDevice: + // Skip to the end of the current device entry. + while (line[0] != '\0' && ffStrbufGetline(&line, &len, &content)); + // Despite the fn name, it resets the string buffer to initial state + ffStrbufDestroy(&device.name); + ffStrbufDestroy(&device.serial); } return NULL; diff --git a/src/detection/keyboard/keyboard_nosupport.c b/src/detection/keyboard/keyboard_nosupport.c index c6431c8fb..2d6aa024c 100644 --- a/src/detection/keyboard/keyboard_nosupport.c +++ b/src/detection/keyboard/keyboard_nosupport.c @@ -1,6 +1,5 @@ #include "keyboard.h" -const char* ffDetectKeyboard(FF_MAYBE_UNUSED FFlist* devices /* List of FFKeyboardDevice */) -{ +const char* ffDetectKeyboard(FF_MAYBE_UNUSED FFlist* devices /* List of FFKeyboardDevice */) { return "No mouse support on this platform"; } diff --git a/src/detection/keyboard/keyboard_windows.c b/src/detection/keyboard/keyboard_windows.c index 1853d72fb..0789623f8 100644 --- a/src/detection/keyboard/keyboard_windows.c +++ b/src/detection/keyboard/keyboard_windows.c @@ -10,34 +10,38 @@ #include #include -const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) -{ +const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { UINT nDevices = 0; - if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) + if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) { return "GetRawInputDeviceList(NULL) failed"; - if (nDevices == 0) + } + if (nDevices == 0) { return "No HID devices found"; + } RAWINPUTDEVICELIST* FF_AUTO_FREE pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); - if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) + if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) { return "GetRawInputDeviceList(pRawInputDeviceList) failed"; + } - - for (UINT i = 0; i < nDevices; ++i) - { - if (pRawInputDeviceList[i].dwType != RIM_TYPEKEYBOARD) continue; + for (UINT i = 0; i < nDevices; ++i) { + if (pRawInputDeviceList[i].dwType != RIM_TYPEKEYBOARD) { + continue; + } HANDLE hDevice = pRawInputDeviceList[i].hDevice; RID_DEVICE_INFO rdi; UINT rdiSize = sizeof(rdi); - if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == (UINT) -1) + if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == (UINT) -1) { continue; + } WCHAR devName[MAX_PATH]; UINT nameSize = MAX_PATH; - if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, devName, &nameSize) == (UINT) -1) + if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, devName, &nameSize) == (UINT) -1) { continue; + } FFKeyboardDevice* device = (FFKeyboardDevice*) ffListAdd(devices); ffStrbufInit(&device->serial); @@ -46,35 +50,35 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) wchar_t buffer[MAX_PATH]; HANDLE FF_AUTO_CLOSE_FD hHidFile = CreateFileW(devName, 0 /* must be 0 instead of GENERIC_READ */, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - if (hHidFile != INVALID_HANDLE_VALUE) - { - if (HidD_GetProductString(hHidFile, buffer, (ULONG) sizeof(buffer))) + if (hHidFile != INVALID_HANDLE_VALUE) { + if (HidD_GetProductString(hHidFile, buffer, (ULONG) sizeof(buffer))) { ffStrbufSetWS(&device->name, buffer); + } - if (HidD_GetSerialNumberString(hHidFile, buffer, sizeof(buffer))) + if (HidD_GetSerialNumberString(hHidFile, buffer, sizeof(buffer))) { ffStrbufSetWS(&device->serial, buffer); + } } - if (!device->name.length) - { + if (!device->name.length) { // https://stackoverflow.com/a/64321096/9976392 DEVPROPTYPE propertyType; ULONG propertySize = sizeof(buffer); - if (CM_Get_Device_Interface_PropertyW(devName, &DEVPKEY_Device_InstanceId, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) - { + if (CM_Get_Device_Interface_PropertyW(devName, &DEVPKEY_Device_InstanceId, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) { DEVINST devInst; - if (CM_Locate_DevNodeW(&devInst, buffer, CM_LOCATE_DEVNODE_NORMAL) == CR_SUCCESS) - { + if (CM_Locate_DevNodeW(&devInst, buffer, CM_LOCATE_DEVNODE_NORMAL) == CR_SUCCESS) { propertySize = sizeof(buffer); - if (CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_NAME, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) + if (CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_NAME, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) { ffStrbufSetWS(&device->name, buffer); + } } } } - if (!device->name.length) + if (!device->name.length) { ffStrbufSetF(&device->name, "Unknown device %04X-%04X", (unsigned) rdi.hid.dwVendorId, (unsigned) rdi.hid.dwProductId); + } } return NULL; diff --git a/src/detection/libc/libc.h b/src/detection/libc/libc.h index ea7bb8013..f2718e8d0 100644 --- a/src/detection/libc/libc.h +++ b/src/detection/libc/libc.h @@ -2,8 +2,7 @@ #include "fastfetch.h" -typedef struct FFLibcResult -{ +typedef struct FFLibcResult { const char* name; const char* version; } FFLibcResult; diff --git a/src/detection/libc/libc_android.c b/src/detection/libc/libc_android.c index 845a66fa4..5042807a6 100644 --- a/src/detection/libc/libc_android.c +++ b/src/detection/libc/libc_android.c @@ -5,19 +5,18 @@ #include -const char* ffDetectLibc(FFLibcResult* result) -{ +const char* ffDetectLibc(FFLibcResult* result) { #if __ANDROID_NDK__ result->name = "ndk-bionic"; result->version = FF_STR(__NDK_MAJOR__) "." FF_STR(__NDK_MINOR__) "." FF_STR(__NDK_BUILD__) - #if __NDK_BETA__ - "-beta" FF_STR(__NDK_BETA__) - #elif __NDK_CANARY__ - "-canary" - #endif +# if __NDK_BETA__ + "-beta" FF_STR(__NDK_BETA__) +# elif __NDK_CANARY__ + "-canary" +# endif - ; + ; return NULL; #else return "Unknown Android libc"; diff --git a/src/detection/libc/libc_apple.c b/src/detection/libc/libc_apple.c index dbaa20d91..07ca2b5a8 100644 --- a/src/detection/libc/libc_apple.c +++ b/src/detection/libc/libc_apple.c @@ -1,7 +1,6 @@ #include "libc.h" -const char* ffDetectLibc(FFLibcResult* result) -{ +const char* ffDetectLibc(FFLibcResult* result) { result->name = "libSystem"; #ifdef FF_LIBSYSTEM_VERSION diff --git a/src/detection/libc/libc_bsd.c b/src/detection/libc/libc_bsd.c index 7c80e1181..07cd72706 100644 --- a/src/detection/libc/libc_bsd.c +++ b/src/detection/libc/libc_bsd.c @@ -1,20 +1,19 @@ #include "libc.h" -const char* ffDetectLibc(FFLibcResult* result) -{ +const char* ffDetectLibc(FFLibcResult* result) { result->name = "Unknown"; result->version = NULL; #ifdef __DragonFly__ // We define `__FreeBSD__` on DragonFly BSD for simplification result->name = "DF"; - #ifdef FF_DF_VERSION +# ifdef FF_DF_VERSION result->version = FF_DF_VERSION; - #endif +# endif #elif __FreeBSD__ result->name = "FBSD"; - #ifdef FF_FBSD_VERSION +# ifdef FF_FBSD_VERSION result->version = FF_FBSD_VERSION; - #endif +# endif #endif return NULL; diff --git a/src/detection/libc/libc_linux.c b/src/detection/libc/libc_linux.c index 19e8e8328..e43b60e81 100644 --- a/src/detection/libc/libc_linux.c +++ b/src/detection/libc/libc_linux.c @@ -5,8 +5,7 @@ #include -const char* ffDetectLibc(FFLibcResult* result) -{ +const char* ffDetectLibc(FFLibcResult* result) { #ifdef __UCLIBC__ result->name = "uClibc"; result->version = FF_STR(__UCLIBC_MAJOR__) "." FF_STR(__UCLIBC_MINOR__) "." FF_STR(__UCLIBC_SUBLEVEL__); @@ -15,11 +14,11 @@ const char* ffDetectLibc(FFLibcResult* result) result->version = FF_STR(__GLIBC__) "." FF_STR(__GLIBC_MINOR__); #else result->name = "musl"; - #ifdef FF_MUSL_VERSION - result->version = FF_MUSL_VERSION; - #else - result->version = NULL; - #endif +# ifdef FF_MUSL_VERSION + result->version = FF_MUSL_VERSION; +# else + result->version = NULL; +# endif #endif return NULL; diff --git a/src/detection/libc/libc_nosupport.c b/src/detection/libc/libc_nosupport.c index be1316cce..e4687b072 100644 --- a/src/detection/libc/libc_nosupport.c +++ b/src/detection/libc/libc_nosupport.c @@ -1,7 +1,6 @@ #include "libc.h" -const char* ffDetectLibc(FFLibcResult* result) -{ +const char* ffDetectLibc(FFLibcResult* result) { result->name = "Unknown"; result->version = NULL; return NULL; diff --git a/src/detection/libc/libc_windows.cpp b/src/detection/libc/libc_windows.cpp index 8a699d765..daa1d27b7 100644 --- a/src/detection/libc/libc_windows.cpp +++ b/src/detection/libc/libc_windows.cpp @@ -1,31 +1,32 @@ -extern "C" -{ +extern "C" { #include "libc.h" } #ifdef __MINGW32__ -#include <_mingw.h> +# include <_mingw.h> #endif -template +template class version_t { constexpr static auto buflen() noexcept { unsigned int len = 2; // "." - if (Major == 0) + if (Major == 0) { len++; - else + } else { for (auto n = Major; n; len++, n /= 10); + } - if (Minor == 0) + if (Minor == 0) { len++; - else + } else { for (auto n = Minor; n; len++, n /= 10); + } return len; } char buf[buflen()] = {}; -public: + public: constexpr version_t() noexcept { auto ptr = buf + buflen(); *--ptr = '\0'; @@ -33,27 +34,29 @@ public: if (Minor == 0) { *--ptr = '0'; } else { - for (auto n = Minor; n; n /= 10) + for (auto n = Minor; n; n /= 10) { *--ptr = "0123456789"[n % 10]; + } } *--ptr = '.'; if (Major == 0) { *--ptr = '0'; } else { - for (auto n = Major; n; n /= 10) + for (auto n = Major; n; n /= 10) { *--ptr = "0123456789"[n % 10]; + } } } - constexpr operator const char *() const { return buf; } + constexpr operator const char*() const { + return buf; + } }; -template +template constexpr version_t version; -extern "C" -const char* ffDetectLibc(FFLibcResult* result) -{ +extern "C" const char* ffDetectLibc(FFLibcResult* result) { #ifdef _UCRT result->name = "ucrt"; #else diff --git a/src/detection/lm/lm.h b/src/detection/lm/lm.h index 1cd8bb3ba..d30229a79 100644 --- a/src/detection/lm/lm.h +++ b/src/detection/lm/lm.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/lm/option.h" -typedef struct FFLMResult -{ +typedef struct FFLMResult { FFstrbuf service; FFstrbuf type; FFstrbuf version; diff --git a/src/detection/lm/lm_linux.c b/src/detection/lm/lm_linux.c index c73adf0cc..6701d97e1 100644 --- a/src/detection/lm/lm_linux.c +++ b/src/detection/lm/lm_linux.c @@ -9,21 +9,13 @@ #define FF_SYSTEMD_SESSIONS_PATH "/run/systemd/sessions/" #define FF_SYSTEMD_USERS_PATH "/run/systemd/users/" -static const char* getGdmVersion(FFstrbuf* version) -{ - const char* error = ffProcessAppendStdOut(version, (char* const[]) { - "gdm", - "--version", - NULL - }); - if (error || version->length == 0) - { - error = ffProcessAppendStdOut(version, (char* const[]) { - "gdm3", - "--version", - NULL - }); - if (error || version->length == 0) return "Failed to get GDM version"; +static const char* getGdmVersion(FFstrbuf* version) { + const char* error = ffProcessAppendStdOut(version, (char* const[]) {"gdm", "--version", NULL}); + if (error || version->length == 0) { + error = ffProcessAppendStdOut(version, (char* const[]) {"gdm3", "--version", NULL}); + if (error || version->length == 0) { + return "Failed to get GDM version"; + } } // GDM 44.1 @@ -31,15 +23,11 @@ static const char* getGdmVersion(FFstrbuf* version) return NULL; } -static const char* getSshdVersion(FFstrbuf* version) -{ - const char* error = ffProcessAppendStdErr(version, (char* const[]) { - "sshd", - "-V", - NULL - }); - if (error) +static const char* getSshdVersion(FFstrbuf* version) { + const char* error = ffProcessAppendStdErr(version, (char* const[]) {"sshd", "-V", NULL}); + if (error) { return error; + } // OpenSSH_9.0p1, OpenSSL 3.0.9 30 May 2023... ffStrbufSubstrBeforeFirstC(version, ','); @@ -48,12 +36,11 @@ static const char* getSshdVersion(FFstrbuf* version) } #ifdef FF_HAVE_ZLIB -#include "common/library.h" -#include -#include +# include "common/library.h" +# include +# include -static const char* getSddmVersion(FFstrbuf* version) -{ +static const char* getSddmVersion(FFstrbuf* version) { FF_LIBRARY_LOAD_MESSAGE(zlib, "libz" FF_LIBRARY_EXTENSION, 2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(zlib, gzopen) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(zlib, gzread) @@ -63,21 +50,22 @@ static const char* getSddmVersion(FFstrbuf* version) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(zlib, gzclose) gzFile file = ffgzopen(FASTFETCH_TARGET_DIR_USR "/share/man/man1/sddm.1.gz", "rb"); - if (file == Z_NULL) + if (file == Z_NULL) { return "ffgzopen(\"/usr/share/man/man1/sddm.1.gz\", \"rb\") failed"; + } ffStrbufEnsureFree(version, 2047); memset(version->chars, 0, version->allocated); int size = ffgzread(file, version->chars, version->allocated - 1); ffgzclose(file); - if (size <= 0) + if (size <= 0) { return "ffgzread(file, version->chars, version->length) failed"; + } version->length = (uint32_t) size; uint32_t index = ffStrbufFirstIndexS(version, ".TH "); - if (index == version->length) - { + if (index == version->length) { ffStrbufClear(version); return ".TH is not found"; } @@ -93,38 +81,29 @@ static const char* getSddmVersion(FFstrbuf* version) return NULL; } #else -static const char* getSddmVersion(FF_MAYBE_UNUSED FFstrbuf* version) -{ +static const char* getSddmVersion(FF_MAYBE_UNUSED FFstrbuf* version) { return "Fastfetch is built without libz support"; } #endif -static const char* getXfwmVersion(FFstrbuf* version) -{ - const char* error = ffProcessAppendStdOut(version, (char* const[]) { - "xfwm4", - "--version", - NULL - }); - if (error) +static const char* getXfwmVersion(FFstrbuf* version) { + const char* error = ffProcessAppendStdOut(version, (char* const[]) {"xfwm4", "--version", NULL}); + if (error) { return error; + } - // This is xfwm4 version 4.18.0 (revision 7e7473c5b) for Xfce 4.18... + // This is xfwm4 version 4.18.0 (revision 7e7473c5b) for Xfce 4.18... ffStrbufSubstrAfterFirstS(version, "version "); ffStrbufSubstrBeforeFirstC(version, ' '); return NULL; } -static const char* getLightdmVersion(FFstrbuf* version) -{ - const char* error = ffProcessAppendStdErr(version, (char* const[]) { - "lightdm", - "--version", - NULL - }); - if (error) +static const char* getLightdmVersion(FFstrbuf* version) { + const char* error = ffProcessAppendStdErr(version, (char* const[]) {"lightdm", "--version", NULL}); + if (error) { return error; + } // lightdm 1.30.0 ffStrbufSubstrAfterFirstC(version, ' '); @@ -133,13 +112,11 @@ static const char* getLightdmVersion(FFstrbuf* version) return NULL; } -const char* ffDetectLM(FFLMResult* result) -{ +const char* ffDetectLM(FFLMResult* result) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY sessionId = ffStrbufCreateS(getenv("XDG_SESSION_ID")); - if (sessionId.length == 0) - { + if (sessionId.length == 0) { // On some incorrectly configured systems, $XDG_SESSION_ID is not set. Try finding it ourself // WARNING: This is private data. Do not parse ffStrbufSetF(&path, FF_SYSTEMD_USERS_PATH "%d", instance.state.platform.uid); @@ -147,9 +124,10 @@ const char* ffDetectLM(FFLMResult* result) // This is actually buggy, and assumes current user is using DE // `sd_pid_get_session` can be a better option, but we need to find a pid to use if (!ffParsePropFileValues(path.chars, 1, (FFpropquery[]) { - {"DISPLAY=", &sessionId}, - })) + {"DISPLAY=", &sessionId}, + })) { return "Failed to get $XDG_SESSION_ID"; + } } ffStrbufSetS(&path, FF_SYSTEMD_SESSIONS_PATH); @@ -157,32 +135,34 @@ const char* ffDetectLM(FFLMResult* result) // WARNING: This is private data. Do not parse if (!ffParsePropFileValues(path.chars, 2, (FFpropquery[]) { - {"SERVICE=", &result->service}, - {"TYPE=", &result->type}, - })) + {"SERVICE=", &result->service}, + {"TYPE=", &result->type}, + })) { return "Failed to parse " FF_SYSTEMD_SESSIONS_PATH "$XDG_SESSION_ID"; + } - if (instance.config.general.detectVersion) - { - if (ffStrbufStartsWithS(&result->service, "gdm")) + if (instance.config.general.detectVersion) { + if (ffStrbufStartsWithS(&result->service, "gdm")) { getGdmVersion(&result->version); - else if (ffStrbufStartsWithS(&result->service, "sddm")) + } else if (ffStrbufStartsWithS(&result->service, "sddm")) { getSddmVersion(&result->version); - else if (ffStrbufStartsWithS(&result->service, "xfwm")) + } else if (ffStrbufStartsWithS(&result->service, "xfwm")) { getXfwmVersion(&result->version); - else if (ffStrbufStartsWithS(&result->service, "lightdm")) + } else if (ffStrbufStartsWithS(&result->service, "lightdm")) { getLightdmVersion(&result->version); - else if (ffStrbufStartsWithS(&result->service, "sshd")) + } else if (ffStrbufStartsWithS(&result->service, "sshd")) { getSshdVersion(&result->version); + } } // Correct char cases - if (ffStrbufIgnCaseEqualS(&result->type, FF_WM_PROTOCOL_WAYLAND)) + if (ffStrbufIgnCaseEqualS(&result->type, FF_WM_PROTOCOL_WAYLAND)) { ffStrbufSetS(&result->type, FF_WM_PROTOCOL_WAYLAND); - else if (ffStrbufIgnCaseEqualS(&result->type, FF_WM_PROTOCOL_X11)) + } else if (ffStrbufIgnCaseEqualS(&result->type, FF_WM_PROTOCOL_X11)) { ffStrbufSetS(&result->type, FF_WM_PROTOCOL_X11); - else if (ffStrbufIgnCaseEqualS(&result->type, FF_WM_PROTOCOL_TTY)) + } else if (ffStrbufIgnCaseEqualS(&result->type, FF_WM_PROTOCOL_TTY)) { ffStrbufSetS(&result->type, FF_WM_PROTOCOL_TTY); + } return NULL; } diff --git a/src/detection/lm/lm_nosupport.c b/src/detection/lm/lm_nosupport.c index cd1f5f7f7..64a71686e 100644 --- a/src/detection/lm/lm_nosupport.c +++ b/src/detection/lm/lm_nosupport.c @@ -1,6 +1,5 @@ #include "lm.h" -const char* ffDetectLM(FF_MAYBE_UNUSED FFLMResult* result) -{ +const char* ffDetectLM(FF_MAYBE_UNUSED FFLMResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/loadavg/loadavg_bsd.c b/src/detection/loadavg/loadavg_bsd.c index ca7b17caf..a3cd4bfdd 100644 --- a/src/detection/loadavg/loadavg_bsd.c +++ b/src/detection/loadavg/loadavg_bsd.c @@ -3,20 +3,21 @@ #include #if __FreeBSD__ || __OpenBSD__ || __NetBSD__ - #include - #include - #if __FreeBSD__ - #include - #endif +# include +# include +# if __FreeBSD__ +# include +# endif #endif -const char* ffDetectLoadavg(double result[3]) -{ +const char* ffDetectLoadavg(double result[3]) { struct loadavg load; size_t size = sizeof(load); - if (sysctl((int []) { CTL_VM, VM_LOADAVG }, 2, &load, &size, NULL, 0) < 0) + if (sysctl((int[]) {CTL_VM, VM_LOADAVG}, 2, &load, &size, NULL, 0) < 0) { return "sysctl({CTL_VM, VM_LOADAVG}) failed"; - for (int i = 0; i < 3; i++) + } + for (int i = 0; i < 3; i++) { result[i] = (double) load.ldavg[i] / (double) load.fscale; + } return NULL; } diff --git a/src/detection/loadavg/loadavg_linux.c b/src/detection/loadavg/loadavg_linux.c index 556a87bbe..a1693123f 100644 --- a/src/detection/loadavg/loadavg_linux.c +++ b/src/detection/loadavg/loadavg_linux.c @@ -3,30 +3,31 @@ #include -const char* ffDetectLoadavg(double result[3]) -{ - #ifndef __ANDROID__ // cat: /proc/loadavg: Permission denied +const char* ffDetectLoadavg(double result[3]) { +#ifndef __ANDROID__ // cat: /proc/loadavg: Permission denied // Don't use syscall for container compatibility. #620 char buf[64]; ssize_t nRead = ffReadFileData("/proc/loadavg", sizeof(buf) - 1, buf); - if (nRead > 0) - { + if (nRead > 0) { buf[nRead] = '\0'; - if (sscanf(buf, "%lf%lf%lf", &result[0], &result[1], &result[2]) == 3) + if (sscanf(buf, "%lf%lf%lf", &result[0], &result[1], &result[2]) == 3) { return NULL; + } } - #endif - #ifndef __GNU__ +#endif +#ifndef __GNU__ // getloadavg requires higher ANDROID_API version struct sysinfo si; - if (sysinfo(&si) < 0) + if (sysinfo(&si) < 0) { return "sysinfo() failed"; + } - for (int i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) { result[i] = (double) si.loads[i] / (1 << SI_LOAD_SHIFT); - #endif + } +#endif return NULL; } diff --git a/src/detection/loadavg/loadavg_nosupport.c b/src/detection/loadavg/loadavg_nosupport.c index 2d51217a5..d4f6134f7 100644 --- a/src/detection/loadavg/loadavg_nosupport.c +++ b/src/detection/loadavg/loadavg_nosupport.c @@ -1,6 +1,5 @@ #include "detection/loadavg/loadavg.h" -const char* ffDetectLoadavg(FF_MAYBE_UNUSED double result[3]) -{ +const char* ffDetectLoadavg(FF_MAYBE_UNUSED double result[3]) { return "Not supported on this platform"; } diff --git a/src/detection/loadavg/loadavg_sunos.c b/src/detection/loadavg/loadavg_sunos.c index 6ae401032..91e3edd73 100644 --- a/src/detection/loadavg/loadavg_sunos.c +++ b/src/detection/loadavg/loadavg_sunos.c @@ -2,7 +2,6 @@ #include -const char* ffDetectLoadavg(double result[3]) -{ +const char* ffDetectLoadavg(double result[3]) { return getloadavg(result, 3) == 3 ? NULL : "getloadavg() failed"; } diff --git a/src/detection/locale/locale_linux.c b/src/detection/locale/locale_linux.c index 1b93dbe88..4c04f26eb 100644 --- a/src/detection/locale/locale_linux.c +++ b/src/detection/locale/locale_linux.c @@ -2,19 +2,21 @@ #include -const char* ffDetectLocale(FFstrbuf* result) -{ +const char* ffDetectLocale(FFstrbuf* result) { ffStrbufAppendS(result, getenv("LC_ALL")); - if(result->length > 0) + if (result->length > 0) { return NULL; + } ffStrbufAppendS(result, getenv("LANG")); - if(result->length > 0) + if (result->length > 0) { return NULL; + } ffStrbufAppendS(result, setlocale(LC_TIME, NULL)); - if(result->length > 0) + if (result->length > 0) { return NULL; + } return "Failed to detect locale"; } diff --git a/src/detection/locale/locale_windows.c b/src/detection/locale/locale_windows.c index e91b70482..b24736506 100644 --- a/src/detection/locale/locale_windows.c +++ b/src/detection/locale/locale_windows.c @@ -3,14 +3,14 @@ #include -const char* ffDetectLocale(FFstrbuf* result) -{ +const char* ffDetectLocale(FFstrbuf* result) { wchar_t name[LOCALE_NAME_MAX_LENGTH]; int size = GetUserDefaultLocaleName(name, LOCALE_NAME_MAX_LENGTH); - if (size <= 1) // including '\0' + if (size <= 1) { // including '\0' return "GetUserDefaultLocaleName() failed"; + } - ffStrbufSetNWS(result, (uint32_t)size - 1, name); + ffStrbufSetNWS(result, (uint32_t) size - 1, name); return NULL; } diff --git a/src/detection/localip/localip.h b/src/detection/localip/localip.h index 98191e690..d845d0d94 100644 --- a/src/detection/localip/localip.h +++ b/src/detection/localip/localip.h @@ -5,19 +5,18 @@ #ifndef IN6_IS_ADDR_GLOBAL /* Global Unicast: 2000::/3 (001...) */ -#define IN6_IS_ADDR_GLOBAL(a) (((a)->s6_addr[0] & 0xE0) == 0x20) +# define IN6_IS_ADDR_GLOBAL(a) (((a)->s6_addr[0] & 0xE0) == 0x20) #endif #ifndef IN6_IS_ADDR_UNIQUE_LOCAL /* Unique Local: fc00::/7 (1111 110...) */ -#define IN6_IS_ADDR_UNIQUE_LOCAL(a) (((a)->s6_addr[0] & 0xFE) == 0xFC) +# define IN6_IS_ADDR_UNIQUE_LOCAL(a) (((a)->s6_addr[0] & 0xFE) == 0xFC) #endif #ifndef IN6_IS_ADDR_LINKLOCAL /* Link-Local: fe80::/10 (1111 1110 10...) */ -#define IN6_IS_ADDR_LINKLOCAL(a) (((a)->s6_addr[0] == 0xFE) && (((a)->s6_addr[1] & 0xC0) == 0x80)) +# define IN6_IS_ADDR_LINKLOCAL(a) (((a)->s6_addr[0] == 0xFE) && (((a)->s6_addr[1] & 0xC0) == 0x80)) #endif -typedef struct FFLocalIpResult -{ +typedef struct FFLocalIpResult { FFstrbuf name; FFstrbuf ipv4; FFstrbuf ipv6; @@ -28,20 +27,17 @@ typedef struct FFLocalIpResult FFLocalIpType defaultRoute; } FFLocalIpResult; -typedef struct FFLocalIpNIFlag -{ +typedef struct FFLocalIpNIFlag { uint32_t flag; - const char *name; + const char* name; } FFLocalIpNIFlag; -static inline void ffLocalIpFillNIFlags(FFstrbuf *buf, uint64_t flag, const FFLocalIpNIFlag names[]) -{ - for (const FFLocalIpNIFlag *nf = names; flag && nf->name; ++nf) - { - if (flag & nf->flag) - { - if (buf->length > 0) +static inline void ffLocalIpFillNIFlags(FFstrbuf* buf, uint64_t flag, const FFLocalIpNIFlag names[]) { + for (const FFLocalIpNIFlag* nf = names; flag && nf->name; ++nf) { + if (flag & nf->flag) { + if (buf->length > 0) { ffStrbufAppendC(buf, ','); + } ffStrbufAppendS(buf, nf->name); flag &= ~nf->flag; } diff --git a/src/detection/localip/localip_linux.c b/src/detection/localip/localip_linux.c index 6989ce9e9..e172b7060 100644 --- a/src/detection/localip/localip_linux.c +++ b/src/detection/localip/localip_linux.c @@ -16,37 +16,37 @@ #include #ifdef __linux__ -#include -#include -#include -#include +# include +# include +# include +# include #endif #if __has_include() - #include +# include #endif #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__) || defined(__NetBSD__) || defined(__HAIKU__) -#include -#include +# include +# include #elif !defined(__GNU__) -#include +# include #endif #if defined(__sun) || defined(__HAIKU__) -#include +# include #endif #if defined(__sun) -#include +# include -static inline void kstatFreeWrap(kstat_ctl_t** pkc) -{ +static inline void kstatFreeWrap(kstat_ctl_t** pkc) { assert(pkc); - if (*pkc) + if (*pkc) { kstat_close(*pkc); + } } #endif -#define FF_LOCALIP_NIFLAG(name) { IFF_##name, #name } +#define FF_LOCALIP_NIFLAG(name) {IFF_##name, #name} static const FFLocalIpNIFlag niFlagOptions[] = { FF_LOCALIP_NIFLAG(UP), @@ -69,7 +69,7 @@ static const FFLocalIpNIFlag niFlagOptions[] = { #ifdef IFF_NOTRAILERS FF_LOCALIP_NIFLAG(NOTRAILERS), #endif -#if defined( __linux__) || defined (__GNU__) +#if defined(__linux__) || defined(__GNU__) FF_LOCALIP_NIFLAG(MASTER), FF_LOCALIP_NIFLAG(SLAVE), FF_LOCALIP_NIFLAG(PORTSEL), @@ -111,107 +111,104 @@ static const FFLocalIpNIFlag niFlagOptions[] = { {}, }; -static FFLocalIpIpv6Type getIpv6Type(struct ifaddrs* ifa) -{ +static FFLocalIpIpv6Type getIpv6Type(struct ifaddrs* ifa) { struct sockaddr_in6* addr = (struct sockaddr_in6*) ifa->ifa_addr; FF_DEBUG("Checking IPv6 type for interface %s", ifa->ifa_name); FFLocalIpIpv6Type result = FF_LOCALIP_IPV6_TYPE_NONE; - if (IN6_IS_ADDR_GLOBAL(&addr->sin6_addr)) - { + if (IN6_IS_ADDR_GLOBAL(&addr->sin6_addr)) { result = FF_LOCALIP_IPV6_TYPE_GUA_BIT; FF_DEBUG("Interface %s has Global Unicast Address", ifa->ifa_name); - } - else if (IN6_IS_ADDR_UNIQUE_LOCAL(&addr->sin6_addr)) - { + } else if (IN6_IS_ADDR_UNIQUE_LOCAL(&addr->sin6_addr)) { result = FF_LOCALIP_IPV6_TYPE_ULA_BIT; FF_DEBUG("Interface %s has Unique Local Address", ifa->ifa_name); - } - else if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) - { + } else if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) { result = FF_LOCALIP_IPV6_TYPE_LLA_BIT; FF_DEBUG("Interface %s has Link-Local Address", ifa->ifa_name); - } - else - { + } else { FF_DEBUG("Interface %s has unknown IPv6 address type", ifa->ifa_name); return FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT; } #ifdef SIOCGIFAFLAG_IN6 static int sockfd = 0; - if (sockfd == 0) - { + if (sockfd == 0) { sockfd = socket(AF_INET6, SOCK_DGRAM - #ifdef SOCK_CLOEXEC - | SOCK_CLOEXEC - #endif - , 0); - #ifndef SOCK_CLOEXEC - if (sockfd > 0) fcntl(sockfd, F_SETFD, FD_CLOEXEC); - #endif +# ifdef SOCK_CLOEXEC + | SOCK_CLOEXEC +# endif + , + 0); +# ifndef SOCK_CLOEXEC + if (sockfd > 0) { + fcntl(sockfd, F_SETFD, FD_CLOEXEC); + } +# endif + } + if (sockfd < 0) { + return result; } - 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) + if (ioctl(sockfd, SIOCGIFAFLAG_IN6, &ifr6) != 0) { return result; + } - #ifdef IN6_IFF_PREFER_SOURCE - if (ifr6.ifr_ifru.ifru_flags6 & IN6_IFF_PREFER_SOURCE) - result |= FF_LOCALIP_IPV6_TYPE_PREFERRED_BIT; - #endif +# ifdef IN6_IFF_PREFER_SOURCE + if (ifr6.ifr_ifru.ifru_flags6 & IN6_IFF_PREFER_SOURCE) { + result |= FF_LOCALIP_IPV6_TYPE_PREFERRED_BIT; + } +# endif 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_LOCALIP_IPV6_TYPE_SECONDARY_BIT; +# ifdef IN6_IFF_OPTIMISTIC + | IN6_IFF_OPTIMISTIC +# endif + )) + result |= FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT; return result; #elif __linux__ static FFlist addresses = {}; - if (addresses.elementSize == 0) - { + if (addresses.elementSize == 0) { ffListInit(&addresses, sizeof(struct in6_addr)); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (!ffReadFileBuffer("/proc/net/if_inet6", &buffer)) + if (!ffReadFileBuffer("/proc/net/if_inet6", &buffer)) { return result; + } char* line = NULL; size_t len = 0; - while (ffStrbufGetline(&line, &len, &buffer)) - { + while (ffStrbufGetline(&line, &len, &buffer)) { struct in6_addr* entry = (struct in6_addr*) ffListAdd(&addresses); uint8_t flags; - if (sscanf(line, "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 " %*s %*s %*s %" SCNx8 " %*s", - &entry->s6_addr[0], &entry->s6_addr[1], &entry->s6_addr[2], &entry->s6_addr[3], - &entry->s6_addr[4], &entry->s6_addr[5], &entry->s6_addr[6], &entry->s6_addr[7], - &entry->s6_addr[8], &entry->s6_addr[9], &entry->s6_addr[10], &entry->s6_addr[11], - &entry->s6_addr[12], &entry->s6_addr[13], &entry->s6_addr[14], &entry->s6_addr[15], - &flags) != 17 || + if (sscanf(line, "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 " %*s %*s %*s %" SCNx8 " %*s", &entry->s6_addr[0], &entry->s6_addr[1], &entry->s6_addr[2], &entry->s6_addr[3], &entry->s6_addr[4], &entry->s6_addr[5], &entry->s6_addr[6], &entry->s6_addr[7], &entry->s6_addr[8], &entry->s6_addr[9], &entry->s6_addr[10], &entry->s6_addr[11], &entry->s6_addr[12], &entry->s6_addr[13], &entry->s6_addr[14], &entry->s6_addr[15], &flags) != 17 || (!IN6_IS_ADDR_GLOBAL(entry) && !IN6_IS_ADDR_UNIQUE_LOCAL(entry)) || - (flags & (IFA_F_DEPRECATED | IFA_F_TEMPORARY | IFA_F_TENTATIVE | IFA_F_DADFAILED | IFA_F_OPTIMISTIC)) - ) + (flags & (IFA_F_DEPRECATED | IFA_F_TEMPORARY | IFA_F_TENTATIVE | IFA_F_DADFAILED | IFA_F_OPTIMISTIC))) { --addresses.length; + } } } - if (addresses.capacity == 0) return result; + 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) + FF_LIST_FOR_EACH (struct in6_addr, entry, addresses) { + if (memcmp(&addr->sin6_addr, entry, sizeof(struct in6_addr)) == 0) { return result; + } } result |= FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT; return result; #elif __sun - if (ifa->ifa_flags & IFF_PREFERRED) + if (ifa->ifa_flags & IFF_PREFERRED) { result |= FF_LOCALIP_IPV6_TYPE_PREFERRED_BIT; - if (ifa->ifa_flags & (IFF_DEPRECATED | IFF_TEMPORARY | IFF_DUPLICATE)) + } + if (ifa->ifa_flags & (IFF_DEPRECATED | IFF_TEMPORARY | IFF_DUPLICATE)) { result |= FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT; + } return result; #else return result; @@ -224,8 +221,7 @@ typedef struct { FFlist /**/ ipv6; } FFAdapter; -static void appendIpv4(const FFLocalIpOptions* options, FFstrbuf* buffer, const struct ifaddrs* ifa) -{ +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]; @@ -233,23 +229,22 @@ static void appendIpv4(const FFLocalIpOptions* options, FFstrbuf* buffer, const FF_DEBUG("Adding IPv4 address %s for interface %s", addressBuffer, ifa->ifa_name); - if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT) - { + 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) - { + if (cidr != 0) { size_t len = strlen(addressBuffer); snprintf(addressBuffer + len, 16, "/%d", cidr); } } - if (buffer->length) ffStrbufAppendC(buffer, ','); + if (buffer->length) { + ffStrbufAppendC(buffer, ','); + } ffStrbufAppendS(buffer, addressBuffer); } -static void appendIpv6(const FFLocalIpOptions* options, FFstrbuf* buffer, const struct ifaddrs* ifa) -{ +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]; @@ -257,32 +252,32 @@ static void appendIpv6(const FFLocalIpOptions* options, FFstrbuf* buffer, const FF_DEBUG("Adding IPv6 address %s for interface %s", addressBuffer, ifa->ifa_name); - if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT) - { + 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) + 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) - { + } + if (cidr != 0) { size_t len = strlen(addressBuffer); snprintf(addressBuffer + len, 16, "/%d", cidr); } } - if (buffer->length) ffStrbufAppendC(buffer, ','); + if (buffer->length) { + ffStrbufAppendC(buffer, ','); + } ffStrbufAppendS(buffer, addressBuffer); } -const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) -{ +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); + options->showType, + options->namePrefix.chars); struct ifaddrs* ifAddrStruct = NULL; - if(getifaddrs(&ifAddrStruct) < 0) - { + if (getifaddrs(&ifAddrStruct) < 0) { FF_DEBUG("getifaddrs() failed"); return "getifaddrs(&ifAddrStruct) failed"; } @@ -291,68 +286,61 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) FF_LIST_AUTO_DESTROY adapters = ffListCreate(sizeof(FFAdapter)); - for (struct ifaddrs* ifa = ifAddrStruct; ifa; ifa = ifa->ifa_next) - { - if (!ifa->ifa_addr) - { + 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 - if (!(ifa->ifa_flags & 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)) - { + 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) - { + if (options->namePrefix.length && strncmp(ifa->ifa_name, options->namePrefix.chars, options->namePrefix.length) != 0) { FF_DEBUG("Skipping interface %s (doesn't match prefix '%s')", - ifa->ifa_name, options->namePrefix.chars); + ifa->ifa_name, + options->namePrefix.chars); continue; } if (!(options->showType & FF_LOCALIP_TYPE_MAC_BIT) && - ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6) - { + 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); + ifa->ifa_name, + ifa->ifa_addr->sa_family); continue; } - if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) - { + 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))) - { + !((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; + continue; } } FF_DEBUG("Processing interface %s (family=%d, flags=0x%lx)", - ifa->ifa_name, ifa->ifa_addr->sa_family, (unsigned long) ifa->ifa_flags); + ifa->ifa_name, + ifa->ifa_addr->sa_family, + (unsigned long) ifa->ifa_flags); FFAdapter* adapter = NULL; - FF_LIST_FOR_EACH(FFAdapter, x, adapters) - { - if (ffStrEquals(x->mac->ifa_name, ifa->ifa_name)) - { + FF_LIST_FOR_EACH (FFAdapter, x, adapters) { + if (ffStrEquals(x->mac->ifa_name, ifa->ifa_name)) { adapter = x; break; } } - if (!adapter) - { + if (!adapter) { adapter = ffListAdd(&adapters); *adapter = (FFAdapter) { .mac = ifa, @@ -362,46 +350,43 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) FF_DEBUG("Created new adapter entry for interface %s", ifa->ifa_name); } - switch (ifa->ifa_addr->sa_family) - { + switch (ifa->ifa_addr->sa_family) { case AF_INET: - if (options->showType & FF_LOCALIP_TYPE_IPV4_BIT) - { + 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) - { + 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__ +#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__ +#elif !__sun && !__GNU__ case AF_PACKET: adapter->mac = ifa; FF_DEBUG("Updated MAC entry for interface %s", ifa->ifa_name); break; - #endif +#endif } } FF_DEBUG("Found %u network adapters", adapters.length); - FF_LIST_FOR_EACH(FFAdapter, adapter, adapters) - { + 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); + 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) ) - { + !(options->showType & FF_LOCALIP_TYPE_MAC_BIT)) { FF_DEBUG("Skipping interface %s (no IP addresses)", adapter->mac->ifa_name); continue; } @@ -416,632 +401,594 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) item->mtu = -1; item->speed = -1; - if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT) - { + 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)) - { + if ((options->showType & FF_LOCALIP_TYPE_IPV4_BIT)) { const FFNetifDefaultRouteResult* defaultRouteV4 = ffNetifGetDefaultRouteV4(); bool isDefaultRouteIf = ffStrEquals(defaultRouteV4->ifName, adapter->mac->ifa_name); - if (isDefaultRouteIf) - { + if (isDefaultRouteIf) { item->defaultRoute |= FF_LOCALIP_TYPE_IPV4_BIT; FF_DEBUG("Interface %s is IPv4 default route", adapter->mac->ifa_name); } - if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) - { - if (!isDefaultRouteIf) - { + if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) { + if (!isDefaultRouteIf) { FF_DEBUG("Skipping IPv4 for interface %s (not default route)", adapter->mac->ifa_name); goto v6; } } - if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) - { + if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) { struct ifaddrs* ifa = NULL; - if (isDefaultRouteIf && defaultRouteV4->preferredSourceAddrV4 != 0) - { - FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv4) - { + if (isDefaultRouteIf && defaultRouteV4->preferredSourceAddrV4 != 0) { + 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) - { + 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) + if (ifa) { appendIpv4(options, &item->ipv4, ifa); - else if (adapter->ipv4.length > 0) - { + } else if (adapter->ipv4.length > 0) { appendIpv4(options, &item->ipv4, *FF_LIST_FIRST(struct ifaddrs*, adapter->ipv4)); FF_DEBUG("Using first IPv4 address for interface %s", adapter->mac->ifa_name); } - } - else - { + } else { FF_DEBUG("Adding all IPv4 addresses for interface %s", adapter->mac->ifa_name); - FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv4) + FF_LIST_FOR_EACH (struct ifaddrs*, pifa, adapter->ipv4) { appendIpv4(options, &item->ipv4, *pifa); + } } } v6: - if ((options->showType & FF_LOCALIP_TYPE_IPV6_BIT)) - { + if ((options->showType & FF_LOCALIP_TYPE_IPV6_BIT)) { const FFNetifDefaultRouteResult* defaultRouteV6 = ffNetifGetDefaultRouteV6(); bool isDefaultRouteIf = ffStrEquals(defaultRouteV6->ifName, adapter->mac->ifa_name); - if (isDefaultRouteIf) - { + 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) - { + if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) { + if (!isDefaultRouteIf) { FF_DEBUG("Skipping IPv6 for interface %s (not default route)", adapter->mac->ifa_name); goto mac; } } - if (options->ipv6Type == FF_LOCALIP_IPV6_TYPE_AUTO) - { - if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) - { + if (options->ipv6Type == FF_LOCALIP_IPV6_TYPE_AUTO) { + if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) { struct ifaddrs* selected = NULL; struct ifaddrs* secondary = NULL; - FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv6) - { + FF_LIST_FOR_EACH (struct ifaddrs*, pifa, adapter->ipv6) { FFLocalIpIpv6Type type = getIpv6Type(*pifa); - if (type & FF_LOCALIP_IPV6_TYPE_PREFERRED_BIT) - { + if (type & FF_LOCALIP_IPV6_TYPE_PREFERRED_BIT) { selected = *pifa; FF_DEBUG("Found preferred IPv6 address for interface %s", adapter->mac->ifa_name); break; - } - else if ((type & FF_LOCALIP_IPV6_TYPE_GUA_BIT) && !(type & FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT) && !selected) - { + } else if ((type & FF_LOCALIP_IPV6_TYPE_GUA_BIT) && !(type & FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT) && !selected) { selected = *pifa; FF_DEBUG("Found GUA IPv6 address for interface %s", adapter->mac->ifa_name); - } - else if ((type & FF_LOCALIP_IPV6_TYPE_ULA_BIT) && !(type & FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT) && !secondary) - { + } else if ((type & FF_LOCALIP_IPV6_TYPE_ULA_BIT) && !(type & FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT) && !secondary) { secondary = *pifa; FF_DEBUG("Found ULA IPv6 address for interface %s", adapter->mac->ifa_name); } } - if (!selected) selected = secondary; + if (!selected) { + selected = secondary; + } - if (selected) + if (selected) { appendIpv6(options, &item->ipv6, selected); - else if (adapter->ipv6.length > 0) - { + } else if (adapter->ipv6.length > 0) { appendIpv6(options, &item->ipv6, *FF_LIST_FIRST(struct ifaddrs*, adapter->ipv6)); FF_DEBUG("Using first IPv6 address for interface %s", adapter->mac->ifa_name); } - } - else - { + } else { FF_DEBUG("Adding all IPv6 addresses for interface %s", adapter->mac->ifa_name); - FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv6) + FF_LIST_FOR_EACH (struct ifaddrs*, pifa, adapter->ipv6) { appendIpv6(options, &item->ipv6, *pifa); + } } - } - else - { - FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv6) - { + } else { + FF_LIST_FOR_EACH (struct ifaddrs*, pifa, adapter->ipv6) { FFLocalIpIpv6Type type = getIpv6Type(*pifa); - if (type & options->ipv6Type) - { - if ((options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT) || !(type & FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT)) - { + if (type & options->ipv6Type) { + if ((options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT) || !(type & FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT)) { appendIpv6(options, &item->ipv6, *pifa); - if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) + if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) { break; + } } } } } } 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]); +#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 - { + } else { FF_DEBUG("No MAC address available for interface %s", adapter->mac->ifa_name); } } - #else +#else (void) adapter; - #endif +#endif } - FF_LIST_FOR_EACH(FFAdapter, adapter, adapters) - { + FF_LIST_FOR_EACH (FFAdapter, adapter, adapters) { ffListDestroy(&adapter->ipv4); ffListDestroy(&adapter->ipv6); } - if (ifAddrStruct) - { + 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 +#ifdef __sun || (options->showType & FF_LOCALIP_TYPE_MAC_BIT) - #endif - ) - { +#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) - { + if (sockfd > 0) { + FF_LIST_FOR_EACH (FFLocalIpResult, iface, *results) { 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) - { + 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 - { + } else { FF_DEBUG("Failed to get MTU for interface %s", iface->name.chars); } } - if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) - { - #ifdef __linux__ - struct ethtool_cmd edata = { .cmd = ETHTOOL_GSET }; + if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) { +#ifdef __linux__ + struct ethtool_cmd edata = {.cmd = ETHTOOL_GSET}; ifr.ifr_data = (void*) &edata; - if (ioctl(sockfd, SIOCETHTOOL, &ifr) == 0) - { + if (ioctl(sockfd, SIOCETHTOOL, &ifr) == 0) { iface->speed = (edata.speed_hi << 16) | edata.speed; FF_DEBUG("Interface %s speed: %d Mbps", iface->name.chars, iface->speed); - } - else - { + } 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__ +#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)) - { + if (ioctl(sockfd, SIOCGIFMEDIA, &ifmr) == 0 && (IFM_TYPE(ifmr.ifm_active) & IFM_ETHER)) { FF_DEBUG("Interface %s media type: 0x%x", iface->name.chars, (unsigned) IFM_SUBTYPE(ifmr.ifm_active)); - switch (IFM_SUBTYPE(ifmr.ifm_active)) - { - #ifdef IFM_HPNA_1 - case IFM_HPNA_1: - #endif - iface->speed = 1; break; - #ifdef IFM_1000_CX - case IFM_1000_CX: - #endif - #ifdef IFM_1000_CX_SGMII - case IFM_1000_CX_SGMII: - #endif - #ifdef IFM_1000_KX - case IFM_1000_KX: - #endif - #ifdef IFM_1000_LX - case IFM_1000_LX: - #endif - #ifdef IFM_1000_SGMII - case IFM_1000_SGMII: - #endif - #ifdef IFM_1000_SX - case IFM_1000_SX: - #endif - #ifdef IFM_1000_T - case IFM_1000_T: - #endif - iface->speed = 1000; break; - #ifdef IFM_100G_AUI2 - case IFM_100G_AUI2: - #endif - #ifdef IFM_100G_AUI2_AC - case IFM_100G_AUI2_AC: - #endif - #ifdef IFM_100G_AUI4 - case IFM_100G_AUI4: - #endif - #ifdef IFM_100G_AUI4_AC - case IFM_100G_AUI4_AC: - #endif - #ifdef IFM_100G_CAUI2 - case IFM_100G_CAUI2: - #endif - #ifdef IFM_100G_CAUI2_AC - case IFM_100G_CAUI2_AC: - #endif - #ifdef IFM_100G_CAUI4 - case IFM_100G_CAUI4: - #endif - #ifdef IFM_100G_CAUI4_AC - case IFM_100G_CAUI4_AC: - #endif - #ifdef IFM_100G_CP2 - case IFM_100G_CP2: - #endif - #ifdef IFM_100G_CR4 - case IFM_100G_CR4: - #endif - #ifdef IFM_100G_CR_PAM4 - case IFM_100G_CR_PAM4: - #endif - #ifdef IFM_100G_DR - case IFM_100G_DR: - #endif - #ifdef IFM_100G_KR2_PAM4 - case IFM_100G_KR2_PAM4: - #endif - #ifdef IFM_100G_KR4 - case IFM_100G_KR4: - #endif - #ifdef IFM_100G_KR_PAM4 - case IFM_100G_KR_PAM4: - #endif - #ifdef IFM_100G_LR4 - case IFM_100G_LR4: - #endif - #ifdef IFM_100G_SR2 - case IFM_100G_SR2: - #endif - #ifdef IFM_100G_SR4 - case IFM_100G_SR4: - #endif - iface->speed = 100000; break; - #ifdef IFM_100_FX - case IFM_100_FX: - #endif - #ifdef IFM_100_SGMII - case IFM_100_SGMII: - #endif - #ifdef IFM_100_T - case IFM_100_T: - #endif - #ifdef IFM_100_T2 - case IFM_100_T2: - #endif - #ifdef IFM_100_T4 - case IFM_100_T4: - #endif - #ifdef IFM_100_TX - case IFM_100_TX: - #endif - #ifdef IFM_100_VG - case IFM_100_VG: - #endif - iface->speed = 100; break; - #ifdef IFM_10G_AOC - case IFM_10G_AOC: - #endif - #ifdef IFM_10G_CR1 - case IFM_10G_CR1: - #endif - #ifdef IFM_10G_CX4 - case IFM_10G_CX4: - #endif - #ifdef IFM_10G_ER - case IFM_10G_ER: - #endif - #ifdef IFM_10G_KR - case IFM_10G_KR: - #endif - #ifdef IFM_10G_KX4 - case IFM_10G_KX4: - #endif - #ifdef IFM_10G_LR - case IFM_10G_LR: - #endif - #ifdef IFM_10G_LRM - case IFM_10G_LRM: - #endif - #ifdef IFM_10G_SFI - case IFM_10G_SFI: - #endif - #ifdef IFM_10G_SR - case IFM_10G_SR: - #endif - #ifdef IFM_10G_T - case IFM_10G_T: - #endif - #ifdef IFM_10G_TWINAX - case IFM_10G_TWINAX: - #endif - #ifdef IFM_10G_TWINAX_LONG - case IFM_10G_TWINAX_LONG: - #endif - iface->speed = 10000; break; - #ifdef IFM_10_2 - case IFM_10_2: - #endif - #ifdef IFM_10_5 - case IFM_10_5: - #endif - #ifdef IFM_10_FL - case IFM_10_FL: - #endif - #ifdef IFM_10_STP - case IFM_10_STP: - #endif - #ifdef IFM_10_T - case IFM_10_T: - #endif - iface->speed = 10; break; - #ifdef IFM_200G_AUI4 - case IFM_200G_AUI4: - #endif - #ifdef IFM_200G_AUI4_AC - case IFM_200G_AUI4_AC: - #endif - #ifdef IFM_200G_AUI8 - case IFM_200G_AUI8: - #endif - #ifdef IFM_200G_AUI8_AC - case IFM_200G_AUI8_AC: - #endif - #ifdef IFM_200G_CR4_PAM4 - case IFM_200G_CR4_PAM4: - #endif - #ifdef IFM_200G_DR4 - case IFM_200G_DR4: - #endif - #ifdef IFM_200G_FR4 - case IFM_200G_FR4: - #endif - #ifdef IFM_200G_KR4_PAM4 - case IFM_200G_KR4_PAM4: - #endif - #ifdef IFM_200G_LR4 - case IFM_200G_LR4: - #endif - #ifdef IFM_200G_SR4 - case IFM_200G_SR4: - #endif - iface->speed = 200000; break; - #ifdef IFM_20G_KR2 - case IFM_20G_KR2: - #endif - iface->speed = 20000; break; - #ifdef IFM_2500_KX - case IFM_2500_KX: - #endif - #ifdef IFM_2500_SX - case IFM_2500_SX: - #endif - #ifdef IFM_2500_T - case IFM_2500_T: - #endif - #ifdef IFM_2500_X - case IFM_2500_X: - #endif - iface->speed = 2500; break; - #ifdef IFM_25G_ACC - case IFM_25G_ACC: - #endif - #ifdef IFM_25G_AOC - case IFM_25G_AOC: - #endif - #ifdef IFM_25G_AUI - case IFM_25G_AUI: - #endif - #ifdef IFM_25G_CR - case IFM_25G_CR: - #endif - #ifdef IFM_25G_CR1 - case IFM_25G_CR1: - #endif - #ifdef IFM_25G_CR_S - case IFM_25G_CR_S: - #endif - #ifdef IFM_25G_KR - case IFM_25G_KR: - #endif - #ifdef IFM_25G_KR1 - case IFM_25G_KR1: - #endif - #ifdef IFM_25G_KR_S - case IFM_25G_KR_S: - #endif - #ifdef IFM_25G_LR - case IFM_25G_LR: - #endif - #ifdef IFM_25G_PCIE - case IFM_25G_PCIE: - #endif - #ifdef IFM_25G_SR - case IFM_25G_SR: - #endif - #ifdef IFM_25G_T - case IFM_25G_T: - #endif - iface->speed = 25000; break; - #ifdef IFM_400G_AUI8 - case IFM_400G_AUI8: - #endif - #ifdef IFM_400G_AUI8_AC - case IFM_400G_AUI8_AC: - #endif - #ifdef IFM_400G_DR4 - case IFM_400G_DR4: - #endif - #ifdef IFM_400G_FR8 - case IFM_400G_FR8: - #endif - #ifdef IFM_400G_LR8 - case IFM_400G_LR8: - #endif - iface->speed = 400000; break; - #ifdef IFM_40G_CR4 - case IFM_40G_CR4: - #endif - #ifdef IFM_40G_ER4 - case IFM_40G_ER4: - #endif - #ifdef IFM_40G_KR4 - case IFM_40G_KR4: - #endif - #ifdef IFM_40G_LR4 - case IFM_40G_LR4: - #endif - #ifdef IFM_40G_SR4 - case IFM_40G_SR4: - #endif - #ifdef IFM_40G_XLAUI - case IFM_40G_XLAUI: - #endif - #ifdef IFM_40G_XLAUI_AC - case IFM_40G_XLAUI_AC: - #endif - #ifdef IFM_40G_XLPPI - case IFM_40G_XLPPI: - #endif - #ifdef IFM_40G_LM4 - case IFM_40G_LM4: - #endif - iface->speed = 40000; break; - #ifdef IFM_5000_KR - case IFM_5000_KR: - #endif - #ifdef IFM_5000_KR1 - case IFM_5000_KR1: - #endif - #ifdef IFM_5000_KR_S - case IFM_5000_KR_S: - #endif - #ifdef IFM_5000_T - case IFM_5000_T: - #endif - iface->speed = 5000; break; - #ifdef IFM_50G_AUI1 - case IFM_50G_AUI1: - #endif - #ifdef IFM_50G_AUI1_AC - case IFM_50G_AUI1_AC: - #endif - #ifdef IFM_50G_AUI2 - case IFM_50G_AUI2: - #endif - #ifdef IFM_50G_AUI2_AC - case IFM_50G_AUI2_AC: - #endif - #ifdef IFM_50G_CP - case IFM_50G_CP: - #endif - #ifdef IFM_50G_CR2 - case IFM_50G_CR2: - #endif - #ifdef IFM_50G_FR - case IFM_50G_FR: - #endif - #ifdef IFM_50G_KR2 - case IFM_50G_KR2: - #endif - #ifdef IFM_50G_KR_PAM4 - case IFM_50G_KR_PAM4: - #endif - #ifdef IFM_50G_LAUI2 - case IFM_50G_LAUI2: - #endif - #ifdef IFM_50G_LAUI2_AC - case IFM_50G_LAUI2_AC: - #endif - #ifdef IFM_50G_LR - case IFM_50G_LR: - #endif - #ifdef IFM_50G_LR2 - case IFM_50G_LR2: - #endif - #ifdef IFM_50G_PCIE - case IFM_50G_PCIE: - #endif - #ifdef IFM_50G_SR - case IFM_50G_SR: - #endif - #ifdef IFM_50G_SR2 - case IFM_50G_SR2: - #endif - #ifdef IFM_50G_KR4 - case IFM_50G_KR4: - #endif - iface->speed = 50000; break; - #ifdef IFM_56G_R4 - case IFM_56G_R4: - #endif - iface->speed = 56000; break; - default: - iface->speed = -1; - FF_DEBUG("Unknown media subtype for interface %s", iface->name.chars); - break; + switch (IFM_SUBTYPE(ifmr.ifm_active)) { +# ifdef IFM_HPNA_1 + case IFM_HPNA_1: +# endif + iface->speed = 1; + break; +# ifdef IFM_1000_CX + case IFM_1000_CX: +# endif +# ifdef IFM_1000_CX_SGMII + case IFM_1000_CX_SGMII: +# endif +# ifdef IFM_1000_KX + case IFM_1000_KX: +# endif +# ifdef IFM_1000_LX + case IFM_1000_LX: +# endif +# ifdef IFM_1000_SGMII + case IFM_1000_SGMII: +# endif +# ifdef IFM_1000_SX + case IFM_1000_SX: +# endif +# ifdef IFM_1000_T + case IFM_1000_T: +# endif + iface->speed = 1000; + break; +# ifdef IFM_100G_AUI2 + case IFM_100G_AUI2: +# endif +# ifdef IFM_100G_AUI2_AC + case IFM_100G_AUI2_AC: +# endif +# ifdef IFM_100G_AUI4 + case IFM_100G_AUI4: +# endif +# ifdef IFM_100G_AUI4_AC + case IFM_100G_AUI4_AC: +# endif +# ifdef IFM_100G_CAUI2 + case IFM_100G_CAUI2: +# endif +# ifdef IFM_100G_CAUI2_AC + case IFM_100G_CAUI2_AC: +# endif +# ifdef IFM_100G_CAUI4 + case IFM_100G_CAUI4: +# endif +# ifdef IFM_100G_CAUI4_AC + case IFM_100G_CAUI4_AC: +# endif +# ifdef IFM_100G_CP2 + case IFM_100G_CP2: +# endif +# ifdef IFM_100G_CR4 + case IFM_100G_CR4: +# endif +# ifdef IFM_100G_CR_PAM4 + case IFM_100G_CR_PAM4: +# endif +# ifdef IFM_100G_DR + case IFM_100G_DR: +# endif +# ifdef IFM_100G_KR2_PAM4 + case IFM_100G_KR2_PAM4: +# endif +# ifdef IFM_100G_KR4 + case IFM_100G_KR4: +# endif +# ifdef IFM_100G_KR_PAM4 + case IFM_100G_KR_PAM4: +# endif +# ifdef IFM_100G_LR4 + case IFM_100G_LR4: +# endif +# ifdef IFM_100G_SR2 + case IFM_100G_SR2: +# endif +# ifdef IFM_100G_SR4 + case IFM_100G_SR4: +# endif + iface->speed = 100000; + break; +# ifdef IFM_100_FX + case IFM_100_FX: +# endif +# ifdef IFM_100_SGMII + case IFM_100_SGMII: +# endif +# ifdef IFM_100_T + case IFM_100_T: +# endif +# ifdef IFM_100_T2 + case IFM_100_T2: +# endif +# ifdef IFM_100_T4 + case IFM_100_T4: +# endif +# ifdef IFM_100_TX + case IFM_100_TX: +# endif +# ifdef IFM_100_VG + case IFM_100_VG: +# endif + iface->speed = 100; + break; +# ifdef IFM_10G_AOC + case IFM_10G_AOC: +# endif +# ifdef IFM_10G_CR1 + case IFM_10G_CR1: +# endif +# ifdef IFM_10G_CX4 + case IFM_10G_CX4: +# endif +# ifdef IFM_10G_ER + case IFM_10G_ER: +# endif +# ifdef IFM_10G_KR + case IFM_10G_KR: +# endif +# ifdef IFM_10G_KX4 + case IFM_10G_KX4: +# endif +# ifdef IFM_10G_LR + case IFM_10G_LR: +# endif +# ifdef IFM_10G_LRM + case IFM_10G_LRM: +# endif +# ifdef IFM_10G_SFI + case IFM_10G_SFI: +# endif +# ifdef IFM_10G_SR + case IFM_10G_SR: +# endif +# ifdef IFM_10G_T + case IFM_10G_T: +# endif +# ifdef IFM_10G_TWINAX + case IFM_10G_TWINAX: +# endif +# ifdef IFM_10G_TWINAX_LONG + case IFM_10G_TWINAX_LONG: +# endif + iface->speed = 10000; + break; +# ifdef IFM_10_2 + case IFM_10_2: +# endif +# ifdef IFM_10_5 + case IFM_10_5: +# endif +# ifdef IFM_10_FL + case IFM_10_FL: +# endif +# ifdef IFM_10_STP + case IFM_10_STP: +# endif +# ifdef IFM_10_T + case IFM_10_T: +# endif + iface->speed = 10; + break; +# ifdef IFM_200G_AUI4 + case IFM_200G_AUI4: +# endif +# ifdef IFM_200G_AUI4_AC + case IFM_200G_AUI4_AC: +# endif +# ifdef IFM_200G_AUI8 + case IFM_200G_AUI8: +# endif +# ifdef IFM_200G_AUI8_AC + case IFM_200G_AUI8_AC: +# endif +# ifdef IFM_200G_CR4_PAM4 + case IFM_200G_CR4_PAM4: +# endif +# ifdef IFM_200G_DR4 + case IFM_200G_DR4: +# endif +# ifdef IFM_200G_FR4 + case IFM_200G_FR4: +# endif +# ifdef IFM_200G_KR4_PAM4 + case IFM_200G_KR4_PAM4: +# endif +# ifdef IFM_200G_LR4 + case IFM_200G_LR4: +# endif +# ifdef IFM_200G_SR4 + case IFM_200G_SR4: +# endif + iface->speed = 200000; + break; +# ifdef IFM_20G_KR2 + case IFM_20G_KR2: +# endif + iface->speed = 20000; + break; +# ifdef IFM_2500_KX + case IFM_2500_KX: +# endif +# ifdef IFM_2500_SX + case IFM_2500_SX: +# endif +# ifdef IFM_2500_T + case IFM_2500_T: +# endif +# ifdef IFM_2500_X + case IFM_2500_X: +# endif + iface->speed = 2500; + break; +# ifdef IFM_25G_ACC + case IFM_25G_ACC: +# endif +# ifdef IFM_25G_AOC + case IFM_25G_AOC: +# endif +# ifdef IFM_25G_AUI + case IFM_25G_AUI: +# endif +# ifdef IFM_25G_CR + case IFM_25G_CR: +# endif +# ifdef IFM_25G_CR1 + case IFM_25G_CR1: +# endif +# ifdef IFM_25G_CR_S + case IFM_25G_CR_S: +# endif +# ifdef IFM_25G_KR + case IFM_25G_KR: +# endif +# ifdef IFM_25G_KR1 + case IFM_25G_KR1: +# endif +# ifdef IFM_25G_KR_S + case IFM_25G_KR_S: +# endif +# ifdef IFM_25G_LR + case IFM_25G_LR: +# endif +# ifdef IFM_25G_PCIE + case IFM_25G_PCIE: +# endif +# ifdef IFM_25G_SR + case IFM_25G_SR: +# endif +# ifdef IFM_25G_T + case IFM_25G_T: +# endif + iface->speed = 25000; + break; +# ifdef IFM_400G_AUI8 + case IFM_400G_AUI8: +# endif +# ifdef IFM_400G_AUI8_AC + case IFM_400G_AUI8_AC: +# endif +# ifdef IFM_400G_DR4 + case IFM_400G_DR4: +# endif +# ifdef IFM_400G_FR8 + case IFM_400G_FR8: +# endif +# ifdef IFM_400G_LR8 + case IFM_400G_LR8: +# endif + iface->speed = 400000; + break; +# ifdef IFM_40G_CR4 + case IFM_40G_CR4: +# endif +# ifdef IFM_40G_ER4 + case IFM_40G_ER4: +# endif +# ifdef IFM_40G_KR4 + case IFM_40G_KR4: +# endif +# ifdef IFM_40G_LR4 + case IFM_40G_LR4: +# endif +# ifdef IFM_40G_SR4 + case IFM_40G_SR4: +# endif +# ifdef IFM_40G_XLAUI + case IFM_40G_XLAUI: +# endif +# ifdef IFM_40G_XLAUI_AC + case IFM_40G_XLAUI_AC: +# endif +# ifdef IFM_40G_XLPPI + case IFM_40G_XLPPI: +# endif +# ifdef IFM_40G_LM4 + case IFM_40G_LM4: +# endif + iface->speed = 40000; + break; +# ifdef IFM_5000_KR + case IFM_5000_KR: +# endif +# ifdef IFM_5000_KR1 + case IFM_5000_KR1: +# endif +# ifdef IFM_5000_KR_S + case IFM_5000_KR_S: +# endif +# ifdef IFM_5000_T + case IFM_5000_T: +# endif + iface->speed = 5000; + break; +# ifdef IFM_50G_AUI1 + case IFM_50G_AUI1: +# endif +# ifdef IFM_50G_AUI1_AC + case IFM_50G_AUI1_AC: +# endif +# ifdef IFM_50G_AUI2 + case IFM_50G_AUI2: +# endif +# ifdef IFM_50G_AUI2_AC + case IFM_50G_AUI2_AC: +# endif +# ifdef IFM_50G_CP + case IFM_50G_CP: +# endif +# ifdef IFM_50G_CR2 + case IFM_50G_CR2: +# endif +# ifdef IFM_50G_FR + case IFM_50G_FR: +# endif +# ifdef IFM_50G_KR2 + case IFM_50G_KR2: +# endif +# ifdef IFM_50G_KR_PAM4 + case IFM_50G_KR_PAM4: +# endif +# ifdef IFM_50G_LAUI2 + case IFM_50G_LAUI2: +# endif +# ifdef IFM_50G_LAUI2_AC + case IFM_50G_LAUI2_AC: +# endif +# ifdef IFM_50G_LR + case IFM_50G_LR: +# endif +# ifdef IFM_50G_LR2 + case IFM_50G_LR2: +# endif +# ifdef IFM_50G_PCIE + case IFM_50G_PCIE: +# endif +# ifdef IFM_50G_SR + case IFM_50G_SR: +# endif +# ifdef IFM_50G_SR2 + case IFM_50G_SR2: +# endif +# ifdef IFM_50G_KR4 + case IFM_50G_KR4: +# endif + iface->speed = 50000; + break; +# ifdef IFM_56G_R4 + case IFM_56G_R4: +# endif + iface->speed = 56000; + break; + default: + iface->speed = -1; + FF_DEBUG("Unknown media subtype for interface %s", iface->name.chars); + break; } - if (iface->speed > 0) + if (iface->speed > 0) { FF_DEBUG("Interface %s speed: %d Mbps", iface->name.chars, iface->speed); - } - else - { + } + } else { FF_DEBUG("Failed to get media info for interface %s", iface->name.chars); } - #endif +#endif } - #if __sun || __GNU__ - if ((options->showType & FF_LOCALIP_TYPE_MAC_BIT) && ioctl(sockfd, SIOCGIFHWADDR, &ifr) == 0) - { +#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]); + 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) - { +#endif +#if __sun + if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) { __attribute__((__cleanup__(kstatFreeWrap))) kstat_ctl_t* kc = kstat_open(); - for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next) - { - if (!ffStrEquals(ks->ks_class, "net") || !ffStrEquals(ks->ks_module, "link")) continue; - if (ffStrbufEqualS(&iface->name, ks->ks_name)) - { - if (kstat_read(kc, ks, NULL) >= 0) - { + for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next) { + if (!ffStrEquals(ks->ks_class, "net") || !ffStrEquals(ks->ks_module, "link")) { + continue; + } + if (ffStrbufEqualS(&iface->name, ks->ks_name)) { + if (kstat_read(kc, ks, NULL) >= 0) { kstat_named_t* ifspeed = (kstat_named_t*) kstat_data_lookup(ks, "ifspeed"); - if (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); } @@ -1050,11 +997,9 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) } } } - #endif +#endif } - } - else - { + } else { FF_DEBUG("Failed to create socket for interface property retrieval"); } } diff --git a/src/detection/localip/localip_windows.c b/src/detection/localip/localip_windows.c index bfdd81091..a633c623a 100644 --- a/src/detection/localip/localip_windows.c +++ b/src/detection/localip/localip_windows.c @@ -7,7 +7,7 @@ #include "common/debug.h" #include "localip.h" -#define FF_LOCALIP_NIFLAG(name) { IP_ADAPTER_##name, #name } +#define FF_LOCALIP_NIFLAG(name) {IP_ADAPTER_##name, #name} static const FFLocalIpNIFlag niFlagOptions[] = { FF_LOCALIP_NIFLAG(DDNS_ENABLED), @@ -24,31 +24,29 @@ static const FFLocalIpNIFlag niFlagOptions[] = { {}, }; -const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) -{ +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); + 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 // we are in the middle of querying them. DWORD adapter_addresses_buffer_size = 0; - for (int attempts = 0;; ++attempts) - { + 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); + 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); + 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( family, @@ -57,18 +55,13 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) adapter_addresses, &adapter_addresses_buffer_size); - if (error == ERROR_SUCCESS) - { + if (error == ERROR_SUCCESS) { FF_DEBUG("GetAdaptersAddresses succeeded on attempt %d", attempts + 1); break; - } - else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4) - { + } else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4) { FF_DEBUG("Buffer overflow, need %lu bytes, retrying", adapter_addresses_buffer_size); continue; - } - else - { + } else { FF_DEBUG("GetAdaptersAddresses failed with error %lu after %d attempts", error, attempts + 1); return "GetAdaptersAddresses() failed"; } @@ -77,50 +70,49 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) 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) - { + for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next) { adapterCount++; FF_DEBUG("Processing adapter %d: IfIndex=%u, IfType=%u, OperStatus=%u", - adapterCount, (unsigned)adapter->IfIndex, (unsigned)adapter->IfType, (unsigned)adapter->OperStatus); + 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); + 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; - FF_DEBUG("Adapter %u: isLoopback=%s", (unsigned)adapter->IfIndex, isLoop ? "true" : "false"); + FF_DEBUG("Adapter %u: isLoopback=%s", (unsigned) adapter->IfIndex, isLoop ? "true" : "false"); - if (isLoop && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT)) - { - FF_DEBUG("Skipping loopback adapter %u (loopback not requested)", (unsigned)adapter->IfIndex); + if (isLoop && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT)) { + FF_DEBUG("Skipping loopback adapter %u (loopback not requested)", (unsigned) adapter->IfIndex); continue; } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateWS(adapter->FriendlyName); - FF_DEBUG("Adapter %u name: '%s'", (unsigned)adapter->IfIndex, name.chars); + FF_DEBUG("Adapter %u name: '%s'", (unsigned) adapter->IfIndex, name.chars); - if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) - { + if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) { FF_DEBUG("Skipping adapter %u (name doesn't match prefix '%.*s')", - (unsigned)adapter->IfIndex, (int)options->namePrefix.length, options->namePrefix.chars); + (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_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); + !((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.chars); + FF_DEBUG("Creating result item for adapter %u ('%s')", (unsigned) adapter->IfIndex, name.chars); FFLocalIpResult* item = (FFLocalIpResult*) ffListAdd(results); ffStrbufInitMove(&item->name, &name); @@ -133,25 +125,24 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) 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_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) - { + for (IP_ADAPTER_UNICAST_ADDRESS* ifa = adapter->FirstUnicastAddress; ifa; ifa = ifa->Next) { FF_DEBUG("Processing unicast address: prefix origin=%d, suffix origin=%d, family=%d, DadState=%d", - ifa->PrefixOrigin, ifa->SuffixOrigin, ifa->Address.lpSockaddr->sa_family, ifa->DadState); + ifa->PrefixOrigin, + ifa->SuffixOrigin, + ifa->Address.lpSockaddr->sa_family, + ifa->DadState); - if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) - { - if (ifa->DadState != IpDadStatePreferred) - { + if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) { + if (ifa->DadState != IpDadStatePreferred) { FF_DEBUG("Skipping address (not preferred)"); continue; } - if (ifa->SuffixOrigin == IpSuffixOriginRandom) - { + if (ifa->SuffixOrigin == IpSuffixOriginRandom) { FF_DEBUG("Skipping temporary address (random suffix)"); continue; } @@ -159,17 +150,14 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) // MIB_UNICASTIPADDRESS_ROW::SkipAsSource } - if (ifa->Address.lpSockaddr->sa_family == AF_INET) - { - if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT))) - { + if (ifa->Address.lpSockaddr->sa_family == AF_INET) { + 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) - { + if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute) { FF_DEBUG("Skipping IPv4 address (not on default route interface)"); continue; } @@ -178,23 +166,27 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) char addressBuffer[INET_ADDRSTRLEN + 10]; char* end = RtlIpv4AddressToStringA(&ipv4->sin_addr, addressBuffer); - if ((options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT) && ifa->OnLinkPrefixLength) + if ((options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT) && ifa->OnLinkPrefixLength) { end += snprintf(end, 10, "/%u", (unsigned) ifa->OnLinkPrefixLength); + } FF_DEBUG("Adding IPv4 address: %s (isDefaultRoute=%s)", addressBuffer, isDefaultRoute ? "true" : "false"); - if (item->ipv4.length) ffStrbufAppendC(&item->ipv4, ','); + if (item->ipv4.length) { + ffStrbufAppendC(&item->ipv4, ','); + } ffStrbufAppendNS(&item->ipv4, (uint32_t) (end - addressBuffer), addressBuffer); - if (isDefaultRoute) item->defaultRoute |= FF_LOCALIP_TYPE_IPV4_BIT; + 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))) - { + 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))) { FF_DEBUG("Skipping IPv6 address (not requested in typesToAdd=0x%X)", typesToAdd); continue; } @@ -202,20 +194,23 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) SOCKADDR_IN6* ipv6 = (SOCKADDR_IN6*) ifa->Address.lpSockaddr; FFLocalIpIpv6Type ipv6Type = FF_LOCALIP_IPV6_TYPE_NONE; - if (IN6_IS_ADDR_GLOBAL(&ipv6->sin6_addr)) ipv6Type |= FF_LOCALIP_IPV6_TYPE_GUA_BIT; - else if (IN6_IS_ADDR_UNIQUE_LOCAL(&ipv6->sin6_addr)) ipv6Type |= FF_LOCALIP_IPV6_TYPE_ULA_BIT; - else if (IN6_IS_ADDR_LINKLOCAL(&ipv6->sin6_addr)) ipv6Type |= FF_LOCALIP_IPV6_TYPE_LLA_BIT; - else ipv6Type |= FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT; + if (IN6_IS_ADDR_GLOBAL(&ipv6->sin6_addr)) { + ipv6Type |= FF_LOCALIP_IPV6_TYPE_GUA_BIT; + } else if (IN6_IS_ADDR_UNIQUE_LOCAL(&ipv6->sin6_addr)) { + ipv6Type |= FF_LOCALIP_IPV6_TYPE_ULA_BIT; + } else if (IN6_IS_ADDR_LINKLOCAL(&ipv6->sin6_addr)) { + ipv6Type |= FF_LOCALIP_IPV6_TYPE_LLA_BIT; + } else { + ipv6Type |= FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT; + } - if (!(options->ipv6Type & ipv6Type)) - { + if (!(options->ipv6Type & ipv6Type)) { FF_DEBUG("Skipping IPv6 address (doesn't match requested type 0x%X)", options->ipv6Type); 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) - { + if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute) { FF_DEBUG("Skipping IPv6 address (not on default route interface)"); continue; } @@ -223,48 +218,53 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) char addressBuffer[INET6_ADDRSTRLEN + 10]; char* end = RtlIpv6AddressToStringA(&ipv6->sin6_addr, addressBuffer); - if ((options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT) && ifa->OnLinkPrefixLength) + if ((options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT) && ifa->OnLinkPrefixLength) { end += snprintf(end, 10, "/%u", (unsigned) ifa->OnLinkPrefixLength); + } FF_DEBUG("Adding IPv6 address: %s (isDefaultRoute=%s)", addressBuffer, isDefaultRoute ? "true" : "false"); - if (item->ipv6.length) ffStrbufAppendC(&item->ipv6, ','); + if (item->ipv6.length) { + ffStrbufAppendC(&item->ipv6, ','); + } ffStrbufAppendNS(&item->ipv6, (uint32_t) (end - addressBuffer), addressBuffer); - if (isDefaultRoute) item->defaultRoute |= FF_LOCALIP_TYPE_IPV6_BIT; + if (isDefaultRoute) { + item->defaultRoute |= FF_LOCALIP_TYPE_IPV6_BIT; + } ipv6Count++; typesToAdd &= ~(unsigned) FF_LOCALIP_TYPE_IPV6_BIT; - if (typesToAdd == 0) break; + if (typesToAdd == 0) { + break; + } } } - FF_DEBUG("Adapter %u: collected %d IPv4 and %d IPv6 addresses", (unsigned)adapter->IfIndex, ipv4Count, ipv6Count); + FF_DEBUG("Adapter %u: collected %d IPv4 and %d IPv6 addresses", (unsigned) adapter->IfIndex, ipv4Count, ipv6Count); - if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) - { + if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) { item->speed = (int32_t) (adapter->ReceiveLinkSpeed / 1000000); - FF_DEBUG("Adapter %u speed: %d Mbps (raw: %llu)", (unsigned)adapter->IfIndex, item->speed, adapter->ReceiveLinkSpeed); + FF_DEBUG("Adapter %u speed: %d Mbps (raw: %llu)", (unsigned) adapter->IfIndex, item->speed, adapter->ReceiveLinkSpeed); } - if (options->showType & FF_LOCALIP_TYPE_MTU_BIT) - { + 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); + FF_DEBUG("Adapter %u MTU: %d", (unsigned) adapter->IfIndex, item->mtu); } - if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT) - { + 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); + 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) - { + 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("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); + adapterCount, + processedCount, + results->length); return NULL; } diff --git a/src/detection/media/media.c b/src/detection/media/media.c index 3a6e4ed22..e488259d2 100644 --- a/src/detection/media/media.c +++ b/src/detection/media/media.c @@ -5,19 +5,15 @@ void ffDetectMediaImpl(FFMediaResult* media, bool saveCover); static FFMediaResult result; -static void removeMediaCoverFile(void) -{ - if (result.cover.length > 0) - { +static void removeMediaCoverFile(void) { + if (result.cover.length > 0) { ffRemoveFile(result.cover.chars); ffStrbufDestroy(&result.cover); } } -const FFMediaResult* ffDetectMedia(bool saveCover) -{ - if (result.error.chars == NULL) - { +const FFMediaResult* ffDetectMedia(bool saveCover) { + if (result.error.chars == NULL) { ffStrbufInit(&result.error); ffStrbufInit(&result.playerId); ffStrbufInit(&result.player); @@ -30,15 +26,17 @@ const FFMediaResult* ffDetectMedia(bool saveCover) result.removeCoverAfterUse = false; ffDetectMediaImpl(&result, saveCover); - if(result.song.length == 0 && result.error.length == 0) + if (result.song.length == 0 && result.error.length == 0) { ffStrbufAppendS(&result.error, "No media found"); + } ffStrbufTrimRightSpace(&result.song); ffStrbufTrimRightSpace(&result.artist); ffStrbufTrimRightSpace(&result.album); ffStrbufTrimRightSpace(&result.player); - if (saveCover && result.removeCoverAfterUse) + if (saveCover && result.removeCoverAfterUse) { atexit(removeMediaCoverFile); + } } return &result; diff --git a/src/detection/media/media.h b/src/detection/media/media.h index 41ca65f55..e2a67df5d 100644 --- a/src/detection/media/media.h +++ b/src/detection/media/media.h @@ -3,11 +3,10 @@ #include "fastfetch.h" #include "modules/media/option.h" -typedef struct FFMediaResult -{ +typedef struct FFMediaResult { FFstrbuf error; FFstrbuf playerId; // Bus name on Linux, app bundle name on macOS. e.g. plasma-browser-integration - FFstrbuf player; // e.g. Google Chrome + FFstrbuf player; // e.g. Google Chrome FFstrbuf song; FFstrbuf artist; FFstrbuf album; diff --git a/src/detection/media/media_linux.c b/src/detection/media/media_linux.c index 67b434d4e..162db1b4f 100644 --- a/src/detection/media/media_linux.c +++ b/src/detection/media/media_linux.c @@ -9,95 +9,87 @@ #define FF_DBUS_MPRIS_PREFIX "org.mpris.MediaPlayer2." #ifdef FF_HAVE_DBUS -#include "common/dbus.h" +# include "common/dbus.h" -#define FF_DBUS_ITER_CONTINUE(dbus, iterator) \ - { \ - if(!(dbus)->lib->ffdbus_message_iter_next(iterator)) \ - break; \ - continue; \ - } +# define FF_DBUS_ITER_CONTINUE(dbus, iterator) \ + { \ + if (!(dbus)->lib->ffdbus_message_iter_next(iterator)) \ + break; \ + continue; \ + } -static bool parseMprisMetadata(FFDBusData* data, DBusMessageIter* rootIterator, FFMediaResult* result) -{ +static bool parseMprisMetadata(FFDBusData* data, DBusMessageIter* rootIterator, FFMediaResult* result) { DBusMessageIter arrayIterator; - if (data->lib->ffdbus_message_iter_get_arg_type(rootIterator) == DBUS_TYPE_VARIANT) - { + if (data->lib->ffdbus_message_iter_get_arg_type(rootIterator) == DBUS_TYPE_VARIANT) { DBusMessageIter variantIterator; data->lib->ffdbus_message_iter_recurse(rootIterator, &variantIterator); - if(data->lib->ffdbus_message_iter_get_arg_type(&variantIterator) != DBUS_TYPE_ARRAY) + if (data->lib->ffdbus_message_iter_get_arg_type(&variantIterator) != DBUS_TYPE_ARRAY) { return false; + } data->lib->ffdbus_message_iter_recurse(&variantIterator, &arrayIterator); - } - else - { + } else { data->lib->ffdbus_message_iter_recurse(rootIterator, &arrayIterator); } - while(true) - { - if(data->lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DICT_ENTRY) + while (true) { + if (data->lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DICT_ENTRY) { FF_DBUS_ITER_CONTINUE(data, &arrayIterator) + } DBusMessageIter dictIterator; data->lib->ffdbus_message_iter_recurse(&arrayIterator, &dictIterator); - if(data->lib->ffdbus_message_iter_get_arg_type(&dictIterator) != DBUS_TYPE_STRING) + if (data->lib->ffdbus_message_iter_get_arg_type(&dictIterator) != DBUS_TYPE_STRING) { FF_DBUS_ITER_CONTINUE(data, &arrayIterator) + } - if(!data->lib->ffdbus_message_iter_has_next(&dictIterator)) + if (!data->lib->ffdbus_message_iter_has_next(&dictIterator)) { FF_DBUS_ITER_CONTINUE(data, &arrayIterator) + } const char* key; data->lib->ffdbus_message_iter_get_basic(&dictIterator, &key); data->lib->ffdbus_message_iter_next(&dictIterator); - if(ffStrStartsWith(key, "xesam:")) - { + if (ffStrStartsWith(key, "xesam:")) { const char* xesam = key + strlen("xesam:"); - if(ffStrEquals(xesam, "title")) + if (ffStrEquals(xesam, "title")) { ffDBusGetString(data, &dictIterator, &result->song); - else if(ffStrEquals(xesam, "album")) + } else if (ffStrEquals(xesam, "album")) { ffDBusGetString(data, &dictIterator, &result->album); - else if(ffStrEquals(xesam, "artist")) + } else if (ffStrEquals(xesam, "artist")) { ffDBusGetString(data, &dictIterator, &result->artist); - else if(ffStrEquals(xesam, "url")) + } else if (ffStrEquals(xesam, "url")) { ffDBusGetString(data, &dictIterator, &result->url); + } - if(result->song.length > 0 && result->artist.length > 0 && result->album.length > 0 && result->url.length > 0) + if (result->song.length > 0 && result->artist.length > 0 && result->album.length > 0 && result->url.length > 0) { break; - } - else if (ffStrStartsWith(key, "mpris:")) - { + } + } else if (ffStrStartsWith(key, "mpris:")) { const char* xesam = key + strlen("mpris:"); - if(ffStrEquals(xesam, "artUrl")) - { + if (ffStrEquals(xesam, "artUrl")) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); ffDBusGetString(data, &dictIterator, &path); - if (ffStrbufStartsWithS(&path, "file:///")) - { + if (ffStrbufStartsWithS(&path, "file:///")) { ffStrbufEnsureFree(&result->cover, path.length - (uint32_t) strlen("file://")); - for (uint32_t i = (uint32_t) strlen("file://"); i < path.length; ++i) - { - if (path.chars[i] == '%') - { - if (i + 2 >= path.length) + for (uint32_t i = (uint32_t) strlen("file://"); i < path.length; ++i) { + if (path.chars[i] == '%') { + if (i + 2 >= path.length) { break; - char str[] = { path.chars[i + 1], path.chars[i + 2], 0 }; + } + char str[] = {path.chars[i + 1], path.chars[i + 2], 0}; char* end = NULL; const char decodedChar = (char) strtoul(str, &end, 16); - if (end == &str[2]) - { + if (end == &str[2]) { i += 2; ffStrbufAppendC(&result->cover, decodedChar); - } - else + } else { ffStrbufAppendC(&result->cover, '%'); - } - else - { + } + } else { ffStrbufAppendC(&result->cover, path.chars[i]); } } @@ -111,17 +103,16 @@ static bool parseMprisMetadata(FFDBusData* data, DBusMessageIter* rootIterator, return true; } -static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResult* result) -{ +static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResult* result) { // Get all properties at once to reduce the number of IPCs DBusMessage* reply = ffDBusGetAllProperties(data, busName, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player"); - if(reply == NULL) + if (reply == NULL) { return false; + } DBusMessageIter rootIterator; - if(!data->lib->ffdbus_message_iter_init(reply, &rootIterator) && - data->lib->ffdbus_message_iter_get_arg_type(&rootIterator) != DBUS_TYPE_ARRAY) - { + if (!data->lib->ffdbus_message_iter_init(reply, &rootIterator) && + data->lib->ffdbus_message_iter_get_arg_type(&rootIterator) != DBUS_TYPE_ARRAY) { data->lib->ffdbus_message_unref(reply); return false; } @@ -129,10 +120,10 @@ static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResul DBusMessageIter arrayIterator; data->lib->ffdbus_message_iter_recurse(&rootIterator, &arrayIterator); - while(true) - { - if(data->lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DICT_ENTRY) + while (true) { + if (data->lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DICT_ENTRY) { FF_DBUS_ITER_CONTINUE(data, &arrayIterator) + } DBusMessageIter dictIterator; data->lib->ffdbus_message_iter_recurse(&arrayIterator, &dictIterator); @@ -142,40 +133,34 @@ static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResul data->lib->ffdbus_message_iter_next(&dictIterator); - if(ffStrEquals(key, "Metadata")) + if (ffStrEquals(key, "Metadata")) { parseMprisMetadata(data, &dictIterator, result); - else if(ffStrEquals(key, "PlaybackStatus")) + } else if (ffStrEquals(key, "PlaybackStatus")) { ffDBusGetString(data, &dictIterator, &result->status); + } FF_DBUS_ITER_CONTINUE(data, &arrayIterator) } - if(result->song.length == 0) - { - if(result->url.length) - { + if (result->song.length == 0) { + if (result->url.length) { const char* fileName = memrchr(result->url.chars, '/', result->url.length); assert(fileName); ++fileName; ffStrbufEnsureFixedLengthFree(&result->song, result->url.length - (uint32_t) (fileName - result->url.chars)); - for(; *fileName && *fileName != '?'; ++fileName) - { - if (*fileName != '%') - { + for (; *fileName && *fileName != '?'; ++fileName) { + if (*fileName != '%') { ffStrbufAppendC(&result->song, *fileName); - } - else - { - if (fileName[1] == 0 || fileName[2] == 0) + } else { + if (fileName[1] == 0 || fileName[2] == 0) { break; - char str[] = { fileName[1], fileName[2], 0 }; + } + char str[] = {fileName[1], fileName[2], 0}; ffStrbufAppendC(&result->song, (char) strtoul(str, NULL, 16)); fileName += 2; } } - } - else - { + } else { ffStrbufClear(&result->artist); ffStrbufClear(&result->album); ffStrbufClear(&result->url); @@ -185,22 +170,21 @@ static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResul } } - //Set short bus name + // Set short bus name ffStrbufAppendS(&result->playerId, busName + sizeof(FF_DBUS_MPRIS_PREFIX) - 1); - //We found a song, get the player name - if (ffStrbufStartsWithS(&result->playerId, "musikcube.instance")) - { + // We found a song, get the player name + if (ffStrbufStartsWithS(&result->playerId, "musikcube.instance")) { // dbus calls are EXTREMELY slow on musikcube, so we set the player name manually ffStrbufSetStatic(&result->player, "musikcube"); - } - else - { + } else { ffDBusGetPropertyString(data, busName, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2", "Identity", &result->player); - if(result->player.length == 0) + if (result->player.length == 0) { ffDBusGetPropertyString(data, busName, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2", "DesktopEntry", &result->player); - if(result->player.length == 0) + } + if (result->player.length == 0) { ffStrbufAppend(&result->player, &result->playerId); + } } data->lib->ffdbus_message_unref(reply); @@ -208,10 +192,8 @@ static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResul return true; } -static void getCustomBus(FFDBusData* data, const FFstrbuf* playerName, FFMediaResult* result) -{ - if(ffStrbufStartsWithS(playerName, FF_DBUS_MPRIS_PREFIX)) - { +static void getCustomBus(FFDBusData* data, const FFstrbuf* playerName, FFMediaResult* result) { + if (ffStrbufStartsWithS(playerName, FF_DBUS_MPRIS_PREFIX)) { getBusProperties(data, playerName->chars, result); return; } @@ -221,38 +203,42 @@ static void getCustomBus(FFDBusData* data, const FFstrbuf* playerName, FFMediaRe getBusProperties(data, busName.chars, result); } -static void getBestBus(FFDBusData* data, FFMediaResult* result) -{ - if( +static void getBestBus(FFDBusData* data, FFMediaResult* result) { + if ( getBusProperties(data, FF_DBUS_MPRIS_PREFIX "spotify", result) || getBusProperties(data, FF_DBUS_MPRIS_PREFIX "vlc", result) || - getBusProperties(data, FF_DBUS_MPRIS_PREFIX "plasma-browser-integration", result) - ) return; + 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, NULL); - if(reply == NULL) + if (reply == NULL) { return; + } DBusMessageIter rootIterator; - if(!data->lib->ffdbus_message_iter_init(reply, &rootIterator) || data->lib->ffdbus_message_iter_get_arg_type(&rootIterator) != DBUS_TYPE_ARRAY) + if (!data->lib->ffdbus_message_iter_init(reply, &rootIterator) || data->lib->ffdbus_message_iter_get_arg_type(&rootIterator) != DBUS_TYPE_ARRAY) { return; + } DBusMessageIter arrayIterator; data->lib->ffdbus_message_iter_recurse(&rootIterator, &arrayIterator); - while(true) - { - if(data->lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_STRING) + while (true) { + if (data->lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_STRING) { FF_DBUS_ITER_CONTINUE(data, &arrayIterator) + } const char* busName; data->lib->ffdbus_message_iter_get_basic(&arrayIterator, &busName); - if(!ffStrStartsWith(busName, FF_DBUS_MPRIS_PREFIX)) + if (!ffStrStartsWith(busName, FF_DBUS_MPRIS_PREFIX)) { FF_DBUS_ITER_CONTINUE(data, &arrayIterator) + } - if(getBusProperties(data, busName, result)) + if (getBusProperties(data, busName, result)) { break; + } FF_DBUS_ITER_CONTINUE(data, &arrayIterator) } @@ -260,32 +246,32 @@ static void getBestBus(FFDBusData* data, FFMediaResult* result) data->lib->ffdbus_message_unref(reply); } -static const char* getMedia(FFMediaResult* result) -{ +static const char* getMedia(FFMediaResult* result) { FF_DBUS_AUTO_DESTROY_DATA FFDBusData data = {}; const char* error = ffDBusLoadData(DBUS_BUS_SESSION, &data); - if(error != NULL) + if (error != NULL) { return error; + } // FIXME: This is shared for both player and media module. // However it uses an option in one specific module - if(instance.config.general.playerName.length > 0) + if (instance.config.general.playerName.length > 0) { getCustomBus(&data, &instance.config.general.playerName, result); - else + } else { getBestBus(&data, result); + } return NULL; } #endif -void ffDetectMediaImpl(FFMediaResult* media, bool saveCover) -{ +void ffDetectMediaImpl(FFMediaResult* media, bool saveCover) { FF_UNUSED(saveCover); // We don't save the cover to a file for Mpris implementation - #ifdef FF_HAVE_DBUS - const char* error = getMedia(media); - ffStrbufAppendS(&media->error, error); - #else - ffStrbufAppendS(&media->error, "Fastfetch was compiled without DBus support"); - #endif +#ifdef FF_HAVE_DBUS + const char* error = getMedia(media); + ffStrbufAppendS(&media->error, error); +#else + ffStrbufAppendS(&media->error, "Fastfetch was compiled without DBus support"); +#endif } diff --git a/src/detection/media/media_nosupport.c b/src/detection/media/media_nosupport.c index b0c19a652..e7d1c0f5b 100644 --- a/src/detection/media/media_nosupport.c +++ b/src/detection/media/media_nosupport.c @@ -1,6 +1,5 @@ #include "media.h" -void ffDetectMediaImpl(FFMediaResult* media) -{ +void ffDetectMediaImpl(FFMediaResult* media) { ffStrbufAppendS(&media->error, "Not supported on this platform"); } diff --git a/src/detection/media/media_windows.c b/src/detection/media/media_windows.c index eb165177b..c9d534a8d 100644 --- a/src/detection/media/media_windows.c +++ b/src/detection/media/media_windows.c @@ -3,8 +3,7 @@ #include "media.h" #include "media_windows.dll.h" -static const char* getMedia(FFMediaResult* media, bool saveCover) -{ +static const char* getMedia(FFMediaResult* media, bool saveCover) { FF_LIBRARY_LOAD_MESSAGE(libffwinrt, "libffwinrt" FF_LIBRARY_EXTENSION, 0) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libffwinrt, ffWinrtDetectMedia) libffwinrt = NULL; // Don't close libffwinrt or it may crash @@ -12,35 +11,32 @@ static const char* getMedia(FFMediaResult* media, bool saveCover) FFWinrtMediaResult result = {}; const char* error = ffffWinrtDetectMedia(&result, saveCover); - if (error) - { + if (error) { ffStrbufSetStatic(&media->error, error); return NULL; } ffStrbufSetWS(&media->playerId, result.playerId); - if (result.playerName[0]) - { + if (result.playerName[0]) { ffStrbufSetWS(&media->player, result.playerName); - } - else - { + } else { ffStrbufSet(&media->player, &media->playerId); - if (ffStrbufEndsWithIgnCaseS(&media->player, ".exe")) + if (ffStrbufEndsWithIgnCaseS(&media->player, ".exe")) { ffStrbufSubstrBefore(&media->player, media->player.length - 4); + } } ffStrbufSetWS(&media->song, result.song); ffStrbufSetWS(&media->artist, result.artist); ffStrbufSetWS(&media->album, result.album); ffStrbufSetWS(&media->cover, result.cover); ffStrbufSetStatic(&media->status, result.status); - if (media->cover.length > 0) + if (media->cover.length > 0) { media->removeCoverAfterUse = true; + } return NULL; } -void ffDetectMediaImpl(FFMediaResult* media, bool saveCover) -{ +void ffDetectMediaImpl(FFMediaResult* media, bool saveCover) { const char* error = getMedia(media, saveCover); ffStrbufAppendS(&media->error, error); } diff --git a/src/detection/media/media_windows.dll.cpp b/src/detection/media/media_windows.dll.cpp index b8a23b9e8..b89ced9c7 100644 --- a/src/detection/media/media_windows.dll.cpp +++ b/src/detection/media/media_windows.dll.cpp @@ -6,46 +6,46 @@ #include #include -extern "C" -{ +extern "C" { #include "media_windows.dll.h" -const char* ffWinrtDetectMedia(FFWinrtMediaResult* result, bool saveCover) -{ +const char* ffWinrtDetectMedia(FFWinrtMediaResult* result, bool saveCover) { // C++/WinRT requires Windows 8.1+ and C++ runtime (std::string, exceptions and other stuff) // Make it a separate dll in order not to break Windows 7 support using namespace winrt::Windows::Media::Control; using namespace winrt::Windows::ApplicationModel; - try - { + try { auto manager = GlobalSystemMediaTransportControlsSessionManager::RequestAsync().get(); - if (!manager) + if (!manager) { return "winrt: GlobalSystemMediaTransportControlsSessionManager::RequestAsync() failed"; + } auto session = manager.GetCurrentSession(); - if (!session) + if (!session) { return "winrt: GetCurrentSession() failed"; + } auto mediaProps = session - .TryGetMediaPropertiesAsync() - .get(); - if (!mediaProps) + .TryGetMediaPropertiesAsync() + .get(); + if (!mediaProps) { return "winrt: TryGetMediaPropertiesAsync() failed"; + } - if (auto playbackInfo = session.GetPlaybackInfo()) - { - switch (playbackInfo.PlaybackStatus()) - { - #define FF_MEDIA_SET_STATUS(status_code) \ - case GlobalSystemMediaTransportControlsSessionPlaybackStatus::status_code: result->status = #status_code; break; + if (auto playbackInfo = session.GetPlaybackInfo()) { + switch (playbackInfo.PlaybackStatus()) { +#define FF_MEDIA_SET_STATUS(status_code) \ + case GlobalSystemMediaTransportControlsSessionPlaybackStatus::status_code: \ + result->status = #status_code; \ + break; FF_MEDIA_SET_STATUS(Closed) FF_MEDIA_SET_STATUS(Opened) FF_MEDIA_SET_STATUS(Changing) FF_MEDIA_SET_STATUS(Stopped) FF_MEDIA_SET_STATUS(Playing) FF_MEDIA_SET_STATUS(Paused) - #undef FF_MEDIA_SET_STATUS +#undef FF_MEDIA_SET_STATUS } } @@ -57,31 +57,24 @@ const char* ffWinrtDetectMedia(FFWinrtMediaResult* result, bool saveCover) result->artist[FF_MEDIA_WIN_RESULT_BUFLEN - 1] = L'\0'; ::wcsncpy(result->album, mediaProps.AlbumTitle().data(), FF_MEDIA_WIN_RESULT_BUFLEN); result->album[FF_MEDIA_WIN_RESULT_BUFLEN - 1] = L'\0'; - try - { + try { // Only works for UWP apps ::wcsncpy(result->playerName, AppInfo::GetFromAppUserModelId(session.SourceAppUserModelId()).DisplayInfo().DisplayName().data(), FF_MEDIA_WIN_RESULT_BUFLEN); result->playerName[FF_MEDIA_WIN_RESULT_BUFLEN - 1] = L'\0'; - } catch (...) { } + } catch (...) {} - if (saveCover) - { + if (saveCover) { using namespace winrt::Windows::Storage; using namespace winrt::Windows::Storage::Streams; - if (auto thumbRef = mediaProps.Thumbnail()) - { - try - { - if (auto stream = thumbRef.OpenReadAsync().get()) - { - if (stream.Size() > 0) - { + if (auto thumbRef = mediaProps.Thumbnail()) { + try { + if (auto stream = thumbRef.OpenReadAsync().get()) { + if (stream.Size() > 0) { Buffer buffer(static_cast(stream.Size())); stream.ReadAsync(buffer, buffer.Capacity(), InputStreamOptions::None).get(); wchar_t tempPath[MAX_PATH]; - if (GetTempPathW(MAX_PATH, tempPath) > 0) - { + if (GetTempPathW(MAX_PATH, tempPath) > 0) { auto tempFolder = StorageFolder::GetFolderFromPathAsync(tempPath).get(); auto tempFile = tempFolder.CreateFileAsync(L"ff_thumb.img", CreationCollisionOption::GenerateUniqueName).get(); FileIO::WriteBufferAsync(tempFile, buffer).get(); @@ -91,18 +84,14 @@ const char* ffWinrtDetectMedia(FFWinrtMediaResult* result, bool saveCover) } } } - } - catch (...) - { + } catch (...) { // Ignore thumbnail errors } } } return NULL; - } - catch (...) - { + } catch (...) { return "A C++ exception is thrown"; } } diff --git a/src/detection/media/media_windows.dll.h b/src/detection/media/media_windows.dll.h index 9d4e37755..b9b942d74 100644 --- a/src/detection/media/media_windows.dll.h +++ b/src/detection/media/media_windows.dll.h @@ -2,8 +2,7 @@ #define FF_MEDIA_WIN_RESULT_BUFLEN 256 -typedef struct FFWinrtMediaResult -{ +typedef struct FFWinrtMediaResult { wchar_t playerId[FF_MEDIA_WIN_RESULT_BUFLEN]; wchar_t playerName[FF_MEDIA_WIN_RESULT_BUFLEN]; wchar_t song[FF_MEDIA_WIN_RESULT_BUFLEN]; @@ -14,4 +13,5 @@ typedef struct FFWinrtMediaResult } FFWinrtMediaResult; __attribute__((__dllexport__)) -const char* ffWinrtDetectMedia(FFWinrtMediaResult* result, bool saveCover); +const char* +ffWinrtDetectMedia(FFWinrtMediaResult* result, bool saveCover); diff --git a/src/detection/memory/memory.h b/src/detection/memory/memory.h index 71a9ea9a4..1c2382853 100644 --- a/src/detection/memory/memory.h +++ b/src/detection/memory/memory.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/memory/option.h" -typedef struct FFMemoryResult -{ +typedef struct FFMemoryResult { uint64_t bytesUsed; uint64_t bytesTotal; } FFMemoryResult; diff --git a/src/detection/memory/memory_apple.c b/src/detection/memory/memory_apple.c index 234db1186..6f6297e4e 100644 --- a/src/detection/memory/memory_apple.c +++ b/src/detection/memory/memory_apple.c @@ -6,22 +6,24 @@ #include #include -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { size_t length = sizeof(ram->bytesTotal); - #if FF_APPLE_MEMSIZE_USABLE - if (sysctlbyname("hw.memsize_usable", &ram->bytesTotal, &length, NULL, 0) != 0) +#if FF_APPLE_MEMSIZE_USABLE + if (sysctlbyname("hw.memsize_usable", &ram->bytesTotal, &length, NULL, 0) != 0) { return "Failed to read hw.memsize_usable"; - #else - if (sysctl((int[]){ CTL_HW, HW_MEMSIZE }, 2, &ram->bytesTotal, &length, NULL, 0) != 0) + } +#else + if (sysctl((int[]) {CTL_HW, HW_MEMSIZE}, 2, &ram->bytesTotal, &length, NULL, 0) != 0) { return "Failed to read hw.memsize"; - #endif + } +#endif mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; vm_statistics64_data_t vmstat; - if(host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) (&vmstat), &count) != KERN_SUCCESS) + if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) (&vmstat), &count) != KERN_SUCCESS) { return "Failed to read host_statistics64"; + } // https://github.com/st3fan/osx-10.9/blob/34e34a6a539b5a822cda4074e56a7ced9b57da71/system_cmds-597.1.1/vm_stat.tproj/vm_stat.c#L139 diff --git a/src/detection/memory/memory_bsd.c b/src/detection/memory/memory_bsd.c index 0db20527a..fa1b6c043 100644 --- a/src/detection/memory/memory_bsd.c +++ b/src/detection/memory/memory_bsd.c @@ -1,16 +1,14 @@ #include "memory.h" #include "common/sysctl.h" -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { size_t length = sizeof(ram->bytesTotal); - if (sysctl((int[]){ CTL_HW, HW_PHYSMEM }, 2, &ram->bytesTotal, &length, NULL, 0)) + if (sysctl((int[]) {CTL_HW, HW_PHYSMEM}, 2, &ram->bytesTotal, &length, NULL, 0)) { return "Failed to read hw.physmem"; + } // vm.stats.vm.* are int values - int32_t pagesFree = ffSysctlGetInt("vm.stats.vm.v_free_count", 0) - + ffSysctlGetInt("vm.stats.vm.v_inactive_count", 0) - + ffSysctlGetInt("vm.stats.vm.v_cache_count", 0); + int32_t pagesFree = ffSysctlGetInt("vm.stats.vm.v_free_count", 0) + ffSysctlGetInt("vm.stats.vm.v_inactive_count", 0) + ffSysctlGetInt("vm.stats.vm.v_cache_count", 0); ram->bytesUsed = ram->bytesTotal - (uint64_t) pagesFree * instance.state.platform.sysinfo.pageSize; diff --git a/src/detection/memory/memory_haiku.c b/src/detection/memory/memory_haiku.c index ec8881455..7888801ce 100644 --- a/src/detection/memory/memory_haiku.c +++ b/src/detection/memory/memory_haiku.c @@ -2,11 +2,11 @@ #include -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { system_info info; - if (get_system_info(&info) != B_OK) + if (get_system_info(&info) != B_OK) { return "Error getting system info"; + } uint32_t pageSize = instance.state.platform.sysinfo.pageSize; ram->bytesTotal = pageSize * info.max_pages; diff --git a/src/detection/memory/memory_linux.c b/src/detection/memory/memory_linux.c index 66a679d10..74d20a031 100644 --- a/src/detection/memory/memory_linux.c +++ b/src/detection/memory/memory_linux.c @@ -4,12 +4,12 @@ #include -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { char buf[PROC_FILE_BUFFSIZ]; ssize_t nRead = ffReadFileData("/proc/meminfo", ARRAY_SIZE(buf) - 1, buf); - if(nRead < 0) + if (nRead < 0) { return "ffReadFileData(\"/proc/meminfo\", ARRAY_SIZE(buf)-1, buf)"; + } buf[nRead] = '\0'; uint64_t memTotal = 0, @@ -20,30 +20,37 @@ const char* ffDetectMemory(FFMemoryResult* ram) cached = 0, sReclaimable = 0; - char *token = NULL; - if((token = strstr(buf, "MemTotal:")) != NULL) + char* token = NULL; + if ((token = strstr(buf, "MemTotal:")) != NULL) { memTotal = strtoul(token + strlen("MemTotal:"), NULL, 10); - else + } else { return "MemTotal not found in /proc/meminfo"; + } - if((token = strstr(buf, "MemAvailable:")) != NULL) + if ((token = strstr(buf, "MemAvailable:")) != NULL) { memAvailable = strtoul(token + strlen("MemAvailable:"), NULL, 10); + } if (memAvailable == 0 || memAvailable >= memTotal) // MemAvailable can be unreasonable. #1988 { - if((token = strstr(buf, "MemFree:")) != NULL) + if ((token = strstr(buf, "MemFree:")) != NULL) { memFree = strtoul(token + strlen("MemFree:"), NULL, 10); + } - if((token = strstr(buf, "Buffers:")) != NULL) + if ((token = strstr(buf, "Buffers:")) != NULL) { buffers = strtoul(token + strlen("Buffers:"), NULL, 10); + } - if((token = strstr(buf, "Cached:")) != NULL) + if ((token = strstr(buf, "Cached:")) != NULL) { cached = strtoul(token + strlen("Cached:"), NULL, 10); + } - if((token = strstr(buf, "Shmem:")) != NULL) + if ((token = strstr(buf, "Shmem:")) != NULL) { shmem = strtoul(token + strlen("Shmem:"), NULL, 10); + } - if((token = strstr(buf, "SReclaimable:")) != NULL) + if ((token = strstr(buf, "SReclaimable:")) != NULL) { sReclaimable = strtoul(token + strlen("SReclaimable:"), NULL, 10); + } memAvailable = memFree + buffers + cached + sReclaimable - shmem; } diff --git a/src/detection/memory/memory_nbsd.c b/src/detection/memory/memory_nbsd.c index 651058686..affaaca41 100644 --- a/src/detection/memory/memory_nbsd.c +++ b/src/detection/memory/memory_nbsd.c @@ -4,12 +4,12 @@ #include #include -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { struct uvmexp_sysctl buf; size_t length = sizeof(buf); - if (sysctl((int[]){ CTL_VM, VM_UVMEXP2 }, 2, &buf, &length, NULL, 0) < 0) + if (sysctl((int[]) {CTL_VM, VM_UVMEXP2}, 2, &buf, &length, NULL, 0) < 0) { return "sysctl(CTL_VM, VM_UVMEXP2) failed"; + } ram->bytesTotal = (uint64_t) buf.npages * instance.state.platform.sysinfo.pageSize; ram->bytesUsed = ((uint64_t) buf.active + (uint64_t) buf.inactive + (uint64_t) buf.wired) * instance.state.platform.sysinfo.pageSize; diff --git a/src/detection/memory/memory_nosupport.c b/src/detection/memory/memory_nosupport.c index 180a276aa..8bc534813 100644 --- a/src/detection/memory/memory_nosupport.c +++ b/src/detection/memory/memory_nosupport.c @@ -1,6 +1,5 @@ #include "memory.h" -const char* ffDetectMemory(FF_MAYBE_UNUSED FFMemoryResult* ram) -{ +const char* ffDetectMemory(FF_MAYBE_UNUSED FFMemoryResult* ram) { return "Not supported on this platform"; } diff --git a/src/detection/memory/memory_obsd.c b/src/detection/memory/memory_obsd.c index e58bf0d37..e0964b97b 100644 --- a/src/detection/memory/memory_obsd.c +++ b/src/detection/memory/memory_obsd.c @@ -4,12 +4,12 @@ #include #include -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { struct uvmexp buf; size_t length = sizeof(buf); - if (sysctl((int[]){ CTL_VM, VM_UVMEXP }, 2, &buf, &length, NULL, 0) < 0) + if (sysctl((int[]) {CTL_VM, VM_UVMEXP}, 2, &buf, &length, NULL, 0) < 0) { return "sysctl(CTL_VM, VM_UVMEXP) failed"; + } ram->bytesTotal = (uint64_t) buf.npages * instance.state.platform.sysinfo.pageSize; ram->bytesUsed = ((uint64_t) buf.active + (uint64_t) buf.inactive + (uint64_t) buf.wired) * instance.state.platform.sysinfo.pageSize; diff --git a/src/detection/memory/memory_sunos.c b/src/detection/memory/memory_sunos.c index f390d0ae3..7dfdeab95 100644 --- a/src/detection/memory/memory_sunos.c +++ b/src/detection/memory/memory_sunos.c @@ -1,8 +1,7 @@ #include "memory.h" #include -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { ram->bytesTotal = (uint64_t) sysconf(_SC_PHYS_PAGES) * instance.state.platform.sysinfo.pageSize; ram->bytesUsed = ram->bytesTotal - (uint64_t) sysconf(_SC_AVPHYS_PAGES) * instance.state.platform.sysinfo.pageSize; diff --git a/src/detection/memory/memory_windows.c b/src/detection/memory/memory_windows.c index 38362fd40..779425d55 100644 --- a/src/detection/memory/memory_windows.c +++ b/src/detection/memory/memory_windows.c @@ -2,16 +2,16 @@ #include -const char* ffDetectMemory(FFMemoryResult* ram) -{ +const char* ffDetectMemory(FFMemoryResult* ram) { MEMORYSTATUSEX statex = { .dwLength = sizeof(statex), }; // GlobalMemoryStatusEx() internally uses // NtQuerySystemInformation(SystemBasicPerformanceInformation) in Win 7, and // NtQuerySystemInformation(SystemMemoryUsageInformation) in Win 10 - if (!GlobalMemoryStatusEx(&statex)) + if (!GlobalMemoryStatusEx(&statex)) { return "GlobalMemoryStatusEx() failed"; + } ram->bytesTotal = statex.ullTotalPhys; ram->bytesUsed = statex.ullTotalPhys - statex.ullAvailPhys; diff --git a/src/detection/mouse/mouse.h b/src/detection/mouse/mouse.h index 710b4f8df..3247eeb0d 100644 --- a/src/detection/mouse/mouse.h +++ b/src/detection/mouse/mouse.h @@ -1,7 +1,6 @@ #include "fastfetch.h" -typedef struct FFMouseDevice -{ +typedef struct FFMouseDevice { FFstrbuf serial; FFstrbuf name; } FFMouseDevice; diff --git a/src/detection/mouse/mouse_apple.c b/src/detection/mouse/mouse_apple.c index f7377d364..0dc14a6be 100644 --- a/src/detection/mouse/mouse_apple.c +++ b/src/detection/mouse/mouse_apple.c @@ -5,8 +5,7 @@ #include #include -static void enumSet(IOHIDDeviceRef value, FFlist* results) -{ +static void enumSet(IOHIDDeviceRef value, FFlist* results) { FFMouseDevice* device = (FFMouseDevice*) ffListAdd(results); ffStrbufInit(&device->serial); ffStrbufInit(&device->name); @@ -18,24 +17,19 @@ static void enumSet(IOHIDDeviceRef value, FFlist* results) ffCfStrGetString(serialNumber, &device->serial); } -const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) -{ +const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { IOHIDManagerRef FF_CFTYPE_AUTO_RELEASE manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) + if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { return "IOHIDManagerOpen() failed"; + } - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void **)(CFStringRef[]){ - CFSTR(kIOHIDDeviceUsagePageKey), - CFSTR(kIOHIDDeviceUsageKey) - }, (const void **)(CFNumberRef[]){ - ffCfCreateInt(kHIDPage_GenericDesktop), - ffCfCreateInt(kHIDUsage_GD_Mouse) - }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) {CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey)}, (const void**) (CFNumberRef[]) {ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Mouse)}, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); IOHIDManagerSetDeviceMatching(manager, matching1); CFSetRef FF_CFTYPE_AUTO_RELEASE set = IOHIDManagerCopyDevices(manager); - if (set) + if (set) { CFSetApplyFunction(set, (CFSetApplierFunction) &enumSet, devices); + } IOHIDManagerClose(manager, kIOHIDOptionsTypeNone); return NULL; diff --git a/src/detection/mouse/mouse_bsd.c b/src/detection/mouse/mouse_bsd.c index 3a2977b40..be0a73dae 100644 --- a/src/detection/mouse/mouse_bsd.c +++ b/src/detection/mouse/mouse_bsd.c @@ -6,42 +6,41 @@ #include #if __has_include() -#include // FreeBSD +# include // FreeBSD #else -#include // DragonFly +# include // DragonFly #endif #define MAX_UHID_MICE 64 -const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) -{ +const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { char path[16]; - for (int i = 0; i < MAX_UHID_MICE; i++) - { + for (int i = 0; i < MAX_UHID_MICE; i++) { snprintf(path, ARRAY_SIZE(path), "/dev/uhid%d", i); FF_AUTO_CLOSE_FD int fd = open(path, O_RDONLY | O_CLOEXEC); - if (fd < 0) - { - if (errno == ENOENT) + if (fd < 0) { + if (errno == ENOENT) { break; // No more devices + } continue; // Device not found } report_desc_t repDesc = hid_get_report_desc(fd); - if (!repDesc) continue; + if (!repDesc) { + continue; + } int reportId = hid_get_report_id(fd); struct hid_data* hData = hid_start_parse(repDesc, 0, reportId); - if (hData) - { + if (hData) { struct hid_item hItem; - while (hid_get_item(hData, &hItem) > 0) - { - if (HID_PAGE(hItem.usage) != 1 || HID_USAGE(hItem.usage) != 2) continue; + while (hid_get_item(hData, &hItem) > 0) { + if (HID_PAGE(hItem.usage) != 1 || HID_USAGE(hItem.usage) != 2) { + continue; + } struct usb_device_info di; - if (ioctl(fd, USB_GET_DEVICEINFO, &di) != -1) - { + if (ioctl(fd, USB_GET_DEVICEINFO, &di) != -1) { FFMouseDevice* device = (FFMouseDevice*) ffListAdd(devices); ffStrbufInitS(&device->serial, di.udi_serial); ffStrbufInitS(&device->name, di.udi_product); diff --git a/src/detection/mouse/mouse_haiku.cpp b/src/detection/mouse/mouse_haiku.cpp index 1178a25b3..c89cac281 100644 --- a/src/detection/mouse/mouse_haiku.cpp +++ b/src/detection/mouse/mouse_haiku.cpp @@ -5,18 +5,18 @@ extern "C" { #include #include -const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) -{ +const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { BList list; - if (get_input_devices(&list) != B_OK) + if (get_input_devices(&list) != B_OK) { return "get_input_devices() failed"; + } - for (int32 i = 0, n = list.CountItems(); i < n; i++) - { - BInputDevice *device = (BInputDevice *) list.ItemAt(i); - if (device->Type() != B_POINTING_DEVICE || !device->IsRunning()) + for (int32 i = 0, n = list.CountItems(); i < n; i++) { + BInputDevice* device = (BInputDevice*) list.ItemAt(i); + if (device->Type() != B_POINTING_DEVICE || !device->IsRunning()) { continue; + } FFMouseDevice* item = (FFMouseDevice*) ffListAdd(devices); ffStrbufInit(&item->serial); diff --git a/src/detection/mouse/mouse_linux.c b/src/detection/mouse/mouse_linux.c index 3b2291853..500e65015 100644 --- a/src/detection/mouse/mouse_linux.c +++ b/src/detection/mouse/mouse_linux.c @@ -2,29 +2,29 @@ #include "common/io.h" #include "common/stringUtils.h" -const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) -{ +const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/input/"); - if (dirp == NULL) + if (dirp == NULL) { return "opendir(\"/sys/class/input/\") == NULL"; + } FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/sys/class/input/"); uint32_t baseLen = path.length; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) - { - if (!ffStrStartsWith(entry->d_name, "mouse")) + while ((entry = readdir(dirp)) != NULL) { + if (!ffStrStartsWith(entry->d_name, "mouse")) { continue; - if (!ffCharIsDigit(entry->d_name[strlen("mouse")])) + } + if (!ffCharIsDigit(entry->d_name[strlen("mouse")])) { continue; + } ffStrbufAppendS(&path, entry->d_name); ffStrbufAppendS(&path, "/device/name"); FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); - if (ffAppendFileBuffer(path.chars, &name)) - { + if (ffAppendFileBuffer(path.chars, &name)) { ffStrbufTrimRightSpace(&name); ffStrbufSubstrBefore(&path, path.length - 4); @@ -33,8 +33,9 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) ffStrbufInit(&device->serial); ffStrbufAppendS(&path, "uniq"); - if (ffAppendFileBuffer(path.chars, &device->serial)) + if (ffAppendFileBuffer(path.chars, &device->serial)) { ffStrbufTrimRightSpace(&device->serial); + } } ffStrbufSubstrBefore(&path, baseLen); diff --git a/src/detection/mouse/mouse_nosupport.c b/src/detection/mouse/mouse_nosupport.c index ba5a6c157..d83006c19 100644 --- a/src/detection/mouse/mouse_nosupport.c +++ b/src/detection/mouse/mouse_nosupport.c @@ -1,6 +1,5 @@ #include "mouse.h" -const char* ffDetectMouse(FF_MAYBE_UNUSED FFlist* devices /* List of FFMouseDevice */) -{ +const char* ffDetectMouse(FF_MAYBE_UNUSED FFlist* devices /* List of FFMouseDevice */) { return "No mouse support on this platform"; } diff --git a/src/detection/mouse/mouse_windows.c b/src/detection/mouse/mouse_windows.c index 0bc9b35d2..ade28f1c9 100644 --- a/src/detection/mouse/mouse_windows.c +++ b/src/detection/mouse/mouse_windows.c @@ -10,32 +10,37 @@ #include #include -const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) -{ +const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { UINT nDevices = 0; - if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) + if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) { return "GetRawInputDeviceList(NULL) failed"; - if (nDevices == 0) + } + if (nDevices == 0) { return "No HID devices found"; + } RAWINPUTDEVICELIST* FF_AUTO_FREE pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); - if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) + if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) { return "GetRawInputDeviceList(pRawInputDeviceList) failed"; + } - for (UINT i = 0; i < nDevices; ++i) - { - if (pRawInputDeviceList[i].dwType != RIM_TYPEMOUSE) continue; + for (UINT i = 0; i < nDevices; ++i) { + if (pRawInputDeviceList[i].dwType != RIM_TYPEMOUSE) { + continue; + } HANDLE hDevice = pRawInputDeviceList[i].hDevice; RID_DEVICE_INFO rdi; UINT rdiSize = sizeof(rdi); - if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == (UINT) -1) + if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == (UINT) -1) { continue; + } WCHAR devName[MAX_PATH]; UINT nameSize = MAX_PATH; - if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, devName, &nameSize) == (UINT) -1) + if (GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, devName, &nameSize) == (UINT) -1) { continue; + } FFMouseDevice* device = (FFMouseDevice*) ffListAdd(devices); ffStrbufInit(&device->serial); @@ -44,35 +49,35 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) wchar_t buffer[MAX_PATH]; HANDLE FF_AUTO_CLOSE_FD hHidFile = CreateFileW(devName, 0 /* must be 0 instead of GENERIC_READ */, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - if (hHidFile != INVALID_HANDLE_VALUE) - { - if (HidD_GetProductString(hHidFile, buffer, (ULONG) sizeof(buffer))) + if (hHidFile != INVALID_HANDLE_VALUE) { + if (HidD_GetProductString(hHidFile, buffer, (ULONG) sizeof(buffer))) { ffStrbufSetWS(&device->name, buffer); + } - if (HidD_GetSerialNumberString(hHidFile, buffer, sizeof(buffer))) + if (HidD_GetSerialNumberString(hHidFile, buffer, sizeof(buffer))) { ffStrbufSetWS(&device->serial, buffer); + } } - if (!device->name.length) - { + if (!device->name.length) { // https://stackoverflow.com/a/64321096/9976392 DEVPROPTYPE propertyType; ULONG propertySize = sizeof(buffer); - if (CM_Get_Device_Interface_PropertyW(devName, &DEVPKEY_Device_InstanceId, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) - { + if (CM_Get_Device_Interface_PropertyW(devName, &DEVPKEY_Device_InstanceId, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) { DEVINST devInst; - if (CM_Locate_DevNodeW(&devInst, buffer, CM_LOCATE_DEVNODE_NORMAL) == CR_SUCCESS) - { + if (CM_Locate_DevNodeW(&devInst, buffer, CM_LOCATE_DEVNODE_NORMAL) == CR_SUCCESS) { propertySize = sizeof(buffer); - if (CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_NAME, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) + if (CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_NAME, &propertyType, (PBYTE) buffer, &propertySize, 0) == CR_SUCCESS) { ffStrbufSetWS(&device->name, buffer); + } } } } - if (!device->name.length) + if (!device->name.length) { ffStrbufSetF(&device->name, "Unknown device %04X-%04X", (unsigned) rdi.hid.dwVendorId, (unsigned) rdi.hid.dwProductId); + } } return NULL; diff --git a/src/detection/netio/netio.c b/src/detection/netio/netio.c index 48d6ba7b1..8cb71e1de 100644 --- a/src/detection/netio/netio.c +++ b/src/detection/netio/netio.c @@ -5,65 +5,68 @@ static FFlist ioCounters1; static uint64_t time1; -void ffPrepareNetIO(FFNetIOOptions* options) -{ - if (options->detectTotal) return; +void ffPrepareNetIO(FFNetIOOptions* options) { + if (options->detectTotal) { + return; + } - if (time1 != 0) return; // Already prepared + if (time1 != 0) { + return; // Already prepared + } ffListInit(&ioCounters1, sizeof(FFNetIOResult)); ffNetIOGetIoCounters(&ioCounters1, options); time1 = ffTimeGetNow(); } -const char* ffDetectNetIO(FFlist* result, FFNetIOOptions* options) -{ +const char* ffDetectNetIO(FFlist* result, FFNetIOOptions* options) { const char* error = NULL; - if (options->detectTotal) - { + if (options->detectTotal) { error = ffNetIOGetIoCounters(result, options); - if (error) + if (error) { return error; + } return NULL; } - if (time1 == 0) - { + if (time1 == 0) { ffListInit(&ioCounters1, sizeof(FFNetIOResult)); error = ffNetIOGetIoCounters(&ioCounters1, options); - if (error) + if (error) { return error; + } time1 = ffTimeGetNow(); } - if (ioCounters1.length == 0) + if (ioCounters1.length == 0) { return "No network interfaces found"; + } uint64_t time2 = ffTimeGetNow(); - while (time2 - time1 < options->waitTime) - { + while (time2 - time1 < options->waitTime) { ffTimeSleep((uint32_t) (options->waitTime - (time2 - time1))); time2 = ffTimeGetNow(); } error = ffNetIOGetIoCounters(result, options); - if (error) + if (error) { return error; + } - if (result->length != ioCounters1.length) + if (result->length != ioCounters1.length) { return "Different number of network interfaces. Network change?"; + } - for (uint32_t i = 0; i < result->length; ++i) - { + for (uint32_t i = 0; i < result->length; ++i) { FFNetIOResult* icPrev = FF_LIST_GET(FFNetIOResult, ioCounters1, i); FFNetIOResult* icCurr = FF_LIST_GET(FFNetIOResult, *result, i); - if (!ffStrbufEqual(&icPrev->name, &icCurr->name)) + if (!ffStrbufEqual(&icPrev->name, &icCurr->name)) { return "Network interface name changed"; + } static_assert(sizeof(FFNetIOResult) - offsetof(FFNetIOResult, txBytes) == sizeof(uint64_t) * 8, "Unexpected struct FFNetIOResult layout"); - for (size_t off = offsetof(FFNetIOResult, txBytes); off < sizeof(FFNetIOResult); off += sizeof(uint64_t)) - { + for (size_t off = offsetof(FFNetIOResult, txBytes); off < sizeof(FFNetIOResult); off += sizeof(uint64_t)) { uint64_t* prevValue = (uint64_t*) ((uint8_t*) icPrev + off); uint64_t* currValue = (uint64_t*) ((uint8_t*) icCurr + off); uint64_t temp = *currValue; diff --git a/src/detection/netio/netio.h b/src/detection/netio/netio.h index 47328b432..1e48b53f5 100644 --- a/src/detection/netio/netio.h +++ b/src/detection/netio/netio.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/netio/option.h" -typedef struct FFNetIOResult -{ +typedef struct FFNetIOResult { FFstrbuf name; bool defaultRoute; uint64_t txBytes; diff --git a/src/detection/netio/netio_apple.c b/src/detection/netio/netio_apple.c index 4be331815..c9230f7b6 100644 --- a/src/detection/netio/netio_apple.c +++ b/src/detection/netio/netio_apple.c @@ -7,35 +7,34 @@ #include #include -const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) -{ - int mib[] = {CTL_NET, PF_LINK, NETLINK_GENERIC, - options->defaultRouteOnly ? IFMIB_IFDATA : IFMIB_IFALLDATA, - options->defaultRouteOnly ? (int) ffNetifGetDefaultRouteV4()->ifIndex : 0, - IFDATA_GENERAL}; +const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { + int mib[] = {CTL_NET, PF_LINK, NETLINK_GENERIC, options->defaultRouteOnly ? IFMIB_IFDATA : IFMIB_IFALLDATA, options->defaultRouteOnly ? (int) ffNetifGetDefaultRouteV4()->ifIndex : 0, IFDATA_GENERAL}; size_t bufSize = 0; - if (sysctl(mib, ARRAY_SIZE(mib), NULL, &bufSize, 0, 0) < 0) + if (sysctl(mib, ARRAY_SIZE(mib), NULL, &bufSize, 0, 0) < 0) { return "sysctl(mib, ARRAY_SIZE(mib), NULL, &bufSize, 0, 0) failed"; + } assert(bufSize % sizeof(struct ifmibdata) == 0); FF_AUTO_FREE struct ifmibdata* buf = (struct ifmibdata*) malloc(bufSize); - if (sysctl(mib, ARRAY_SIZE(mib), buf, &bufSize, 0, 0) < 0) + if (sysctl(mib, ARRAY_SIZE(mib), buf, &bufSize, 0, 0) < 0) { return "sysctl(mib, ARRAY_SIZE(mib), buf, &bufSize, 0, 0) failed"; + } size_t ifCount = bufSize / sizeof(struct ifmibdata); const char* defaultRouteIfName = ffNetifGetDefaultRouteV4()->ifName; - for (size_t i = 0; i < ifCount; i++) - { + for (size_t i = 0; i < ifCount; i++) { struct ifmibdata* mibdata = &buf[i]; - if (!(mibdata->ifmd_flags & IFF_RUNNING) || (mibdata->ifmd_flags & IFF_NOARP)) + if (!(mibdata->ifmd_flags & IFF_RUNNING) || (mibdata->ifmd_flags & IFF_NOARP)) { continue; + } - if (options->namePrefix.length && strncmp(mibdata->ifmd_name, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(mibdata->ifmd_name, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } FFNetIOResult* counters = (FFNetIOResult*) ffListAdd(result); *counters = (FFNetIOResult) { diff --git a/src/detection/netio/netio_bsd.c b/src/detection/netio/netio_bsd.c index acea26b72..6e8ac29af 100644 --- a/src/detection/netio/netio_bsd.c +++ b/src/detection/netio/netio_bsd.c @@ -10,31 +10,34 @@ #include #include -const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) -{ +const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteV4()->ifIndex; size_t bufSize = 0; - if (sysctl((int[]) { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, (options->defaultRouteOnly ? (int) defaultRouteIfIndex : 0) }, 6, NULL, &bufSize, 0, 0) < 0) + if (sysctl((int[]) {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, (options->defaultRouteOnly ? (int) defaultRouteIfIndex : 0)}, 6, NULL, &bufSize, 0, 0) < 0) { return "sysctl({ CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, ifIndex }, 6, NULL, &bufSize, 0, 0) failed"; + } FF_AUTO_FREE struct if_msghdr* buf = (struct if_msghdr*) malloc(bufSize); - if (sysctl((int[]) { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, (options->defaultRouteOnly ? (int) defaultRouteIfIndex : 0) }, 6, buf, &bufSize, 0, 0) < 0) + if (sysctl((int[]) {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, (options->defaultRouteOnly ? (int) defaultRouteIfIndex : 0)}, 6, buf, &bufSize, 0, 0) < 0) { return "sysctl({ CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, ifIndex }, 6, buf, &bufSize, 0, 0) failed"; + } for (struct if_msghdr* ifm = buf; ifm < (struct if_msghdr*) ((uint8_t*) buf + bufSize); - ifm = (struct if_msghdr*) ((uint8_t*) ifm + ifm->ifm_msglen)) - { - if (ifm->ifm_type != RTM_IFINFO || !(ifm->ifm_flags & IFF_RUNNING) || (ifm->ifm_flags & IFF_NOARP)) continue; + ifm = (struct if_msghdr*) ((uint8_t*) ifm + ifm->ifm_msglen)) { + if (ifm->ifm_type != RTM_IFINFO || !(ifm->ifm_flags & IFF_RUNNING) || (ifm->ifm_flags & IFF_NOARP)) { + continue; + } struct sockaddr_dl* sdl = (struct sockaddr_dl*) (ifm + 1); assert(sdl->sdl_family == AF_LINK); sdl->sdl_data[sdl->sdl_nlen] = 0; - if (options->namePrefix.length && strncmp(sdl->sdl_data, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(sdl->sdl_data, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } FFNetIOResult* counters = (FFNetIOResult*) ffListAdd(result); *counters = (FFNetIOResult) { @@ -45,11 +48,11 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) .rxPackets = ifm->ifm_data.ifi_ipackets, .txErrors = ifm->ifm_data.ifi_oerrors, .rxErrors = ifm->ifm_data.ifi_ierrors, - #ifdef FF_HAVE_IFI_OQDROPS +#ifdef FF_HAVE_IFI_OQDROPS .txDrops = ifm->ifm_data.ifi_oqdrops, - #else +#else .txDrops = 0, // unsupported - #endif +#endif .rxDrops = ifm->ifm_data.ifi_iqdrops, .defaultRoute = sdl->sdl_index == defaultRouteIfIndex, }; diff --git a/src/detection/netio/netio_haiku.cpp b/src/detection/netio/netio_haiku.cpp index e415a9b21..f7105a1cf 100644 --- a/src/detection/netio/netio_haiku.cpp +++ b/src/detection/netio/netio_haiku.cpp @@ -6,8 +6,7 @@ extern "C" { #include #include -const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) -{ +const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { BNetworkRoster& roster = BNetworkRoster::Default(); BNetworkInterface interface; @@ -15,20 +14,24 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteV4()->ifIndex; - while (roster.GetNextInterface(&cookie, interface) == B_OK) - { - if (!interface.Exists()) + while (roster.GetNextInterface(&cookie, interface) == B_OK) { + if (!interface.Exists()) { continue; + } bool defaultRoute = interface.Index() == defaultRouteIfIndex; - if (options->defaultRouteOnly && !defaultRoute) + if (options->defaultRouteOnly && !defaultRoute) { continue; + } - if (options->namePrefix.length && strncmp(interface.Name(), options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(interface.Name(), options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } ifreq_stats stats = {}; - if (interface.GetStats(stats) != B_OK) continue; + if (interface.GetStats(stats) != B_OK) { + continue; + } FFNetIOResult* counters = (FFNetIOResult*) ffListAdd(result); *counters = (FFNetIOResult) { @@ -41,8 +44,7 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) .rxErrors = stats.receive.errors, .txErrors = stats.send.errors, .rxDrops = stats.receive.dropped, - .txDrops = stats.send.dropped - }; + .txDrops = stats.send.dropped}; } return NULL; diff --git a/src/detection/netio/netio_linux.c b/src/detection/netio/netio_linux.c index 60a2f6993..72add989f 100644 --- a/src/detection/netio/netio_linux.c +++ b/src/detection/netio/netio_linux.c @@ -7,72 +7,81 @@ #include #include -static void getData(FFstrbuf* buffer, const char* ifName, bool isDefaultRoute, int basefd, FFlist* result) -{ +static void getData(FFstrbuf* buffer, const char* ifName, bool isDefaultRoute, int basefd, FFlist* result) { FF_AUTO_CLOSE_FD int dfd = openat(basefd, ifName, O_RDONLY | O_DIRECTORY); - if (dfd < 0) + if (dfd < 0) { return; + } char operstate; - if(!ffReadFileDataRelative(dfd, "operstate", 1, &operstate) || operstate != 'u' /* up or unknown */) + if (!ffReadFileDataRelative(dfd, "operstate", 1, &operstate) || operstate != 'u' /* up or unknown */) { return; + } FFNetIOResult* counters = (FFNetIOResult*) ffListAdd(result); ffStrbufInitS(&counters->name, ifName); counters->defaultRoute = isDefaultRoute; - if (ffReadFileBufferRelative(dfd, "statistics/rx_bytes", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/rx_bytes", buffer)) { counters->rxBytes = ffStrbufToUInt(buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "statistics/tx_bytes", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/tx_bytes", buffer)) { counters->txBytes = ffStrbufToUInt(buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "statistics/rx_packets", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/rx_packets", buffer)) { counters->rxPackets = ffStrbufToUInt(buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "statistics/tx_packets", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/tx_packets", buffer)) { counters->txPackets = ffStrbufToUInt(buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "statistics/rx_errors", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/rx_errors", buffer)) { counters->rxErrors = ffStrbufToUInt(buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "statistics/tx_errors", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/tx_errors", buffer)) { counters->txErrors = ffStrbufToUInt(buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "statistics/rx_dropped", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/rx_dropped", buffer)) { counters->rxDrops = ffStrbufToUInt(buffer, 0); + } - if (ffReadFileBufferRelative(dfd, "statistics/tx_dropped", buffer)) + if (ffReadFileBufferRelative(dfd, "statistics/tx_dropped", buffer)) { counters->txDrops = ffStrbufToUInt(buffer, 0); + } } -const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) -{ +const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/net"); - if (!dirp) return "opendir(\"/sys/class/net\") == NULL"; + if (!dirp) { + return "opendir(\"/sys/class/net\") == NULL"; + } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); const char* defaultRouteIfName = ffNetifGetDefaultRouteV4()->ifName; - if (options->defaultRouteOnly) - { - if (options->namePrefix.length && strncmp(defaultRouteIfName, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->defaultRouteOnly) { + if (options->namePrefix.length && strncmp(defaultRouteIfName, options->namePrefix.chars, options->namePrefix.length) != 0) { return NULL; + } - getData(&buffer, defaultRouteIfName, true, dirfd(dirp), result); - } - else - { + getData(&buffer, defaultRouteIfName, true, dirfd(dirp), result); + } else { struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { + while ((entry = readdir(dirp)) != NULL) { const char* ifName = entry->d_name; - if(ifName[0] == '.') + if (ifName[0] == '.') { continue; + } - if (options->namePrefix.length && strncmp(ifName, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(ifName, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } getData(&buffer, ifName, ffStrEquals(ifName, defaultRouteIfName), dirfd(dirp), result); } diff --git a/src/detection/netio/netio_nosupport.c b/src/detection/netio/netio_nosupport.c index be9a30b6c..fedfd2d5d 100644 --- a/src/detection/netio/netio_nosupport.c +++ b/src/detection/netio/netio_nosupport.c @@ -1,6 +1,5 @@ #include "netio.h" -const char* ffNetIOGetIoCounters(FF_MAYBE_UNUSED FFlist* result, FF_MAYBE_UNUSED FFNetIOOptions* options) -{ +const char* ffNetIOGetIoCounters(FF_MAYBE_UNUSED FFlist* result, FF_MAYBE_UNUSED FFNetIOOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/netio/netio_sunos.c b/src/detection/netio/netio_sunos.c index 461e69c2e..ef6047ceb 100644 --- a/src/detection/netio/netio_sunos.c +++ b/src/detection/netio/netio_sunos.c @@ -4,34 +4,38 @@ #include -static inline void kstatFreeWrap(kstat_ctl_t** pkc) -{ +static inline void kstatFreeWrap(kstat_ctl_t** pkc) { assert(pkc); - if (*pkc) + if (*pkc) { kstat_close(*pkc); + } } -const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) -{ +const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { __attribute__((__cleanup__(kstatFreeWrap))) kstat_ctl_t* kc = kstat_open(); - if (!kc) + if (!kc) { return "kstat_open() failed"; + } const char* defaultRouteIfName = ffNetifGetDefaultRouteV4()->ifName; - for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next) - { - if (!ffStrEquals(ks->ks_class, "net") || !ffStrEquals(ks->ks_module, "link")) continue; - - if (options->namePrefix.length && strncmp(ks->ks_name, options->namePrefix.chars, options->namePrefix.length) != 0) + for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next) { + if (!ffStrEquals(ks->ks_class, "net") || !ffStrEquals(ks->ks_module, "link")) { continue; + } + + if (options->namePrefix.length && strncmp(ks->ks_name, options->namePrefix.chars, options->namePrefix.length) != 0) { + continue; + } bool isDefaultRoute = ffStrEquals(ks->ks_name, defaultRouteIfName); - if (options->defaultRouteOnly && !isDefaultRoute) + if (options->defaultRouteOnly && !isDefaultRoute) { continue; + } - if (kstat_read(kc, ks, NULL) < 0) + if (kstat_read(kc, ks, NULL) < 0) { continue; + } FFNetIOResult* counters = (FFNetIOResult*) ffListAdd(result); @@ -55,8 +59,9 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) .defaultRoute = isDefaultRoute, }; - if (options->defaultRouteOnly) + if (options->defaultRouteOnly) { break; + } } return NULL; diff --git a/src/detection/netio/netio_windows.c b/src/detection/netio/netio_windows.c index 37b4dff33..4f30bc848 100644 --- a/src/detection/netio/netio_windows.c +++ b/src/detection/netio/netio_windows.c @@ -7,18 +7,15 @@ #include #include -const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) -{ +const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { IP_ADAPTER_ADDRESSES* FF_AUTO_FREE adapter_addresses = NULL; // Multiple attempts in case interfaces change while // we are in the middle of querying them. DWORD adapter_addresses_buffer_size = 0; - for (int attempts = 0;; ++attempts) - { - if (adapter_addresses_buffer_size) - { - adapter_addresses = (IP_ADAPTER_ADDRESSES*)realloc(adapter_addresses, adapter_addresses_buffer_size); + for (int attempts = 0;; ++attempts) { + if (adapter_addresses_buffer_size) { + adapter_addresses = (IP_ADAPTER_ADDRESSES*) realloc(adapter_addresses, adapter_addresses_buffer_size); assert(adapter_addresses); } @@ -29,30 +26,31 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) adapter_addresses, &adapter_addresses_buffer_size); - if (error == ERROR_SUCCESS) + if (error == ERROR_SUCCESS) { break; - else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4) + } else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4) { continue; - else + } else { return "GetAdaptersAddresses() failed"; + } } uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteV4()->ifIndex; // Iterate through all of the adapters - for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next) - { + for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next) { bool isDefaultRoute = adapter->IfIndex == defaultRouteIfIndex; - if (options->defaultRouteOnly && !isDefaultRoute) + if (options->defaultRouteOnly && !isDefaultRoute) { continue; + } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateWS(adapter->FriendlyName); - if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) + if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) { continue; + } - MIB_IF_ROW2 ifRow = { .InterfaceIndex = adapter->IfIndex }; - if (GetIfEntry2(&ifRow) == NO_ERROR) - { + MIB_IF_ROW2 ifRow = {.InterfaceIndex = adapter->IfIndex}; + if (GetIfEntry2(&ifRow) == NO_ERROR) { FFNetIOResult* counters = (FFNetIOResult*) ffListAdd(result); *counters = (FFNetIOResult) { .name = ffStrbufCreateMove(&name), diff --git a/src/detection/opencl/opencl.c b/src/detection/opencl/opencl.c index da67587d5..94ef321c5 100644 --- a/src/detection/opencl/opencl.c +++ b/src/detection/opencl/opencl.c @@ -2,46 +2,42 @@ #include "detection/gpu/gpu.h" #if !defined(FF_HAVE_OPENCL) && defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_15) - #define FF_HAVE_OPENCL 1 +# define FF_HAVE_OPENCL 1 #endif #ifdef FF_HAVE_OPENCL -#include "common/library.h" -#include "common/parsing.h" -#include "common/stringUtils.h" -#include +# include "common/library.h" +# include "common/parsing.h" +# include "common/stringUtils.h" +# include -#define CL_TARGET_OPENCL_VERSION 110 -#ifndef __APPLE__ - #include - #include -#else - #include - #include -#endif +# define CL_TARGET_OPENCL_VERSION 110 +# ifndef __APPLE__ +# include +# include +# else +# include +# include +# endif -typedef struct OpenCLData -{ +typedef struct OpenCLData { FF_LIBRARY_SYMBOL(clGetPlatformIDs) FF_LIBRARY_SYMBOL(clGetPlatformInfo) FF_LIBRARY_SYMBOL(clGetDeviceInfo) FF_LIBRARY_SYMBOL(clGetDeviceIDs) } OpenCLData; -static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) -{ +static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { cl_platform_id platforms[32]; cl_uint numPlatforms = 0; cl_int ret = data->ffclGetPlatformIDs(ARRAY_SIZE(platforms), platforms, &numPlatforms); - if (ret != CL_SUCCESS) - { - switch (ret) - { - #ifdef CL_PLATFORM_NOT_FOUND_KHR // not available on macOS + if (ret != CL_SUCCESS) { + switch (ret) { +# ifdef CL_PLATFORM_NOT_FOUND_KHR // not available on macOS case CL_PLATFORM_NOT_FOUND_KHR: return "clGetPlatformIDs() failed: CL_PLATFORM_NOT_FOUND_KHR"; - #endif +# endif case CL_INVALID_VALUE: return "clGetPlatformIDs() failed: CL_INVALID_VALUE"; case CL_OUT_OF_HOST_MEMORY: @@ -51,41 +47,45 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) } } - if (numPlatforms == 0) + if (numPlatforms == 0) { return "clGetPlatformIDs returned 0 platforms"; + } char buffer[1024]; - for (cl_uint iplat = 0; iplat < numPlatforms; ++iplat) - { - if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VERSION, sizeof(buffer), buffer, NULL) != CL_SUCCESS) + for (cl_uint iplat = 0; iplat < numPlatforms; ++iplat) { + if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VERSION, sizeof(buffer), buffer, NULL) != CL_SUCCESS) { return "clGetPlatformInfo() failed"; + } // Use the newest supported OpenCL version - if (ffStrbufCompS(&result->version, buffer) < 0) - { + if (ffStrbufCompS(&result->version, buffer) < 0) { const char* versionPretty = buffer; - if(ffStrStartsWithIgnCase(buffer, "OpenCL ")) + if (ffStrStartsWithIgnCase(buffer, "OpenCL ")) { versionPretty = buffer + strlen("OpenCL "); + } ffStrbufSetS(&result->version, versionPretty); ffStrbufTrim(&result->version, ' '); - if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_NAME, sizeof(buffer), buffer, NULL) == CL_SUCCESS) + if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_NAME, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { ffStrbufSetS(&result->name, buffer); + } - if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VENDOR, sizeof(buffer), buffer, NULL) == CL_SUCCESS) + if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VENDOR, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { ffStrbufSetS(&result->vendor, buffer); + } } cl_device_id deviceIDs[32]; cl_uint numDevices = (cl_uint) ARRAY_SIZE(deviceIDs); - if (data->ffclGetDeviceIDs(platforms[iplat], CL_DEVICE_TYPE_GPU, numDevices, deviceIDs, &numDevices) != CL_SUCCESS) + if (data->ffclGetDeviceIDs(platforms[iplat], CL_DEVICE_TYPE_GPU, numDevices, deviceIDs, &numDevices) != CL_SUCCESS) { continue; + } - for (cl_uint idev = 0; idev < numDevices; ++idev) - { + for (cl_uint idev = 0; idev < numDevices; ++idev) { cl_device_id deviceID = deviceIDs[idev]; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_NAME, sizeof(buffer), buffer, NULL) != CL_SUCCESS) + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_NAME, sizeof(buffer), buffer, NULL) != CL_SUCCESS) { continue; + } FFGPUResult* gpu = ffListAdd(&result->gpus); ffStrbufInitS(&gpu->name, buffer); @@ -102,56 +102,58 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) gpu->frequency = FF_GPU_FREQUENCY_UNSET; gpu->coreUsage = FF_GPU_CORE_USAGE_UNSET; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VERSION, sizeof(buffer), buffer, NULL) == CL_SUCCESS) - { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VERSION, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { ffStrbufSetS(&gpu->platformApi, buffer); ffStrbufTrimRight(&gpu->platformApi, ' '); - } - else + } else { ffStrbufSetStatic(&gpu->platformApi, "OpenCL"); + } { cl_uint vendorId; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR_ID, sizeof(vendorId), &vendorId, NULL) == CL_SUCCESS) + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR_ID, sizeof(vendorId), &vendorId, NULL) == CL_SUCCESS) { ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(vendorId)); - if (gpu->vendor.length == 0 && data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR, sizeof(buffer), buffer, NULL) == CL_SUCCESS) + } + if (gpu->vendor.length == 0 && data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { ffStrbufSetS(&gpu->vendor, buffer); + } } - if (data->ffclGetDeviceInfo(deviceID, CL_DRIVER_VERSION, sizeof(buffer), buffer, NULL) == CL_SUCCESS) - { + if (data->ffclGetDeviceInfo(deviceID, CL_DRIVER_VERSION, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { const char* versionPretty = strchr(buffer, ' '); - if (versionPretty && *versionPretty) + if (versionPretty && *versionPretty) { ffStrbufSetS(&gpu->driver, versionPretty + 1); - else + } else { ffStrbufSetS(&gpu->driver, buffer); + } } { cl_uint value; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(value), &value, NULL) == CL_SUCCESS) + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(value), &value, NULL) == CL_SUCCESS) { gpu->coreCount = (int32_t) value; + } } { cl_uint value; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(value), &value, NULL) == CL_SUCCESS) + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(value), &value, NULL) == CL_SUCCESS) { gpu->frequency = value; + } } { cl_bool value; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(value), &value, NULL) == CL_SUCCESS) - { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(value), &value, NULL) == CL_SUCCESS) { gpu->type = value ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; cl_ulong memSize; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(memSize), &memSize, NULL) == CL_SUCCESS) - { - if (gpu->type == FF_GPU_TYPE_INTEGRATED) + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(memSize), &memSize, NULL) == CL_SUCCESS) { + if (gpu->type == FF_GPU_TYPE_INTEGRATED) { gpu->shared.total = memSize; - else + } else { gpu->dedicated.total = memSize; + } } } } @@ -161,18 +163,18 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) return NULL; } -static const char* detectOpenCL(FFOpenCLResult* result) -{ +static const char* detectOpenCL(FFOpenCLResult* result) { OpenCLData data; - #ifndef __APPLE__ +# ifndef __APPLE__ FF_LIBRARY_LOAD_MESSAGE(opencl, - #ifdef _WIN32 - "OpenCL" FF_LIBRARY_EXTENSION, -1, - #endif - "libOpenCL" FF_LIBRARY_EXTENSION, 1 - ); +# ifdef _WIN32 + "OpenCL" FF_LIBRARY_EXTENSION, + -1, +# endif + "libOpenCL" FF_LIBRARY_EXTENSION, + 1); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(opencl, data, clGetPlatformIDs); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(opencl, data, clGetPlatformInfo); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(opencl, data, clGetDeviceIDs); @@ -180,7 +182,7 @@ static const char* detectOpenCL(FFOpenCLResult* result) return openCLHandleData(&data, result); - #else +# else data.ffclGetPlatformIDs = clGetPlatformIDs; data.ffclGetPlatformInfo = clGetPlatformInfo; @@ -189,27 +191,25 @@ static const char* detectOpenCL(FFOpenCLResult* result) return openCLHandleData(&data, result); - #endif +# endif } #endif // defined(FF_HAVE_OPENCL) -FFOpenCLResult* ffDetectOpenCL(void) -{ +FFOpenCLResult* ffDetectOpenCL(void) { static FFOpenCLResult result; - if (result.gpus.elementSize == 0) - { + if (result.gpus.elementSize == 0) { ffStrbufInit(&result.version); ffStrbufInit(&result.name); ffStrbufInit(&result.vendor); ffListInit(&result.gpus, sizeof(FFGPUResult)); - #ifdef FF_HAVE_OPENCL - result.error = detectOpenCL(&result); - #else - result.error = "fastfetch was compiled without OpenCL support"; - #endif +#ifdef FF_HAVE_OPENCL + result.error = detectOpenCL(&result); +#else + result.error = "fastfetch was compiled without OpenCL support"; +#endif } return &result; diff --git a/src/detection/opencl/opencl.h b/src/detection/opencl/opencl.h index c7d6ddb96..d96eb5080 100644 --- a/src/detection/opencl/opencl.h +++ b/src/detection/opencl/opencl.h @@ -3,12 +3,11 @@ #include "fastfetch.h" #include "modules/opencl/option.h" -typedef struct FFOpenCLResult -{ +typedef struct FFOpenCLResult { FFstrbuf version; FFstrbuf name; FFstrbuf vendor; - FFlist gpus; //List of FFGPUResult, see detection/gpu/gpu.h + FFlist gpus; // List of FFGPUResult, see detection/gpu/gpu.h const char* error; } FFOpenCLResult; diff --git a/src/detection/opengl/opengl.h b/src/detection/opengl/opengl.h index 5dbf2e392..f7ff9d5ea 100644 --- a/src/detection/opengl/opengl.h +++ b/src/detection/opengl/opengl.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/opengl/option.h" -typedef struct FFOpenGLResult -{ +typedef struct FFOpenGLResult { FFstrbuf version; FFstrbuf renderer; FFstrbuf vendor; diff --git a/src/detection/opengl/opengl_apple.c b/src/detection/opengl/opengl_apple.c index 63751d6b8..b12e02a26 100644 --- a/src/detection/opengl/opengl_apple.c +++ b/src/detection/opengl/opengl_apple.c @@ -8,10 +8,10 @@ void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); -static const char* cglHandleContext(FFOpenGLResult* result, CGLContextObj context) -{ - if(CGLSetCurrentContext(context) != kCGLNoError) +static const char* cglHandleContext(FFOpenGLResult* result, CGLContextObj context) { + if (CGLSetCurrentContext(context) != kCGLNoError) { return "CGLSetCurrentContext() failed"; + } ffOpenGLHandleResult(result, &glGetString); @@ -22,49 +22,44 @@ static const char* cglHandleContext(FFOpenGLResult* result, CGLContextObj contex return NULL; } -static const char* cglHandlePixelFormat(FFOpenGLResult* result, CGLPixelFormatObj pixelFormat) -{ +static const char* cglHandlePixelFormat(FFOpenGLResult* result, CGLPixelFormatObj pixelFormat) { CGLContextObj context; - if(CGLCreateContext(pixelFormat, NULL, &context) != kCGLNoError) + if (CGLCreateContext(pixelFormat, NULL, &context) != kCGLNoError) { return "CGLCreateContext() failed"; + } const char* error = cglHandleContext(result, context); CGLDestroyContext(context); return error; } -const char* cglDetectOpenGL(FFOpenGLResult* result) -{ +const char* cglDetectOpenGL(FFOpenGLResult* result) { CGLPixelFormatObj pixelFormat; CGLPixelFormatAttribute attrs[] = { - kCGLPFAOpenGLProfile, (CGLPixelFormatAttribute) kCGLOGLPVersion_3_2_Core, - kCGLPFAAccelerated, - 0 - }; + kCGLPFAOpenGLProfile, (CGLPixelFormatAttribute) kCGLOGLPVersion_3_2_Core, kCGLPFAAccelerated, 0}; GLint num; - if (CGLChoosePixelFormat(attrs, &pixelFormat, &num) != kCGLNoError) + if (CGLChoosePixelFormat(attrs, &pixelFormat, &num) != kCGLNoError) { return "CGLChoosePixelFormat() failed"; + } const char* error = cglHandlePixelFormat(result, pixelFormat); CGLDestroyPixelFormat(pixelFormat); return error; } -const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) -{ - if (options->library == FF_OPENGL_LIBRARY_AUTO) +const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) { + if (options->library == FF_OPENGL_LIBRARY_AUTO) { return cglDetectOpenGL(result); - else if (options->library == FF_OPENGL_LIBRARY_EGL) - { - #if __has_include() - const char* ffOpenGLDetectByEGL(FFOpenGLResult* result); + } else if (options->library == FF_OPENGL_LIBRARY_EGL) { +#if __has_include() + const char* ffOpenGLDetectByEGL(FFOpenGLResult * result); return ffOpenGLDetectByEGL(result); - #else +#else return "fastfetch was compiled without egl support"; - #endif - } - else +#endif + } else { return "Unsupported OpenGL library"; + } } diff --git a/src/detection/opengl/opengl_haiku.cpp b/src/detection/opengl/opengl_haiku.cpp index c7301786f..64a21a0d5 100644 --- a/src/detection/opengl/opengl_haiku.cpp +++ b/src/detection/opengl/opengl_haiku.cpp @@ -9,31 +9,30 @@ const char* ffOpenGLDetectByEGL(FFOpenGLResult* result); void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); } -static const char* oglDetectOpenGL(FFOpenGLResult* result) -{ +static const char* oglDetectOpenGL(FFOpenGLResult* result) { BApplication app("application/x-vnd.fastfetch-cli-fastfetch"); FF_SUPPRESS_IO(); BGLView glView(BRect(), "ff_ogl_view", B_FOLLOW_NONE, B_WILL_DRAW, BGL_RGB); auto ffglGetString = (decltype(&glGetString)) glView.GetGLProcAddress("glGetString"); - if (!ffglGetString) return "glView.GetGLProcAddress() failed"; + if (!ffglGetString) { + return "glView.GetGLProcAddress() failed"; + } ffOpenGLHandleResult(result, ffglGetString); ffStrbufSetStatic(&result->library, "OpenGLKit"); return NULL; } -const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) -{ - if (options->library == FF_OPENGL_LIBRARY_AUTO) +const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) { + if (options->library == FF_OPENGL_LIBRARY_AUTO) { return oglDetectOpenGL(result); - else if (options->library == FF_OPENGL_LIBRARY_EGL) - { - #if FF_HAVE_EGL + } else if (options->library == FF_OPENGL_LIBRARY_EGL) { +#if FF_HAVE_EGL return ffOpenGLDetectByEGL(result); - #else +#else return "fastfetch was compiled without egl support"; - #endif - } - else +#endif + } else { return "Unsupported OpenGL library"; + } } diff --git a/src/detection/opengl/opengl_linux.c b/src/detection/opengl/opengl_linux.c index 8222a8034..308a6f888 100644 --- a/src/detection/opengl/opengl_linux.c +++ b/src/detection/opengl/opengl_linux.c @@ -5,28 +5,27 @@ #include #if __ANDROID__ && !defined(FF_HAVE_EGL) - // On Android, installing OpenGL headers is enough (mesa-dev) - #if __has_include() - #define FF_HAVE_EGL 1 - #endif +// On Android, installing OpenGL headers is enough (mesa-dev) +# if __has_include() +# define FF_HAVE_EGL 1 +# endif #endif #if defined(FF_HAVE_EGL) || defined(FF_HAVE_GLX) -#define FF_HAVE_GL 1 +# define FF_HAVE_GL 1 -#include "common/library.h" +# include "common/library.h" -#include +# include void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); #endif // FF_HAVE_GL #ifdef FF_HAVE_GLX -#include +# include -typedef struct GLXData -{ +typedef struct GLXData { FF_LIBRARY_SYMBOL(glGetString) FF_LIBRARY_SYMBOL(glXGetProcAddress) FF_LIBRARY_SYMBOL(glXQueryVersion) @@ -49,91 +48,93 @@ typedef struct GLXData GLXContext context; } GLXData; -static const char* glxHandleContext(FFOpenGLResult* result, GLXData* data) -{ - if(data->ffglXMakeCurrent(data->display, data->glxPixmap, data->context) != True) +static const char* glxHandleContext(FFOpenGLResult* result, GLXData* data) { + if (data->ffglXMakeCurrent(data->display, data->glxPixmap, data->context) != True) { return "glXMakeCurrent returned False"; + } ffOpenGLHandleResult(result, data->ffglGetString); int major, minor; - if (data->ffglXQueryVersion(data->display, &major, &minor)) + if (data->ffglXQueryVersion(data->display, &major, &minor)) { ffStrbufSetF(&result->library, "GLX %d.%d", major, minor); - else + } else { ffStrbufSetStatic(&result->library, "GLX"); + } return NULL; } -static const char* glxHandleGLXPixmap(FFOpenGLResult* result, GLXData* data) -{ +static const char* glxHandleGLXPixmap(FFOpenGLResult* result, GLXData* data) { data->context = data->ffglXCreateContext(data->display, data->visualInfo, NULL, True); - if(data->context == NULL) + if (data->context == NULL) { return "glXCreateContext returned NULL"; + } const char* error = glxHandleContext(result, data); data->ffglXDestroyContext(data->display, data->context); return error; } -static const char* glxHandlePixmap(FFOpenGLResult* result, GLXData* data) -{ +static const char* glxHandlePixmap(FFOpenGLResult* result, GLXData* data) { data->glxPixmap = data->ffglXCreateGLXPixmap(data->display, data->visualInfo, data->pixmap); - if(data->glxPixmap == None) + if (data->glxPixmap == None) { return "glXCreateGLXPixmap returned None"; + } const char* error = glxHandleGLXPixmap(result, data); data->ffglXDestroyGLXPixmap(data->display, data->glxPixmap); return error; } -static const char* glxHandleVisualInfo(FFOpenGLResult* result, GLXData* data) -{ +static const char* glxHandleVisualInfo(FFOpenGLResult* result, GLXData* data) { data->pixmap = data->ffXCreatePixmap(data->display, DefaultRootWindow(data->display), FF_OPENGL_BUFFER_WIDTH, FF_OPENGL_BUFFER_HEIGHT, (unsigned int) data->visualInfo->depth); - if(data->pixmap == None) + if (data->pixmap == None) { return "XCreatePixmap returned None"; + } const char* error = glxHandlePixmap(result, data); data->ffXFreePixmap(data->display, data->pixmap); return error; } -static const char* glxHandleDisplay(FFOpenGLResult* result, GLXData* data) -{ - data->visualInfo = data->ffglXChooseVisual(data->display, DefaultScreen(data->display), (int[]){None}); - if(data->visualInfo == NULL) +static const char* glxHandleDisplay(FFOpenGLResult* result, GLXData* data) { + data->visualInfo = data->ffglXChooseVisual(data->display, DefaultScreen(data->display), (int[]) {None}); + if (data->visualInfo == NULL) { return "glXChooseVisual returned NULL"; + } const char* error = glxHandleVisualInfo(result, data); data->ffXFree(data->visualInfo); return error; } -static const char* glxHandleData(FFOpenGLResult* result, GLXData* data) -{ +static const char* glxHandleData(FFOpenGLResult* result, GLXData* data) { data->ffglGetString = (__typeof__(data->ffglGetString)) data->ffglXGetProcAddress((const GLubyte*) "glGetString"); - if(data->ffglGetString == NULL) + if (data->ffglGetString == NULL) { return "glXGetProcAddress(glGetString) returned NULL"; + } data->display = data->ffXOpenDisplay(NULL); - if(data->display == NULL) + if (data->display == NULL) { return "XOpenDisplay returned NULL"; + } const char* error = glxHandleDisplay(result, data); data->ffXCloseDisplay(data->display); return error; } -static const char* detectByGlx(FFOpenGLResult* result) -{ +static const char* detectByGlx(FFOpenGLResult* result) { GLXData data; FF_LIBRARY_LOAD_MESSAGE(glx, - #if !__OpenBSD__ && !__NetBSD__ - "libGLX" - #else - "libGL" - #endif - FF_LIBRARY_EXTENSION, 1); +# if !__OpenBSD__ && !__NetBSD__ + "libGLX" +# else + "libGL" +# endif + FF_LIBRARY_EXTENSION, + 1); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(glx, data, glXGetProcAddress); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(glx, data, glXQueryVersion); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(glx, data, XOpenDisplay); @@ -153,49 +154,47 @@ static const char* detectByGlx(FFOpenGLResult* result) return glxHandleData(result, &data); } -#endif //FF_HAVE_GLX +#endif // FF_HAVE_GLX -const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) -{ - #if FF_HAVE_GL +const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) { +#if FF_HAVE_GL - if(options->library == FF_OPENGL_LIBRARY_GLX) - { - #ifdef FF_HAVE_GLX - return detectByGlx(result); - #else - return "fastfetch was compiled without glx support"; - #endif + if (options->library == FF_OPENGL_LIBRARY_GLX) { +# ifdef FF_HAVE_GLX + return detectByGlx(result); +# else + return "fastfetch was compiled without glx support"; +# endif } - if(options->library == FF_OPENGL_LIBRARY_EGL) - { - #ifdef FF_HAVE_EGL - const char* ffOpenGLDetectByEGL(FFOpenGLResult* result); - return ffOpenGLDetectByEGL(result); - #else - return "fastfetch was compiled without egl support"; - #endif + if (options->library == FF_OPENGL_LIBRARY_EGL) { +# ifdef FF_HAVE_EGL + const char* ffOpenGLDetectByEGL(FFOpenGLResult * result); + return ffOpenGLDetectByEGL(result); +# else + return "fastfetch was compiled without egl support"; +# endif } const char* error = ""; // not NULL dummy value - #ifdef FF_HAVE_EGL - const char* ffOpenGLDetectByEGL(FFOpenGLResult* result); - error = ffOpenGLDetectByEGL(result); - #endif +# ifdef FF_HAVE_EGL + const char* ffOpenGLDetectByEGL(FFOpenGLResult * result); + error = ffOpenGLDetectByEGL(result); +# endif - #ifdef FF_HAVE_GLX - if(error != NULL) - error = detectByGlx(result); - #endif +# ifdef FF_HAVE_GLX + if (error != NULL) { + error = detectByGlx(result); + } +# endif return error; - #else +#else - FF_UNUSED(options, result); - return "Fastfetch was built without gl support."; + FF_UNUSED(options, result); + return "Fastfetch was built without gl support."; - #endif //FF_HAVE_GL +#endif // FF_HAVE_GL } diff --git a/src/detection/opengl/opengl_shared.c b/src/detection/opengl/opengl_shared.c index a3ee920f3..9113c16b9 100644 --- a/src/detection/opengl/opengl_shared.c +++ b/src/detection/opengl/opengl_shared.c @@ -3,38 +3,36 @@ #include "common/library.h" #if __has_include() -#include +# include #elif __APPLE__ -#define GL_SILENCE_DEPRECATION 1 -#include +# define GL_SILENCE_DEPRECATION 1 +# include #else -#define FF_HAVE_NO_GL 1 +# define FF_HAVE_NO_GL 1 #endif #ifndef FF_HAVE_NO_GL -#ifndef GL_SHADING_LANGUAGE_VERSION // For WGL - #define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#endif +# ifndef GL_SHADING_LANGUAGE_VERSION // For WGL +# define GL_SHADING_LANGUAGE_VERSION 0x8B8C +# endif -void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString) -{ +void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString) { ffStrbufAppendS(&result->version, (const char*) ffglGetString(GL_VERSION)); ffStrbufAppendS(&result->renderer, (const char*) ffglGetString(GL_RENDERER)); ffStrbufAppendS(&result->vendor, (const char*) ffglGetString(GL_VENDOR)); ffStrbufAppendS(&result->slv, (const char*) ffglGetString(GL_SHADING_LANGUAGE_VERSION)); } -#if defined(FF_HAVE_EGL) || __has_include() -#include "common/io.h" +# if defined(FF_HAVE_EGL) || __has_include() +# include "common/io.h" -#define EGL_EGL_PROTOTYPES 1 -#define EGL_EGLEXT_PROTOTYPES 1 -#include -#include +# define EGL_EGL_PROTOTYPES 1 +# define EGL_EGLEXT_PROTOTYPES 1 +# include +# include -typedef struct EGLData -{ +typedef struct EGLData { FF_LIBRARY_SYMBOL(glGetString) FF_LIBRARY_SYMBOL(eglGetProcAddress) FF_LIBRARY_SYMBOL(eglGetDisplay) @@ -55,11 +53,9 @@ typedef struct EGLData EGLContext context; } EGLData; -static const char* eglHandleContext(FFOpenGLResult* result, EGLData* data) -{ +static const char* eglHandleContext(FFOpenGLResult* result, EGLData* data) { FF_DEBUG("Making EGL context current"); - if(data->ffeglMakeCurrent(data->display, data->surface, data->surface, data->context) != EGL_TRUE) - { + if (data->ffeglMakeCurrent(data->display, data->surface, data->surface, data->context) != EGL_TRUE) { FF_DEBUG("eglMakeCurrent() returned EGL_FALSE"); return "eglMakeCurrent returned EGL_FALSE"; } @@ -75,20 +71,16 @@ static const char* eglHandleContext(FFOpenGLResult* result, EGLData* data) return NULL; } -static const char* eglHandleSurface(FFOpenGLResult* result, EGLData* data, bool gles) -{ +static const char* eglHandleSurface(FFOpenGLResult* result, EGLData* data, bool gles) { FF_DEBUG("Creating EGL context (preferred API=%s, client version=%d)", gles ? "OpenGL ES" : "OpenGL", gles ? 2 : 1); - data->context = data->ffeglCreateContext(data->display, data->config, EGL_NO_CONTEXT, (EGLint[]){ - EGL_CONTEXT_CLIENT_VERSION, gles ? 2 : 1, // Try GLES 2.0+ first - EGL_NONE - }); - if(data->context == EGL_NO_CONTEXT && gles) // Some ANGLE builds support GLES 1.1 only + data->context = data->ffeglCreateContext(data->display, data->config, EGL_NO_CONTEXT, (EGLint[]) {EGL_CONTEXT_CLIENT_VERSION, gles ? 2 : 1, // Try GLES 2.0+ first + EGL_NONE}); + if (data->context == EGL_NO_CONTEXT && gles) // Some ANGLE builds support GLES 1.1 only { FF_DEBUG("EGL context creation with GLES 2.x failed, retrying with default attributes (GLES 1.1 fallback)"); - data->context = data->ffeglCreateContext(data->display, data->config, EGL_NO_CONTEXT, (EGLint[]){EGL_NONE}); + data->context = data->ffeglCreateContext(data->display, data->config, EGL_NO_CONTEXT, (EGLint[]) {EGL_NONE}); } - if(data->context == EGL_NO_CONTEXT) - { + if (data->context == EGL_NO_CONTEXT) { FF_DEBUG("eglCreateContext() returned EGL_NO_CONTEXT"); return "eglCreateContext returned EGL_NO_CONTEXT"; } @@ -106,8 +98,7 @@ static const char* eglHandleSurface(FFOpenGLResult* result, EGLData* data, bool return error; } -static const char* eglHandleDisplay(FFOpenGLResult* result, EGLData* data) -{ +static const char* eglHandleDisplay(FFOpenGLResult* result, EGLData* data) { // try use OpenGL API. If failed, use the default API (usually OpenGL ES) bool gles = !data->ffeglBindAPI(EGL_OPENGL_API); FF_DEBUG("eglBindAPI(EGL_OPENGL_API) %s, effective API=%s", @@ -118,21 +109,15 @@ static const char* eglHandleDisplay(FFOpenGLResult* result, EGLData* data) data->ffeglGetConfigs(data->display, &data->config, 1, &eglConfigCount); FF_DEBUG("eglGetConfigs() returned %d config(s)", eglConfigCount); - if(eglConfigCount == 0) - { + if (eglConfigCount == 0) { FF_DEBUG("No EGL config is available"); return "eglGetConfigs returned 0 configs"; } FF_DEBUG("Creating EGL pbuffer surface (%dx%d)", FF_OPENGL_BUFFER_WIDTH, FF_OPENGL_BUFFER_HEIGHT); - data->surface = data->ffeglCreatePbufferSurface(data->display, data->config, (EGLint[]){ - EGL_WIDTH, FF_OPENGL_BUFFER_WIDTH, - EGL_HEIGHT, FF_OPENGL_BUFFER_HEIGHT, - EGL_NONE - }); + data->surface = data->ffeglCreatePbufferSurface(data->display, data->config, (EGLint[]) {EGL_WIDTH, FF_OPENGL_BUFFER_WIDTH, EGL_HEIGHT, FF_OPENGL_BUFFER_HEIGHT, EGL_NONE}); - if(data->surface == EGL_NO_SURFACE) - { + if (data->surface == EGL_NO_SURFACE) { FF_DEBUG("eglCreatePbufferSurface() returned EGL_NO_SURFACE"); return "eglCreatePbufferSurface returned EGL_NO_SURFACE"; } @@ -147,35 +132,31 @@ static const char* eglHandleDisplay(FFOpenGLResult* result, EGLData* data) return error; } -static const char* eglHandleData(FFOpenGLResult* result, EGLData* data) -{ +static const char* eglHandleData(FFOpenGLResult* result, EGLData* data) { FF_DEBUG("Resolving glGetString via eglGetProcAddress()"); data->ffglGetString = (__typeof__(&glGetString)) data->ffeglGetProcAddress("glGetString"); - if(!data->ffglGetString) - { + if (!data->ffglGetString) { FF_DEBUG("eglGetProcAddress('glGetString') returned NULL"); return "eglGetProcAddress(glGetString) returned NULL"; } - #if EGL_VERSION_1_5 +# if EGL_VERSION_1_5 PFNEGLGETPLATFORMDISPLAYEXTPROC ffeglGetPlatformDisplay = (PFNEGLGETPLATFORMDISPLAYEXTPROC) data->ffeglGetProcAddress("eglGetPlatformDisplay"); - if (ffeglGetPlatformDisplay) - { + if (ffeglGetPlatformDisplay) { FF_DEBUG("Trying eglGetPlatformDisplay(EGL_PLATFORM_SURFACELESS_MESA)"); data->display = ffeglGetPlatformDisplay(EGL_PLATFORM_SURFACELESS_MESA, NULL, NULL); FF_DEBUG("eglGetPlatformDisplay() %s", data->display == EGL_NO_DISPLAY ? "failed" : "succeeded"); - } - else + } else { FF_DEBUG("eglGetPlatformDisplay is unavailable, falling back to eglGetDisplay"); + } - if(!ffeglGetPlatformDisplay || data->display == EGL_NO_DISPLAY) - #endif + if (!ffeglGetPlatformDisplay || data->display == EGL_NO_DISPLAY) +# endif { FF_DEBUG("Trying eglGetDisplay(EGL_DEFAULT_DISPLAY)"); data->display = data->ffeglGetDisplay(EGL_DEFAULT_DISPLAY); - if(data->display == EGL_NO_DISPLAY) - { + if (data->display == EGL_NO_DISPLAY) { FF_DEBUG("eglGetDisplay() returned EGL_NO_DISPLAY"); return "eglGetDisplay returned EGL_NO_DISPLAY"; } @@ -183,10 +164,8 @@ static const char* eglHandleData(FFOpenGLResult* result, EGLData* data) FF_DEBUG("eglGetDisplay() succeeded"); } - EGLint major, minor; - if(data->ffeglInitialize(data->display, &major, &minor) == EGL_FALSE) - { + if (data->ffeglInitialize(data->display, &major, &minor) == EGL_FALSE) { FF_DEBUG("eglInitialize() returned EGL_FALSE"); return "eglInitialize returned EGL_FALSE"; } @@ -201,9 +180,7 @@ static const char* eglHandleData(FFOpenGLResult* result, EGLData* data) return error; } - -const char* ffOpenGLDetectByEGL(FFOpenGLResult* result) -{ +const char* ffOpenGLDetectByEGL(FFOpenGLResult* result) { FF_DEBUG("Starting OpenGL detection via EGL"); EGLData eglData; @@ -232,6 +209,6 @@ const char* ffOpenGLDetectByEGL(FFOpenGLResult* result) return error; } -#endif //FF_HAVE_EGL +# endif // FF_HAVE_EGL -#endif //FF_HAVE_NO_GL +#endif // FF_HAVE_NO_GL diff --git a/src/detection/opengl/opengl_windows.c b/src/detection/opengl/opengl_windows.c index 8e86ad475..b8e0c41d1 100644 --- a/src/detection/opengl/opengl_windows.c +++ b/src/detection/opengl/opengl_windows.c @@ -6,8 +6,7 @@ #include #include -typedef struct WGLData -{ +typedef struct WGLData { FF_LIBRARY_SYMBOL(glGetString) FF_LIBRARY_SYMBOL(wglMakeCurrent) FF_LIBRARY_SYMBOL(wglCreateContext) @@ -16,23 +15,24 @@ typedef struct WGLData void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); -static const char* wglHandleContext(WGLData* wglData, FFOpenGLResult* result, HDC hdc, HGLRC context) -{ - if(wglData->ffwglMakeCurrent(hdc, context) == FALSE) +static const char* wglHandleContext(WGLData* wglData, FFOpenGLResult* result, HDC hdc, HGLRC context) { + if (wglData->ffwglMakeCurrent(hdc, context) == FALSE) { return "wglMakeCurrent() failed"; + } ffOpenGLHandleResult(result, wglData->ffglGetString); ffStrbufSetStatic(&result->library, "WGL 1.0"); - if(wglData->ffwglMakeCurrent(NULL, NULL) == FALSE) + if (wglData->ffwglMakeCurrent(NULL, NULL) == FALSE) { return "wglMakeCurrent(NULL, NULL) failed"; + } return NULL; } -static const char* wglHandlePixelFormat(WGLData* wglData, FFOpenGLResult* result, HWND hWnd) -{ +static const char* wglHandlePixelFormat(WGLData* wglData, FFOpenGLResult* result, HWND hWnd) { HDC hdc = GetDC(hWnd); - if(hdc == NULL) + if (hdc == NULL) { return "GetDC() failed"; + } PIXELFORMATDESCRIPTOR pfd = { .nSize = sizeof(PIXELFORMATDESCRIPTOR), @@ -41,24 +41,20 @@ static const char* wglHandlePixelFormat(WGLData* wglData, FFOpenGLResult* result .iPixelType = PFD_TYPE_RGBA, .cColorBits = 32, .cDepthBits = 24, - .iLayerType = PFD_MAIN_PLANE - }; + .iLayerType = PFD_MAIN_PLANE}; int pixelFormat = ChoosePixelFormat(hdc, &pfd); - if(pixelFormat == 0) - { + if (pixelFormat == 0) { ReleaseDC(hWnd, hdc); return "ChoosePixelFormat() failed"; } - if(SetPixelFormat(hdc, pixelFormat, &pfd) == FALSE) - { + if (SetPixelFormat(hdc, pixelFormat, &pfd) == FALSE) { ReleaseDC(hWnd, hdc); return "SetPixelFormat() failed"; } HGLRC context = wglData->ffwglCreateContext(hdc); - if(context == NULL) - { + if (context == NULL) { ReleaseDC(hWnd, hdc); return "wglCreateContext() failed"; } @@ -71,8 +67,7 @@ static const char* wglHandlePixelFormat(WGLData* wglData, FFOpenGLResult* result return error; } -static const char* wglDetectOpenGL(FFOpenGLResult* result) -{ +static const char* wglDetectOpenGL(FFOpenGLResult* result) { FF_LIBRARY_LOAD_MESSAGE(opengl32, "opengl32" FF_LIBRARY_EXTENSION, 1); WGLData data = {}; @@ -87,16 +82,18 @@ static const char* wglDetectOpenGL(FFOpenGLResult* result) WNDCLASSW wc = { .lpfnWndProc = DefWindowProcW, .hInstance = hInstance, - .hbrBackground = (HBRUSH)COLOR_BACKGROUND, + .hbrBackground = (HBRUSH) COLOR_BACKGROUND, .lpszClassName = L"ogl_version_check", .style = CS_OWNDC, }; - if(!RegisterClassW(&wc)) + if (!RegisterClassW(&wc)) { return "RegisterClassW() failed"; + } HWND hWnd = CreateWindowW(wc.lpszClassName, L"ogl_version_check", 0, 0, 0, FF_OPENGL_BUFFER_WIDTH, FF_OPENGL_BUFFER_HEIGHT, NULL, NULL, hInstance, NULL); - if(!hWnd) + if (!hWnd) { return "CreateWindowW() failed"; + } const char* error = wglHandlePixelFormat(&data, result, hWnd); @@ -106,20 +103,17 @@ static const char* wglDetectOpenGL(FFOpenGLResult* result) return error; } - -const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) -{ - if (options->library == FF_OPENGL_LIBRARY_AUTO) +const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) { + if (options->library == FF_OPENGL_LIBRARY_AUTO) { return wglDetectOpenGL(result); - else if (options->library == FF_OPENGL_LIBRARY_EGL) - { - #if __has_include() - const char* ffOpenGLDetectByEGL(FFOpenGLResult* result); + } else if (options->library == FF_OPENGL_LIBRARY_EGL) { +#if __has_include() + const char* ffOpenGLDetectByEGL(FFOpenGLResult * result); return ffOpenGLDetectByEGL(result); - #else +#else return "fastfetch was compiled without egl support"; - #endif - } - else +#endif + } else { return "Unsupported OpenGL library"; + } } diff --git a/src/detection/os/os.c b/src/detection/os/os.c index c8f10d5f1..7f66733bb 100644 --- a/src/detection/os/os.c +++ b/src/detection/os/os.c @@ -2,11 +2,9 @@ void ffDetectOSImpl(FFOSResult* os); -const FFOSResult* ffDetectOS(void) -{ +const FFOSResult* ffDetectOS(void) { static FFOSResult result; - if (result.name.chars == NULL) - { + if (result.name.chars == NULL) { ffStrbufInit(&result.name); ffStrbufInit(&result.prettyName); ffStrbufInit(&result.id); diff --git a/src/detection/os/os.h b/src/detection/os/os.h index 09226b9c2..5b62aab2e 100644 --- a/src/detection/os/os.h +++ b/src/detection/os/os.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/os/option.h" -typedef struct FFOSResult -{ +typedef struct FFOSResult { FFstrbuf name; FFstrbuf prettyName; FFstrbuf id; diff --git a/src/detection/os/os_android.c b/src/detection/os/os_android.c index 7d39954d6..47ea40b46 100644 --- a/src/detection/os/os_android.c +++ b/src/detection/os/os_android.c @@ -1,8 +1,7 @@ #include "os.h" #include "common/settings.h" -void ffDetectOSImpl(FFOSResult* os) -{ +void ffDetectOSImpl(FFOSResult* os) { ffStrbufSetStatic(&os->name, "Android"); ffStrbufSetStatic(&os->id, "android"); diff --git a/src/detection/os/os_haiku.c b/src/detection/os/os_haiku.c index 561bdcc6e..40dad2220 100644 --- a/src/detection/os/os_haiku.c +++ b/src/detection/os/os_haiku.c @@ -2,24 +2,22 @@ #include #include -void ffDetectOSImpl(FFOSResult* os) -{ +void ffDetectOSImpl(FFOSResult* os) { ffStrbufSetStatic(&os->name, "Haiku"); ffStrbufSetStatic(&os->id, "haiku"); image_info image; int32 cookie = 0; - while (get_next_image_info(B_SYSTEM_TEAM, &cookie, &image) == B_OK) - { + while (get_next_image_info(B_SYSTEM_TEAM, &cookie, &image) == B_OK) { int32 ver = image.api_version; - if (ver == 0) continue; + if (ver == 0) { + continue; + } // https://github.com/haiku/haiku/blob/e63683b2fb337d2034059a7e053c170eaf978142/headers/os/BeBuild.h#L36 - if (ver < B_HAIKU_VERSION_1_ALPHA_1) - { - switch (ver) - { + if (ver < B_HAIKU_VERSION_1_ALPHA_1) { + switch (ver) { case B_HAIKU_VERSION_BEOS: ffStrbufSetStatic(&os->version, "BEOS"); break; @@ -30,44 +28,38 @@ void ffDetectOSImpl(FFOSResult* os) ffStrbufSetStatic(&os->version, "DANO"); break; } - } - else - { + } else { int32 relVer = ver / 0x10000; ver %= 0x10000; - if (ver == 0) - { + if (ver == 0) { ffStrbufSetF(&os->version, "R%d", relVer); - } - else - { + } else { relVer++; bool isPre = !!(ver & 1); - if (ver < B_HAIKU_VERSION_1_PRE_BETA_1) - { + if (ver < B_HAIKU_VERSION_1_PRE_BETA_1) { int32 alphaVer = ver / 0x100; - if (isPre) + if (isPre) { ffStrbufSetF(&os->version, "R%dA%d-", relVer, alphaVer + 1); - else + } else { ffStrbufSetF(&os->version, "R%dA%d", relVer, alphaVer); - } - else if (ver < 0x00010000 /* B_HAIKU_VERSION_1 */) - { + } + } else if (ver < 0x00010000 /* B_HAIKU_VERSION_1 */) { int32 betaVer = (ver - B_HAIKU_VERSION_1_ALPHA_4) / 0x100; - if (isPre) + if (isPre) { ffStrbufSetF(&os->version, "R%dB%d-", relVer, betaVer + 1); - else + } else { ffStrbufSetF(&os->version, "R%dB%d", relVer, betaVer); + } } } } } - if (!os->version.length) - { + if (!os->version.length) { system_info sys; - if (get_system_info(&sys) == B_OK) + if (get_system_info(&sys) == B_OK) { ffStrbufAppendF(&os->version, "R%ldx", sys.kernel_version); + } } } diff --git a/src/detection/os/os_linux.c b/src/detection/os/os_linux.c index 2e58c3e4e..f9c5869ee 100644 --- a/src/detection/os/os_linux.c +++ b/src/detection/os/os_linux.c @@ -11,45 +11,43 @@ #define FF_STR_INDIR(x) #x #define FF_STR(x) FF_STR_INDIR(x) -static bool parseLsbRelease(const char* fileName, FFOSResult* result) -{ +static bool parseLsbRelease(const char* fileName, FFOSResult* result) { return ffParsePropFileValues(fileName, 4, (FFpropquery[]) { - {"DISTRIB_ID =", &result->id}, - {"DISTRIB_DESCRIPTION =", &result->prettyName}, - {"DISTRIB_RELEASE =", &result->version}, - {"DISTRIB_CODENAME =", &result->codename}, - }); + {"DISTRIB_ID =", &result->id}, + {"DISTRIB_DESCRIPTION =", &result->prettyName}, + {"DISTRIB_RELEASE =", &result->version}, + {"DISTRIB_CODENAME =", &result->codename}, + }); } -static bool parseOsRelease(const char* fileName, FFOSResult* result) -{ +static bool parseOsRelease(const char* fileName, FFOSResult* result) { return ffParsePropFileValues(fileName, 11, (FFpropquery[]) { - {"PRETTY_NAME =", &result->prettyName}, - {"NAME =", &result->name}, - {"ID =", &result->id}, - {"ID_LIKE =", &result->idLike}, - {"VARIANT =", &result->variant}, - {"VARIANT_ID =", &result->variantID}, - {"VERSION =", &result->version}, - {"VERSION_ID =", &result->versionID}, - {"VERSION_CODENAME =", &result->codename}, - {"CODENAME =", &result->codename}, - {"BUILD_ID =", &result->buildID}, - }); + {"PRETTY_NAME =", &result->prettyName}, + {"NAME =", &result->name}, + {"ID =", &result->id}, + {"ID_LIKE =", &result->idLike}, + {"VARIANT =", &result->variant}, + {"VARIANT_ID =", &result->variantID}, + {"VERSION =", &result->version}, + {"VERSION_ID =", &result->versionID}, + {"VERSION_CODENAME =", &result->codename}, + {"CODENAME =", &result->codename}, + {"BUILD_ID =", &result->buildID}, + }); } // Common logic for detecting Armbian image version -FF_MAYBE_UNUSED static bool detectArmbianVersion(FFOSResult* result) -{ +FF_MAYBE_UNUSED static bool detectArmbianVersion(FFOSResult* result) { // Possible values `PRETTY_NAME` starts with on Armbian: // - `Armbian` for official releases // - `Armbian_community` for community releases // - `Armbian_Security` for images with kali repo added // - `Armbian-unofficial` for an unofficial image built from source, e.g. during development and testing - if (ffStrbufStartsWithS(&result->prettyName, "Armbian")) + if (ffStrbufStartsWithS(&result->prettyName, "Armbian")) { ffStrbufSetStatic(&result->name, "Armbian"); - else + } else { return false; + } ffStrbufSet(&result->idLike, &result->id); ffStrbufSetS(&result->id, "armbian"); ffStrbufClear(&result->versionID); @@ -60,118 +58,104 @@ FF_MAYBE_UNUSED static bool detectArmbianVersion(FFOSResult* result) } // Returns false if PrettyName should be updated by caller -FF_MAYBE_UNUSED static bool getUbuntuFlavour(FFOSResult* result) -{ - if (detectArmbianVersion(result)) +FF_MAYBE_UNUSED static bool getUbuntuFlavour(FFOSResult* result) { + if (detectArmbianVersion(result)) { return true; - else if(ffStrbufStartsWithS(&result->prettyName, "Linux Lite ")) - { + } else if (ffStrbufStartsWithS(&result->prettyName, "Linux Lite ")) { ffStrbufSetStatic(&result->name, "Linux Lite"); ffStrbufSetStatic(&result->id, "linuxlite"); ffStrbufSetStatic(&result->idLike, "ubuntu"); ffStrbufSetS(&result->versionID, result->prettyName.chars + strlen("Linux Lite ")); return true; - } - else if(ffStrbufStartsWithS(&result->prettyName, "Rhino Linux ")) - { + } else if (ffStrbufStartsWithS(&result->prettyName, "Rhino Linux ")) { ffStrbufSetStatic(&result->name, "Rhino Linux"); ffStrbufSetStatic(&result->id, "rhinolinux"); ffStrbufSetStatic(&result->idLike, "ubuntu"); ffStrbufSetS(&result->versionID, result->prettyName.chars + strlen("Rhino Linux ")); return true; - } - else if(ffStrbufStartsWithS(&result->prettyName, "VanillaOS ")) - { + } else if (ffStrbufStartsWithS(&result->prettyName, "VanillaOS ")) { ffStrbufSetStatic(&result->id, "vanilla"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return true; } - if (ffPathExists("/usr/bin/lliurex-version", FF_PATHTYPE_FILE)) - { + if (ffPathExists("/usr/bin/lliurex-version", FF_PATHTYPE_FILE)) { ffStrbufSetStatic(&result->name, "LliureX"); ffStrbufSetStatic(&result->id, "lliurex"); ffStrbufClear(&result->version); if (ffProcessAppendStdOut(&result->version, (char* const[]) { - "/usr/bin/lliurex-version", - NULL, - }) == NULL) // 8.2.2 + "/usr/bin/lliurex-version", + NULL, + }) == NULL) { // 8.2.2 ffStrbufTrimRightSpace(&result->version); + } ffStrbufSetF(&result->prettyName, "LliureX %s", result->version.chars); ffStrbufSetStatic(&result->idLike, "ubuntu"); return true; } const char* xdgConfigDirs = getenv("XDG_CONFIG_DIRS"); - if(!ffStrSet(xdgConfigDirs)) + if (!ffStrSet(xdgConfigDirs)) { return false; + } - if(ffStrContains(xdgConfigDirs, "kde") || ffStrContains(xdgConfigDirs, "plasma") || ffStrContains(xdgConfigDirs, "kubuntu")) - { + if (ffStrContains(xdgConfigDirs, "kde") || ffStrContains(xdgConfigDirs, "plasma") || ffStrContains(xdgConfigDirs, "kubuntu")) { ffStrbufSetStatic(&result->name, "Kubuntu"); ffStrbufSetStatic(&result->id, "kubuntu"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "xfce") || ffStrContains(xdgConfigDirs, "xubuntu")) - { + if (ffStrContains(xdgConfigDirs, "xfce") || ffStrContains(xdgConfigDirs, "xubuntu")) { ffStrbufSetStatic(&result->name, "Xubuntu"); ffStrbufSetStatic(&result->id, "xubuntu"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "lxqt") || ffStrContains(xdgConfigDirs, "lubuntu")) - { + if (ffStrContains(xdgConfigDirs, "lxqt") || ffStrContains(xdgConfigDirs, "lubuntu")) { ffStrbufSetStatic(&result->name, "Lubuntu"); ffStrbufSetStatic(&result->id, "lubuntu"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "budgie")) - { + if (ffStrContains(xdgConfigDirs, "budgie")) { ffStrbufSetStatic(&result->name, "Ubuntu Budgie"); ffStrbufSetStatic(&result->id, "ubuntu-budgie"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "cinnamon")) - { + if (ffStrContains(xdgConfigDirs, "cinnamon")) { ffStrbufSetStatic(&result->name, "Ubuntu Cinnamon"); ffStrbufSetStatic(&result->id, "ubuntu-cinnamon"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "mate")) - { + if (ffStrContains(xdgConfigDirs, "mate")) { ffStrbufSetStatic(&result->name, "Ubuntu MATE"); ffStrbufSetStatic(&result->id, "ubuntu-mate"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "studio")) - { + if (ffStrContains(xdgConfigDirs, "studio")) { ffStrbufSetStatic(&result->name, "Ubuntu Studio"); ffStrbufSetStatic(&result->id, "ubuntu-studio"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "sway")) - { + if (ffStrContains(xdgConfigDirs, "sway")) { ffStrbufSetStatic(&result->name, "Ubuntu Sway"); ffStrbufSetStatic(&result->id, "ubuntu-sway"); ffStrbufSetStatic(&result->idLike, "ubuntu"); return false; } - if(ffStrContains(xdgConfigDirs, "touch")) - { + if (ffStrContains(xdgConfigDirs, "touch")) { ffStrbufSetStatic(&result->name, "Ubuntu Touch"); ffStrbufSetStatic(&result->id, "ubuntu-touch"); ffStrbufSetStatic(&result->idLike, "ubuntu"); @@ -181,70 +165,60 @@ FF_MAYBE_UNUSED static bool getUbuntuFlavour(FFOSResult* result) return false; } -FF_MAYBE_UNUSED static void getDebianVersion(FFOSResult* result) -{ +FF_MAYBE_UNUSED static void getDebianVersion(FFOSResult* result) { FF_STRBUF_AUTO_DESTROY debianVersion = ffStrbufCreate(); ffAppendFileBuffer("/etc/debian_version", &debianVersion); ffStrbufTrimRightSpace(&debianVersion); - if (!debianVersion.length) return; + if (!debianVersion.length) { + return; + } ffStrbufDestroy(&result->versionID); ffStrbufInitMove(&result->versionID, &debianVersion); ffStrbufSetF(&result->prettyName, "%s %s (%s)", result->name.chars, result->versionID.chars, result->codename.chars); } -FF_MAYBE_UNUSED static bool detectDebianDerived(FFOSResult* result) -{ - if (detectArmbianVersion(result)) +FF_MAYBE_UNUSED static bool detectDebianDerived(FFOSResult* result) { + if (detectArmbianVersion(result)) { return true; - else if (ffStrbufStartsWithS(&result->name, "Loc-OS")) - { + } else if (ffStrbufStartsWithS(&result->name, "Loc-OS")) { ffStrbufSetStatic(&result->id, "locos"); ffStrbufSetStatic(&result->idLike, "debian"); return true; - } - else if (ffStrbufEqualS(&result->name, "Parrot Security")) - { + } else if (ffStrbufEqualS(&result->name, "Parrot Security")) { // https://github.com/ParrotSec/base-files/blob/c06f6d42ddf8d79564882306576576eddab7d907/etc/os-release ffStrbufSetS(&result->id, "parrot"); ffStrbufSetS(&result->idLike, "debian"); return true; - } - else if (ffStrbufStartsWithS(&result->name, "Lilidog GNU/Linux")) - { + } else if (ffStrbufStartsWithS(&result->name, "Lilidog GNU/Linux")) { // https://github.com/fastfetch-cli/fastfetch/issues/1373 ffStrbufSetStatic(&result->id, "lilidog"); ffStrbufSetStatic(&result->idLike, "debian"); return true; - } - else if (access("/usr/bin/pveversion", X_OK) == 0) - { + } else if (access("/usr/bin/pveversion", X_OK) == 0) { ffStrbufSetStatic(&result->id, "pve"); ffStrbufSetStatic(&result->idLike, "debian"); ffStrbufSetStatic(&result->name, "Proxmox VE"); ffStrbufClear(&result->versionID); if (ffProcessAppendStdOut(&result->versionID, (char* const[]) { - "/usr/bin/dpkg-query", - "--showformat=${version}", - "--show", - "pve-manager", - NULL, - }) == NULL) // 8.2.2 + "/usr/bin/dpkg-query", + "--showformat=${version}", + "--show", + "pve-manager", + NULL, + }) == NULL) { // 8.2.2 ffStrbufTrimRightSpace(&result->versionID); + } ffStrbufSetF(&result->prettyName, "Proxmox VE %s", result->versionID.chars); return true; - } - else if (ffPathExists("/etc/rpi-issue", FF_PATHTYPE_FILE)) - { + } else if (ffPathExists("/etc/rpi-issue", FF_PATHTYPE_FILE)) { // Raspberry Pi OS ffStrbufSetStatic(&result->id, "raspbian"); ffStrbufSetStatic(&result->idLike, "debian"); ffStrbufSetStatic(&result->name, "Raspberry Pi OS"); getDebianVersion(result); return true; - } - else if (ffPathExists("/boot/dietpi/.version", FF_PATHTYPE_FILE)) - { + } else if (ffPathExists("/boot/dietpi/.version", FF_PATHTYPE_FILE)) { // DietPi ffStrbufSetStatic(&result->id, "dietpi"); ffStrbufSetStatic(&result->name, "DietPi"); @@ -254,36 +228,31 @@ FF_MAYBE_UNUSED static bool detectDebianDerived(FFOSResult* result) FF_STRBUF_AUTO_DESTROY sub = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY rc = ffStrbufCreate(); if (ffParsePropFileValues("/boot/dietpi/.version", 3, (FFpropquery[]) { - {"G_DIETPI_VERSION_CORE=", &core}, - {"G_DIETPI_VERSION_SUB=", &sub}, - {"G_DIETPI_VERSION_RC=", &rc}, - })) ffStrbufAppendF(&result->prettyName, " %s.%s.%s", core.chars, sub.chars, rc.chars); + {"G_DIETPI_VERSION_CORE=", &core}, + {"G_DIETPI_VERSION_SUB=", &sub}, + {"G_DIETPI_VERSION_RC=", &rc}, + })) { + ffStrbufAppendF(&result->prettyName, " %s.%s.%s", core.chars, sub.chars, rc.chars); + } return true; - } - else if (ffStrbufEndsWithS(&instance.state.platform.sysinfo.release, "+truenas")) - { + } else if (ffStrbufEndsWithS(&instance.state.platform.sysinfo.release, "+truenas")) { // TrueNAS Scale ffStrbufSetStatic(&result->id, "truenas-scale"); ffStrbufSetStatic(&result->idLike, "debian"); ffStrbufSetStatic(&result->name, "TrueNAS Scale"); ffStrbufSetStatic(&result->prettyName, "TrueNAS Scale"); return true; - } - else if (ffPathExists("/usr/bin/emmabuntus_config.sh", FF_PATHTYPE_FILE)) - { + } else if (ffPathExists("/usr/bin/emmabuntus_config.sh", FF_PATHTYPE_FILE)) { // Emmabuntüs ffStrbufSetStatic(&result->id, "emmabuntus"); ffStrbufSetStatic(&result->idLike, "debian"); ffStrbufSetStatic(&result->name, "Emmabuntüs"); getDebianVersion(result); return true; - } - else - { + } else { // Hack for MX Linux. See #847 FF_STRBUF_AUTO_DESTROY lsbRelease = ffStrbufCreate(); - if (ffAppendFileBuffer("/etc/lsb-release", &lsbRelease) && ffStrbufContainS(&lsbRelease, "DISTRIB_ID=MX")) - { + if (ffAppendFileBuffer("/etc/lsb-release", &lsbRelease) && ffStrbufContainS(&lsbRelease, "DISTRIB_ID=MX")) { ffStrbufSetStatic(&result->id, "mx"); ffStrbufSetStatic(&result->idLike, "debian"); ffStrbufSetStatic(&result->name, "MX"); @@ -303,13 +272,8 @@ FF_MAYBE_UNUSED static bool detectDebianDerived(FFOSResult* result) return false; } -FF_MAYBE_UNUSED static bool detectFedoraVariant(FFOSResult* result) -{ - if (ffStrbufEqualS(&result->variantID, "coreos") - || ffStrbufEqualS(&result->variantID, "kinoite") - || ffStrbufEqualS(&result->variantID, "sericea") - || ffStrbufEqualS(&result->variantID, "silverblue")) - { +FF_MAYBE_UNUSED static bool detectFedoraVariant(FFOSResult* result) { + if (ffStrbufEqualS(&result->variantID, "coreos") || ffStrbufEqualS(&result->variantID, "kinoite") || ffStrbufEqualS(&result->variantID, "sericea") || ffStrbufEqualS(&result->variantID, "silverblue")) { ffStrbufAppendC(&result->id, '-'); ffStrbufAppend(&result->id, &result->variantID); ffStrbufSetStatic(&result->idLike, "fedora"); @@ -318,38 +282,39 @@ FF_MAYBE_UNUSED static bool detectFedoraVariant(FFOSResult* result) return false; } -static bool detectBedrock(FFOSResult* os) -{ +static bool detectBedrock(FFOSResult* os) { const char* bedrockRestrict = getenv("BEDROCK_RESTRICT"); - if(bedrockRestrict && bedrockRestrict[0] == '1') return false; + if (bedrockRestrict && bedrockRestrict[0] == '1') { + return false; + } return parseOsRelease(FASTFETCH_TARGET_DIR_ROOT "/bedrock/strata/bedrock/etc/os-release", os); } -static void detectOS(FFOSResult* os) -{ - #ifdef FF_CUSTOM_OS_RELEASE_PATH +static void detectOS(FFOSResult* os) { +#ifdef FF_CUSTOM_OS_RELEASE_PATH parseOsRelease(FF_STR(FF_CUSTOM_OS_RELEASE_PATH), os); - #ifdef FF_CUSTOM_LSB_RELEASE_PATH - parseLsbRelease(FF_STR(FF_CUSTOM_LSB_RELEASE_PATH), os); - #endif +# ifdef FF_CUSTOM_LSB_RELEASE_PATH + parseLsbRelease(FF_STR(FF_CUSTOM_LSB_RELEASE_PATH), os); +# endif return; - #endif +#endif - if (detectBedrock(os)) + if (detectBedrock(os)) { return; + } // Refer: https://gist.github.com/natefoo/814c5bf936922dad97ff parseOsRelease(FASTFETCH_TARGET_DIR_ETC "/os-release", os); - if (os->id.length == 0 || os->version.length == 0 || os->prettyName.length == 0 || os->codename.length == 0) + if (os->id.length == 0 || os->version.length == 0 || os->prettyName.length == 0 || os->codename.length == 0) { parseLsbRelease(FASTFETCH_TARGET_DIR_ETC "/lsb-release", os); - if (os->id.length == 0 || os->name.length == 0 || os->prettyName.length == 0) + } + if (os->id.length == 0 || os->name.length == 0 || os->prettyName.length == 0) { parseOsRelease(FASTFETCH_TARGET_DIR_USR "/lib/os-release", os); - if (os->id.length == 0 && os->name.length == 0 && os->prettyName.length == 0) - { + } + if (os->id.length == 0 && os->name.length == 0 && os->prettyName.length == 0) { // HarmonyOS has no os-release file - if (ffStrbufEqualS(&instance.state.platform.sysinfo.name, "HarmonyOS")) - { + if (ffStrbufEqualS(&instance.state.platform.sysinfo.name, "HarmonyOS")) { ffStrbufSetS(&os->id, "harmonyos"); ffStrbufSetS(&os->idLike, "harmonyos"); ffStrbufSetS(&os->name, "HarmonyOS"); @@ -358,33 +323,27 @@ static void detectOS(FFOSResult* os) } } -void ffDetectOSImpl(FFOSResult* os) -{ +void ffDetectOSImpl(FFOSResult* os) { detectOS(os); - #if __linux__ || __GNU__ - if(ffStrbufEqualS(&os->id, "ubuntu")) - { - if (!getUbuntuFlavour(os)) - { - if (!ffStrbufEndsWithS(&os->prettyName, " (development branch)")) +#if __linux__ || __GNU__ + if (ffStrbufEqualS(&os->id, "ubuntu")) { + if (!getUbuntuFlavour(os)) { + if (!ffStrbufEndsWithS(&os->prettyName, " (development branch)")) { ffStrbufSetF(&os->prettyName, "%s %s", os->name.chars, os->version.chars); // os->version contains code name + } } - } - else if(ffStrbufEqualS(&os->id, "debian")) - { - if (!detectDebianDerived(os)) + } else if (ffStrbufEqualS(&os->id, "debian")) { + if (!detectDebianDerived(os)) { getDebianVersion(os); - } - else if(ffStrbufEqualS(&os->id, "fedora")) + } + } else if (ffStrbufEqualS(&os->id, "fedora")) { detectFedoraVariant(os); - else if(ffStrbufEqualS(&os->id, "linuxmint")) - { - if (ffStrbufEqualS(&os->name, "LMDE")) - { + } else if (ffStrbufEqualS(&os->id, "linuxmint")) { + if (ffStrbufEqualS(&os->name, "LMDE")) { ffStrbufSetS(&os->id, "lmde"); ffStrbufSetS(&os->idLike, "linuxmint"); } } - #endif +#endif } diff --git a/src/detection/os/os_nbsd.c b/src/detection/os/os_nbsd.c index 229df96d1..200d0f2cf 100644 --- a/src/detection/os/os_nbsd.c +++ b/src/detection/os/os_nbsd.c @@ -1,7 +1,6 @@ #include "os.h" -void ffDetectOSImpl(FFOSResult* os) -{ +void ffDetectOSImpl(FFOSResult* os) { ffStrbufSetStatic(&os->name, "NetBSD"); ffStrbufSet(&os->version, &instance.state.platform.sysinfo.release); } diff --git a/src/detection/os/os_obsd.c b/src/detection/os/os_obsd.c index 10a0bfd81..4baf185bc 100644 --- a/src/detection/os/os_obsd.c +++ b/src/detection/os/os_obsd.c @@ -1,7 +1,6 @@ #include "os.h" -void ffDetectOSImpl(FFOSResult* os) -{ +void ffDetectOSImpl(FFOSResult* os) { ffStrbufSetStatic(&os->name, "OpenBSD"); ffStrbufSet(&os->version, &instance.state.platform.sysinfo.release); } diff --git a/src/detection/os/os_sunos.c b/src/detection/os/os_sunos.c index 1708e2f14..72f994665 100644 --- a/src/detection/os/os_sunos.c +++ b/src/detection/os/os_sunos.c @@ -1,10 +1,10 @@ #include "os.h" #include "common/io.h" -void ffDetectOSImpl(FFOSResult* os) -{ - if (!ffReadFileBuffer("/etc/release", &os->prettyName)) +void ffDetectOSImpl(FFOSResult* os) { + if (!ffReadFileBuffer("/etc/release", &os->prettyName)) { return; + } ffStrbufSubstrBeforeFirstC(&os->prettyName, '\n'); ffStrbufSubstrBeforeLastC(&os->prettyName, '('); diff --git a/src/detection/os/os_windows.c b/src/detection/os/os_windows.c index 07b11761a..f4eb11339 100644 --- a/src/detection/os/os_windows.c +++ b/src/detection/os/os_windows.c @@ -8,77 +8,74 @@ PWSTR WINAPI BrandingFormatString(PCWSTR format); -static bool getCodeName(FFOSResult* os) -{ +static bool getCodeName(FFOSResult* os) { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) + if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) { return false; + } - if(!ffRegReadStrbuf(hKey, L"DisplayVersion", &os->codename, NULL)) - { - if (!ffRegReadStrbuf(hKey, L"CSDVersion", &os->codename, NULL)) // For Windows 7 and Windows 8 - if (!ffRegReadStrbuf(hKey, L"ReleaseId", &os->codename, NULL)) // For old Windows 10 + if (!ffRegReadStrbuf(hKey, L"DisplayVersion", &os->codename, NULL)) { + if (!ffRegReadStrbuf(hKey, L"CSDVersion", &os->codename, NULL)) { // For Windows 7 and Windows 8 + if (!ffRegReadStrbuf(hKey, L"ReleaseId", &os->codename, NULL)) { // For old Windows 10 return false; + } + } } return true; } -void ffDetectOSImpl(FFOSResult* os) -{ - //https://dennisbabkin.com/blog/?t=how-to-tell-the-real-version-of-windows-your-app-is-running-on#ver_string +void ffDetectOSImpl(FFOSResult* os) { + // https://dennisbabkin.com/blog/?t=how-to-tell-the-real-version-of-windows-your-app-is-running-on#ver_string const wchar_t* rawName = BrandingFormatString(L"%WINDOWS_LONG%"); ffStrbufSetWS(&os->variant, rawName); - GlobalFree((HGLOBAL)rawName); + GlobalFree((HGLOBAL) rawName); ffStrbufSet(&os->prettyName, &os->variant); ffStrbufTrimRight(&os->variant, ' '); - //WMI returns the "Microsoft" prefix while BrandingFormatString doesn't. Make them consistent. - if(ffStrbufStartsWithS(&os->variant, "Microsoft ")) + // WMI returns the "Microsoft" prefix while BrandingFormatString doesn't. Make them consistent. + if (ffStrbufStartsWithS(&os->variant, "Microsoft ")) { ffStrbufSubstrAfter(&os->variant, strlen("Microsoft ") - 1); + } - if(os->variant.length == 0) // Windows PE? + if (os->variant.length == 0) // Windows PE? { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) + if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) { ffRegReadStrbuf(hKey, L"ProductName", &os->variant, NULL); + } } ffStrbufSet(&os->prettyName, &os->variant); - if(ffStrbufStartsWithS(&os->variant, "Windows ")) - { + if (ffStrbufStartsWithS(&os->variant, "Windows ")) { ffStrbufAppendS(&os->name, "Windows"); ffStrbufSubstrAfter(&os->variant, strlen("Windows ") - 1); - if(ffStrbufStartsWithS(&os->variant, "Server ")) - { + if (ffStrbufStartsWithS(&os->variant, "Server ")) { ffStrbufAppendS(&os->name, " Server"); ffStrbufSubstrAfter(&os->variant, strlen(" Server") - 1); } - if(ffStrbufStartsWithIgnCaseS(&os->variant, "(TM) ")) + if (ffStrbufStartsWithIgnCaseS(&os->variant, "(TM) ")) { ffStrbufSubstrAfter(&os->variant, strlen(" (TM)") - 1); + } uint32_t index = ffStrbufFirstIndexC(&os->variant, ' '); ffStrbufAppendNS(&os->version, index, os->variant.chars); ffStrbufSubstrAfter(&os->variant, index); // Windows Server 20xx Rx - if(ffStrbufEndsWithC(&os->name, 'r')) - { - if(os->variant.chars[0] == 'R' && + if (ffStrbufEndsWithC(&os->name, 'r')) { + if (os->variant.chars[0] == 'R' && ffCharIsDigit(os->variant.chars[1]) && - (os->variant.chars[2] == '\0' || os->variant.chars[2] == ' ')) - { + (os->variant.chars[2] == '\0' || os->variant.chars[2] == ' ')) { ffStrbufAppendF(&os->version, " R%c", os->variant.chars[1]); ffStrbufSubstrAfter(&os->variant, strlen("Rx ") - 1); } } - } - else - { + } else { // Unknown Windows name, please report this ffStrbufAppend(&os->name, &os->variant); ffStrbufClear(&os->variant); @@ -87,6 +84,7 @@ void ffDetectOSImpl(FFOSResult* os) ffStrbufAppendF(&os->id, "%s %s", os->name.chars, os->version.chars); ffStrbufSetStatic(&os->idLike, "Windows"); - if (getCodeName(os) && os->codename.length > 0) + if (getCodeName(os) && os->codename.length > 0) { ffStrbufAppendF(&os->prettyName, " (%s)", os->codename.chars); + } } diff --git a/src/detection/packages/packages.c b/src/detection/packages/packages.c index 96497c16a..6007c98f7 100644 --- a/src/detection/packages/packages.c +++ b/src/detection/packages/packages.c @@ -6,27 +6,27 @@ #include #ifdef __APPLE__ -#define st_mtim st_mtimespec +# define st_mtim st_mtimespec #endif void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options); -const char* ffDetectPackages(FFPackagesResult* result, FFPackagesOptions* options) -{ +const char* ffDetectPackages(FFPackagesResult* result, FFPackagesOptions* options) { ffDetectPackagesImpl(result, options); - for(uint32_t i = 0; i < offsetof(FFPackagesResult, all) / sizeof(uint32_t); ++i) - result->all += ((uint32_t *)result)[i]; + for (uint32_t i = 0; i < offsetof(FFPackagesResult, all) / sizeof(uint32_t); ++i) { + result->all += ((uint32_t*) result)[i]; + } - if (result->all == 0) + if (result->all == 0) { return "No packages from known package managers found"; + } return NULL; } -bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* filePath, const char* packageId, uint32_t* result) -{ - #ifndef _WIN32 +bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* filePath, const char* packageId, uint32_t* result) { +#ifndef _WIN32 struct stat st; if (stat(filePath, &st) < 0) // file doesn't exist or isn't accessible { @@ -34,11 +34,12 @@ bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* return true; } - if (__builtin_expect(st.st_mtim.tv_sec <= 0, false)) + if (__builtin_expect(st.st_mtim.tv_sec <= 0, false)) { return false; + } uint64_t mtime_current = (uint64_t) st.st_mtim.tv_sec * 1000ull + (uint64_t) st.st_mtim.tv_nsec / 1000000ull; - #else +#else FF_AUTO_CLOSE_FD HANDLE handle = CreateFileA(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) // file doesn't exist or isn't accessible @@ -50,23 +51,22 @@ bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* uint64_t mtime_current; FILE_BASIC_INFORMATION fileInfo; IO_STATUS_BLOCK iosb; - if (!NT_SUCCESS(NtQueryInformationFile(handle, &iosb, &fileInfo, sizeof(fileInfo), FileBasicInformation))) + if (!NT_SUCCESS(NtQueryInformationFile(handle, &iosb, &fileInfo, sizeof(fileInfo), FileBasicInformation))) { return false; + } mtime_current = ffFileTimeToUnixMs((uint64_t) fileInfo.LastWriteTime.QuadPart); - #endif +#endif ffStrbufSet(cacheDir, &instance.state.platform.cacheDir); ffStrbufEnsureEndsWithC(cacheDir, '/'); ffStrbufAppendF(cacheDir, "fastfetch/packages/%s.txt", packageId); - if (ffReadFileBuffer(cacheDir->chars, cacheContent)) - { + if (ffReadFileBuffer(cacheDir->chars, cacheContent)) { uint64_t mtime_cached; uint32_t num_cached; if (sscanf(cacheContent->chars, "%" SCNu64 " %" SCNu32, &mtime_cached, &num_cached) == 2 && - mtime_cached == mtime_current && num_cached > 0) - { + mtime_cached == mtime_current && num_cached > 0) { *result = num_cached; return true; } @@ -77,47 +77,47 @@ bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* return false; } -bool ffPackagesWriteCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, uint32_t num_elements) -{ - if (__builtin_expect(cacheContent->length == 0, false)) +bool ffPackagesWriteCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, uint32_t num_elements) { + if (__builtin_expect(cacheContent->length == 0, false)) { return false; + } ffStrbufAppendF(cacheContent, "%" PRIu32, num_elements); return ffWriteFileBuffer(cacheDir->chars, cacheContent); } #ifndef _WIN32 -uint32_t ffPackagesGetNumElements(const char* dirname, bool isdir) -{ +uint32_t ffPackagesGetNumElements(const char* dirname, bool isdir) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir(dirname); - if(dirp == NULL) + if (dirp == NULL) { return 0; + } uint32_t num_elements = 0; - struct dirent *entry; - while((entry = readdir(dirp)) != NULL) - { + struct dirent* entry; + while ((entry = readdir(dirp)) != NULL) { bool ok = false; - if (entry->d_name[0] != '.') - { -#if !defined(__sun) && !defined(__HAIKU__) - if(entry->d_type != DT_UNKNOWN && entry->d_type != DT_LNK) + if (entry->d_name[0] != '.') { +# if !defined(__sun) && !defined(__HAIKU__) + if (entry->d_type != DT_UNKNOWN && entry->d_type != DT_LNK) { ok = entry->d_type == (isdir ? DT_DIR : DT_REG); - else -#endif + } else +# endif { struct stat stbuf; - if (fstatat(dirfd(dirp), entry->d_name, &stbuf, 0) == 0) + if (fstatat(dirfd(dirp), entry->d_name, &stbuf, 0) == 0) { ok = isdir ? S_ISDIR(stbuf.st_mode) : S_ISREG(stbuf.st_mode); + } } } - if(ok) ++num_elements; + if (ok) { + ++num_elements; + } } - return num_elements; } #endif diff --git a/src/detection/packages/packages.h b/src/detection/packages/packages.h index 8b8a435d9..f5ae1c999 100644 --- a/src/detection/packages/packages.h +++ b/src/detection/packages/packages.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/packages/option.h" -typedef struct FFPackagesResult -{ +typedef struct FFPackagesResult { uint32_t amSystem; uint32_t amUser; uint32_t apk; @@ -48,7 +47,7 @@ typedef struct FFPackagesResult uint32_t winget; uint32_t xbps; - uint32_t all; //Make sure this goes last + uint32_t all; // Make sure this goes last FFstrbuf pacmanBranch; } FFPackagesResult; diff --git a/src/detection/packages/packages_apple.c b/src/detection/packages/packages_apple.c index 245b3d6b7..83ccaf047 100644 --- a/src/detection/packages/packages_apple.c +++ b/src/detection/packages/packages_apple.c @@ -4,9 +4,7 @@ #include "common/processing.h" #include "common/stringUtils.h" -static void countBrewPackages(FFstrbuf* baseDir, FFPackagesResult* result) -{ - +static void countBrewPackages(FFstrbuf* baseDir, FFPackagesResult* result) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, "/Caskroom"); @@ -18,48 +16,37 @@ static void countBrewPackages(FFstrbuf* baseDir, FFPackagesResult* result) ffStrbufSubstrBefore(baseDir, baseDirLength); } -static uint32_t getMacPortsPackages(FFstrbuf* baseDir) -{ +static uint32_t getMacPortsPackages(FFstrbuf* baseDir) { ffStrbufAppendS(baseDir, "/var/macports/software"); return ffPackagesGetNumElements(baseDir->chars, true); } -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { FF_STRBUF_AUTO_DESTROY baseDir = ffStrbufCreate(); - if (!(options->disabled & FF_PACKAGES_FLAG_BREW_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_BREW_BIT)) { const char* prefix = getenv("HOMEBREW_PREFIX"); - if (ffStrSet(prefix)) - { + if (ffStrSet(prefix)) { ffStrbufSetS(&baseDir, prefix); - } - else - { - #ifdef __aarch64__ + } else { +#ifdef __aarch64__ ffStrbufSetS(&baseDir, FASTFETCH_TARGET_DIR_ROOT "/opt/homebrew"); - #else +#else ffStrbufSetS(&baseDir, FASTFETCH_TARGET_DIR_USR "/local"); - #endif +#endif } countBrewPackages(&baseDir, result); } - if (!(options->disabled & FF_PACKAGES_FLAG_MACPORTS_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_MACPORTS_BIT)) { const char* prefix = getenv("MACPORTS_PREFIX"); - if (ffStrSet(prefix)) - { + if (ffStrSet(prefix)) { ffStrbufSetS(&baseDir, prefix); - } - else - { + } else { ffStrbufSetS(&baseDir, FASTFETCH_TARGET_DIR_ROOT "/opt/local"); } result->macports = getMacPortsPackages(&baseDir); } - if (!(options->disabled & FF_PACKAGES_FLAG_NIX_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_NIX_BIT)) { ffStrbufSetS(&baseDir, FASTFETCH_TARGET_DIR_ROOT); result->nixDefault += ffPackagesGetNix(&baseDir, "/nix/var/nix/profiles/default"); result->nixSystem += ffPackagesGetNix(&baseDir, "/run/current-system"); diff --git a/src/detection/packages/packages_bsd.c b/src/detection/packages/packages_bsd.c index 4ad2d8b49..32521160f 100644 --- a/src/detection/packages/packages_bsd.c +++ b/src/detection/packages/packages_bsd.c @@ -2,14 +2,14 @@ #include "common/settings.h" -static uint32_t getSQLite3Int(const char* dbPath, const char* query, const char* packageId) -{ +static uint32_t getSQLite3Int(const char* dbPath, const char* query, const char* packageId) { FF_STRBUF_AUTO_DESTROY cacheDir = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY cacheContent = ffStrbufCreate(); uint32_t num_elements; - if (ffPackagesReadCache(&cacheDir, &cacheContent, dbPath, packageId, &num_elements)) + if (ffPackagesReadCache(&cacheDir, &cacheContent, dbPath, packageId, &num_elements)) { return num_elements; + } num_elements = (uint32_t) ffSettingsGetSQLite3Int(dbPath, query); @@ -18,10 +18,11 @@ static uint32_t getSQLite3Int(const char* dbPath, const char* query, const char* return num_elements; } -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ - if (!(options->disabled & FF_PACKAGES_FLAG_PKG_BIT)) +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { + if (!(options->disabled & FF_PACKAGES_FLAG_PKG_BIT)) { result->pkg = getSQLite3Int(FASTFETCH_TARGET_DIR_ROOT "/var/db/pkg/local.sqlite", "SELECT count(*) FROM packages", "pkg"); - if (!(options->disabled & FF_PACKAGES_FLAG_MPORT_BIT)) + } + if (!(options->disabled & FF_PACKAGES_FLAG_MPORT_BIT)) { result->mport = getSQLite3Int(FASTFETCH_TARGET_DIR_ROOT "/var/db/mport/master.db", "SELECT count(*) FROM packages", "mport"); + } } diff --git a/src/detection/packages/packages_haiku.c b/src/detection/packages/packages_haiku.c index 45770589d..f63482107 100644 --- a/src/detection/packages/packages_haiku.c +++ b/src/detection/packages/packages_haiku.c @@ -2,12 +2,10 @@ #include "common/io.h" -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { // TODO: Use the Package Kit C++ API instead (would account for disabled packages) - if (!(options->disabled & FF_PACKAGES_FLAG_HPKG_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_HPKG_BIT)) { result->hpkgSystem = ffPackagesGetNumElements(FASTFETCH_TARGET_DIR_ROOT "/system/packages", false); result->hpkgUser = ffPackagesGetNumElements(FASTFETCH_TARGET_DIR_ROOT "/boot/home/config/packages", false); } diff --git a/src/detection/packages/packages_linux.c b/src/detection/packages/packages_linux.c index 8d9c9b0be..9c13694d6 100644 --- a/src/detection/packages/packages_linux.c +++ b/src/detection/packages/packages_linux.c @@ -6,8 +6,7 @@ #include "common/stringUtils.h" #include "detection/os/os.h" -static uint32_t getNumElements(FFstrbuf* baseDir, const char* dirname, bool isdir) -{ +static uint32_t getNumElements(FFstrbuf* baseDir, const char* dirname, bool isdir) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, dirname); uint32_t num_elements = ffPackagesGetNumElements(baseDir->chars, isdir); @@ -15,17 +14,16 @@ static uint32_t getNumElements(FFstrbuf* baseDir, const char* dirname, bool isdi return num_elements; } -static uint32_t getNumStringsImpl(const char* filename, const char* needle) -{ +static uint32_t getNumStringsImpl(const char* filename, const char* needle) { FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); - if (!ffReadFileBuffer(filename, &content)) + if (!ffReadFileBuffer(filename, &content)) { return 0; + } uint32_t count = 0; - char *iter = content.chars; + char* iter = content.chars; size_t needleLength = strlen(needle); - while ((iter = memmem(iter, content.length - (size_t)(iter - content.chars), needle, needleLength)) != NULL) - { + while ((iter = memmem(iter, content.length - (size_t) (iter - content.chars), needle, needleLength)) != NULL) { ++count; iter += needleLength; } @@ -33,8 +31,7 @@ static uint32_t getNumStringsImpl(const char* filename, const char* needle) return count; } -static uint32_t getNumStrings(FFstrbuf* baseDir, const char* filename, const char* needle, const char* packageId) -{ +static uint32_t getNumStrings(FFstrbuf* baseDir, const char* filename, const char* needle, const char* packageId) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, filename); @@ -42,8 +39,7 @@ static uint32_t getNumStrings(FFstrbuf* baseDir, const char* filename, const cha FF_STRBUF_AUTO_DESTROY cacheContent = ffStrbufCreate(); uint32_t num_elements; - if (ffPackagesReadCache(&cacheDir, &cacheContent, baseDir->chars, packageId, &num_elements)) - { + if (ffPackagesReadCache(&cacheDir, &cacheContent, baseDir->chars, packageId, &num_elements)) { ffStrbufSubstrBefore(baseDir, baseDirLength); return num_elements; } @@ -56,8 +52,7 @@ static uint32_t getNumStrings(FFstrbuf* baseDir, const char* filename, const cha return num_elements; } -static uint32_t getSQLite3Int(FFstrbuf* baseDir, const char* dbPath, const char* query, const char* packageId) -{ +static uint32_t getSQLite3Int(FFstrbuf* baseDir, const char* dbPath, const char* query, const char* packageId) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, dbPath); @@ -65,8 +60,7 @@ static uint32_t getSQLite3Int(FFstrbuf* baseDir, const char* dbPath, const char* FF_STRBUF_AUTO_DESTROY cacheContent = ffStrbufCreate(); uint32_t num_elements; - if (ffPackagesReadCache(&cacheDir, &cacheContent, baseDir->chars, packageId, &num_elements)) - { + if (ffPackagesReadCache(&cacheDir, &cacheContent, baseDir->chars, packageId, &num_elements)) { ffStrbufSubstrBefore(baseDir, baseDirLength); return num_elements; } @@ -79,31 +73,33 @@ static uint32_t getSQLite3Int(FFstrbuf* baseDir, const char* dbPath, const char* return num_elements; } -static uint32_t countFilesRecursiveImpl(FFstrbuf* baseDirPath, const char* filename) -{ +static uint32_t countFilesRecursiveImpl(FFstrbuf* baseDirPath, const char* filename) { uint32_t baseDirPathLength = baseDirPath->length; ffStrbufAppendC(baseDirPath, '/'); ffStrbufAppendS(baseDirPath, filename); bool exists = ffPathExists(baseDirPath->chars, FF_PATHTYPE_FILE); ffStrbufSubstrBefore(baseDirPath, baseDirPathLength); - if(exists) + if (exists) { return 1; + } DIR* dirp = opendir(baseDirPath->chars); - if(dirp == NULL) + if (dirp == NULL) { return 0; + } ffStrbufAppendC(baseDirPath, '/'); baseDirPathLength = baseDirPath->length; uint32_t sum = 0; - struct dirent *entry; - while((entry = readdir(dirp)) != NULL) { + struct dirent* entry; + while ((entry = readdir(dirp)) != NULL) { // According to the PMS, neither category nor package name can begin with '.', so no need to check for . or .. specifically - if(entry->d_type != DT_DIR || entry->d_name[0] == '.') + if (entry->d_type != DT_DIR || entry->d_name[0] == '.') { continue; + } ffStrbufAppendS(baseDirPath, entry->d_name); sum += countFilesRecursiveImpl(baseDirPath, filename); @@ -114,8 +110,7 @@ static uint32_t countFilesRecursiveImpl(FFstrbuf* baseDirPath, const char* filen return sum; } -static uint32_t countFilesRecursive(FFstrbuf* baseDir, const char* dirname, const char* filename) -{ +static uint32_t countFilesRecursive(FFstrbuf* baseDir, const char* dirname, const char* filename) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, dirname); uint32_t sum = countFilesRecursiveImpl(baseDir, filename); @@ -123,19 +118,19 @@ static uint32_t countFilesRecursive(FFstrbuf* baseDir, const char* dirname, cons return sum; } -static uint32_t getXBPSImpl(FFstrbuf* baseDir) -{ +static uint32_t getXBPSImpl(FFstrbuf* baseDir) { DIR* dir = opendir(baseDir->chars); - if(dir == NULL) + if (dir == NULL) { return 0; + } uint32_t result = 0; - struct dirent *entry; - while((entry = readdir(dir)) != NULL) - { - if(entry->d_type != DT_REG || !ffStrStartsWithIgnCase(entry->d_name, "pkgdb-")) + struct dirent* entry; + while ((entry = readdir(dir)) != NULL) { + if (entry->d_type != DT_REG || !ffStrStartsWithIgnCase(entry->d_name, "pkgdb-")) { continue; + } ffStrbufAppendC(baseDir, '/'); ffStrbufAppendS(baseDir, entry->d_name); @@ -147,8 +142,7 @@ static uint32_t getXBPSImpl(FFstrbuf* baseDir) return result; } -static uint32_t getXBPS(FFstrbuf* baseDir, const char* dirname) -{ +static uint32_t getXBPS(FFstrbuf* baseDir, const char* dirname) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, dirname); uint32_t result = getXBPSImpl(baseDir); @@ -156,26 +150,25 @@ static uint32_t getXBPS(FFstrbuf* baseDir, const char* dirname) return result; } -static uint32_t getSnap(FFstrbuf* baseDir) -{ +static uint32_t getSnap(FFstrbuf* baseDir) { uint32_t result = getNumElements(baseDir, "/snap", true); - if (result == 0) + if (result == 0) { result = getNumElements(baseDir, "/var/lib/snapd/snap", true); + } - //Accounting for the /snap/bin folder + // Accounting for the /snap/bin folder return result > 0 ? result - 1 : 0; } #ifdef FF_HAVE_RPM -#include "common/library.h" -#include -#include -#include -#include +# include "common/library.h" +# include +# include +# include +# include -static uint32_t getRpmFromLibrpm(void) -{ +static uint32_t getRpmFromLibrpm(void) { FF_LIBRARY_LOAD(rpm, 0, "librpm" FF_LIBRARY_EXTENSION, 12) FF_LIBRARY_LOAD_SYMBOL(rpm, rpmReadConfigFiles, 0) FF_LIBRARY_LOAD_SYMBOL(rpm, rpmtsCreate, 0) @@ -188,16 +181,17 @@ static uint32_t getRpmFromLibrpm(void) // Don't print any error messages ffrpmlogSetMask(RPMLOG_MASK(RPMLOG_EMERG)); - if(ffrpmReadConfigFiles(NULL, NULL) != 0) + if (ffrpmReadConfigFiles(NULL, NULL) != 0) { return 0; + } rpmts ts = ffrpmtsCreate(); - if(ts == NULL) + if (ts == NULL) { return 0; + } rpmdbMatchIterator mi = ffrpmtsInitIterator(ts, RPMDBI_LABEL, NULL, 0); - if(mi == NULL) - { + if (mi == NULL) { ffrpmtsFree(ts); return 0; } @@ -210,32 +204,33 @@ static uint32_t getRpmFromLibrpm(void) return count > 0 ? (uint32_t) count : 0; } -#endif //FF_HAVE_RPM +#endif // FF_HAVE_RPM -static uint32_t getAMPackages(FFstrbuf* baseDir) -{ +static uint32_t getAMPackages(FFstrbuf* baseDir) { uint32_t baseLength = baseDir->length; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (!dirp) return 0; + if (!dirp) { + return 0; + } uint32_t result = 0; - struct dirent *entry; - while ((entry = readdir(dirp)) != NULL) - { - if (entry->d_name[0] == '.') continue; - if (entry->d_type == DT_DIR) - { + struct dirent* entry; + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { + continue; + } + if (entry->d_type == DT_DIR) { ffStrbufAppendF(baseDir, "/%s/remove", entry->d_name); - if (ffPathExists(baseDir->chars, FF_PATHTYPE_FILE)) + if (ffPathExists(baseDir->chars, FF_PATHTYPE_FILE)) { ++result; + } ffStrbufSubstrBefore(baseDir, baseLength); } } return result; } -static uint32_t getAMSystem(FFstrbuf* baseDir) -{ +static uint32_t getAMSystem(FFstrbuf* baseDir) { // #771 uint32_t baseDirLength = baseDir->length; @@ -245,8 +240,7 @@ static uint32_t getAMSystem(FFstrbuf* baseDir) uint32_t result = 0; ffStrbufAppendS(baseDir, "/am/APP-MANAGER"); - if (ffPathExists(baseDir->chars, FF_PATHTYPE_FILE)) - { + if (ffPathExists(baseDir->chars, FF_PATHTYPE_FILE)) { ++result; // `am` itself is counted as a package too ffStrbufSubstrBefore(baseDir, optDirLength); result = getAMPackages(baseDir); @@ -256,58 +250,59 @@ static uint32_t getAMSystem(FFstrbuf* baseDir) return result; } -static uint32_t getAMUser(void) -{ - if (instance.state.platform.configDirs.length == 0) return 0; +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_FIRST(FFstrbuf, instance.state.platform.configDirs); uint32_t baseLen = baseDir->length; ffStrbufAppendS(baseDir, "appman/appman-config"); FF_STRBUF_AUTO_DESTROY packagesPath = ffStrbufCreate(); - if (ffReadFileBuffer(baseDir->chars, &packagesPath)) + if (ffReadFileBuffer(baseDir->chars, &packagesPath)) { ffStrbufTrimRightSpace(&packagesPath); + } ffStrbufSubstrBefore(baseDir, baseLen); return packagesPath.length > 0 ? getAMPackages(&packagesPath) : 0; } -static int compareHash(const void* a, const void* b) -{ +static int compareHash(const void* a, const void* b) { return memcmp(a, b, 32); } -static uint32_t getGuixPackagesImpl(char* filename) -{ +static uint32_t getGuixPackagesImpl(char* filename) { FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); - if (!ffAppendFileBuffer(filename, &content)) + if (!ffAppendFileBuffer(filename, &content)) { return 0; + } // Count number of unique /gnu/store/ paths in PROFILE/manifest based on their hash value. // Contains packages explicitly installed and their propagated inputs. char* pend = content.chars; - for (const char* pattern = content.chars; (pattern = strstr(pattern, "/gnu/store/")); pattern += 32) - { + for (const char* pattern = content.chars; (pattern = strstr(pattern, "/gnu/store/")); pattern += 32) { pattern += strlen("/gnu/store/"); memmove(pend, pattern, 32); pend += 32; } - if (pend == content.chars) + if (pend == content.chars) { return 0; + } qsort(content.chars, (size_t) (pend - content.chars) / 32, 32, compareHash); uint32_t count = 1; - for (const char* p = content.chars + 32; p < pend; p += 32) + for (const char* p = content.chars + 32; p < pend; p += 32) { count += compareHash(p - 32, p) != 0; + } return count; } -static uint32_t getGuixPackages(FFstrbuf* baseDir, const char* dirname) -{ +static uint32_t getGuixPackages(FFstrbuf* baseDir, const char* dirname) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, dirname); ffStrbufAppendS(baseDir, "/manifest"); @@ -316,19 +311,17 @@ static uint32_t getGuixPackages(FFstrbuf* baseDir, const char* dirname) return num_elements; } -static inline uint32_t getFlatpakRuntimePackagesArch(FFstrbuf* baseDir) -{ +static inline uint32_t getFlatpakRuntimePackagesArch(FFstrbuf* baseDir) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (dirp == NULL) + if (dirp == NULL) { return 0; + } uint32_t num_elements = 0; - struct dirent *entry; - while ((entry = readdir(dirp)) != NULL) - { - if(entry->d_type == DT_DIR && entry->d_name[0] != '.') - { + struct dirent* entry; + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_type == DT_DIR && entry->d_name[0] != '.') { num_elements += getNumElements(baseDir, entry->d_name, true); } } @@ -336,28 +329,29 @@ static inline uint32_t getFlatpakRuntimePackagesArch(FFstrbuf* baseDir) return num_elements; } -static inline uint32_t getFlatpakRuntimePackages(FFstrbuf* baseDir) -{ +static inline uint32_t getFlatpakRuntimePackages(FFstrbuf* baseDir) { ffStrbufAppendS(baseDir, "runtime/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (dirp == NULL) + if (dirp == NULL) { return 0; + } uint32_t runtimeDirLength = baseDir->length; uint32_t num_elements = 0; - struct dirent *entry; - while ((entry = readdir(dirp)) != NULL) - { - if(entry->d_type == DT_DIR && entry->d_name[0] != '.') - { + struct dirent* entry; + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_type == DT_DIR && entry->d_name[0] != '.') { // `flatpak list` ignores `.Locale` and `.Debug` packages, and maybe others const char* dot = strrchr(entry->d_name, '.'); - if (__builtin_expect(!dot, false)) continue; + if (__builtin_expect(!dot, false)) { + continue; + } dot++; - if (ffStrEquals(dot, "Locale") || ffStrEquals(dot, "Debug")) + if (ffStrEquals(dot, "Locale") || ffStrEquals(dot, "Debug")) { continue; + } ffStrbufAppendS(baseDir, entry->d_name); ffStrbufAppendC(baseDir, '/'); @@ -369,33 +363,31 @@ static inline uint32_t getFlatpakRuntimePackages(FFstrbuf* baseDir) return num_elements; } -static inline uint32_t getFlatpakAppPackages(FFstrbuf* baseDir) -{ +static inline uint32_t getFlatpakAppPackages(FFstrbuf* baseDir) { ffStrbufAppendS(baseDir, "app/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (dirp == NULL) + if (dirp == NULL) { return 0; + } uint32_t appDirLength = baseDir->length; uint32_t num_elements = 0; - struct dirent *entry; - while ((entry = readdir(dirp)) != NULL) - { - if(entry->d_type == DT_DIR && entry->d_name[0] != '.') - { + struct dirent* entry; + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_type == DT_DIR && entry->d_name[0] != '.') { ffStrbufAppendS(baseDir, entry->d_name); ffStrbufAppendS(baseDir, "/current"); - if (ffPathExists(baseDir->chars, FF_PATHTYPE_ANY)) // Exclude deleted apps, #1856 + if (ffPathExists(baseDir->chars, FF_PATHTYPE_ANY)) { // Exclude deleted apps, #1856 ++num_elements; + } ffStrbufSubstrBefore(baseDir, appDirLength); } } return num_elements; } -static uint32_t getFlatpakPackages(FFstrbuf* baseDir, const char* dirname) -{ +static uint32_t getFlatpakPackages(FFstrbuf* baseDir, const char* dirname) { uint32_t num_elements = 0; uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, dirname); @@ -412,8 +404,7 @@ static uint32_t getFlatpakPackages(FFstrbuf* baseDir, const char* dirname) return num_elements; } -static uint32_t getPacmanPackages(FFstrbuf* baseDir) -{ +static uint32_t getPacmanPackages(FFstrbuf* baseDir) { FF_STRBUF_AUTO_DESTROY dbPath = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY rootDir = ffStrbufCreate(); @@ -421,22 +412,18 @@ static uint32_t getPacmanPackages(FFstrbuf* baseDir) uint32_t baseDirLen = baseDir->length; ffStrbufAppendS(baseDir, "/etc/pacman.conf"); - bool confFound = ffParsePropFileValues(baseDir->chars, 2, (FFpropquery[]){ - { "DBPath =", &dbPath }, - { "RootDir =", &rootDir }, - }); + bool confFound = ffParsePropFileValues(baseDir->chars, 2, (FFpropquery[]) { + {"DBPath =", &dbPath}, + {"RootDir =", &rootDir}, + }); ffStrbufSubstrBefore(baseDir, baseDirLen); - if (confFound) - { - if (dbPath.length > 0) - { + if (confFound) { + if (dbPath.length > 0) { // If DBPath is specified, use it ffStrbufEnsureEndsWithC(&dbPath, '/'); ffStrbufAppendS(&dbPath, "local"); - } - else if (rootDir.length > 0) - { + } else if (rootDir.length > 0) { // ... otherwise, use RootDir ffStrbufDestroy(&dbPath); ffStrbufInitMove(&dbPath, &rootDir); @@ -445,79 +432,114 @@ static uint32_t getPacmanPackages(FFstrbuf* baseDir) } } - if (dbPath.length == 0) + if (dbPath.length == 0) { ffStrbufSetStatic(&dbPath, "/var/lib/pacman/local"); + } return getNumElements(baseDir, dbPath.chars, true); } -static void getPackageCounts(FFstrbuf* baseDir, FFPackagesResult* packageCounts, FFPackagesOptions* options) -{ - if (!(options->disabled & FF_PACKAGES_FLAG_APK_BIT)) packageCounts->apk += getNumStrings(baseDir, "/lib/apk/db/installed", "C:Q", "apk"); - if (!(options->disabled & FF_PACKAGES_FLAG_DPKG_BIT)) packageCounts->dpkg += getNumStrings(baseDir, "/var/lib/dpkg/status", "Status: install ok installed", "dpkg"); - if (!(options->disabled & FF_PACKAGES_FLAG_LPKG_BIT)) packageCounts->lpkg += getNumStrings(baseDir, "/opt/Loc-OS-LPKG/installed-lpkg/Listinstalled-lpkg.list", "\n", "lpkg"); - if (!(options->disabled & FF_PACKAGES_FLAG_EMERGE_BIT)) packageCounts->emerge += countFilesRecursive(baseDir, "/var/db/pkg", "SIZE"); - if (!(options->disabled & FF_PACKAGES_FLAG_EOPKG_BIT)) packageCounts->eopkg += getNumElements(baseDir, "/var/lib/eopkg/package", true); - if (!(options->disabled & FF_PACKAGES_FLAG_FLATPAK_BIT)) packageCounts->flatpakSystem += getFlatpakPackages(baseDir, "/var/lib"); - if (!(options->disabled & FF_PACKAGES_FLAG_KISS_BIT)) packageCounts->kiss += getNumElements(baseDir, "/var/db/kiss/installed", true); - if (!(options->disabled & FF_PACKAGES_FLAG_NIX_BIT)) - { +static void getPackageCounts(FFstrbuf* baseDir, FFPackagesResult* packageCounts, FFPackagesOptions* options) { + if (!(options->disabled & FF_PACKAGES_FLAG_APK_BIT)) { + packageCounts->apk += getNumStrings(baseDir, "/lib/apk/db/installed", "C:Q", "apk"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_DPKG_BIT)) { + packageCounts->dpkg += getNumStrings(baseDir, "/var/lib/dpkg/status", "Status: install ok installed", "dpkg"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_LPKG_BIT)) { + packageCounts->lpkg += getNumStrings(baseDir, "/opt/Loc-OS-LPKG/installed-lpkg/Listinstalled-lpkg.list", "\n", "lpkg"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_EMERGE_BIT)) { + packageCounts->emerge += countFilesRecursive(baseDir, "/var/db/pkg", "SIZE"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_EOPKG_BIT)) { + packageCounts->eopkg += getNumElements(baseDir, "/var/lib/eopkg/package", true); + } + if (!(options->disabled & FF_PACKAGES_FLAG_FLATPAK_BIT)) { + packageCounts->flatpakSystem += getFlatpakPackages(baseDir, "/var/lib"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_KISS_BIT)) { + packageCounts->kiss += getNumElements(baseDir, "/var/db/kiss/installed", true); + } + if (!(options->disabled & FF_PACKAGES_FLAG_NIX_BIT)) { packageCounts->nixDefault += ffPackagesGetNix(baseDir, "/nix/var/nix/profiles/default"); packageCounts->nixSystem += ffPackagesGetNix(baseDir, "/run/current-system"); } - if (!(options->disabled & FF_PACKAGES_FLAG_PACMAN_BIT)) packageCounts->pacman += getPacmanPackages(baseDir); - if (!(options->disabled & FF_PACKAGES_FLAG_LPKGBUILD_BIT)) packageCounts->lpkgbuild += getNumElements(baseDir, "/opt/Loc-OS-LPKG/lpkgbuild/remove", false); - if (!(options->disabled & FF_PACKAGES_FLAG_PKGTOOL_BIT)) packageCounts->pkgtool += getNumElements(baseDir, "/var/log/packages", false); - if (!(options->disabled & FF_PACKAGES_FLAG_RPM_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_PACMAN_BIT)) { + packageCounts->pacman += getPacmanPackages(baseDir); + } + if (!(options->disabled & FF_PACKAGES_FLAG_LPKGBUILD_BIT)) { + packageCounts->lpkgbuild += getNumElements(baseDir, "/opt/Loc-OS-LPKG/lpkgbuild/remove", false); + } + if (!(options->disabled & FF_PACKAGES_FLAG_PKGTOOL_BIT)) { + packageCounts->pkgtool += getNumElements(baseDir, "/var/log/packages", false); + } + if (!(options->disabled & FF_PACKAGES_FLAG_RPM_BIT)) { // `Sigmd5` is the only table that doesn't contain the virtual `gpg-pubkey` package packageCounts->rpm += getSQLite3Int(baseDir, "/var/lib/rpm/rpmdb.sqlite", "SELECT count(*) FROM Sigmd5", "rpm"); } - if (!(options->disabled & FF_PACKAGES_FLAG_SNAP_BIT)) packageCounts->snap += getSnap(baseDir); - if (!(options->disabled & FF_PACKAGES_FLAG_XBPS_BIT)) packageCounts->xbps += getXBPS(baseDir, "/var/db/xbps"); - if (!(options->disabled & FF_PACKAGES_FLAG_BREW_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_SNAP_BIT)) { + packageCounts->snap += getSnap(baseDir); + } + if (!(options->disabled & FF_PACKAGES_FLAG_XBPS_BIT)) { + packageCounts->xbps += getXBPS(baseDir, "/var/db/xbps"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_BREW_BIT)) { packageCounts->brewCask += getNumElements(baseDir, "/home/linuxbrew/.linuxbrew/Caskroom", true); packageCounts->brew += getNumElements(baseDir, "/home/linuxbrew/.linuxbrew/Cellar", true); } - if (!(options->disabled & FF_PACKAGES_FLAG_PALUDIS_BIT)) packageCounts->paludis += countFilesRecursive(baseDir, "/var/db/paludis/repositories", "environment.bz2"); - if (!(options->disabled & FF_PACKAGES_FLAG_OPKG_BIT)) packageCounts->opkg += getNumStrings(baseDir, "/usr/lib/opkg/status", "Package:", "opkg"); // openwrt - if (!(options->disabled & FF_PACKAGES_FLAG_AM_BIT)) packageCounts->amSystem = getAMSystem(baseDir); - if (!(options->disabled & FF_PACKAGES_FLAG_SORCERY_BIT)) packageCounts->sorcery += getNumStrings(baseDir, "/var/state/sorcery/packages", ":installed:", "sorcery"); - if (!(options->disabled & FF_PACKAGES_FLAG_GUIX_BIT)) - { - packageCounts->guixSystem += getGuixPackages(baseDir, "/run/current-system/profile"); + if (!(options->disabled & FF_PACKAGES_FLAG_PALUDIS_BIT)) { + packageCounts->paludis += countFilesRecursive(baseDir, "/var/db/paludis/repositories", "environment.bz2"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_OPKG_BIT)) { + packageCounts->opkg += getNumStrings(baseDir, "/usr/lib/opkg/status", "Package:", "opkg"); // openwrt + } + if (!(options->disabled & FF_PACKAGES_FLAG_AM_BIT)) { + packageCounts->amSystem = getAMSystem(baseDir); + } + if (!(options->disabled & FF_PACKAGES_FLAG_SORCERY_BIT)) { + packageCounts->sorcery += getNumStrings(baseDir, "/var/state/sorcery/packages", ":installed:", "sorcery"); + } + if (!(options->disabled & FF_PACKAGES_FLAG_GUIX_BIT)) { + packageCounts->guixSystem += getGuixPackages(baseDir, "/run/current-system/profile"); + } + 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); + } + if (!(options->disabled & FF_PACKAGES_FLAG_MOSS_BIT)) { + packageCounts->moss += getSQLite3Int(baseDir, "/.moss/db/state", "SELECT COUNT(*) FROM state_selections WHERE state_id = (SELECT MAX(id) FROM state)", "moss"); } - 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); - if (!(options->disabled & FF_PACKAGES_FLAG_MOSS_BIT)) packageCounts->moss += getSQLite3Int(baseDir, "/.moss/db/state", "SELECT COUNT(*) FROM state_selections WHERE state_id = (SELECT MAX(id) FROM state)", "moss"); } -static void getPackageCountsRegular(FFstrbuf* baseDir, FFPackagesResult* packageCounts, FFPackagesOptions* options) -{ +static void getPackageCountsRegular(FFstrbuf* baseDir, FFPackagesResult* packageCounts, FFPackagesOptions* options) { getPackageCounts(baseDir, packageCounts, options); - if (!(options->disabled & FF_PACKAGES_FLAG_PACMAN_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_PACMAN_BIT)) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, FASTFETCH_TARGET_DIR_ETC "/pacman-mirrors.conf"); - if(ffParsePropFile(baseDir->chars, "Branch =", &packageCounts->pacmanBranch) && packageCounts->pacmanBranch.length == 0) + if (ffParsePropFile(baseDir->chars, "Branch =", &packageCounts->pacmanBranch) && packageCounts->pacmanBranch.length == 0) { ffStrbufAppendS(&packageCounts->pacmanBranch, "stable"); + } ffStrbufSubstrBefore(baseDir, baseDirLength); } } -static void getPackageCountsBedrock(FFstrbuf* baseDir, FFPackagesResult* packageCounts, FFPackagesOptions* options) -{ +static void getPackageCountsBedrock(FFstrbuf* baseDir, FFPackagesResult* packageCounts, FFPackagesOptions* options) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, "/bedrock/strata"); FF_AUTO_CLOSE_DIR DIR* dir = opendir(baseDir->chars); - if(dir == NULL) - { + if (dir == NULL) { ffStrbufSubstrBefore(baseDir, baseDirLength); return; } @@ -526,12 +548,13 @@ static void getPackageCountsBedrock(FFstrbuf* baseDir, FFPackagesResult* package uint32_t baseDirLength2 = baseDir->length; struct dirent* entry; - while((entry = readdir(dir)) != NULL) - { - if(entry->d_type != DT_DIR) + while ((entry = readdir(dir)) != NULL) { + if (entry->d_type != DT_DIR) { continue; - if(entry->d_name[0] == '.') + } + if (entry->d_name[0] == '.') { continue; + } ffStrbufAppendS(baseDir, entry->d_name); getPackageCounts(baseDir, packageCounts, options); @@ -541,40 +564,37 @@ static void getPackageCountsBedrock(FFstrbuf* baseDir, FFPackagesResult* package ffStrbufSubstrBefore(baseDir, baseDirLength); } -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { FF_STRBUF_AUTO_DESTROY baseDir = ffStrbufCreateA(512); ffStrbufAppendS(&baseDir, FASTFETCH_TARGET_DIR_ROOT); - if(ffStrbufIgnCaseEqualS(&ffDetectOS()->id, "bedrock")) + if (ffStrbufIgnCaseEqualS(&ffDetectOS()->id, "bedrock")) { getPackageCountsBedrock(&baseDir, result, options); - else + } else { getPackageCountsRegular(&baseDir, result, options); + } - // If SQL failed, we can still try with librpm. - // This is needed on openSUSE, which seems to use a proprietary database file - // This method doesn't work on bedrock, so we do it here. - #ifdef FF_HAVE_RPM - if(!(options->disabled & FF_PACKAGES_FLAG_RPM_BIT) && result->rpm == 0) - result->rpm = getRpmFromLibrpm(); - #endif +// If SQL failed, we can still try with librpm. +// This is needed on openSUSE, which seems to use a proprietary database file +// This method doesn't work on bedrock, so we do it here. +#ifdef FF_HAVE_RPM + if (!(options->disabled & FF_PACKAGES_FLAG_RPM_BIT) && result->rpm == 0) { + result->rpm = getRpmFromLibrpm(); + } +#endif ffStrbufSet(&baseDir, &instance.state.platform.homeDir); - if (!(options->disabled & FF_PACKAGES_FLAG_NIX_BIT)) - { + if (!(options->disabled & FF_PACKAGES_FLAG_NIX_BIT)) { // Count packages from $HOME/.nix-profile result->nixUser += ffPackagesGetNix(&baseDir, ".nix-profile"); // Check in $XDG_STATE_HOME/nix/profile FF_STRBUF_AUTO_DESTROY stateHome = ffStrbufCreate(); const char* stateHomeEnv = getenv("XDG_STATE_HOME"); - if (ffStrSet(stateHomeEnv)) - { + if (ffStrSet(stateHomeEnv)) { ffStrbufSetS(&stateHome, stateHomeEnv); ffStrbufEnsureEndsWithC(&stateHome, '/'); - } - else - { + } else { ffStrbufSet(&stateHome, &instance.state.platform.homeDir); ffStrbufAppendS(&stateHome, ".local/state/"); } @@ -585,18 +605,20 @@ void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) result->nixUser += ffPackagesGetNix(&userPkgsDir, instance.state.platform.userName.chars); } - if (!(options->disabled & FF_PACKAGES_FLAG_GUIX_BIT)) - { - result->guixUser += getGuixPackages(&baseDir, ".guix-profile"); - result->guixHome += getGuixPackages(&baseDir, ".guix-home/profile"); + if (!(options->disabled & FF_PACKAGES_FLAG_GUIX_BIT)) { + result->guixUser += getGuixPackages(&baseDir, ".guix-profile"); + result->guixHome += getGuixPackages(&baseDir, ".guix-home/profile"); } - if (!(options->disabled & FF_PACKAGES_FLAG_FLATPAK_BIT)) + if (!(options->disabled & FF_PACKAGES_FLAG_FLATPAK_BIT)) { result->flatpakUser = getFlatpakPackages(&baseDir, "/.local/share"); + } - if (!(options->disabled & FF_PACKAGES_FLAG_AM_BIT)) + if (!(options->disabled & FF_PACKAGES_FLAG_AM_BIT)) { result->amUser = getAMUser(); + } - if (!(options->disabled & FF_PACKAGES_FLAG_SOAR_BIT)) + if (!(options->disabled & FF_PACKAGES_FLAG_SOAR_BIT)) { result->soar += getSQLite3Int(&baseDir, ".local/share/soar/db/soar.db", "SELECT COUNT(DISTINCT pkg_id || pkg_name) FROM packages WHERE is_installed = true", "soar"); + } } diff --git a/src/detection/packages/packages_nbsd.c b/src/detection/packages/packages_nbsd.c index a713a2b07..3a96c239a 100644 --- a/src/detection/packages/packages_nbsd.c +++ b/src/detection/packages/packages_nbsd.c @@ -2,8 +2,8 @@ #include "common/io.h" -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ - if (!(options->disabled & FF_PACKAGES_FLAG_PKGSRC_BIT)) +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { + if (!(options->disabled & FF_PACKAGES_FLAG_PKGSRC_BIT)) { result->pkgsrc = ffPackagesGetNumElements(FASTFETCH_TARGET_DIR_ROOT "/usr/pkg/pkgdb", true); + } } diff --git a/src/detection/packages/packages_nix.c b/src/detection/packages/packages_nix.c index 1d9a21df7..b62dd67eb 100644 --- a/src/detection/packages/packages_nix.c +++ b/src/detection/packages/packages_nix.c @@ -3,10 +3,10 @@ #include "common/processing.h" #include "common/stringUtils.h" -static bool isValidNixPkg(FFstrbuf* pkg) -{ - if (!ffPathExists(pkg->chars, FF_PATHTYPE_DIRECTORY)) +static bool isValidNixPkg(FFstrbuf* pkg) { + if (!ffPathExists(pkg->chars, FF_PATHTYPE_DIRECTORY)) { return false; + } ffStrbufSubstrAfterLastC(pkg, '/'); if ( @@ -15,33 +15,39 @@ static bool isValidNixPkg(FFstrbuf* pkg) ffStrbufEndsWithS(pkg, "-man") || ffStrbufEndsWithS(pkg, "-info") || ffStrbufEndsWithS(pkg, "-dev") || - ffStrbufEndsWithS(pkg, "-bin") - ) return false; + ffStrbufEndsWithS(pkg, "-bin")) { + return false; + } - enum { START, DIGIT, DOT, MATCH } state = START; + enum { START, + DIGIT, + DOT, + MATCH } state = START; - for (uint32_t i = 0; i < pkg->length; i++) - { + for (uint32_t i = 0; i < pkg->length; i++) { char c = pkg->chars[i]; - switch (state) - { + switch (state) { case START: - if (ffCharIsDigit(c)) + if (ffCharIsDigit(c)) { state = DIGIT; + } break; case DIGIT: - if (ffCharIsDigit(c)) + if (ffCharIsDigit(c)) { continue; - if (c == '.') + } + if (c == '.') { state = DOT; - else + } else { state = START; + } break; case DOT: - if (ffCharIsDigit(c)) + if (ffCharIsDigit(c)) { state = MATCH; - else + } else { state = START; + } break; case MATCH: break; @@ -51,81 +57,69 @@ static bool isValidNixPkg(FFstrbuf* pkg) return state == MATCH; } -static bool checkNixCache(FFstrbuf* cacheDir, FFstrbuf* hash, uint32_t* count) -{ - if (!ffPathExists(cacheDir->chars, FF_PATHTYPE_FILE)) +static bool checkNixCache(FFstrbuf* cacheDir, FFstrbuf* hash, uint32_t* count) { + if (!ffPathExists(cacheDir->chars, FF_PATHTYPE_FILE)) { return false; + } FF_STRBUF_AUTO_DESTROY cacheContent = ffStrbufCreate(); - if (!ffReadFileBuffer(cacheDir->chars, &cacheContent)) + if (!ffReadFileBuffer(cacheDir->chars, &cacheContent)) { return false; + } // Format: \n uint32_t split = ffStrbufFirstIndexC(&cacheContent, '\n'); - if (split == cacheContent.length) + if (split == cacheContent.length) { return false; + } ffStrbufSetNS(hash, split, cacheContent.chars); - *count = (uint32_t)atoi(cacheContent.chars + split + 1); + *count = (uint32_t) atoi(cacheContent.chars + split + 1); return true; } -static bool writeNixCache(FFstrbuf* cacheDir, FFstrbuf* hash, uint32_t count) -{ +static bool writeNixCache(FFstrbuf* cacheDir, FFstrbuf* hash, uint32_t count) { FF_STRBUF_AUTO_DESTROY cacheContent = ffStrbufCreateCopy(hash); ffStrbufAppendF(&cacheContent, "\n%u", count); return ffWriteFileBuffer(cacheDir->chars, &cacheContent); } -static uint32_t getNixPackagesImpl(char* path) -{ - //Nix detection is kinda slow, so we only do it if the dir exists - if(!ffPathExists(path, FF_PATHTYPE_DIRECTORY)) +static uint32_t getNixPackagesImpl(char* path) { + // Nix detection is kinda slow, so we only do it if the dir exists + if (!ffPathExists(path, FF_PATHTYPE_DIRECTORY)) { return 0; + } FF_STRBUF_AUTO_DESTROY cacheDir = ffStrbufCreateCopy(&instance.state.platform.cacheDir); ffStrbufEnsureEndsWithC(&cacheDir, '/'); ffStrbufAppendS(&cacheDir, "fastfetch/packages/nix"); ffStrbufAppendS(&cacheDir, path); - //Check the hash first to determine if we need to recompute the count + // Check the hash first to determine if we need to recompute the count FF_STRBUF_AUTO_DESTROY hash = ffStrbufCreateA(64); FF_STRBUF_AUTO_DESTROY cacheHash = ffStrbufCreateA(64); uint32_t count = 0; - ffProcessAppendStdOut(&hash, (char* const[]) { - "nix-store", - "--query", - "--hash", - path, - NULL - }); + ffProcessAppendStdOut(&hash, (char* const[]) {"nix-store", "--query", "--hash", path, NULL}); - if (checkNixCache(&cacheDir, &cacheHash, &count) && ffStrbufEqual(&hash, &cacheHash)) + if (checkNixCache(&cacheDir, &cacheHash, &count) && ffStrbufEqual(&hash, &cacheHash)) { return count; + } - //Cache is invalid, recompute the count + // Cache is invalid, recompute the count count = 0; - //Implementation based on bash script from here: - //https://github.com/fastfetch-cli/fastfetch/issues/195#issuecomment-1191748222 + // Implementation based on bash script from here: + // https://github.com/fastfetch-cli/fastfetch/issues/195#issuecomment-1191748222 FF_STRBUF_AUTO_DESTROY output = ffStrbufCreateA(1024); - ffProcessAppendStdOut(&output, (char* const[]) { - "nix-store", - "--query", - "--requisites", - path, - NULL - }); + ffProcessAppendStdOut(&output, (char* const[]) {"nix-store", "--query", "--requisites", path, NULL}); uint32_t lineLength = 0; - for (uint32_t i = 0; i < output.length; i++) - { - if (output.chars[i] != '\n') - { + for (uint32_t i = 0; i < output.length; i++) { + if (output.chars[i] != '\n') { lineLength++; continue; } @@ -134,10 +128,10 @@ static uint32_t getNixPackagesImpl(char* path) FFstrbuf line = { .allocated = 0, .length = lineLength, - .chars = output.chars + i - lineLength - }; - if (isValidNixPkg(&line)) + .chars = output.chars + i - lineLength}; + if (isValidNixPkg(&line)) { count++; + } lineLength = 0; } @@ -145,8 +139,7 @@ static uint32_t getNixPackagesImpl(char* path) return count; } -uint32_t ffPackagesGetNix(FFstrbuf* baseDir, const char* dirname) -{ +uint32_t ffPackagesGetNix(FFstrbuf* baseDir, const char* dirname) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, dirname); uint32_t num_elements = getNixPackagesImpl(baseDir->chars); diff --git a/src/detection/packages/packages_nosupport.c b/src/detection/packages/packages_nosupport.c index a6d9a7b90..c0984db8f 100644 --- a/src/detection/packages/packages_nosupport.c +++ b/src/detection/packages/packages_nosupport.c @@ -1,5 +1,4 @@ #include "packages.h" -void ffDetectPackagesImpl(FF_MAYBE_UNUSED FFPackagesResult* result, FF_MAYBE_UNUSED FFPackagesOptions* options) -{ +void ffDetectPackagesImpl(FF_MAYBE_UNUSED FFPackagesResult* result, FF_MAYBE_UNUSED FFPackagesOptions* options) { } diff --git a/src/detection/packages/packages_obsd.c b/src/detection/packages/packages_obsd.c index 2ff2cc737..ef37fb48b 100644 --- a/src/detection/packages/packages_obsd.c +++ b/src/detection/packages/packages_obsd.c @@ -2,8 +2,8 @@ #include "common/io.h" -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ - if (!(options->disabled & FF_PACKAGES_FLAG_PKG_BIT)) +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { + if (!(options->disabled & FF_PACKAGES_FLAG_PKG_BIT)) { result->pkg = ffPackagesGetNumElements(FASTFETCH_TARGET_DIR_ROOT "/var/db/pkg", true); + } } diff --git a/src/detection/packages/packages_sunos.c b/src/detection/packages/packages_sunos.c index a112d79b0..b471f0914 100644 --- a/src/detection/packages/packages_sunos.c +++ b/src/detection/packages/packages_sunos.c @@ -1,18 +1,17 @@ #include "packages.h" #include -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ - if (!(options->disabled & FF_PACKAGES_FLAG_PKG_BIT)) - { +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { + if (!(options->disabled & FF_PACKAGES_FLAG_PKG_BIT)) { yyjson_doc* doc = yyjson_read_file(FASTFETCH_TARGET_DIR_ROOT "/var/pkg/state/installed/catalog.attrs", YYJSON_READ_NOFLAG, NULL, NULL); - if (doc) - { + if (doc) { yyjson_val* packageCount = yyjson_obj_get(yyjson_doc_get_root(doc), "package-count"); - if (packageCount) + if (packageCount) { result->pkg = (uint32_t) yyjson_get_uint(packageCount); + } } } - if (!(options->disabled & FF_PACKAGES_FLAG_PKGSRC_BIT)) + if (!(options->disabled & FF_PACKAGES_FLAG_PKGSRC_BIT)) { result->pkgsrc = ffPackagesGetNumElements(FASTFETCH_TARGET_DIR_ROOT "/usr/pkg/pkgdb", true); + } } diff --git a/src/detection/packages/packages_windows.c b/src/detection/packages/packages_windows.c index 1ec5cb07a..7e7ff710a 100644 --- a/src/detection/packages/packages_windows.c +++ b/src/detection/packages/packages_windows.c @@ -12,10 +12,11 @@ #include #include -static uint32_t getNumElements(const char* searchPath, DWORD type, const wchar_t* ignore) -{ +static uint32_t getNumElements(const char* searchPath, DWORD type, const wchar_t* ignore) { FF_AUTO_CLOSE_FD HANDLE dfd = CreateFileA(searchPath, FILE_LIST_DIRECTORY | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (dfd == INVALID_HANDLE_VALUE) return 0; + if (dfd == INVALID_HANDLE_VALUE) { + return 0; + } bool flag = ignore == NULL; uint32_t counter = 0; @@ -28,55 +29,63 @@ static uint32_t getNumElements(const char* searchPath, DWORD type, const wchar_t IO_STATUS_BLOCK ioStatus = {}; NTSTATUS status = NtQueryDirectoryFile( dfd, - NULL, NULL, NULL, + NULL, + NULL, + NULL, &ioStatus, - buffer, ARRAY_SIZE(buffer), + buffer, + ARRAY_SIZE(buffer), FileDirectoryInformation, FALSE, NULL, - firstScan - ); + firstScan); firstScan = FALSE; - if (!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW) break; + if (!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW) { + break; + } for (FILE_DIRECTORY_INFORMATION* entry = (FILE_DIRECTORY_INFORMATION*) buffer; ; - entry = (FILE_DIRECTORY_INFORMATION*) ((uint8_t*) entry + entry->NextEntryOffset)) - { - if (!(entry->FileAttributes & type)) continue; + entry = (FILE_DIRECTORY_INFORMATION*) ((uint8_t*) entry + entry->NextEntryOffset)) { + if (!(entry->FileAttributes & type)) { + continue; + } if (!flag && ignoreLen == entry->FileNameLength / sizeof(*entry->FileName) && - _wcsnicmp(entry->FileName, ignore, ignoreLen) == 0) - { + _wcsnicmp(entry->FileName, ignore, ignoreLen) == 0) { flag = true; continue; } counter++; - if (entry->NextEntryOffset == 0) break; + if (entry->NextEntryOffset == 0) { + break; + } } - if (status == STATUS_SUCCESS) break; // No next page + if (status == STATUS_SUCCESS) { + break; // No next page + } } - if(type == FILE_ATTRIBUTE_DIRECTORY && counter >= 2) + if (type == FILE_ATTRIBUTE_DIRECTORY && counter >= 2) { counter -= 2; // accounting for . and .. + } return counter; } -static inline void wrapYyjsonFree(yyjson_doc** doc) -{ +static inline void wrapYyjsonFree(yyjson_doc** doc) { assert(doc); - if (*doc) + if (*doc) { yyjson_doc_free(*doc); + } } -static void detectScoop(FFPackagesResult* result) -{ +static void detectScoop(FFPackagesResult* result) { FF_STRBUF_AUTO_DESTROY scoopPath = ffStrbufCreateA(MAX_PATH + 3); ffStrbufAppend(&scoopPath, &instance.state.platform.homeDir); ffStrbufAppendS(&scoopPath, ".config/scoop/config.json"); @@ -84,18 +93,19 @@ static void detectScoop(FFPackagesResult* result) yyjson_val* root = NULL; yyjson_doc* __attribute__((__cleanup__(wrapYyjsonFree))) doc = yyjson_read_file(scoopPath.chars, 0, NULL, NULL); - if (doc) - { + if (doc) { root = yyjson_doc_get_root(doc); - if (!yyjson_is_obj(root)) root = NULL; + if (!yyjson_is_obj(root)) { + root = NULL; + } } { ffStrbufClear(&scoopPath); - if (root) + if (root) { ffStrbufSetJsonVal(&scoopPath, yyjson_obj_get(root, "root_path")); - if (scoopPath.length == 0) - { + } + if (scoopPath.length == 0) { ffStrbufSet(&scoopPath, &instance.state.platform.homeDir); ffStrbufAppendS(&scoopPath, "/scoop"); } @@ -105,13 +115,12 @@ static void detectScoop(FFPackagesResult* result) { ffStrbufClear(&scoopPath); - if (root) + if (root) { ffStrbufSetJsonVal(&scoopPath, yyjson_obj_get(root, "global_path")); - if (scoopPath.length == 0) - { + } + if (scoopPath.length == 0) { PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramData, KF_FLAG_DEFAULT, NULL, &pPath))) - { + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramData, KF_FLAG_DEFAULT, NULL, &pPath))) { ffStrbufSetWS(&scoopPath, pPath); CoTaskMemFree(pPath); } @@ -122,11 +131,11 @@ static void detectScoop(FFPackagesResult* result) } } -static void detectChoco(FF_MAYBE_UNUSED FFPackagesResult* result) -{ +static void detectChoco(FF_MAYBE_UNUSED FFPackagesResult* result) { const char* chocoInstall = getenv("ChocolateyInstall"); - if(!chocoInstall || chocoInstall[0] == '\0') + if (!chocoInstall || chocoInstall[0] == '\0') { return; + } char chocoPath[MAX_PATH + 3]; char* pend = ffStrCopy(chocoPath, chocoInstall, ARRAY_SIZE(chocoPath)); @@ -134,11 +143,11 @@ static void detectChoco(FF_MAYBE_UNUSED FFPackagesResult* result) result->choco = getNumElements(chocoPath, FILE_ATTRIBUTE_DIRECTORY, L"choco"); } -static void detectPacman(FFPackagesResult* result) -{ +static void detectPacman(FFPackagesResult* result) { const char* msystemPrefix = getenv("MSYSTEM_PREFIX"); - if(!msystemPrefix) + if (!msystemPrefix) { return; + } // MSYS2 char pacmanPath[MAX_PATH + 3]; @@ -147,39 +156,48 @@ static void detectPacman(FFPackagesResult* result) result->pacman = getNumElements(pacmanPath, FILE_ATTRIBUTE_DIRECTORY, NULL); } -static void detectWinget(FFPackagesResult* result) -{ +static void detectWinget(FFPackagesResult* result) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buffer, (char* []) { - "winget.exe", - "list", - "--disable-interactivity", - NULL, - })) + if (ffProcessAppendStdOut(&buffer, (char*[]) { + "winget.exe", + "list", + "--disable-interactivity", + NULL, + })) { return; + } uint32_t index = ffStrbufFirstIndexS(&buffer, "--\r\n"); // Ignore garbage and table headers - if (index == buffer.length) + if (index == buffer.length) { return; + } uint32_t count = 0; for ( index += strlen("--\r\n"); (index = ffStrbufNextIndexC(&buffer, index, '\n')) < buffer.length; - ++index - ) + ++index) { ++count; + } - if (buffer.chars[buffer.length - 1] != '\n') // count last line + if (buffer.chars[buffer.length - 1] != '\n') { // count last line ++count; + } result->winget = count; } -void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) -{ - if (!(options->disabled & FF_PACKAGES_FLAG_SCOOP_BIT)) detectScoop(result); - if (!(options->disabled & FF_PACKAGES_FLAG_CHOCO_BIT)) detectChoco(result); - if (!(options->disabled & FF_PACKAGES_FLAG_PACMAN_BIT)) detectPacman(result); - if (!(options->disabled & FF_PACKAGES_FLAG_WINGET_BIT)) detectWinget(result); +void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { + if (!(options->disabled & FF_PACKAGES_FLAG_SCOOP_BIT)) { + detectScoop(result); + } + if (!(options->disabled & FF_PACKAGES_FLAG_CHOCO_BIT)) { + detectChoco(result); + } + if (!(options->disabled & FF_PACKAGES_FLAG_PACMAN_BIT)) { + detectPacman(result); + } + if (!(options->disabled & FF_PACKAGES_FLAG_WINGET_BIT)) { + detectWinget(result); + } } diff --git a/src/detection/physicaldisk/physicaldisk.h b/src/detection/physicaldisk/physicaldisk.h index d0b84d37e..9f987b9bf 100644 --- a/src/detection/physicaldisk/physicaldisk.h +++ b/src/detection/physicaldisk/physicaldisk.h @@ -3,8 +3,7 @@ #define FF_PHYSICALDISK_TEMP_UNSET (-DBL_MAX) -typedef enum __attribute__((__packed__)) FFPhysicalDiskType -{ +typedef enum __attribute__((__packed__)) FFPhysicalDiskType { FF_PHYSICALDISK_TYPE_NONE = 0, // If neither is set, it's unknown @@ -21,8 +20,7 @@ typedef enum __attribute__((__packed__)) FFPhysicalDiskType } FFPhysicalDiskType; static_assert(sizeof(FFPhysicalDiskType) == sizeof(uint8_t), ""); -typedef struct FFPhysicalDiskResult -{ +typedef struct FFPhysicalDiskResult { FFstrbuf name; FFstrbuf interconnect; FFstrbuf serial; diff --git a/src/detection/physicaldisk/physicaldisk_apple.c b/src/detection/physicaldisk/physicaldisk_apple.c index 860d33999..5284b2d41 100644 --- a/src/detection/physicaldisk/physicaldisk_apple.c +++ b/src/detection/physicaldisk/physicaldisk_apple.c @@ -8,68 +8,73 @@ #include #include #ifdef MAC_OS_X_VERSION_10_15 - #include +# include #endif #ifdef MAC_OS_X_VERSION_10_15 -static inline void wrapIoDestroyPlugInInterface(IOCFPlugInInterface*** pluginInf) -{ +static inline void wrapIoDestroyPlugInInterface(IOCFPlugInInterface*** pluginInf) { assert(pluginInf); - if (*pluginInf) + if (*pluginInf) { IODestroyPlugInInterface(*pluginInf); + } } #endif -static const char* detectSsdTemp(io_service_t entryPhysical, double* temp) -{ - #ifdef MAC_OS_X_VERSION_10_15 +static const char* detectSsdTemp(io_service_t entryPhysical, double* temp) { +#ifdef MAC_OS_X_VERSION_10_15 __attribute__((__cleanup__(wrapIoDestroyPlugInInterface))) IOCFPlugInInterface** pluginInf = NULL; int32_t score; - if (IOCreatePlugInInterfaceForService(entryPhysical, kIONVMeSMARTUserClientTypeID, kIOCFPlugInInterfaceID, &pluginInf, &score) != kIOReturnSuccess) + if (IOCreatePlugInInterfaceForService(entryPhysical, kIONVMeSMARTUserClientTypeID, kIOCFPlugInInterfaceID, &pluginInf, &score) != kIOReturnSuccess) { return "IOCreatePlugInInterfaceForService() failed"; + } IONVMeSMARTInterface** smartInf = NULL; - if ((*pluginInf)->QueryInterface(pluginInf, CFUUIDGetUUIDBytes(kIONVMeSMARTInterfaceID), (LPVOID) &smartInf) != kIOReturnSuccess) + if ((*pluginInf)->QueryInterface(pluginInf, CFUUIDGetUUIDBytes(kIONVMeSMARTInterfaceID), (LPVOID) &smartInf) != kIOReturnSuccess) { return "QueryInterface() failed"; + } NVMeSMARTData smartData; const char* error = NULL; - if ((*smartInf)->SMARTReadData(smartInf, &smartData) == kIOReturnSuccess) + if ((*smartInf)->SMARTReadData(smartInf, &smartData) == kIOReturnSuccess) { *temp = smartData.TEMPERATURE - 273; - else + } else { error = "SMARTReadData() failed"; + } (*pluginInf)->Release(smartInf); return error; - #else +#else return "No support for old MacOS version"; - #endif +#endif } -const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { FF_IOOBJECT_AUTO_RELEASE io_iterator_t iterator = 0; - if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching(kIOMediaClass), &iterator) != KERN_SUCCESS) + if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching(kIOMediaClass), &iterator) != KERN_SUCCESS) { return "IOServiceGetMatchingServices() failed"; + } io_registry_entry_t registryEntry; - while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) - { + while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryPartition = registryEntry; io_name_t deviceName; - if (IORegistryEntryGetName(registryEntry, deviceName) != KERN_SUCCESS) + if (IORegistryEntryGetName(registryEntry, deviceName) != KERN_SUCCESS) { continue; + } - if (options->namePrefix.length && strncmp(deviceName, options->namePrefix.chars, options->namePrefix.length) != 0) + if (options->namePrefix.length && strncmp(deviceName, options->namePrefix.chars, options->namePrefix.length) != 0) { continue; + } FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryDriver = 0; - if (IORegistryEntryGetParentEntry(entryPartition, kIOServicePlane, &entryDriver) != KERN_SUCCESS) + if (IORegistryEntryGetParentEntry(entryPartition, kIOServicePlane, &entryDriver) != KERN_SUCCESS) { continue; + } - if (!IOObjectConformsTo(entryDriver, kIOBlockStorageDriverClass)) // physical disk only + if (!IOObjectConformsTo(entryDriver, kIOBlockStorageDriverClass)) { // physical disk only continue; + } FFPhysicalDiskResult* device = (FFPhysicalDiskResult*) ffListAdd(result); ffStrbufInit(&device->serial); @@ -82,59 +87,60 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) device->temperature = FF_PHYSICALDISK_TEMP_UNSET; FF_CFTYPE_AUTO_RELEASE CFBooleanRef removable = IORegistryEntryCreateCFProperty(entryPartition, CFSTR(kIOMediaRemovableKey), kCFAllocatorDefault, kNilOptions); - if (removable) + if (removable) { device->type |= CFBooleanGetValue(removable) ? FF_PHYSICALDISK_TYPE_REMOVABLE : FF_PHYSICALDISK_TYPE_FIXED; + } FF_CFTYPE_AUTO_RELEASE CFBooleanRef writable = IORegistryEntryCreateCFProperty(entryPartition, CFSTR(kIOMediaWritableKey), kCFAllocatorDefault, kNilOptions); - if (writable) + if (writable) { device->type |= CFBooleanGetValue(writable) ? FF_PHYSICALDISK_TYPE_READWRITE : FF_PHYSICALDISK_TYPE_READONLY; + } FF_CFTYPE_AUTO_RELEASE CFStringRef bsdName = IORegistryEntryCreateCFProperty(entryPartition, CFSTR(kIOBSDNameKey), kCFAllocatorDefault, kNilOptions); - if (bsdName) - { + if (bsdName) { ffCfStrGetString(bsdName, &device->devPath); ffStrbufPrependS(&device->devPath, "/dev/"); } FF_CFTYPE_AUTO_RELEASE CFNumberRef mediaSize = IORegistryEntryCreateCFProperty(entryPartition, CFSTR(kIOMediaSizeKey), kCFAllocatorDefault, kNilOptions); - if (mediaSize) + if (mediaSize) { ffCfNumGetInt64(mediaSize, (int64_t*) &device->size); - else + } else { device->size = 0; + } FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryPhysical = 0; - if (IORegistryEntryGetParentEntry(entryDriver, kIOServicePlane, &entryPhysical) == KERN_SUCCESS) - { + if (IORegistryEntryGetParentEntry(entryDriver, kIOServicePlane, &entryPhysical) == KERN_SUCCESS) { FF_CFTYPE_AUTO_RELEASE CFDictionaryRef protocolCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyProtocolCharacteristicsKey), kCFAllocatorDefault, kNilOptions); - if (protocolCharacteristics) + if (protocolCharacteristics) { ffCfDictGetString(protocolCharacteristics, CFSTR(kIOPropertyPhysicalInterconnectTypeKey), &device->interconnect); + } FF_CFTYPE_AUTO_RELEASE CFDictionaryRef deviceCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyDeviceCharacteristicsKey), kCFAllocatorDefault, kNilOptions); - if (deviceCharacteristics) - { + if (deviceCharacteristics) { ffCfDictGetString(deviceCharacteristics, CFSTR(kIOPropertyProductSerialNumberKey), &device->serial); ffStrbufTrimSpace(&device->serial); ffCfDictGetString(deviceCharacteristics, CFSTR(kIOPropertyProductRevisionLevelKey), &device->revision); ffStrbufTrimRightSpace(&device->revision); CFStringRef mediumType = (CFStringRef) CFDictionaryGetValue(deviceCharacteristics, CFSTR(kIOPropertyMediumTypeKey)); - if (mediumType) - { - if (CFStringCompare(mediumType, CFSTR(kIOPropertyMediumTypeSolidStateKey), 0) == 0) + if (mediumType) { + if (CFStringCompare(mediumType, CFSTR(kIOPropertyMediumTypeSolidStateKey), 0) == 0) { device->type |= FF_PHYSICALDISK_TYPE_SSD; - else if (CFStringCompare(mediumType, CFSTR(kIOPropertyMediumTypeRotationalKey), 0) == 0) + } else if (CFStringCompare(mediumType, CFSTR(kIOPropertyMediumTypeRotationalKey), 0) == 0) { device->type |= FF_PHYSICALDISK_TYPE_HDD; + } } } - #ifdef MAC_OS_X_VERSION_10_15 - if (options->temp) - { +#ifdef MAC_OS_X_VERSION_10_15 + if (options->temp) { FF_CFTYPE_AUTO_RELEASE CFBooleanRef nvmeSMARTCapable = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyNVMeSMARTCapableKey), kCFAllocatorDefault, kNilOptions); - if (nvmeSMARTCapable && CFBooleanGetValue(nvmeSMARTCapable)) + if (nvmeSMARTCapable && CFBooleanGetValue(nvmeSMARTCapable)) { detectSsdTemp(entryPhysical, &device->temperature); + } } - #endif +#endif } } diff --git a/src/detection/physicaldisk/physicaldisk_bsd.c b/src/detection/physicaldisk/physicaldisk_bsd.c index 4878d7805..5a186ce8a 100644 --- a/src/detection/physicaldisk/physicaldisk_bsd.c +++ b/src/detection/physicaldisk/physicaldisk_bsd.c @@ -2,65 +2,69 @@ #if __has_include() -#include "common/stringUtils.h" +# include "common/stringUtils.h" -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include -const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { struct gmesh geomTree; - if (geom_gettree(&geomTree) < 0) + if (geom_gettree(&geomTree) < 0) { return "geom_gettree() failed"; + } - if (geom_stats_open() < 0) + if (geom_stats_open() < 0) { return "geom_stats_open() failed"; + } void* snap = geom_stats_snapshot_get(); struct devstat* snapIter; - while ((snapIter = geom_stats_snapshot_next(snap)) != NULL) - { - if (snapIter->device_type & DEVSTAT_TYPE_PASS) + while ((snapIter = geom_stats_snapshot_next(snap)) != NULL) { + if (snapIter->device_type & DEVSTAT_TYPE_PASS) { continue; + } struct gident* geomId = geom_lookupid(&geomTree, snapIter->id); - if (geomId == NULL) + if (geomId == NULL) { continue; - if (geomId->lg_what != ISPROVIDER) + } + if (geomId->lg_what != ISPROVIDER) { continue; + } struct gprovider* provider = (struct gprovider*) geomId->lg_ptr; - if (provider->lg_geom->lg_rank != 1) + if (provider->lg_geom->lg_rank != 1) { continue; + } // Should memory disk (MD) be considered as physical disk? - //if (!ffStrEquals(provider->lg_geom->lg_class->lg_name, "DISK")) + // if (!ffStrEquals(provider->lg_geom->lg_class->lg_name, "DISK")) // continue; FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateS(provider->lg_name); FF_STRBUF_AUTO_DESTROY identifier = ffStrbufCreate(); FFPhysicalDiskType type = FF_PHYSICALDISK_TYPE_NONE; - for (struct gconfig* ptr = provider->lg_config.lh_first; ptr; ptr = ptr->lg_config.le_next) - { - if (ffStrEquals(ptr->lg_name, "descr")) + for (struct gconfig* ptr = provider->lg_config.lh_first; ptr; ptr = ptr->lg_config.le_next) { + if (ffStrEquals(ptr->lg_name, "descr")) { ffStrbufSetS(&name, ptr->lg_val); - else if (ffStrEquals(ptr->lg_name, "rotationrate") && !ffStrEquals(ptr->lg_val, "unknown")) + } else if (ffStrEquals(ptr->lg_name, "rotationrate") && !ffStrEquals(ptr->lg_val, "unknown")) { type |= ffStrEquals(ptr->lg_val, "0") ? FF_PHYSICALDISK_TYPE_SSD : FF_PHYSICALDISK_TYPE_HDD; - else if (ffStrEquals(ptr->lg_name, "ident")) + } else if (ffStrEquals(ptr->lg_name, "ident")) { ffStrbufSetS(&identifier, ptr->lg_val); - else if (ffStrEquals(ptr->lg_name, "access")) - { - if (ffStrEquals(ptr->lg_val, "read-only")) + } else if (ffStrEquals(ptr->lg_name, "access")) { + if (ffStrEquals(ptr->lg_val, "read-only")) { type |= FF_PHYSICALDISK_TYPE_READONLY; - else if (ffStrEquals(ptr->lg_val, "read-write")) + } else if (ffStrEquals(ptr->lg_val, "read-write")) { type |= FF_PHYSICALDISK_TYPE_READWRITE; + } } } - if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) + if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) { continue; + } FFPhysicalDiskResult* device = (FFPhysicalDiskResult*) ffListAdd(result); ffStrbufInitF(&device->devPath, "/dev/%s", provider->lg_name); @@ -68,23 +72,30 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) ffStrbufTrimSpace(&device->serial); ffStrbufInit(&device->revision); ffStrbufInit(&device->interconnect); - switch (snapIter->device_type & DEVSTAT_TYPE_IF_MASK) - { - case DEVSTAT_TYPE_IF_SCSI: ffStrbufAppendS(&device->interconnect, "SCSI"); break; - case DEVSTAT_TYPE_IF_IDE: ffStrbufAppendS(&device->interconnect, "IDE"); break; - case DEVSTAT_TYPE_IF_OTHER: ffStrbufAppendS(&device->interconnect, "OTHER"); break; + switch (snapIter->device_type & DEVSTAT_TYPE_IF_MASK) { + case DEVSTAT_TYPE_IF_SCSI: + ffStrbufAppendS(&device->interconnect, "SCSI"); + break; + case DEVSTAT_TYPE_IF_IDE: + ffStrbufAppendS(&device->interconnect, "IDE"); + break; + case DEVSTAT_TYPE_IF_OTHER: + ffStrbufAppendS(&device->interconnect, "OTHER"); + break; // https://github.com/freebsd/freebsd-src/commit/d282baddb0b029ca8466d23ac51e95c918442535 - case 0x040 /*DEVSTAT_TYPE_IF_NVME*/: ffStrbufAppendS(&device->interconnect, "NVMe"); break; + case 0x040 /*DEVSTAT_TYPE_IF_NVME*/: + ffStrbufAppendS(&device->interconnect, "NVMe"); + break; } device->size = (uint64_t) provider->lg_mediasize; ffStrbufInitMove(&device->name, &name); - if (!(device->type & FF_PHYSICALDISK_TYPE_READONLY) && !(device->type & FF_PHYSICALDISK_TYPE_READWRITE)) - { + if (!(device->type & FF_PHYSICALDISK_TYPE_READONLY) && !(device->type & FF_PHYSICALDISK_TYPE_READWRITE)) { int acr = 1, acw = 1; // Number of partitions mounted for reading or writing - if (sscanf(provider->lg_mode, "r%dw%de%*d", &acr, &acw) == 2 && acr) + if (sscanf(provider->lg_mode, "r%dw%de%*d", &acr, &acw) == 2 && acr) { type |= acw ? FF_PHYSICALDISK_TYPE_READWRITE : FF_PHYSICALDISK_TYPE_READONLY; + } } device->type = type; @@ -97,8 +108,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) return NULL; } #else -const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { return "Fastfetch was compiled without libgeom support"; } #endif diff --git a/src/detection/physicaldisk/physicaldisk_haiku.c b/src/detection/physicaldisk/physicaldisk_haiku.c index deed69653..9909c4628 100644 --- a/src/detection/physicaldisk/physicaldisk_haiku.c +++ b/src/detection/physicaldisk/physicaldisk_haiku.c @@ -8,18 +8,19 @@ #include #include -static const char* detectDisk(FFstrbuf* path, const char* diskType, FFlist* result) -{ +static const char* detectDisk(FFstrbuf* path, const char* diskType, FFlist* result) { FF_AUTO_CLOSE_FD int rawfd = open(path->chars, O_RDONLY | O_CLOEXEC); - if (rawfd < 0) return "detectDisk: open(rawfd) failed"; + if (rawfd < 0) { + return "detectDisk: open(rawfd) failed"; + } device_geometry geometry; - if (ioctl(rawfd, B_GET_GEOMETRY, &geometry, sizeof(geometry)) < 0) + if (ioctl(rawfd, B_GET_GEOMETRY, &geometry, sizeof(geometry)) < 0) { return "ioctl(B_GET_GEOMETRY) failed"; + } char name[B_OS_NAME_LENGTH]; - if (ioctl(rawfd, B_GET_DEVICE_NAME, name, sizeof(name)) != 0) - { + if (ioctl(rawfd, B_GET_DEVICE_NAME, name, sizeof(name)) != 0) { // ioctl reports `not a tty` for NVME drives for some reason snprintf(name, sizeof(name), "Unknown %s drive", diskType); } @@ -39,49 +40,53 @@ static const char* detectDisk(FFstrbuf* path, const char* diskType, FFlist* resu return NULL; } -static const char* searchRawDeviceFile(FFstrbuf* path, const char* diskType, FFlist* result) -{ +static const char* searchRawDeviceFile(FFstrbuf* path, const char* diskType, FFlist* result) { FF_AUTO_CLOSE_DIR DIR* dir = opendir(path->chars); - if (!dir) return "detectDiskType: opendir() failed"; + if (!dir) { + return "detectDiskType: opendir() failed"; + } uint32_t baseLen = path->length; struct dirent* entry; - while((entry = readdir(dir))) - { - if (entry->d_name[0] == '.') continue; + while ((entry = readdir(dir))) { + if (entry->d_name[0] == '.') { + continue; + } ffStrbufAppendC(path, '/'); ffStrbufAppendS(path, entry->d_name); struct stat st; - if (stat(path->chars, &st) != 0) - { + if (stat(path->chars, &st) != 0) { ffStrbufSubstrBefore(path, baseLen); continue; } - if (S_ISDIR(st.st_mode)) + if (S_ISDIR(st.st_mode)) { searchRawDeviceFile(path, diskType, result); - else if (ffStrEquals(entry->d_name, "raw")) + } else if (ffStrEquals(entry->d_name, "raw")) { detectDisk(path, diskType, result); + } ffStrbufSubstrBefore(path, baseLen); } return NULL; } -const char* ffDetectPhysicalDisk(FFlist* result, FF_MAYBE_UNUSED FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FFlist* result, FF_MAYBE_UNUSED FFPhysicalDiskOptions* options) { FF_AUTO_CLOSE_DIR DIR* dir = opendir("/dev/disk"); - if (!dir) return "opendir(/dev/disk) failed"; + if (!dir) { + return "opendir(/dev/disk) failed"; + } FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateA(64); ffStrbufAppendS(&path, "/dev/disk/"); uint32_t baseLen = path.length; struct dirent* entry; - while((entry = readdir(dir))) - { - if (entry->d_name[0] == '.' || ffStrEquals(entry->d_name, "virtual")) continue; + while ((entry = readdir(dir))) { + if (entry->d_name[0] == '.' || ffStrEquals(entry->d_name, "virtual")) { + continue; + } ffStrbufAppendS(&path, entry->d_name); searchRawDeviceFile(&path, entry->d_name, result); ffStrbufSubstrBefore(&path, baseLen); diff --git a/src/detection/physicaldisk/physicaldisk_linux.c b/src/detection/physicaldisk/physicaldisk_linux.c index 33019d7bc..f3ddbc0e2 100644 --- a/src/detection/physicaldisk/physicaldisk_linux.c +++ b/src/detection/physicaldisk/physicaldisk_linux.c @@ -8,8 +8,7 @@ #include #include -static double detectNvmeTemp(int devfd) -{ +static double detectNvmeTemp(int devfd) { char pathHwmon[] = "hwmon$/temp1_input"; for (char c = '0'; c <= '9'; c++) // hopefully there's only one digit @@ -17,8 +16,7 @@ static double detectNvmeTemp(int devfd) pathHwmon[strlen("hwmon")] = c; char buffer[64]; ssize_t size = ffReadFileDataRelative(devfd, pathHwmon, ARRAY_SIZE(buffer), buffer); - if (size > 0) - { + if (size > 0) { buffer[size] = '\0'; double temp = strtod(buffer, NULL); return temp > 0 && temp < 10000000 /*VMware*/ ? temp / 1000 : FF_PHYSICALDISK_TEMP_UNSET; @@ -28,49 +26,48 @@ static double detectNvmeTemp(int devfd) return FF_PHYSICALDISK_TEMP_UNSET; } -static void parsePhysicalDisk(int dfd, const char* devName, FFPhysicalDiskOptions* options, FFlist* result) -{ +static void parsePhysicalDisk(int dfd, const char* devName, FFPhysicalDiskOptions* options, FFlist* result) { int devfd = openat(dfd, "device", O_RDONLY | O_CLOEXEC | O_PATH | O_DIRECTORY); - if (devfd < 0) return; // virtual device + if (devfd < 0) { + return; // virtual device + } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); { - if (ffAppendFileBufferRelative(devfd, "vendor", &name)) - { + if (ffAppendFileBufferRelative(devfd, "vendor", &name)) { ffStrbufTrimRightSpace(&name); - if (name.length > 0) + if (name.length > 0) { ffStrbufAppendC(&name, ' '); + } } ffAppendFileBufferRelative(devfd, "model", &name); ffStrbufTrimRightSpace(&name); - if (name.length == 0) + if (name.length == 0) { ffStrbufSetS(&name, devName); + } - if (ffStrStartsWith(devName, "nvme")) - { + if (ffStrStartsWith(devName, "nvme")) { int devid, nsid; - if (sscanf(devName, "nvme%dn%d", &devid, &nsid) == 2) - { + if (sscanf(devName, "nvme%dn%d", &devid, &nsid) == 2) { bool multiNs = nsid > 1; - if (!multiNs) - { + if (!multiNs) { char pathSysBlock[32]; snprintf(pathSysBlock, ARRAY_SIZE(pathSysBlock), "/dev/nvme%dn2", devid); multiNs = access(pathSysBlock, F_OK) == 0; } - if (multiNs) - { + if (multiNs) { // In Asahi Linux, there are multiple namespaces for the same NVMe drive. ffStrbufAppendF(&name, " - %d", nsid); } } } - if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) + if (options->namePrefix.length && !ffStrbufStartsWith(&name, &options->namePrefix)) { return; + } } FFPhysicalDiskResult* device = (FFPhysicalDiskResult*) ffListAdd(result); @@ -81,117 +78,116 @@ static void parsePhysicalDisk(int dfd, const char* devName, FFPhysicalDiskOption bool isVirtual = false; { ffStrbufInit(&device->interconnect); - if (ffStrStartsWith(devName, "nvme")) + if (ffStrStartsWith(devName, "nvme")) { ffStrbufSetStatic(&device->interconnect, "NVMe"); - else if (ffStrStartsWith(devName, "mmcblk")) + } else if (ffStrStartsWith(devName, "mmcblk")) { ffStrbufSetStatic(&device->interconnect, "MMC"); - else if (ffStrStartsWith(devName, "md")) - { + } else if (ffStrStartsWith(devName, "md")) { ffStrbufSetStatic(&device->interconnect, "RAID"); isVirtual = true; - } - else - { + } else { char pathSysDeviceLink[64]; snprintf(pathSysDeviceLink, ARRAY_SIZE(pathSysDeviceLink), "/sys/block/%s/device", devName); char pathSysDeviceReal[PATH_MAX]; - if (realpath(pathSysDeviceLink, pathSysDeviceReal)) - { - if (strstr(pathSysDeviceReal, "/usb") != NULL) + if (realpath(pathSysDeviceLink, pathSysDeviceReal)) { + if (strstr(pathSysDeviceReal, "/usb") != NULL) { ffStrbufSetStatic(&device->interconnect, "USB"); - else if (strstr(pathSysDeviceReal, "/ata") != NULL) + } else if (strstr(pathSysDeviceReal, "/ata") != NULL) { ffStrbufSetStatic(&device->interconnect, "ATA"); - else if (strstr(pathSysDeviceReal, "/scsi") != NULL) + } else if (strstr(pathSysDeviceReal, "/scsi") != NULL) { ffStrbufSetStatic(&device->interconnect, "SCSI"); - else if (strstr(pathSysDeviceReal, "/nvme") != NULL) + } else if (strstr(pathSysDeviceReal, "/nvme") != NULL) { ffStrbufSetStatic(&device->interconnect, "NVMe"); - else if (strstr(pathSysDeviceReal, "/virtio") != NULL) - { + } else if (strstr(pathSysDeviceReal, "/virtio") != NULL) { ffStrbufSetStatic(&device->interconnect, "Virtual"); isVirtual = true; - } - else - { - if (ffAppendFileBufferRelative(devfd, "transport", &device->interconnect)) + } else { + if (ffAppendFileBufferRelative(devfd, "transport", &device->interconnect)) { ffStrbufTrimRightSpace(&device->interconnect); + } } } } } - if (!isVirtual) - { + if (!isVirtual) { char isRotationalChar = '1'; - if (ffReadFileDataRelative(dfd, "queue/rotational", 1, &isRotationalChar) > 0) + if (ffReadFileDataRelative(dfd, "queue/rotational", 1, &isRotationalChar) > 0) { device->type |= isRotationalChar == '1' ? FF_PHYSICALDISK_TYPE_HDD : FF_PHYSICALDISK_TYPE_SSD; + } } { char blkSize[32]; ssize_t fileSize = ffReadFileDataRelative(dfd, "size", ARRAY_SIZE(blkSize) - 1, blkSize); - if (fileSize > 0) - { + if (fileSize > 0) { blkSize[fileSize] = 0; device->size = (uint64_t) strtoul(blkSize, NULL, 10) * 512; - } - else + } else { device->size = 0; + } } { char removableChar = '0'; - if (ffReadFileDataRelative(dfd, "removable", 1, &removableChar) > 0) + if (ffReadFileDataRelative(dfd, "removable", 1, &removableChar) > 0) { device->type |= removableChar == '1' ? FF_PHYSICALDISK_TYPE_REMOVABLE : FF_PHYSICALDISK_TYPE_FIXED; + } } { char roChar = '0'; - if (ffReadFileDataRelative(dfd, "ro", 1, &roChar) > 0) + if (ffReadFileDataRelative(dfd, "ro", 1, &roChar) > 0) { device->type |= roChar == '1' ? FF_PHYSICALDISK_TYPE_READONLY : FF_PHYSICALDISK_TYPE_READWRITE; + } } { ffStrbufInit(&device->serial); - if (ffReadFileBufferRelative(devfd, "serial", &device->serial)) + if (ffReadFileBufferRelative(devfd, "serial", &device->serial)) { ffStrbufTrimSpace(&device->serial); + } } { ffStrbufInit(&device->revision); - if (ffReadFileBufferRelative(devfd, "firmware_rev", &device->revision)) + if (ffReadFileBufferRelative(devfd, "firmware_rev", &device->revision)) { ffStrbufTrimRightSpace(&device->revision); - else - { - if (ffReadFileBufferRelative(devfd, "rev", &device->revision)) + } else { + if (ffReadFileBufferRelative(devfd, "rev", &device->revision)) { ffStrbufTrimRightSpace(&device->revision); + } } } - if (options->temp) + if (options->temp) { device->temperature = detectNvmeTemp(devfd); - else + } else { device->temperature = FF_PHYSICALDISK_TEMP_UNSET; + } } -const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { FF_AUTO_CLOSE_DIR DIR* sysBlockDirp = opendir("/sys/block/"); - if(sysBlockDirp == NULL) + if (sysBlockDirp == NULL) { return "opendir(\"/sys/block/\") == NULL"; + } struct dirent* sysBlockEntry; - while ((sysBlockEntry = readdir(sysBlockDirp)) != NULL) - { + while ((sysBlockEntry = readdir(sysBlockDirp)) != NULL) { const char* const devName = sysBlockEntry->d_name; - if (devName[0] == '.') + if (devName[0] == '.') { continue; + } char pathSysBlock[sizeof("/sys/block/") + sizeof(sysBlockEntry->d_name)]; snprintf(pathSysBlock, ARRAY_SIZE(pathSysBlock), "/sys/block/%s", devName); int dfd = openat(dirfd(sysBlockDirp), devName, O_RDONLY | O_CLOEXEC | O_PATH | O_DIRECTORY); - if (dfd > 0) parsePhysicalDisk(dfd, devName, options, result); + if (dfd > 0) { + parsePhysicalDisk(dfd, devName, options, result); + } } return NULL; diff --git a/src/detection/physicaldisk/physicaldisk_nosupport.c b/src/detection/physicaldisk/physicaldisk_nosupport.c index 1e4c2412e..e922f8ab4 100644 --- a/src/detection/physicaldisk/physicaldisk_nosupport.c +++ b/src/detection/physicaldisk/physicaldisk_nosupport.c @@ -1,6 +1,5 @@ #include "physicaldisk.h" -const char* ffDetectPhysicalDisk(FF_MAYBE_UNUSED FFlist* result, FF_MAYBE_UNUSED FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FF_MAYBE_UNUSED FFlist* result, FF_MAYBE_UNUSED FFPhysicalDiskOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/physicaldisk/physicaldisk_sunos.c b/src/detection/physicaldisk/physicaldisk_sunos.c index aeb5ff27e..89a5757d2 100644 --- a/src/detection/physicaldisk/physicaldisk_sunos.c +++ b/src/detection/physicaldisk/physicaldisk_sunos.c @@ -5,24 +5,23 @@ #include #include -struct FFWalkTreeBundle -{ +struct FFWalkTreeBundle { FFPhysicalDiskOptions* options; FFlist* disks; }; -static int walkDevTree(di_node_t node, di_minor_t minor, struct FFWalkTreeBundle* bundle) -{ - if (di_minor_spectype(minor) != S_IFCHR || !ffStrEquals(di_minor_name(minor), "a,raw")) return DI_WALK_CONTINUE; +static int walkDevTree(di_node_t node, di_minor_t minor, struct FFWalkTreeBundle* bundle) { + if (di_minor_spectype(minor) != S_IFCHR || !ffStrEquals(di_minor_name(minor), "a,raw")) { + return DI_WALK_CONTINUE; + } char* productId; char* vendorId; - if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-product-id", &productId) > 0 - && di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-vendor-id", &vendorId) > 0) - { + if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-product-id", &productId) > 0 && di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-vendor-id", &vendorId) > 0) { FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateF("%s %s", vendorId, productId); - if (bundle->options->namePrefix.length && !ffStrbufStartsWithIgnCase(&name, &bundle->options->namePrefix)) + if (bundle->options->namePrefix.length && !ffStrbufStartsWithIgnCase(&name, &bundle->options->namePrefix)) { return DI_WALK_CONTINUE; + } FFPhysicalDiskResult* device = (FFPhysicalDiskResult*) ffListAdd(bundle->disks); ffStrbufInitMove(&device->name, &name); @@ -35,42 +34,44 @@ static int walkDevTree(di_node_t node, di_minor_t minor, struct FFWalkTreeBundle device->size = 0; char* buf; - if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-serial-no", &buf) > 0) - { + if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-serial-no", &buf) > 0) { ffStrbufSetS(&device->serial, buf); ffStrbufTrimSpace(&device->serial); } - if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-revision-id", &buf) > 0) - { + if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "inquiry-revision-id", &buf) > 0) { ffStrbufSetS(&device->revision, buf); ffStrbufTrimRightSpace(&device->revision); } - if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "class", &buf) > 0) + if (di_prop_lookup_strings(DDI_DEV_T_ANY, node, "class", &buf) > 0) { ffStrbufSetS(&device->interconnect, buf); + } device->type |= di_prop_find(DDI_DEV_T_ANY, node, "removable-media") ? FF_PHYSICALDISK_TYPE_REMOVABLE : FF_PHYSICALDISK_TYPE_FIXED; int* value; - if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-solid-state", &value) > 0) + if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-solid-state", &value) > 0) { device->type |= *value ? FF_PHYSICALDISK_TYPE_SSD : FF_PHYSICALDISK_TYPE_HDD; - if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "inquiry-device-type", &value) > 0) - device->type |= *value == DTYPE_DIRECT ? FF_PHYSICALDISK_TYPE_READWRITE : *value == DTYPE_RODIRECT ? FF_PHYSICALDISK_TYPE_READONLY : 0; + } + if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "inquiry-device-type", &value) > 0) { + device->type |= *value == DTYPE_DIRECT ? FF_PHYSICALDISK_TYPE_READWRITE : *value == DTYPE_RODIRECT ? FF_PHYSICALDISK_TYPE_READONLY + : 0; + } int64_t* nblocks; - if (di_prop_lookup_int64(DDI_DEV_T_ANY, node, "device-nblocks", &nblocks) > 0 - && di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-blksize", &value) > 0) + if (di_prop_lookup_int64(DDI_DEV_T_ANY, node, "device-nblocks", &nblocks) > 0 && di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-blksize", &value) > 0) { device->size = (uint64_t) ((uint64_t) *nblocks * (uint64_t) *value); + } } return DI_WALK_CONTINUE; } -const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { di_node_t rootNode = di_init("/", DINFOCPYALL); - if (rootNode == DI_NODE_NIL) + if (rootNode == DI_NODE_NIL) { return "di_init() failed"; - di_walk_minor(rootNode, DDI_NT_BLOCK, DI_WALK_CLDFIRST, &(struct FFWalkTreeBundle) { options, result }, (void*) walkDevTree); + } + di_walk_minor(rootNode, DDI_NT_BLOCK, DI_WALK_CLDFIRST, &(struct FFWalkTreeBundle) {options, result}, (void*) walkDevTree); di_fini(rootNode); return NULL; diff --git a/src/detection/physicaldisk/physicaldisk_windows.c b/src/detection/physicaldisk/physicaldisk_windows.c index 6c359e83b..41eb03be7 100644 --- a/src/detection/physicaldisk/physicaldisk_windows.c +++ b/src/detection/physicaldisk/physicaldisk_windows.c @@ -6,53 +6,53 @@ #include #include -static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFPhysicalDiskOptions* options) -{ +static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFPhysicalDiskOptions* options) { FF_AUTO_CLOSE_FD HANDLE hDevice = CreateFileW(szDevice, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - if (hDevice == INVALID_HANDLE_VALUE) + if (hDevice == INVALID_HANDLE_VALUE) { return false; + } DWORD retSize; char sddBuffer[4096]; - if(!DeviceIoControl( - hDevice, - IOCTL_STORAGE_QUERY_PROPERTY, - &(STORAGE_PROPERTY_QUERY) { - .PropertyId = StorageDeviceProperty, - .QueryType = PropertyStandardQuery, - }, - sizeof(STORAGE_PROPERTY_QUERY), - &sddBuffer, - sizeof(sddBuffer), - &retSize, - NULL - ) || retSize == 0) + if (!DeviceIoControl( + hDevice, + IOCTL_STORAGE_QUERY_PROPERTY, + &(STORAGE_PROPERTY_QUERY) { + .PropertyId = StorageDeviceProperty, + .QueryType = PropertyStandardQuery, + }, + sizeof(STORAGE_PROPERTY_QUERY), + &sddBuffer, + sizeof(sddBuffer), + &retSize, + NULL) || + retSize == 0) { return true; + } FFPhysicalDiskResult* device = (FFPhysicalDiskResult*) ffListAdd(result); device->type = FF_PHYSICALDISK_TYPE_NONE; STORAGE_DEVICE_DESCRIPTOR* sdd = (STORAGE_DEVICE_DESCRIPTOR*) sddBuffer; ffStrbufInit(&device->name); - if (sdd->VendorIdOffset != 0) - { + if (sdd->VendorIdOffset != 0) { ffStrbufSetS(&device->name, (const char*) sddBuffer + sdd->VendorIdOffset); ffStrbufTrim(&device->name, ' '); } - if (sdd->ProductIdOffset != 0) - { - if (device->name.length) + if (sdd->ProductIdOffset != 0) { + if (device->name.length) { ffStrbufAppendC(&device->name, ' '); + } ffStrbufAppendS(&device->name, (const char*) sddBuffer + sdd->ProductIdOffset); ffStrbufTrimRight(&device->name, ' '); } - if (!device->name.length) + if (!device->name.length) { ffStrbufSetWS(&device->name, szDevice); + } - if (options->namePrefix.length && !ffStrbufStartsWith(&device->name, &options->namePrefix)) - { + if (options->namePrefix.length && !ffStrbufStartsWith(&device->name, &options->namePrefix)) { ffStrbufDestroy(&device->name); result->length--; return true; @@ -60,15 +60,13 @@ static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFPhysic ffStrbufInitWS(&device->devPath, szDevice); ffStrbufInit(&device->serial); - if (sdd->SerialNumberOffset != 0) - { + if (sdd->SerialNumberOffset != 0) { ffStrbufSetS(&device->serial, (const char*) sddBuffer + sdd->SerialNumberOffset); ffStrbufTrimSpace(&device->serial); } ffStrbufInit(&device->revision); - if (sdd->ProductRevisionOffset != 0) - { + if (sdd->ProductRevisionOffset != 0) { ffStrbufSetS(&device->revision, (const char*) sddBuffer + sdd->ProductRevisionOffset); ffStrbufTrimRightSpace(&device->revision); } @@ -76,159 +74,200 @@ static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFPhysic device->type |= sdd->RemovableMedia ? FF_PHYSICALDISK_TYPE_REMOVABLE : FF_PHYSICALDISK_TYPE_FIXED; ffStrbufInit(&device->interconnect); - switch (sdd->BusType) - { - case BusTypeUnknown: ffStrbufSetStatic(&device->interconnect, "Unknown"); break; - case BusTypeScsi: ffStrbufSetStatic(&device->interconnect, "SCSI"); break; - case BusTypeAtapi: ffStrbufSetStatic(&device->interconnect, "ATAPI"); break; - case BusTypeAta: ffStrbufSetStatic(&device->interconnect, "ATA"); break; - case BusType1394: ffStrbufSetStatic(&device->interconnect, "1394"); break; - case BusTypeSsa: ffStrbufSetStatic(&device->interconnect, "SSA"); break; - case BusTypeFibre: ffStrbufSetStatic(&device->interconnect, "Fibre"); break; - case BusTypeUsb: ffStrbufSetStatic(&device->interconnect, "USB"); break; - case BusTypeRAID: ffStrbufSetStatic(&device->interconnect, "RAID"); break; - case BusTypeiScsi: ffStrbufSetStatic(&device->interconnect, "iSCSI"); break; - case BusTypeSas: ffStrbufSetStatic(&device->interconnect, "SAS"); break; - case BusTypeSata: ffStrbufSetStatic(&device->interconnect, "SATA"); break; - case BusTypeSd: ffStrbufSetStatic(&device->interconnect, "SD"); break; - case BusTypeMmc: ffStrbufSetStatic(&device->interconnect, "MMC"); break; - case BusTypeVirtual: ffStrbufSetStatic(&device->interconnect, "Virtual"); break; - case BusTypeFileBackedVirtual: ffStrbufSetStatic(&device->interconnect, "File Backed Virtual"); break; - case BusTypeSpaces: ffStrbufSetStatic(&device->interconnect, "Spaces"); break; - case BusTypeNvme: ffStrbufSetStatic(&device->interconnect, "NVMe"); break; - case BusTypeSCM: ffStrbufSetStatic(&device->interconnect, "SCM"); break; - case BusTypeUfs: ffStrbufSetStatic(&device->interconnect, "UFS"); break; - default: ffStrbufSetF(&device->interconnect, "Unknown (%d)", (int) sdd->BusType); break; + switch (sdd->BusType) { + case BusTypeUnknown: + ffStrbufSetStatic(&device->interconnect, "Unknown"); + break; + case BusTypeScsi: + ffStrbufSetStatic(&device->interconnect, "SCSI"); + break; + case BusTypeAtapi: + ffStrbufSetStatic(&device->interconnect, "ATAPI"); + break; + case BusTypeAta: + ffStrbufSetStatic(&device->interconnect, "ATA"); + break; + case BusType1394: + ffStrbufSetStatic(&device->interconnect, "1394"); + break; + case BusTypeSsa: + ffStrbufSetStatic(&device->interconnect, "SSA"); + break; + case BusTypeFibre: + ffStrbufSetStatic(&device->interconnect, "Fibre"); + break; + case BusTypeUsb: + ffStrbufSetStatic(&device->interconnect, "USB"); + break; + case BusTypeRAID: + ffStrbufSetStatic(&device->interconnect, "RAID"); + break; + case BusTypeiScsi: + ffStrbufSetStatic(&device->interconnect, "iSCSI"); + break; + case BusTypeSas: + ffStrbufSetStatic(&device->interconnect, "SAS"); + break; + case BusTypeSata: + ffStrbufSetStatic(&device->interconnect, "SATA"); + break; + case BusTypeSd: + ffStrbufSetStatic(&device->interconnect, "SD"); + break; + case BusTypeMmc: + ffStrbufSetStatic(&device->interconnect, "MMC"); + break; + case BusTypeVirtual: + ffStrbufSetStatic(&device->interconnect, "Virtual"); + break; + case BusTypeFileBackedVirtual: + ffStrbufSetStatic(&device->interconnect, "File Backed Virtual"); + break; + case BusTypeSpaces: + ffStrbufSetStatic(&device->interconnect, "Spaces"); + break; + case BusTypeNvme: + ffStrbufSetStatic(&device->interconnect, "NVMe"); + break; + case BusTypeSCM: + ffStrbufSetStatic(&device->interconnect, "SCM"); + break; + case BusTypeUfs: + ffStrbufSetStatic(&device->interconnect, "UFS"); + break; + default: + ffStrbufSetF(&device->interconnect, "Unknown (%d)", (int) sdd->BusType); + break; } { DEVICE_SEEK_PENALTY_DESCRIPTOR dspd = {}; - if(DeviceIoControl( - hDevice, - IOCTL_STORAGE_QUERY_PROPERTY, - &(STORAGE_PROPERTY_QUERY) { - .PropertyId = StorageDeviceSeekPenaltyProperty, - .QueryType = PropertyStandardQuery, - }, - sizeof(STORAGE_PROPERTY_QUERY), - &dspd, - sizeof(dspd), - &retSize, - NULL - ) && retSize == sizeof(dspd)) + if (DeviceIoControl( + hDevice, + IOCTL_STORAGE_QUERY_PROPERTY, + &(STORAGE_PROPERTY_QUERY) { + .PropertyId = StorageDeviceSeekPenaltyProperty, + .QueryType = PropertyStandardQuery, + }, + sizeof(STORAGE_PROPERTY_QUERY), + &dspd, + sizeof(dspd), + &retSize, + NULL) && + retSize == sizeof(dspd)) { device->type |= dspd.IncursSeekPenalty ? FF_PHYSICALDISK_TYPE_HDD : FF_PHYSICALDISK_TYPE_SSD; + } } { DISK_GEOMETRY_EX dge = {}; - if(DeviceIoControl( - hDevice, - IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, - NULL, - 0, - &dge, - sizeof(dge), - &retSize, - NULL)) + if (DeviceIoControl( + hDevice, + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, + NULL, + 0, + &dge, + sizeof(dge), + &retSize, + NULL)) { device->size = (uint64_t) dge.DiskSize.QuadPart; - else + } else { device->size = 0; + } } { alignas(GET_MEDIA_TYPES) uint8_t buffer[sizeof(GET_MEDIA_TYPES) + sizeof(DEVICE_MEDIA_INFO) * 7] = {}; GET_MEDIA_TYPES* gmt = (GET_MEDIA_TYPES*) buffer; - if(DeviceIoControl( - hDevice, - IOCTL_STORAGE_GET_MEDIA_TYPES_EX, - NULL, - 0, - gmt, - sizeof(buffer), - &retSize, - NULL) && gmt->MediaInfoCount > 0 - ) - { + if (DeviceIoControl( + hDevice, + IOCTL_STORAGE_GET_MEDIA_TYPES_EX, + NULL, + 0, + gmt, + sizeof(buffer), + &retSize, + NULL) && + gmt->MediaInfoCount > 0) { // DiskInfo and RemovableDiskInfo have the same structures. TapeInfo doesn't. - if (gmt->DeviceType != FILE_DEVICE_TAPE) - { + if (gmt->DeviceType != FILE_DEVICE_TAPE) { __auto_type diskInfo = &gmt->MediaInfo[0].DeviceSpecific.DiskInfo; - if (diskInfo->MediaCharacteristics & MEDIA_READ_ONLY) + if (diskInfo->MediaCharacteristics & MEDIA_READ_ONLY) { device->type |= FF_PHYSICALDISK_TYPE_READONLY; - else if (diskInfo->MediaCharacteristics & MEDIA_READ_WRITE) + } else if (diskInfo->MediaCharacteristics & MEDIA_READ_WRITE) { device->type |= FF_PHYSICALDISK_TYPE_READWRITE; - if (device->size == 0) + } + if (device->size == 0) { device->size = (uint64_t) diskInfo->NumberMediaSides * diskInfo->TracksPerCylinder * diskInfo->SectorsPerTrack * diskInfo->BytesPerSector; - } - else - { + } + } else { __auto_type tapeInfo = &gmt->MediaInfo[0].DeviceSpecific.TapeInfo; - if (tapeInfo->MediaCharacteristics & MEDIA_READ_ONLY) + if (tapeInfo->MediaCharacteristics & MEDIA_READ_ONLY) { device->type |= FF_PHYSICALDISK_TYPE_READONLY; - else if (tapeInfo->MediaCharacteristics & MEDIA_READ_WRITE) + } else if (tapeInfo->MediaCharacteristics & MEDIA_READ_WRITE) { device->type |= FF_PHYSICALDISK_TYPE_READWRITE; + } } } } device->temperature = FF_PHYSICALDISK_TEMP_UNSET; - if (options->temp) - { + if (options->temp) { STORAGE_TEMPERATURE_DATA_DESCRIPTOR stdd = {}; - if(DeviceIoControl( - hDevice, - IOCTL_STORAGE_QUERY_PROPERTY, - &(STORAGE_PROPERTY_QUERY) { - .PropertyId = StorageDeviceTemperatureProperty, - .QueryType = PropertyStandardQuery, - }, - sizeof(STORAGE_PROPERTY_QUERY), - &stdd, - sizeof(stdd), - &retSize, - NULL - ) && retSize == sizeof(stdd)) + if (DeviceIoControl( + hDevice, + IOCTL_STORAGE_QUERY_PROPERTY, + &(STORAGE_PROPERTY_QUERY) { + .PropertyId = StorageDeviceTemperatureProperty, + .QueryType = PropertyStandardQuery, + }, + sizeof(STORAGE_PROPERTY_QUERY), + &stdd, + sizeof(stdd), + &retSize, + NULL) && + retSize == sizeof(stdd)) { device->temperature = stdd.TemperatureInfo[0].Temperature; + } } return true; } -const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) -{ +const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { { wchar_t szPhysicalDrive[32] = L"\\\\.\\PhysicalDrive"; wchar_t* pNum = szPhysicalDrive + strlen("\\\\.\\PhysicalDrive"); - for (uint32_t idev = 0; ; ++idev) - { + for (uint32_t idev = 0;; ++idev) { _ultow(idev, pNum, 10); - if (!detectPhysicalDisk(szPhysicalDrive, result, options)) + if (!detectPhysicalDisk(szPhysicalDrive, result, options)) { break; + } } } { wchar_t szCdrom[32] = L"\\\\.\\CDROM"; wchar_t* pNum = szCdrom + strlen("\\\\.\\CDROM"); - for (uint32_t idev = 0; ; ++idev) - { + for (uint32_t idev = 0;; ++idev) { _ultow(idev, pNum, 10); - if (!detectPhysicalDisk(szCdrom, result, options)) + if (!detectPhysicalDisk(szCdrom, result, options)) { break; + } } } { wchar_t szTape[32] = L"\\\\.\\Tape"; wchar_t* pNum = szTape + strlen("\\\\.\\Tape"); - for (uint32_t idev = 0; ; ++idev) - { + for (uint32_t idev = 0;; ++idev) { _ultow(idev, pNum, 10); - if (!detectPhysicalDisk(szTape, result, options)) + if (!detectPhysicalDisk(szTape, result, options)) { break; + } } } diff --git a/src/detection/physicalmemory/physicalmemory.c b/src/detection/physicalmemory/physicalmemory.c index 70e111b08..0188e0544 100644 --- a/src/detection/physicalmemory/physicalmemory.c +++ b/src/detection/physicalmemory/physicalmemory.c @@ -1,50 +1,73 @@ #include "physicalmemory.h" -static inline const char* getVendorString(unsigned vendorId) -{ - switch (vendorId) - { - case 0x017A: return "Apacer"; - case 0x0198: return "Kingston"; - case 0x029E: return "Corsair"; - case 0x04CB: return "A-DATA"; - case 0x04CD: return "G-Skill"; - case 0x059B: case 0x859B: return "Crucial"; - case 0x00CE: case 0x80CE: case 0xCE00: return "Samsung"; - case 0x014F: return "Transcend"; - case 0x2C00: case 0x802C: return "Micron"; - case 0xAD00: case 0x80AD: return "SK Hynix"; - case 0x5105: case 0x8551: return "Qimonda"; - case 0x02FE: return "Elpida"; - case 0x0467: return "Ramaxel"; - default: return NULL; +static inline const char* getVendorString(unsigned vendorId) { + switch (vendorId) { + case 0x017A: + return "Apacer"; + case 0x0198: + return "Kingston"; + case 0x029E: + return "Corsair"; + case 0x04CB: + return "A-DATA"; + case 0x04CD: + return "G-Skill"; + case 0x059B: + case 0x859B: + return "Crucial"; + case 0x00CE: + case 0x80CE: + case 0xCE00: + return "Samsung"; + case 0x014F: + return "Transcend"; + case 0x2C00: + case 0x802C: + return "Micron"; + case 0xAD00: + case 0x80AD: + return "SK Hynix"; + case 0x5105: + case 0x8551: + return "Qimonda"; + case 0x02FE: + return "Elpida"; + case 0x0467: + return "Ramaxel"; + default: + return NULL; } } -void FFPhysicalMemoryUpdateVendorString(FFPhysicalMemoryResult* device) -{ - if (device->vendor.length == 0) return; - if (ffStrbufEqualS(&device->vendor, "Unknown")) - { +void FFPhysicalMemoryUpdateVendorString(FFPhysicalMemoryResult* device) { + if (device->vendor.length == 0) { + return; + } + if (ffStrbufEqualS(&device->vendor, "Unknown")) { ffStrbufClear(&device->vendor); return; } char vendorIdStr[5]; - if (ffStrbufStartsWithS(&device->vendor, "0x")) - { - if (device->vendor.length < 6) return; + if (ffStrbufStartsWithS(&device->vendor, "0x")) { + if (device->vendor.length < 6) { + return; + } memcpy(vendorIdStr, device->vendor.chars + 2, 4); - } - else - { - if (device->vendor.length < 4) return; + } else { + if (device->vendor.length < 4) { + return; + } memcpy(vendorIdStr, device->vendor.chars, 4); } vendorIdStr[4] = '\0'; char* pEnd = NULL; uint32_t vendorId = (uint32_t) strtoul(vendorIdStr, &pEnd, 16); - if (*pEnd != '\0') return; + if (*pEnd != '\0') { + return; + } const char* vendorStr = getVendorString(vendorId); - if (vendorStr) ffStrbufSetStatic(&device->vendor, vendorStr); + if (vendorStr) { + ffStrbufSetStatic(&device->vendor, vendorStr); + } } diff --git a/src/detection/physicalmemory/physicalmemory.h b/src/detection/physicalmemory/physicalmemory.h index 17fa4c615..6f683803a 100644 --- a/src/detection/physicalmemory/physicalmemory.h +++ b/src/detection/physicalmemory/physicalmemory.h @@ -3,10 +3,9 @@ #include "fastfetch.h" #include "modules/physicalmemory/option.h" -typedef struct FFPhysicalMemoryResult -{ - uint64_t size; // B - uint32_t maxSpeed; // MT/s +typedef struct FFPhysicalMemoryResult { + uint64_t size; // B + uint32_t maxSpeed; // MT/s uint32_t runningSpeed; // MT/s bool installed; FFstrbuf type; diff --git a/src/detection/physicalmemory/physicalmemory_linux.c b/src/detection/physicalmemory/physicalmemory_linux.c index e077baebc..7e71316b6 100644 --- a/src/detection/physicalmemory/physicalmemory_linux.c +++ b/src/detection/physicalmemory/physicalmemory_linux.c @@ -2,83 +2,84 @@ #include "common/smbiosHelper.h" // 7.18 -typedef struct FFSmbiosMemoryDevice -{ +typedef struct FFSmbiosMemoryDevice { FFSmbiosHeader Header; // 2.1+ - uint16_t PhysicalMemoryArrayHandle; // varies - uint16_t MemoryErrorInformationHandle; //varies - uint16_t TotalWidth; // varies - uint16_t DataWidth; // varies - uint16_t Size; // varies - uint8_t FormFactor; // enum - uint8_t DeviceSet; // varies - uint8_t DeviceLocator; // string - uint8_t BankLocator; // string - uint8_t MemoryType; // enum - uint16_t TypeDetail; // bit field + uint16_t PhysicalMemoryArrayHandle; // varies + uint16_t MemoryErrorInformationHandle; // varies + uint16_t TotalWidth; // varies + uint16_t DataWidth; // varies + uint16_t Size; // varies + uint8_t FormFactor; // enum + uint8_t DeviceSet; // varies + uint8_t DeviceLocator; // string + uint8_t BankLocator; // string + uint8_t MemoryType; // enum + uint16_t TypeDetail; // bit field // 2.3+ - uint16_t Speed; // varies + uint16_t Speed; // varies uint8_t Manufacturer; // string uint8_t SerialNumber; // string - uint8_t AssetTag; // string - uint8_t PartNumber; // string + uint8_t AssetTag; // string + uint8_t PartNumber; // string // 2.6+ uint8_t Attributes; // varies // 2.7+ - uint32_t ExtendedSize; // varies + uint32_t ExtendedSize; // varies uint16_t ConfiguredMemorySpeed; // varies // 2.8+ - uint16_t MinimumVoltage; // varies - uint16_t MaximumVoltage; // varies + uint16_t MinimumVoltage; // varies + uint16_t MaximumVoltage; // varies uint16_t ConfiguredVoltage; // varies // 3.2+ - uint8_t MemoryTechnology; // varies - uint16_t MemoryOperatingMode; // bit field - uint8_t FirmwareVersion; // string - uint16_t ModuleManufacturerID; // varies - uint16_t ModuleProductID; // varies + uint8_t MemoryTechnology; // varies + uint16_t MemoryOperatingMode; // bit field + uint8_t FirmwareVersion; // string + uint16_t ModuleManufacturerID; // varies + uint16_t ModuleProductID; // varies uint16_t MemorySubsystemControllerManufacturerID; // vaies - uint16_t MemorySubsystemControllerProductID; // varies - uint64_t NonVolatileSize; // varies - uint64_t VolatileSize; // varies - uint64_t CacheSize; // varies - uint64_t LogicalSize; // varies + uint16_t MemorySubsystemControllerProductID; // varies + uint64_t NonVolatileSize; // varies + uint64_t VolatileSize; // varies + uint64_t CacheSize; // varies + uint64_t LogicalSize; // varies // 3.3+ - uint32_t ExtendedSpeed; // varies + uint32_t ExtendedSpeed; // varies uint32_t ExtendedConfiguredSpeed; // varies // 3.7+ uint16_t Pmic0ManufacturerID; // varies uint16_t Pmic0RevisionNumber; // varies - uint16_t RcdManufacturerID; // varies - uint16_t RcdRevisionNumber; // varies + uint16_t RcdManufacturerID; // varies + uint16_t RcdRevisionNumber; // varies } __attribute__((__packed__)) FFSmbiosMemoryDevice; static_assert(offsetof(FFSmbiosMemoryDevice, RcdRevisionNumber) == 0x62, "FFSmbiosMemoryDevice: Wrong struct alignment"); -const char* ffDetectPhysicalMemory(FFlist* result) -{ +const char* ffDetectPhysicalMemory(FFlist* result) { const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable(); - if (!smbiosTable) + if (!smbiosTable) { return "Failed to get SMBIOS data"; + } const FFSmbiosMemoryDevice* data = (const FFSmbiosMemoryDevice*) (*smbiosTable)[FF_SMBIOS_TYPE_MEMORY_DEVICE]; - if (!data) + if (!data) { return "Memory device is not found in SMBIOS data"; + } const FFSmbiosMemoryDevice* endOfTable = (const FFSmbiosMemoryDevice*) (*smbiosTable)[FF_SMBIOS_TYPE_END_OF_TABLE]; - for (; data != endOfTable; data = (const FFSmbiosMemoryDevice*) ffSmbiosNextEntry(&data->Header)) - { - if (data->Header.Type != FF_SMBIOS_TYPE_MEMORY_DEVICE) continue; + for (; data != endOfTable; data = (const FFSmbiosMemoryDevice*) ffSmbiosNextEntry(&data->Header)) { + if (data->Header.Type != FF_SMBIOS_TYPE_MEMORY_DEVICE) { + continue; + } const char* strings = (const char*) data + data->Header.Length; bool installed = data->Size != 0; @@ -96,20 +97,17 @@ const char* ffDetectPhysicalMemory(FFlist* result) device->installed = installed; device->ecc = false; - if (installed && data->TotalWidth != 0xFFFF && data->DataWidth != 0xFFFF) + if (installed && data->TotalWidth != 0xFFFF && data->DataWidth != 0xFFFF) { device->ecc = data->TotalWidth > data->DataWidth; + } - if (installed && data->Size != 0xFFFF) - { - if (data->Size == 0x7FFF) + if (installed && data->Size != 0xFFFF) { + if (data->Size == 0x7FFF) { device->size = (data->ExtendedSize & ~(1ULL << 31)) * 1024ULL * 1024ULL; - else if (data->Size & (1 << 15)) - { + } else if (data->Size & (1 << 15)) { // in kB device->size = (data->Size & ~(1ULL << 15)) * 1024ULL; - } - else - { + } else { // in MB device->size = data->Size * 1024ULL * 1024ULL; } @@ -118,87 +116,91 @@ const char* ffDetectPhysicalMemory(FFlist* result) // https://github.com/fastfetch-cli/fastfetch/issues/1051#issuecomment-2206687345 const char* lbank = ffSmbiosLocateString(strings, data->BankLocator); const char* ldevice = ffSmbiosLocateString(strings, data->DeviceLocator); - if (lbank && ldevice) + if (lbank && ldevice) { ffStrbufSetF(&device->locator, "%s/%s", lbank, ldevice); - else if (lbank) + } else if (lbank) { ffStrbufSetS(&device->locator, lbank); - else if (ldevice) + } else if (ldevice) { ffStrbufSetS(&device->locator, ldevice); + } const char* formFactorNames[] = { - NULL, // 0x00 (Placeholder for indexing) - "Other", // 0x01 - "Unknown", // 0x02 - "SIMM", // 0x03 - "SIP", // 0x04 - "Chip", // 0x05 - "DIP", // 0x06 - "ZIP", // 0x07 - "Proprietary Card",// 0x08 - "DIMM", // 0x09 - "TSOP", // 0x0A - "Row of chips", // 0x0B - "RIMM", // 0x0C - "SODIMM", // 0x0D - "SRIMM", // 0x0E - "FBDIMM", // 0x0F - "Die", // 0x10 + NULL, // 0x00 (Placeholder for indexing) + "Other", // 0x01 + "Unknown", // 0x02 + "SIMM", // 0x03 + "SIP", // 0x04 + "Chip", // 0x05 + "DIP", // 0x06 + "ZIP", // 0x07 + "Proprietary Card", // 0x08 + "DIMM", // 0x09 + "TSOP", // 0x0A + "Row of chips", // 0x0B + "RIMM", // 0x0C + "SODIMM", // 0x0D + "SRIMM", // 0x0E + "FBDIMM", // 0x0F + "Die", // 0x10 }; - if (data->FormFactor > 0 && data->FormFactor < ARRAY_SIZE(formFactorNames)) + if (data->FormFactor > 0 && data->FormFactor < ARRAY_SIZE(formFactorNames)) { ffStrbufSetS(&device->formFactor, formFactorNames[data->FormFactor]); - else + } else { ffStrbufSetF(&device->formFactor, "Unknown (%d)", (int) data->FormFactor); + } const char* memoryTypeNames[] = { - NULL, // 0x00 (Placeholder for indexing) - "Other", // 0x01 - "Unknown", // 0x02 - "DRAM", // 0x03 - "EDRAM", // 0x04 - "VRAM", // 0x05 - "SRAM", // 0x06 - "RAM", // 0x07 - "ROM", // 0x08 - "FLASH", // 0x09 - "EEPROM", // 0x0A - "FEPROM", // 0x0B - "EPROM", // 0x0C - "CDRAM", // 0x0D - "3DRAM", // 0x0E - "SDRAM", // 0x0F - "SGRAM", // 0x10 - "RDRAM", // 0x11 - "DDR", // 0x12 - "DDR2", // 0x13 - "DDR2 FB-DIMM", // 0x14 - "Reserved", // 0x15 - "Reserved", // 0x16 - "Reserved", // 0x17 - "DDR3", // 0x18 - "FBD2", // 0x19 - "DDR4", // 0x1A - "LPDDR", // 0x1B - "LPDDR2", // 0x1C - "LPDDR3", // 0x1D - "LPDDR4", // 0x1E + NULL, // 0x00 (Placeholder for indexing) + "Other", // 0x01 + "Unknown", // 0x02 + "DRAM", // 0x03 + "EDRAM", // 0x04 + "VRAM", // 0x05 + "SRAM", // 0x06 + "RAM", // 0x07 + "ROM", // 0x08 + "FLASH", // 0x09 + "EEPROM", // 0x0A + "FEPROM", // 0x0B + "EPROM", // 0x0C + "CDRAM", // 0x0D + "3DRAM", // 0x0E + "SDRAM", // 0x0F + "SGRAM", // 0x10 + "RDRAM", // 0x11 + "DDR", // 0x12 + "DDR2", // 0x13 + "DDR2 FB-DIMM", // 0x14 + "Reserved", // 0x15 + "Reserved", // 0x16 + "Reserved", // 0x17 + "DDR3", // 0x18 + "FBD2", // 0x19 + "DDR4", // 0x1A + "LPDDR", // 0x1B + "LPDDR2", // 0x1C + "LPDDR3", // 0x1D + "LPDDR4", // 0x1E "Logical non-volatile device", // 0x1F - "HBM", // 0x20 - "HBM2", // 0x21 - "DDR5", // 0x22 - "LPDDR5", // 0x23 - "HBM3", // 0x24 + "HBM", // 0x20 + "HBM2", // 0x21 + "DDR5", // 0x22 + "LPDDR5", // 0x23 + "HBM3", // 0x24 }; - if (!installed) + if (!installed) { ffStrbufSetStatic(&device->type, "Empty"); - else if (data->MemoryType > 0 && data->MemoryType < ARRAY_SIZE(memoryTypeNames)) + } else if (data->MemoryType > 0 && data->MemoryType < ARRAY_SIZE(memoryTypeNames)) { ffStrbufSetStatic(&device->type, memoryTypeNames[data->MemoryType]); - else + } else { ffStrbufSetF(&device->type, "Unknown (%d)", (int) data->MemoryType); + } if (installed && data->Header.Length > offsetof(FFSmbiosMemoryDevice, Speed)) // 2.3+ { - if (data->Speed) + if (data->Speed) { device->maxSpeed = data->Speed == 0xFFFF ? data->ExtendedSpeed : data->Speed; + } ffStrbufSetStatic(&device->vendor, ffSmbiosLocateString(strings, data->Manufacturer)); ffCleanUpSmbiosValue(&device->vendor); @@ -213,9 +215,11 @@ const char* ffDetectPhysicalMemory(FFlist* result) if (installed && data->Header.Length > offsetof(FFSmbiosMemoryDevice, ConfiguredMemorySpeed)) // 2.7+ { - if (data->ConfiguredMemorySpeed) + if (data->ConfiguredMemorySpeed) { device->runningSpeed = data->ConfiguredMemorySpeed == 0xFFFF - ? data->ExtendedConfiguredSpeed : data->ConfiguredMemorySpeed; + ? data->ExtendedConfiguredSpeed + : data->ConfiguredMemorySpeed; + } } } diff --git a/src/detection/physicalmemory/physicalmemory_nosupport.c b/src/detection/physicalmemory/physicalmemory_nosupport.c index a035753d7..998c602c3 100644 --- a/src/detection/physicalmemory/physicalmemory_nosupport.c +++ b/src/detection/physicalmemory/physicalmemory_nosupport.c @@ -1,6 +1,5 @@ #include "physicalmemory.h" -const char* ffDetectPhysicalMemory(FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectPhysicalMemory(FF_MAYBE_UNUSED FFlist* result) { return "Not supported on this platform"; } diff --git a/src/detection/poweradapter/poweradapter.h b/src/detection/poweradapter/poweradapter.h index 64c0eb5ec..2d889b788 100644 --- a/src/detection/poweradapter/poweradapter.h +++ b/src/detection/poweradapter/poweradapter.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/poweradapter/option.h" -typedef struct FFPowerAdapterResult -{ +typedef struct FFPowerAdapterResult { FFstrbuf description; FFstrbuf name; FFstrbuf modelName; diff --git a/src/detection/poweradapter/poweradapter_apple.c b/src/detection/poweradapter/poweradapter_apple.c index bee95e967..557afcd69 100644 --- a/src/detection/poweradapter/poweradapter_apple.c +++ b/src/detection/poweradapter/poweradapter_apple.c @@ -5,11 +5,9 @@ #include #include -const char* ffDetectPowerAdapter(FFlist* results) -{ +const char* ffDetectPowerAdapter(FFlist* results) { FF_CFTYPE_AUTO_RELEASE CFDictionaryRef details = IOPSCopyExternalPowerAdapterDetails(); - if (details && CFDictionaryContainsKey(details, CFSTR(kIOPSPowerAdapterWattsKey))) - { + if (details && CFDictionaryContainsKey(details, CFSTR(kIOPSPowerAdapterWattsKey))) { FFPowerAdapterResult* adapter = ffListAdd(results); ffStrbufInit(&adapter->name); @@ -20,19 +18,19 @@ const char* ffDetectPowerAdapter(FFlist* results) adapter->watts = 0; ffCfDictGetString(details, CFSTR(kIOPSNameKey), &adapter->name); - if (ffCfDictGetString(details, CFSTR("Model"), &adapter->modelName) != NULL) - { + if (ffCfDictGetString(details, CFSTR("Model"), &adapter->modelName) != NULL) { int adapterId; - if (ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterIDKey), &adapterId) == 0) + if (ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterIDKey), &adapterId) == 0) { ffStrbufSetF(&adapter->modelName, "%d", adapterId); + } } ffCfDictGetString(details, CFSTR("Manufacturer"), &adapter->manufacturer); ffCfDictGetString(details, CFSTR("Description"), &adapter->description); - if (ffCfDictGetString(details, CFSTR("SerialString"), &adapter->serial) != NULL) - { + if (ffCfDictGetString(details, CFSTR("SerialString"), &adapter->serial) != NULL) { int serialNumber; - if (ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterSerialNumberKey), &serialNumber) == 0) + if (ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterSerialNumberKey), &serialNumber) == 0) { ffStrbufSetF(&adapter->serial, "%X", serialNumber); + } } ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterWattsKey), &adapter->watts); } diff --git a/src/detection/poweradapter/poweradapter_linux.c b/src/detection/poweradapter/poweradapter_linux.c index 4e0576490..1ce20049e 100644 --- a/src/detection/poweradapter/poweradapter_linux.c +++ b/src/detection/poweradapter/poweradapter_linux.c @@ -6,33 +6,38 @@ #include #include -static void parsePowerAdapter(int dfd, FF_MAYBE_UNUSED const char* id, FFlist* results) -{ +static void parsePowerAdapter(int dfd, FF_MAYBE_UNUSED const char* id, FFlist* results) { FF_STRBUF_AUTO_DESTROY tmpBuffer = ffStrbufCreate(); - //type must exist and be "Mains" - if (ffReadFileBufferRelative(dfd, "type", &tmpBuffer)) + // type must exist and be "Mains" + if (ffReadFileBufferRelative(dfd, "type", &tmpBuffer)) { ffStrbufTrimRightSpace(&tmpBuffer); + } - if(!ffStrbufIgnCaseEqualS(&tmpBuffer, "Mains")) + if (!ffStrbufIgnCaseEqualS(&tmpBuffer, "Mains")) { return; + } - //scope may not exist or must not be "Device" (?) - if (ffReadFileBufferRelative(dfd, "scope", &tmpBuffer)) + // scope may not exist or must not be "Device" (?) + if (ffReadFileBufferRelative(dfd, "scope", &tmpBuffer)) { ffStrbufTrimRightSpace(&tmpBuffer); + } - if(ffStrbufIgnCaseEqualS(&tmpBuffer, "Device")) + if (ffStrbufIgnCaseEqualS(&tmpBuffer, "Device")) { return; + } char online = '\0'; ffReadFileDataRelative(dfd, "online", sizeof(online), &online); - if (online != '1') + if (online != '1') { return; + } - //input_power_limit must exist and be not empty - if (!ffReadFileBufferRelative(dfd, "input_power_limit", &tmpBuffer) || tmpBuffer.length == 0) + // input_power_limit must exist and be not empty + if (!ffReadFileBufferRelative(dfd, "input_power_limit", &tmpBuffer) || tmpBuffer.length == 0) { return; + } FFPowerAdapterResult* result = ffListAdd(results); ffStrbufInit(&result->name); @@ -42,32 +47,37 @@ static void parsePowerAdapter(int dfd, FF_MAYBE_UNUSED const char* id, FFlist* r ffStrbufInit(&result->modelName); ffStrbufInit(&result->serial); - if (ffReadFileBufferRelative(dfd, "manufacturer", &result->manufacturer)) + if (ffReadFileBufferRelative(dfd, "manufacturer", &result->manufacturer)) { ffStrbufTrimRightSpace(&result->manufacturer); - else if (ffStrEquals(id, "macsmc-ac")) // asahi + } else if (ffStrEquals(id, "macsmc-ac")) { // asahi ffStrbufSetStatic(&result->manufacturer, "Apple Inc."); + } - if (ffReadFileBufferRelative(dfd, "model_name", &result->modelName)) + if (ffReadFileBufferRelative(dfd, "model_name", &result->modelName)) { ffStrbufTrimRightSpace(&result->modelName); + } - if (ffReadFileBufferRelative(dfd, "serial_number", &result->serial)) + if (ffReadFileBufferRelative(dfd, "serial_number", &result->serial)) { ffStrbufTrimRightSpace(&result->serial); + } } -const char* ffDetectPowerAdapter(FFlist* results) -{ +const char* ffDetectPowerAdapter(FFlist* results) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/power_supply/"); - if(dirp == NULL) + if (dirp == NULL) { return "opendir(\"/sys/class/power_supply/\") == NULL"; + } struct dirent* entry; - while((entry = readdir(dirp)) != NULL) - { - if(entry->d_name[0] == '.') + while ((entry = readdir(dirp)) != NULL) { + if (entry->d_name[0] == '.') { continue; + } FF_AUTO_CLOSE_FD int dfd = openat(dirfd(dirp), entry->d_name, O_RDONLY | O_CLOEXEC); - if (dfd > 0) parsePowerAdapter(dfd, entry->d_name, results); + if (dfd > 0) { + parsePowerAdapter(dfd, entry->d_name, results); + } } return NULL; diff --git a/src/detection/poweradapter/poweradapter_nosupport.c b/src/detection/poweradapter/poweradapter_nosupport.c index 1ae9d5395..4458d1e8a 100644 --- a/src/detection/poweradapter/poweradapter_nosupport.c +++ b/src/detection/poweradapter/poweradapter_nosupport.c @@ -1,6 +1,5 @@ #include "poweradapter.h" -const char* ffDetectPowerAdapter(FF_MAYBE_UNUSED FFlist* results) -{ +const char* ffDetectPowerAdapter(FF_MAYBE_UNUSED FFlist* results) { return "Not supported on this platform"; } diff --git a/src/detection/processes/processes_bsd.c b/src/detection/processes/processes_bsd.c index 47d8d5166..e3205b5a6 100644 --- a/src/detection/processes/processes_bsd.c +++ b/src/detection/processes/processes_bsd.c @@ -2,22 +2,22 @@ #include #ifdef __FreeBSD__ - #include - #include +# include +# include #endif #ifndef KERN_PROC_PROC - #define KERN_PROC_PROC KERN_PROC_ALL // Apple +# define KERN_PROC_PROC KERN_PROC_ALL // Apple #endif -const char* ffDetectProcesses(uint32_t* result) -{ +const char* ffDetectProcesses(uint32_t* result) { int request[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC}; size_t length; - if(sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) + if (sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) { return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_PROC}) failed"; + } - *result = (uint32_t)(length / sizeof(struct kinfo_proc)); + *result = (uint32_t) (length / sizeof(struct kinfo_proc)); return NULL; } diff --git a/src/detection/processes/processes_haiku.c b/src/detection/processes/processes_haiku.c index 8e373729e..c50e62d53 100644 --- a/src/detection/processes/processes_haiku.c +++ b/src/detection/processes/processes_haiku.c @@ -2,11 +2,11 @@ #include -const char* ffDetectProcesses(uint32_t* result) -{ +const char* ffDetectProcesses(uint32_t* result) { system_info info; - if (get_system_info(&info) != B_OK) + if (get_system_info(&info) != B_OK) { return "Error getting system info"; + } *result = info.used_teams; diff --git a/src/detection/processes/processes_linux.c b/src/detection/processes/processes_linux.c index 397961e11..6b7b46855 100644 --- a/src/detection/processes/processes_linux.c +++ b/src/detection/processes/processes_linux.c @@ -3,22 +3,21 @@ #include "common/io.h" #include "common/stringUtils.h" -const char* ffDetectProcesses(uint32_t* result) -{ +const char* ffDetectProcesses(uint32_t* result) { FF_AUTO_CLOSE_DIR DIR* dir = opendir("/proc"); - if(dir == NULL) + if (dir == NULL) { return "opendir(\"/proc\") failed"; + } uint32_t num = 0; struct dirent* entry; - while ((entry = readdir(dir)) != NULL) - { + while ((entry = readdir(dir)) != NULL) { if ( - #ifdef _DIRENT_HAVE_D_TYPE - (entry->d_type == DT_DIR || entry->d_type == DT_UNKNOWN) && - #endif - ffCharIsDigit(entry->d_name[0])) +#ifdef _DIRENT_HAVE_D_TYPE + (entry->d_type == DT_DIR || entry->d_type == DT_UNKNOWN) && +#endif + ffCharIsDigit(entry->d_name[0])) ++num; } diff --git a/src/detection/processes/processes_nbsd.c b/src/detection/processes/processes_nbsd.c index cf16a04cd..915827a2b 100644 --- a/src/detection/processes/processes_nbsd.c +++ b/src/detection/processes/processes_nbsd.c @@ -2,14 +2,14 @@ #include -const char* ffDetectProcesses(uint32_t* result) -{ +const char* ffDetectProcesses(uint32_t* result) { int request[] = {CTL_KERN, KERN_PROC2, KERN_PROC_ALL, -1, sizeof(struct kinfo_proc2), 0}; size_t length = 0; - if(sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) + if (sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) { return "sysctl({CTL_KERN, KERN_PROC2, KERN_PROC_ALL}) failed"; + } - *result = (uint32_t)(length / sizeof(struct kinfo_proc2)); + *result = (uint32_t) (length / sizeof(struct kinfo_proc2)); return NULL; } diff --git a/src/detection/processes/processes_nosupport.c b/src/detection/processes/processes_nosupport.c index e1774dd04..7da208ec4 100644 --- a/src/detection/processes/processes_nosupport.c +++ b/src/detection/processes/processes_nosupport.c @@ -1,6 +1,5 @@ #include "processes.h" -const char* ffDetectProcesses(uint32_t* result) -{ +const char* ffDetectProcesses(uint32_t* result) { return "Not supported on this platform"; } diff --git a/src/detection/processes/processes_obsd.c b/src/detection/processes/processes_obsd.c index 75db1c4d0..6246d8f8a 100644 --- a/src/detection/processes/processes_obsd.c +++ b/src/detection/processes/processes_obsd.c @@ -4,11 +4,12 @@ #include #include -const char* ffDetectProcesses(uint32_t* result) -{ +const char* ffDetectProcesses(uint32_t* result) { kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); const void* ret = kvm_getprocs(kd, KERN_PROC_ALL, 0, 1, result); kvm_close(kd); - if (!ret) return "kvm_getprocs() failed"; + if (!ret) { + return "kvm_getprocs() failed"; + } return NULL; } diff --git a/src/detection/processes/processes_windows.c b/src/detection/processes/processes_windows.c index 3267cff38..03b34db98 100644 --- a/src/detection/processes/processes_windows.c +++ b/src/detection/processes/processes_windows.c @@ -4,32 +4,31 @@ #include #include -const char* ffDetectProcesses(uint32_t* result) -{ +const char* ffDetectProcesses(uint32_t* result) { SYSTEM_PROCESS_INFORMATION* FF_AUTO_FREE pstart = NULL; // Multiple attempts in case processes change while // we are in the middle of querying them. ULONG size = 0; - for (int attempts = 0;; ++attempts) - { - if (size) - { - pstart = (SYSTEM_PROCESS_INFORMATION*)realloc(pstart, size); + for (int attempts = 0;; ++attempts) { + if (size) { + pstart = (SYSTEM_PROCESS_INFORMATION*) realloc(pstart, size); assert(pstart); } NTSTATUS status = NtQuerySystemInformation(SystemProcessInformation, pstart, size, &size); - if(NT_SUCCESS(status)) + if (NT_SUCCESS(status)) { break; - else if(status == STATUS_INFO_LENGTH_MISMATCH && attempts < 4) + } else if (status == STATUS_INFO_LENGTH_MISMATCH && attempts < 4) { size += sizeof(SYSTEM_PROCESS_INFORMATION) * 5; - else + } else { return "NtQuerySystemInformation(SystemProcessInformation) failed"; + } } - *result = 1; //Init with 1 because we test for ptr->NextEntryOffset - for (SYSTEM_PROCESS_INFORMATION* ptr = pstart; ptr->NextEntryOffset; ptr = (SYSTEM_PROCESS_INFORMATION*)((uint8_t*)ptr + ptr->NextEntryOffset)) + *result = 1; // Init with 1 because we test for ptr->NextEntryOffset + for (SYSTEM_PROCESS_INFORMATION* ptr = pstart; ptr->NextEntryOffset; ptr = (SYSTEM_PROCESS_INFORMATION*) ((uint8_t*) ptr + ptr->NextEntryOffset)) { ++*result; + } return NULL; } diff --git a/src/detection/publicip/publicip.c b/src/detection/publicip/publicip.c index 5aa9c1c90..2225abbf3 100644 --- a/src/detection/publicip/publicip.c +++ b/src/detection/publicip/publicip.c @@ -1,16 +1,14 @@ #include "publicip.h" #include "common/networking.h" -#define FF_UNITIALIZED ((const char*)(uintptr_t) -1) +#define FF_UNITIALIZED ((const char*) (uintptr_t) -1) static FFNetworkingState states[2]; -static const char* statuses[2] = { FF_UNITIALIZED, FF_UNITIALIZED }; +static const char* statuses[2] = {FF_UNITIALIZED, FF_UNITIALIZED}; -void ffPreparePublicIp(FFPublicIPOptions* options) -{ +void ffPreparePublicIp(FFPublicIPOptions* options) { FFNetworkingState* state = &states[options->ipv6]; const char** status = &statuses[options->ipv6]; - if (*status != FF_UNITIALIZED) - { + if (*status != FF_UNITIALIZED) { fputs("Error: PublicIp module can only be used once due to internal limitations\n", stderr); exit(1); } @@ -18,20 +16,15 @@ void ffPreparePublicIp(FFPublicIPOptions* options) state->timeout = options->timeout; state->ipv6 = options->ipv6; - if (options->url.length == 0) - { + if (options->url.length == 0) { state->compression = true; state->tfo = true; *status = ffNetworkingSendHttpRequest(state, options->ipv6 ? "v6.ipinfo.io" : "ipinfo.io", "/json", NULL); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY host = ffStrbufCreateCopy(&options->url); uint32_t hostStartIndex = ffStrbufFirstIndexS(&host, "://"); - if (hostStartIndex < host.length) - { - if (hostStartIndex != 4 || !ffStrbufStartsWithIgnCaseS(&host, "http")) - { + if (hostStartIndex < host.length) { + if (hostStartIndex != 4 || !ffStrbufStartsWithIgnCaseS(&host, "http")) { fputs("Error: only http: protocol is supported. Use `Command` module with `curl` if needed\n", stderr); exit(1); } @@ -40,8 +33,7 @@ void ffPreparePublicIp(FFPublicIPOptions* options) uint32_t pathStartIndex = ffStrbufFirstIndexC(&host, '/'); FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); - if(pathStartIndex != host.length) - { + if (pathStartIndex != host.length) { ffStrbufAppendNS(&path, pathStartIndex, host.chars + (host.length - pathStartIndex)); host.length = pathStartIndex; host.chars[pathStartIndex] = '\0'; @@ -51,42 +43,43 @@ void ffPreparePublicIp(FFPublicIPOptions* options) } } -static inline void wrapYyjsonFree(yyjson_doc** doc) -{ +static inline void wrapYyjsonFree(yyjson_doc** doc) { assert(doc); - if (*doc) + if (*doc) { yyjson_doc_free(*doc); + } } -const char* ffDetectPublicIp(FFPublicIPOptions* options, FFPublicIpResult* result) -{ +const char* ffDetectPublicIp(FFPublicIPOptions* options, FFPublicIpResult* result) { FFNetworkingState* state = &states[options->ipv6]; const char** status = &statuses[options->ipv6]; - if (*status == FF_UNITIALIZED) + if (*status == FF_UNITIALIZED) { ffPreparePublicIp(options); + } - if (*status != NULL) + if (*status != NULL) { return *status; + } FF_STRBUF_AUTO_DESTROY response = ffStrbufCreateA(4096); const char* error = ffNetworkingRecvHttpResponse(state, &response); - *state = (FFNetworkingState){}; + *state = (FFNetworkingState) {}; *status = FF_UNITIALIZED; - if (error == NULL) + if (error == NULL) { ffStrbufSubstrAfterFirstS(&response, "\r\n\r\n"); - else + } else { return error; + } - if (response.length == 0) + if (response.length == 0) { return "Empty server response received"; + } - if (options->url.length == 0) - { + if (options->url.length == 0) { yyjson_doc* __attribute__((__cleanup__(wrapYyjsonFree))) doc = yyjson_read_opts(response.chars, response.length, 0, NULL, NULL); - if (doc) - { + if (doc) { yyjson_val* root = yyjson_doc_get_root(doc); ffStrbufAppendJsonVal(&result->ip, yyjson_obj_get(root, "ip")); ffStrbufDestroy(&result->location); diff --git a/src/detection/publicip/publicip.h b/src/detection/publicip/publicip.h index 917e787ab..e8f97024a 100644 --- a/src/detection/publicip/publicip.h +++ b/src/detection/publicip/publicip.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/publicip/option.h" -typedef struct FFPublicIpResult -{ +typedef struct FFPublicIpResult { FFstrbuf ip; FFstrbuf location; } FFPublicIpResult; diff --git a/src/detection/sound/audio_oss_sunos.h b/src/detection/sound/audio_oss_sunos.h index c5e4e07e7..3ee36da90 100644 --- a/src/detection/sound/audio_oss_sunos.h +++ b/src/detection/sound/audio_oss_sunos.h @@ -25,9 +25,8 @@ * Use is subject to license terms. */ - -#ifndef _SYS_AUDIO_OSS_H -#define _SYS_AUDIO_OSS_H +#ifndef _SYS_AUDIO_OSS_H +#define _SYS_AUDIO_OSS_H #include #include @@ -57,11 +56,11 @@ extern "C" { * SNDCTL_DSP_GETOSPACE and SNDCTL_DSP_GETISPACE */ typedef struct audio_buf_info { - int fragments; /* # of available fragments */ - int fragstotal; /* Total # of fragments allocated */ - int fragsize; /* Size of a fragment in bytes */ - int bytes; /* Available space in bytes */ - /* Note! 'bytes' could be more than fragments*fragsize */ + int fragments; /* # of available fragments */ + int fragstotal; /* Total # of fragments allocated */ + int fragsize; /* Size of a fragment in bytes */ + int bytes; /* Available space in bytes */ + /* Note! 'bytes' could be more than fragments*fragsize */ } audio_buf_info; /* @@ -69,57 +68,57 @@ typedef struct audio_buf_info { * SNDCTL_DSP_SYNCGROUP and SNDCTL_DSP_SYNCSTART */ typedef struct oss_syncgroup { - int id; - int mode; - int filler[16]; + int id; + int mode; + int filler[16]; } oss_syncgroup; /* * SNDCTL_DSP_GETERROR */ typedef struct audio_errinfo { - int play_underruns; - int rec_overruns; - unsigned int play_ptradjust; - unsigned int rec_ptradjust; - int play_errorcount; - int rec_errorcount; - int play_lasterror; - int rec_lasterror; - int play_errorparm; - int rec_errorparm; - int filler[16]; + int play_underruns; + int rec_overruns; + unsigned int play_ptradjust; + unsigned int rec_ptradjust; + int play_errorcount; + int rec_errorcount; + int play_lasterror; + int rec_lasterror; + int play_errorparm; + int rec_errorparm; + int filler[16]; } audio_errinfo; /* * SNDCTL_DSP_GETIPTR and SNDCTL_DSP_GETOPTR */ typedef struct count_info { - unsigned int bytes; /* Total # of bytes processed */ - int blocks; /* # of fragment transitions since last time */ - int ptr; /* Current DMA pointer value */ + unsigned int bytes; /* Total # of bytes processed */ + int blocks; /* # of fragment transitions since last time */ + int ptr; /* Current DMA pointer value */ } count_info; /* * SNDCTL_DSP_CURENT_IPTR and SNDCTL_DSP_CURRENT_OPTR */ typedef struct { - long long samples; /* Total # of samples */ - int fifo_samples; /* Samples in device FIFO */ - int filler[32]; /* For future use */ + long long samples; /* Total # of samples */ + int fifo_samples; /* Samples in device FIFO */ + int filler[32]; /* For future use */ } oss_count_t; /* * SNDCTL_DSP_GET_RECSRC_NAMES and SNDCTL_DSP_GET_PLAYTGT_NAMES */ -#define OSS_ENUM_MAXVALUE 255 +#define OSS_ENUM_MAXVALUE 255 typedef struct oss_mixer_enuminfo { - int dev; - int ctrl; - int nvalues; - int version; - short strindex[OSS_ENUM_MAXVALUE]; - char strings[3000]; + int dev; + int ctrl; + int nvalues; + int version; + short strindex[OSS_ENUM_MAXVALUE]; + char strings[3000]; } oss_mixer_enuminfo; /* @@ -127,94 +126,94 @@ typedef struct oss_mixer_enuminfo { * SNDCTL_DSP_READCTL and SNDCTL_DSP_WRITECTL */ typedef struct oss_digital_control { - unsigned int caps; -#define DIG_CBITIN_NONE 0x00000000 -#define DIG_CBITIN_LIMITED 0x00000001 -#define DIG_CBITIN_DATA 0x00000002 -#define DIG_CBITIN_BYTE0 0x00000004 -#define DIG_CBITIN_FULL 0x00000008 -#define DIG_CBITIN_MASK 0x0000000f -#define DIG_CBITOUT_NONE 0x00000000 -#define DIG_CBITOUT_LIMITED 0x00000010 -#define DIG_CBITOUT_BYTE0 0x00000020 -#define DIG_CBITOUT_FULL 0x00000040 -#define DIG_CBITOUT_DATA 0x00000080 -#define DIG_CBITOUT_MASK 0x000000f0 -#define DIG_UBITIN 0x00000100 -#define DIG_UBITOUT 0x00000200 -#define DIG_VBITOUT 0x00000400 -#define DIG_OUTRATE 0x00000800 -#define DIG_INRATE 0x00001000 -#define DIG_INBITS 0x00002000 -#define DIG_OUTBITS 0x00004000 -#define DIG_EXACT 0x00010000 -#define DIG_PRO 0x00020000 -#define DIG_CONSUMER 0x00040000 -#define DIG_PASSTHROUGH 0x00080000 -#define DIG_OUTSEL 0x00100000 + unsigned int caps; +#define DIG_CBITIN_NONE 0x00000000 +#define DIG_CBITIN_LIMITED 0x00000001 +#define DIG_CBITIN_DATA 0x00000002 +#define DIG_CBITIN_BYTE0 0x00000004 +#define DIG_CBITIN_FULL 0x00000008 +#define DIG_CBITIN_MASK 0x0000000f +#define DIG_CBITOUT_NONE 0x00000000 +#define DIG_CBITOUT_LIMITED 0x00000010 +#define DIG_CBITOUT_BYTE0 0x00000020 +#define DIG_CBITOUT_FULL 0x00000040 +#define DIG_CBITOUT_DATA 0x00000080 +#define DIG_CBITOUT_MASK 0x000000f0 +#define DIG_UBITIN 0x00000100 +#define DIG_UBITOUT 0x00000200 +#define DIG_VBITOUT 0x00000400 +#define DIG_OUTRATE 0x00000800 +#define DIG_INRATE 0x00001000 +#define DIG_INBITS 0x00002000 +#define DIG_OUTBITS 0x00004000 +#define DIG_EXACT 0x00010000 +#define DIG_PRO 0x00020000 +#define DIG_CONSUMER 0x00040000 +#define DIG_PASSTHROUGH 0x00080000 +#define DIG_OUTSEL 0x00100000 - unsigned int valid; -#define VAL_CBITIN 0x00000001 -#define VAL_UBITIN 0x00000002 -#define VAL_CBITOUT 0x00000004 -#define VAL_UBITOUT 0x00000008 -#define VAL_ISTATUS 0x00000010 -#define VAL_IRATE 0x00000020 -#define VAL_ORATE 0x00000040 -#define VAL_INBITS 0x00000080 -#define VAL_OUTBITS 0x00000100 -#define VAL_REQUEST 0x00000200 -#define VAL_OUTSEL 0x00000400 + unsigned int valid; +#define VAL_CBITIN 0x00000001 +#define VAL_UBITIN 0x00000002 +#define VAL_CBITOUT 0x00000004 +#define VAL_UBITOUT 0x00000008 +#define VAL_ISTATUS 0x00000010 +#define VAL_IRATE 0x00000020 +#define VAL_ORATE 0x00000040 +#define VAL_INBITS 0x00000080 +#define VAL_OUTBITS 0x00000100 +#define VAL_REQUEST 0x00000200 +#define VAL_OUTSEL 0x00000400 -#define VAL_OUTMASK (VAL_CBITOUT|VAL_UBITOUT|VAL_ORATE|VAL_OUTBITS|VAL_OUTSEL) +#define VAL_OUTMASK (VAL_CBITOUT | VAL_UBITOUT | VAL_ORATE | VAL_OUTBITS | VAL_OUTSEL) - unsigned int request; - unsigned int param; -#define SPD_RQ_PASSTHROUGH 1 + unsigned int request; + unsigned int param; +#define SPD_RQ_PASSTHROUGH 1 - unsigned char cbitin[24]; - unsigned char ubitin[24]; - unsigned char cbitout[24]; - unsigned char ubitout[24]; + unsigned char cbitin[24]; + unsigned char ubitin[24]; + unsigned char cbitout[24]; + unsigned char ubitout[24]; - unsigned int outsel; -#define OUTSEL_DIGITAL 1 -#define OUTSEL_ANALOG 2 -#define OUTSEL_BOTH (OUTSEL_DIGITAL|OUTSEL_ANALOG) + unsigned int outsel; +#define OUTSEL_DIGITAL 1 +#define OUTSEL_ANALOG 2 +#define OUTSEL_BOTH (OUTSEL_DIGITAL | OUTSEL_ANALOG) - int in_data; /* Audio/data if autodetectable by receiver */ -#define IND_UNKNOWN 0 -#define IND_AUDIO 1 -#define IND_DATA 2 + int in_data; /* Audio/data if autodetectable by receiver */ +#define IND_UNKNOWN 0 +#define IND_AUDIO 1 +#define IND_DATA 2 - int in_locked; /* Receiver locked */ -#define LOCK_NOT_INDICATED 0 -#define LOCK_UNLOCKED 1 -#define LOCK_LOCKED 2 + int in_locked; /* Receiver locked */ +#define LOCK_NOT_INDICATED 0 +#define LOCK_UNLOCKED 1 +#define LOCK_LOCKED 2 - int in_quality; /* Input signal quality */ -#define IN_QUAL_NOT_INDICATED 0 -#define IN_QUAL_POOR 1 -#define IN_QUAL_GOOD 2 + int in_quality; /* Input signal quality */ +#define IN_QUAL_NOT_INDICATED 0 +#define IN_QUAL_POOR 1 +#define IN_QUAL_GOOD 2 - int in_vbit; - int out_vbit; /* V bits */ -#define VBIT_NOT_INDICATED 0 -#define VBIT_OFF 1 -#define VBIT_ON 2 + int in_vbit; + int out_vbit; /* V bits */ +#define VBIT_NOT_INDICATED 0 +#define VBIT_OFF 1 +#define VBIT_ON 2 - unsigned int in_errors; /* Various input error conditions */ -#define INERR_CRC 0x0001 -#define INERR_QCODE_CRC 0x0002 -#define INERR_PARITY 0x0004 -#define INERR_BIPHASE 0x0008 + unsigned int in_errors; /* Various input error conditions */ +#define INERR_CRC 0x0001 +#define INERR_QCODE_CRC 0x0002 +#define INERR_PARITY 0x0004 +#define INERR_BIPHASE 0x0008 - int srate_in; - int srate_out; - int bits_in; - int bits_out; + int srate_in; + int srate_out; + int bits_in; + int bits_out; - int filler[32]; + int filler[32]; } oss_digital_control; /* @@ -225,363 +224,360 @@ typedef struct oss_digital_control { * section of the OSS API Developer's Manual. There is no chance that you * could use this interface correctly just by examining this header. */ -#define OSS_VERSION 0x040003 -#define SOUND_VERSION OSS_VERSION +#define OSS_VERSION 0x040003 +#define SOUND_VERSION OSS_VERSION typedef struct oss_sysinfo { - char product[32]; /* E.g. SunOS Audio */ - char version[32]; /* E.g. 4.0a */ - int versionnum; /* See OSS_GETVERSION */ - char options[128]; /* NOT SUPPORTED */ + char product[32]; /* E.g. SunOS Audio */ + char version[32]; /* E.g. 4.0a */ + int versionnum; /* See OSS_GETVERSION */ + char options[128]; /* NOT SUPPORTED */ - int numaudios; /* # of audio/dsp devices */ - int openedaudio[8]; /* Mask of audio devices are busy */ + int numaudios; /* # of audio/dsp devices */ + int openedaudio[8]; /* Mask of audio devices are busy */ - int numsynths; /* NOT SUPPORTED, always 0 */ - int nummidis; /* NOT SUPPORTED, always 0 */ - int numtimers; /* NOT SUPPORTED, always 0 */ - int nummixers; /* # of mixer devices */ + int numsynths; /* NOT SUPPORTED, always 0 */ + int nummidis; /* NOT SUPPORTED, always 0 */ + int numtimers; /* NOT SUPPORTED, always 0 */ + int nummixers; /* # of mixer devices */ - int openedmidi[8]; /* Mask of midi devices are busy */ - int numcards; /* Number of sound cards in the system */ - int numaudioengines; /* Number of audio engines in the system */ - char license[16]; /* E.g. "GPL" or "CDDL" */ - char revision_info[256]; /* For internal use */ - int filler[172]; /* For future expansion */ + int openedmidi[8]; /* Mask of midi devices are busy */ + int numcards; /* Number of sound cards in the system */ + int numaudioengines; /* Number of audio engines in the system */ + char license[16]; /* E.g. "GPL" or "CDDL" */ + char revision_info[256]; /* For internal use */ + int filler[172]; /* For future expansion */ } oss_sysinfo; typedef struct oss_mixext { - int dev; /* Mixer device number */ - int ctrl; /* Extension number */ - int type; /* Entry type */ -#define MIXT_DEVROOT 0 /* Device root entry */ -#define MIXT_GROUP 1 /* Controller group */ -#define MIXT_ONOFF 2 /* OFF (0) or ON (1) */ -#define MIXT_ENUM 3 /* Enumerated (0 to maxvalue) */ -#define MIXT_MONOSLIDER 4 /* Mono slider (0 to 255) */ -#define MIXT_STEREOSLIDER 5 /* Stereo slider (dual 0 to 255) */ -#define MIXT_MESSAGE 6 /* (Readable) textual message */ -#define MIXT_MONOVU 7 /* VU meter value (mono) */ -#define MIXT_STEREOVU 8 /* VU meter value (stereo) */ -#define MIXT_MONOPEAK 9 /* VU meter peak value (mono) */ -#define MIXT_STEREOPEAK 10 /* VU meter peak value (stereo) */ -#define MIXT_RADIOGROUP 11 /* Radio button group */ -#define MIXT_MARKER 12 /* Separator between entries */ -#define MIXT_VALUE 13 /* Decimal value entry */ -#define MIXT_HEXVALUE 14 /* Hexadecimal value entry */ -#define MIXT_MONODB 15 /* OBSOLETE */ -#define MIXT_STEREODB 16 /* OBSOLETE */ -#define MIXT_SLIDER 17 /* Slider (mono, 31 bit int range) */ -#define MIXT_3D 18 -#define MIXT_MONOSLIDER16 19 /* Mono slider (0-32767) */ -#define MIXT_STEREOSLIDER16 20 /* Stereo slider (dual 0-32767) */ -#define MIXT_MUTE 21 /* Mute=1, unmute=0 */ + int dev; /* Mixer device number */ + int ctrl; /* Extension number */ + int type; /* Entry type */ +#define MIXT_DEVROOT 0 /* Device root entry */ +#define MIXT_GROUP 1 /* Controller group */ +#define MIXT_ONOFF 2 /* OFF (0) or ON (1) */ +#define MIXT_ENUM 3 /* Enumerated (0 to maxvalue) */ +#define MIXT_MONOSLIDER 4 /* Mono slider (0 to 255) */ +#define MIXT_STEREOSLIDER 5 /* Stereo slider (dual 0 to 255) */ +#define MIXT_MESSAGE 6 /* (Readable) textual message */ +#define MIXT_MONOVU 7 /* VU meter value (mono) */ +#define MIXT_STEREOVU 8 /* VU meter value (stereo) */ +#define MIXT_MONOPEAK 9 /* VU meter peak value (mono) */ +#define MIXT_STEREOPEAK 10 /* VU meter peak value (stereo) */ +#define MIXT_RADIOGROUP 11 /* Radio button group */ +#define MIXT_MARKER 12 /* Separator between entries */ +#define MIXT_VALUE 13 /* Decimal value entry */ +#define MIXT_HEXVALUE 14 /* Hexadecimal value entry */ +#define MIXT_MONODB 15 /* OBSOLETE */ +#define MIXT_STEREODB 16 /* OBSOLETE */ +#define MIXT_SLIDER 17 /* Slider (mono, 31 bit int range) */ +#define MIXT_3D 18 +#define MIXT_MONOSLIDER16 19 /* Mono slider (0-32767) */ +#define MIXT_STEREOSLIDER16 20 /* Stereo slider (dual 0-32767) */ +#define MIXT_MUTE 21 /* Mute=1, unmute=0 */ - /* Possible value range (minvalue to maxvalue) */ - /* Note that maxvalue may also be smaller than minvalue */ - int maxvalue; - int minvalue; + /* Possible value range (minvalue to maxvalue) */ + /* Note that maxvalue may also be smaller than minvalue */ + int maxvalue; + int minvalue; - int flags; -#define MIXF_READABLE 0x00000001 /* Has readable value */ -#define MIXF_WRITEABLE 0x00000002 /* Has writeable value */ -#define MIXF_POLL 0x00000004 /* May change itself */ -#define MIXF_HZ 0x00000008 /* Hertz scale */ -#define MIXF_STRING 0x00000010 /* Use dynamic extensions for value */ -#define MIXF_DYNAMIC 0x00000010 /* Supports dynamic extensions */ -#define MIXF_OKFAIL 0x00000020 /* Interpret value as 1=OK, 0=FAIL */ -#define MIXF_FLAT 0x00000040 /* NOT SUPPORTED */ -#define MIXF_LEGACY 0x00000080 /* NOT SUPPORTED */ -#define MIXF_CENTIBEL 0x00000100 /* Centibel (0.1 dB) step size */ -#define MIXF_DECIBEL 0x00000200 /* Step size of 1 dB */ -#define MIXF_MAINVOL 0x00000400 /* Main volume control */ -#define MIXF_PCMVOL 0x00000800 /* PCM output volume control */ -#define MIXF_RECVOL 0x00001000 /* PCM recording volume control */ -#define MIXF_MONVOL 0x00002000 /* Input->output monitor volume */ -#define MIXF_WIDE 0x00004000 /* NOT SUPPORTED */ -#define MIXF_DESCR 0x00008000 /* NOT SUPPORTED */ -#define MIXF_DISABLE 0x00010000 /* Control has been disabled */ + int flags; +#define MIXF_READABLE 0x00000001 /* Has readable value */ +#define MIXF_WRITEABLE 0x00000002 /* Has writeable value */ +#define MIXF_POLL 0x00000004 /* May change itself */ +#define MIXF_HZ 0x00000008 /* Hertz scale */ +#define MIXF_STRING 0x00000010 /* Use dynamic extensions for value */ +#define MIXF_DYNAMIC 0x00000010 /* Supports dynamic extensions */ +#define MIXF_OKFAIL 0x00000020 /* Interpret value as 1=OK, 0=FAIL */ +#define MIXF_FLAT 0x00000040 /* NOT SUPPORTED */ +#define MIXF_LEGACY 0x00000080 /* NOT SUPPORTED */ +#define MIXF_CENTIBEL 0x00000100 /* Centibel (0.1 dB) step size */ +#define MIXF_DECIBEL 0x00000200 /* Step size of 1 dB */ +#define MIXF_MAINVOL 0x00000400 /* Main volume control */ +#define MIXF_PCMVOL 0x00000800 /* PCM output volume control */ +#define MIXF_RECVOL 0x00001000 /* PCM recording volume control */ +#define MIXF_MONVOL 0x00002000 /* Input->output monitor volume */ +#define MIXF_WIDE 0x00004000 /* NOT SUPPORTED */ +#define MIXF_DESCR 0x00008000 /* NOT SUPPORTED */ +#define MIXF_DISABLE 0x00010000 /* Control has been disabled */ - char id[16]; /* Mnemonic ID (internal use) */ - int parent; /* Entry# of parent (-1 if root) */ + char id[16]; /* Mnemonic ID (internal use) */ + int parent; /* Entry# of parent (-1 if root) */ - int dummy; /* NOT SUPPORTED */ + int dummy; /* NOT SUPPORTED */ - int timestamp; + int timestamp; - char data[64]; /* Misc data (entry type dependent) */ - unsigned char enum_present[32]; /* Mask of allowed enum values */ - int control_no; /* NOT SUPPORTED, always -1 */ + char data[64]; /* Misc data (entry type dependent) */ + unsigned char enum_present[32]; /* Mask of allowed enum values */ + int control_no; /* NOT SUPPORTED, always -1 */ - unsigned int desc; /* Scope flags, etc */ -#define MIXEXT_SCOPE_MASK 0x0000003f -#define MIXEXT_SCOPE_OTHER 0x00000000 -#define MIXEXT_SCOPE_INPUT 0x00000001 -#define MIXEXT_SCOPE_OUTPUT 0x00000002 -#define MIXEXT_SCOPE_MONITOR 0x00000003 -#define MIXEXT_SCOPE_RECSWITCH 0x00000004 + unsigned int desc; /* Scope flags, etc */ +#define MIXEXT_SCOPE_MASK 0x0000003f +#define MIXEXT_SCOPE_OTHER 0x00000000 +#define MIXEXT_SCOPE_INPUT 0x00000001 +#define MIXEXT_SCOPE_OUTPUT 0x00000002 +#define MIXEXT_SCOPE_MONITOR 0x00000003 +#define MIXEXT_SCOPE_RECSWITCH 0x00000004 - char extname[32]; - int update_counter; -#ifdef _KERNEL - int filler[6]; - int enumbit; + char extname[32]; + int update_counter; +#ifdef _KERNEL + int filler[6]; + int enumbit; #else - int filler[7]; + int filler[7]; #endif } oss_mixext; typedef struct oss_mixext_root { - char id[16]; - char name[48]; + char id[16]; + char name[48]; } oss_mixext_root; typedef struct oss_mixer_value { - int dev; - int ctrl; - int value; - int flags; /* Reserved for future use. Initialize to 0 */ - int timestamp; /* Must be set to oss_mixext.timestamp */ - int filler[8]; /* Reserved for future use. Initialize to 0 */ + int dev; + int ctrl; + int value; + int flags; /* Reserved for future use. Initialize to 0 */ + int timestamp; /* Must be set to oss_mixext.timestamp */ + int filler[8]; /* Reserved for future use. Initialize to 0 */ } oss_mixer_value; -#define OSS_LONGNAME_SIZE 64 -#define OSS_LABEL_SIZE 16 -#define OSS_DEVNODE_SIZE 32 -typedef char oss_longname_t[OSS_LONGNAME_SIZE]; -typedef char oss_label_t[OSS_LABEL_SIZE]; -typedef char oss_devnode_t[OSS_DEVNODE_SIZE]; - +#define OSS_LONGNAME_SIZE 64 +#define OSS_LABEL_SIZE 16 +#define OSS_DEVNODE_SIZE 32 +typedef char oss_longname_t[OSS_LONGNAME_SIZE]; +typedef char oss_label_t[OSS_LABEL_SIZE]; +typedef char oss_devnode_t[OSS_DEVNODE_SIZE]; typedef struct oss_audioinfo { - int dev; /* Audio device number */ - char name[64]; - int busy; /* 0, OPEN_READ, OPEN_WRITE, OPEN_READWRITE */ - int pid; /* Process ID, not used in SunOS */ - int caps; /* PCM_CAP_INPUT, PCM_CAP_OUTPUT */ - int iformats; /* Supported input formats */ - int oformats; /* Supported output formats */ - int magic; /* Internal use only */ - char cmd[64]; /* Command using the device (if known) */ - int card_number; - int port_number; - int mixer_dev; - int legacy_device; /* Obsolete field. Replaced by devnode */ - int enabled; /* 1=enabled, 0=device not ready */ - int flags; /* internal use only - no practical meaning */ - int min_rate; /* Minimum sample rate */ - int max_rate; /* Maximum sample rate */ - int min_channels; /* Minimum number of channels */ - int max_channels; /* Maximum number of channels */ - int binding; /* DSP_BIND_FRONT, etc. 0 means undefined */ - int rate_source; - char handle[32]; -#define OSS_MAX_SAMPLE_RATES 20 /* Cannot be changed */ - unsigned int nrates; /* Array of supported sample rates */ - unsigned int rates[OSS_MAX_SAMPLE_RATES]; - oss_longname_t song_name; /* Song name (if given) */ - oss_label_t label; /* Device label (if given) */ - int latency; /* In usecs, -1=unknown */ - oss_devnode_t devnode; /* Device special file name (absolute path) */ - int next_play_engine; - int next_rec_engine; - int filler[184]; + int dev; /* Audio device number */ + char name[64]; + int busy; /* 0, OPEN_READ, OPEN_WRITE, OPEN_READWRITE */ + int pid; /* Process ID, not used in SunOS */ + int caps; /* PCM_CAP_INPUT, PCM_CAP_OUTPUT */ + int iformats; /* Supported input formats */ + int oformats; /* Supported output formats */ + int magic; /* Internal use only */ + char cmd[64]; /* Command using the device (if known) */ + int card_number; + int port_number; + int mixer_dev; + int legacy_device; /* Obsolete field. Replaced by devnode */ + int enabled; /* 1=enabled, 0=device not ready */ + int flags; /* internal use only - no practical meaning */ + int min_rate; /* Minimum sample rate */ + int max_rate; /* Maximum sample rate */ + int min_channels; /* Minimum number of channels */ + int max_channels; /* Maximum number of channels */ + int binding; /* DSP_BIND_FRONT, etc. 0 means undefined */ + int rate_source; + char handle[32]; +#define OSS_MAX_SAMPLE_RATES 20 /* Cannot be changed */ + unsigned int nrates; /* Array of supported sample rates */ + unsigned int rates[OSS_MAX_SAMPLE_RATES]; + oss_longname_t song_name; /* Song name (if given) */ + oss_label_t label; /* Device label (if given) */ + int latency; /* In usecs, -1=unknown */ + oss_devnode_t devnode; /* Device special file name (absolute path) */ + int next_play_engine; + int next_rec_engine; + int filler[184]; } oss_audioinfo; typedef struct oss_mixerinfo { - int dev; - char id[16]; - char name[32]; - int modify_counter; - int card_number; - int port_number; - char handle[32]; - int magic; /* Reserved */ - int enabled; /* Reserved */ - int caps; -#define MIXER_CAP_VIRTUAL 0x00000001 -#define MIXER_CAP_LAYOUT_B 0x00000002 /* For internal use only */ -#define MIXER_CAP_NARROW 0x00000004 /* Conserve horiz space */ - int flags; /* Reserved */ - int nrext; - /* - * The priority field can be used to select the default - * (motherboard) mixer device. The mixer with the highest - * priority is the most preferred one. -2 or less means that - * this device cannot be used as the default mixer. - */ - int priority; - oss_devnode_t devnode; /* Device special file name (absolute path) */ - int legacy_device; - int filler[245]; /* Reserved */ + int dev; + char id[16]; + char name[32]; + int modify_counter; + int card_number; + int port_number; + char handle[32]; + int magic; /* Reserved */ + int enabled; /* Reserved */ + int caps; +#define MIXER_CAP_VIRTUAL 0x00000001 +#define MIXER_CAP_LAYOUT_B 0x00000002 /* For internal use only */ +#define MIXER_CAP_NARROW 0x00000004 /* Conserve horiz space */ + int flags; /* Reserved */ + int nrext; + /* + * The priority field can be used to select the default + * (motherboard) mixer device. The mixer with the highest + * priority is the most preferred one. -2 or less means that + * this device cannot be used as the default mixer. + */ + int priority; + oss_devnode_t devnode; /* Device special file name (absolute path) */ + int legacy_device; + int filler[245]; /* Reserved */ } oss_mixerinfo; typedef struct oss_card_info { - int card; - char shortname[16]; - char longname[128]; - int flags; - char hw_info[400]; - int intr_count; - int ack_count; - int filler[154]; + int card; + char shortname[16]; + char longname[128]; + int flags; + char hw_info[400]; + int intr_count; + int ack_count; + int filler[154]; } oss_card_info; -typedef struct mixer_info { /* OBSOLETE */ - char id[16]; - char name[32]; - int modify_counter; - int card_number; - int port_number; - char handle[32]; +typedef struct mixer_info { /* OBSOLETE */ + char id[16]; + char name[32]; + int modify_counter; + int card_number; + int port_number; + char handle[32]; } mixer_info; -#define MAX_PEAK_CHANNELS 128 +#define MAX_PEAK_CHANNELS 128 typedef unsigned short oss_peaks_t[MAX_PEAK_CHANNELS]; /* For use with SNDCTL_DSP_GET_CHNORDER */ -#define CHID_UNDEF 0 -#define CHID_L 1 -#define CHID_R 2 -#define CHID_C 3 -#define CHID_LFE 4 -#define CHID_LS 5 -#define CHID_RS 6 -#define CHID_LR 7 -#define CHID_RR 8 -#define CHNORDER_UNDEF 0x0000000000000000ULL -#define CHNORDER_NORMAL 0x0000000087654321ULL +#define CHID_UNDEF 0 +#define CHID_L 1 +#define CHID_R 2 +#define CHID_C 3 +#define CHID_LFE 4 +#define CHID_LS 5 +#define CHID_RS 6 +#define CHID_LR 7 +#define CHID_RR 8 +#define CHNORDER_UNDEF 0x0000000000000000ULL +#define CHNORDER_NORMAL 0x0000000087654321ULL +#define OSSIOCPARM_MASK 0x1fff /* parameters must be < 8192 bytes */ +#define OSSIOC_VOID 0x00000000 /* no parameters */ +#define OSSIOC_OUT 0x20000000 /* copy out parameters */ +#define OSSIOC_IN 0x40000000 /* copy in parameters */ +#define OSSIOC_INOUT (OSSIOC_IN | OSSIOC_OUT) +#define OSSIOC_SZ(t) ((sizeof(t) & OSSIOCPARM_MASK) << 16) +#define OSSIOC_GETSZ(x) (((x) >> 16) & OSSIOCPARM_MASK) -#define OSSIOCPARM_MASK 0x1fff /* parameters must be < 8192 bytes */ -#define OSSIOC_VOID 0x00000000 /* no parameters */ -#define OSSIOC_OUT 0x20000000 /* copy out parameters */ -#define OSSIOC_IN 0x40000000 /* copy in parameters */ -#define OSSIOC_INOUT (OSSIOC_IN|OSSIOC_OUT) -#define OSSIOC_SZ(t) ((sizeof (t) & OSSIOCPARM_MASK) << 16) -#define OSSIOC_GETSZ(x) (((x) >> 16) & OSSIOCPARM_MASK) +#define __OSSIO(x, y) ((int) (OSSIOC_VOID | (x << 8) | y)) +#define __OSSIOR(x, y, t) ((int) (OSSIOC_OUT | OSSIOC_SZ(t) | (x << 8) | y)) +#define __OSSIOW(x, y, t) ((int) (OSSIOC_IN | OSSIOC_SZ(t) | (x << 8) | y)) +#define __OSSIOWR(x, y, t) ((int) (OSSIOC_INOUT | OSSIOC_SZ(t) | (x << 8) | y)) -#define __OSSIO(x, y) ((int)(OSSIOC_VOID|(x<<8)|y)) -#define __OSSIOR(x, y, t) ((int)(OSSIOC_OUT|OSSIOC_SZ(t)|(x<<8)|y)) -#define __OSSIOW(x, y, t) ((int)(OSSIOC_IN|OSSIOC_SZ(t)|(x<<8)|y)) -#define __OSSIOWR(x, y, t) ((int)(OSSIOC_INOUT|OSSIOC_SZ(t)|(x<<8)|y)) +#define SNDCTL_SYSINFO __OSSIOR('X', 1, oss_sysinfo) +#define OSS_SYSINFO SNDCTL_SYSINFO /* Old name */ -#define SNDCTL_SYSINFO __OSSIOR('X', 1, oss_sysinfo) -#define OSS_SYSINFO SNDCTL_SYSINFO /* Old name */ +#define SNDCTL_MIX_NRMIX __OSSIOR('X', 2, int) +#define SNDCTL_MIX_NREXT __OSSIOWR('X', 3, int) +#define SNDCTL_MIX_EXTINFO __OSSIOWR('X', 4, oss_mixext) +#define SNDCTL_MIX_READ __OSSIOWR('X', 5, oss_mixer_value) +#define SNDCTL_MIX_WRITE __OSSIOWR('X', 6, oss_mixer_value) -#define SNDCTL_MIX_NRMIX __OSSIOR('X', 2, int) -#define SNDCTL_MIX_NREXT __OSSIOWR('X', 3, int) -#define SNDCTL_MIX_EXTINFO __OSSIOWR('X', 4, oss_mixext) -#define SNDCTL_MIX_READ __OSSIOWR('X', 5, oss_mixer_value) -#define SNDCTL_MIX_WRITE __OSSIOWR('X', 6, oss_mixer_value) - -#define SNDCTL_AUDIOINFO __OSSIOWR('X', 7, oss_audioinfo) -#define SNDCTL_MIX_ENUMINFO __OSSIOWR('X', 8, oss_mixer_enuminfo) -#define SNDCTL_MIDIINFO __OSSIO('X', 9) -#define SNDCTL_MIXERINFO __OSSIOWR('X', 10, oss_mixerinfo) -#define SNDCTL_CARDINFO __OSSIOWR('X', 11, oss_card_info) -#define SNDCTL_ENGINEINFO __OSSIOWR('X', 12, oss_audioinfo) -#define SNDCTL_AUDIOINFO_EX __OSSIOWR('X', 13, oss_audioinfo) -#define SNDCTL_MIX_DESCRIPTION __OSSIOWR('X', 14, oss_mixer_enuminfo) +#define SNDCTL_AUDIOINFO __OSSIOWR('X', 7, oss_audioinfo) +#define SNDCTL_MIX_ENUMINFO __OSSIOWR('X', 8, oss_mixer_enuminfo) +#define SNDCTL_MIDIINFO __OSSIO('X', 9) +#define SNDCTL_MIXERINFO __OSSIOWR('X', 10, oss_mixerinfo) +#define SNDCTL_CARDINFO __OSSIOWR('X', 11, oss_card_info) +#define SNDCTL_ENGINEINFO __OSSIOWR('X', 12, oss_audioinfo) +#define SNDCTL_AUDIOINFO_EX __OSSIOWR('X', 13, oss_audioinfo) +#define SNDCTL_MIX_DESCRIPTION __OSSIOWR('X', 14, oss_mixer_enuminfo) /* ioctl codes 'X', 200-255 are reserved for internal use */ /* * Few more "globally" available ioctl calls. */ -#define SNDCTL_SETSONG __OSSIOW('Y', 2, oss_longname_t) -#define SNDCTL_GETSONG __OSSIOR('Y', 2, oss_longname_t) -#define SNDCTL_SETNAME __OSSIOW('Y', 3, oss_longname_t) -#define SNDCTL_SETLABEL __OSSIOW('Y', 4, oss_label_t) -#define SNDCTL_GETLABEL __OSSIOR('Y', 4, oss_label_t) +#define SNDCTL_SETSONG __OSSIOW('Y', 2, oss_longname_t) +#define SNDCTL_GETSONG __OSSIOR('Y', 2, oss_longname_t) +#define SNDCTL_SETNAME __OSSIOW('Y', 3, oss_longname_t) +#define SNDCTL_SETLABEL __OSSIOW('Y', 4, oss_label_t) +#define SNDCTL_GETLABEL __OSSIOR('Y', 4, oss_label_t) /* * IOCTL commands for /dev/dsp */ -#define SNDCTL_DSP_HALT __OSSIO('P', 0) -#define SNDCTL_DSP_RESET SNDCTL_DSP_HALT /* Old name */ -#define SNDCTL_DSP_SYNC __OSSIO('P', 1) -#define SNDCTL_DSP_SPEED __OSSIOWR('P', 2, int) +#define SNDCTL_DSP_HALT __OSSIO('P', 0) +#define SNDCTL_DSP_RESET SNDCTL_DSP_HALT /* Old name */ +#define SNDCTL_DSP_SYNC __OSSIO('P', 1) +#define SNDCTL_DSP_SPEED __OSSIOWR('P', 2, int) -#define SNDCTL_DSP_STEREO __OSSIOWR('P', 3, int) /* OBSOLETE */ +#define SNDCTL_DSP_STEREO __OSSIOWR('P', 3, int) /* OBSOLETE */ -#define SNDCTL_DSP_GETBLKSIZE __OSSIOWR('P', 4, int) -#define SNDCTL_DSP_SAMPLESIZE SNDCTL_DSP_SETFMT -#define SNDCTL_DSP_CHANNELS __OSSIOWR('P', 6, int) -#define SNDCTL_DSP_POST __OSSIO('P', 8) -#define SNDCTL_DSP_SUBDIVIDE __OSSIOWR('P', 9, int) -#define SNDCTL_DSP_SETFRAGMENT __OSSIOWR('P', 10, int) +#define SNDCTL_DSP_GETBLKSIZE __OSSIOWR('P', 4, int) +#define SNDCTL_DSP_SAMPLESIZE SNDCTL_DSP_SETFMT +#define SNDCTL_DSP_CHANNELS __OSSIOWR('P', 6, int) +#define SNDCTL_DSP_POST __OSSIO('P', 8) +#define SNDCTL_DSP_SUBDIVIDE __OSSIOWR('P', 9, int) +#define SNDCTL_DSP_SETFRAGMENT __OSSIOWR('P', 10, int) -#define SNDCTL_DSP_GETFMTS __OSSIOR('P', 11, int) /* Returns a mask */ -#define SNDCTL_DSP_SETFMT __OSSIOWR('P', 5, int) /* Selects ONE fmt */ +#define SNDCTL_DSP_GETFMTS __OSSIOR('P', 11, int) /* Returns a mask */ +#define SNDCTL_DSP_SETFMT __OSSIOWR('P', 5, int) /* Selects ONE fmt */ -#define SNDCTL_DSP_GETOSPACE __OSSIOR('P', 12, audio_buf_info) -#define SNDCTL_DSP_GETISPACE __OSSIOR('P', 13, audio_buf_info) -#define SNDCTL_DSP_NONBLOCK __OSSIO('P', 14) /* Obsolete */ -#define SNDCTL_DSP_GETCAPS __OSSIOR('P', 15, int) +#define SNDCTL_DSP_GETOSPACE __OSSIOR('P', 12, audio_buf_info) +#define SNDCTL_DSP_GETISPACE __OSSIOR('P', 13, audio_buf_info) +#define SNDCTL_DSP_NONBLOCK __OSSIO('P', 14) /* Obsolete */ +#define SNDCTL_DSP_GETCAPS __OSSIOR('P', 15, int) -#define SNDCTL_DSP_GETTRIGGER __OSSIOR('P', 16, int) -#define SNDCTL_DSP_SETTRIGGER __OSSIOW('P', 16, int) +#define SNDCTL_DSP_GETTRIGGER __OSSIOR('P', 16, int) +#define SNDCTL_DSP_SETTRIGGER __OSSIOW('P', 16, int) -#define SNDCTL_DSP_GETIPTR __OSSIOR('P', 17, count_info) -#define SNDCTL_DSP_GETOPTR __OSSIOR('P', 18, count_info) +#define SNDCTL_DSP_GETIPTR __OSSIOR('P', 17, count_info) +#define SNDCTL_DSP_GETOPTR __OSSIOR('P', 18, count_info) -#define SNDCTL_DSP_SETSYNCRO __OSSIO('P', 21) -#define SNDCTL_DSP_SETDUPLEX __OSSIO('P', 22) +#define SNDCTL_DSP_SETSYNCRO __OSSIO('P', 21) +#define SNDCTL_DSP_SETDUPLEX __OSSIO('P', 22) -#define SNDCTL_DSP_PROFILE __OSSIOW('P', 23, int) /* OBSOLETE */ -#define APF_NORMAL 0 /* Normal applications */ -#define APF_NETWORK 1 /* Underruns caused by "external" delay */ -#define APF_CPUINTENS 2 /* Underruns caused by "overheating" the CPU */ +#define SNDCTL_DSP_PROFILE __OSSIOW('P', 23, int) /* OBSOLETE */ +#define APF_NORMAL 0 /* Normal applications */ +#define APF_NETWORK 1 /* Underruns caused by "external" delay */ +#define APF_CPUINTENS 2 /* Underruns caused by "overheating" the CPU */ +#define SNDCTL_DSP_GETODELAY __OSSIOR('P', 23, int) -#define SNDCTL_DSP_GETODELAY __OSSIOR('P', 23, int) +#define SNDCTL_DSP_GETPLAYVOL __OSSIOR('P', 24, int) +#define SNDCTL_DSP_SETPLAYVOL __OSSIOWR('P', 24, int) +#define SNDCTL_DSP_GETERROR __OSSIOR('P', 25, audio_errinfo) -#define SNDCTL_DSP_GETPLAYVOL __OSSIOR('P', 24, int) -#define SNDCTL_DSP_SETPLAYVOL __OSSIOWR('P', 24, int) -#define SNDCTL_DSP_GETERROR __OSSIOR('P', 25, audio_errinfo) +#define SNDCTL_DSP_READCTL __OSSIOWR('P', 26, oss_digital_control) +#define SNDCTL_DSP_WRITECTL __OSSIOWR('P', 27, oss_digital_control) -#define SNDCTL_DSP_READCTL __OSSIOWR('P', 26, oss_digital_control) -#define SNDCTL_DSP_WRITECTL __OSSIOWR('P', 27, oss_digital_control) +#define SNDCTL_DSP_SYNCGROUP __OSSIOWR('P', 28, oss_syncgroup) +#define SNDCTL_DSP_SYNCSTART __OSSIOW('P', 29, int) -#define SNDCTL_DSP_SYNCGROUP __OSSIOWR('P', 28, oss_syncgroup) -#define SNDCTL_DSP_SYNCSTART __OSSIOW('P', 29, int) +#define SNDCTL_DSP_COOKEDMODE __OSSIOW('P', 30, int) -#define SNDCTL_DSP_COOKEDMODE __OSSIOW('P', 30, int) +#define SNDCTL_DSP_SILENCE __OSSIO('P', 31) +#define SNDCTL_DSP_SKIP __OSSIO('P', 32) -#define SNDCTL_DSP_SILENCE __OSSIO('P', 31) -#define SNDCTL_DSP_SKIP __OSSIO('P', 32) +#define SNDCTL_DSP_HALT_INPUT __OSSIO('P', 33) +#define SNDCTL_DSP_RESET_INPUT SNDCTL_DSP_HALT_INPUT /* Old name */ +#define SNDCTL_DSP_HALT_OUTPUT __OSSIO('P', 34) +#define SNDCTL_DSP_RESET_OUTPUT SNDCTL_DSP_HALT_OUTPUT /* Old name */ -#define SNDCTL_DSP_HALT_INPUT __OSSIO('P', 33) -#define SNDCTL_DSP_RESET_INPUT SNDCTL_DSP_HALT_INPUT /* Old name */ -#define SNDCTL_DSP_HALT_OUTPUT __OSSIO('P', 34) -#define SNDCTL_DSP_RESET_OUTPUT SNDCTL_DSP_HALT_OUTPUT /* Old name */ +#define SNDCTL_DSP_LOW_WATER __OSSIOW('P', 34, int) -#define SNDCTL_DSP_LOW_WATER __OSSIOW('P', 34, int) +#define SNDCTL_DSP_CURRENT_IPTR __OSSIOR('P', 35, oss_count_t) +#define SNDCTL_DSP_CURRENT_OPTR __OSSIOR('P', 36, oss_count_t) -#define SNDCTL_DSP_CURRENT_IPTR __OSSIOR('P', 35, oss_count_t) -#define SNDCTL_DSP_CURRENT_OPTR __OSSIOR('P', 36, oss_count_t) +#define SNDCTL_DSP_GET_RECSRC_NAMES __OSSIOR('P', 37, oss_mixer_enuminfo) +#define SNDCTL_DSP_GET_RECSRC __OSSIOR('P', 38, int) +#define SNDCTL_DSP_SET_RECSRC __OSSIOWR('P', 38, int) -#define SNDCTL_DSP_GET_RECSRC_NAMES __OSSIOR('P', 37, oss_mixer_enuminfo) -#define SNDCTL_DSP_GET_RECSRC __OSSIOR('P', 38, int) -#define SNDCTL_DSP_SET_RECSRC __OSSIOWR('P', 38, int) +#define SNDCTL_DSP_GET_PLAYTGT_NAMES __OSSIOR('P', 39, oss_mixer_enuminfo) +#define SNDCTL_DSP_GET_PLAYTGT __OSSIOR('P', 40, int) +#define SNDCTL_DSP_SET_PLAYTGT __OSSIOWR('P', 40, int) +#define SNDCTL_DSP_GETRECVOL __OSSIOR('P', 41, int) +#define SNDCTL_DSP_SETRECVOL __OSSIOWR('P', 41, int) -#define SNDCTL_DSP_GET_PLAYTGT_NAMES __OSSIOR('P', 39, oss_mixer_enuminfo) -#define SNDCTL_DSP_GET_PLAYTGT __OSSIOR('P', 40, int) -#define SNDCTL_DSP_SET_PLAYTGT __OSSIOWR('P', 40, int) -#define SNDCTL_DSP_GETRECVOL __OSSIOR('P', 41, int) -#define SNDCTL_DSP_SETRECVOL __OSSIOWR('P', 41, int) +#define SNDCTL_DSP_GET_CHNORDER __OSSIOR('P', 42, unsigned long long) +#define SNDCTL_DSP_SET_CHNORDER __OSSIOWR('P', 42, unsigned long long) -#define SNDCTL_DSP_GET_CHNORDER __OSSIOR('P', 42, unsigned long long) -#define SNDCTL_DSP_SET_CHNORDER __OSSIOWR('P', 42, unsigned long long) +#define SNDCTL_DSP_GETIPEAKS __OSSIOR('P', 43, oss_peaks_t) +#define SNDCTL_DSP_GETOPEAKS __OSSIOR('P', 44, oss_peaks_t) -#define SNDCTL_DSP_GETIPEAKS __OSSIOR('P', 43, oss_peaks_t) -#define SNDCTL_DSP_GETOPEAKS __OSSIOR('P', 44, oss_peaks_t) +#define SNDCTL_DSP_POLICY __OSSIOW('P', 45, int) /* See the manual */ -#define SNDCTL_DSP_POLICY __OSSIOW('P', 45, int) /* See the manual */ - -#define SNDCTL_DSP_GETCHANNELMASK __OSSIOWR('P', 64, int) -#define SNDCTL_DSP_BIND_CHANNEL __OSSIOWR('P', 65, int) +#define SNDCTL_DSP_GETCHANNELMASK __OSSIOWR('P', 64, int) +#define SNDCTL_DSP_BIND_CHANNEL __OSSIOWR('P', 65, int) /* * These definitions are here for the benefit of compiling application @@ -589,235 +585,227 @@ typedef unsigned short oss_peaks_t[MAX_PEAK_CHANNELS]; * however. This is the older 3.x OSS API, and only the master input and * output levels are actually supported. */ -#define SOUND_MIXER_NRDEVICES 28 -#define SOUND_MIXER_VOLUME 0 -#define SOUND_MIXER_BASS 1 -#define SOUND_MIXER_TREBLE 2 -#define SOUND_MIXER_SYNTH 3 -#define SOUND_MIXER_PCM 4 -#define SOUND_MIXER_SPEAKER 5 -#define SOUND_MIXER_LINE 6 -#define SOUND_MIXER_MIC 7 -#define SOUND_MIXER_CD 8 -#define SOUND_MIXER_IMIX 9 /* Recording monitor */ -#define SOUND_MIXER_ALTPCM 10 -#define SOUND_MIXER_RECLEV 11 /* Recording level */ -#define SOUND_MIXER_IGAIN 12 /* Input gain */ -#define SOUND_MIXER_OGAIN 13 /* Output gain */ -#define SOUND_MIXER_LINE1 14 /* Input source 1 (aux1) */ -#define SOUND_MIXER_LINE2 15 /* Input source 2 (aux2) */ -#define SOUND_MIXER_LINE3 16 /* Input source 3 (line) */ -#define SOUND_MIXER_DIGITAL1 17 /* Digital I/O 1 */ -#define SOUND_MIXER_DIGITAL2 18 /* Digital I/O 2 */ -#define SOUND_MIXER_DIGITAL3 19 /* Digital I/O 3 */ -#define SOUND_MIXER_PHONE 20 /* Phone */ -#define SOUND_MIXER_MONO 21 /* Mono Output */ -#define SOUND_MIXER_VIDEO 22 /* Video/TV (audio) in */ -#define SOUND_MIXER_RADIO 23 /* Radio in */ -#define SOUND_MIXER_DEPTH 24 /* Surround depth */ -#define SOUND_MIXER_REARVOL 25 /* Rear/Surround speaker vol */ -#define SOUND_MIXER_CENTERVOL 26 /* Center/LFE speaker vol */ -#define SOUND_MIXER_SIDEVOL 27 /* Side-Surround (8speaker) vol */ -#define SOUND_MIXER_SURRVOL SOUND_MIXER_SIDEVOL -#define SOUND_ONOFF_MIN 28 -#define SOUND_ONOFF_MAX 30 -#define SOUND_MIXER_NONE 31 +#define SOUND_MIXER_NRDEVICES 28 +#define SOUND_MIXER_VOLUME 0 +#define SOUND_MIXER_BASS 1 +#define SOUND_MIXER_TREBLE 2 +#define SOUND_MIXER_SYNTH 3 +#define SOUND_MIXER_PCM 4 +#define SOUND_MIXER_SPEAKER 5 +#define SOUND_MIXER_LINE 6 +#define SOUND_MIXER_MIC 7 +#define SOUND_MIXER_CD 8 +#define SOUND_MIXER_IMIX 9 /* Recording monitor */ +#define SOUND_MIXER_ALTPCM 10 +#define SOUND_MIXER_RECLEV 11 /* Recording level */ +#define SOUND_MIXER_IGAIN 12 /* Input gain */ +#define SOUND_MIXER_OGAIN 13 /* Output gain */ +#define SOUND_MIXER_LINE1 14 /* Input source 1 (aux1) */ +#define SOUND_MIXER_LINE2 15 /* Input source 2 (aux2) */ +#define SOUND_MIXER_LINE3 16 /* Input source 3 (line) */ +#define SOUND_MIXER_DIGITAL1 17 /* Digital I/O 1 */ +#define SOUND_MIXER_DIGITAL2 18 /* Digital I/O 2 */ +#define SOUND_MIXER_DIGITAL3 19 /* Digital I/O 3 */ +#define SOUND_MIXER_PHONE 20 /* Phone */ +#define SOUND_MIXER_MONO 21 /* Mono Output */ +#define SOUND_MIXER_VIDEO 22 /* Video/TV (audio) in */ +#define SOUND_MIXER_RADIO 23 /* Radio in */ +#define SOUND_MIXER_DEPTH 24 /* Surround depth */ +#define SOUND_MIXER_REARVOL 25 /* Rear/Surround speaker vol */ +#define SOUND_MIXER_CENTERVOL 26 /* Center/LFE speaker vol */ +#define SOUND_MIXER_SIDEVOL 27 /* Side-Surround (8speaker) vol */ +#define SOUND_MIXER_SURRVOL SOUND_MIXER_SIDEVOL +#define SOUND_ONOFF_MIN 28 +#define SOUND_ONOFF_MAX 30 +#define SOUND_MIXER_NONE 31 -#define SOUND_MIXER_RECSRC 0xff /* Recording sources */ -#define SOUND_MIXER_DEVMASK 0xfe /* Supported devices */ -#define SOUND_MIXER_RECMASK 0xfd /* Recording sources */ -#define SOUND_MIXER_CAPS 0xfc /* Mixer capabilities (do not use) */ -#define SOUND_MIXER_STEREODEVS 0xfb /* Mixer channels supporting stereo */ -#define SOUND_MIXER_OUTSRC 0xfa -#define SOUND_MIXER_OUTMASK 0xf9 +#define SOUND_MIXER_RECSRC 0xff /* Recording sources */ +#define SOUND_MIXER_DEVMASK 0xfe /* Supported devices */ +#define SOUND_MIXER_RECMASK 0xfd /* Recording sources */ +#define SOUND_MIXER_CAPS 0xfc /* Mixer capabilities (do not use) */ +#define SOUND_MIXER_STEREODEVS 0xfb /* Mixer channels supporting stereo */ +#define SOUND_MIXER_OUTSRC 0xfa +#define SOUND_MIXER_OUTMASK 0xf9 -#define SOUND_MIXER_ENHANCE SOUND_MIXER_NONE -#define SOUND_MIXER_MUTE SOUND_MIXER_NONE -#define SOUND_MIXER_LOUD SOUND_MIXER_NONE +#define SOUND_MIXER_ENHANCE SOUND_MIXER_NONE +#define SOUND_MIXER_MUTE SOUND_MIXER_NONE +#define SOUND_MIXER_LOUD SOUND_MIXER_NONE -#define SOUND_MASK_VOLUME (1 << SOUND_MIXER_VOLUME) -#define SOUND_MASK_BASS (1 << SOUND_MIXER_BASS) -#define SOUND_MASK_TREBLE (1 << SOUND_MIXER_TREBLE) -#define SOUND_MASK_SYNTH (1 << SOUND_MIXER_SYNTH) -#define SOUND_MASK_PCM (1 << SOUND_MIXER_PCM) -#define SOUND_MASK_SPEAKER (1 << SOUND_MIXER_SPEAKER) -#define SOUND_MASK_LINE (1 << SOUND_MIXER_LINE) -#define SOUND_MASK_MIC (1 << SOUND_MIXER_MIC) -#define SOUND_MASK_CD (1 << SOUND_MIXER_CD) -#define SOUND_MASK_IMIX (1 << SOUND_MIXER_IMIX) -#define SOUND_MASK_ALTPCM (1 << SOUND_MIXER_ALTPCM) -#define SOUND_MASK_RECLEV (1 << SOUND_MIXER_RECLEV) -#define SOUND_MASK_IGAIN (1 << SOUND_MIXER_IGAIN) -#define SOUND_MASK_OGAIN (1 << SOUND_MIXER_OGAIN) -#define SOUND_MASK_LINE1 (1 << SOUND_MIXER_LINE1) -#define SOUND_MASK_LINE2 (1 << SOUND_MIXER_LINE2) -#define SOUND_MASK_LINE3 (1 << SOUND_MIXER_LINE3) -#define SOUND_MASK_DIGITAL1 (1 << SOUND_MIXER_DIGITAL1) -#define SOUND_MASK_DIGITAL2 (1 << SOUND_MIXER_DIGITAL2) -#define SOUND_MASK_DIGITAL3 (1 << SOUND_MIXER_DIGITAL3) -#define SOUND_MASK_MONO (1 << SOUND_MIXER_MONO) -#define SOUND_MASK_PHONE (1 << SOUND_MIXER_PHONE) -#define SOUND_MASK_RADIO (1 << SOUND_MIXER_RADIO) -#define SOUND_MASK_VIDEO (1 << SOUND_MIXER_VIDEO) -#define SOUND_MASK_DEPTH (1 << SOUND_MIXER_DEPTH) -#define SOUND_MASK_REARVOL (1 << SOUND_MIXER_REARVOL) -#define SOUND_MASK_CENTERVOL (1 << SOUND_MIXER_CENTERVOL) -#define SOUND_MASK_SIDEVOL (1 << SOUND_MIXER_SIDEVOL) -#define SOUND_MASK_SURRVOL SOUND_MASK_SIDEVOL -#define SOUND_MASK_MUTE (1 << SOUND_MIXER_MUTE) -#define SOUND_MASK_ENHANCE (1 << SOUND_MIXER_ENHANCE) -#define SOUND_MASK_LOUD (1 << SOUND_MIXER_LOUD) +#define SOUND_MASK_VOLUME (1 << SOUND_MIXER_VOLUME) +#define SOUND_MASK_BASS (1 << SOUND_MIXER_BASS) +#define SOUND_MASK_TREBLE (1 << SOUND_MIXER_TREBLE) +#define SOUND_MASK_SYNTH (1 << SOUND_MIXER_SYNTH) +#define SOUND_MASK_PCM (1 << SOUND_MIXER_PCM) +#define SOUND_MASK_SPEAKER (1 << SOUND_MIXER_SPEAKER) +#define SOUND_MASK_LINE (1 << SOUND_MIXER_LINE) +#define SOUND_MASK_MIC (1 << SOUND_MIXER_MIC) +#define SOUND_MASK_CD (1 << SOUND_MIXER_CD) +#define SOUND_MASK_IMIX (1 << SOUND_MIXER_IMIX) +#define SOUND_MASK_ALTPCM (1 << SOUND_MIXER_ALTPCM) +#define SOUND_MASK_RECLEV (1 << SOUND_MIXER_RECLEV) +#define SOUND_MASK_IGAIN (1 << SOUND_MIXER_IGAIN) +#define SOUND_MASK_OGAIN (1 << SOUND_MIXER_OGAIN) +#define SOUND_MASK_LINE1 (1 << SOUND_MIXER_LINE1) +#define SOUND_MASK_LINE2 (1 << SOUND_MIXER_LINE2) +#define SOUND_MASK_LINE3 (1 << SOUND_MIXER_LINE3) +#define SOUND_MASK_DIGITAL1 (1 << SOUND_MIXER_DIGITAL1) +#define SOUND_MASK_DIGITAL2 (1 << SOUND_MIXER_DIGITAL2) +#define SOUND_MASK_DIGITAL3 (1 << SOUND_MIXER_DIGITAL3) +#define SOUND_MASK_MONO (1 << SOUND_MIXER_MONO) +#define SOUND_MASK_PHONE (1 << SOUND_MIXER_PHONE) +#define SOUND_MASK_RADIO (1 << SOUND_MIXER_RADIO) +#define SOUND_MASK_VIDEO (1 << SOUND_MIXER_VIDEO) +#define SOUND_MASK_DEPTH (1 << SOUND_MIXER_DEPTH) +#define SOUND_MASK_REARVOL (1 << SOUND_MIXER_REARVOL) +#define SOUND_MASK_CENTERVOL (1 << SOUND_MIXER_CENTERVOL) +#define SOUND_MASK_SIDEVOL (1 << SOUND_MIXER_SIDEVOL) +#define SOUND_MASK_SURRVOL SOUND_MASK_SIDEVOL +#define SOUND_MASK_MUTE (1 << SOUND_MIXER_MUTE) +#define SOUND_MASK_ENHANCE (1 << SOUND_MIXER_ENHANCE) +#define SOUND_MASK_LOUD (1 << SOUND_MIXER_LOUD) /* * Again, DO NOT USE the following two macros. They are here for SOURCE * COMPATIBILITY ONLY. */ -#define SOUND_DEVICE_LABELS { \ - "Vol ", "Bass ", "Treble", "Synth", "Pcm ", "Speaker ", "Line ", \ - "Mic ", "CD ", "Mix ", "Pcm2 ", "Rec ", "IGain", "OGain", \ - "Aux1", "Aux2", "Aux3", "Digital1", "Digital2", "Digital3", \ - "Phone", "Mono", "Video", "Radio", "Depth", \ - "Rear", "Center", "Side" } +#define SOUND_DEVICE_LABELS { \ + "Vol ", "Bass ", "Treble", "Synth", "Pcm ", "Speaker ", "Line ", "Mic ", "CD ", "Mix ", "Pcm2 ", "Rec ", "IGain", "OGain", "Aux1", "Aux2", "Aux3", "Digital1", "Digital2", "Digital3", "Phone", "Mono", "Video", "Radio", "Depth", "Rear", "Center", "Side"} -#define SOUND_DEVICE_NAMES { \ - "vol", "bass", "treble", "synth", "pcm", "speaker", "line", \ - "mic", "cd", "mix", "pcm2", "rec", "igain", "ogain", \ - "aux1", "aux2", "aux3", "dig1", "dig2", "dig3", \ - "phone", "mono", "video", "radio", "depth", \ - "rear", "center", "side" } +#define SOUND_DEVICE_NAMES { \ + "vol", "bass", "treble", "synth", "pcm", "speaker", "line", "mic", "cd", "mix", "pcm2", "rec", "igain", "ogain", "aux1", "aux2", "aux3", "dig1", "dig2", "dig3", "phone", "mono", "video", "radio", "depth", "rear", "center", "side"} -#define MIXER_READ(dev) __OSSIOR('M', dev, int) -#define MIXER_WRITE(dev) __OSSIOWR('M', dev, int) -#define SOUND_MIXER_INFO __OSSIOR('M', 101, mixer_info) -#define OSS_GETVERSION __OSSIOR('M', 118, int) +#define MIXER_READ(dev) __OSSIOR('M', dev, int) +#define MIXER_WRITE(dev) __OSSIOWR('M', dev, int) +#define SOUND_MIXER_INFO __OSSIOR('M', 101, mixer_info) +#define OSS_GETVERSION __OSSIOR('M', 118, int) /* * These macros are useful for some applications. They are implemented * as soft values for the application, and do not affect real hardware. */ -#define SOUND_MIXER_READ_VOLUME MIXER_READ(SOUND_MIXER_VOLUME) -#define SOUND_MIXER_READ_OGAIN MIXER_READ(SOUND_MIXER_OGAIN) -#define SOUND_MIXER_READ_PCM MIXER_READ(SOUND_MIXER_PCM) -#define SOUND_MIXER_READ_IGAIN MIXER_READ(SOUND_MIXER_IGAIN) -#define SOUND_MIXER_READ_RECLEV MIXER_READ(SOUND_MIXER_RECLEV) -#define SOUND_MIXER_READ_RECSRC MIXER_READ(SOUND_MIXER_RECSRC) -#define SOUND_MIXER_READ_DEVMASK MIXER_READ(SOUND_MIXER_DEVMASK) -#define SOUND_MIXER_READ_RECMASK MIXER_READ(SOUND_MIXER_RECMASK) -#define SOUND_MIXER_READ_CAPS MIXER_READ(SOUND_MIXER_CAPS) -#define SOUND_MIXER_READ_STEREODEVS MIXER_READ(SOUND_MIXER_STEREODEVS) -#define SOUND_MIXER_READ_RECGAIN __OSSIOR('M', 119, int) -#define SOUND_MIXER_READ_MONGAIN __OSSIOR('M', 120, int) +#define SOUND_MIXER_READ_VOLUME MIXER_READ(SOUND_MIXER_VOLUME) +#define SOUND_MIXER_READ_OGAIN MIXER_READ(SOUND_MIXER_OGAIN) +#define SOUND_MIXER_READ_PCM MIXER_READ(SOUND_MIXER_PCM) +#define SOUND_MIXER_READ_IGAIN MIXER_READ(SOUND_MIXER_IGAIN) +#define SOUND_MIXER_READ_RECLEV MIXER_READ(SOUND_MIXER_RECLEV) +#define SOUND_MIXER_READ_RECSRC MIXER_READ(SOUND_MIXER_RECSRC) +#define SOUND_MIXER_READ_DEVMASK MIXER_READ(SOUND_MIXER_DEVMASK) +#define SOUND_MIXER_READ_RECMASK MIXER_READ(SOUND_MIXER_RECMASK) +#define SOUND_MIXER_READ_CAPS MIXER_READ(SOUND_MIXER_CAPS) +#define SOUND_MIXER_READ_STEREODEVS MIXER_READ(SOUND_MIXER_STEREODEVS) +#define SOUND_MIXER_READ_RECGAIN __OSSIOR('M', 119, int) +#define SOUND_MIXER_READ_MONGAIN __OSSIOR('M', 120, int) -#define SOUND_MIXER_WRITE_VOLUME MIXER_WRITE(SOUND_MIXER_VOLUME) -#define SOUND_MIXER_WRITE_OGAIN MIXER_WRITE(SOUND_MIXER_OGAIN) -#define SOUND_MIXER_WRITE_PCM MIXER_WRITE(SOUND_MIXER_PCM) -#define SOUND_MIXER_WRITE_IGAIN MIXER_WRITE(SOUND_MIXER_IGAIN) -#define SOUND_MIXER_WRITE_RECLEV MIXER_WRITE(SOUND_MIXER_RECLEV) -#define SOUND_MIXER_WRITE_RECSRC MIXER_WRITE(SOUND_MIXER_RECSRC) -#define SOUND_MIXER_WRITE_RECGAIN __OSSIOWR('M', 119, int) -#define SOUND_MIXER_WRITE_MONGAIN __OSSIOWR('M', 120, int) +#define SOUND_MIXER_WRITE_VOLUME MIXER_WRITE(SOUND_MIXER_VOLUME) +#define SOUND_MIXER_WRITE_OGAIN MIXER_WRITE(SOUND_MIXER_OGAIN) +#define SOUND_MIXER_WRITE_PCM MIXER_WRITE(SOUND_MIXER_PCM) +#define SOUND_MIXER_WRITE_IGAIN MIXER_WRITE(SOUND_MIXER_IGAIN) +#define SOUND_MIXER_WRITE_RECLEV MIXER_WRITE(SOUND_MIXER_RECLEV) +#define SOUND_MIXER_WRITE_RECSRC MIXER_WRITE(SOUND_MIXER_RECSRC) +#define SOUND_MIXER_WRITE_RECGAIN __OSSIOWR('M', 119, int) +#define SOUND_MIXER_WRITE_MONGAIN __OSSIOWR('M', 120, int) /* * These macros are here for source compatibility. They intentionally don't * map to any real hardware. NOT SUPPORTED! */ -#define SOUND_MIXER_READ_BASS MIXER_READ(SOUND_MIXER_BASS) -#define SOUND_MIXER_READ_TREBLE MIXER_READ(SOUND_MIXER_TREBLE) -#define SOUND_MIXER_READ_SYNTH MIXER_READ(SOUND_MIXER_SYNTH) -#define SOUND_MIXER_READ_SPEAKER MIXER_READ(SOUND_MIXER_SPEAKER) -#define SOUND_MIXER_READ_LINE MIXER_READ(SOUND_MIXER_LINE) -#define SOUND_MIXER_READ_MIC MIXER_READ(SOUND_MIXER_MIC) -#define SOUND_MIXER_READ_CD MIXER_READ(SOUND_MIXER_CD) -#define SOUND_MIXER_READ_IMIX MIXER_READ(SOUND_MIXER_IMIX) -#define SOUND_MIXER_READ_ALTPCM MIXER_READ(SOUND_MIXER_ALTPCM) -#define SOUND_MIXER_READ_LINE1 MIXER_READ(SOUND_MIXER_LINE1) -#define SOUND_MIXER_READ_LINE2 MIXER_READ(SOUND_MIXER_LINE2) -#define SOUND_MIXER_READ_LINE3 MIXER_READ(SOUND_MIXER_LINE3) +#define SOUND_MIXER_READ_BASS MIXER_READ(SOUND_MIXER_BASS) +#define SOUND_MIXER_READ_TREBLE MIXER_READ(SOUND_MIXER_TREBLE) +#define SOUND_MIXER_READ_SYNTH MIXER_READ(SOUND_MIXER_SYNTH) +#define SOUND_MIXER_READ_SPEAKER MIXER_READ(SOUND_MIXER_SPEAKER) +#define SOUND_MIXER_READ_LINE MIXER_READ(SOUND_MIXER_LINE) +#define SOUND_MIXER_READ_MIC MIXER_READ(SOUND_MIXER_MIC) +#define SOUND_MIXER_READ_CD MIXER_READ(SOUND_MIXER_CD) +#define SOUND_MIXER_READ_IMIX MIXER_READ(SOUND_MIXER_IMIX) +#define SOUND_MIXER_READ_ALTPCM MIXER_READ(SOUND_MIXER_ALTPCM) +#define SOUND_MIXER_READ_LINE1 MIXER_READ(SOUND_MIXER_LINE1) +#define SOUND_MIXER_READ_LINE2 MIXER_READ(SOUND_MIXER_LINE2) +#define SOUND_MIXER_READ_LINE3 MIXER_READ(SOUND_MIXER_LINE3) -#define SOUND_MIXER_WRITE_BASS MIXER_WRITE(SOUND_MIXER_BASS) -#define SOUND_MIXER_WRITE_TREBLE MIXER_WRITE(SOUND_MIXER_TREBLE) -#define SOUND_MIXER_WRITE_SYNTH MIXER_WRITE(SOUND_MIXER_SYNTH) -#define SOUND_MIXER_WRITE_SPEAKER MIXER_WRITE(SOUND_MIXER_SPEAKER) -#define SOUND_MIXER_WRITE_LINE MIXER_WRITE(SOUND_MIXER_LINE) -#define SOUND_MIXER_WRITE_MIC MIXER_WRITE(SOUND_MIXER_MIC) -#define SOUND_MIXER_WRITE_CD MIXER_WRITE(SOUND_MIXER_CD) -#define SOUND_MIXER_WRITE_IMIX MIXER_WRITE(SOUND_MIXER_IMIX) -#define SOUND_MIXER_WRITE_ALTPCM MIXER_WRITE(SOUND_MIXER_ALTPCM) -#define SOUND_MIXER_WRITE_LINE1 MIXER_WRITE(SOUND_MIXER_LINE1) -#define SOUND_MIXER_WRITE_LINE2 MIXER_WRITE(SOUND_MIXER_LINE2) -#define SOUND_MIXER_WRITE_LINE3 MIXER_WRITE(SOUND_MIXER_LINE3) +#define SOUND_MIXER_WRITE_BASS MIXER_WRITE(SOUND_MIXER_BASS) +#define SOUND_MIXER_WRITE_TREBLE MIXER_WRITE(SOUND_MIXER_TREBLE) +#define SOUND_MIXER_WRITE_SYNTH MIXER_WRITE(SOUND_MIXER_SYNTH) +#define SOUND_MIXER_WRITE_SPEAKER MIXER_WRITE(SOUND_MIXER_SPEAKER) +#define SOUND_MIXER_WRITE_LINE MIXER_WRITE(SOUND_MIXER_LINE) +#define SOUND_MIXER_WRITE_MIC MIXER_WRITE(SOUND_MIXER_MIC) +#define SOUND_MIXER_WRITE_CD MIXER_WRITE(SOUND_MIXER_CD) +#define SOUND_MIXER_WRITE_IMIX MIXER_WRITE(SOUND_MIXER_IMIX) +#define SOUND_MIXER_WRITE_ALTPCM MIXER_WRITE(SOUND_MIXER_ALTPCM) +#define SOUND_MIXER_WRITE_LINE1 MIXER_WRITE(SOUND_MIXER_LINE1) +#define SOUND_MIXER_WRITE_LINE2 MIXER_WRITE(SOUND_MIXER_LINE2) +#define SOUND_MIXER_WRITE_LINE3 MIXER_WRITE(SOUND_MIXER_LINE3) /* * Audio encoding types (Note! U8=8 and S16_LE=16 for compatibility) */ -#define AFMT_QUERY 0x00000000 /* Return current fmt */ -#define AFMT_MU_LAW 0x00000001 -#define AFMT_A_LAW 0x00000002 -#define AFMT_IMA_ADPCM 0x00000004 -#define AFMT_U8 0x00000008 -#define AFMT_S16_LE 0x00000010 -#define AFMT_S16_BE 0x00000020 -#define AFMT_S8 0x00000040 -#define AFMT_U16_LE 0x00000080 -#define AFMT_U16_BE 0x00000100 -#define AFMT_MPEG 0x00000200 /* NOT SUPPORTED: MPEG (2) audio */ -#define AFMT_AC3 0x00000400 /* NOT SUPPORTED: AC3 compressed */ -#define AFMT_VORBIS 0x00000800 /* NOT SUPPORTED: Ogg Vorbis */ -#define AFMT_S32_LE 0x00001000 -#define AFMT_S32_BE 0x00002000 -#define AFMT_FLOAT 0x00004000 /* NOT SUPPORTED: IEEE double float */ -#define AFMT_S24_LE 0x00008000 /* LSB aligned in 32 bit word */ -#define AFMT_S24_BE 0x00010000 /* LSB aligned in 32 bit word */ -#define AFMT_SPDIF_RAW 0x00020000 /* NOT SUPPORTED: Raw S/PDIF frames */ -#define AFMT_S24_PACKED 0x00040000 /* 24 bit packed little endian */ +#define AFMT_QUERY 0x00000000 /* Return current fmt */ +#define AFMT_MU_LAW 0x00000001 +#define AFMT_A_LAW 0x00000002 +#define AFMT_IMA_ADPCM 0x00000004 +#define AFMT_U8 0x00000008 +#define AFMT_S16_LE 0x00000010 +#define AFMT_S16_BE 0x00000020 +#define AFMT_S8 0x00000040 +#define AFMT_U16_LE 0x00000080 +#define AFMT_U16_BE 0x00000100 +#define AFMT_MPEG 0x00000200 /* NOT SUPPORTED: MPEG (2) audio */ +#define AFMT_AC3 0x00000400 /* NOT SUPPORTED: AC3 compressed */ +#define AFMT_VORBIS 0x00000800 /* NOT SUPPORTED: Ogg Vorbis */ +#define AFMT_S32_LE 0x00001000 +#define AFMT_S32_BE 0x00002000 +#define AFMT_FLOAT 0x00004000 /* NOT SUPPORTED: IEEE double float */ +#define AFMT_S24_LE 0x00008000 /* LSB aligned in 32 bit word */ +#define AFMT_S24_BE 0x00010000 /* LSB aligned in 32 bit word */ +#define AFMT_SPDIF_RAW 0x00020000 /* NOT SUPPORTED: Raw S/PDIF frames */ +#define AFMT_S24_PACKED 0x00040000 /* 24 bit packed little endian */ /* * Some big endian/little endian handling macros (native endian and * opposite endian formats). */ #if defined(_BIG_ENDIAN) -#define AFMT_S16_NE AFMT_S16_BE -#define AFMT_U16_NE AFMT_U16_BE -#define AFMT_S32_NE AFMT_S32_BE -#define AFMT_S24_NE AFMT_S24_BE -#define AFMT_S16_OE AFMT_S16_LE -#define AFMT_S32_OE AFMT_S32_LE -#define AFMT_S24_OE AFMT_S24_LE +# define AFMT_S16_NE AFMT_S16_BE +# define AFMT_U16_NE AFMT_U16_BE +# define AFMT_S32_NE AFMT_S32_BE +# define AFMT_S24_NE AFMT_S24_BE +# define AFMT_S16_OE AFMT_S16_LE +# define AFMT_S32_OE AFMT_S32_LE +# define AFMT_S24_OE AFMT_S24_LE #else -#define AFMT_S16_NE AFMT_S16_LE -#define AFMT_U16_NE AFMT_U16_LE -#define AFMT_S32_NE AFMT_S32_LE -#define AFMT_S24_NE AFMT_S24_LE -#define AFMT_S16_OE AFMT_S16_BE -#define AFMT_S32_OE AFMT_S32_BE -#define AFMT_S24_OE AFMT_S24_BE +# define AFMT_S16_NE AFMT_S16_LE +# define AFMT_U16_NE AFMT_U16_LE +# define AFMT_S32_NE AFMT_S32_LE +# define AFMT_S24_NE AFMT_S24_LE +# define AFMT_S16_OE AFMT_S16_BE +# define AFMT_S32_OE AFMT_S32_BE +# define AFMT_S24_OE AFMT_S24_BE #endif /* * SNDCTL_DSP_GETCAPS bits */ -#define PCM_CAP_REVISION 0x000000ff /* Revision level (0 to 255) */ -#define PCM_CAP_DUPLEX 0x00000100 /* Full duplex rec/play */ -#define PCM_CAP_REALTIME 0x00000200 /* NOT SUPPORTED */ -#define PCM_CAP_BATCH 0x00000400 /* NOT SUPPORTED */ -#define PCM_CAP_COPROC 0x00000800 /* NOT SUPPORTED */ -#define PCM_CAP_TRIGGER 0x00001000 /* Supports SETTRIGGER */ -#define PCM_CAP_MMAP 0x00002000 /* Supports mmap() */ -#define PCM_CAP_MULTI 0x00004000 /* Supports multiple open */ -#define PCM_CAP_BIND 0x00008000 /* Supports channel binding */ -#define PCM_CAP_INPUT 0x00010000 /* Supports recording */ -#define PCM_CAP_OUTPUT 0x00020000 /* Supports playback */ -#define PCM_CAP_VIRTUAL 0x00040000 /* Virtual device */ -#define PCM_CAP_ANALOGOUT 0x00100000 /* NOT SUPPORTED */ -#define PCM_CAP_ANALOGIN 0x00200000 /* NOT SUPPORTED */ -#define PCM_CAP_DIGITALOUT 0x00400000 /* NOT SUPPORTED */ -#define PCM_CAP_DIGITALIN 0x00800000 /* NOT SUPPORTED */ -#define PCM_CAP_ADMASK 0x00f00000 /* NOT SUPPORTED */ -#define PCM_CAP_SHADOW 0x01000000 /* "Shadow" device */ -#define PCM_CAP_CH_MASK 0x06000000 /* See DSP_CH_MASK below */ -#define PCM_CAP_HIDDEN 0x08000000 /* NOT SUPPORTED */ -#define PCM_CAP_FREERATE 0x10000000 -#define PCM_CAP_MODEM 0x20000000 /* NOT SUPPORTED */ -#define PCM_CAP_DEFAULT 0x40000000 /* "Default" device */ +#define PCM_CAP_REVISION 0x000000ff /* Revision level (0 to 255) */ +#define PCM_CAP_DUPLEX 0x00000100 /* Full duplex rec/play */ +#define PCM_CAP_REALTIME 0x00000200 /* NOT SUPPORTED */ +#define PCM_CAP_BATCH 0x00000400 /* NOT SUPPORTED */ +#define PCM_CAP_COPROC 0x00000800 /* NOT SUPPORTED */ +#define PCM_CAP_TRIGGER 0x00001000 /* Supports SETTRIGGER */ +#define PCM_CAP_MMAP 0x00002000 /* Supports mmap() */ +#define PCM_CAP_MULTI 0x00004000 /* Supports multiple open */ +#define PCM_CAP_BIND 0x00008000 /* Supports channel binding */ +#define PCM_CAP_INPUT 0x00010000 /* Supports recording */ +#define PCM_CAP_OUTPUT 0x00020000 /* Supports playback */ +#define PCM_CAP_VIRTUAL 0x00040000 /* Virtual device */ +#define PCM_CAP_ANALOGOUT 0x00100000 /* NOT SUPPORTED */ +#define PCM_CAP_ANALOGIN 0x00200000 /* NOT SUPPORTED */ +#define PCM_CAP_DIGITALOUT 0x00400000 /* NOT SUPPORTED */ +#define PCM_CAP_DIGITALIN 0x00800000 /* NOT SUPPORTED */ +#define PCM_CAP_ADMASK 0x00f00000 /* NOT SUPPORTED */ +#define PCM_CAP_SHADOW 0x01000000 /* "Shadow" device */ +#define PCM_CAP_CH_MASK 0x06000000 /* See DSP_CH_MASK below */ +#define PCM_CAP_HIDDEN 0x08000000 /* NOT SUPPORTED */ +#define PCM_CAP_FREERATE 0x10000000 +#define PCM_CAP_MODEM 0x20000000 /* NOT SUPPORTED */ +#define PCM_CAP_DEFAULT 0x40000000 /* "Default" device */ /* * Preferred channel usage. These bits can be used to give @@ -832,67 +820,66 @@ typedef unsigned short oss_peaks_t[MAX_PEAK_CHANNELS]; * To find out which modes are actually supported the application * should try to select them using SNDCTL_DSP_CHANNELS. */ -#define DSP_CH_MASK 0x06000000 /* Mask */ -#define DSP_CH_ANY 0x00000000 /* No preferred mode */ -#define DSP_CH_MONO 0x02000000 -#define DSP_CH_STEREO 0x04000000 -#define DSP_CH_MULTI 0x06000000 /* More than two channels */ - +#define DSP_CH_MASK 0x06000000 /* Mask */ +#define DSP_CH_ANY 0x00000000 /* No preferred mode */ +#define DSP_CH_MONO 0x02000000 +#define DSP_CH_STEREO 0x04000000 +#define DSP_CH_MULTI 0x06000000 /* More than two channels */ /* * The PCM_CAP_* capability names used to be known as DSP_CAP_*, so * it's necessary to define the older names too. */ -#define DSP_CAP_ADMASK PCM_CAP_ADMASK -#define DSP_CAP_ANALOGIN PCM_CAP_ANALOGIN -#define DSP_CAP_ANALOGOUT PCM_CAP_ANALOGOUT -#define DSP_CAP_BATCH PCM_CAP_BATCH -#define DSP_CAP_BIND PCM_CAP_BIND -#define DSP_CAP_COPROC PCM_CAP_COPROC -#define DSP_CAP_DEFAULT PCM_CAP_DEFAULT -#define DSP_CAP_DIGITALIN PCM_CAP_DIGITALIN -#define DSP_CAP_DIGITALOUT PCM_CAP_DIGITALOUT -#define DSP_CAP_DUPLEX PCM_CAP_DUPLEX -#define DSP_CAP_FREERATE PCM_CAP_FREERATE -#define DSP_CAP_HIDDEN PCM_CAP_HIDDEN -#define DSP_CAP_INPUT PCM_CAP_INPUT -#define DSP_CAP_MMAP PCM_CAP_MMAP -#define DSP_CAP_MODEM PCM_CAP_MODEM -#define DSP_CAP_MULTI PCM_CAP_MULTI -#define DSP_CAP_OUTPUT PCM_CAP_OUTPUT -#define DSP_CAP_REALTIME PCM_CAP_REALTIME -#define DSP_CAP_REVISION PCM_CAP_REVISION -#define DSP_CAP_SHADOW PCM_CAP_SHADOW -#define DSP_CAP_TRIGGER PCM_CAP_TRIGGER -#define DSP_CAP_VIRTUAL PCM_CAP_VIRTUAL +#define DSP_CAP_ADMASK PCM_CAP_ADMASK +#define DSP_CAP_ANALOGIN PCM_CAP_ANALOGIN +#define DSP_CAP_ANALOGOUT PCM_CAP_ANALOGOUT +#define DSP_CAP_BATCH PCM_CAP_BATCH +#define DSP_CAP_BIND PCM_CAP_BIND +#define DSP_CAP_COPROC PCM_CAP_COPROC +#define DSP_CAP_DEFAULT PCM_CAP_DEFAULT +#define DSP_CAP_DIGITALIN PCM_CAP_DIGITALIN +#define DSP_CAP_DIGITALOUT PCM_CAP_DIGITALOUT +#define DSP_CAP_DUPLEX PCM_CAP_DUPLEX +#define DSP_CAP_FREERATE PCM_CAP_FREERATE +#define DSP_CAP_HIDDEN PCM_CAP_HIDDEN +#define DSP_CAP_INPUT PCM_CAP_INPUT +#define DSP_CAP_MMAP PCM_CAP_MMAP +#define DSP_CAP_MODEM PCM_CAP_MODEM +#define DSP_CAP_MULTI PCM_CAP_MULTI +#define DSP_CAP_OUTPUT PCM_CAP_OUTPUT +#define DSP_CAP_REALTIME PCM_CAP_REALTIME +#define DSP_CAP_REVISION PCM_CAP_REVISION +#define DSP_CAP_SHADOW PCM_CAP_SHADOW +#define DSP_CAP_TRIGGER PCM_CAP_TRIGGER +#define DSP_CAP_VIRTUAL PCM_CAP_VIRTUAL /* * SNDCTL_DSP_GETTRIGGER and SNDCTL_DSP_SETTRIGGER */ -#define PCM_ENABLE_INPUT 0x00000001 -#define PCM_ENABLE_OUTPUT 0x00000002 +#define PCM_ENABLE_INPUT 0x00000001 +#define PCM_ENABLE_OUTPUT 0x00000002 /* * SNDCTL_DSP_BIND_CHANNEL */ -#define DSP_BIND_QUERY 0x00000000 -#define DSP_BIND_FRONT 0x00000001 -#define DSP_BIND_SURR 0x00000002 -#define DSP_BIND_CENTER_LFE 0x00000004 -#define DSP_BIND_HANDSET 0x00000008 -#define DSP_BIND_MIC 0x00000010 -#define DSP_BIND_MODEM1 0x00000020 -#define DSP_BIND_MODEM2 0x00000040 -#define DSP_BIND_I2S 0x00000080 -#define DSP_BIND_SPDIF 0x00000100 -#define DSP_BIND_REAR 0x00000200 +#define DSP_BIND_QUERY 0x00000000 +#define DSP_BIND_FRONT 0x00000001 +#define DSP_BIND_SURR 0x00000002 +#define DSP_BIND_CENTER_LFE 0x00000004 +#define DSP_BIND_HANDSET 0x00000008 +#define DSP_BIND_MIC 0x00000010 +#define DSP_BIND_MODEM1 0x00000020 +#define DSP_BIND_MODEM2 0x00000040 +#define DSP_BIND_I2S 0x00000080 +#define DSP_BIND_SPDIF 0x00000100 +#define DSP_BIND_REAR 0x00000200 /* * SOUND_MIXER_READ_CAPS */ -#define SOUND_CAP_EXCL_INPUT 0x00000001 -#define SOUND_CAP_NOLEGACY 0x00000004 -#define SOUND_CAP_NORECSRC 0x00000008 +#define SOUND_CAP_EXCL_INPUT 0x00000001 +#define SOUND_CAP_NOLEGACY 0x00000004 +#define SOUND_CAP_NORECSRC 0x00000008 /* * The following ioctl is for internal use only -- it is used to @@ -900,7 +887,7 @@ typedef unsigned short oss_peaks_t[MAX_PEAK_CHANNELS]; * Applications must not use it. (This is duplicated in sys/audioio.h * as well.) */ -#define SNDCTL_SUN_SEND_NUMBER __OSSIOW('X', 200, int) +#define SNDCTL_SUN_SEND_NUMBER __OSSIOW('X', 200, int) #ifdef __cplusplus } diff --git a/src/detection/sound/sound.h b/src/detection/sound/sound.h index fb8d05f7e..16344f215 100644 --- a/src/detection/sound/sound.h +++ b/src/detection/sound/sound.h @@ -4,8 +4,7 @@ #define FF_SOUND_VOLUME_UNKNOWN 255 -typedef struct FFSoundDevice -{ +typedef struct FFSoundDevice { FFstrbuf identifier; FFstrbuf name; FFstrbuf platformApi; diff --git a/src/detection/sound/sound_apple.c b/src/detection/sound/sound_apple.c index 7f800b372..c2be7f2dc 100644 --- a/src/detection/sound/sound_apple.c +++ b/src/detection/sound/sound_apple.c @@ -5,57 +5,40 @@ #include #ifndef MAC_OS_VERSION_12_0 -#define kAudioObjectPropertyElementMain kAudioObjectPropertyElementMaster +# define kAudioObjectPropertyElementMain kAudioObjectPropertyElementMaster #endif -const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) -{ +const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) { AudioDeviceID mainDeviceId; UInt32 dataSize = sizeof(mainDeviceId); - if(AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress){ - kAudioHardwarePropertyDefaultOutputDevice, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &mainDeviceId) != kAudioHardwareNoError) + if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress) {kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &mainDeviceId) != kAudioHardwareNoError) { return "AudioObjectGetPropertyData(kAudioHardwarePropertyDefaultOutputDevice) failed"; + } AudioObjectID deviceIds[32] = {}; dataSize = sizeof(deviceIds); - if(AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress){ - kAudioHardwarePropertyDevices, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &deviceIds) != kAudioHardwareNoError) + if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress) {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &deviceIds) != kAudioHardwareNoError) { return "AudioObjectGetPropertyData(kAudioHardwarePropertyDevices) failed"; + } - for(uint32_t index = 0, length = dataSize / sizeof(*deviceIds); index < length; ++index) - { + for (uint32_t index = 0, length = dataSize / sizeof(*deviceIds); index < length; ++index) { AudioDeviceID deviceId = deviceIds[index]; // Ignore input devices - if(AudioObjectGetPropertyDataSize(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyStreams, - kAudioObjectPropertyScopeInput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize) == kAudioHardwareNoError && dataSize > 0) + if (AudioObjectGetPropertyDataSize(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyStreams, kAudioObjectPropertyScopeInput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize) == kAudioHardwareNoError && dataSize > 0) { continue; + } uint32_t dataSource; dataSize = sizeof(dataSource); - if(AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyDataSource, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &dataSource) == kAudioHardwareNoError && dataSource == 'hdpn') - { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyDataSource, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &dataSource) == kAudioHardwareNoError && dataSource == 'hdpn') { uint32_t connected; dataSize = sizeof(connected); - if(AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyJackIsConnected, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &connected) == kAudioHardwareNoError) - if (!connected) continue; + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyJackIsConnected, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &connected) == kAudioHardwareNoError) { + if (!connected) { + continue; + } + } } FFSoundDevice* device = (FFSoundDevice*) ffListAdd(devices); @@ -68,81 +51,50 @@ const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) FF_CFTYPE_AUTO_RELEASE CFStringRef uid = NULL; dataSize = sizeof(uid); - if(AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { - kAudioDevicePropertyDeviceUID, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &uid) == kAudioHardwareNoError) + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyDeviceUID, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &uid) == kAudioHardwareNoError) { ffCfStrGetString(uid, &device->identifier); - else + } else { ffStrbufAppendF(&device->identifier, "ID-%u", (unsigned) deviceId); + } FF_CFTYPE_AUTO_RELEASE CFStringRef name = NULL; dataSize = sizeof(name); - if(AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioObjectPropertyName, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &name) == kAudioHardwareNoError) + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioObjectPropertyName, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &name) == kAudioHardwareNoError) { ffCfStrGetString(name, &device->name); - else + } else { ffStrbufSet(&device->name, &device->identifier); + } uint32_t muted; dataSize = sizeof(muted); - if(AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyMute, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &muted) != kAudioHardwareNoError) + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyMute, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &muted) != kAudioHardwareNoError) { muted = false; // Device may not support volume control + } uint32_t active; dataSize = sizeof(active); - if(AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyDeviceIsAlive, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &active) == kAudioHardwareNoError) + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &active) == kAudioHardwareNoError) { device->active = !!active; + } - if (muted) + if (muted) { device->volume = 0; - else - { + } else { float volume; dataSize = sizeof(volume); - if(AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyVolumeScalar, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, &volume) == kAudioHardwareNoError) + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, &volume) == kAudioHardwareNoError) { device->volume = (uint8_t) (volume * 100 + 0.5); - else - { + } else { // Try detecting volume from channels uint32_t channels[2]; dataSize = sizeof(channels); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyPreferredChannelsForStereo, - kAudioObjectPropertyScopeOutput, - kAudioObjectPropertyElementMain - }, 0, NULL, &dataSize, channels) == kAudioHardwareNoError) - { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyPreferredChannelsForStereo, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain}, 0, NULL, &dataSize, channels) == kAudioHardwareNoError) { dataSize = sizeof(volume); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyVolumeScalar, - kAudioObjectPropertyScopeOutput, - channels[0] - }, 0, NULL, &dataSize, &volume) == kAudioHardwareNoError) - { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, channels[0]}, 0, NULL, &dataSize, &volume) == kAudioHardwareNoError) { float temp; - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress){ - kAudioDevicePropertyVolumeScalar, - kAudioObjectPropertyScopeOutput, - channels[1] - }, 0, NULL, &dataSize, &temp) == kAudioHardwareNoError) + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) {kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, channels[1]}, 0, NULL, &dataSize, &temp) == kAudioHardwareNoError) { device->volume = (uint8_t) ((volume + temp) / 2 * 100 + 0.5); + } } } } diff --git a/src/detection/sound/sound_bsd.c b/src/detection/sound/sound_bsd.c index 68404fa85..e6716ed4b 100644 --- a/src/detection/sound/sound_bsd.c +++ b/src/detection/sound/sound_bsd.c @@ -6,60 +6,67 @@ #include #include -const char* ffDetectSound(FFlist* devices) -{ - #ifndef __NetBSD__ +const char* ffDetectSound(FFlist* devices) { +#ifndef __NetBSD__ int defaultDev = ffSysctlGetInt("hw.snd.default_unit", -1); - if (defaultDev == -1) + if (defaultDev == -1) { return "sysctl(hw.snd.default_unit) failed"; - #else + } +#else int defaultDev; { char mixerp[12]; ssize_t plen = readlink("/dev/mixer", mixerp, ARRAY_SIZE(mixerp)); - if (plen < 6) + if (plen < 6) { return "readlink(/dev/mixer) failed"; + } defaultDev = mixerp[plen - 1] - '0'; - if (defaultDev < 0 || defaultDev > 9) + if (defaultDev < 0 || defaultDev > 9) { return "Invalid mixer device"; + } } - #endif +#endif char path[] = "/dev/mixer0"; - struct oss_sysinfo info = { .nummixers = 9 }; + struct oss_sysinfo info = {.nummixers = 9}; - for (int idev = 0; idev <= info.nummixers; ++idev) - { + for (int idev = 0; idev <= info.nummixers; ++idev) { path[strlen("/dev/mixer")] = (char) ('0' + idev); FF_AUTO_CLOSE_FD int fd = open(path, O_RDWR | O_CLOEXEC); - if (fd < 0) break; + if (fd < 0) { + break; + } - if (idev == 0) - { - if (ioctl(fd, SNDCTL_SYSINFO, &info) != 0) + if (idev == 0) { + if (ioctl(fd, SNDCTL_SYSINFO, &info) != 0) { return "ioctl(SNDCTL_SYSINFO) failed"; + } } uint32_t devmask = 0; - if (ioctl(fd, SOUND_MIXER_READ_DEVMASK, &devmask) < 0) + if (ioctl(fd, SOUND_MIXER_READ_DEVMASK, &devmask) < 0) { continue; - if (!(devmask & SOUND_MASK_VOLUME)) + } + if (!(devmask & SOUND_MASK_VOLUME)) { continue; + } - #if defined(SOUND_MIXER_MUTE) && (SOUND_MIXER_MUTE != SOUND_MIXER_NONE) - #define FF_SOUND_HAVE_MIXER_MUTE 1 +#if defined(SOUND_MIXER_MUTE) && (SOUND_MIXER_MUTE != SOUND_MIXER_NONE) +# define FF_SOUND_HAVE_MIXER_MUTE 1 uint32_t mutemask = 0; ioctl(fd, SOUND_MIXER_READ_MUTE, &mutemask); - #endif +#endif - struct oss_card_info ci = { .card = idev }; - if (ioctl(fd, SNDCTL_CARDINFO, &ci) < 0) + struct oss_card_info ci = {.card = idev}; + if (ioctl(fd, SNDCTL_CARDINFO, &ci) < 0) { continue; + } uint32_t volume; - if (ioctl(fd, SOUND_MIXER_READ_VOLUME, &volume) < 0) + if (ioctl(fd, SOUND_MIXER_READ_VOLUME, &volume) < 0) { continue; + } FFSoundDevice* device = ffListAdd(devices); ffStrbufInitS(&device->identifier, path); @@ -67,10 +74,10 @@ const char* ffDetectSound(FFlist* devices) ffStrbufTrimRightSpace(&device->name); ffStrbufInitF(&device->platformApi, "%s %s", info.product, info.version); device->volume = - #ifdef FF_SOUND_HAVE_MIXER_MUTE +#ifdef FF_SOUND_HAVE_MIXER_MUTE mutemask & SOUND_MASK_VOLUME ? 0 : - #endif - ((uint8_t) volume /*left*/ + (uint8_t) (volume >> 8) /*right*/) / 2; +#endif + ((uint8_t) volume /*left*/ + (uint8_t) (volume >> 8) /*right*/) / 2; device->active = true; device->main = defaultDev == idev; } diff --git a/src/detection/sound/sound_haiku.cpp b/src/detection/sound/sound_haiku.cpp index 9471909e2..8dc8ef8eb 100644 --- a/src/detection/sound/sound_haiku.cpp +++ b/src/detection/sound/sound_haiku.cpp @@ -1,5 +1,4 @@ -extern "C" -{ +extern "C" { #include "sound.h" #include "common/stringUtils.h" } @@ -8,23 +7,23 @@ extern "C" #include #include -const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) -{ +const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) { BMediaRoster* roster = BMediaRoster::Roster(); media_node mediaNode; live_node_info liveInfo; dormant_node_info dormantInfo; - if (roster->GetAudioOutput(&mediaNode) != B_OK) + if (roster->GetAudioOutput(&mediaNode) != B_OK) { return NULL; + } - FFSoundDevice* device = (FFSoundDevice*)ffListAdd(devices); + FFSoundDevice* device = (FFSoundDevice*) ffListAdd(devices); ffStrbufInit(&device->identifier); - if (roster->GetDormantNodeFor(mediaNode, &dormantInfo) == B_OK) + if (roster->GetDormantNodeFor(mediaNode, &dormantInfo) == B_OK) { ffStrbufAppendS(&device->identifier, dormantInfo.name); + } ffStrbufInit(&device->name); - if (roster->GetLiveNodeInfo(mediaNode, &liveInfo) == B_OK) - { + if (roster->GetLiveNodeInfo(mediaNode, &liveInfo) == B_OK) { ffStrbufAppendS(&device->name, liveInfo.name); ffStrbufTrimRightSpace(&device->name); } @@ -37,51 +36,54 @@ const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) roster->ReleaseNode(mediaNode); media_node mixer; - if (roster->GetAudioMixer(&mixer) != B_OK) + if (roster->GetAudioMixer(&mixer) != B_OK) { return NULL; + } - BParameterWeb *web; + BParameterWeb* web; status_t status = roster->GetParameterWebFor(mixer, &web); roster->ReleaseNode(mixer); // the web is all we need :-) - if (status != B_OK) + if (status != B_OK) { return NULL; + } - BContinuousParameter *gain = NULL; - BParameter *mute = NULL; - BParameter *parameter; - for (int32 index = 0; (parameter = web->ParameterAt(index)) != NULL; index++) - { + BContinuousParameter* gain = NULL; + BParameter* mute = NULL; + BParameter* parameter; + for (int32 index = 0; (parameter = web->ParameterAt(index)) != NULL; index++) { // assume the mute preceding master gain control - if (ffStrEquals(parameter->Kind(), B_MUTE)) + if (ffStrEquals(parameter->Kind(), B_MUTE)) { mute = parameter; + } - if (ffStrEquals(parameter->Kind(), B_MASTER_GAIN)) - { + if (ffStrEquals(parameter->Kind(), B_MASTER_GAIN)) { // Can not use dynamic_cast due to fno-rtti - //gain = dynamic_cast(parameter); - gain = (BContinuousParameter *)(parameter); + // gain = dynamic_cast(parameter); + gain = (BContinuousParameter*) (parameter); break; } } - if (gain == NULL) + if (gain == NULL) { return NULL; + } bigtime_t when; size_t size; - if (mute) - { + if (mute) { int32 isMute = false; size = sizeof(isMute); - if (mute->GetValue(&isMute, &size, &when) == B_OK && isMute) + if (mute->GetValue(&isMute, &size, &when) == B_OK && isMute) { return NULL; + } } float volume = 0.0; size = sizeof(volume); - if (gain->GetValue(&volume, &size, &when) == B_OK) + if (gain->GetValue(&volume, &size, &when) == B_OK) { device->volume = (uint8_t) (100 * (volume - gain->MinValue()) / (gain->MaxValue() - gain->MinValue())); + } return NULL; } diff --git a/src/detection/sound/sound_linux.c b/src/detection/sound/sound_linux.c index ace1d0b08..73cfe29c4 100644 --- a/src/detection/sound/sound_linux.c +++ b/src/detection/sound/sound_linux.c @@ -1,15 +1,15 @@ #include "sound.h" #ifdef FF_HAVE_PULSE -#include "common/library.h" -#include +# include "common/library.h" +# include -static void paSinkInfoCallback(pa_context *c, const pa_sink_info *i, int eol, void *userdata) -{ +static void paSinkInfoCallback(pa_context* c, const pa_sink_info* i, int eol, void* userdata) { FF_UNUSED(c); - if(eol > 0 || !i) + if (eol > 0 || !i) { return; + } FFSoundDevice* device = ffListAdd(userdata); ffStrbufInitS(&device->identifier, i->name); @@ -23,29 +23,27 @@ static void paSinkInfoCallback(pa_context *c, const pa_sink_info *i, int eol, vo device->main = false; } -static void paServerInfoCallback(FF_MAYBE_UNUSED pa_context *c, const pa_server_info *i, void *userdata) -{ - if(!i) return; +static void paServerInfoCallback(FF_MAYBE_UNUSED pa_context* c, const pa_server_info* i, void* userdata) { + if (!i) { + return; + } FF_STRBUF_AUTO_DESTROY api = ffStrbufCreate(); const char* realServer = strstr(i->server_name, "(on "); - if (realServer) - { + if (realServer) { ffStrbufSetS(&api, realServer + strlen("(on ")); ffStrbufTrimRight(&api, ')'); - } - else + } else { ffStrbufSetF(&api, "%s %s", i->server_name, i->server_version); + } - FF_LIST_FOR_EACH(FFSoundDevice, device, *(FFlist*)userdata) - { + FF_LIST_FOR_EACH (FFSoundDevice, device, *(FFlist*) userdata) { device->main = ffStrbufEqualS(&device->identifier, i->default_sink_name); ffStrbufSet(&device->platformApi, &api); } } -static const char* detectSound(FFlist* devices) -{ +static const char* detectSound(FFlist* devices) { FF_LIBRARY_LOAD_MESSAGE(pulse, "libpulse" FF_LIBRARY_EXTENSION, 0) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(pulse, pa_mainloop_new) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(pulse, pa_mainloop_get_api) @@ -61,35 +59,31 @@ static const char* detectSound(FFlist* devices) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(pulse, pa_operation_unref) pa_mainloop* mainloop = ffpa_mainloop_new(); - if(!mainloop) + if (!mainloop) { return "Failed to create pulseaudio mainloop"; + } pa_mainloop_api* mainloopApi = ffpa_mainloop_get_api(mainloop); - if(!mainloopApi) - { + if (!mainloopApi) { ffpa_mainloop_free(mainloop); return "Failed to get pulseaudio mainloop api"; } pa_context* context = ffpa_context_new(mainloopApi, "fastfetch"); - if(!context) - { + if (!context) { ffpa_mainloop_free(mainloop); return "Failed to create pulseaudio context"; } - if(ffpa_context_connect(context, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0) - { + if (ffpa_context_connect(context, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0) { ffpa_context_unref(context); ffpa_mainloop_free(mainloop); return "Failed to connect to pulseaudio context"; } pa_context_state_t state; - while((state = ffpa_context_get_state(context)) != PA_CONTEXT_READY) - { - if(!PA_CONTEXT_IS_GOOD(state)) - { + while ((state = ffpa_context_get_state(context)) != PA_CONTEXT_READY) { + if (!PA_CONTEXT_IS_GOOD(state)) { ffpa_context_unref(context); ffpa_mainloop_free(mainloop); return "Failed to get pulseaudio context state"; @@ -99,23 +93,23 @@ static const char* detectSound(FFlist* devices) } pa_operation* operation = ffpa_context_get_sink_info_list(context, paSinkInfoCallback, devices); - if(!operation) - { + if (!operation) { ffpa_context_unref(context); ffpa_mainloop_free(mainloop); return "Failed to get pulseaudio sink info list"; } - while(ffpa_operation_get_state(operation) == PA_OPERATION_RUNNING) + while (ffpa_operation_get_state(operation) == PA_OPERATION_RUNNING) { ffpa_mainloop_iterate(mainloop, 1, NULL); + } ffpa_operation_unref(operation); operation = ffpa_context_get_server_info(context, paServerInfoCallback, devices); - if(operation) - { - while(ffpa_operation_get_state(operation) == PA_OPERATION_RUNNING) + if (operation) { + while (ffpa_operation_get_state(operation) == PA_OPERATION_RUNNING) { ffpa_mainloop_iterate(mainloop, 1, NULL); + } ffpa_operation_unref(operation); } @@ -127,12 +121,11 @@ static const char* detectSound(FFlist* devices) #endif // FF_HAVE_PULSE -const char* ffDetectSound(FFlist* devices) -{ - #ifdef FF_HAVE_PULSE - return detectSound(devices); - #else - FF_UNUSED(devices); - return "Fastfetch was built without libpulse support"; - #endif +const char* ffDetectSound(FFlist* devices) { +#ifdef FF_HAVE_PULSE + return detectSound(devices); +#else + FF_UNUSED(devices); + return "Fastfetch was built without libpulse support"; +#endif } diff --git a/src/detection/sound/sound_nbsd.c b/src/detection/sound/sound_nbsd.c index 396ce4b66..a65aa82f7 100644 --- a/src/detection/sound/sound_nbsd.c +++ b/src/detection/sound/sound_nbsd.c @@ -7,34 +7,38 @@ #include #include -const char* ffDetectSound(FFlist* devices) -{ +const char* ffDetectSound(FFlist* devices) { int defaultDev; { char audiop[12]; ssize_t plen = readlink("/dev/audio", audiop, ARRAY_SIZE(audiop)); - if (plen < (ssize_t) strlen("audioN")) + if (plen < (ssize_t) strlen("audioN")) { return "readlink(/dev/audio) failed"; + } defaultDev = audiop[plen - 1] - '0'; - if (defaultDev < 0 || defaultDev > 9) + if (defaultDev < 0 || defaultDev > 9) { return "Invalid audio device"; + } } char path[] = "/dev/audio0"; - for (int idev = 0; idev < 9; ++idev) - { + for (int idev = 0; idev < 9; ++idev) { path[strlen("/dev/audio")] = (char) ('0' + idev); FF_AUTO_CLOSE_FD int fd = open(path, O_RDWR | O_CLOEXEC); - if (fd < 0) break; + if (fd < 0) { + break; + } audio_device_t ad; - if (ioctl(fd, AUDIO_GETDEV, &ad) < 0) + if (ioctl(fd, AUDIO_GETDEV, &ad) < 0) { continue; + } audio_info_t ai; - if (ioctl(fd, AUDIO_GETINFO, &ai) < 0) + if (ioctl(fd, AUDIO_GETINFO, &ai) < 0) { continue; + } FFSoundDevice* device = ffListAdd(devices); ffStrbufInitS(&device->identifier, path); diff --git a/src/detection/sound/sound_nosupport.c b/src/detection/sound/sound_nosupport.c index 7b23b2fa4..c48b66531 100644 --- a/src/detection/sound/sound_nosupport.c +++ b/src/detection/sound/sound_nosupport.c @@ -1,6 +1,5 @@ #include "sound.h" -const char* ffDetectSound(FF_MAYBE_UNUSED FFlist* devices /* List of FFSoundDevice */) -{ +const char* ffDetectSound(FF_MAYBE_UNUSED FFlist* devices /* List of FFSoundDevice */) { return "Not supported on this platform"; } diff --git a/src/detection/sound/sound_obsd.c b/src/detection/sound/sound_obsd.c index 7e7554f5d..653faee07 100644 --- a/src/detection/sound/sound_obsd.c +++ b/src/detection/sound/sound_obsd.c @@ -4,16 +4,16 @@ #include #include -static void close_hdl(struct sioctl_hdl** phdl) -{ +static void close_hdl(struct sioctl_hdl** phdl) { assert(phdl); - if (*phdl) sioctl_close(*phdl); + if (*phdl) { + sioctl_close(*phdl); + } } enum { MAX_CHANNEL_NUM = 8 }; -typedef struct FFSoundDeviceBundle -{ +typedef struct FFSoundDeviceBundle { char name[SIOCTL_DISPLAYMAX]; double level[MAX_CHANNEL_NUM]; uint8_t iLevel; @@ -21,50 +21,55 @@ typedef struct FFSoundDeviceBundle uint8_t iMute; } FFSoundDeviceBundle; -static void enumerate_props(FFSoundDeviceBundle* bundle, struct sioctl_desc* desc, int val) -{ - if (!desc) return; - - if (desc->type == SIOCTL_SEL) - { - if (desc->display[0] != '\0' && ffStrEquals(desc->node0.name, "server")) - ffStrCopy(bundle->name, desc->display, SIOCTL_DISPLAYMAX); +static void enumerate_props(FFSoundDeviceBundle* bundle, struct sioctl_desc* desc, int val) { + if (!desc) { return; } - if (desc->type != SIOCTL_NUM && desc->type != SIOCTL_SW) + if (desc->type == SIOCTL_SEL) { + if (desc->display[0] != '\0' && ffStrEquals(desc->node0.name, "server")) { + ffStrCopy(bundle->name, desc->display, SIOCTL_DISPLAYMAX); + } return; + } - if (!ffStrEquals(desc->node0.name, "output")) + if (desc->type != SIOCTL_NUM && desc->type != SIOCTL_SW) { return; + } - if (ffStrEquals(desc->func, "level")) - { - if (__builtin_expect(bundle->iLevel == MAX_CHANNEL_NUM, false)) + if (!ffStrEquals(desc->node0.name, "output")) { + return; + } + + if (ffStrEquals(desc->func, "level")) { + if (__builtin_expect(bundle->iLevel == MAX_CHANNEL_NUM, false)) { return; + } bundle->level[bundle->iLevel] = (double) val / (double) desc->maxval; ++bundle->iLevel; - } - else if (ffStrEquals(desc->func, "mute")) - { - if (__builtin_expect(bundle->iMute == MAX_CHANNEL_NUM, false)) + } else if (ffStrEquals(desc->func, "mute")) { + if (__builtin_expect(bundle->iMute == MAX_CHANNEL_NUM, false)) { return; + } bundle->mute[bundle->iMute] = !!val; ++bundle->iMute; } } -const char* ffDetectSound(FFlist* devices) -{ +const char* ffDetectSound(FFlist* devices) { __attribute__((__cleanup__(close_hdl))) struct sioctl_hdl* hdl = sioctl_open(SIO_DEVANY, SIOCTL_READ, 0); - if (!hdl) return "sio_open() failed"; + if (!hdl) { + return "sio_open() failed"; + } FFSoundDeviceBundle bundle = {}; - if (sioctl_ondesc(hdl, (void*) enumerate_props, &bundle) == 0) + if (sioctl_ondesc(hdl, (void*) enumerate_props, &bundle) == 0) { return "sioctl_ondesc() failed"; + } - if (bundle.iLevel != bundle.iMute || bundle.iLevel == 0) + if (bundle.iLevel != bundle.iMute || bundle.iLevel == 0) { return "Unexpected sioctl_ondesc() result"; + } FFSoundDevice* device = ffListAdd(devices); ffStrbufInitS(&device->name, bundle.name); @@ -75,10 +80,10 @@ const char* ffDetectSound(FFlist* devices) device->volume = 0; double totalLevel = 0; - for (uint8_t i = 0; i < bundle.iLevel; ++i) - { - if (!bundle.mute[i]) + for (uint8_t i = 0; i < bundle.iLevel; ++i) { + if (!bundle.mute[i]) { totalLevel += bundle.level[i]; + } } device->volume = (uint8_t) ((totalLevel * 100 + bundle.iLevel / 2) / bundle.iLevel); diff --git a/src/detection/sound/sound_sunos.c b/src/detection/sound/sound_sunos.c index dc185c618..2bc0d5326 100644 --- a/src/detection/sound/sound_sunos.c +++ b/src/detection/sound/sound_sunos.c @@ -5,61 +5,63 @@ #include #include #if __has_include() - #include +# include #else - // Strangely, they don't provide this file on default installation - #include "audio_oss_sunos.h" +// Strangely, they don't provide this file on default installation +# include "audio_oss_sunos.h" #endif -const char* ffDetectSound(FFlist* devices) -{ +const char* ffDetectSound(FFlist* devices) { int defaultDev; { char mixerp[12]; ssize_t plen = readlink("/dev/audio", mixerp, ARRAY_SIZE(mixerp)); - if (plen < 6) + if (plen < 6) { return "readlink(/dev/audio) failed"; + } defaultDev = mixerp[plen - 1] - '0'; - if (defaultDev < 0 || defaultDev > 9) + if (defaultDev < 0 || defaultDev > 9) { return "Invalid mixer device"; + } } char path[] = "/dev/mixer0"; FF_STRBUF_AUTO_DESTROY sndstat = ffStrbufCreate(); - struct oss_sysinfo info = { .nummixers = 9 }; + struct oss_sysinfo info = {.nummixers = 9}; // The implementation is very different from *BSD's. They call it OSS4 - for (int idev = 0; idev < info.nummixers; ++idev) - { + for (int idev = 0; idev < info.nummixers; ++idev) { path[strlen("/dev/mixer")] = (char) ('0' + idev); FF_AUTO_CLOSE_FD int fd = open(path, O_RDWR | O_CLOEXEC); - if (fd < 0) break; + if (fd < 0) { + break; + } - if (idev == 0) - { - if (ioctl(fd, SNDCTL_SYSINFO, &info) != 0) + if (idev == 0) { + if (ioctl(fd, SNDCTL_SYSINFO, &info) != 0) { return "ioctl(SNDCTL_SYSINFO) failed"; - if (ffAppendFDBuffer(fd, &sndstat)) + } + if (ffAppendFDBuffer(fd, &sndstat)) { ffStrbufSubstrAfterFirstS(&sndstat, "\nMixers:"); + } } struct oss_mixerinfo mi = {}; - if (ioctl(fd, SNDCTL_MIXERINFO, &mi) < 0) + if (ioctl(fd, SNDCTL_MIXERINFO, &mi) < 0) { continue; + } int volume = -1; - for (int iext = 0; iext < mi.nrext; ++iext) - { - struct oss_mixext me = { .dev = mi.dev, .ctrl = iext }; - if (ioctl(fd, SNDCTL_MIX_EXTINFO, &me) < 0) + for (int iext = 0; iext < mi.nrext; ++iext) { + struct oss_mixext me = {.dev = mi.dev, .ctrl = iext}; + if (ioctl(fd, SNDCTL_MIX_EXTINFO, &me) < 0) { continue; - if (me.flags & MIXF_PCMVOL) - { - struct oss_mixer_value mv = { .dev = mi.dev, .ctrl = iext, .timestamp = me.timestamp }; - if (ioctl(fd, SNDCTL_MIX_READ, &mv) >= 0) - { + } + if (me.flags & MIXF_PCMVOL) { + struct oss_mixer_value mv = {.dev = mi.dev, .ctrl = iext, .timestamp = me.timestamp}; + if (ioctl(fd, SNDCTL_MIX_READ, &mv) >= 0) { mv.value -= me.minvalue; me.maxvalue -= me.minvalue; volume = (uint8_t) ((mv.value * 100 + me.maxvalue / 2) / me.maxvalue); @@ -67,7 +69,9 @@ const char* ffDetectSound(FFlist* devices) break; } } - if (volume == -1) continue; + if (volume == -1) { + continue; + } FFSoundDevice* device = ffListAdd(devices); ffStrbufInitS(&device->identifier, path); @@ -75,15 +79,16 @@ const char* ffDetectSound(FFlist* devices) int bufLen = snprintf(buf, ARRAY_SIZE(buf), "\n%d: ", mi.dev); assert(bufLen > 3); const char* pLine = memmem(sndstat.chars, sndstat.length, buf, (size_t) bufLen); - if (pLine) - { + if (pLine) { pLine += bufLen; const char* pEnd = strchr(pLine, '\n'); - if (!pEnd) pEnd = sndstat.chars + sndstat.length; + if (!pEnd) { + pEnd = sndstat.chars + sndstat.length; + } ffStrbufInitNS(&device->name, (uint32_t) (pEnd - pLine), pLine); - } - else + } else { ffStrbufInitS(&device->name, mi.name); + } ffStrbufTrimRightSpace(&device->name); ffStrbufInitF(&device->platformApi, "%s %s", info.product, info.version); device->volume = (uint8_t) volume; diff --git a/src/detection/sound/sound_windows.cpp b/src/detection/sound/sound_windows.cpp index 5a85f57c2..f2d6c372a 100644 --- a/src/detection/sound/sound_windows.cpp +++ b/src/detection/sound/sound_windows.cpp @@ -1,5 +1,5 @@ extern "C" { - #include "sound.h" +#include "sound.h" } #include "common/windows/unicode.hpp" #include "common/windows/com.hpp" @@ -10,63 +10,72 @@ extern "C" { #include #include -static void ffCoTaskMemFreeWrapper(void* pptr) -{ +static void ffCoTaskMemFreeWrapper(void* pptr) { assert(pptr != NULL); - void* ptr = *(void**)pptr; - if (ptr) CoTaskMemFree(ptr); + void* ptr = *(void**) pptr; + if (ptr) { + CoTaskMemFree(ptr); + } } #define FF_COTASK_AUTO_FREE __attribute__((__cleanup__(ffCoTaskMemFreeWrapper))) -const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) -{ +const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) { const char* error = ffInitCom(); - if (error) + if (error) { return error; + } IMMDeviceEnumerator* FF_AUTO_RELEASE_COM_OBJECT pEnum = NULL; - if (FAILED(CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pEnum)))) + if (FAILED(CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pEnum)))) { return "CoCreateInstance(CLSID_MMDeviceEnumerator) failed"; + } LPWSTR FF_COTASK_AUTO_FREE mainDeviceId = NULL; { IMMDevice* FF_AUTO_RELEASE_COM_OBJECT pDefaultDevice = NULL; - if (FAILED(pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDefaultDevice))) + if (FAILED(pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDefaultDevice))) { return "GetDefaultAudioEndpoint() failed"; + } - if (FAILED(pDefaultDevice->GetId(&mainDeviceId))) + if (FAILED(pDefaultDevice->GetId(&mainDeviceId))) { return "pDefaultDevice->GetId() failed"; + } } IMMDeviceCollection* FF_AUTO_RELEASE_COM_OBJECT pDevices = NULL; - if (FAILED(pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE | DEVICE_STATE_DISABLED, &pDevices))) + if (FAILED(pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE | DEVICE_STATE_DISABLED, &pDevices))) { return "EnumAudioEndpoints() failed"; + } uint32_t deviceCount; - if (FAILED(pDevices->GetCount(&deviceCount))) + if (FAILED(pDevices->GetCount(&deviceCount))) { return "pDevices->GetCount() failed"; + } - for (uint32_t deviceIdx = 0; deviceIdx < deviceCount; ++deviceIdx) - { + for (uint32_t deviceIdx = 0; deviceIdx < deviceCount; ++deviceIdx) { IMMDevice* FF_AUTO_RELEASE_COM_OBJECT immDevice = NULL; - if (FAILED(pDevices->Item(deviceIdx, &immDevice))) + if (FAILED(pDevices->Item(deviceIdx, &immDevice))) { continue; + } LPWSTR FF_COTASK_AUTO_FREE immDeviceId = NULL; - if (FAILED(immDevice->GetId(&immDeviceId))) + if (FAILED(immDevice->GetId(&immDeviceId))) { continue; + } IPropertyStore* FF_AUTO_RELEASE_COM_OBJECT immPropStore; - if (FAILED(immDevice->OpenPropertyStore(STGM_READ, &immPropStore))) + if (FAILED(immDevice->OpenPropertyStore(STGM_READ, &immPropStore))) { continue; + } DWORD immState; - if (FAILED(immDevice->GetState(&immState))) + if (FAILED(immDevice->GetState(&immState))) { continue; + } FFSoundDevice* device = (FFSoundDevice*) ffListAdd(devices); device->main = wcscmp(mainDeviceId, immDeviceId) == 0; @@ -78,19 +87,19 @@ const char* ffDetectSound(FFlist* devices /* List of FFSoundDevice */) { FFPropVariant friendlyName; - if (SUCCEEDED(immPropStore->GetValue(PKEY_Device_FriendlyName, &friendlyName))) + if (SUCCEEDED(immPropStore->GetValue(PKEY_Device_FriendlyName, &friendlyName))) { ffStrbufSetWSV(&device->name, friendlyName.get()); + } } IAudioEndpointVolume* FF_AUTO_RELEASE_COM_OBJECT immEndpointVolume; - if(SUCCEEDED(immDevice->Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, NULL, (void**) &immEndpointVolume))) - { + if (SUCCEEDED(immDevice->Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, NULL, (void**) &immEndpointVolume))) { BOOL muted; - if (FAILED(immEndpointVolume->GetMute(&muted)) || !muted) - { + if (FAILED(immEndpointVolume->GetMute(&muted)) || !muted) { FLOAT volume; - if (SUCCEEDED(immEndpointVolume->GetMasterVolumeLevelScalar(&volume))) + if (SUCCEEDED(immEndpointVolume->GetMasterVolumeLevelScalar(&volume))) { device->volume = (uint8_t) (volume * 100 + 0.5); + } } } } diff --git a/src/detection/swap/swap.h b/src/detection/swap/swap.h index c89940c12..eb32f7590 100644 --- a/src/detection/swap/swap.h +++ b/src/detection/swap/swap.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/swap/option.h" -typedef struct FFSwapResult -{ +typedef struct FFSwapResult { FFstrbuf name; uint64_t bytesUsed; uint64_t bytesTotal; diff --git a/src/detection/swap/swap_apple.c b/src/detection/swap/swap_apple.c index b9e7f7b9c..c550d6a25 100644 --- a/src/detection/swap/swap_apple.c +++ b/src/detection/swap/swap_apple.c @@ -3,12 +3,12 @@ #include #include -const char* ffDetectSwap(FFlist* result) -{ +const char* ffDetectSwap(FFlist* result) { struct xsw_usage xsw; size_t size = sizeof(xsw); - if(sysctl((int[]){ CTL_VM, VM_SWAPUSAGE }, 2, &xsw, &size, NULL, 0) != 0) + if (sysctl((int[]) {CTL_VM, VM_SWAPUSAGE}, 2, &xsw, &size, NULL, 0) != 0) { return "Failed to read vm.swapusage"; + } FFSwapResult* swap = ffListAdd(result); ffStrbufInitStatic(&swap->name, xsw.xsu_encrypted ? "Encrypted" : "Normal"); diff --git a/src/detection/swap/swap_bsd.c b/src/detection/swap/swap_bsd.c index c3e40b3df..b3e8d65b6 100644 --- a/src/detection/swap/swap_bsd.c +++ b/src/detection/swap/swap_bsd.c @@ -5,64 +5,69 @@ #include #include -static void addSwapEntry(FFlist* result, struct xswdev* xsw, uint32_t pageSize) -{ - if (xsw->xsw_nblks == 0) // DFBSD reports some /dev/wdog devices with nblks == 0 +static void addSwapEntry(FFlist* result, struct xswdev* xsw, uint32_t pageSize) { + if (xsw->xsw_nblks == 0) { // DFBSD reports some /dev/wdog devices with nblks == 0 return; + } FFSwapResult* swap = ffListAdd(result); - if (xsw->xsw_dev == NODEV) + if (xsw->xsw_dev == NODEV) { ffStrbufInitStatic(&swap->name, "[NFS]"); - else + } else { ffStrbufInitF(&swap->name, "/dev/%s", devname(xsw->xsw_dev, S_IFCHR)); + } swap->bytesUsed = (uint64_t) xsw->xsw_used * pageSize; swap->bytesTotal = (uint64_t) xsw->xsw_nblks * pageSize; } #if __DragonFly__ -const char* ffDetectSwap(FFlist* result) -{ +const char* ffDetectSwap(FFlist* result) { struct xswdev xsws[32]; size_t size = sizeof(xsws); - if (sysctlbyname("vm.swap_info_array", xsws, &size, NULL, 0) < 0) + if (sysctlbyname("vm.swap_info_array", xsws, &size, NULL, 0) < 0) { return "sysctlbyname(\"vm.swap_info_array\") failed"; + } uint32_t pageSize = instance.state.platform.sysinfo.pageSize; size_t count = size / sizeof(struct xswdev); - if (count == 0) + if (count == 0) { return NULL; + } - if (xsws->xsw_version != XSWDEV_VERSION) + if (xsws->xsw_version != XSWDEV_VERSION) { return "xswdev version mismatch"; + } - for (uint32_t i = 0; i < count; ++i) + for (uint32_t i = 0; i < count; ++i) { addSwapEntry(result, &xsws[i], pageSize); + } return NULL; } #elif __FreeBSD__ -const char* ffDetectSwap(FFlist* result) -{ +const char* ffDetectSwap(FFlist* result) { int mib[16]; size_t mibsize = ARRAY_SIZE(mib); - if (sysctlnametomib("vm.swap_info", mib, &mibsize) < 0) + if (sysctlnametomib("vm.swap_info", mib, &mibsize) < 0) { return "sysctlnametomib(\"vm.swap_info\") failed"; + } uint32_t pageSize = instance.state.platform.sysinfo.pageSize; - for (int n = 0; ; ++n) - { + for (int n = 0;; ++n) { mib[mibsize] = n; struct xswdev xsw; size_t size = sizeof(xsw); - if (sysctl(mib, (uint32_t) (mibsize + 1), &xsw, &size, NULL, 0) < 0) + if (sysctl(mib, (uint32_t) (mibsize + 1), &xsw, &size, NULL, 0) < 0) { break; - if (xsw.xsw_version != XSWDEV_VERSION) + } + if (xsw.xsw_version != XSWDEV_VERSION) { return "xswdev version mismatch"; + } addSwapEntry(result, &xsw, pageSize); } diff --git a/src/detection/swap/swap_haiku.c b/src/detection/swap/swap_haiku.c index 990e741fd..3fe7e7ff2 100644 --- a/src/detection/swap/swap_haiku.c +++ b/src/detection/swap/swap_haiku.c @@ -3,21 +3,21 @@ #include #include -const char* ffDetectSwap(FFlist* result) -{ +const char* ffDetectSwap(FFlist* result) { system_info info; - if (get_system_info(&info) != B_OK) + if (get_system_info(&info) != B_OK) { return "Error getting system info"; + } uint32_t pageSize = instance.state.platform.sysinfo.pageSize; FFSwapResult* swap = ffListAdd(result); ffStrbufInitStatic(&swap->name, "System"); void* kvms = load_driver_settings("virtual_memory"); // /boot/home/config/settings/kernel/drivers/virtual_memory - if (kvms) - { + 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); } swap->bytesTotal = pageSize * (uint64_t) info.max_swap_pages; diff --git a/src/detection/swap/swap_linux.c b/src/detection/swap/swap_linux.c index da6b2744f..3967d26ce 100644 --- a/src/detection/swap/swap_linux.c +++ b/src/detection/swap/swap_linux.c @@ -5,24 +5,26 @@ #include -static const char* detectByProcMeminfo(FFlist* result) -{ +static const char* detectByProcMeminfo(FFlist* result) { // For Android // Ref: #620 char buf[PROC_FILE_BUFFSIZ]; ssize_t nRead = ffReadFileData("/proc/meminfo", ARRAY_SIZE(buf) - 1, buf); - if(nRead < 0) + if (nRead < 0) { return "ffReadFileData(\"/proc/meminfo\", ARRAY_SIZE(buf)-1, buf)"; + } buf[nRead] = '\0'; uint64_t swapTotal = 0, swapFree = 0; - char *token = NULL; - if ((token = strstr(buf, "SwapTotal:")) != NULL) + char* token = NULL; + if ((token = strstr(buf, "SwapTotal:")) != NULL) { swapTotal = strtoul(token + strlen("SwapTotal:"), NULL, 10); + } - if ((token = strstr(buf, "SwapFree:")) != NULL) + if ((token = strstr(buf, "SwapFree:")) != NULL) { swapFree = strtoul(token + strlen("SwapFree:"), NULL, 10); + } FFSwapResult* swap = ffListAdd(result); ffStrbufInitStatic(&swap->name, "Total"); @@ -32,38 +34,36 @@ static const char* detectByProcMeminfo(FFlist* result) return NULL; } -static const char* detectByProcSwaps(FFlist* result) -{ +static const char* detectByProcSwaps(FFlist* result) { // Ref: #620 char buf[PROC_FILE_BUFFSIZ]; ssize_t nRead = ffReadFileData("/proc/swaps", ARRAY_SIZE(buf) - 1, buf); - if(nRead <= 0) + if (nRead <= 0) { return "ffReadFileData(\"/proc/swaps\", ARRAY_SIZE(buf)-1, buf) failed"; + } buf[nRead] = '\0'; // Skip header char* line = memchr(buf, '\n', (size_t) nRead); - while(line && *++line) - { + while (line && *++line) { uint64_t total, used; char name[256]; - if(sscanf(line, "%255s %*[^\t]%" SCNu64 "%" SCNu64, name, &total, &used) != 3) + if (sscanf(line, "%255s %*[^\t]%" SCNu64 "%" SCNu64, name, &total, &used) != 3) { return "Invalid /proc/swaps format found"; + } uint32_t nameLen = (uint32_t) strnlen(name, sizeof(name)); FFSwapResult* swap = ffListAdd(result); ffStrbufInitA(&swap->name, nameLen); - for (size_t i = 0; i < nameLen; ++i) - { - if(name[i] == '\\') - { - char octal[4] = { name[i + 1], name[i + 2], name[i + 3], '\0' }; + for (size_t i = 0; i < nameLen; ++i) { + if (name[i] == '\\') { + char octal[4] = {name[i + 1], name[i + 2], name[i + 3], '\0'}; ffStrbufAppendC(&swap->name, (char) strtol(octal, NULL, 8)); i += 3; - } - else + } else { ffStrbufAppendC(&swap->name, name[i]); + } } swap->bytesTotal = total * 1024u; swap->bytesUsed = used * 1024u; @@ -74,9 +74,9 @@ static const char* detectByProcSwaps(FFlist* result) return NULL; } -const char* ffDetectSwap(FFlist* result) -{ - if (detectByProcSwaps(result) == NULL) +const char* ffDetectSwap(FFlist* result) { + if (detectByProcSwaps(result) == NULL) { return NULL; + } return detectByProcMeminfo(result); } diff --git a/src/detection/swap/swap_nosupport.c b/src/detection/swap/swap_nosupport.c index 98a11195f..ebc29b485 100644 --- a/src/detection/swap/swap_nosupport.c +++ b/src/detection/swap/swap_nosupport.c @@ -1,6 +1,5 @@ #include "swap.h" -const char* ffDetectSwap(FFSwapResult* swap) -{ +const char* ffDetectSwap(FFSwapResult* swap) { return "Not supported on this platform"; } diff --git a/src/detection/swap/swap_obsd.c b/src/detection/swap/swap_obsd.c index e262e4c61..04afe8053 100644 --- a/src/detection/swap/swap_obsd.c +++ b/src/detection/swap/swap_obsd.c @@ -7,21 +7,23 @@ #include #include -const char* ffDetectSwap(FFlist* result) -{ +const char* ffDetectSwap(FFlist* result) { int nswap = swapctl(SWAP_NSWAP, 0, 0); - if (nswap < 0) return "swapctl(SWAP_NSWAP) failed"; - if (nswap == 0) return NULL; + if (nswap < 0) { + return "swapctl(SWAP_NSWAP) failed"; + } + if (nswap == 0) { + return NULL; + } FF_AUTO_FREE struct swapent* swdev = malloc((uint32_t) nswap * sizeof(*swdev)); - if (swapctl(SWAP_STATS, swdev, nswap) < 0) + if (swapctl(SWAP_STATS, swdev, nswap) < 0) { return "swapctl(SWAP_STATS) failed"; + } - for (int i = 0; i < nswap; i++) - { - if (swdev[i].se_flags & SWF_ENABLE) - { + for (int i = 0; i < nswap; i++) { + if (swdev[i].se_flags & SWF_ENABLE) { FFSwapResult* swap = ffListAdd(result); ffStrbufInitS(&swap->name, swdev[i].se_path); swap->bytesUsed = (uint64_t) swdev[i].se_inuse * DEV_BSIZE; diff --git a/src/detection/swap/swap_sunos.c b/src/detection/swap/swap_sunos.c index 87361b56b..323b4decc 100644 --- a/src/detection/swap/swap_sunos.c +++ b/src/detection/swap/swap_sunos.c @@ -6,22 +6,22 @@ enum { FFMaxNSwap = 8 }; -const char* ffDetectSwap(FFlist* result) -{ +const char* ffDetectSwap(FFlist* result) { char strings[FFMaxNSwap][PATH_MAX]; alignas(swaptbl_t) uint8_t buffer[sizeof(swaptbl_t) + sizeof(swapent_t) * (FFMaxNSwap - 1)] = {}; swaptbl_t* table = (swaptbl_t*) buffer; table->swt_n = FFMaxNSwap; - for (int i = 0; i < FFMaxNSwap; ++i) + for (int i = 0; i < FFMaxNSwap; ++i) { table->swt_ent[i].ste_path = strings[i]; + } int size = swapctl(SC_LIST, table); - if (size < 0) + if (size < 0) { return "swapctl() failed"; + } uint32_t pageSize = instance.state.platform.sysinfo.pageSize; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { FFSwapResult* swap = ffListAdd(result); ffStrbufInitS(&swap->name, table->swt_ent[i].ste_path); swap->bytesTotal = (uint64_t) table->swt_ent[i].ste_pages * pageSize; diff --git a/src/detection/swap/swap_windows.c b/src/detection/swap/swap_windows.c index ced111f6c..a0c6999c5 100644 --- a/src/detection/swap/swap_windows.c +++ b/src/detection/swap/swap_windows.c @@ -6,25 +6,26 @@ #include #include -const char* ffDetectSwap(FFlist* result) -{ +const char* ffDetectSwap(FFlist* result) { alignas(SYSTEM_PAGEFILE_INFORMATION) uint8_t buffer[4096]; ULONG size = sizeof(buffer); SYSTEM_PAGEFILE_INFORMATION* pstart = (SYSTEM_PAGEFILE_INFORMATION*) buffer; - if(!NT_SUCCESS(NtQuerySystemInformation(SystemPagefileInformation, pstart, size, &size))) + if (!NT_SUCCESS(NtQuerySystemInformation(SystemPagefileInformation, pstart, size, &size))) { return "NtQuerySystemInformation(SystemPagefileInformation, size) failed"; + } uint32_t pageSize = instance.state.platform.sysinfo.pageSize; - for (SYSTEM_PAGEFILE_INFORMATION* current = pstart; ; current = (SYSTEM_PAGEFILE_INFORMATION*)((uint8_t*) current + current->NextEntryOffset)) - { + for (SYSTEM_PAGEFILE_INFORMATION* current = pstart;; current = (SYSTEM_PAGEFILE_INFORMATION*) ((uint8_t*) current + current->NextEntryOffset)) { FFSwapResult* swap = ffListAdd(result); ffStrbufInitNWS(&swap->name, current->FileName.Length / sizeof(wchar_t), current->FileName.Buffer); - if (ffStrbufStartsWithS(&swap->name, "\\??\\")) + if (ffStrbufStartsWithS(&swap->name, "\\??\\")) { ffStrbufSubstrAfter(&swap->name, strlen("\\??\\") - 1); + } swap->bytesUsed = (uint64_t) current->TotalUsed * pageSize; swap->bytesTotal = (uint64_t) current->CurrentSize * pageSize; - if (current->NextEntryOffset == 0) + if (current->NextEntryOffset == 0) { break; + } } return NULL; } diff --git a/src/detection/terminalfont/terminalfont.c b/src/detection/terminalfont/terminalfont.c index 0793236c5..bc938387d 100644 --- a/src/detection/terminalfont/terminalfont.c +++ b/src/detection/terminalfont/terminalfont.c @@ -6,8 +6,7 @@ #include "common/stringUtils.h" #include "detection/terminalshell/terminalshell.h" -static void detectAlacritty(FFTerminalFontResult* terminalFont) -{ +static void detectAlacritty(FFTerminalFontResult* terminalFont) { // Maybe using a toml parser to read the config file is better? // https://github.com/cktan/tomlc17 @@ -24,16 +23,18 @@ static void detectAlacritty(FFTerminalFontResult* terminalFont) }; // alacritty parses config files in this order - if(ffParsePropFileConfigValues("alacritty/alacritty.toml", 2, fontQueryToml)) + if (ffParsePropFileConfigValues("alacritty/alacritty.toml", 2, fontQueryToml)) { break; - if(ffParsePropFileConfigValues("alacritty.toml", 2, fontQueryToml)) + } + if (ffParsePropFileConfigValues("alacritty.toml", 2, fontQueryToml)) { break; - if(ffParsePropFileConfigValues(".alacritty.toml", 2, fontQueryToml)) + } + if (ffParsePropFileConfigValues(".alacritty.toml", 2, fontQueryToml)) { break; + } } while (false); - if(fontNormal.length > 0) - { + if (fontNormal.length > 0) { // { family = "Fira Code", style = "Medium" } ffStrbufTrimSpace(&fontNormal); ffStrbufTrimRight(&fontNormal, '}'); @@ -46,27 +47,27 @@ static void detectAlacritty(FFTerminalFontResult* terminalFont) ffParsePropLines(fontNormal.chars, "style =", &fontStyle); } - if (fontFamily.length == 0) - { - #if __APPLE__ + if (fontFamily.length == 0) { +#if __APPLE__ ffStrbufSetStatic(&fontFamily, "Menlo"); - #elif _WIN32 +#elif _WIN32 ffStrbufSetStatic(&fontFamily, "Consolas"); - #else +#else ffStrbufSetStatic(&fontFamily, "monospace"); - #endif +#endif } - if (fontStyle.length == 0) + if (fontStyle.length == 0) { ffStrbufSetStatic(&fontStyle, "Regular"); + } - if(fontSize.length == 0) + if (fontSize.length == 0) { ffStrbufSetStatic(&fontSize, "11.25"); + } ffFontInitMoveValues(&terminalFont->font, &fontFamily, &fontSize, &fontStyle); } -static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFont) -{ +static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFont) { FF_DEBUG("detectGhostty: start"); FF_STRBUF_AUTO_DESTROY configPath = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); @@ -75,23 +76,20 @@ static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFon // Try ghostty +show-config first FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - const char* error = ffProcessAppendStdOut(&buffer, (char* const[]){ - exe->chars, - "+show-config", - NULL, - }); - if(error != NULL) - { + const char* error = ffProcessAppendStdOut(&buffer, (char* const[]) { + exe->chars, + "+show-config", + NULL, + }); + if (error != NULL) { FF_DEBUG("`ghostty +show-config` failed: %s", error); return; } char* line = NULL; size_t len = 0; - while (ffStrbufGetline(&line, &len, &buffer)) - { - if (!fontName.length || !fontNameFallback.length) - { + while (ffStrbufGetline(&line, &len, &buffer)) { + if (!fontName.length || !fontNameFallback.length) { if (ffStrStartsWith(line, "font-family = ")) { FF_DEBUG("found %s", line); ffStrbufSetNS( @@ -101,8 +99,7 @@ static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFon continue; } } - if (!fontSize.length) - { + if (!fontSize.length) { if (ffStrStartsWith(line, "font-size = ")) { FF_DEBUG("found fallback %s", line); ffStrbufSetNS( @@ -121,11 +118,11 @@ static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFon if (fontSize.length == 0) { ffStrbufAppendS(&fontSize, - #if __APPLE__ - "13" - #else - "12" - #endif +#if __APPLE__ + "13" +#else + "12" +#endif ); FF_DEBUG("using default size='%s'", fontSize.chars); } @@ -139,71 +136,62 @@ static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFon FF_DEBUG("detectGhostty: end"); } -FF_MAYBE_UNUSED static void detectTTY(FFTerminalFontResult* terminalFont) -{ +FF_MAYBE_UNUSED static void detectTTY(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); - ffParsePropFile(FASTFETCH_TARGET_DIR_ETC"/vconsole.conf", "Font =", &fontName); + ffParsePropFile(FASTFETCH_TARGET_DIR_ETC "/vconsole.conf", "Font =", &fontName); - if(fontName.length == 0) - { + if (fontName.length == 0) { ffStrbufAppendS(&fontName, "VGA default kernel font "); - ffProcessAppendStdOut(&fontName, (char* const[]){ - "showconsolefont", - "--info", - NULL - }); + ffProcessAppendStdOut(&fontName, (char* const[]) {"showconsolefont", "--info", NULL}); ffStrbufTrimRight(&fontName, ' '); } - if(fontName.length > 0) + if (fontName.length > 0) { ffFontInitCopy(&terminalFont->font, fontName.chars); - else - ffStrbufAppendS(&terminalFont->error, "Couldn't find Font in "FASTFETCH_TARGET_DIR_ETC"/vconsole.conf"); + } else { + ffStrbufAppendS(&terminalFont->error, "Couldn't find Font in " FASTFETCH_TARGET_DIR_ETC "/vconsole.conf"); + } } -FF_MAYBE_UNUSED static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResult* result) -{ +FF_MAYBE_UNUSED static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); char fontHex[512] = "", sizeHex[512] = ""; // https://github.com/fastfetch-cli/fastfetch/discussions/1030#discussioncomment-9845233 if (ffGetTerminalResponse( - "\eP+q6b697474792d71756572792d666f6e745f66616d696c79;6b697474792d71756572792d666f6e745f73697a65\e\\", // kitty-query-font_family;kitty-query-font_size - 2, - "\eP1+r%*[^=]=%511[^\e]\e\\\eP1+r%*[^=]=%511[^\e]\e\\", fontHex, sizeHex) == NULL && *fontHex && *sizeHex) - { + "\eP+q6b697474792d71756572792d666f6e745f66616d696c79;6b697474792d71756572792d666f6e745f73697a65\e\\", // kitty-query-font_family;kitty-query-font_size + 2, + "\eP1+r%*[^=]=%511[^\e]\e\\\eP1+r%*[^=]=%511[^\e]\e\\", + fontHex, + sizeHex) == NULL && + *fontHex && *sizeHex) { // decode hex string - for (const char* p = fontHex; p[0] && p[1]; p += 2) - { + for (const char* p = fontHex; p[0] && p[1]; p += 2) { unsigned value; - if (sscanf(p, "%2x", &value) == 1) + if (sscanf(p, "%2x", &value) == 1) { ffStrbufAppendC(&fontName, (char) value); + } } - for (const char* p = sizeHex; p[0] && p[1]; p += 2) - { + for (const char* p = sizeHex; p[0] && p[1]; p += 2) { unsigned value; - if (sscanf(p, "%2x", &value) == 1) + if (sscanf(p, "%2x", &value) == 1) { ffStrbufAppendC(&fontSize, (char) value); + } } - } - else - { + } else { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if(!ffProcessAppendStdOut(&buf, (char* const[]){ - exe->chars, - "+kitten", - "query-terminal", - NULL, - })) - { + if (!ffProcessAppendStdOut(&buf, (char* const[]) { + exe->chars, + "+kitten", + "query-terminal", + NULL, + })) { ffParsePropLines(buf.chars, "font_family: ", &fontName); ffParsePropLines(buf.chars, "font_size: ", &fontSize); - } - else - { + } else { FFpropquery fontQuery[] = { {"font_family ", &fontName}, {"font_size ", &fontSize}, @@ -211,10 +199,12 @@ FF_MAYBE_UNUSED static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResul ffParsePropFileConfigValues("kitty/kitty.conf", 2, fontQuery); - if(fontName.length == 0) + if (fontName.length == 0) { ffStrbufSetS(&fontName, "monospace"); - if(fontSize.length == 0) + } + if (fontSize.length == 0) { ffStrbufSetS(&fontSize, "11.0"); + } } } @@ -223,42 +213,36 @@ FF_MAYBE_UNUSED static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResul return true; } -static bool detectWezterm(const FFstrbuf* exe, FFTerminalFontResult* result) -{ +static bool detectWezterm(const FFstrbuf* exe, FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY cli = ffStrbufCreateCopy(exe); ffStrbufSubstrBeforeLastC(&cli, '-'); - #ifdef _WIN32 +#ifdef _WIN32 ffStrbufAppendS(&cli, ".exe"); - #endif +#endif FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); - ffStrbufSetS(&result->error, ffProcessAppendStdOut(&fontName, (char* const[]){ - cli.chars, - "ls-fonts", - "--text", - "a", - NULL - })); - if(result->error.length) + ffStrbufSetS(&result->error, ffProcessAppendStdOut(&fontName, (char* const[]) {cli.chars, "ls-fonts", "--text", "a", NULL})); + if (result->error.length) { return false; + } - //LeftToRight - // 0 a \u{61} x_adv=7 cells=1 glyph=a,180 wezterm.font("JetBrains Mono", {weight="Regular", stretch="Normal", style="Normal"}) - // , BuiltIn + // LeftToRight + // 0 a \u{61} x_adv=7 cells=1 glyph=a,180 wezterm.font("JetBrains Mono", {weight="Regular", stretch="Normal", style="Normal"}) + // , BuiltIn ffStrbufSubstrAfterFirstC(&fontName, '"'); ffStrbufSubstrBeforeFirstC(&fontName, '"'); - if(!fontName.length) + if (!fontName.length) { return false; + } ffFontInitCopy(&result->font, fontName.chars); return true; } -static bool detectTabby(FFTerminalFontResult* result) -{ +static bool detectTabby(FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); @@ -267,50 +251,48 @@ static bool detectTabby(FFTerminalFontResult* result) {"fontSize: ", &fontSize}, }; - if(!ffParsePropFileConfigValues("tabby/config.yaml", 2, fontQuery)) + if (!ffParsePropFileConfigValues("tabby/config.yaml", 2, fontQuery)) { return false; + } - if(fontName.length == 0) + if (fontName.length == 0) { ffStrbufSetS(&fontName, "monospace"); - if(fontSize.length == 0) + } + if (fontSize.length == 0) { ffStrbufSetS(&fontSize, "14"); + } ffFontInitValues(&result->font, fontName.chars, fontSize.chars); return true; } -static bool detectContour(const FFstrbuf* exe, FFTerminalFontResult* result) -{ +static bool detectContour(const FFstrbuf* exe, FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if(ffProcessAppendStdOut(&buf, (char* const[]){ - exe->chars, - "font-locator", - NULL - })) - { + if (ffProcessAppendStdOut(&buf, (char* const[]) {exe->chars, "font-locator", NULL})) { ffStrbufAppendS(&result->error, "`contour font-locator` failed"); return false; } //[error] Missing key .logging.enabled. Using default: false. //[error] ... - //Matching fonts using : Fontconfig - //Font description : (family=Sarasa Term SC Nerd weight=Regular slant=Roman spacing=Monospace, strict_spacing=yes) - //Number of fonts found : 49 + // Matching fonts using : Fontconfig + // Font description : (family=Sarasa Term SC Nerd weight=Regular slant=Roman spacing=Monospace, strict_spacing=yes) + // Number of fonts found : 49 // path /usr/share/fonts/google-noto/NotoSansMono-Regular.ttf Regular Roman // path ... uint32_t index = ffStrbufFirstIndexS(&buf, "Font description : (family="); - if(index >= buf.length) return false; + if (index >= buf.length) { + return false; + } index += (uint32_t) strlen("Font description : (family="); ffStrbufSubstrBefore(&buf, ffStrbufNextIndexS(&buf, index, " weight=")); ffFontInitCopy(&result->font, buf.chars + index); return true; } -static bool detectRio(FFTerminalFontResult* terminalFont) -{ +static bool detectRio(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); @@ -321,11 +303,13 @@ static bool detectRio(FFTerminalFontResult* terminalFont) ffParsePropFileConfigValues("rio/config.toml", 2, fontQueryToml); - if(fontName.length == 0) + if (fontName.length == 0) { ffStrbufAppendS(&fontName, "Cascadia Code"); + } - if(fontSize.length == 0) + if (fontSize.length == 0) { ffStrbufAppendS(&fontSize, "18"); + } ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); @@ -334,48 +318,51 @@ static bool detectRio(FFTerminalFontResult* terminalFont) bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont); -static bool detectTerminalFontCommon(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) -{ - if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "alacritty")) +static bool detectTerminalFontCommon(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) { + if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "alacritty")) { detectAlacritty(terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "wezterm-gui")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "wezterm-gui")) { detectWezterm(&terminal->exe, terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "tabby")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "tabby")) { detectTabby(terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "contour")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "contour")) { detectContour(&terminal->exe, terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "ghostty")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "ghostty")) { detectGhostty(&terminal->exe, terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "rio")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "rio")) { detectRio(terminalFont); - - #ifndef _WIN32 - else if(ffStrbufStartsWithIgnCaseS(&terminal->exe, "/dev/pts/")) + } +#ifndef _WIN32 + else if (ffStrbufStartsWithIgnCaseS(&terminal->exe, "/dev/pts/")) { ffStrbufAppendS(&terminalFont->error, "Terminal font detection is not supported on PTS"); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "kitty")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "kitty")) { detectKitty(&terminal->exe, terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->exe, "/dev/tty")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->exe, "/dev/tty")) { detectTTY(terminalFont); - #endif + } +#endif - else + else { return false; + } return true; } -bool ffDetectTerminalFont(FFTerminalFontResult* result) -{ +bool ffDetectTerminalFont(FFTerminalFontResult* result) { const FFTerminalResult* terminal = ffDetectTerminal(); - if(terminal->processName.length == 0) + if (terminal->processName.length == 0) { ffStrbufAppendS(&result->error, "Terminal font needs successful terminal detection"); + } - else if(!detectTerminalFontCommon(terminal, result)) + else if (!detectTerminalFontCommon(terminal, result)) { ffDetectTerminalFontPlatform(terminal, result); + } - if(result->error.length == 0 && result->font.pretty.length == 0) + if (result->error.length == 0 && result->font.pretty.length == 0) { ffStrbufAppendF(&result->error, "Unknown terminal: %s", terminal->processName.chars); + } return result->error.length == 0; } diff --git a/src/detection/terminalfont/terminalfont.h b/src/detection/terminalfont/terminalfont.h index 03ddad99e..bdc416c1a 100644 --- a/src/detection/terminalfont/terminalfont.h +++ b/src/detection/terminalfont/terminalfont.h @@ -4,8 +4,7 @@ #include "common/font.h" #include "modules/font/option.h" -typedef struct FFTerminalFontResult -{ +typedef struct FFTerminalFontResult { FFstrbuf error; FFfont font; FFfont fallback; diff --git a/src/detection/terminalfont/terminalfont_android.c b/src/detection/terminalfont/terminalfont_android.c index ef2ef39ef..1188f1617 100644 --- a/src/detection/terminalfont/terminalfont_android.c +++ b/src/detection/terminalfont/terminalfont_android.c @@ -4,22 +4,20 @@ #include "common/io.h" #ifdef FF_HAVE_FREETYPE - #include "common/library.h" - #include - #include FT_FREETYPE_H +# include "common/library.h" +# include +# include FT_FREETYPE_H #endif #define FF_TERMUX_FONT_PATH FASTFETCH_TARGET_DIR_HOME "/.termux/font.ttf" -const char* detectTermux(FFTerminalFontResult* terminalFont) -{ - if(!ffPathExists(FF_TERMUX_FONT_PATH, FF_PATHTYPE_FILE)) - { +const char* detectTermux(FFTerminalFontResult* terminalFont) { + if (!ffPathExists(FF_TERMUX_FONT_PATH, FF_PATHTYPE_FILE)) { ffFontInitCopy(&terminalFont->font, "monospace"); return NULL; } - #ifdef FF_HAVE_FREETYPE +#ifdef FF_HAVE_FREETYPE FF_LIBRARY_LOAD_MESSAGE(freetype, "libfreetype" FF_LIBRARY_EXTENSION, 2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(freetype, FT_Init_FreeType); @@ -31,14 +29,12 @@ const char* detectTermux(FFTerminalFontResult* terminalFont) FT_Face face = NULL; const char* error = NULL; - if(ffFT_Init_FreeType(&library)) - { + if (ffFT_Init_FreeType(&library)) { error = "FT_Init_FreeType() failed"; goto exit; } - if(ffFT_New_Face(library, FF_TERMUX_FONT_PATH, 0, &face)) - { + if (ffFT_New_Face(library, FF_TERMUX_FONT_PATH, 0, &face)) { error = "FT_NEW_Face(" FF_TERMUX_FONT_PATH ") failed"; goto exit; } @@ -46,25 +42,27 @@ const char* detectTermux(FFTerminalFontResult* terminalFont) ffFontInitCopy(&terminalFont->font, face->family_name); exit: - if(face) ffFT_Done_Face(face); - if(library) ffFT_Done_FreeType(library); + if (face) { + ffFT_Done_Face(face); + } + if (library) { + ffFT_Done_FreeType(library); + } return error; - #else +#else FF_UNUSED(terminalFont); return "Fastfetch was built without freetype2 support"; - #endif +#endif } -bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) -{ - if(ffStrbufEqualS(&terminal->processName, "com.termux")) +bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) { + if (ffStrbufEqualS(&terminal->processName, "com.termux")) { ffStrbufSetS(&terminalFont->error, detectTermux(terminalFont)); - else - { + } else { bool ffDetectTerminalFontPlatformLinux(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont); return ffDetectTerminalFontPlatformLinux(terminal, terminalFont); } diff --git a/src/detection/terminalfont/terminalfont_linux.c b/src/detection/terminalfont/terminalfont_linux.c index a8c0ddac9..bf45b158b 100644 --- a/src/detection/terminalfont/terminalfont_linux.c +++ b/src/detection/terminalfont/terminalfont_linux.c @@ -11,72 +11,64 @@ #include "detection/terminalshell/terminalshell.h" #include "detection/displayserver/displayserver.h" -static const char* getSystemMonospaceFont(void) -{ +static const char* getSystemMonospaceFont(void) { const FFDisplayServerResult* wmde = ffConnectDisplayServer(); - if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Cinnamon")) - { + if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Cinnamon")) { 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)) + if (ffStrSet(systemMonospaceFont)) { return systemMonospaceFont; - } - else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Mate")) - { + } + } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Mate")) { 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)) + if (ffStrSet(systemMonospaceFont)) { return systemMonospaceFont; + } } 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) -{ +static void detectKgx(FFTerminalFontResult* terminalFont) { // kgx (gnome console) doesn't support profiles - if(!ffSettingsGetGnome("/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 = ffSettingsGetGnome("/org/gnome/Console/custom-font", "org.gnome.Console", NULL, "custom-font", FF_VARIANT_TYPE_STRING).strValue; - if(ffStrSet(fontName)) + if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); - else + } else { ffStrbufAppendF(&terminalFont->error, "Couldn't get terminal font from GSettings (org.gnome.Console::custom-font)"); - } - else - { + } + } else { FF_AUTO_FREE const char* fontName = getSystemMonospaceFont(); - if(ffStrSet(fontName)) + if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); - else + } else { ffStrbufAppendS(&terminalFont->error, "Couldn't get system monospace font name from GSettings / DConf"); + } } } -static void detectPtyxis(FFTerminalFontResult* terminalFont) -{ - if(!ffSettingsGetGnome("/org/gnome/Ptyxis/use-system-font", "org.gnome.Ptyxis", NULL, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue) - { +static void detectPtyxis(FFTerminalFontResult* terminalFont) { + 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 = ffSettingsGetGnome("/org/gnome/Ptyxis/font-name", "org.gnome.Ptyxis", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue; - if(ffStrSet(fontName)) + if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); - else + } else { ffStrbufAppendF(&terminalFont->error, "Couldn't get terminal font from GSettings (org.gnome.Ptyxis::font-name)"); - } - else - { + } + } else { FF_AUTO_FREE const char* fontName = getSystemMonospaceFont(); - if(ffStrSet(fontName)) + if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); - else + } else { ffStrbufAppendS(&terminalFont->error, "Couldn't get system monospace font name from GSettings / DConf"); + } } } -static void detectFromGSettings(const char* profilePath, const char* profileList, const char* profile, const char* defaultProfileKey, FFTerminalFontResult* terminalFont) -{ +static void detectFromGSettings(const char* profilePath, const char* profileList, const char* profile, const char* defaultProfileKey, FFTerminalFontResult* terminalFont) { FF_AUTO_FREE const char* defaultProfile = ffSettingsGetGSettings(profileList, NULL, defaultProfileKey, FF_VARIANT_TYPE_STRING).strValue; - if(!ffStrSet(defaultProfile)) - { + if (!ffStrSet(defaultProfile)) { ffStrbufAppendF(&terminalFont->error, "Could not get default profile from gsettings: %s", profileList); return; } @@ -86,46 +78,42 @@ static void detectFromGSettings(const char* profilePath, const char* profileList ffStrbufAppendS(&path, defaultProfile); ffStrbufAppendC(&path, '/'); - if(!ffSettingsGetGSettings(profile, path.chars, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue) - { + if (!ffSettingsGetGSettings(profile, path.chars, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue) { FF_AUTO_FREE const char* fontName = ffSettingsGetGSettings(profile, path.chars, "font", FF_VARIANT_TYPE_STRING).strValue; - if(ffStrSet(fontName)) + if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); - else + } else { ffStrbufAppendF(&terminalFont->error, "Couldn't get terminal font from GSettings (%s::%s::font)", profile, path.chars); - } - else - { + } + } else { FF_AUTO_FREE const char* fontName = getSystemMonospaceFont(); - if(ffStrSet(fontName)) + if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); - else + } else { ffStrbufAppendS(&terminalFont->error, "Couldn't get system monospace font name from GSettings / DConf"); + } } } -static void detectFromConfigFile(const char* configFile, const char* start, FFTerminalFontResult* terminalFont) -{ +static void detectFromConfigFile(const char* configFile, const char* start, FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); ffParsePropFileConfig(configFile, start, &fontName); - if(fontName.length == 0) + if (fontName.length == 0) { ffStrbufAppendF(&terminalFont->error, "Couldn't find %s in .config/%s", start, configFile); - else + } else { ffFontInitPango(&terminalFont->font, fontName.chars); + } } -static void detectKonsole(FFTerminalFontResult* terminalFont, const char* rcFile) -{ +static void detectKonsole(FFTerminalFontResult* terminalFont, const char* rcFile) { FF_STRBUF_AUTO_DESTROY profile = ffStrbufCreate(); - if(!ffParsePropFileConfig(rcFile, "DefaultProfile =", &profile)) - { + if (!ffParsePropFileConfig(rcFile, "DefaultProfile =", &profile)) { ffStrbufAppendF(&terminalFont->error, "Configuration \".config/%s\" doesn't exist", rcFile); return; } - if(profile.length == 0) - { + if (profile.length == 0) { ffStrbufAppendS(&terminalFont->error, "Built-in profile is used"); return; } @@ -137,56 +125,45 @@ static void detectKonsole(FFTerminalFontResult* terminalFont, const char* rcFile FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); ffParsePropFileData(profilePath.chars, "Font =", &fontName); - if(fontName.length == 0) + if (fontName.length == 0) { ffStrbufAppendF(&terminalFont->error, "Couldn't find \"Font=%%[^\\n]\" in \"%s\"", profilePath.chars); - else + } else { ffFontInitQt(&terminalFont->font, fontName.chars); + } } -static void detectXFCETerminal(FFTerminalFontResult* terminalFont) -{ +static void detectXFCETerminal(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY useSysFont = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); const char* path = "xfce4/xfconf/xfce-perchannel-xml/xfce4-terminal.xml"; - bool configFound = ffParsePropFileConfigValues(path, 2, (FFpropquery[]) { - {"error, "Couldn't find FontName in %s", path); - else + } else { ffFontInitPango(&terminalFont->font, fontName.chars); - } - else - { + } + } else { const char* systemFontName = ffSettingsGetXFConf("xsettings", "/Gtk/MonospaceFontName", FF_VARIANT_TYPE_STRING).strValue; - if(ffStrSet(systemFontName)) + if (ffStrSet(systemFontName)) { ffFontInitPango(&terminalFont->font, systemFontName); - else + } else { ffStrbufAppendS(&terminalFont->error, "Couldn't find xsettings::/Gtk/MonospaceFontName in XFConf"); + } } } -static void detectDeepinTerminal(FFTerminalFontResult* terminalFont) -{ +static void detectDeepinTerminal(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); @@ -194,23 +171,20 @@ static void detectDeepinTerminal(FFTerminalFontResult* terminalFont) ffSearchUserConfigFile(&instance.state.platform.configDirs, "deepin/deepin-terminal/config.conf", &profile); FILE* file = fopen(profile.chars, "r"); - if(file) - { + if (file) { char* line = NULL; size_t len = 0; - for(int count = 0; getline(&line, &len, file) != -1 && count < 2;) - { - if(ffStrEquals(line, "[basic.interface.font]\n")) - { - if(getline(&line, &len, file) != -1) + for (int count = 0; getline(&line, &len, file) != -1 && count < 2;) { + if (ffStrEquals(line, "[basic.interface.font]\n")) { + if (getline(&line, &len, file) != -1) { ffParsePropLine(line, "value=", &fontName); + } ++count; - } - else if(ffStrEquals(line, "[basic.interface.font_size]\n")) - { - if(getline(&line, &len, file) != -1) + } else if (ffStrEquals(line, "[basic.interface.font_size]\n")) { + if (getline(&line, &len, file) != -1) { ffParsePropLine(line, "value=", &fontSize); + } ++count; } } @@ -219,125 +193,120 @@ static void detectDeepinTerminal(FFTerminalFontResult* terminalFont) fclose(file); } - if(fontName.length == 0) + if (fontName.length == 0) { ffStrbufAppendS(&fontName, "Noto Sans Mono"); - if(fontSize.length == 0) + } + if (fontSize.length == 0) { ffStrbufAppendS(&fontSize, "11"); + } ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); } -static void detectFootTerminal(FFTerminalFontResult* terminalFont) -{ +static void detectFootTerminal(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY font = ffStrbufCreate(); - if (!ffParsePropFileConfig("foot/foot.ini", "font=", &font) || !ffStrSet(font.chars)) - { + if (!ffParsePropFileConfig("foot/foot.ini", "font=", &font) || !ffStrSet(font.chars)) { ffFontInitValues(&terminalFont->font, "monospace", "8"); return; } - //Sarasa Term SC Nerd:size=8 + // Sarasa Term SC Nerd:size=8 uint32_t colon = ffStrbufFirstIndexC(&font, ':'); - if(colon == font.length) - { + if (colon == font.length) { ffFontInitValues(&terminalFont->font, font.chars, "8"); return; } uint32_t equal = ffStrbufNextIndexS(&font, colon, "size="); font.chars[colon] = '\0'; - if (equal == font.length) - { + if (equal == font.length) { ffFontInitValues(&terminalFont->font, font.chars, "8"); return; } uint32_t size = equal + (uint32_t) strlen("size="); uint32_t comma = ffStrbufNextIndexC(&font, size, ','); - if (comma < font.length) + if (comma < font.length) { font.chars[comma] = '\0'; + } ffFontInitValues(&terminalFont->font, font.chars, &font.chars[size]); - if (comma < font.length) + if (comma < font.length) { ffFontInitValues(&terminalFont->fallback, &font.chars[comma + 1], NULL); + } } -static void detectQTerminal(FFTerminalFontResult* terminalFont) -{ +static void detectQTerminal(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); ffParsePropFileConfigValues("qterminal.org/qterminal.ini", 2, (FFpropquery[]) { - {"fontFamily=", &fontName}, - {"fontSize=", &fontSize}, - }); + {"fontFamily=", &fontName}, + {"fontSize=", &fontSize}, + }); - if (fontName.length == 0) + if (fontName.length == 0) { ffStrbufAppendS(&fontName, "monospace"); - if (fontSize.length == 0) + } + if (fontSize.length == 0) { ffStrbufAppendS(&fontSize, "12"); + } ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); } -static void detectXterm(FFTerminalFontResult* terminalFont) -{ +static void detectXterm(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); ffParsePropFileHomeValues(".Xresources", 2, (FFpropquery[]) { - {"xterm*faceName:", &fontName}, - {"xterm*faceSize:", &fontSize}, - }); + {"xterm*faceName:", &fontName}, + {"xterm*faceSize:", &fontSize}, + }); - if (fontName.length == 0) - { + if (fontName.length == 0) { ffParsePropFileHomeValues(".Xresources", 2, (FFpropquery[]) { - {"xterm.vt100.faceName:", &fontName}, - {"xterm.vt100.faceSize:", &fontSize}, - }); + {"xterm.vt100.faceName:", &fontName}, + {"xterm.vt100.faceSize:", &fontSize}, + }); } - if (fontName.length == 0) + if (fontName.length == 0) { ffStrbufAppendS(&fontName, "fixed"); - if (fontSize.length == 0) + } + if (fontSize.length == 0) { ffStrbufAppendS(&fontSize, "8.0"); + } ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); } -static bool extractStTermFont(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) -{ - if (!ffStrContains(str, "size=")) return true; +static bool extractStTermFont(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrContains(str, "size=")) { + return true; + } ffStrbufSetNS((FFstrbuf*) userdata, len, str); return false; } -static void detectSt(FFTerminalFontResult* terminalFont, const FFTerminalResult* terminal) -{ +static void detectSt(FFTerminalFontResult* terminalFont, const FFTerminalResult* terminal) { FF_STRBUF_AUTO_DESTROY size = ffStrbufCreateF("/proc/%u/cmdline", terminal->pid); FF_STRBUF_AUTO_DESTROY font = ffStrbufCreate(); - if (!ffAppendFileBuffer(size.chars, &font)) - { + if (!ffAppendFileBuffer(size.chars, &font)) { ffStrbufAppendF(&terminalFont->error, "Failed to open %s", size.chars); return; } const char* p = memmem(font.chars, font.length, "\0-f", sizeof("\0-f")); // find parameter of `-f` - if (p) - { + if (p) { // st was executed with `-f` parameter ffStrbufSubstrAfter(&font, (uint32_t) (p + (sizeof("\0-f") - 1) - font.chars)); ffStrbufRecalculateLength(&font); - } - else - { + } else { ffStrbufClear(&font); const char* error = ffBinaryExtractStrings(terminal->exePath.chars, extractStTermFont, &font, (uint32_t) strlen("size=0")); - if (error) - { + if (error) { ffStrbufAppendS(&terminalFont->error, error); return; } - if (font.length == 0) - { + if (font.length == 0) { ffStrbufAppendS(&terminalFont->error, "No font config found in st binary"); return; } @@ -346,42 +315,43 @@ static void detectSt(FFTerminalFontResult* terminalFont, const FFTerminalResult* // JetBrainsMono Nerd Font Mono:pixelsize=12:antialias=true:autohint=true uint32_t index = ffStrbufFirstIndexC(&font, ':'); - if (index != font.length) - { + if (index != font.length) { uint32_t sIndex = ffStrbufNextIndexS(&font, index + 1, "size="); - if (sIndex != font.length) - { + if (sIndex != font.length) { sIndex += (uint32_t) strlen("size="); uint32_t sIndexEnd = ffStrbufNextIndexC(&font, sIndex, ':'); ffStrbufSetNS(&size, sIndexEnd - sIndex, font.chars + sIndex); } ffStrbufSubstrBefore(&font, index); - } - else + } else { ffStrbufClear(&size); + } ffFontInitValues(&terminalFont->font, font.chars, size.chars); } -static void detectWarp(FFTerminalFontResult* terminalFont) -{ +static void detectWarp(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY baseDir = ffStrbufCreateA(64); - FF_LIST_FOR_EACH(FFstrbuf, dirPrefix, instance.state.platform.configDirs) - { - //We need to copy the dir each time, because it used by multiple threads, so we can't directly write to it. + FF_LIST_FOR_EACH (FFstrbuf, dirPrefix, instance.state.platform.configDirs) { + // We need to copy the dir each time, because it used by multiple threads, so we can't directly write to it. ffStrbufSet(&baseDir, dirPrefix); ffStrbufAppendS(&baseDir, "warp-terminal/user_preferences.json"); yyjson_doc* doc = yyjson_read_file(baseDir.chars, YYJSON_READ_INSITU | YYJSON_READ_ALLOW_TRAILING_COMMAS | YYJSON_READ_ALLOW_COMMENTS, NULL, NULL); - if (!doc) continue; + if (!doc) { + continue; + } yyjson_val* prefs = yyjson_obj_get(yyjson_doc_get_root(doc), "prefs"); - if (yyjson_is_obj(prefs)) - { + if (yyjson_is_obj(prefs)) { const char* fontName = yyjson_get_str(yyjson_obj_get(prefs, "FontName")); - if (!fontName) fontName = "Hack"; + if (!fontName) { + fontName = "Hack"; + } const char* fontSize = yyjson_get_str(yyjson_obj_get(prefs, "FontSize")); - if (!fontSize) fontSize = "13"; + if (!fontSize) { + fontSize = "13"; + } ffFontInitValues(&terminalFont->font, fontName, fontSize); } @@ -390,53 +360,56 @@ static void detectWarp(FFTerminalFontResult* terminalFont) } } -static void detectTerminator(FFTerminalFontResult* result) -{ +static void detectTerminator(FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY useSystemFont = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); - if(!ffParsePropFileConfigValues("terminator/config", 2, (FFpropquery[]) { - {"use_system_font =", &useSystemFont}, - {"font =", &fontName}, - }) || ffStrbufIgnCaseEqualS(&useSystemFont, "True")) - { + if (!ffParsePropFileConfigValues("terminator/config", 2, (FFpropquery[]) { + {"use_system_font =", &useSystemFont}, + {"font =", &fontName}, + }) || + ffStrbufIgnCaseEqualS(&useSystemFont, "True")) { FF_AUTO_FREE const char* fontName = getSystemMonospaceFont(); - if(ffStrSet(fontName)) + if (ffStrSet(fontName)) { ffFontInitPango(&result->font, fontName); - else + } else { ffStrbufAppendS(&result->error, "Couldn't get system monospace font name from GSettings / DConf"); + } return; } - if(fontName.length == 0) + if (fontName.length == 0) { ffFontInitValues(&result->font, "Mono", "10"); - else + } else { ffFontInitPango(&result->font, fontName.chars); + } } -static void detectWestonTerminal(FFTerminalFontResult* terminalFont) -{ +static void detectWestonTerminal(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY font = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY size = ffStrbufCreate(); ffParsePropFileConfigValues("weston.ini", 2, (FFpropquery[]) { - {"font=", &font}, - {"font-size=", &size}, - }); - if (!font.length) ffStrbufSetStatic(&font, "DejaVu Sans Mono"); - if (!size.length) ffStrbufSetStatic(&size, "14"); + {"font=", &font}, + {"font-size=", &size}, + }); + if (!font.length) { + ffStrbufSetStatic(&font, "DejaVu Sans Mono"); + } + if (!size.length) { + ffStrbufSetStatic(&size, "14"); + } ffFontInitValues(&terminalFont->font, font.chars, size.chars); } -static void detectUrxvt(FFTerminalFontResult* terminalFont) -{ +static void detectUrxvt(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); if (!(ffParsePropFileHomeValues(".Xresources", 1, (FFpropquery[]) { - {"URxvt.font:", &buffer}, - }) || ffParsePropFileHomeValues(".Xdefaults", 1, (FFpropquery[]) { - {"URxvt.font:", &buffer}, - }))) - { + {"URxvt.font:", &buffer}, + }) || + ffParsePropFileHomeValues(".Xdefaults", 1, (FFpropquery[]) { + {"URxvt.font:", &buffer}, + }))) { ffStrbufAppendS(&terminalFont->error, "Could not find URxvt.font in .Xresources or .Xdefaults"); return; } @@ -445,25 +418,24 @@ static void detectUrxvt(FFTerminalFontResult* terminalFont) char* line = NULL; size_t len = 0; - while (ffStrbufGetdelim(&line, &len, ',', &buffer)) - { + while (ffStrbufGetdelim(&line, &len, ',', &buffer)) { FFfont* font = index == 0 ? &terminalFont->font : &terminalFont->fallback; - if (line[0] == '-') + if (line[0] == '-') { ffFontInitXlfd(font, line); - else if (ffStrStartsWith(line, "xft:")) + } else if (ffStrStartsWith(line, "xft:")) { ffFontInitXft(font, line + 4); - else - { + } else { ffStrbufAppendF(&terminalFont->error, "Unknown URxvt font format: %s", line); continue; } index++; - if (index > 1) break; + if (index > 1) { + break; + } } } -static bool detectCosmicTerm(FFTerminalFontResult* terminalFont) -{ +static bool detectCosmicTerm(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); @@ -475,13 +447,18 @@ static bool detectCosmicTerm(FFTerminalFontResult* terminalFont) ffReadFileBuffer(path.chars, &fontName); ffStrbufTrim(&path, '"'); ffStrbufSubstrBefore(&path, baseLen); - if (fontName.length == 0) ffStrbufSetStatic(&fontName, "Noto Sans Mono"); + if (fontName.length == 0) { + ffStrbufSetStatic(&fontName, "Noto Sans Mono"); + } ffStrbufAppendS(&path, "font_size"); - if (ffReadFileBuffer(path.chars, &fontSize)) + if (ffReadFileBuffer(path.chars, &fontSize)) { ffStrbufAppendS(&fontSize, "px"); + } ffStrbufSubstrBefore(&path, baseLen); - if (fontSize.length == 0) ffStrbufSetStatic(&fontSize, "14px"); + if (fontSize.length == 0) { + ffStrbufSetStatic(&fontSize, "14px"); + } ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); @@ -489,16 +466,19 @@ static bool detectCosmicTerm(FFTerminalFontResult* terminalFont) } #ifdef __HAIKU__ -static void detectHaikuTerminal(FFTerminalFontResult* terminalFont) -{ +static void detectHaikuTerminal(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY font = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY size = ffStrbufCreate(); ffParsePropFileConfigValues("Terminal/Default", 2, (FFpropquery[]) { - {"\"Half Font Family\" , ", &font}, - {"\"Half Font Size\" , ", &size}, - }); - if (!font.length) ffStrbufSetStatic(&font, "Noto Sans Mono"); - if (!size.length) ffStrbufSetStatic(&size, "12"); + {"\"Half Font Family\" , ", &font}, + {"\"Half Font Size\" , ", &size}, + }); + if (!font.length) { + ffStrbufSetStatic(&font, "Noto Sans Mono"); + } + if (!size.length) { + ffStrbufSetStatic(&size, "12"); + } ffFontInitValues(&terminalFont->font, font.chars, size.chars); } #endif @@ -509,57 +489,57 @@ ffDetectTerminalFontPlatformLinux #else ffDetectTerminalFontPlatform #endif -(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) -{ - if(ffStrbufIgnCaseEqualS(&terminal->processName, "konsole")) + (const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) { + if (ffStrbufIgnCaseEqualS(&terminal->processName, "konsole")) { detectKonsole(terminalFont, "konsolerc"); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "yakuake")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "yakuake")) { detectKonsole(terminalFont, "yakuakerc"); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "xfce4-terminal")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "xfce4-terminal")) { detectXFCETerminal(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "lxterminal")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "lxterminal")) { detectFromConfigFile("lxterminal/lxterminal.conf", "fontname =", terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "tilix")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "tilix")) { detectFromGSettings("/com/gexperts/Tilix/profiles/", "com.gexperts.Tilix.ProfilesList", "com.gexperts.Tilix.Profile", "default", terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "gnome-terminal")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "gnome-terminal")) { detectFromGSettings("/org/gnome/terminal/legacy/profiles:/:", "org.gnome.Terminal.ProfilesList", "org.gnome.Terminal.Legacy.Profile", "default", terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "ptyxis-agent")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "ptyxis-agent")) { detectPtyxis(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "kgx")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "kgx")) { detectKgx(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "mate-terminal")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "mate-terminal")) { detectFromGSettings("/org/mate/terminal/profiles/", "org.mate.terminal.global", "org.mate.terminal.profile", "default-profile", terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "deepin-terminal")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "deepin-terminal")) { detectDeepinTerminal(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "foot")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "foot")) { detectFootTerminal(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "qterminal")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "qterminal")) { detectQTerminal(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "xterm")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "xterm")) { detectXterm(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "st")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "st")) { detectSt(terminalFont, terminal); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "warp")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "warp")) { detectWarp(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "weston-terminal")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "weston-terminal")) { detectWestonTerminal(terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "terminator")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "terminator")) { detectTerminator(terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "sakura")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "sakura")) { detectFromConfigFile("sakura/sakura.conf", "font=", terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "cosmic-term")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "cosmic-term")) { detectCosmicTerm(terminalFont); - #ifdef __HAIKU__ - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "Terminal")) + } +#ifdef __HAIKU__ + else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "Terminal")) { detectHaikuTerminal(terminalFont); - #endif - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "termite")) + } +#endif + else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "termite")) { detectFromConfigFile("termite/config", "font =", terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "rxvt") - || ffStrbufIgnCaseEqualS(&terminal->processName, "urxvt") - || ffStrbufIgnCaseEqualS(&terminal->processName, "urxvtd")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "rxvt") || ffStrbufIgnCaseEqualS(&terminal->processName, "urxvt") || ffStrbufIgnCaseEqualS(&terminal->processName, "urxvtd")) { detectUrxvt(terminalFont); - else + } else { return false; + } return true; } diff --git a/src/detection/terminalfont/terminalfont_windows.c b/src/detection/terminalfont/terminalfont_windows.c index 4d57c5a91..0bac1e579 100644 --- a/src/detection/terminalfont/terminalfont_windows.c +++ b/src/detection/terminalfont/terminalfont_windows.c @@ -13,64 +13,61 @@ #include #include -static const char* detectWTProfile(yyjson_val* profile, FFstrbuf* name, double* size) -{ +static const char* detectWTProfile(yyjson_val* profile, FFstrbuf* name, double* size) { yyjson_val* font = yyjson_obj_get(profile, "font"); - if (!font) + if (!font) { return "yyjson_obj_get(profile, \"font\"); failed"; + } - if (!yyjson_is_obj(font)) + if (!yyjson_is_obj(font)) { return "yyjson_is_obj(font) returns false"; + } - if (name->length == 0) - { + if (name->length == 0) { ffStrbufAppendJsonVal(name, yyjson_obj_get(font, "face")); } - if (*size < 0) - { + if (*size < 0) { yyjson_val* psize = yyjson_obj_get(font, "size"); - if (yyjson_is_num(psize)) + if (yyjson_is_num(psize)) { *size = unsafe_yyjson_get_num(psize); + } } return NULL; } -static inline void wrapYyjsonFree(yyjson_doc** doc) -{ +static inline void wrapYyjsonFree(yyjson_doc** doc) { assert(doc); - if (*doc) + if (*doc) { yyjson_doc_free(*doc); + } } -static const char* detectFromWTImpl(FFstrbuf* content, FFstrbuf* name, double* size) -{ +static const char* detectFromWTImpl(FFstrbuf* content, FFstrbuf* name, double* size) { yyjson_doc* __attribute__((__cleanup__(wrapYyjsonFree))) doc = yyjson_read_opts(content->chars, content->length, YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS, NULL, NULL); - if (!doc) + if (!doc) { return "Failed to parse WT JSON config file"; + } yyjson_val* const root = yyjson_doc_get_root(doc); assert(root); yyjson_val* profiles = yyjson_obj_get(root, "profiles"); - if (!profiles) + if (!profiles) { return "yyjson_obj_get(root, \"profiles\") failed"; + } FF_STRBUF_AUTO_DESTROY wtProfileId = ffStrbufCreateS(getenv("WT_PROFILE_ID")); ffStrbufTrim(&wtProfileId, '\''); - if (wtProfileId.length > 0) - { + if (wtProfileId.length > 0) { yyjson_val* list = yyjson_obj_get(profiles, "list"); - if (yyjson_is_arr(list)) - { + if (yyjson_is_arr(list)) { yyjson_val* profile; size_t idx, max; - yyjson_arr_foreach(list, idx, max, profile) - { + yyjson_arr_foreach (list, idx, max, profile) { yyjson_val* guid = yyjson_obj_get(profile, "guid"); - if(ffStrbufEqualS(&wtProfileId, yyjson_get_str(guid))) - { + if (ffStrbufEqualS(&wtProfileId, yyjson_get_str(guid))) { detectWTProfile(profile, name, size); break; } @@ -79,96 +76,85 @@ static const char* detectFromWTImpl(FFstrbuf* content, FFstrbuf* name, double* s } yyjson_val* defaults = yyjson_obj_get(profiles, "defaults"); - if (defaults) + if (defaults) { detectWTProfile(defaults, name, size); + } - if(name->length == 0) + if (name->length == 0) { ffStrbufSetS(name, "Cascadia Mono"); - if(*size < 0) + } + if (*size < 0) { *size = 12; + } return NULL; } -static void detectFromWindowsTerminal(const FFstrbuf* terminalExe, FFTerminalFontResult* terminalFont) -{ - //https://learn.microsoft.com/en-us/windows/terminal/install#settings-json-file +static void detectFromWindowsTerminal(const FFstrbuf* terminalExe, FFTerminalFontResult* terminalFont) { + // https://learn.microsoft.com/en-us/windows/terminal/install#settings-json-file FF_STRBUF_AUTO_DESTROY json = ffStrbufCreate(); const char* error = NULL; - if(terminalExe && ffIsAbsolutePath(terminalExe->chars)) - { + if (terminalExe && ffIsAbsolutePath(terminalExe->chars)) { FF_STRBUF_AUTO_DESTROY jsonPath = ffStrbufCreateA(MAX_PATH); ffStrbufAppendNS(&jsonPath, ffStrbufLastIndexC(terminalExe, '\\') + 1, terminalExe->chars); ffStrbufAppendS(&jsonPath, ".portable"); - if(ffPathExists(jsonPath.chars, FF_PATHTYPE_ANY)) - { + if (ffPathExists(jsonPath.chars, FF_PATHTYPE_ANY)) { ffStrbufSubstrBefore(&jsonPath, jsonPath.length - strlen(".portable")); ffStrbufAppendS(&jsonPath, "settings\\settings.json"); - if(!ffAppendFileBuffer(jsonPath.chars, &json)) + if (!ffAppendFileBuffer(jsonPath.chars, &json)) { error = "Error reading Windows Terminal portable settings JSON file"; - } - else - { + } + } else { PWSTR localAppDataW = NULL; - if(SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, NULL, &localAppDataW))) - { + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, NULL, &localAppDataW))) { ffStrbufSetWS(&jsonPath, localAppDataW); CoTaskMemFree(localAppDataW); - if(ffStrbufContainIgnCaseS(terminalExe, "_8wekyb3d8bbwe\\")) - { + if (ffStrbufContainIgnCaseS(terminalExe, "_8wekyb3d8bbwe\\")) { // Microsoft Store version - if(ffStrbufContainIgnCaseS(terminalExe, ".WindowsTerminalPreview_")) - { + if (ffStrbufContainIgnCaseS(terminalExe, ".WindowsTerminalPreview_")) { // Preview version ffStrbufAppendS(&jsonPath, "\\Packages\\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\\LocalState\\settings.json"); - if(!ffAppendFileBuffer(jsonPath.chars, &json)) + if (!ffAppendFileBuffer(jsonPath.chars, &json)) { error = "Error reading Windows Terminal Preview settings JSON file"; - } - else - { + } + } else { // Stable version ffStrbufAppendS(&jsonPath, "\\Packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\LocalState\\settings.json"); - if(!ffAppendFileBuffer(jsonPath.chars, &json)) + if (!ffAppendFileBuffer(jsonPath.chars, &json)) { error = "Error reading Windows Terminal settings JSON file"; + } } - } - else - { + } else { ffStrbufAppendS(&jsonPath, "\\Microsoft\\Windows Terminal\\settings.json"); - if(!ffAppendFileBuffer(jsonPath.chars, &json)) + if (!ffAppendFileBuffer(jsonPath.chars, &json)) { error = "Error reading Windows Terminal settings JSON file"; + } } } } } - if(!error && json.length == 0) - { - error = ffProcessAppendStdOut(&json, (char* const[]) { - "cmd.exe", - "/c", - //print the file content directly, so we don't need to handle the difference of Windows and POSIX path - "if exist %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\LocalState\\settings.json " - "( type %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\LocalState\\settings.json ) " - "else if exist %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\\LocalState\\settings.json " - "( type %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\\LocalState\\settings.json ) " - "else if exist \"%LOCALAPPDATA%\\Microsoft\\Windows Terminal\\settings.json\" " - "( type %LOCALAPPDATA%\\Microsoft\\Windows Terminal\\settings.json ) " - "else ( call )", - NULL - }); + if (!error && json.length == 0) { + error = ffProcessAppendStdOut(&json, (char* const[]) {"cmd.exe", "/c", + // print the file content directly, so we don't need to handle the difference of Windows and POSIX path + "if exist %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\LocalState\\settings.json " + "( type %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\LocalState\\settings.json ) " + "else if exist %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\\LocalState\\settings.json " + "( type %LOCALAPPDATA%\\Packages\\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\\LocalState\\settings.json ) " + "else if exist \"%LOCALAPPDATA%\\Microsoft\\Windows Terminal\\settings.json\" " + "( type %LOCALAPPDATA%\\Microsoft\\Windows Terminal\\settings.json ) " + "else ( call )", + NULL}); } - if(error) - { + if (error) { ffStrbufAppendS(&terminalFont->error, error); return; } ffStrbufTrimRight(&json, '\n'); - if(json.length == 0) - { + if (json.length == 0) { ffStrbufAppendS(&terminalFont->error, "Cannot find file \"settings.json\""); return; } @@ -177,42 +163,35 @@ static void detectFromWindowsTerminal(const FFstrbuf* terminalExe, FFTerminalFon double size = -1; error = detectFromWTImpl(&json, &name, &size); - if(error) + if (error) { ffStrbufAppendS(&terminalFont->error, error); - else - { + } else { char sizeStr[16]; snprintf(sizeStr, ARRAY_SIZE(sizeStr), "%g", size); ffFontInitValues(&terminalFont->font, name.chars, sizeStr); } } -static void detectMintty(FFTerminalFontResult* terminalFont) -{ +static void detectMintty(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); - if(!ffParsePropFileConfigValues("mintty/config", 2, (FFpropquery[]) { - {"Font=", &fontName}, - {"FontHeight=", &fontSize} - })) - ffParsePropFileConfigValues(".minttyrc", 2, (FFpropquery[]) { - {"Font=", &fontName}, - {"FontHeight=", &fontSize} - }); - if(fontName.length == 0) + if (!ffParsePropFileConfigValues("mintty/config", 2, (FFpropquery[]) {{"Font=", &fontName}, {"FontHeight=", &fontSize}})) { + ffParsePropFileConfigValues(".minttyrc", 2, (FFpropquery[]) {{"Font=", &fontName}, {"FontHeight=", &fontSize}}); + } + if (fontName.length == 0) { ffStrbufAppendS(&fontName, "Lucida Console"); - if(fontSize.length == 0) + } + if (fontSize.length == 0) { ffStrbufAppendC(&fontSize, '9'); + } ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); } -static void detectConhost(FFTerminalFontResult* terminalFont) -{ - CONSOLE_FONT_INFOEX cfi = { .cbSize = sizeof(cfi) }; - if(!GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi)) - { +static void detectConhost(FFTerminalFontResult* terminalFont) { + CONSOLE_FONT_INFOEX cfi = {.cbSize = sizeof(cfi)}; + if (!GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi)) { ffStrbufAppendS(&terminalFont->error, "GetCurrentConsoleFontEx() failed"); return; } @@ -220,70 +199,60 @@ static void detectConhost(FFTerminalFontResult* terminalFont) FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreateWS(cfi.FaceName); char fontSize[16]; - _ultoa((unsigned long)(cfi.dwFontSize.Y), fontSize, 10); + _ultoa((unsigned long) (cfi.dwFontSize.Y), fontSize, 10); ffFontInitValues(&terminalFont->font, fontName.chars, fontSize); } -static void detectConEmu(FFTerminalFontResult* terminalFont) -{ - //https://conemu.github.io/en/ConEmuXml.html#search-sequence +static void detectConEmu(FFTerminalFontResult* terminalFont) { + // https://conemu.github.io/en/ConEmuXml.html#search-sequence FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); - const char* paths[] = { "ConEmuDir", "ConEmuBaseDir", "APPDATA" }; - for (uint32_t i = 0; i < ARRAY_SIZE(paths); ++i) - { + const char* paths[] = {"ConEmuDir", "ConEmuBaseDir", "APPDATA"}; + for (uint32_t i = 0; i < ARRAY_SIZE(paths); ++i) { ffStrbufSetS(&path, getenv(paths[i])); - if(path.length > 0) - { + if (path.length > 0) { ffStrbufAppendS(&path, "/ConEmu.xml"); - if(ffParsePropFileValues(path.chars, 2, (FFpropquery[]){ - {"error, "Failed to parse ConEmu.xml"); return; } - if(fontName.length > 0) + if (fontName.length > 0) { ffStrbufSubstrBeforeLastC(&fontName, '"'); - else + } else { ffStrbufAppendS(&fontName, "Consola"); + } - if(fontSize.length > 0) + if (fontSize.length > 0) { ffStrbufSubstrBeforeLastC(&fontSize, '"'); - else + } else { ffStrbufAppendS(&fontSize, "14"); + } ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); } -static void detectWarp(FFTerminalFontResult* terminalFont) -{ +static void detectWarp(FFTerminalFontResult* terminalFont) { FF_AUTO_CLOSE_FD HANDLE key = NULL; - if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Warp.dev\\Warp", &key, &terminalFont->error)) + if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Warp.dev\\Warp", &key, &terminalFont->error)) { return; + } FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); - if (ffRegReadValues(key, 2, (FFRegValueArg[]) { - FF_ARG(fontName, L"FontName"), - FF_ARG(fontSize, L"FontSize") - }, &terminalFont->error)) - { + if (ffRegReadValues(key, 2, (FFRegValueArg[]) {FF_ARG(fontName, L"FontName"), FF_ARG(fontSize, L"FontSize")}, &terminalFont->error)) { ffStrbufTrim(&fontName, '"'); ffStrbufAppendS(&fontSize, "px"); - } - else - { + } else { ffStrbufSetS(&fontName, "Hack"); ffStrbufSetS(&fontSize, "13.0px"); } @@ -292,26 +261,27 @@ static void detectWarp(FFTerminalFontResult* terminalFont) FFstrbuf* fontWeight = (FFstrbuf*) ffListAdd(&terminalFont->font.styles); ffStrbufInit(fontWeight); - if (ffRegReadStrbuf(key, L"FontWeight", fontWeight, NULL)) + if (ffRegReadStrbuf(key, L"FontWeight", fontWeight, NULL)) { ffStrbufTrim(fontWeight, '"'); - else + } else { ffStrbufSetStatic(fontWeight, "Normal"); + } } -bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) -{ - if(ffStrbufIgnCaseEqualS(&terminal->processName, "Windows Terminal") || - ffStrbufIgnCaseEqualS(&terminal->processName, "WindowsTerminal.exe")) +bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont) { + if (ffStrbufIgnCaseEqualS(&terminal->processName, "Windows Terminal") || + ffStrbufIgnCaseEqualS(&terminal->processName, "WindowsTerminal.exe")) { detectFromWindowsTerminal(&terminal->exe, terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "mintty")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "mintty")) { detectMintty(terminalFont); - else if(ffStrbufIgnCaseEqualS(&terminal->processName, "conhost.exe")) + } else if (ffStrbufIgnCaseEqualS(&terminal->processName, "conhost.exe")) { detectConhost(terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "ConEmu")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "ConEmu")) { detectConEmu(terminalFont); - else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "warp")) + } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "warp")) { detectWarp(terminalFont); - else + } else { return false; + } return true; } diff --git a/src/detection/terminalshell/terminalshell.c b/src/detection/terminalshell/terminalshell.c index 6df1eedd1..dc5715d3a 100644 --- a/src/detection/terminalshell/terminalshell.c +++ b/src/detection/terminalshell/terminalshell.c @@ -9,134 +9,122 @@ #include #include #ifdef __FreeBSD__ - #include - #ifndef _PATH_LOCALBASE - #define _PATH_LOCALBASE "/usr/local" - #endif +# include +# ifndef _PATH_LOCALBASE +# define _PATH_LOCALBASE "/usr/local" +# endif #elif __OpenBSD__ - #define _PATH_LOCALBASE "/usr/local" +# define _PATH_LOCALBASE "/usr/local" #elif __NetBSD__ - #define _PATH_LOCALBASE "/usr/pkg" +# define _PATH_LOCALBASE "/usr/pkg" #elif _WIN32 -#include "common/windows/version.h" -#include +# include "common/windows/version.h" +# include -static bool getFileVersion(const FFstrbuf* exePath, const wchar_t* stringName, FFstrbuf* version) -{ +static bool getFileVersion(const FFstrbuf* exePath, const wchar_t* stringName, FFstrbuf* version) { wchar_t exePathW[PATH_MAX + 1]; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(exePathW, (ULONG) sizeof(exePathW), NULL, exePath->chars, (ULONG)exePath->length + 1))) + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(exePathW, (ULONG) sizeof(exePathW), NULL, exePath->chars, (ULONG) exePath->length + 1))) { return false; + } return ffGetFileVersion(exePathW, stringName, version); } #elif __HAIKU__ - #include "common/haiku/version.h" +# include "common/haiku/version.h" #endif -static bool getExeVersionRaw(FFstrbuf* exe, FFstrbuf* version) -{ - return ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "--version", - NULL - }) == NULL; +static bool getExeVersionRaw(FFstrbuf* exe, FFstrbuf* version) { + return ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "--version", NULL}) == NULL; } -static bool getExeVersionGeneral(FFstrbuf* exe, FFstrbuf* version) -{ - if(!getExeVersionRaw(exe, version)) +static bool getExeVersionGeneral(FFstrbuf* exe, FFstrbuf* version) { + if (!getExeVersionRaw(exe, version)) { return false; + } ffStrbufSubstrAfterFirstC(version, ' '); ffStrbufSubstrBeforeFirstC(version, ' '); return true; } -static bool extractBashVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void *userdata) -{ - if (!ffStrStartsWith(line, "@(#)Bash version ")) return true; +static bool extractBashVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrStartsWith(line, "@(#)Bash version ")) { + return true; + } const char* start = line + strlen("@(#)Bash version "); const char* end = strchr(start, '('); - if (!end) return true; + if (!end) { + return true; + } ffStrbufSetNS((FFstrbuf*) userdata, (uint32_t) (end - start), start); return false; } -static bool getShellVersionBash(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getShellVersionBash(FFstrbuf* exe, FFstrbuf* version) { ffBinaryExtractStrings(exe->chars, extractBashVersion, version, (uint32_t) strlen("@(#)Bash version 0.0.0(0) release GNU")); - if (version->length > 0) return true; + if (version->length > 0) { + return true; + } - if(!getExeVersionRaw(exe, version)) + if (!getExeVersionRaw(exe, version)) { return false; + } // GNU bash, version 5.1.16(1)-release (x86_64-pc-msys)\nCopyright... ffStrbufSubstrBeforeFirstC(version, '('); // GNU bash, version 5.1.16 - ffStrbufSubstrAfterLastC(version, ' '); // 5.1.16 + ffStrbufSubstrAfterLastC(version, ' '); // 5.1.16 return true; } -static bool getShellVersionFish(FFstrbuf* exe, FFstrbuf* version) -{ - if(!getExeVersionRaw(exe, version)) +static bool getShellVersionFish(FFstrbuf* exe, FFstrbuf* version) { + if (!getExeVersionRaw(exe, version)) { return false; + } - //fish, version 4.0.2-1 (Built by MSYS2 project) // version can be localized if LC_ALL is set - if (version->length < strlen("fish, v") || !ffStrbufStartsWithS(version, "fish")) return false; + // fish, version 4.0.2-1 (Built by MSYS2 project) // version can be localized if LC_ALL is set + if (version->length < strlen("fish, v") || !ffStrbufStartsWithS(version, "fish")) { + return false; + } uint32_t index = ffStrbufNextIndexC(version, strlen("fish, "), ' '); ffStrbufSubstrAfter(version, index); ffStrbufSubstrBeforeFirstC(version, ' '); return true; } -static bool getShellVersionPwsh(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getShellVersionPwsh(FFstrbuf* exe, FFstrbuf* version) { // Requires manually setting $POWERSHELL_VERSION // $env:POWERSHELL_VERSION = $PSVersionTable.PSVersion.ToString(); fastfetch.exe const char* env = getenv("POWERSHELL_VERSION"); - if (env) - { + if (env) { ffStrbufSetS(version, env); return true; } - #ifdef _WIN32 - if(getFileVersion(exe, NULL, version)) - { +#ifdef _WIN32 + if (getFileVersion(exe, NULL, version)) { ffStrbufSubstrBeforeLastC(version, '.'); return true; } - #endif +#endif - if(!getExeVersionRaw(exe, version)) + if (!getExeVersionRaw(exe, version)) { return false; + } ffStrbufSubstrAfterLastC(version, ' '); return true; } -static bool getShellVersionKsh(FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdErr(version, (char* const[]) { - exe->chars, - "--version", - NULL - }) == NULL && ffStrbufSubstrAfterFirstS(version, " (AT&T Research) ")) - { - // version sh (AT&T Research) 93u+ 2012-08-01 +static bool getShellVersionKsh(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdErr(version, (char* const[]) {exe->chars, "--version", NULL}) == NULL && ffStrbufSubstrAfterFirstS(version, " (AT&T Research) ")) { + // version sh (AT&T Research) 93u+ 2012-08-01 ffStrbufSubstrBeforeFirstC(version, ' '); return true; } ffStrbufClear(version); - if(ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "-c", - "echo $KSH_VERSION", - NULL - }) == NULL && ffStrbufSubstrAfterFirstS(version, " KSH ")) - { + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "-c", "echo $KSH_VERSION", NULL}) == NULL && ffStrbufSubstrAfterFirstS(version, " KSH ")) { // OKSH: @(#)PD KSH v5.2.14 99/07/13.2 // MKSH: @(#)MIRBSD KSH R59 2025/04/26 +Debian // $OKSH_VERSION doesn't exist on OpenBSD @@ -148,30 +136,21 @@ static bool getShellVersionKsh(FFstrbuf* exe, FFstrbuf* version) return false; } -static bool getShellVersionOksh(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getShellVersionOksh(FFstrbuf* exe, FFstrbuf* version) { // Homebrew version - if(ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "-c", - "echo $OKSH_VERSION", - NULL - }) != NULL) + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "-c", "echo $OKSH_VERSION", NULL}) != NULL) { return false; + } - //oksh 7.3 + // oksh 7.3 ffStrbufSubstrAfterFirstC(version, ' '); return true; } -static bool getShellVersionOils(FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "--version", - NULL - }) != NULL) +static bool getShellVersionOils(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "--version", NULL}) != NULL) { return false; + } // Oils 0.18.0 https://www.oilshell.org/... ffStrbufSubstrAfterFirstC(version, ' '); @@ -179,21 +158,18 @@ static bool getShellVersionOils(FFstrbuf* exe, FFstrbuf* version) return true; } -static bool getShellVersionNushell(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getShellVersionNushell(FFstrbuf* exe, FFstrbuf* version) { ffStrbufSetS(version, getenv("NU_VERSION")); - if (version->length) return true; - return getExeVersionRaw(exe, version); //0.73.0 + if (version->length) { + return true; + } + return getExeVersionRaw(exe, version); // 0.73.0 } -static bool getShellVersionAsh(FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdErr(version, (char* const[]) { - exe->chars, - "--help", - NULL - }) != NULL) +static bool getShellVersionAsh(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdErr(version, (char* const[]) {exe->chars, "--help", NULL}) != NULL) { return false; + } // BusyBox v1.36.1 (2023-11-07 18:53:09 UTC) multi-call binary... ffStrbufSubstrAfterFirstC(version, ' '); @@ -202,178 +178,181 @@ static bool getShellVersionAsh(FFstrbuf* exe, FFstrbuf* version) return true; } -static bool getShellVersionXonsh(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) -{ +static bool getShellVersionXonsh(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) { ffStrbufSetS(version, getenv("XONSH_VERSION")); - if (version->length) return true; + if (version->length) { + return true; + } // exe is python here - if(ffProcessAppendStdErr(version, (char* const[]) { - "xonsh", - "--version", - NULL - }) != NULL) + if (ffProcessAppendStdErr(version, (char* const[]) {"xonsh", "--version", NULL}) != NULL) { return false; + } // xonsh/0.14.1 ffStrbufSubstrAfterFirstC(version, '/'); return true; } -static bool extractZshVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void *userdata) -{ - if (!ffStrStartsWith(line, "zsh-")) return true; +static bool extractZshVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrStartsWith(line, "zsh-")) { + return true; + } const char* start = line + strlen("zsh-"); const char* end = strchr(start, '-'); - if (!end) return true; + if (!end) { + return true; + } ffStrbufSetNS((FFstrbuf*) userdata, (uint32_t) (end - start), start); return false; } -static bool getShellVersionZsh(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getShellVersionZsh(FFstrbuf* exe, FFstrbuf* version) { ffBinaryExtractStrings(exe->chars, extractZshVersion, version, (uint32_t) strlen("zsh-0.0-0")); - if (version->length) return true; + if (version->length) { + return true; + } - return getExeVersionGeneral(exe, version); //zsh 5.9 (arm-apple-darwin21.3.0) + return getExeVersionGeneral(exe, version); // zsh 5.9 (arm-apple-darwin21.3.0) } #ifdef _WIN32 -static bool getShellVersionWinPowerShell(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getShellVersionWinPowerShell(FFstrbuf* exe, FFstrbuf* version) { const char* env = getenv("POWERSHELL_VERSION"); - if (env) - { + if (env) { ffStrbufSetS(version, env); return true; } - return ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "-NoLogo", - "-NoProfile", - "-Command", - "$PSVersionTable.PSVersion.ToString()", - NULL - }) == NULL; + return ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "-NoLogo", "-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()", NULL}) == NULL; } #endif -bool fftsGetShellVersion(FFstrbuf* exe, const char* exeName, FFstrbuf* version) -{ - if (!instance.config.general.detectVersion) return false; - - if(ffStrEqualsIgnCase(exeName, "sh")) // #849 +bool fftsGetShellVersion(FFstrbuf* exe, const char* exeName, FFstrbuf* version) { + if (!instance.config.general.detectVersion) { return false; + } - if(ffStrEqualsIgnCase(exeName, "bash")) + if (ffStrEqualsIgnCase(exeName, "sh")) { // #849 + return false; + } + + if (ffStrEqualsIgnCase(exeName, "bash")) { return getShellVersionBash(exe, version); - if(ffStrEqualsIgnCase(exeName, "zsh")) + } + if (ffStrEqualsIgnCase(exeName, "zsh")) { return getShellVersionZsh(exe, version); - if(ffStrEqualsIgnCase(exeName, "fish")) + } + if (ffStrEqualsIgnCase(exeName, "fish")) { return getShellVersionFish(exe, version); - if(ffStrEqualsIgnCase(exeName, "pwsh")) + } + if (ffStrEqualsIgnCase(exeName, "pwsh")) { return getShellVersionPwsh(exe, version); - if(ffStrEqualsIgnCase(exeName, "csh") || ffStrEqualsIgnCase(exeName, "tcsh")) - return getExeVersionGeneral(exe, version); //tcsh 6.24.07 (Astron) 2022-12-21 (aarch64-apple-darwin) options wide,nls,dl,al,kan,sm,rh,color,filec - if(ffStrEqualsIgnCase(exeName, "nu")) + } + if (ffStrEqualsIgnCase(exeName, "csh") || ffStrEqualsIgnCase(exeName, "tcsh")) { + return getExeVersionGeneral(exe, version); // tcsh 6.24.07 (Astron) 2022-12-21 (aarch64-apple-darwin) options wide,nls,dl,al,kan,sm,rh,color,filec + } + if (ffStrEqualsIgnCase(exeName, "nu")) { return getShellVersionNushell(exe, version); - if(ffStrEqualsIgnCase(exeName, "ksh") || ffStrEqualsIgnCase(exeName, "mksh")) + } + if (ffStrEqualsIgnCase(exeName, "ksh") || ffStrEqualsIgnCase(exeName, "mksh")) { return getShellVersionKsh(exe, version); - if(ffStrEqualsIgnCase(exeName, "oksh")) + } + if (ffStrEqualsIgnCase(exeName, "oksh")) { return getShellVersionOksh(exe, version); - if(ffStrEqualsIgnCase(exeName, "oil.ovm")) + } + if (ffStrEqualsIgnCase(exeName, "oil.ovm")) { return getShellVersionOils(exe, version); - if(ffStrEqualsIgnCase(exeName, "elvish")) + } + if (ffStrEqualsIgnCase(exeName, "elvish")) { return getExeVersionRaw(exe, version); - if(ffStrEqualsIgnCase(exeName, "ash")) + } + if (ffStrEqualsIgnCase(exeName, "ash")) { return getShellVersionAsh(exe, version); - if(ffStrEqualsIgnCase(exeName, "xonsh")) + } + if (ffStrEqualsIgnCase(exeName, "xonsh")) { return getShellVersionXonsh(exe, version); - if(ffStrEqualsIgnCase(exeName, "brush")) + } + if (ffStrEqualsIgnCase(exeName, "brush")) { return getExeVersionGeneral(exe, version); // brush 0.2.23 (git:2835487) + } - #ifdef _WIN32 - if(ffStrEqualsIgnCase(exeName, "powershell") || ffStrEqualsIgnCase(exeName, "powershell_ise")) +#ifdef _WIN32 + if (ffStrEqualsIgnCase(exeName, "powershell") || ffStrEqualsIgnCase(exeName, "powershell_ise")) { return getShellVersionWinPowerShell(exe, version); + } return getFileVersion(exe, NULL, version); - #endif +#endif return false; } -FF_MAYBE_UNUSED static bool getTerminalVersionTermux(FFstrbuf* version) -{ +FF_MAYBE_UNUSED static bool getTerminalVersionTermux(FFstrbuf* version) { ffStrbufSetS(version, getenv("TERMUX_VERSION")); return version->length > 0; } -static bool extractGeneralVersion(const char *str, FF_MAYBE_UNUSED uint32_t len, void *userdata) -{ - if (!ffCharIsDigit(str[0])) return true; +static bool extractGeneralVersion(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffCharIsDigit(str[0])) { + return true; + } int count = 0; sscanf(str, "%*d.%*d.%*d%n", &count); - if (count == 0) return true; + if (count == 0) { + return true; + } ffStrbufSetS((FFstrbuf*) userdata, str); return false; } -FF_MAYBE_UNUSED static bool getTerminalVersionGnome(FFstrbuf* exe, FFstrbuf* version) -{ - if (ffIsAbsolutePath(exe->chars)) - { +FF_MAYBE_UNUSED static bool getTerminalVersionGnome(FFstrbuf* exe, FFstrbuf* version) { + if (ffIsAbsolutePath(exe->chars)) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); - if (version->length) return true; + if (version->length) { + return true; + } } - if(ffProcessAppendStdOut(version, (char* const[]){ - "gnome-terminal", - "--version", - NULL - })) return false; + if (ffProcessAppendStdOut(version, (char* const[]) {"gnome-terminal", "--version", NULL})) { + return false; + } - //# GNOME Terminal 3.46.7 using VTE 0.70.2 +BIDI +GNUTLS +ICU +SYSTEMD + // # GNOME Terminal 3.46.7 using VTE 0.70.2 +BIDI +GNUTLS +ICU +SYSTEMD ffStrbufSubstrAfterFirstS(version, "Terminal "); ffStrbufSubstrBeforeFirstC(version, ' '); return true; } -FF_MAYBE_UNUSED static bool getTerminalVersionXfce4Terminal(FFstrbuf* exe, FFstrbuf* version) -{ - if (ffIsAbsolutePath(exe->chars)) - { +FF_MAYBE_UNUSED static bool getTerminalVersionXfce4Terminal(FFstrbuf* exe, FFstrbuf* version) { + if (ffIsAbsolutePath(exe->chars)) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); - if (version->length) return true; + if (version->length) { + return true; + } } - return getExeVersionGeneral(exe, version);//xfce4-terminal 1.0.4 (Xfce 4.18)... + return getExeVersionGeneral(exe, version); // xfce4-terminal 1.0.4 (Xfce 4.18)... } -FF_MAYBE_UNUSED static bool getTerminalVersionKgx(FFstrbuf* version) -{ - if(ffProcessAppendStdOut(version, (char* const[]){ - "kgx", - "--version", - NULL - })) return false; +FF_MAYBE_UNUSED static bool getTerminalVersionKgx(FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) {"kgx", "--version", NULL})) { + return false; + } - //# KGX 45.0 using VTE 0.74.0 +BIDI +GNUTLS +ICU +SYSTEMD + // # KGX 45.0 using VTE 0.74.0 +BIDI +GNUTLS +ICU +SYSTEMD ffStrbufSubstrAfterFirstS(version, "KGX "); ffStrbufSubstrBeforeFirstC(version, ' '); return true; } -FF_MAYBE_UNUSED static bool getTerminalVersionKonsole(FFstrbuf* exe, FFstrbuf* version) -{ +FF_MAYBE_UNUSED static bool getTerminalVersionKonsole(FFstrbuf* exe, FFstrbuf* version) { const char* konsoleVersion = getenv("KONSOLE_VERSION"); - if(konsoleVersion) - { - //221201 + if (konsoleVersion) { + // 221201 long major = strtol(konsoleVersion, NULL, 10); - if (major >= 0) - { + if (major >= 0) { long patch = major % 100; major /= 100; long minor = major % 100; @@ -386,192 +365,177 @@ FF_MAYBE_UNUSED static bool getTerminalVersionKonsole(FFstrbuf* exe, FFstrbuf* v return getExeVersionGeneral(exe, version); } -FF_MAYBE_UNUSED static bool getTerminalVersionFoot(FFstrbuf* exe, FFstrbuf* version) -{ +FF_MAYBE_UNUSED static bool getTerminalVersionFoot(FFstrbuf* exe, FFstrbuf* version) { uint32_t major = 0, minor = 0, patch = 0; - if (ffGetTerminalResponse("\e[>c", 3, "\e[>1;%2u%2u%2u;0c", &major, &minor, &patch) == NULL) - { + if (ffGetTerminalResponse("\e[>c", 3, "\e[>1;%2u%2u%2u;0c", &major, &minor, &patch) == NULL) { ffStrbufSetF(version, "%u.%u.%u", major, minor, patch); return true; } - if(!getExeVersionRaw(exe, version)) return false; + if (!getExeVersionRaw(exe, version)) { + return false; + } - //foot version: 1.13.1 -pgo +ime -graphemes -assertions + // foot version: 1.13.1 -pgo +ime -graphemes -assertions ffStrbufSubstrAfterFirstS(version, "version: "); ffStrbufSubstrBeforeFirstC(version, ' '); return true; } -FF_MAYBE_UNUSED static bool getTerminalVersionMateTerminal(FFstrbuf* exe, FFstrbuf* version) -{ +FF_MAYBE_UNUSED static bool getTerminalVersionMateTerminal(FFstrbuf* exe, FFstrbuf* version) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); - if (version->length > 0) return true; + if (version->length > 0) { + return true; + } - if(!getExeVersionRaw(exe, version)) return false; + if (!getExeVersionRaw(exe, version)) { + return false; + } - //MATE Terminal 1.26.1 + // MATE Terminal 1.26.1 ffStrbufSubstrAfterLastC(version, ' '); return version->length > 0; } -FF_MAYBE_UNUSED static bool getTerminalVersionCockpit(FFstrbuf* exe, FFstrbuf* version) -{ - if(!getExeVersionRaw(exe, version)) return false; +FF_MAYBE_UNUSED static bool getTerminalVersionCockpit(FFstrbuf* exe, FFstrbuf* version) { + if (!getExeVersionRaw(exe, version)) { + return false; + } - //Version: 295\n... + // Version: 295\n... ffStrbufSubstrBeforeFirstC(version, '\n'); ffStrbufSubstrAfterFirstC(version, ' '); return version->length > 0; } -FF_MAYBE_UNUSED static bool getTerminalVersionXterm(FFstrbuf* exe, FFstrbuf* version) -{ +FF_MAYBE_UNUSED static bool getTerminalVersionXterm(FFstrbuf* exe, FFstrbuf* version) { ffStrbufSetS(version, getenv("XTERM_VERSION")); - if (!version->length) - { - if(ffProcessAppendStdOut(version, (char* const[]){ - exe->chars, - "-v", - NULL - })) return false; + if (!version->length) { + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "-v", NULL})) { + return false; + } } - //xterm(273) + // xterm(273) ffStrbufTrimRight(version, ')'); ffStrbufSubstrAfterFirstC(version, '('); return version->length > 0; } -FF_MAYBE_UNUSED static bool getTerminalVersionBlackbox(FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdOut(version, (char* const[]){ - exe->chars, - "--version", - NULL - })) return false; +FF_MAYBE_UNUSED static bool getTerminalVersionBlackbox(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "--version", NULL})) { + return false; + } - //BlackBox version 0.14.0 (flatpak) + // BlackBox version 0.14.0 (flatpak) ffStrbufSubstrAfterFirstS(version, "version "); ffStrbufSubstrBeforeFirstC(version, ' '); return version->length > 0; } -FF_MAYBE_UNUSED static bool getTerminalVersionUrxvt(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdErr(version, (char* const[]){ - "urxvt", // Don't use exe because of urxvtd - "-invalid", - NULL - })) return false; +FF_MAYBE_UNUSED static bool getTerminalVersionUrxvt(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdErr(version, (char* const[]) {"urxvt", // Don't use exe because of urxvtd + "-invalid", + NULL})) { + return false; + } - //urxvt: "invalid": unknown or malformed option. - //rxvt-unicode (urxvt) v9.31 - released: 2023-01-02 + // urxvt: "invalid": unknown or malformed option. + // rxvt-unicode (urxvt) v9.31 - released: 2023-01-02 ffStrbufSubstrAfterFirstS(version, "(urxvt) v"); ffStrbufSubstrBeforeFirstC(version, ' '); return version->length > 0; } -FF_MAYBE_UNUSED static bool getTerminalVersionSt(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdErr(version, (char* const[]){ - exe->chars, - "-v", - NULL - })) return false; +FF_MAYBE_UNUSED static bool getTerminalVersionSt(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdErr(version, (char* const[]) {exe->chars, "-v", NULL})) { + return false; + } - //st 0.9 + // st 0.9 ffStrbufSubstrAfterFirstC(version, ' '); return version->length > 0; } -FF_MAYBE_UNUSED static bool getTerminalVersionLxterminal(FFstrbuf* exe, FFstrbuf* version) -{ - if(!getExeVersionRaw(exe, version)) return false; +FF_MAYBE_UNUSED static bool getTerminalVersionLxterminal(FFstrbuf* exe, FFstrbuf* version) { + if (!getExeVersionRaw(exe, version)) { + return false; + } // lxterminal 0.3.2 ffStrbufSubstrAfterFirstC(version, ' '); return version->length > 0; } -FF_MAYBE_UNUSED static bool getTerminalVersionWeston(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) -{ +FF_MAYBE_UNUSED static bool getTerminalVersionWeston(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) { // weston-terminal doesn't report a version, use weston version instead - if(ffProcessAppendStdOut(version, (char* const[]){ - "weston", - "--version", - NULL - })) return false; + if (ffProcessAppendStdOut(version, (char* const[]) {"weston", "--version", NULL})) { + return false; + } - //weston 8.0.0 + // weston 8.0.0 ffStrbufSubstrAfterFirstC(version, ' '); return version->length > 0; } -static bool getTerminalVersionContour(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getTerminalVersionContour(FFstrbuf* exe, FFstrbuf* version) { const char* env = getenv("TERMINAL_VERSION_STRING"); - if (env) - { + if (env) { ffStrbufAppendS(version, env); return true; } - if(!getExeVersionRaw(exe, version)) return false; + if (!getExeVersionRaw(exe, version)) { + return false; + } // Contour Terminal Emulator 0.3.12.262 ffStrbufSubstrAfterLastC(version, ' '); return version->length > 0; } -static bool getTerminalVersionScreen(FFstrbuf* exe, FFstrbuf* version) -{ - if(!getExeVersionRaw(exe, version)) return false; +static bool getTerminalVersionScreen(FFstrbuf* exe, FFstrbuf* version) { + if (!getExeVersionRaw(exe, version)) { + return false; + } // Screen version 4.09.01 (GNU) 20-Aug-23 ffStrbufSubstrAfter(version, (uint32_t) strlen("Screen version ") - 1); ffStrbufSubstrBeforeFirstC(version, ' '); return version->length > 0; } -static bool getTerminalVersionTmux(FFstrbuf* exe, FFstrbuf* version) -{ - if (ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "-V", - NULL - }) != NULL) +static bool getTerminalVersionTmux(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "-V", NULL}) != NULL) { return false; + } // tmux 3.4 ffStrbufSubstrAfterFirstC(version, ' '); return version->length > 0; } -static bool getTerminalVersionZellij(FFstrbuf* exe, FFstrbuf* version) -{ - if(!getExeVersionRaw(exe, version)) return false; +static bool getTerminalVersionZellij(FFstrbuf* exe, FFstrbuf* version) { + if (!getExeVersionRaw(exe, version)) { + return false; + } // zellij 0.39.2 ffStrbufSubstrAfterFirstC(version, ' '); return version->length > 0; } -static bool getTerminalVersionZed(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getTerminalVersionZed(FFstrbuf* exe, FFstrbuf* version) { FF_STRBUF_AUTO_DESTROY cli = ffStrbufCreateCopy(exe); ffStrbufSubstrBeforeLastC(&cli, '/'); ffStrbufAppendS(&cli, "/cli" - #ifdef _WIN32 - ".exe" - #endif +#ifdef _WIN32 + ".exe" +#endif ); - if(ffProcessAppendStdOut(version, (char* const[]) { - cli.chars, - "--version", - NULL - }) != NULL) + if (ffProcessAppendStdOut(version, (char* const[]) {cli.chars, "--version", NULL}) != NULL) { return false; + } // Zed 0.142.6 – /Applications/Zed.app ffStrbufSubstrAfterFirstC(version, ' '); @@ -579,37 +543,40 @@ static bool getTerminalVersionZed(FFstrbuf* exe, FFstrbuf* version) return true; } -static bool extractSshdVersion(const char *str, FF_MAYBE_UNUSED uint32_t len, void *userdata) -{ - if (!ffStrStartsWith(str, "OpenSSH_") || !ffCharIsDigit(str[strlen("OpenSSH_")])) return true; +static bool extractSshdVersion(const char* str, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrStartsWith(str, "OpenSSH_") || !ffCharIsDigit(str[strlen("OpenSSH_")])) { + return true; + } str += strlen("OpenSSH_"); int count = 0; sscanf(str, "%*d.%*dp%*d%n", &count); - if (count == 0) return true; + if (count == 0) { + return true; + } ffStrbufSetS((FFstrbuf*) userdata, str); return false; } -static bool getTerminalVersionSshd(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getTerminalVersionSshd(FFstrbuf* exe, FFstrbuf* version) { FF_STRBUF_AUTO_DESTROY exePath = ffStrbufCreate(); - if (ffIsAbsolutePath(exe->chars)) + if (ffIsAbsolutePath(exe->chars)) { ffStrbufSet(&exePath, exe); - else if (ffFindExecutableInPath("sshd", &exePath) != NULL) + } else if (ffFindExecutableInPath("sshd", &exePath) != NULL) { return false; + } ffBinaryExtractStrings(exePath.chars, extractSshdVersion, version, (uint32_t) strlen("OpenSSH0.0")); - if (version->length) return true; + if (version->length) { + return true; + } - if(ffProcessAppendStdOut(version, (char* const[]) { - exePath.chars, - "-V", - NULL - }) != NULL) + if (ffProcessAppendStdOut(version, (char* const[]) {exePath.chars, "-V", NULL}) != NULL) { return false; + } - if (ffStrbufStartsWithS(version, "unknown ")) // `unknown option -- V` (ancient OpenSSH version) + if (ffStrbufStartsWithS(version, "unknown ")) { // `unknown option -- V` (ancient OpenSSH version) ffStrbufSubstrAfterFirstC(version, '\n'); + } // OpenSSH_10.0p2 Ubuntu-5ubuntu5, OpenSSL 3.5.3 16 Sep 2025 ffStrbufSubstrAfterFirstC(version, '_'); @@ -618,57 +585,48 @@ static bool getTerminalVersionSshd(FFstrbuf* exe, FFstrbuf* version) } #ifndef _WIN32 -static bool getTerminalVersionKitty(FFstrbuf* exe, FFstrbuf* version) -{ - #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__GNU__) +static bool getTerminalVersionKitty(FFstrbuf* exe, FFstrbuf* version) { +# if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__GNU__) char buffer[1024] = {}; if ( - #if __linux__ || __GNU__ +# 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 +# else ffReadFileData(_PATH_LOCALBASE "/share/kitty/kitty/constants.py", ARRAY_SIZE(buffer) - 1, buffer) - #endif - ) - { +# endif + ) { // Starts from version 0.17.0 // https://github.com/kovidgoyal/kitty/blob/master/kitty/constants.py#L25 const char* p = memmem(buffer, ARRAY_SIZE(buffer) - 1, "version: Version = Version(", strlen("version: Version = Version(")); - if (p) - { + if (p) { p += strlen("version: Version = Version("); int major, minor, patch; - if (sscanf(p, "%d,%d,%d", &major, &minor, &patch) == 3) - { + if (sscanf(p, "%d,%d,%d", &major, &minor, &patch) == 3) { ffStrbufSetF(version, "%d.%d.%d", major, minor, patch); return true; } } } - #elif __APPLE__ - if (ffStrbufEndsWithS(exe, "/kitty.app/Contents/MacOS/kitty")) - { +# elif __APPLE__ + if (ffStrbufEndsWithS(exe, "/kitty.app/Contents/MacOS/kitty")) { ffStrbufSet(version, exe); ffStrbufSubstrBeforeLastC(version, '/'); ffStrbufSubstrBeforeLastC(version, '/'); ffStrbufAppendS(version, "/Info.plist"); char buf[4096]; ssize_t size = ffReadFileData(version->chars, ARRAY_SIZE(buf) - 1, buf); - if (size > 0) - { + if (size > 0) { buf[size] = '\0'; const char* p = strstr(buf, "CFBundleShortVersionString"); - if (p) - { + if (p) { p += strlen("CFBundleShortVersionString"); p = strchr(p, '>'); - if (p) - { + if (p) { p++; const char* end = strchr(p, '<'); - if (end) - { + if (end) { ffStrbufSetNS(version, (uint32_t) (end - p), p); return true; } @@ -677,60 +635,55 @@ static bool getTerminalVersionKitty(FFstrbuf* exe, FFstrbuf* version) } ffStrbufClear(version); } - #endif +# endif char versionHex[64]; // https://github.com/fastfetch-cli/fastfetch/discussions/1030#discussioncomment-9845233 if (ffGetTerminalResponse( - "\eP+q6b697474792d71756572792d76657273696f6e\e\\", // kitty-query-version - 1, - "\eP1+r%*[^=]=%63[^\e]\e\\\\", versionHex) == NULL) - { + "\eP+q6b697474792d71756572792d76657273696f6e\e\\", // kitty-query-version + 1, + "\eP1+r%*[^=]=%63[^\e]\e\\\\", + versionHex) == NULL) { // decode hex string - for (const char* p = versionHex; p[0] && p[1]; p += 2) - { + for (const char* p = versionHex; p[0] && p[1]; p += 2) { unsigned value; - if (sscanf(p, "%2x", &value) == 1) + if (sscanf(p, "%2x", &value) == 1) { ffStrbufAppendC(version, (char) value); + } } return true; } - //kitty 0.21.2 created by Kovid Goyal + // kitty 0.21.2 created by Kovid Goyal return getExeVersionGeneral(exe, version); } -FF_MAYBE_UNUSED static bool getTerminalVersionPtyxis(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdOut(version, (char* const[]) { - "ptyxis", - "--version", - NULL - }) != NULL) +FF_MAYBE_UNUSED static bool getTerminalVersionPtyxis(FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) {"ptyxis", "--version", NULL}) != NULL) { return false; + } ffStrbufSubstrBeforeFirstC(version, '\n'); ffStrbufSubstrAfterFirstC(version, ' '); return true; } -FF_MAYBE_UNUSED static bool getTerminalVersionTilix(FFstrbuf* exe, FFstrbuf* version) -{ - if (ffIsAbsolutePath(exe->chars)) - { +FF_MAYBE_UNUSED static bool getTerminalVersionTilix(FFstrbuf* exe, FFstrbuf* version) { + if (ffIsAbsolutePath(exe->chars)) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); - if (version->length) return true; + if (version->length) { + return true; + } } - if(ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "--version", - NULL - }) != NULL) + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "--version", NULL}) != NULL) { return false; + } uint32_t index = ffStrbufFirstIndexS(version, "Tilix version: "); - if (index == version->length) return false; + if (index == version->length) { + return false; + } index += (uint32_t) strlen("Tilix version:"); uint32_t end = ffStrbufNextIndexC(version, index, '\n'); @@ -740,27 +693,19 @@ FF_MAYBE_UNUSED static bool getTerminalVersionTilix(FFstrbuf* exe, FFstrbuf* ver return true; } -FF_MAYBE_UNUSED static bool getTerminalVersionSakura(FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdErr(version, (char* const[]) { - exe->chars, - "--version", - NULL - }) != NULL) // sakura version is 3.8.8 +FF_MAYBE_UNUSED static bool getTerminalVersionSakura(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdErr(version, (char* const[]) {exe->chars, "--version", NULL}) != NULL) { // sakura version is 3.8.8 return false; + } ffStrbufSubstrAfterLastC(version, ' '); return true; } -FF_MAYBE_UNUSED static bool getTerminalVersionTermite(FFstrbuf* exe, FFstrbuf* version) -{ - if(ffProcessAppendStdOut(version, (char* const[]) { - exe->chars, - "--version", - NULL - }) != NULL) // termite v16.9\nvte 0.78.1 +BIDI +GNUTLS +ICU +SYSTEMD +FF_MAYBE_UNUSED static bool getTerminalVersionTermite(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) {exe->chars, "--version", NULL}) != NULL) { // termite v16.9\nvte 0.78.1 +BIDI +GNUTLS +ICU +SYSTEMD return false; + } ffStrbufSubstrBeforeFirstC(version, '\n'); ffStrbufSubstrAfterLastC(version, 'v'); @@ -770,14 +715,12 @@ FF_MAYBE_UNUSED static bool getTerminalVersionTermite(FFstrbuf* exe, FFstrbuf* v #ifdef _WIN32 -static bool getTerminalVersionWindowsTerminal(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getTerminalVersionWindowsTerminal(FFstrbuf* exe, FFstrbuf* version) { FF_STRBUF_AUTO_DESTROY buildInfoPath; ffStrbufInitNS(&buildInfoPath, ffStrbufLastIndexC(exe, '\\') + 1, exe->chars); ffStrbufAppendS(&buildInfoPath, "BuildInfo.xml"); - if(ffParsePropFile(buildInfoPath.chars, "StoreVersion=\"", version)) - { + if (ffParsePropFile(buildInfoPath.chars, "StoreVersion=\"", version)) { ffStrbufTrimRight(version, '"'); return true; } @@ -785,159 +728,188 @@ static bool getTerminalVersionWindowsTerminal(FFstrbuf* exe, FFstrbuf* version) return getFileVersion(exe, NULL, version); } -static bool getTerminalVersionConEmu(FFstrbuf* exe, FFstrbuf* version) -{ +static bool getTerminalVersionConEmu(FFstrbuf* exe, FFstrbuf* version) { ffStrbufSetS(version, getenv("ConEmuBuild")); - if(version->length) + if (version->length) { return true; + } return getFileVersion(exe, NULL, version); } #endif -bool fftsGetTerminalVersion(FFstrbuf* processName, FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) -{ - if (!instance.config.general.detectVersion) return false; +bool fftsGetTerminalVersion(FFstrbuf* processName, FF_MAYBE_UNUSED FFstrbuf* exe, FFstrbuf* version) { + if (!instance.config.general.detectVersion) { + return false; + } - #ifdef __ANDROID__ +#ifdef __ANDROID__ - if(ffStrbufEqualS(processName, "com.termux")) + if (ffStrbufEqualS(processName, "com.termux")) { return getTerminalVersionTermux(version); + } - #endif +#endif - #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__sun) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__sun) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) - if(ffStrbufStartsWithIgnCaseS(processName, "gnome-terminal")) + if (ffStrbufStartsWithIgnCaseS(processName, "gnome-terminal")) { return getTerminalVersionGnome(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "konsole")) + if (ffStrbufIgnCaseEqualS(processName, "konsole")) { return getTerminalVersionKonsole(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "yakuake")) + if (ffStrbufIgnCaseEqualS(processName, "yakuake")) { return getTerminalVersionKonsole(exe, version); // yakuake shares code with konsole + } - if(ffStrbufIgnCaseEqualS(processName, "xfce4-terminal")) + if (ffStrbufIgnCaseEqualS(processName, "xfce4-terminal")) { return getTerminalVersionXfce4Terminal(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "terminator")) - return getExeVersionGeneral(exe, version);//terminator 2.1.3 + if (ffStrbufIgnCaseEqualS(processName, "terminator")) { + return getExeVersionGeneral(exe, version); // terminator 2.1.3 + } - if(ffStrbufIgnCaseEqualS(processName, "deepin-terminal")) - return getExeVersionGeneral(exe, version);//deepin-terminal 5.4.36 + if (ffStrbufIgnCaseEqualS(processName, "deepin-terminal")) { + return getExeVersionGeneral(exe, version); // deepin-terminal 5.4.36 + } - if(ffStrbufIgnCaseEqualS(processName, "foot")) + if (ffStrbufIgnCaseEqualS(processName, "foot")) { return getTerminalVersionFoot(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "qterminal")) - return getExeVersionRaw(exe, version); //1.2.0 + if (ffStrbufIgnCaseEqualS(processName, "qterminal")) { + return getExeVersionRaw(exe, version); // 1.2.0 + } - if(ffStrbufIgnCaseEqualS(processName, "mate-terminal")) + if (ffStrbufIgnCaseEqualS(processName, "mate-terminal")) { return getTerminalVersionMateTerminal(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "cockpit-bridge")) + if (ffStrbufIgnCaseEqualS(processName, "cockpit-bridge")) { return getTerminalVersionCockpit(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "xterm")) + if (ffStrbufIgnCaseEqualS(processName, "xterm")) { return getTerminalVersionXterm(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "blackbox")) + if (ffStrbufIgnCaseEqualS(processName, "blackbox")) { return getTerminalVersionBlackbox(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "st")) + if (ffStrbufIgnCaseEqualS(processName, "st")) { return getTerminalVersionSt(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "lxterminal")) + if (ffStrbufIgnCaseEqualS(processName, "lxterminal")) { return getTerminalVersionLxterminal(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "weston-terminal")) + if (ffStrbufIgnCaseEqualS(processName, "weston-terminal")) { return getTerminalVersionWeston(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "urxvt") || + if (ffStrbufIgnCaseEqualS(processName, "urxvt") || ffStrbufIgnCaseEqualS(processName, "urxvtd") || ffStrbufIgnCaseEqualS(processName, "rxvt") || - ffStrbufIgnCaseEqualS(processName, "rxvt-unicode") - ) + ffStrbufIgnCaseEqualS(processName, "rxvt-unicode")) { return getTerminalVersionUrxvt(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "ptyxis-agent")) + if (ffStrbufIgnCaseEqualS(processName, "ptyxis-agent")) { return getTerminalVersionPtyxis(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "tilix")) + if (ffStrbufIgnCaseEqualS(processName, "tilix")) { return getTerminalVersionTilix(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "sakura")) + if (ffStrbufIgnCaseEqualS(processName, "sakura")) { return getTerminalVersionSakura(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "termite")) + if (ffStrbufIgnCaseEqualS(processName, "termite")) { return getTerminalVersionTermite(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "cosmic-term")) + if (ffStrbufIgnCaseEqualS(processName, "cosmic-term")) { return getTerminalVersionTmux(exe, version); + } - #endif +#endif - #ifdef _WIN32 +#ifdef _WIN32 - if(ffStrbufIgnCaseEqualS(processName, "WindowsTerminal.exe")) + if (ffStrbufIgnCaseEqualS(processName, "WindowsTerminal.exe")) { return getTerminalVersionWindowsTerminal(exe, version); + } - if(ffStrbufStartsWithIgnCaseS(processName, "ConEmu")) + if (ffStrbufStartsWithIgnCaseS(processName, "ConEmu")) { return getTerminalVersionConEmu(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "warp.exe")) + if (ffStrbufIgnCaseEqualS(processName, "warp.exe")) { return getFileVersion(exe, L"ProductVersion", version); + } - #endif +#endif - #ifndef _WIN32 +#ifndef _WIN32 - if(ffStrbufIgnCaseEqualS(processName, "kitty")) + if (ffStrbufIgnCaseEqualS(processName, "kitty")) { return getTerminalVersionKitty(exe, version); + } - if (ffStrbufIgnCaseEqualS(processName, "Tabby") && getExeVersionRaw(exe, version)) + if (ffStrbufIgnCaseEqualS(processName, "Tabby") && getExeVersionRaw(exe, version)) { return true; + } - #endif +#endif - if(ffStrbufStartsWithIgnCaseS(processName, "alacritty")) + if (ffStrbufStartsWithIgnCaseS(processName, "alacritty")) { return getExeVersionGeneral(exe, version); + } - if(ffStrbufStartsWithIgnCaseS(processName, "contour")) + if (ffStrbufStartsWithIgnCaseS(processName, "contour")) { return getTerminalVersionContour(exe, version); + } - if(ffStrbufStartsWithIgnCaseS(processName, "screen")) + if (ffStrbufStartsWithIgnCaseS(processName, "screen")) { return getTerminalVersionScreen(exe, version); + } - if(ffStrbufStartsWithIgnCaseS(processName, "zellij")) + if (ffStrbufStartsWithIgnCaseS(processName, "zellij")) { return getTerminalVersionZellij(exe, version); + } - if(ffStrbufStartsWithIgnCaseS(processName, "zed")) + if (ffStrbufStartsWithIgnCaseS(processName, "zed")) { return getTerminalVersionZed(exe, version); + } - #if __HAIKU__ - if(ffStrbufEqualS(processName, "Terminal")) +#if __HAIKU__ + if (ffStrbufEqualS(processName, "Terminal")) { return ffGetFileVersion(exe->chars, version); - #endif + } +#endif const char* termProgramVersion = getenv("TERM_PROGRAM_VERSION"); - if(termProgramVersion) - { + if (termProgramVersion) { const char* termProgram = getenv("TERM_PROGRAM"); - if(termProgram) - { - if(ffStrbufStartsWithIgnCaseS(processName, termProgram) || // processName ends with `.exe` on Windows + if (termProgram) { + if (ffStrbufStartsWithIgnCaseS(processName, termProgram) || // processName ends with `.exe` on Windows (ffStrEquals(termProgram, "vscode") && ffStrbufStartsWithIgnCaseS(processName, "code")) || - - #ifdef __APPLE__ +#ifdef __APPLE__ (ffStrEquals(termProgram, "iTerm.app") && ffStrbufStartsWithIgnCaseS(processName, "iTermServer-")) || - #elif defined(__linux__) +#elif defined(__linux__) (ffStrEquals(termProgram, "WarpTerminal") && ffStrbufEqualS(processName, "warp")) || - #endif - false - ) { +#endif + false) { ffStrbufSetS(version, termProgramVersion); return true; } @@ -945,34 +917,33 @@ bool fftsGetTerminalVersion(FFstrbuf* processName, FF_MAYBE_UNUSED FFstrbuf* exe } termProgramVersion = getenv("LC_TERMINAL_VERSION"); - if(termProgramVersion) - { + if (termProgramVersion) { const char* termProgram = getenv("LC_TERMINAL"); - if(termProgram) - { - if(ffStrbufStartsWithIgnCaseS(processName, termProgram) || // processName ends with `.exe` on Windows + if (termProgram) { + if (ffStrbufStartsWithIgnCaseS(processName, termProgram) || // processName ends with `.exe` on Windows (ffStrEquals(termProgram, "vscode") && ffStrbufStartsWithIgnCaseS(processName, "code")) || - (ffStrStartsWith(termProgram, "iTerm") && ffStrbufStartsWithIgnCaseS(processName, "iTermServer-")) - ) { + (ffStrStartsWith(termProgram, "iTerm") && ffStrbufStartsWithIgnCaseS(processName, "iTermServer-"))) { ffStrbufSetS(version, termProgramVersion); return true; } } } - if(ffStrbufStartsWithIgnCaseS(processName, "tmux")) + if (ffStrbufStartsWithIgnCaseS(processName, "tmux")) { return getTerminalVersionTmux(exe, version); + } - if(ffStrbufIgnCaseEqualS(processName, "sshd") || ffStrbufStartsWithIgnCaseS(processName, "sshd-")) + if (ffStrbufIgnCaseEqualS(processName, "sshd") || ffStrbufStartsWithIgnCaseS(processName, "sshd-")) { return getTerminalVersionSshd(exe, version); + } - #ifdef _WIN32 +#ifdef _WIN32 return getFileVersion(exe, NULL, version); - #else +#else return false; - #endif +#endif } diff --git a/src/detection/terminalshell/terminalshell.h b/src/detection/terminalshell/terminalshell.h index a2a6f23f8..85083fa12 100644 --- a/src/detection/terminalshell/terminalshell.h +++ b/src/detection/terminalshell/terminalshell.h @@ -4,12 +4,11 @@ #include "modules/terminal/option.h" #include "modules/shell/option.h" -typedef struct FFShellResult -{ +typedef struct FFShellResult { FFstrbuf processName; - FFstrbuf exe; //Actually arg0 in *nix - const char* exeName; //pointer to a char in exe - FFstrbuf exePath; //Full real path to executable file + FFstrbuf exe; // Actually arg0 in *nix + const char* exeName; // pointer to a char in exe + FFstrbuf exePath; // Full real path to executable file FFstrbuf prettyName; FFstrbuf version; uint32_t pid; @@ -17,13 +16,12 @@ typedef struct FFShellResult int32_t tty; } FFShellResult; -typedef struct FFTerminalResult -{ +typedef struct FFTerminalResult { FFstrbuf processName; FFstrbuf exe; FFstrbuf prettyName; - const char* exeName; //pointer to a char in exe - FFstrbuf exePath; //Full real path to executable file + const char* exeName; // pointer to a char in exe + FFstrbuf exePath; // Full real path to executable file FFstrbuf version; FFstrbuf tty; uint32_t pid; diff --git a/src/detection/terminalshell/terminalshell_linux.c b/src/detection/terminalshell/terminalshell_linux.c index 79fbbc6e9..38be51a82 100644 --- a/src/detection/terminalshell/terminalshell_linux.c +++ b/src/detection/terminalshell/terminalshell_linux.c @@ -9,62 +9,58 @@ #include #include -static void setExeName(FFstrbuf* exe, const char** exeName) -{ +static void setExeName(FFstrbuf* exe, const char** exeName) { assert(exe->length > 0); uint32_t lastSlashIndex = ffStrbufLastIndexC(exe, '/'); - if(lastSlashIndex < exe->length) + if (lastSlashIndex < exe->length) { *exeName = exe->chars + lastSlashIndex + 1; + } } -static pid_t getShellInfo(FFShellResult* result, pid_t pid) -{ +static pid_t getShellInfo(FFShellResult* result, pid_t pid) { pid_t ppid = 0; int32_t tty = -1; const char* userShellName = NULL; { uint32_t index = ffStrbufLastIndexC(&instance.state.platform.userShell, '/'); - if (index == instance.state.platform.userShell.length) + if (index == instance.state.platform.userShell.length) { userShellName = instance.state.platform.userShell.chars; - else + } else { userShellName = instance.state.platform.userShell.chars + index + 1; + } } - 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( + 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") || - ffStrbufEqualS(&result->processName, "strace") || - ffStrbufEqualS(&result->processName, "gdb") || - ffStrbufEqualS(&result->processName, "lldb") || - ffStrbufEqualS(&result->processName, "lldb-mi") || - ffStrbufEqualS(&result->processName, "login") || - ffStrbufEqualS(&result->processName, "ltrace") || - ffStrbufEqualS(&result->processName, "perf") || - ffStrbufEqualS(&result->processName, "guake-wrapped") || - ffStrbufEqualS(&result->processName, "time") || - ffStrbufEqualS(&result->processName, "clifm") || //https://github.com/leo-arch/clifm/issues/289 - ffStrbufEqualS(&result->processName, "valgrind") || - ffStrbufEqualS(&result->processName, "fastfetch") || //#994 - ffStrbufEqualS(&result->processName, "flashfetch") || - ffStrbufEqualS(&result->processName, "proot") || - ffStrbufEqualS(&result->processName, "script") || - #ifdef __linux__ - ffStrbufEqualS(&result->processName, "run-parts") || - #endif - ffStrbufContainS(&result->processName, "debug") || - ffStrbufContainS(&result->processName, "command-not-") || - ffStrbufEndsWithS(&result->processName, ".sh") - ) - { + 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") || + ffStrbufEqualS(&result->processName, "strace") || + ffStrbufEqualS(&result->processName, "gdb") || + ffStrbufEqualS(&result->processName, "lldb") || + ffStrbufEqualS(&result->processName, "lldb-mi") || + ffStrbufEqualS(&result->processName, "login") || + ffStrbufEqualS(&result->processName, "ltrace") || + ffStrbufEqualS(&result->processName, "perf") || + ffStrbufEqualS(&result->processName, "guake-wrapped") || + ffStrbufEqualS(&result->processName, "time") || + ffStrbufEqualS(&result->processName, "clifm") || // https://github.com/leo-arch/clifm/issues/289 + ffStrbufEqualS(&result->processName, "valgrind") || + ffStrbufEqualS(&result->processName, "fastfetch") || // #994 + ffStrbufEqualS(&result->processName, "flashfetch") || + ffStrbufEqualS(&result->processName, "proot") || + ffStrbufEqualS(&result->processName, "script") || +#ifdef __linux__ + ffStrbufEqualS(&result->processName, "run-parts") || +#endif + ffStrbufContainS(&result->processName, "debug") || + ffStrbufContainS(&result->processName, "command-not-") || + ffStrbufEndsWithS(&result->processName, ".sh")) { pid = ppid; ffStrbufClear(&result->processName); continue; @@ -80,69 +76,66 @@ static pid_t getShellInfo(FFShellResult* result, pid_t pid) return pid > 1 ? ppid : 0; } -static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid) -{ +static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid) { pid_t ppid = 0; - while (pid > 1 && ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, NULL) == NULL) - { - //Known shells + 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") || - ffStrbufEqualS(&result->processName, "ash") || - ffStrbufEqualS(&result->processName, "bash") || - ffStrbufEqualS(&result->processName, "zsh") || - ffStrbufEqualS(&result->processName, "ksh") || - ffStrbufEqualS(&result->processName, "mksh") || - ffStrbufEqualS(&result->processName, "oksh") || - ffStrbufEqualS(&result->processName, "csh") || - ffStrbufEqualS(&result->processName, "tcsh") || - ffStrbufEqualS(&result->processName, "fish") || - ffStrbufEqualS(&result->processName, "dash") || - ffStrbufEqualS(&result->processName, "pwsh") || - ffStrbufEqualS(&result->processName, "nu") || - ffStrbufEqualS(&result->processName, "git-shell") || - ffStrbufEqualS(&result->processName, "elvish") || - ffStrbufEqualS(&result->processName, "oil.ovm") || - ffStrbufEqualS(&result->processName, "xonsh") || // works in Linux but not in macOS because kernel returns `Python` in this case - ffStrbufEqualS(&result->processName, "login") || - ffStrbufEqualS(&result->processName, "clifm") || // https://github.com/leo-arch/clifm/issues/289 - ffStrbufEqualS(&result->processName, "chezmoi") || // #762 - ffStrbufEqualS(&result->processName, "proot") || - ffStrbufEqualS(&result->processName, "script") || - #ifdef __linux__ - ffStrbufStartsWithS(&result->processName, "Relay(") || // Unknown process in WSL2 + ffStrbufEqualS(&result->processName, "sudo") || + ffStrbufEqualS(&result->processName, "su") || + ffStrbufEqualS(&result->processName, "sh") || + ffStrbufEqualS(&result->processName, "ash") || + ffStrbufEqualS(&result->processName, "bash") || + ffStrbufEqualS(&result->processName, "zsh") || + ffStrbufEqualS(&result->processName, "ksh") || + ffStrbufEqualS(&result->processName, "mksh") || + ffStrbufEqualS(&result->processName, "oksh") || + ffStrbufEqualS(&result->processName, "csh") || + ffStrbufEqualS(&result->processName, "tcsh") || + ffStrbufEqualS(&result->processName, "fish") || + ffStrbufEqualS(&result->processName, "dash") || + ffStrbufEqualS(&result->processName, "pwsh") || + ffStrbufEqualS(&result->processName, "nu") || + ffStrbufEqualS(&result->processName, "git-shell") || + ffStrbufEqualS(&result->processName, "elvish") || + ffStrbufEqualS(&result->processName, "oil.ovm") || + ffStrbufEqualS(&result->processName, "xonsh") || // works in Linux but not in macOS because kernel returns `Python` in this case + ffStrbufEqualS(&result->processName, "login") || + ffStrbufEqualS(&result->processName, "clifm") || // https://github.com/leo-arch/clifm/issues/289 + ffStrbufEqualS(&result->processName, "chezmoi") || // #762 + ffStrbufEqualS(&result->processName, "proot") || + ffStrbufEqualS(&result->processName, "script") || +#ifdef __linux__ + ffStrbufStartsWithS(&result->processName, "Relay(") || // Unknown process in WSL2 ffStrbufStartsWithS(&result->processName, "flatpak-") || // #707 - ffStrbufEqualS(&result->processName, "run-parts") || // #2048 - #endif - ffStrbufEndsWithS(&result->processName, ".sh") - ) - { + ffStrbufEqualS(&result->processName, "run-parts") || // #2048 +#endif + ffStrbufEndsWithS(&result->processName, ".sh")) { pid = ppid; ffStrbufClear(&result->processName); continue; } - #ifdef __APPLE__ +#ifdef __APPLE__ // https://github.com/fastfetch-cli/fastfetch/discussions/501 const char* pLeft = strstr(result->processName.chars, " ("); - if (pLeft) - { + if (pLeft) { pLeft += 2; const char* pRight = strstr(pLeft, "term)"); - if (pRight && pRight[5] == '\0') - { - for (; pLeft < pRight; ++pLeft) - if (*pLeft < 'a' || *pLeft > 'z') + if (pRight && pRight[5] == '\0') { + for (; pLeft < pRight; ++pLeft) { + if (*pLeft < 'a' || *pLeft > 'z') { break; - if (pLeft == pRight && ffProcessGetBasicInfoLinux(ppid, &result->processName, &ppid, NULL) != NULL) + } + } + if (pLeft == pRight && ffProcessGetBasicInfoLinux(ppid, &result->processName, &ppid, NULL) != NULL) { return 0; + } } } - #endif +#endif result->pid = (uint32_t) pid; result->ppid = (uint32_t) ppid; @@ -152,16 +145,15 @@ static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid) return pid > 1 ? ppid : 0; } -static bool getTerminalInfoByPidEnv(FFTerminalResult* result, const char* pidEnv) -{ +static bool getTerminalInfoByPidEnv(FFTerminalResult* result, const char* pidEnv) { const char* envStr = getenv(pidEnv); - if (envStr == NULL) + if (envStr == NULL) { return false; + } pid_t pid = (pid_t) strtol(envStr, NULL, 10); result->pid = (uint32_t) pid; - if (ffProcessGetBasicInfoLinux(pid, &result->processName, (pid_t*) &result->ppid, NULL) == NULL) - { + if (ffProcessGetBasicInfoLinux(pid, &result->processName, (pid_t*) &result->ppid, NULL) == NULL) { ffProcessGetInfoLinux(pid, &result->processName, &result->exe, &result->exeName, &result->exePath); return true; } @@ -169,24 +161,22 @@ static bool getTerminalInfoByPidEnv(FFTerminalResult* result, const char* pidEnv return false; } -static void getTerminalFromEnv(FFTerminalResult* result) -{ - if (result->processName.length > 0) - { +static void getTerminalFromEnv(FFTerminalResult* result) { + if (result->processName.length > 0) { if (!ffStrbufStartsWithS(&result->processName, "login") && !ffStrbufEqualS(&result->processName, "(login)") && - #ifdef __APPLE__ +#ifdef __APPLE__ !ffStrbufEqualS(&result->processName, "launchd") && - #else +#else !ffStrbufEqualS(&result->processName, "systemd") && !ffStrbufEqualS(&result->processName, "init") && !ffStrbufEqualS(&result->processName, "(init)") && !ffStrbufEqualS(&result->processName, "SessionLeader") && // #750 - #endif +#endif - !ffStrbufEqualS(&result->processName, "0") - ) return; + !ffStrbufEqualS(&result->processName, "0")) + return; ffStrbufClear(&result->processName); ffStrbufClear(&result->exe); @@ -197,95 +187,93 @@ static void getTerminalFromEnv(FFTerminalResult* result) const char* term = NULL; - //SSH - if( - getenv("SSH_TTY") != NULL - ) + // SSH + if ( + getenv("SSH_TTY") != NULL) { term = getenv("SSH_TTY"); - else if( + } else if ( getenv("KITTY_PID") != NULL || - getenv("KITTY_INSTALLATION_DIR") != NULL - ) - { - if (getTerminalInfoByPidEnv(result, "KITTY_PID")) + getenv("KITTY_INSTALLATION_DIR") != NULL) { + if (getTerminalInfoByPidEnv(result, "KITTY_PID")) { return; + } term = "kitty"; } - #ifdef __linux__ // WSL - //Windows Terminal - else if( +#ifdef __linux__ // WSL + // Windows Terminal + else if ( getenv("WT_SESSION") != NULL || - getenv("WT_PROFILE_ID") != NULL - ) term = "Windows Terminal"; + getenv("WT_PROFILE_ID") != NULL) + term = "Windows Terminal"; - //ConEmu - else if( - getenv("ConEmuPID") != NULL - ) term = "ConEmu"; - #endif + // ConEmu + else if ( + getenv("ConEmuPID") != NULL) { + term = "ConEmu"; + } +#endif - //Alacritty - else if( + // Alacritty + else if ( getenv("ALACRITTY_SOCKET") != NULL || getenv("ALACRITTY_LOG") != NULL || - getenv("ALACRITTY_WINDOW_ID") != NULL - ) term = "Alacritty"; - - #ifdef __ANDROID__ - //Termux - else if( + getenv("ALACRITTY_WINDOW_ID") != NULL) { + term = "Alacritty"; + } +#ifdef __ANDROID__ + // Termux + else if ( getenv("TERMUX_VERSION") != NULL || - getenv("TERMUX_MAIN_PACKAGE_FORMAT") != NULL - ) - { - if (getTerminalInfoByPidEnv(result, "TERMUX_APP__PID")) + getenv("TERMUX_MAIN_PACKAGE_FORMAT") != NULL) { + if (getTerminalInfoByPidEnv(result, "TERMUX_APP__PID")) { return; + } term = "com.termux"; } - #endif +#endif - #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__GNU__) - //Konsole - else if( - getenv("KONSOLE_VERSION") != NULL - ) term = "konsole"; +#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__GNU__) + // Konsole + else if ( + getenv("KONSOLE_VERSION") != NULL) + term = "konsole"; - else if( + else if ( getenv("GNOME_TERMINAL_SCREEN") != NULL || - getenv("GNOME_TERMINAL_SERVICE") != NULL - ) term = "gnome-terminal"; - #endif + getenv("GNOME_TERMINAL_SERVICE") != NULL) { + term = "gnome-terminal"; + } +#endif - //MacOS, mintty - else if(getenv("TERM_PROGRAM") != NULL) + // MacOS, mintty + else if (getenv("TERM_PROGRAM") != NULL) { term = getenv("TERM_PROGRAM"); - - else if(getenv("LC_TERMINAL") != NULL) - term = getenv("LC_TERMINAL"); - - //Normal Terminal - else - { - term = getenv("TERM"); - //TTY - if(!ffStrSet(term) || ffStrEquals(term, "linux")) - term = ttyname(STDIN_FILENO); } - if(ffStrSet(term)) - { + else if (getenv("LC_TERMINAL") != NULL) { + term = getenv("LC_TERMINAL"); + } + + // Normal Terminal + else { + term = getenv("TERM"); + // TTY + if (!ffStrSet(term) || ffStrEquals(term, "linux")) { + term = ttyname(STDIN_FILENO); + } + } + + if (ffStrSet(term)) { ffStrbufSetS(&result->processName, term); ffStrbufSetS(&result->exe, term); setExeName(&result->exe, &result->exeName); } } -static void getUserShellFromEnv(FFShellResult* result) -{ - //If shell detection via processes failed - if(result->processName.length == 0 && instance.state.platform.userShell.length > 0) - { +static void getUserShellFromEnv(FFShellResult* result) { + // If shell detection via processes failed + if (result->processName.length == 0 && instance.state.platform.userShell.length > 0) { ffStrbufSet(&result->exe, &instance.state.platform.userShell); setExeName(&result->exe, &result->exeName); ffStrbufAppendS(&result->processName, result->exeName); @@ -296,115 +284,109 @@ bool fftsGetShellVersion(FFstrbuf* exe, const char* exeName, FFstrbuf* version); bool fftsGetTerminalVersion(FFstrbuf* processName, FFstrbuf* exe, FFstrbuf* version); -static void setShellInfoDetails(FFShellResult* result) -{ +static void setShellInfoDetails(FFShellResult* result) { ffStrbufClear(&result->version); fftsGetShellVersion(result->exePath.length > 0 ? &result->exePath : &result->exe, result->exeName, &result->version); - if(ffStrbufEqualS(&result->processName, "pwsh")) + if (ffStrbufEqualS(&result->processName, "pwsh")) { ffStrbufInitStatic(&result->prettyName, "PowerShell"); - else if(ffStrbufEqualS(&result->processName, "nu")) + } else if (ffStrbufEqualS(&result->processName, "nu")) { ffStrbufInitStatic(&result->prettyName, "nushell"); - else if(ffStrbufEqualS(&result->processName, "oil.ovm")) + } else if (ffStrbufEqualS(&result->processName, "oil.ovm")) { ffStrbufInitStatic(&result->prettyName, "Oils"); - else - { + } else { // https://github.com/fastfetch-cli/fastfetch/discussions/280#discussioncomment-3831734 ffStrbufInitS(&result->prettyName, result->exeName); } } -static void setTerminalInfoDetails(FFTerminalResult* result) -{ - if(ffStrbufStartsWithC(&result->processName, '.') && ffStrbufContainS(&result->processName, "-wrap")) - { +static void setTerminalInfoDetails(FFTerminalResult* result) { + if (ffStrbufStartsWithC(&result->processName, '.') && ffStrbufContainS(&result->processName, "-wrap")) { // For NixOS. Ref: #510 and https://github.com/NixOS/nixpkgs/pull/249428 // We use processName when detecting version and font, overriding it for simplification ffStrbufSubstrBeforeLastC(&result->processName, '-'); ffStrbufSubstrAfter(&result->processName, 0); } - if(ffStrbufEqualS(&result->processName, "wezterm-gui")) + if (ffStrbufEqualS(&result->processName, "wezterm-gui")) { ffStrbufInitStatic(&result->prettyName, "WezTerm"); - else if(ffStrbufStartsWithS(&result->processName, "tmux:")) + } else if (ffStrbufStartsWithS(&result->processName, "tmux:")) { ffStrbufInitStatic(&result->prettyName, "tmux"); - else if(ffStrbufStartsWithS(&result->processName, "screen-")) + } else if (ffStrbufStartsWithS(&result->processName, "screen-")) { ffStrbufInitStatic(&result->prettyName, "screen"); - else if(ffStrbufEqualS(&result->processName, "sshd") || ffStrbufStartsWithS(&result->processName, "sshd-")) - { - if (result->tty.length) + } else if (ffStrbufEqualS(&result->processName, "sshd") || ffStrbufStartsWithS(&result->processName, "sshd-")) { + if (result->tty.length) { ffStrbufInitCopy(&result->prettyName, &result->tty); - else + } else { ffStrbufSetStatic(&result->prettyName, "sshd"); + } } - #if defined(__ANDROID__) +#if defined(__ANDROID__) - else if(ffStrbufEqualS(&result->processName, "com.termux")) + else if (ffStrbufEqualS(&result->processName, "com.termux")) ffStrbufInitStatic(&result->prettyName, "Termux"); - #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__GNU__) +#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__GNU__) - else if(ffStrbufStartsWithS(&result->processName, "gnome-terminal")) + else if (ffStrbufStartsWithS(&result->processName, "gnome-terminal")) ffStrbufInitStatic(&result->prettyName, "GNOME Terminal"); - else if(ffStrbufStartsWithS(&result->processName, "kgx")) + else if (ffStrbufStartsWithS(&result->processName, "kgx")) { ffStrbufInitStatic(&result->prettyName, "GNOME Console"); - else if(ffStrbufEqualS(&result->processName, "urxvt") || + } else if (ffStrbufEqualS(&result->processName, "urxvt") || ffStrbufEqualS(&result->processName, "urxvtd") || - ffStrbufEqualS(&result->processName, "rxvt") - ) + ffStrbufEqualS(&result->processName, "rxvt")) { ffStrbufInitStatic(&result->prettyName, "rxvt-unicode"); - else if(ffStrbufStartsWithS(&result->processName, "ptyxis-agent")) + } else if (ffStrbufStartsWithS(&result->processName, "ptyxis-agent")) { ffStrbufInitStatic(&result->prettyName, "Ptyxis"); + } - #elif defined(__APPLE__) +#elif defined(__APPLE__) - else if(ffStrbufEqualS(&result->processName, "iTerm.app") || ffStrbufStartsWithS(&result->processName, "iTermServer-")) + else if (ffStrbufEqualS(&result->processName, "iTerm.app") || ffStrbufStartsWithS(&result->processName, "iTermServer-")) ffStrbufInitStatic(&result->prettyName, "iTerm"); - else if(ffStrbufEndsWithS(&result->exePath, "Terminal.app/Contents/MacOS/Terminal")) - { + else if (ffStrbufEndsWithS(&result->exePath, "Terminal.app/Contents/MacOS/Terminal")) { ffStrbufSetStatic(&result->processName, "Apple_Terminal"); // $TERM_PROGRAM, for terminal font detection ffStrbufInitStatic(&result->prettyName, "Apple Terminal"); - } - else if(ffStrbufEqualS(&result->processName, "Apple_Terminal")) + } else if (ffStrbufEqualS(&result->processName, "Apple_Terminal")) { ffStrbufInitStatic(&result->prettyName, "Apple Terminal"); - else if(ffStrbufEndsWithS(&result->exePath, "Warp.app/Contents/MacOS/stable")) - { + } else if (ffStrbufEndsWithS(&result->exePath, "Warp.app/Contents/MacOS/stable")) { ffStrbufSetStatic(&result->processName, "WarpTerminal"); // $TERM_PROGRAM, for terminal font detection ffStrbufInitStatic(&result->prettyName, "Warp"); - } - else if(ffStrbufEqualS(&result->processName, "WarpTerminal")) + } else if (ffStrbufEqualS(&result->processName, "WarpTerminal")) { ffStrbufInitStatic(&result->prettyName, "Warp"); + } - #elif defined(__HAIKU__) +#elif defined(__HAIKU__) - else if(ffStrbufEqualS(&result->processName, "Terminal")) + else if (ffStrbufEqualS(&result->processName, "Terminal")) ffStrbufInitStatic(&result->prettyName, "Haiku Terminal"); - #endif +#endif - else if(strncmp(result->exeName, result->processName.chars, result->processName.length) == 0) // if exeName starts with processName, print it. Otherwise print processName + else if (strncmp(result->exeName, result->processName.chars, result->processName.length) == 0) { // if exeName starts with processName, print it. Otherwise print processName ffStrbufInitS(&result->prettyName, result->exeName); - else + } else { ffStrbufInitCopy(&result->prettyName, &result->processName); + } fftsGetTerminalVersion(&result->processName, result->exePath.length > 0 ? &result->exePath : &result->exe, &result->version); } #if defined(MAXPATH) -#define FF_EXE_PATH_LEN MAXPATH +# define FF_EXE_PATH_LEN MAXPATH #elif defined(PATH_MAX) -#define FF_EXE_PATH_LEN PATH_MAX +# define FF_EXE_PATH_LEN PATH_MAX #else -#define FF_EXE_PATH_LEN 260 +# define FF_EXE_PATH_LEN 260 #endif -const FFShellResult* ffDetectShell() -{ +const FFShellResult* ffDetectShell() { static FFShellResult result; static bool init = false; - if(init) + if (init) { return &result; + } init = true; ffStrbufInit(&result.processName); @@ -419,8 +401,7 @@ const FFShellResult* ffDetectShell() pid_t ppid = getppid(); const char* ignoreParent = getenv("FFTS_IGNORE_PARENT"); - if (ignoreParent && ffStrEquals(ignoreParent, "1")) - { + if (ignoreParent && ffStrEquals(ignoreParent, "1")) { FF_STRBUF_AUTO_DESTROY _ = ffStrbufCreate(); ffProcessGetBasicInfoLinux(ppid, &_, &ppid, NULL); } @@ -432,12 +413,12 @@ const FFShellResult* ffDetectShell() return &result; } -const FFTerminalResult* ffDetectTerminal() -{ +const FFTerminalResult* ffDetectTerminal() { static FFTerminalResult result; static bool init = false; - if(init) + if (init) { return &result; + } init = true; ffStrbufInit(&result.processName); @@ -451,8 +432,9 @@ const FFTerminalResult* ffDetectTerminal() pid_t ppid = (pid_t) ffDetectShell()->ppid; - if (ppid) + if (ppid) { ppid = getTerminalInfo(&result, ppid); + } getTerminalFromEnv(&result); setTerminalInfoDetails(&result); diff --git a/src/detection/terminalshell/terminalshell_windows.c b/src/detection/terminalshell/terminalshell_windows.c index 9d4f3dff0..ee4deb563 100644 --- a/src/detection/terminalshell/terminalshell_windows.c +++ b/src/detection/terminalshell/terminalshell_windows.c @@ -19,32 +19,22 @@ bool fftsGetShellVersion(FFstrbuf* exe, const char* exeName, FFstrbuf* version); -static uint32_t getShellInfo(FFShellResult* result, uint32_t pid) -{ +static uint32_t getShellInfo(FFShellResult* result, uint32_t pid) { uint32_t ppid = 0; bool gui = false; - while (pid != 0 && ffProcessGetInfoWindows(pid, &ppid, &result->processName, &result->exe, &result->exeName, &result->exePath, &gui)) - { + while (pid != 0 && ffProcessGetInfoWindows(pid, &ppid, &result->processName, &result->exe, &result->exeName, &result->exePath, &gui)) { ffStrbufSet(&result->prettyName, &result->processName); - if (ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) + if (ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) { ffStrbufSubstrBefore(&result->prettyName, result->prettyName.length - 4); + } - //Common programs that are between terminal and own process, but are not the shell + // Common programs that are between terminal and own process, but are not the shell if ( - !gui && ( - ffStrbufIgnCaseEqualS(&result->prettyName, "sudo") || - ffStrbufIgnCaseEqualS(&result->prettyName, "su") || - ffStrbufIgnCaseEqualS(&result->prettyName, "gdb") || - ffStrbufIgnCaseEqualS(&result->prettyName, "lldb") || - ffStrbufIgnCaseEqualS(&result->prettyName, "lldb-dap") || - 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") || - ffStrbufContainIgnCaseS(&result->prettyName, "debug") || - ffStrbufContainIgnCaseS(&result->prettyName, "time") || - ffStrbufStartsWithIgnCaseS(&result->prettyName, "ConEmuC") // https://github.com/fastfetch-cli/fastfetch/issues/488#issuecomment-1619982014 - )) { + !gui && (ffStrbufIgnCaseEqualS(&result->prettyName, "sudo") || ffStrbufIgnCaseEqualS(&result->prettyName, "su") || ffStrbufIgnCaseEqualS(&result->prettyName, "gdb") || ffStrbufIgnCaseEqualS(&result->prettyName, "lldb") || ffStrbufIgnCaseEqualS(&result->prettyName, "lldb-dap") || 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") || ffStrbufContainIgnCaseS(&result->prettyName, "debug") || ffStrbufContainIgnCaseS(&result->prettyName, "time") || ffStrbufStartsWithIgnCaseS(&result->prettyName, "ConEmuC") // https://github.com/fastfetch-cli/fastfetch/issues/488#issuecomment-1619982014 + )) { ffStrbufClear(&result->processName); ffStrbufClear(&result->prettyName); ffStrbufClear(&result->exe); @@ -55,16 +45,14 @@ static uint32_t getShellInfo(FFShellResult* result, uint32_t pid) result->pid = pid; - if (gui) - { + if (gui) { // Started without shell // In this case, terminal process will be created by fastfetch itself. ppid = 0; - if (ffStrbufIgnCaseEqualS(&result->prettyName, "explorer")) + if (ffStrbufIgnCaseEqualS(&result->prettyName, "explorer")) { ffStrbufSetS(&result->prettyName, "Windows Explorer"); - } - else - { + } + } else { result->ppid = ppid; } @@ -73,101 +61,92 @@ static uint32_t getShellInfo(FFShellResult* result, uint32_t pid) return ppid; } -static void setShellInfoDetails(FFShellResult* result) -{ - if(ffStrbufIgnCaseEqualS(&result->prettyName, "pwsh")) +static void setShellInfoDetails(FFShellResult* result) { + if (ffStrbufIgnCaseEqualS(&result->prettyName, "pwsh")) { ffStrbufSetS(&result->prettyName, "PowerShell"); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "powershell")) + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "powershell")) { ffStrbufSetS(&result->prettyName, "Windows PowerShell"); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "powershell_ise")) + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "powershell_ise")) { ffStrbufSetS(&result->prettyName, "Windows PowerShell ISE"); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "cmd")) - { + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "cmd")) { ffStrbufSetS(&result->prettyName, "CMD"); - if (instance.config.general.detectVersion) - { + if (instance.config.general.detectVersion) { FF_AUTO_CLOSE_FD HANDLE snapshot = NULL; - while(!(snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, result->pid)) && GetLastError() == ERROR_BAD_LENGTH) {} + while (!(snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, result->pid)) && GetLastError() == ERROR_BAD_LENGTH) {} - if(snapshot) - { + if (snapshot) { MODULEENTRY32W module; module.dwSize = sizeof(module); - for(BOOL success = Module32FirstW(snapshot, &module); success; success = Module32NextW(snapshot, &module)) - { - if(wcsncmp(module.szModule, L"clink_dll_", strlen("clink_dll_")) == 0) - { + for (BOOL success = Module32FirstW(snapshot, &module); success; success = Module32NextW(snapshot, &module)) { + if (wcsncmp(module.szModule, L"clink_dll_", strlen("clink_dll_")) == 0) { FF_STRBUF_AUTO_DESTROY clinkVersion = ffStrbufCreate(); - if (ffGetFileVersion(module.szExePath, NULL, &clinkVersion)) + if (ffGetFileVersion(module.szExePath, NULL, &clinkVersion)) { ffStrbufAppendF(&result->prettyName, " (with Clink %s)", clinkVersion.chars); - else + } else { ffStrbufAppendS(&result->prettyName, " (with Clink)"); + } break; } } } } - } - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "nu")) + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "nu")) { ffStrbufSetS(&result->prettyName, "nushell"); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "explorer")) + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "explorer")) { ffStrbufSetS(&result->prettyName, "Windows Explorer"); + } } -static bool getTerminalFromEnv(FFTerminalResult* result) -{ - if( +static bool getTerminalFromEnv(FFTerminalResult* result) { + if ( result->processName.length > 0 && - ffStrbufIgnCaseCompS(&result->processName, "explorer") != 0 - ) return false; + ffStrbufIgnCaseCompS(&result->processName, "explorer") != 0) { + return false; + } const char* term = getenv("ConEmuPID"); - if(term) - { - //ConEmu + if (term) { + // ConEmu uint32_t pid = (uint32_t) strtoul(term, NULL, 10); result->pid = pid; - if(ffProcessGetInfoWindows(pid, NULL, &result->processName, &result->exe, &result->exeName, &result->exePath, NULL)) - { + if (ffProcessGetInfoWindows(pid, NULL, &result->processName, &result->exe, &result->exeName, &result->exePath, NULL)) { ffStrbufSet(&result->prettyName, &result->processName); - if(ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) + if (ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) { ffStrbufSubstrBefore(&result->prettyName, result->prettyName.length - 4); + } return true; - } - else - { + } else { term = "ConEmu"; } } - //SSH - if(getenv("SSH_TTY") != NULL) + // SSH + if (getenv("SSH_TTY") != NULL) { term = getenv("SSH_TTY"); + } - //Windows Terminal - if(!term && ( - getenv("WT_SESSION") != NULL || - getenv("WT_PROFILE_ID") != NULL - )) term = "WindowsTerminal"; + // Windows Terminal + if (!term && (getenv("WT_SESSION") != NULL || getenv("WT_PROFILE_ID") != NULL)) { + term = "WindowsTerminal"; + } - //Alacritty - if(!term && ( - getenv("ALACRITTY_SOCKET") != NULL || - getenv("ALACRITTY_LOG") != NULL || - getenv("ALACRITTY_WINDOW_ID") != NULL - )) term = "Alacritty"; + // Alacritty + if (!term && (getenv("ALACRITTY_SOCKET") != NULL || getenv("ALACRITTY_LOG") != NULL || getenv("ALACRITTY_WINDOW_ID") != NULL)) { + term = "Alacritty"; + } - if(!term) + if (!term) { term = getenv("TERM_PROGRAM"); + } - //Normal Terminal - if(!term) + // Normal Terminal + if (!term) { term = getenv("TERM"); + } - if(term) - { + if (term) { ffStrbufSetS(&result->processName, term); ffStrbufSetS(&result->prettyName, term); ffStrbufSetS(&result->exe, term); @@ -178,33 +157,27 @@ static bool getTerminalFromEnv(FFTerminalResult* result) return false; } -static bool detectDefaultTerminal(FFTerminalResult* result) -{ +static bool detectDefaultTerminal(FFTerminalResult* result) { wchar_t regPath[128] = L"SOFTWARE\\Classes\\PackagedCom\\ClassIndex\\"; wchar_t* uuid = regPath + strlen("SOFTWARE\\Classes\\PackagedCom\\ClassIndex\\"); DWORD bufSize = 80; - if (RegGetValueW(HKEY_CURRENT_USER, L"Console\\%%Startup", L"DelegationTerminal", RRF_RT_REG_SZ, NULL, uuid, &bufSize) == ERROR_SUCCESS) - { - if(wcscmp(uuid, L"{00000000-0000-0000-0000-000000000000}") == 0 || // Let Windows decide - wcscmp(uuid, L"{B23D10C0-E52E-411E-9D5B-C09FDF709C7D}") == 0) // Conhost + if (RegGetValueW(HKEY_CURRENT_USER, L"Console\\%%Startup", L"DelegationTerminal", RRF_RT_REG_SZ, NULL, uuid, &bufSize) == ERROR_SUCCESS) { + if (wcscmp(uuid, L"{00000000-0000-0000-0000-000000000000}") == 0 || // Let Windows decide + wcscmp(uuid, L"{B23D10C0-E52E-411E-9D5B-C09FDF709C7D}") == 0) // Conhost { goto conhost; } FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regPath, &hKey, NULL)) - { + if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regPath, &hKey, NULL)) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); - if(ffRegGetSubKey(hKey, 0, &path, NULL)) - { - if (ffStrbufStartsWithS(&path, "Microsoft.WindowsTerminal")) - { + if (ffRegGetSubKey(hKey, 0, &path, NULL)) { + if (ffStrbufStartsWithS(&path, "Microsoft.WindowsTerminal")) { ffStrbufSetS(&result->processName, "WindowsTerminal.exe"); ffStrbufSetS(&result->prettyName, "WindowsTerminal"); PWSTR programFiles = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, NULL, &programFiles))) - { + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, NULL, &programFiles))) { ffStrbufSetWS(&result->exe, programFiles); CoTaskMemFree(programFiles); programFiles = NULL; @@ -213,13 +186,10 @@ static bool detectDefaultTerminal(FFTerminalResult* result) ffStrbufAppend(&result->exe, &path); ffStrbufAppendS(&result->exe, "\\WindowsTerminal.exe"); - if(ffPathExists(result->exe.chars, FF_PATHTYPE_FILE)) - { + if (ffPathExists(result->exe.chars, FF_PATHTYPE_FILE)) { result->exeName = result->exe.chars + ffStrbufLastIndexC(&result->exe, '\\') + 1; ffStrbufSet(&result->exePath, &result->exe); - } - else - { + } else { ffStrbufDestroy(&result->exe); ffStrbufInitMove(&result->exe, &path); result->exeName = ""; @@ -234,14 +204,13 @@ static bool detectDefaultTerminal(FFTerminalResult* result) conhost:; ULONG_PTR conhostPid = 0; ULONG size; - if(NT_SUCCESS(NtQueryInformationProcess(NtCurrentProcess(), ProcessConsoleHostProcess, &conhostPid, sizeof(conhostPid), &size)) && conhostPid != 0) - { + if (NT_SUCCESS(NtQueryInformationProcess(NtCurrentProcess(), ProcessConsoleHostProcess, &conhostPid, sizeof(conhostPid), &size)) && conhostPid != 0) { // For Windows Terminal, it reports the PID of OpenConsole - if(ffProcessGetInfoWindows((uint32_t) conhostPid, NULL, &result->processName, &result->exe, &result->exeName, &result->exePath, NULL)) - { + if (ffProcessGetInfoWindows((uint32_t) conhostPid, NULL, &result->processName, &result->exe, &result->exeName, &result->exePath, NULL)) { ffStrbufSet(&result->prettyName, &result->processName); - if(ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) + if (ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) { ffStrbufSubstrBefore(&result->prettyName, result->prettyName.length - 4); + } return true; } } @@ -250,10 +219,8 @@ conhost:; return false; } -static uint32_t getTerminalInfo(FFTerminalResult* result, uint32_t pid) -{ - if (getenv("MSYSTEM")) - { +static uint32_t getTerminalInfo(FFTerminalResult* result, uint32_t pid) { + if (getenv("MSYSTEM")) { // Don't try to detect terminals in MSYS shell // It won't work because MSYS doesn't follow process tree of native Windows programs return 0; @@ -262,11 +229,9 @@ static uint32_t getTerminalInfo(FFTerminalResult* result, uint32_t pid) uint32_t ppid = 0; bool gui; - while (pid != 0 && ffProcessGetInfoWindows(pid, &ppid, &result->processName, &result->exe, &result->exeName, &result->exePath, &gui)) - { - if (!gui) - { - //We are in nested shell + while (pid != 0 && ffProcessGetInfoWindows(pid, &ppid, &result->processName, &result->exe, &result->exeName, &result->exePath, &gui)) { + if (!gui) { + // We are in nested shell ffStrbufClear(&result->processName); ffStrbufClear(&result->prettyName); ffStrbufClear(&result->exe); @@ -277,13 +242,13 @@ static uint32_t getTerminalInfo(FFTerminalResult* result, uint32_t pid) } ffStrbufSet(&result->prettyName, &result->processName); - if(ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) + if (ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) { ffStrbufSubstrBefore(&result->prettyName, result->prettyName.length - 4); + } - if(ffStrbufIgnCaseEqualS(&result->prettyName, "sihost") || - ffStrbufIgnCaseEqualS(&result->prettyName, "explorer") || - ffStrbufIgnCaseEqualS(&result->prettyName, "wininit") - ) { + if (ffStrbufIgnCaseEqualS(&result->prettyName, "sihost") || + ffStrbufIgnCaseEqualS(&result->prettyName, "explorer") || + ffStrbufIgnCaseEqualS(&result->prettyName, "wininit")) { // A CUI program created by Windows Explorer will spawn a conhost as its child. // However the conhost process is just a placeholder; // The true terminal can be Windows Terminal or others. @@ -293,9 +258,7 @@ static uint32_t getTerminalInfo(FFTerminalResult* result, uint32_t pid) ffStrbufClear(&result->exePath); result->exeName = ""; return 0; - } - else - { + } else { result->pid = pid; result->ppid = ppid; } @@ -305,36 +268,33 @@ static uint32_t getTerminalInfo(FFTerminalResult* result, uint32_t pid) return ppid; } -static void setTerminalInfoDetails(FFTerminalResult* result) -{ - if(ffStrbufIgnCaseEqualS(&result->prettyName, "WindowsTerminal")) - ffStrbufSetStatic(&result->prettyName, ffStrbufContainIgnCaseS(&result->exe, ".WindowsTerminalPreview_") - ? "Windows Terminal Preview" - : "Windows Terminal" - ); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "conhost")) +static void setTerminalInfoDetails(FFTerminalResult* result) { + if (ffStrbufIgnCaseEqualS(&result->prettyName, "WindowsTerminal")) { + ffStrbufSetStatic(&result->prettyName, ffStrbufContainIgnCaseS(&result->exe, ".WindowsTerminalPreview_") ? "Windows Terminal Preview" : "Windows Terminal"); + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "conhost")) { ffStrbufSetStatic(&result->prettyName, "Windows Console"); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "Code")) + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "Code")) { ffStrbufSetStatic(&result->prettyName, "Visual Studio Code"); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "explorer")) + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "explorer")) { ffStrbufSetStatic(&result->prettyName, "Windows Explorer"); - else if(ffStrbufEqualS(&result->prettyName, "wezterm-gui")) + } else if (ffStrbufEqualS(&result->prettyName, "wezterm-gui")) { ffStrbufSetStatic(&result->prettyName, "WezTerm"); - else if(ffStrbufIgnCaseEqualS(&result->prettyName, "sshd") || ffStrbufStartsWithIgnCaseS(&result->prettyName, "sshd-")) - { + } else if (ffStrbufIgnCaseEqualS(&result->prettyName, "sshd") || ffStrbufStartsWithIgnCaseS(&result->prettyName, "sshd-")) { const char* tty = getenv("SSH_TTY"); - if (tty) ffStrbufSetS(&result->prettyName, tty); + if (tty) { + ffStrbufSetS(&result->prettyName, tty); + } } } bool fftsGetTerminalVersion(FFstrbuf* processName, FFstrbuf* exe, FFstrbuf* version); -const FFShellResult* ffDetectShell(void) -{ +const FFShellResult* ffDetectShell(void) { static FFShellResult result; static bool init = false; - if(init) + if (init) { return &result; + } init = true; ffStrbufInit(&result.processName); @@ -348,34 +308,37 @@ const FFShellResult* ffDetectShell(void) result.tty = -1; uint32_t ppid; - if(!ffProcessGetInfoWindows(0, &ppid, NULL, NULL, NULL, NULL, NULL)) + if (!ffProcessGetInfoWindows(0, &ppid, NULL, NULL, NULL, NULL, NULL)) { return &result; + } const char* ignoreParent = getenv("FFTS_IGNORE_PARENT"); - if (ignoreParent && ffStrEquals(ignoreParent, "1")) + if (ignoreParent && ffStrEquals(ignoreParent, "1")) { ffProcessGetInfoWindows(ppid, &ppid, NULL, NULL, NULL, NULL, NULL); + } ppid = getShellInfo(&result, ppid); - if (result.processName.length > 0) - { + if (result.processName.length > 0) { setShellInfoDetails(&result); char tmp[MAX_PATH]; strcpy(tmp, result.exeName); char* ext = strrchr(tmp, '.'); - if (ext) *ext = '\0'; + if (ext) { + *ext = '\0'; + } fftsGetShellVersion(result.exePath.length > 0 ? &result.exePath : &result.exe, tmp, &result.version); } return &result; } -const FFTerminalResult* ffDetectTerminal(void) -{ +const FFTerminalResult* ffDetectTerminal(void) { static FFTerminalResult result; static bool init = false; - if(init) + if (init) { return &result; + } init = true; ffStrbufInit(&result.processName); @@ -389,16 +352,18 @@ const FFTerminalResult* ffDetectTerminal(void) result.ppid = 0; uint32_t ppid = ffDetectShell()->ppid; - if(ppid) + if (ppid) { getTerminalInfo(&result, ppid); + } - if(result.processName.length == 0) + if (result.processName.length == 0) { getTerminalFromEnv(&result); - if(result.processName.length == 0) + } + if (result.processName.length == 0) { detectDefaultTerminal(&result); + } - if(result.processName.length > 0) - { + if (result.processName.length > 0) { setTerminalInfoDetails(&result); fftsGetTerminalVersion(&result.processName, result.exePath.length > 0 ? &result.exePath : &result.exe, &result.version); } diff --git a/src/detection/terminalsize/terminalsize.h b/src/detection/terminalsize/terminalsize.h index e178f34b9..1ad97e1ba 100644 --- a/src/detection/terminalsize/terminalsize.h +++ b/src/detection/terminalsize/terminalsize.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/terminalsize/option.h" -typedef struct FFTerminalSizeResult -{ +typedef struct FFTerminalSizeResult { uint16_t rows; uint16_t columns; uint16_t width; diff --git a/src/detection/terminalsize/terminalsize_linux.c b/src/detection/terminalsize/terminalsize_linux.c index fce2d5d33..523bf8a00 100644 --- a/src/detection/terminalsize/terminalsize_linux.c +++ b/src/detection/terminalsize/terminalsize_linux.c @@ -6,26 +6,29 @@ #include #ifdef __sun - #include +# include #endif -bool ffDetectTerminalSize(FFTerminalSizeResult* result) -{ +bool ffDetectTerminalSize(FFTerminalSizeResult* result) { struct winsize winsize = {}; static int ttyfd = STDOUT_FILENO; - if (!isatty(ttyfd)) + if (!isatty(ttyfd)) { ttyfd = open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC); + } ioctl(ttyfd, TIOCGWINSZ, &winsize); - if (winsize.ws_row == 0 || winsize.ws_col == 0) + if (winsize.ws_row == 0 || winsize.ws_col == 0) { ffGetTerminalResponse("\e[18t", 2, "\e[8;%hu;%hut", &winsize.ws_row, &winsize.ws_col); + } - if (winsize.ws_ypixel == 0 || winsize.ws_xpixel == 0) + if (winsize.ws_ypixel == 0 || winsize.ws_xpixel == 0) { ffGetTerminalResponse("\e[14t", 2, "\e[4;%hu;%hut", &winsize.ws_ypixel, &winsize.ws_xpixel); + } - if (winsize.ws_row == 0 && winsize.ws_col == 0) + if (winsize.ws_row == 0 && winsize.ws_col == 0) { return false; + } result->rows = winsize.ws_row; result->columns = winsize.ws_col; diff --git a/src/detection/terminalsize/terminalsize_windows.c b/src/detection/terminalsize/terminalsize_windows.c index dfbde494b..dce3cd8c0 100644 --- a/src/detection/terminalsize/terminalsize_windows.c +++ b/src/detection/terminalsize/terminalsize_windows.c @@ -3,44 +3,39 @@ #include -bool ffDetectTerminalSize(FFTerminalSizeResult* result) -{ +bool ffDetectTerminalSize(FFTerminalSizeResult* result) { HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); FF_AUTO_CLOSE_FD HANDLE hConout = INVALID_HANDLE_VALUE; { DWORD outputMode; - if (!GetConsoleMode(hOutput, &outputMode)) - { + if (!GetConsoleMode(hOutput, &outputMode)) { hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL); hOutput = hConout; } } { CONSOLE_SCREEN_BUFFER_INFO csbi; - if (GetConsoleScreenBufferInfo(hOutput, &csbi)) - { + if (GetConsoleScreenBufferInfo(hOutput, &csbi)) { result->columns = (uint16_t) (csbi.srWindow.Right - csbi.srWindow.Left + 1); result->rows = (uint16_t) (csbi.srWindow.Bottom - csbi.srWindow.Top + 1); - } - else - { + } else { // Windows Terminal doesn't report `\e` for some reason ffGetTerminalResponse("\e[18t", 2, "%*[^;];%hu;%hut", &result->rows, &result->columns); } } - if (result->columns == 0 && result->rows == 0) + if (result->columns == 0 && result->rows == 0) { return false; + } { - CONSOLE_FONT_INFOEX cfi = { .cbSize = sizeof(cfi) }; - if(GetCurrentConsoleFontEx(hOutput, FALSE, &cfi)) // Only works for ConHost + CONSOLE_FONT_INFOEX cfi = {.cbSize = sizeof(cfi)}; + if (GetCurrentConsoleFontEx(hOutput, FALSE, &cfi)) // Only works for ConHost { result->width = result->columns * (uint16_t) cfi.dwFontSize.X; result->height = result->rows * (uint16_t) cfi.dwFontSize.Y; } - if (result->width == 0 || result->height == 0) - { + if (result->width == 0 || result->height == 0) { // Windows Terminal doesn't report `\e` for some reason ffGetTerminalResponse("\e[14t", 2, "%*[^;];%hu;%hut", &result->height, &result->width); } diff --git a/src/detection/terminaltheme/terminaltheme.c b/src/detection/terminaltheme/terminaltheme.c index 552560a1f..b0bdebc29 100644 --- a/src/detection/terminaltheme/terminaltheme.c +++ b/src/detection/terminaltheme/terminaltheme.c @@ -4,80 +4,101 @@ #include -static bool detectByEscapeCode(FFTerminalThemeResult* result) -{ +static bool detectByEscapeCode(FFTerminalThemeResult* result) { // Windows Terminal removes all `\e`s in its output if (ffGetTerminalResponse("\e]10;?\e\\" /*fg*/ "\e]11;?\e\\" /*bg*/, - 6, - "%*[^0-9]10;rgb:%" SCNx16 "/%" SCNx16 "/%" SCNx16 /*"\e\\"*/ "%*[^0-9]11;rgb:%" SCNx16 "/%" SCNx16 "/%" SCNx16 /*"\e\\"*/, - &result->fg.r, &result->fg.g, &result->fg.b, - &result->bg.r, &result->bg.g, &result->bg.b) == NULL) - { - if (result->fg.r > 0x0100 || result->fg.g > 0x0100 || result->fg.b > 0x0100) + 6, + "%*[^0-9]10;rgb:%" SCNx16 "/%" SCNx16 "/%" SCNx16 /*"\e\\"*/ "%*[^0-9]11;rgb:%" SCNx16 "/%" SCNx16 "/%" SCNx16 /*"\e\\"*/, + &result->fg.r, + &result->fg.g, + &result->fg.b, + &result->bg.r, + &result->bg.g, + &result->bg.b) == NULL) { + if (result->fg.r > 0x0100 || result->fg.g > 0x0100 || result->fg.b > 0x0100) { result->fg.r /= 0x0100, result->fg.g /= 0x0100, result->fg.b /= 0x0100; - if (result->bg.r > 0x0100 || result->bg.g > 0x0100 || result->bg.b > 0x0100) + } + if (result->bg.r > 0x0100 || result->bg.g > 0x0100 || result->bg.b > 0x0100) { result->bg.r /= 0x0100, result->bg.g /= 0x0100, result->bg.b /= 0x0100; - } - else + } + } else { return false; + } return true; } -static FFTerminalThemeColor fgbgToColor(int num) -{ +static FFTerminalThemeColor fgbgToColor(int num) { // https://github.com/dalance/termbg/blob/13c478a433fa182e65c401d26a1e7792a7f7f453/src/lib.rs#L251 - switch (num) - { - case 0: return (FFTerminalThemeColor){ 0, 0, 0, false}; // black - case 1: return (FFTerminalThemeColor){205, 0, 0, false}; // red - case 2: return (FFTerminalThemeColor){ 0, 205, 0, false}; // green - case 3: return (FFTerminalThemeColor){205, 205, 0, false}; // yellow - case 4: return (FFTerminalThemeColor){ 0, 0, 238, false}; // blue - case 5: return (FFTerminalThemeColor){205, 0, 205, false}; // magenta - case 6: return (FFTerminalThemeColor){ 0, 205, 205, false}; // cyan - case 7: return (FFTerminalThemeColor){229, 229, 229, false}; // white + switch (num) { + case 0: + return (FFTerminalThemeColor) {0, 0, 0, false}; // black + case 1: + return (FFTerminalThemeColor) {205, 0, 0, false}; // red + case 2: + return (FFTerminalThemeColor) {0, 205, 0, false}; // green + case 3: + return (FFTerminalThemeColor) {205, 205, 0, false}; // yellow + case 4: + return (FFTerminalThemeColor) {0, 0, 238, false}; // blue + case 5: + return (FFTerminalThemeColor) {205, 0, 205, false}; // magenta + case 6: + return (FFTerminalThemeColor) {0, 205, 205, false}; // cyan + case 7: + return (FFTerminalThemeColor) {229, 229, 229, false}; // white - case 8: return (FFTerminalThemeColor){127, 127, 127, false}; // bright black - case 9: return (FFTerminalThemeColor){255, 0, 0, false}; // bright red - case 10: return (FFTerminalThemeColor){ 0, 255, 0, false}; // bright green - case 11: return (FFTerminalThemeColor){255, 255, 0, false}; // bright yellow - case 12: return (FFTerminalThemeColor){ 92, 92, 255, false}; // bright blue - case 13: return (FFTerminalThemeColor){255, 0, 255, false}; // bright magenta - case 14: return (FFTerminalThemeColor){ 0, 255, 255, false}; // bright cyan - case 15: return (FFTerminalThemeColor){255, 255, 255, false}; // bright white + case 8: + return (FFTerminalThemeColor) {127, 127, 127, false}; // bright black + case 9: + return (FFTerminalThemeColor) {255, 0, 0, false}; // bright red + case 10: + return (FFTerminalThemeColor) {0, 255, 0, false}; // bright green + case 11: + return (FFTerminalThemeColor) {255, 255, 0, false}; // bright yellow + case 12: + return (FFTerminalThemeColor) {92, 92, 255, false}; // bright blue + case 13: + return (FFTerminalThemeColor) {255, 0, 255, false}; // bright magenta + case 14: + return (FFTerminalThemeColor) {0, 255, 255, false}; // bright cyan + case 15: + return (FFTerminalThemeColor) {255, 255, 255, false}; // bright white - default: return (FFTerminalThemeColor){ 0, 0, 0, false}; // invalid + default: + return (FFTerminalThemeColor) {0, 0, 0, false}; // invalid } } -static bool detectByEnv(FFTerminalThemeResult* result) -{ +static bool detectByEnv(FFTerminalThemeResult* result) { const char* color = getenv("COLORFGBG"); // 7;0 - if (!ffStrSet(color)) + if (!ffStrSet(color)) { return false; + } int f, g; - if (sscanf(color, "%d;%d", &f, &g) != 2) + if (sscanf(color, "%d;%d", &f, &g) != 2) { return false; + } result->fg = fgbgToColor(f); result->bg = fgbgToColor(g); return true; } -static inline bool detectColor(FFTerminalThemeResult* result, bool forceEnv) -{ - if (!forceEnv && detectByEscapeCode(result)) +static inline bool detectColor(FFTerminalThemeResult* result, bool forceEnv) { + if (!forceEnv && detectByEscapeCode(result)) { return true; + } return detectByEnv(result); } -bool ffDetectTerminalTheme(FFTerminalThemeResult* result, bool forceEnv) -{ - if (!detectColor(result, forceEnv)) return false; +bool ffDetectTerminalTheme(FFTerminalThemeResult* result, bool forceEnv) { + if (!detectColor(result, forceEnv)) { + return false; + } result->fg.dark = result->fg.r * 299 + result->fg.g * 587 + result->fg.b * 114 < 128000; result->bg.dark = result->bg.r * 299 + result->bg.g * 587 + result->bg.b * 114 < 128000; return true; diff --git a/src/detection/terminaltheme/terminaltheme.h b/src/detection/terminaltheme/terminaltheme.h index a3077823b..a2808dc1a 100644 --- a/src/detection/terminaltheme/terminaltheme.h +++ b/src/detection/terminaltheme/terminaltheme.h @@ -3,16 +3,14 @@ #include "fastfetch.h" #include "modules/terminaltheme/option.h" -typedef struct FFTerminalThemeColor -{ +typedef struct FFTerminalThemeColor { uint16_t r; uint16_t g; uint16_t b; bool dark; } FFTerminalThemeColor; -typedef struct FFTerminalThemeResult -{ +typedef struct FFTerminalThemeResult { FFTerminalThemeColor fg; FFTerminalThemeColor bg; } FFTerminalThemeResult; diff --git a/src/detection/theme/theme.h b/src/detection/theme/theme.h index afd3400c6..3498b1da2 100644 --- a/src/detection/theme/theme.h +++ b/src/detection/theme/theme.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/theme/option.h" -typedef struct FFThemeResult -{ +typedef struct FFThemeResult { FFstrbuf theme1; FFstrbuf theme2; } FFThemeResult; diff --git a/src/detection/theme/theme_apple.c b/src/detection/theme/theme_apple.c index b46d5afbf..a60d39cdb 100644 --- a/src/detection/theme/theme_apple.c +++ b/src/detection/theme/theme_apple.c @@ -2,15 +2,13 @@ #include "detection/os/os.h" -const char* ffDetectTheme(FFThemeResult* result) -{ +const char* ffDetectTheme(FFThemeResult* result) { const FFOSResult* os = ffDetectOS(); char* str_end; const char* version = os->version.chars; unsigned long osNum = strtoul(version, &str_end, 10); - if (str_end != version) - { + if (str_end != version) { if (osNum > 15) { // Tahoe ffStrbufSetStatic(&result->theme1, "Liquid Glass"); } else if (osNum < 10) { diff --git a/src/detection/theme/theme_linux.c b/src/detection/theme/theme_linux.c index 650130775..1de7db819 100644 --- a/src/detection/theme/theme_linux.c +++ b/src/detection/theme/theme_linux.c @@ -3,57 +3,58 @@ #include "detection/gtk_qt/gtk_qt.h" #include "detection/displayserver/displayserver.h" -const char* ffDetectTheme(FFThemeResult* result) -{ +const char* ffDetectTheme(FFThemeResult* result) { const FFDisplayServerResult* wmde = ffConnectDisplayServer(); - if(ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) + if (ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY)) { return "Theme isn't supported in TTY"; + } const FFQtResult* plasma = ffDetectQt(); const FFstrbuf* gtk2 = &ffDetectGTK2()->theme; const FFstrbuf* gtk3 = &ffDetectGTK3()->theme; const FFstrbuf* gtk4 = &ffDetectGTK4()->theme; - if(plasma->widgetStyle.length == 0 && plasma->colorScheme.length == 0 && gtk2->length == 0 && gtk3->length == 0 && gtk4->length == 0) + if (plasma->widgetStyle.length == 0 && plasma->colorScheme.length == 0 && gtk2->length == 0 && gtk3->length == 0 && gtk4->length == 0) { return "No themes found"; + } ffParseGTK(&result->theme2, gtk2, gtk3, gtk4); FF_STRBUF_AUTO_DESTROY plasmaColorPretty = ffStrbufCreate(); - if(ffStrbufStartsWithIgnCase(&plasma->colorScheme, &plasma->widgetStyle)) + if (ffStrbufStartsWithIgnCase(&plasma->colorScheme, &plasma->widgetStyle)) { ffStrbufAppendNS(&plasmaColorPretty, plasma->colorScheme.length - plasma->widgetStyle.length, &plasma->colorScheme.chars[plasma->widgetStyle.length]); - else + } else { ffStrbufAppend(&plasmaColorPretty, &plasma->colorScheme); + } ffStrbufTrim(&plasmaColorPretty, ' '); - if(plasma->widgetStyle.length > 0) - { + if (plasma->widgetStyle.length > 0) { ffStrbufAppend(&result->theme1, &plasma->widgetStyle); - if(plasma->colorScheme.length > 0) - { + if (plasma->colorScheme.length > 0) { ffStrbufAppendS(&result->theme1, " ("); - if(plasmaColorPretty.length > 0) + if (plasmaColorPretty.length > 0) { ffStrbufAppend(&result->theme1, &plasmaColorPretty); - else + } else { ffStrbufAppend(&result->theme1, &plasma->colorScheme); + } ffStrbufAppendC(&result->theme1, ')'); } - } - else if(plasma->colorScheme.length > 0) - { - if(plasmaColorPretty.length > 0) + } else if (plasma->colorScheme.length > 0) { + if (plasmaColorPretty.length > 0) { ffStrbufAppend(&result->theme1, &plasmaColorPretty); - else + } else { ffStrbufAppend(&result->theme1, &plasma->colorScheme); + } } - if(plasma->widgetStyle.length > 0 || plasma->colorScheme.length > 0) + if (plasma->widgetStyle.length > 0 || plasma->colorScheme.length > 0) { ffStrbufAppendS(&result->theme1, " [Qt]"); + } return NULL; } diff --git a/src/detection/theme/theme_nosupport.c b/src/detection/theme/theme_nosupport.c index caddd724d..2eeacc9a0 100644 --- a/src/detection/theme/theme_nosupport.c +++ b/src/detection/theme/theme_nosupport.c @@ -1,6 +1,5 @@ #include "theme.h" -const char* ffDetectTheme(FF_MAYBE_UNUSED FFThemeResult* result) -{ +const char* ffDetectTheme(FF_MAYBE_UNUSED FFThemeResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/theme/theme_windows.c b/src/detection/theme/theme_windows.c index 54853f62d..339b79be9 100644 --- a/src/detection/theme/theme_windows.c +++ b/src/detection/theme/theme_windows.c @@ -2,28 +2,26 @@ #include "detection/os/os.h" -const char* ffDetectTheme(FFThemeResult* result) -{ +const char* ffDetectTheme(FFThemeResult* result) { const FFOSResult* os = ffDetectOS(); uint32_t ver = (uint32_t) ffStrbufToUInt(&os->version, 0); - if (ver > 1000) - { + if (ver > 1000) { // Windows Server - if (ver >= 2016) + if (ver >= 2016) { ffStrbufSetStatic(&result->theme1, "Fluent"); - else if (ver >= 2012) + } else if (ver >= 2012) { ffStrbufSetStatic(&result->theme1, "Metro"); - else + } else { ffStrbufSetStatic(&result->theme1, "Aero"); - } - else - { - if (ver >= 10) + } + } else { + if (ver >= 10) { ffStrbufSetStatic(&result->theme1, "Fluent"); - else if (ver >= 8) + } else if (ver >= 8) { ffStrbufSetStatic(&result->theme1, "Metro"); - else + } else { ffStrbufSetStatic(&result->theme1, "Aero"); + } } return NULL; } diff --git a/src/detection/tpm/tpm.h b/src/detection/tpm/tpm.h index 5b5aa4e43..da842eca0 100644 --- a/src/detection/tpm/tpm.h +++ b/src/detection/tpm/tpm.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/tpm/option.h" -typedef struct FFTPMResult -{ +typedef struct FFTPMResult { FFstrbuf version; FFstrbuf description; } FFTPMResult; diff --git a/src/detection/tpm/tpm_apple.c b/src/detection/tpm/tpm_apple.c index d95679c55..07fbdb40f 100644 --- a/src/detection/tpm/tpm_apple.c +++ b/src/detection/tpm/tpm_apple.c @@ -1,19 +1,18 @@ #include "tpm.h" #ifndef __aarch64__ - #include "common/apple/cf_helpers.h" - #include +# include "common/apple/cf_helpers.h" +# include #endif -const char* ffDetectTPM(FFTPMResult* result) -{ - #ifdef __aarch64__ +const char* ffDetectTPM(FFTPMResult* result) { +#ifdef __aarch64__ ffStrbufSetStatic(&result->version, "2.0"); ffStrbufSetStatic(&result->description, "Apple Silicon Security"); return NULL; - #else +#else FF_IOOBJECT_AUTO_RELEASE io_service_t t2Service = IOServiceGetMatchingService( MACH_PORT_NULL, @@ -25,7 +24,7 @@ const char* ffDetectTPM(FFTPMResult* result) return NULL; } - #endif +#endif return "No Apple Security hardware detected"; } diff --git a/src/detection/tpm/tpm_bsd.c b/src/detection/tpm/tpm_bsd.c index 55c1e211c..4b7341306 100644 --- a/src/detection/tpm/tpm_bsd.c +++ b/src/detection/tpm/tpm_bsd.c @@ -2,20 +2,21 @@ #include "common/sysctl.h" #include "common/kmod.h" -const char* ffDetectTPM(FFTPMResult* result) -{ - if (ffSysctlGetString("dev.tpmcrb.0.%desc", &result->description) != NULL) - { - if (!ffKmodLoaded("tpm")) return "`tpm` kernel module is not loaded"; +const char* ffDetectTPM(FFTPMResult* result) { + if (ffSysctlGetString("dev.tpmcrb.0.%desc", &result->description) != NULL) { + if (!ffKmodLoaded("tpm")) { + return "`tpm` kernel module is not loaded"; + } return "TPM device is not found"; } - if (ffStrbufContainS(&result->description, "2.0")) + if (ffStrbufContainS(&result->description, "2.0")) { ffStrbufSetStatic(&result->version, "2.0"); - else if (ffStrbufContainS(&result->description, "1.2")) + } else if (ffStrbufContainS(&result->description, "1.2")) { ffStrbufSetStatic(&result->version, "1.2"); - else + } else { ffStrbufSetStatic(&result->version, "unknown"); + } return NULL; } diff --git a/src/detection/tpm/tpm_linux.c b/src/detection/tpm/tpm_linux.c index b7c6ab412..040da38cc 100644 --- a/src/detection/tpm/tpm_linux.c +++ b/src/detection/tpm/tpm_linux.c @@ -1,24 +1,24 @@ #include "tpm.h" #include "common/io.h" -const char* ffDetectTPM(FFTPMResult* result) -{ - if (!ffPathExists("/sys/class/tpm/tpm0/", FF_PATHTYPE_DIRECTORY)) - { - if (!ffPathExists("/sys/class/tpm/", FF_PATHTYPE_DIRECTORY)) +const char* ffDetectTPM(FFTPMResult* result) { + if (!ffPathExists("/sys/class/tpm/tpm0/", FF_PATHTYPE_DIRECTORY)) { + if (!ffPathExists("/sys/class/tpm/", FF_PATHTYPE_DIRECTORY)) { return "TPM is not supported by kernel"; + } return "TPM device is not found"; } - if (ffReadFileBuffer("/sys/class/tpm/tpm0/tpm_version_major", &result->version)) - { + if (ffReadFileBuffer("/sys/class/tpm/tpm0/tpm_version_major", &result->version)) { ffStrbufTrimRightSpace(&result->version); - if (ffStrbufEqualS(&result->version, "2")) + if (ffStrbufEqualS(&result->version, "2")) { ffStrbufSetStatic(&result->version, "2.0"); + } } - if (ffReadFileBuffer("/sys/class/tpm/tpm0/device/description", &result->description)) + if (ffReadFileBuffer("/sys/class/tpm/tpm0/device/description", &result->description)) { ffStrbufTrimRightSpace(&result->description); + } return NULL; } diff --git a/src/detection/tpm/tpm_nosupport.c b/src/detection/tpm/tpm_nosupport.c index 7865f70b5..3dfb4ab04 100644 --- a/src/detection/tpm/tpm_nosupport.c +++ b/src/detection/tpm/tpm_nosupport.c @@ -1,6 +1,5 @@ #include "tpm.h" -const char* ffDetectTPM(FF_MAYBE_UNUSED FFTPMResult* result) -{ +const char* ffDetectTPM(FF_MAYBE_UNUSED FFTPMResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/tpm/tpm_windows.c b/src/detection/tpm/tpm_windows.c index ecc5f21c2..14f6e8a4e 100644 --- a/src/detection/tpm/tpm_windows.c +++ b/src/detection/tpm/tpm_windows.c @@ -5,48 +5,46 @@ #include #include -const char* ffDetectTPM(FFTPMResult* result) -{ +const char* ffDetectTPM(FFTPMResult* result) { FF_LIBRARY_LOAD_MESSAGE(tbs, "TBS" FF_LIBRARY_EXTENSION, -1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(tbs, Tbsi_GetDeviceInfo) TPM_DEVICE_INFO deviceInfo = {}; TBS_RESULT code = ffTbsi_GetDeviceInfo(sizeof(deviceInfo), &deviceInfo); - if (code != TBS_SUCCESS) + if (code != TBS_SUCCESS) { return code == (TBS_RESULT) TBS_E_TPM_NOT_FOUND ? "TPM device is not found" : "Tbsi_GetDeviceInfo() failed"; - - switch (deviceInfo.tpmVersion) - { - case TPM_VERSION_12: - ffStrbufSetStatic(&result->version, "1.2"); - break; - case TPM_VERSION_20: - ffStrbufSetStatic(&result->version, "2.0"); - break; - default: - ffStrbufSetStatic(&result->version, "unknown"); - break; } - switch (deviceInfo.tpmInterfaceType) - { - case TPM_IFTYPE_1: - ffStrbufSetF(&result->description, "I/O-port or MMIO TPM %s", result->version.chars); - break; - case TPM_IFTYPE_TRUSTZONE: - ffStrbufSetF(&result->description, "Trustzone TPM %s", result->version.chars); - break; - case TPM_IFTYPE_HW: - ffStrbufSetF(&result->description, "HW TPM %s", result->version.chars); - break; - case TPM_IFTYPE_EMULATOR: - ffStrbufSetF(&result->description, "SW-emulator TPM %s", result->version.chars); - break; - case TPM_IFTYPE_SPB: - ffStrbufSetF(&result->description, "SPB attached TPM %s", result->version.chars); - break; - default: - break; + switch (deviceInfo.tpmVersion) { + case TPM_VERSION_12: + ffStrbufSetStatic(&result->version, "1.2"); + break; + case TPM_VERSION_20: + ffStrbufSetStatic(&result->version, "2.0"); + break; + default: + ffStrbufSetStatic(&result->version, "unknown"); + break; + } + + switch (deviceInfo.tpmInterfaceType) { + case TPM_IFTYPE_1: + ffStrbufSetF(&result->description, "I/O-port or MMIO TPM %s", result->version.chars); + break; + case TPM_IFTYPE_TRUSTZONE: + ffStrbufSetF(&result->description, "Trustzone TPM %s", result->version.chars); + break; + case TPM_IFTYPE_HW: + ffStrbufSetF(&result->description, "HW TPM %s", result->version.chars); + break; + case TPM_IFTYPE_EMULATOR: + ffStrbufSetF(&result->description, "SW-emulator TPM %s", result->version.chars); + break; + case TPM_IFTYPE_SPB: + ffStrbufSetF(&result->description, "SPB attached TPM %s", result->version.chars); + break; + default: + break; } return NULL; diff --git a/src/detection/uptime/uptime.h b/src/detection/uptime/uptime.h index f6426bc59..3f8631c0f 100644 --- a/src/detection/uptime/uptime.h +++ b/src/detection/uptime/uptime.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/uptime/option.h" -typedef struct FFUptimeResult -{ +typedef struct FFUptimeResult { uint64_t bootTime; uint64_t uptime; } FFUptimeResult; diff --git a/src/detection/uptime/uptime_bsd.c b/src/detection/uptime/uptime_bsd.c index 57a17b0d7..f831f9e46 100644 --- a/src/detection/uptime/uptime_bsd.c +++ b/src/detection/uptime/uptime_bsd.c @@ -4,26 +4,23 @@ #include #include -const char* ffDetectUptime(FFUptimeResult* result) -{ - #if __NetBSD__ +const char* ffDetectUptime(FFUptimeResult* result) { +#if __NetBSD__ struct timespec bootTime; - #else +#else struct timeval bootTime; - #endif +#endif size_t bootTimeSize = sizeof(bootTime); - if(sysctl( - (int[]) {CTL_KERN, KERN_BOOTTIME}, 2, - &bootTime, &bootTimeSize, - NULL, 0 - ) != 0) + if (sysctl( + (int[]) {CTL_KERN, KERN_BOOTTIME}, 2, &bootTime, &bootTimeSize, NULL, 0) != 0) { return "sysctl({CTL_KERN, KERN_BOOTTIME}) failed"; + } - #if __NetBSD__ +#if __NetBSD__ result->bootTime = (uint64_t) bootTime.tv_sec * 1000 + (uint64_t) bootTime.tv_nsec / 1000000; - #else +#else result->bootTime = (uint64_t) bootTime.tv_sec * 1000 + (uint64_t) bootTime.tv_usec / 1000; - #endif +#endif result->uptime = ffTimeGetNow() - result->bootTime; return NULL; diff --git a/src/detection/uptime/uptime_haiku.c b/src/detection/uptime/uptime_haiku.c index a2c48a5ec..bf5dd25c7 100644 --- a/src/detection/uptime/uptime_haiku.c +++ b/src/detection/uptime/uptime_haiku.c @@ -1,8 +1,7 @@ #include "uptime.h" #include "common/time.h" -const char* ffDetectUptime(FFUptimeResult* result) -{ +const char* ffDetectUptime(FFUptimeResult* result) { result->uptime = (uint64_t) system_time() / 1000; result->bootTime = ffTimeGetNow() - result->uptime; return NULL; diff --git a/src/detection/uptime/uptime_linux.c b/src/detection/uptime/uptime_linux.c index a69d85a27..75c7768a8 100644 --- a/src/detection/uptime/uptime_linux.c +++ b/src/detection/uptime/uptime_linux.c @@ -4,37 +4,35 @@ #include -const char* ffDetectUptime(FFUptimeResult* result) -{ - #ifndef __ANDROID__ // cat: /proc/uptime: Permission denied +const char* ffDetectUptime(FFUptimeResult* result) { +#ifndef __ANDROID__ // cat: /proc/uptime: Permission denied // #620 char buf[64]; ssize_t nRead = ffReadFileData("/proc/uptime", ARRAY_SIZE(buf) - 1, buf); - if(nRead > 0) - { + if (nRead > 0) { buf[nRead] = '\0'; - char *err = NULL; + char* err = NULL; double sec = strtod(buf, &err); - if(err != buf) - { + if (err != buf) { result->uptime = (uint64_t) (sec * 1000); result->bootTime = ffTimeGetNow() - result->uptime; return NULL; } } - #endif - #ifndef __GNU__ +#endif +#ifndef __GNU__ struct timespec uptime; - if (clock_gettime(CLOCK_BOOTTIME, &uptime) != 0) + 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 +#else return "read(/proc/uptime) failed"; - #endif +#endif } diff --git a/src/detection/uptime/uptime_sunos.c b/src/detection/uptime/uptime_sunos.c index 74ce8b8a7..2a372999e 100644 --- a/src/detection/uptime/uptime_sunos.c +++ b/src/detection/uptime/uptime_sunos.c @@ -3,15 +3,12 @@ #include -const char* ffDetectUptime(FFUptimeResult* result) -{ +const char* ffDetectUptime(FFUptimeResult* result) { struct utmpx* ut; setutxent(); - while (NULL != (ut = getutxent())) - { - if (ut->ut_type == BOOT_TIME) - { + while (NULL != (ut = getutxent())) { + if (ut->ut_type == BOOT_TIME) { result->bootTime = (uint64_t) ut->ut_tv.tv_sec * 1000 + (uint64_t) ut->ut_tv.tv_usec / 1000000; result->uptime = ffTimeGetNow() - result->bootTime; break; diff --git a/src/detection/uptime/uptime_windows.c b/src/detection/uptime/uptime_windows.c index 8ac7b3dc5..695edadea 100644 --- a/src/detection/uptime/uptime_windows.c +++ b/src/detection/uptime/uptime_windows.c @@ -2,8 +2,7 @@ #include "common/time.h" #include "common/windows/nt.h" -const char* ffDetectUptime(FFUptimeResult* result) -{ +const char* ffDetectUptime(FFUptimeResult* result) { // QueryInterruptTime with Win7 support uint64_t interruptTime = ffKSystemTimeToUInt64(&SharedUserData->InterruptTime); diff --git a/src/detection/users/users.h b/src/detection/users/users.h index baa3775c6..8f24cc0d4 100644 --- a/src/detection/users/users.h +++ b/src/detection/users/users.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/users/option.h" -typedef struct FFUserResult -{ +typedef struct FFUserResult { FFstrbuf name; FFstrbuf hostName; FFstrbuf clientIp; diff --git a/src/detection/users/users_linux.c b/src/detection/users/users_linux.c index 357c1ab7d..9c821282d 100644 --- a/src/detection/users/users_linux.c +++ b/src/detection/users/users_linux.c @@ -6,22 +6,21 @@ #include #if FF_HAVE_UTMPX - #include +# include #else - //for Android compatibility - #include - #define utmpx utmp - #define setutxent setutent - #define getutxent getutent +// for Android compatibility +# include +# define utmpx utmp +# define setutxent setutent +# define getutxent getutent #endif #if __linux__ || __GNU__ - #include - #include +# include +# include #endif #if __linux__ -bool detectUserBySystemd(const FFstrbuf* pathUsers, FFlist* users) -{ +bool detectUserBySystemd(const FFstrbuf* pathUsers, FFlist* users) { FF_STRBUF_AUTO_DESTROY state = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY userName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY loginTime = ffStrbufCreate(); @@ -29,12 +28,14 @@ bool detectUserBySystemd(const FFstrbuf* pathUsers, FFlist* users) // WARNING: This is private data. Do not parse if (!ffParsePropFileValues(pathUsers->chars, 4, (FFpropquery[]) { - {"NAME=", &userName}, - {"STATE=", &state}, - {"REALTIME=", &loginTime}, - {"ONLINE_SESSIONS=", &sessions}, - }) || !ffStrbufEqualS(&state, "active")) + {"NAME=", &userName}, + {"STATE=", &state}, + {"REALTIME=", &loginTime}, + {"ONLINE_SESSIONS=", &sessions}, + }) || + !ffStrbufEqualS(&state, "active")) { return false; + } FFUserResult* user = FF_LIST_ADD(FFUserResult, *users); ffStrbufInitMove(&user->name, &userName); @@ -53,8 +54,7 @@ bool detectUserBySystemd(const FFstrbuf* pathUsers, FFlist* users) char* token = NULL; size_t n = 0; - while (ffStrbufGetdelim(&token, &n, ' ', &sessions)) - { + while (ffStrbufGetdelim(&token, &n, ' ', &sessions)) { ffStrbufSubstrBefore(&pathSessions, pathSessionsBaseLen); ffStrbufAppendS(&pathSessions, token); @@ -65,23 +65,21 @@ bool detectUserBySystemd(const FFstrbuf* pathUsers, FFlist* users) // WARNING: This is private data. Do not parse if (ffParsePropFileValues(pathSessions.chars, 4, (FFpropquery[]) { - {"REMOTE_HOST=", &remoteHost}, - {"TTY=", &tty}, - {"SERVICE=", &service}, - {"REALTIME=", &loginTime}, - }) && !ffStrbufEqualS(&service, "systemd-user")) - { - if (remoteHost.length) - { + {"REMOTE_HOST=", &remoteHost}, + {"TTY=", &tty}, + {"SERVICE=", &service}, + {"REALTIME=", &loginTime}, + }) && + !ffStrbufEqualS(&service, "systemd-user")) { + if (remoteHost.length) { ffStrbufTrimRight(&remoteHost, ']'); ffStrbufTrimLeft(&remoteHost, '['); ffStrbufInitMove(&user->hostName, &remoteHost); - } - else + } else { ffStrbufSetStatic(&user->hostName, "localhost"); + } ffStrbufInitMove(&user->sessionName, tty.length ? &tty : &service); - if (loginTime.length) - { + if (loginTime.length) { ffStrbufSubstrBefore(&loginTime, loginTime.length - 3); // converts us to ms user->loginTime = ffStrbufToUInt(&loginTime, 0); } @@ -92,27 +90,26 @@ bool detectUserBySystemd(const FFstrbuf* pathUsers, FFlist* users) return true; } -const char* detectBySystemd(FFUsersOptions* options, FFlist* users) -{ +const char* detectBySystemd(FFUsersOptions* options, FFlist* users) { // For some reason, debian/ubuntu no longer updates `/var/run/utmp` (#2064) // Query systemd instead FF_STRBUF_AUTO_DESTROY pathUsers = ffStrbufCreateS("/run/systemd/users/"); - if (options->myselfOnly) - { + if (options->myselfOnly) { ffStrbufAppendUInt(&pathUsers, instance.state.platform.uid); detectUserBySystemd(&pathUsers, users); - } - else - { + } else { const uint32_t pathUsersBaseLen = pathUsers.length; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pathUsers.chars); - if (!dirp) return "opendir(\"/run/systemd/users/\") failed"; + if (!dirp) { + return "opendir(\"/run/systemd/users/\") failed"; + } struct dirent* entry; - while ((entry = readdir(dirp))) - { - if (entry->d_type != DT_REG) continue; + while ((entry = readdir(dirp))) { + if (entry->d_type != DT_REG) { + continue; + } ffStrbufAppendS(&pathUsers, entry->d_name); detectUserBySystemd(&pathUsers, users); @@ -124,8 +121,7 @@ const char* detectBySystemd(FFUsersOptions* options, FFlist* users) #endif #if __linux__ || __GNU__ -static void fillUtmpIpAddr(FFUserResult* user, struct utmpx* n) -{ +static void fillUtmpIpAddr(FFUserResult* user, struct utmpx* n) { bool isIpv6 = false; for (int i = 1; i < 4; ++i) { if (n->ut_addr_v6[i] != 0) { @@ -147,32 +143,28 @@ static void fillUtmpIpAddr(FFUserResult* user, struct utmpx* n) } } #else -static void fillUtmpIpAddr(FF_MAYBE_UNUSED FFUserResult* user, FF_MAYBE_UNUSED struct utmpx* n) -{ +static void fillUtmpIpAddr(FF_MAYBE_UNUSED FFUserResult* user, FF_MAYBE_UNUSED struct utmpx* n) { } #endif -const char* detectByUtmp(FFUsersOptions* options, FFlist* users) -{ +const char* detectByUtmp(FFUsersOptions* options, FFlist* users) { struct utmpx* n = NULL; setutxent(); next: - while ((n = getutxent())) - { - if (n->ut_type != USER_PROCESS) + while ((n = getutxent())) { + if (n->ut_type != USER_PROCESS) { continue; + } - if (options->myselfOnly && !ffStrbufEqualS(&instance.state.platform.userName, n->ut_user)) + if (options->myselfOnly && !ffStrbufEqualS(&instance.state.platform.userName, n->ut_user)) { continue; + } - FF_LIST_FOR_EACH(FFUserResult, user, *users) - { - if(ffStrbufEqualS(&user->name, n->ut_user)) - { + FF_LIST_FOR_EACH (FFUserResult, user, *users) { + if (ffStrbufEqualS(&user->name, n->ut_user)) { uint64_t newLoginTime = (uint64_t) n->ut_tv.tv_sec * 1000 + (uint64_t) n->ut_tv.tv_usec / 1000; - if (newLoginTime > user->loginTime) - { + if (newLoginTime > user->loginTime) { ffStrbufSetS(&user->hostName, n->ut_host); ffStrbufSetS(&user->sessionName, n->ut_line); fillUtmpIpAddr(user, n); @@ -196,14 +188,17 @@ next: return NULL; } -const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) -{ +const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { const char* err = detectByUtmp(options, users); - if (err) return err; + if (err) { + return err; + } - #if __linux__ - if (users->length == 0) detectBySystemd(options, users); - #endif +#if __linux__ + if (users->length == 0) { + detectBySystemd(options, users); + } +#endif return NULL; } diff --git a/src/detection/users/users_nosupport.c b/src/detection/users/users_nosupport.c index d7893ba46..0a7e30a4c 100644 --- a/src/detection/users/users_nosupport.c +++ b/src/detection/users/users_nosupport.c @@ -1,7 +1,6 @@ #include "fastfetch.h" #include "users.h" -const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) -{ +const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { return "Not supported on this platform"; } diff --git a/src/detection/users/users_obsd.c b/src/detection/users/users_obsd.c index 61370392d..e573e8542 100644 --- a/src/detection/users/users_obsd.c +++ b/src/detection/users/users_obsd.c @@ -4,24 +4,27 @@ #include -const char* ffDetectUsers(FF_MAYBE_UNUSED FFUsersOptions* options, FFlist* users) -{ +const char* ffDetectUsers(FF_MAYBE_UNUSED FFUsersOptions* options, FFlist* users) { FF_AUTO_CLOSE_FILE FILE* fp = fopen(_PATH_UTMP, "r"); - if (!fp) return "fopen(_PATH_UTMP, r) failed"; + if (!fp) { + return "fopen(_PATH_UTMP, r) failed"; + } struct utmp n; next: - while (fread(&n, sizeof(n), 1, fp) == 1) - { - if (!n.ut_name[0]) continue; - - if (options->myselfOnly && !ffStrbufEqualS(&instance.state.platform.userName, n.ut_name)) + while (fread(&n, sizeof(n), 1, fp) == 1) { + if (!n.ut_name[0]) { continue; + } - FF_LIST_FOR_EACH(FFUserResult, user, *users) - { - if (ffStrbufEqualS(&user->name, n.ut_name)) + if (options->myselfOnly && !ffStrbufEqualS(&instance.state.platform.userName, n.ut_name)) { + continue; + } + + FF_LIST_FOR_EACH (FFUserResult, user, *users) { + if (ffStrbufEqualS(&user->name, n.ut_name)) { goto next; + } } FFUserResult* user = (FFUserResult*) ffListAdd(users); diff --git a/src/detection/users/users_windows.c b/src/detection/users/users_windows.c index 047607278..ca5c52611 100644 --- a/src/detection/users/users_windows.c +++ b/src/detection/users/users_windows.c @@ -6,25 +6,26 @@ #include #include -const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) -{ +const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { WTS_SESSION_INFO_1W* sessionInfo; DWORD sessionCount; DWORD level = 1; - if (!WTSEnumerateSessionsExW(WTS_CURRENT_SERVER_HANDLE, &level, 0, &sessionInfo, &sessionCount)) + if (!WTSEnumerateSessionsExW(WTS_CURRENT_SERVER_HANDLE, &level, 0, &sessionInfo, &sessionCount)) { return "WTSEnumerateSessionsW(WTS_CURRENT_SERVER_HANDLE) failed"; + } - for (DWORD i = 0; i < sessionCount; i++) - { + for (DWORD i = 0; i < sessionCount; i++) { WTS_SESSION_INFO_1W* session = &sessionInfo[i]; - if (session->State != WTSActive) + if (session->State != WTSActive) { continue; + } FF_STRBUF_AUTO_DESTROY userName = ffStrbufCreateWS(session->pUserName); - if (options->myselfOnly && !ffStrbufEqual(&instance.state.platform.userName, &userName)) + if (options->myselfOnly && !ffStrbufEqual(&instance.state.platform.userName, &userName)) { continue; + } FFUserResult* user = (FFUserResult*) ffListAdd(users); ffStrbufInitMove(&user->name, &userName); @@ -35,14 +36,12 @@ const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) DWORD bytes = 0; PWTS_CLIENT_ADDRESS address = NULL; - if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session->SessionId, WTSClientAddress, (LPWSTR *) &address, &bytes)) - { - if (address->AddressFamily == AF_INET) + if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session->SessionId, WTSClientAddress, (LPWSTR*) &address, &bytes)) { + if (address->AddressFamily == AF_INET) { ffStrbufSetF(&user->clientIp, "%u.%u.%u.%u", address->Address[2], address->Address[3], address->Address[4], address->Address[5]); - else if (address->AddressFamily == AF_INET6) - { + } else if (address->AddressFamily == AF_INET6) { char ipStr[INET6_ADDRSTRLEN]; - const char* end = RtlIpv6AddressToStringA((const IN6_ADDR *) address->Address, ipStr); + const char* end = RtlIpv6AddressToStringA((const IN6_ADDR*) address->Address, ipStr); ffStrbufSetNS(&user->clientIp, (uint32_t) (end - ipStr), ipStr); } WTSFreeMemory(address); @@ -50,8 +49,7 @@ const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) bytes = 0; PWTSINFOW wtsInfo = NULL; - if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session->SessionId, WTSSessionInfo, (LPWSTR *) &wtsInfo, &bytes)) - { + if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session->SessionId, WTSSessionInfo, (LPWSTR*) &wtsInfo, &bytes)) { user->loginTime = ffFileTimeToUnixMs((uint64_t) wtsInfo->LogonTime.QuadPart); WTSFreeMemory(wtsInfo); } diff --git a/src/detection/version/version.c b/src/detection/version/version.c index edccce86d..0027166bc 100644 --- a/src/detection/version/version.c +++ b/src/detection/version/version.c @@ -1,65 +1,65 @@ #include "version.h" #if defined(__x86_64__) - #define FF_ARCHITECTURE "x86_64" +# define FF_ARCHITECTURE "x86_64" #elif defined(__i386__) - #define FF_ARCHITECTURE "i386" +# define FF_ARCHITECTURE "i386" #elif defined(__ia64__) - #define FF_ARCHITECTURE "ia64" +# define FF_ARCHITECTURE "ia64" #elif defined(__aarch64__) - #define FF_ARCHITECTURE "aarch64" +# define FF_ARCHITECTURE "aarch64" #elif defined(__arm__) - #define FF_ARCHITECTURE "arm" +# define FF_ARCHITECTURE "arm" #elif defined(__mips__) - #define FF_ARCHITECTURE "mips" +# define FF_ARCHITECTURE "mips" #elif defined(__powerpc__) || defined(__powerpc) - #define FF_ARCHITECTURE "powerpc" +# define FF_ARCHITECTURE "powerpc" #elif defined(__riscv__) || defined(__riscv) - #define FF_ARCHITECTURE "riscv" +# define FF_ARCHITECTURE "riscv" #elif defined(__s390x__) - #define FF_ARCHITECTURE "s390x" +# define FF_ARCHITECTURE "s390x" #elif defined(__loongarch__) - #define FF_ARCHITECTURE "loongarch" +# define FF_ARCHITECTURE "loongarch" #elif defined(__sparc__) - #define FF_ARCHITECTURE "sparc" +# define FF_ARCHITECTURE "sparc" #elif defined(__alpha__) - #define FF_ARCHITECTURE "alpha" +# define FF_ARCHITECTURE "alpha" #elif defined(__hppa__) - #define FF_ARCHITECTURE "hppa" +# define FF_ARCHITECTURE "hppa" #elif defined(__sh__) - #define FF_ARCHITECTURE "sh" +# define FF_ARCHITECTURE "sh" #elif defined(__m68k__) - #define FF_ARCHITECTURE "m68k" +# define FF_ARCHITECTURE "m68k" #else - #define FF_ARCHITECTURE "Unknown" +# define FF_ARCHITECTURE "Unknown" #endif #if defined(__ANDROID__) - #define FF_SYSNAME "Android" +# define FF_SYSNAME "Android" #elif defined(__linux__) - #define FF_SYSNAME "Linux" +# define FF_SYSNAME "Linux" #elif defined(__DragonFly__) // We define `__FreeBSD__` on DragonFly BSD for simplification - #define FF_SYSNAME "DragonFly" +# define FF_SYSNAME "DragonFly" #elif defined(__MidnightBSD__) - #define FF_SYSNAME "MidnightBSD" +# define FF_SYSNAME "MidnightBSD" #elif defined(__FreeBSD__) - #define FF_SYSNAME "FreeBSD" +# define FF_SYSNAME "FreeBSD" #elif defined(__APPLE__) - #define FF_SYSNAME "macOS" +# define FF_SYSNAME "macOS" #elif defined(_WIN32) - #define FF_SYSNAME "Windows" +# define FF_SYSNAME "Windows" #elif defined(__sun) - #define FF_SYSNAME "SunOS" +# define FF_SYSNAME "SunOS" #elif defined(__OpenBSD__) - #define FF_SYSNAME "OpenBSD" +# define FF_SYSNAME "OpenBSD" #elif defined(__NetBSD__) - #define FF_SYSNAME "NetBSD" +# define FF_SYSNAME "NetBSD" #elif defined(__HAIKU__) - #define FF_SYSNAME "Haiku" +# define FF_SYSNAME "Haiku" #elif defined(__GNU__) - #define FF_SYSNAME "GNU" +# define FF_SYSNAME "GNU" #else - #define FF_SYSNAME "Unknown" +# define FF_SYSNAME "Unknown" #endif #define FF_STR_INDIR(x) #x @@ -76,33 +76,35 @@ FFVersionResult ffVersionResult = { .compileTime = __DATE__ ", " __TIME__, .compiler = - #ifdef __clang__ - #ifdef _MSC_VER - "clang-cl " ; - #elif defined(__APPLE__) && defined(__apple_build_version__) - "Apple clang " - #else - "clang " - #endif +#ifdef __clang__ +# ifdef _MSC_VER + "clang-cl "; +# elif defined(__APPLE__) && defined(__apple_build_version__) + "Apple clang " +# else + "clang " +# endif - FF_STR(__clang_major__) "." FF_STR(__clang_minor__) "." FF_STR(__clang_patchlevel__) +FF_STR(__clang_major__) +"." FF_STR(__clang_minor__) "." FF_STR(__clang_patchlevel__) - #if defined(__APPLE__) && defined(__apple_build_version__) - " (" FF_STR(__apple_build_version__) ")" - #endif - , - #elif defined(__GNUC__) +# if defined(__APPLE__) && defined(__apple_build_version__) + " (" FF_STR(__apple_build_version__) ")" +# endif + , +#elif defined(__GNUC__) "gcc " FF_STR(__GNUC__) "." FF_STR(__GNUC_MINOR__) "." FF_STR(__GNUC_PATCHLEVEL__), - #elif defined(_MSC_VER) +#elif defined(_MSC_VER) "msvc " FF_STR(_MSC_VER), - #else +#else "unknown", - #endif +#endif .debugMode = - #ifndef NDEBUG +#ifndef NDEBUG true, - #else +#else false, - #endif -}; +#endif +} +; diff --git a/src/detection/version/version.h b/src/detection/version/version.h index e97099aac..1330535ed 100644 --- a/src/detection/version/version.h +++ b/src/detection/version/version.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/version/option.h" -typedef struct FFVersionResult -{ +typedef struct FFVersionResult { const char* projectName; const char* sysName; const char* architecture; diff --git a/src/detection/vulkan/vulkan.c b/src/detection/vulkan/vulkan.c index 4dc2b775f..24f6c5c91 100644 --- a/src/detection/vulkan/vulkan.c +++ b/src/detection/vulkan/vulkan.c @@ -4,25 +4,24 @@ #include "detection/vulkan/vulkan.h" #ifdef FF_HAVE_VULKAN -#include "common/library.h" -#include "common/io.h" -#include "common/parsing.h" -#include "common/stringUtils.h" +# include "common/library.h" +# include "common/io.h" +# include "common/parsing.h" +# include "common/stringUtils.h" -#include -#include +# include +# include -static inline void applyVulkanVersion(uint32_t vulkanVersion, FFVersion* ffVersion) -{ +static inline void applyVulkanVersion(uint32_t vulkanVersion, FFVersion* ffVersion) { ffVersion->major = VK_VERSION_MAJOR(vulkanVersion); ffVersion->minor = VK_VERSION_MINOR(vulkanVersion); ffVersion->patch = VK_VERSION_PATCH(vulkanVersion); } -static void applyDriverName(VkPhysicalDeviceDriverPropertiesKHR* properties, FFstrbuf* result) -{ - if(!ffStrSet(properties->driverName)) +static void applyDriverName(VkPhysicalDeviceDriverPropertiesKHR* properties, FFstrbuf* result) { + if (!ffStrSet(properties->driverName)) { return; + } ffStrbufAppendS(result, properties->driverName); @@ -30,89 +29,87 @@ static void applyDriverName(VkPhysicalDeviceDriverPropertiesKHR* properties, FFs * Some drivers (android for example) expose a multiline string as driver info. * It contains too much info anyways, so we just don't append it. */ - if(!ffStrSet(properties->driverInfo) || strchr(properties->driverInfo, '\n') != NULL) + if (!ffStrSet(properties->driverInfo) || strchr(properties->driverInfo, '\n') != NULL) { return; + } ffStrbufAppendS(result, " ["); ffStrbufAppendS(result, properties->driverInfo); ffStrbufAppendC(result, ']'); } -static const char* detectVulkan(FFVulkanResult* result) -{ +static const char* detectVulkan(FFVulkanResult* result) { FF_DEBUG("Starting Vulkan detection"); FF_LIBRARY_LOAD_MESSAGE(vulkan, - #if __APPLE__ - "libMoltenVK" FF_LIBRARY_EXTENSION, -1 - #elif _WIN32 - "vulkan-1" FF_LIBRARY_EXTENSION, -1 - #else - "libvulkan" FF_LIBRARY_EXTENSION, 2 - #endif +# if __APPLE__ + "libMoltenVK" FF_LIBRARY_EXTENSION, + -1 +# elif _WIN32 + "vulkan-1" FF_LIBRARY_EXTENSION, + -1 +# else + "libvulkan" FF_LIBRARY_EXTENSION, + 2 +# endif ) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(vulkan, vkGetInstanceProcAddr) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(vulkan, vkCreateInstance) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(vulkan, vkDestroyInstance) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(vulkan, vkEnumeratePhysicalDevices) - //Some drivers (nvdc) print messages to stdout - //and that is the best way I found to disable that + // Some drivers (nvdc) print messages to stdout + // and that is the best way I found to disable that FF_SUPPRESS_IO(); FF_DEBUG("Suppressed stdout/stderr during Vulkan probing to avoid noisy drivers"); FFVersion instanceVersion = FF_VERSION_INIT; - //We need to get the function pointer this way, because it is only provided by vulkan 1.1 and higher. - //a dlsym would fail on 1.0 implementations + // We need to get the function pointer this way, because it is only provided by vulkan 1.1 and higher. + // a dlsym would fail on 1.0 implementations PFN_vkEnumerateInstanceVersion ffvkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion) ffvkGetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion"); - if(ffvkEnumerateInstanceVersion != NULL) - { + if (ffvkEnumerateInstanceVersion != NULL) { uint32_t version; - if(ffvkEnumerateInstanceVersion(&version) == VK_SUCCESS) - { + if (ffvkEnumerateInstanceVersion(&version) == VK_SUCCESS) { applyVulkanVersion(version, &instanceVersion); FF_DEBUG("Detected Vulkan instance version: %u.%u.%u", instanceVersion.major, instanceVersion.minor, instanceVersion.patch); - } - else + } else { FF_DEBUG("vkEnumerateInstanceVersion() is available but returned a non-success status"); - } - else + } + } else { FF_DEBUG("vkEnumerateInstanceVersion() is unavailable (likely Vulkan 1.0 runtime)"); + } const uint32_t projectVersion = VK_MAKE_VERSION( FASTFETCH_PROJECT_VERSION_MAJOR, FASTFETCH_PROJECT_VERSION_MINOR, - FASTFETCH_PROJECT_VERSION_PATCH - ); + FASTFETCH_PROJECT_VERSION_PATCH); VkInstance vkInstance; FF_DEBUG("Creating Vulkan instance with requested API version %s", instanceVersion.minor >= 1 ? "1.1" : "1.0"); VkResult res = ffvkCreateInstance(&(VkInstanceCreateInfo) { - .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, - .pNext = NULL, - .pApplicationInfo = &(VkApplicationInfo) { - .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, - .pNext = NULL, - .pApplicationName = FASTFETCH_PROJECT_NAME, - .applicationVersion = projectVersion, - .pEngineName = "vulkanPrintGPUs", - .engineVersion = projectVersion, + .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pNext = NULL, + .pApplicationInfo = &(VkApplicationInfo) { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pNext = NULL, + .pApplicationName = FASTFETCH_PROJECT_NAME, + .applicationVersion = projectVersion, + .pEngineName = "vulkanPrintGPUs", + .engineVersion = projectVersion, - // We need to request 1.1 to get physicalDeviceDriverProperties - .apiVersion = instanceVersion.minor >= 1 ? VK_API_VERSION_1_1 : VK_API_VERSION_1_0 - }, - .enabledLayerCount = 0, - .ppEnabledLayerNames = NULL, - .enabledExtensionCount = 0, - .ppEnabledExtensionNames = NULL, - .flags = 0 - }, NULL, &vkInstance); - if(res != VK_SUCCESS) - { + // We need to request 1.1 to get physicalDeviceDriverProperties + .apiVersion = instanceVersion.minor >= 1 ? VK_API_VERSION_1_1 : VK_API_VERSION_1_0}, + .enabledLayerCount = 0, + .ppEnabledLayerNames = NULL, + .enabledExtensionCount = 0, + .ppEnabledExtensionNames = NULL, + .flags = 0}, + NULL, + &vkInstance); + if (res != VK_SUCCESS) { FF_DEBUG("ffvkCreateInstance() failed with VkResult=%d", res); - switch (res) - { + switch (res) { case VK_ERROR_OUT_OF_HOST_MEMORY: return "ffvkCreateInstance() failed: VK_ERROR_OUT_OF_HOST_MEMORY"; case VK_ERROR_OUT_OF_DEVICE_MEMORY: @@ -131,10 +128,9 @@ static const char* detectVulkan(FFVulkanResult* result) } FF_DEBUG("Vulkan instance created successfully"); - //if instance creation succeeded, but vkEnumerateInstanceVersion didn't, this means we are running against a vulkan 1.0 implementation - //explicitly set this version, if no device is found, so we still have at least this info - if(instanceVersion.major == 0 && instanceVersion.minor == 0 && instanceVersion.patch == 0) - { + // if instance creation succeeded, but vkEnumerateInstanceVersion didn't, this means we are running against a vulkan 1.0 implementation + // explicitly set this version, if no device is found, so we still have at least this info + if (instanceVersion.major == 0 && instanceVersion.minor == 0 && instanceVersion.patch == 0) { instanceVersion.major = 1; FF_DEBUG("Falling back to Vulkan instance version 1.0 due to unavailable enumerate call"); } @@ -142,36 +138,34 @@ static const char* detectVulkan(FFVulkanResult* result) VkPhysicalDevice physicalDevices[128]; uint32_t physicalDeviceCount = (uint32_t) ARRAY_SIZE(physicalDevices); res = ffvkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDevices); - if(res != VK_SUCCESS) - { + if (res != VK_SUCCESS) { FF_DEBUG("ffvkEnumeratePhysicalDevices() failed with VkResult=%d", res); ffvkDestroyInstance(vkInstance, NULL); - switch (res) - { - case VK_ERROR_OUT_OF_HOST_MEMORY: - return "ffvkEnumeratePhysicalDevices() failed: VK_ERROR_OUT_OF_HOST_MEMORY"; - case VK_ERROR_OUT_OF_DEVICE_MEMORY: - return "ffvkEnumeratePhysicalDevices() failed: VK_ERROR_OUT_OF_DEVICE_MEMORY"; - case VK_ERROR_INITIALIZATION_FAILED: - return "ffvkEnumeratePhysicalDevices() failed: VK_ERROR_INITIALIZATION_FAILED"; - case VK_INCOMPLETE: - return "ffvkEnumeratePhysicalDevices() failed: VK_INCOMPLETE"; - default: - return "ffvkEnumeratePhysicalDevices() failed"; + switch (res) { + case VK_ERROR_OUT_OF_HOST_MEMORY: + return "ffvkEnumeratePhysicalDevices() failed: VK_ERROR_OUT_OF_HOST_MEMORY"; + case VK_ERROR_OUT_OF_DEVICE_MEMORY: + return "ffvkEnumeratePhysicalDevices() failed: VK_ERROR_OUT_OF_DEVICE_MEMORY"; + case VK_ERROR_INITIALIZATION_FAILED: + return "ffvkEnumeratePhysicalDevices() failed: VK_ERROR_INITIALIZATION_FAILED"; + case VK_INCOMPLETE: + return "ffvkEnumeratePhysicalDevices() failed: VK_INCOMPLETE"; + default: + return "ffvkEnumeratePhysicalDevices() failed"; } } FF_DEBUG("Enumerated %u Vulkan physical device(s)", physicalDeviceCount); PFN_vkGetPhysicalDeviceProperties ffvkGetPhysicalDeviceProperties = NULL; PFN_vkGetPhysicalDeviceProperties2 ffvkGetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceProperties2"); // 1.1 - if(!ffvkGetPhysicalDeviceProperties2) + if (!ffvkGetPhysicalDeviceProperties2) { ffvkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceProperties"); + } FF_DEBUG("Using %s for querying physical device properties", ffvkGetPhysicalDeviceProperties2 ? "vkGetPhysicalDeviceProperties2" : "vkGetPhysicalDeviceProperties"); PFN_vkGetPhysicalDeviceMemoryProperties ffvkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceMemoryProperties"); - if(!ffvkGetPhysicalDeviceMemoryProperties) - { + if (!ffvkGetPhysicalDeviceMemoryProperties) { FF_DEBUG("vkGetPhysicalDeviceMemoryProperties is unavailable"); ffvkDestroyInstance(vkInstance, NULL); return "vkGetPhysicalDeviceMemoryProperties is not available"; @@ -180,11 +174,10 @@ static const char* detectVulkan(FFVulkanResult* result) FFVersion maxDeviceApiVersion = FF_VERSION_INIT; FFVersion maxDeviceConformanceVersion = FF_VERSION_INIT; - for(uint32_t i = 0; i < physicalDeviceCount; i++) - { - //Get device properties. - //On VK 1.1 and up, we use vkGetPhysicalDeviceProperties2, so we can put VkPhysicalDeviceDriverProperties in the pNext chain. - //This is required to get the driver name and conformance version. + for (uint32_t i = 0; i < physicalDeviceCount; i++) { + // Get device properties. + // On VK 1.1 and up, we use vkGetPhysicalDeviceProperties2, so we can put VkPhysicalDeviceDriverProperties in the pNext chain. + // This is required to get the driver name and conformance version. VkPhysicalDeviceDriverPropertiesKHR driverProperties = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR, @@ -194,32 +187,26 @@ static const char* detectVulkan(FFVulkanResult* result) .pNext = &driverProperties, }; - if(ffvkGetPhysicalDeviceProperties2 != NULL) + if (ffvkGetPhysicalDeviceProperties2 != NULL) { ffvkGetPhysicalDeviceProperties2(physicalDevices[i], &physicalDeviceProperties); - else + } else { ffvkGetPhysicalDeviceProperties(physicalDevices[i], &physicalDeviceProperties.properties); + } - FF_DEBUG("Processing Vulkan device #%u: name='%s', vendorId=0x%04X, deviceId=0x%04X, type=%u", i, - physicalDeviceProperties.properties.deviceName, - physicalDeviceProperties.properties.vendorID, - physicalDeviceProperties.properties.deviceID, - physicalDeviceProperties.properties.deviceType); + FF_DEBUG("Processing Vulkan device #%u: name='%s', vendorId=0x%04X, deviceId=0x%04X, type=%u", i, physicalDeviceProperties.properties.deviceName, physicalDeviceProperties.properties.vendorID, physicalDeviceProperties.properties.deviceID, physicalDeviceProperties.properties.deviceType); - - //We don't want software rasterizers to show up as physical gpu - if(physicalDeviceProperties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) - { + // We don't want software rasterizers to show up as physical gpu + if (physicalDeviceProperties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) { FF_DEBUG("Skipping CPU Vulkan device '%s'", physicalDeviceProperties.properties.deviceName); continue; } - //If the device api version is higher than the current highest device api version, overwrite it - //In this case, also use the current device driver name as the shown driver name + // If the device api version is higher than the current highest device api version, overwrite it + // In this case, also use the current device driver name as the shown driver name FFVersion deviceAPIVersion = FF_VERSION_INIT; applyVulkanVersion(physicalDeviceProperties.properties.apiVersion, &deviceAPIVersion); - if(ffVersionCompare(&deviceAPIVersion, &maxDeviceApiVersion) > 0) - { + if (ffVersionCompare(&deviceAPIVersion, &maxDeviceApiVersion) > 0) { maxDeviceApiVersion = deviceAPIVersion; applyDriverName(&driverProperties, &result->driver); FF_DEBUG("Updated max Vulkan device API version to %u.%u.%u (driver='%s')", @@ -229,17 +216,15 @@ static const char* detectVulkan(FFVulkanResult* result) result->driver.chars); } - //If the device conformance version is higher than the current highest device conformance version, overwrite it - if(ffvkGetPhysicalDeviceProperties2) - { + // If the device conformance version is higher than the current highest device conformance version, overwrite it + if (ffvkGetPhysicalDeviceProperties2) { FFVersion deviceConformanceVersion = { .major = driverProperties.conformanceVersion.major, .minor = driverProperties.conformanceVersion.minor, .patch = driverProperties.conformanceVersion.patch, }; - if(ffVersionCompare(&deviceConformanceVersion, &maxDeviceConformanceVersion) > 0) - { + if (ffVersionCompare(&deviceConformanceVersion, &maxDeviceConformanceVersion) > 0) { maxDeviceConformanceVersion = deviceConformanceVersion; FF_DEBUG("Updated max Vulkan conformance version to %u.%u.%u", maxDeviceConformanceVersion.major, @@ -248,13 +233,11 @@ static const char* detectVulkan(FFVulkanResult* result) } } - //Add the device to the list of devices shown by the GPU module + // Add the device to the list of devices shown by the GPU module // #456 - FF_LIST_FOR_EACH(FFGPUResult, gpu, result->gpus) - { - if (gpu->deviceId == physicalDeviceProperties.properties.deviceID) - { + FF_LIST_FOR_EACH (FFGPUResult, gpu, result->gpus) { + if (gpu->deviceId == physicalDeviceProperties.properties.deviceID) { FF_DEBUG("Skipping duplicate Vulkan GPU entry for deviceId=0x%04X", physicalDeviceProperties.properties.deviceID); goto next; } @@ -281,8 +264,7 @@ static const char* detectVulkan(FFVulkanResult* result) gpu->dedicated.total = gpu->shared.total = 0; gpu->dedicated.used = gpu->shared.used = FF_GPU_VMEM_SIZE_UNSET; - for(uint32_t index = 0; index < memoryProperties.memoryHeapCount; ++index) - { + for (uint32_t index = 0; index < memoryProperties.memoryHeapCount; ++index) { const VkMemoryHeap* heap = &memoryProperties.memoryHeaps[index]; FFGPUMemory* vmem = gpu->type == FF_GPU_TYPE_DISCRETE && (heap->flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) ? &gpu->dedicated : &gpu->shared; vmem->total += heap->size; @@ -292,7 +274,7 @@ static const char* detectVulkan(FFVulkanResult* result) (unsigned long long) gpu->dedicated.total, (unsigned long long) gpu->shared.total); - //No way to detect those using vulkan + // No way to detect those using vulkan gpu->index = FF_GPU_INDEX_UNSET; gpu->coreCount = FF_GPU_CORE_COUNT_UNSET; gpu->temperature = FF_GPU_TEMP_UNSET; @@ -320,12 +302,10 @@ static const char* detectVulkan(FFVulkanResult* result) #endif -FFVulkanResult* ffDetectVulkan(void) -{ +FFVulkanResult* ffDetectVulkan(void) { static FFVulkanResult result; - if (result.gpus.elementSize == 0) - { + if (result.gpus.elementSize == 0) { FF_DEBUG("Initializing Vulkan detection cache"); ffStrbufInit(&result.driver); ffStrbufInit(&result.apiVersion); @@ -333,17 +313,18 @@ FFVulkanResult* ffDetectVulkan(void) ffStrbufInit(&result.instanceVersion); ffListInit(&result.gpus, sizeof(FFGPUResult)); - #ifdef FF_HAVE_VULKAN - result.error = detectVulkan(&result); - if (result.error) - FF_DEBUG("Vulkan detection returned error: %s", result.error); - #else - result.error = "fastfetch was compiled without vulkan support"; - FF_DEBUG("Vulkan support is disabled at compile time"); - #endif - } - else +#ifdef FF_HAVE_VULKAN + result.error = detectVulkan(&result); + if (result.error) { + FF_DEBUG("Vulkan detection returned error: %s", result.error); + } +#else + result.error = "fastfetch was compiled without vulkan support"; + FF_DEBUG("Vulkan support is disabled at compile time"); +#endif + } else { FF_DEBUG("Reusing cached Vulkan detection result"); + } return &result; } diff --git a/src/detection/vulkan/vulkan.h b/src/detection/vulkan/vulkan.h index 75a5b8de7..6a49722cf 100644 --- a/src/detection/vulkan/vulkan.h +++ b/src/detection/vulkan/vulkan.h @@ -3,13 +3,12 @@ #include "fastfetch.h" #include "modules/vulkan/option.h" -typedef struct FFVulkanResult -{ +typedef struct FFVulkanResult { FFstrbuf driver; FFstrbuf apiVersion; FFstrbuf conformanceVersion; FFstrbuf instanceVersion; - FFlist gpus; //List of FFGPUResult, see detection/gpu/gpu.h + FFlist gpus; // List of FFGPUResult, see detection/gpu/gpu.h const char* error; } FFVulkanResult; diff --git a/src/detection/wallpaper/wallpaper_linux.c b/src/detection/wallpaper/wallpaper_linux.c index d2aa65b6c..ee709b1cd 100644 --- a/src/detection/wallpaper/wallpaper_linux.c +++ b/src/detection/wallpaper/wallpaper_linux.c @@ -2,25 +2,26 @@ #include "common/settings.h" #include "detection/gtk_qt/gtk_qt.h" -const char* ffDetectWallpaper(FFstrbuf* result) -{ +const char* ffDetectWallpaper(FFstrbuf* result) { const FFstrbuf* wallpaper = NULL; const FFGTKResult* gtk = ffDetectGTK4(); - if (gtk->wallpaper.length) + if (gtk->wallpaper.length) { wallpaper = >k->wallpaper; - else - { + } else { const FFQtResult* qt = ffDetectQt(); - if (qt->wallpaper.length) + if (qt->wallpaper.length) { wallpaper = &qt->wallpaper; + } } - if (!wallpaper) + if (!wallpaper) { return "Failed to detect the current wallpaper path"; + } - if (ffStrbufStartsWithS(wallpaper, "file:///")) + if (ffStrbufStartsWithS(wallpaper, "file:///")) { ffStrbufAppendS(result, wallpaper->chars + strlen("file://")); - else + } else { ffStrbufAppend(result, wallpaper); + } return NULL; } diff --git a/src/detection/wallpaper/wallpaper_nosupport.c b/src/detection/wallpaper/wallpaper_nosupport.c index 787b106af..ce4f73d21 100644 --- a/src/detection/wallpaper/wallpaper_nosupport.c +++ b/src/detection/wallpaper/wallpaper_nosupport.c @@ -1,6 +1,5 @@ #include "wallpaper.h" -const char* ffDetectWallpaper(FF_MAYBE_UNUSED FFstrbuf* result) -{ +const char* ffDetectWallpaper(FF_MAYBE_UNUSED FFstrbuf* result) { return "Not supported on this platform"; } diff --git a/src/detection/wallpaper/wallpaper_windows.c b/src/detection/wallpaper/wallpaper_windows.c index 8a5324c84..2adf08394 100644 --- a/src/detection/wallpaper/wallpaper_windows.c +++ b/src/detection/wallpaper/wallpaper_windows.c @@ -1,14 +1,15 @@ #include "wallpaper.h" #include "common/windows/registry.h" -const char* ffDetectWallpaper(FFstrbuf* result) -{ +const char* ffDetectWallpaper(FFstrbuf* result) { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if(!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop", &hKey, NULL)) + if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop", &hKey, NULL)) { return "ffRegOpenKeyForRead(Control Panel\\Desktop) failed"; + } - if(!ffRegReadStrbuf(hKey, L"WallPaper", result, NULL)) + if (!ffRegReadStrbuf(hKey, L"WallPaper", result, NULL)) { return "ffRegReadStrbuf(WallPaper) failed"; + } return NULL; } diff --git a/src/detection/weather/weather.c b/src/detection/weather/weather.c index 150c9e36f..69df64290 100644 --- a/src/detection/weather/weather.c +++ b/src/detection/weather/weather.c @@ -1,14 +1,12 @@ #include "weather.h" #include "common/networking.h" -#define FF_UNITIALIZED ((const char*)(uintptr_t) -1) +#define FF_UNITIALIZED ((const char*) (uintptr_t) -1) static FFNetworkingState state; static const char* status = FF_UNITIALIZED; -void ffPrepareWeather(FFWeatherOptions* options) -{ - if (status != FF_UNITIALIZED) - { +void ffPrepareWeather(FFWeatherOptions* options) { + if (status != FF_UNITIALIZED) { fputs("Error: Weather module can only be used once due to internal limitations\n", stderr); exit(1); } @@ -16,12 +14,12 @@ void ffPrepareWeather(FFWeatherOptions* options) state.timeout = options->timeout; FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/"); - if (options->location.length) + if (options->location.length) { ffStrbufAppend(&path, &options->location); + } ffStrbufAppendS(&path, "?format="); ffStrbufAppend(&path, &options->outputFormat); - switch (instance.config.display.tempUnit) - { + switch (instance.config.display.tempUnit) { case FF_TEMPERATURE_UNIT_CELSIUS: ffStrbufAppendS(&path, "&m"); break; @@ -34,30 +32,31 @@ void ffPrepareWeather(FFWeatherOptions* options) status = ffNetworkingSendHttpRequest(&state, "wttr.in", path.chars, "User-Agent: curl/0.0.0\r\n"); } -const char* ffDetectWeather(FFWeatherOptions* options, FFstrbuf* result) -{ - if(status == FF_UNITIALIZED) +const char* ffDetectWeather(FFWeatherOptions* options, FFstrbuf* result) { + if (status == FF_UNITIALIZED) { ffPrepareWeather(options); + } - if(status != NULL) + if (status != NULL) { return status; + } ffStrbufEnsureFree(result, 4095); const char* error = ffNetworkingRecvHttpResponse(&state, result); - state = (FFNetworkingState){}; + state = (FFNetworkingState) {}; status = FF_UNITIALIZED; - if (error == NULL) - { + if (error == NULL) { ffStrbufSubstrAfterFirstS(result, "\r\n\r\n"); ffStrbufTrimRightSpace(result); - } - else + } else { return error; + } - if(result->length == 0) + if (result->length == 0) { return "Empty server response received"; + } return NULL; } diff --git a/src/detection/wifi/wifi.h b/src/detection/wifi/wifi.h index a7a99f4e4..df29a43e3 100644 --- a/src/detection/wifi/wifi.h +++ b/src/detection/wifi/wifi.h @@ -3,14 +3,12 @@ #include "fastfetch.h" #include "modules/wifi/option.h" -struct FFWifiInterface -{ +struct FFWifiInterface { FFstrbuf description; FFstrbuf status; }; -struct FFWifiConnection -{ +struct FFWifiConnection { FFstrbuf status; FFstrbuf ssid; FFstrbuf bssid; @@ -23,22 +21,21 @@ struct FFWifiConnection uint16_t frequency; // MHz }; -typedef struct FFWifiResult -{ +typedef struct FFWifiResult { struct FFWifiInterface inf; struct FFWifiConnection conn; } FFWifiResult; const char* ffDetectWifi(FFlist* result /*list of FFWifiItem*/); -static inline uint16_t ffWifiFreqToChannel(uint16_t frequency) -{ +static inline uint16_t ffWifiFreqToChannel(uint16_t frequency) { // https://github.com/opetryna/win32wifi/blob/master/win32wifi/Win32Wifi.py#L140 // FIXME: Does it work for 6 GHz? - if (frequency == 2484) + if (frequency == 2484) { return 14; - else if (frequency < 2484) + } else if (frequency < 2484) { return (uint16_t) ((frequency - 2407) / 5); - else + } else { return (uint16_t) ((frequency / 5) - 1000); + } } diff --git a/src/detection/wifi/wifi_android.c b/src/detection/wifi/wifi_android.c index e74a96b37..472324cc6 100644 --- a/src/detection/wifi/wifi_android.c +++ b/src/detection/wifi/wifi_android.c @@ -6,33 +6,31 @@ #define FF_TERMUX_API_PATH FASTFETCH_TARGET_DIR_ROOT "/libexec/termux-api" #define FF_TERMUX_API_PARAM "WifiConnectionInfo" -static inline void wrapYyjsonFree(yyjson_doc** doc) -{ +static inline void wrapYyjsonFree(yyjson_doc** doc) { assert(doc); - if (*doc) + if (*doc) { yyjson_doc_free(*doc); + } } -const char* ffDetectWifi(FFlist* result) -{ +const char* ffDetectWifi(FFlist* result) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if(ffProcessAppendStdOut(&buffer, (char* const[]){ - FF_TERMUX_API_PATH, - FF_TERMUX_API_PARAM, - NULL - })) + if (ffProcessAppendStdOut(&buffer, (char* const[]) {FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, NULL})) { return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed"; + } yyjson_doc* __attribute__((__cleanup__(wrapYyjsonFree))) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, NULL, NULL); - if (!doc) + if (!doc) { return "Failed to parse wifi connection info"; + } yyjson_val* root = yyjson_doc_get_root(doc); - if (!yyjson_is_obj(root)) + if (!yyjson_is_obj(root)) { return "Wifi info result is not a JSON object"; + } - FFWifiResult* item = (FFWifiResult*)ffListAdd(result); + FFWifiResult* item = (FFWifiResult*) ffListAdd(result); ffStrbufInit(&item->inf.description); ffStrbufInit(&item->inf.status); ffStrbufInit(&item->conn.status); @@ -47,17 +45,18 @@ const char* ffDetectWifi(FFlist* result) item->conn.frequency = 0; ffStrbufAppendJsonVal(&item->inf.status, yyjson_obj_get(root, "supplicant_state")); - if(!item->inf.status.length) - { + if (!item->inf.status.length) { ffStrbufAppendS(&item->inf.status, "Unknown"); return NULL; } - if(!ffStrbufEqualS(&item->inf.status, "COMPLETED")) + if (!ffStrbufEqualS(&item->inf.status, "COMPLETED")) { return NULL; + } double rssi = yyjson_get_num(yyjson_obj_get(root, "rssi")); - item->conn.signalQuality = rssi >= -50 ? 100 : rssi <= -100 ? 0 : (rssi + 100) * 2; + item->conn.signalQuality = rssi >= -50 ? 100 : rssi <= -100 ? 0 + : (rssi + 100) * 2; ffStrbufAppendJsonVal(&item->inf.description, yyjson_obj_get(root, "ip")); ffStrbufAppendJsonVal(&item->conn.bssid, yyjson_obj_get(root, "bssid")); diff --git a/src/detection/wifi/wifi_bsd.c b/src/detection/wifi/wifi_bsd.c index efe05cc95..7c3f7d79d 100644 --- a/src/detection/wifi/wifi_bsd.c +++ b/src/detection/wifi/wifi_bsd.c @@ -8,21 +8,19 @@ #include #include -const char* ffDetectWifi(FFlist* result) -{ +const char* ffDetectWifi(FFlist* result) { struct if_nameindex* infs = if_nameindex(); - if(!infs) { + if (!infs) { return "if_nameindex() failed"; } FF_AUTO_CLOSE_FD int sock = socket(AF_INET, SOCK_DGRAM, 0); - if(sock < 0) { + if (sock < 0) { if_freenameindex(infs); return "socket() failed"; } - for(struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) - { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { if (!ffStrStartsWith(i->if_name, "wlan")) { continue; } @@ -70,8 +68,7 @@ const char* ffDetectWifi(FFlist* result) ireq.i_len = sizeof(bssid); if (ioctl(sock, SIOCG80211, &ireq) >= 0) { - ffStrbufSetF(&item->conn.bssid, "%02X:%02X:%02X:%02X:%02X:%02X", - bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); + ffStrbufSetF(&item->conn.bssid, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); } struct ieee80211_channel curchan = {}; @@ -83,23 +80,24 @@ const char* ffDetectWifi(FFlist* result) item->conn.channel = curchan.ic_ieee; item->conn.frequency = curchan.ic_freq; - #ifdef IEEE80211_IS_CHAN_HE // for future use - if (IEEE80211_IS_CHAN_HE(&curchan)) +#ifdef IEEE80211_IS_CHAN_HE // for future use + if (IEEE80211_IS_CHAN_HE(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11ax (Wi-Fi 6)"); - else - #endif - if (IEEE80211_IS_CHAN_VHT(&curchan)) + } else +#endif + if (IEEE80211_IS_CHAN_VHT(&curchan)) ffStrbufSetStatic(&item->conn.protocol, "802.11ac (Wi-Fi 5)"); - else if (IEEE80211_IS_CHAN_HT(&curchan)) + else if (IEEE80211_IS_CHAN_HT(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11n (Wi-Fi 4)"); - else if (IEEE80211_IS_CHAN_ANYG(&curchan)) + } else if (IEEE80211_IS_CHAN_ANYG(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11g"); - else if (IEEE80211_IS_CHAN_B(&curchan)) + } else if (IEEE80211_IS_CHAN_B(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11b"); - else if (IEEE80211_IS_CHAN_A(&curchan)) + } else if (IEEE80211_IS_CHAN_A(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11a"); - else if (IEEE80211_IS_CHAN_FHSS(&curchan)) + } else if (IEEE80211_IS_CHAN_FHSS(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11 (FHSS)"); + } } union { @@ -114,7 +112,8 @@ const char* ffDetectWifi(FFlist* result) if (ioctl(sock, SIOCG80211, &ireq) >= 0) { struct ieee80211req_sta_info* sta = stareq.req.info; if (sta->isi_len != 0) { - item->conn.signalQuality = (sta->isi_rssi >= -50 ? 100 : sta->isi_rssi <= -100 ? 0 : (sta->isi_rssi + 100) * 2); + item->conn.signalQuality = (sta->isi_rssi >= -50 ? 100 : sta->isi_rssi <= -100 ? 0 + : (sta->isi_rssi + 100) * 2); item->conn.rxRate = sta->isi_txmbps * 0.5; } } @@ -124,27 +123,27 @@ const char* ffDetectWifi(FFlist* result) ireq.i_len = 0; if (ioctl(sock, SIOCG80211, &ireq) >= 0) { switch (ireq.i_val) { - case IEEE80211_AUTH_NONE: - ffStrbufSetStatic(&item->conn.security, "Insecure"); - break; - case IEEE80211_AUTH_OPEN: - ffStrbufSetStatic(&item->conn.security, "Open"); - break; - case IEEE80211_AUTH_SHARED: - ffStrbufSetStatic(&item->conn.security, "Shared"); - break; - case IEEE80211_AUTH_8021X: - ffStrbufSetStatic(&item->conn.security, "8021X"); - break; - case IEEE80211_AUTH_AUTO: - ffStrbufSetStatic(&item->conn.security, "Auto"); - break; - case IEEE80211_AUTH_WPA: - ffStrbufSetStatic(&item->conn.security, "WPA"); - break; - default: - ffStrbufSetF(&item->conn.security, "Unknown (%d)", ireq.i_val); - break; + case IEEE80211_AUTH_NONE: + ffStrbufSetStatic(&item->conn.security, "Insecure"); + break; + case IEEE80211_AUTH_OPEN: + ffStrbufSetStatic(&item->conn.security, "Open"); + break; + case IEEE80211_AUTH_SHARED: + ffStrbufSetStatic(&item->conn.security, "Shared"); + break; + case IEEE80211_AUTH_8021X: + ffStrbufSetStatic(&item->conn.security, "8021X"); + break; + case IEEE80211_AUTH_AUTO: + ffStrbufSetStatic(&item->conn.security, "Auto"); + break; + case IEEE80211_AUTH_WPA: + ffStrbufSetStatic(&item->conn.security, "WPA"); + break; + default: + ffStrbufSetF(&item->conn.security, "Unknown (%d)", ireq.i_val); + break; } } } diff --git a/src/detection/wifi/wifi_linux.c b/src/detection/wifi/wifi_linux.c index 199b9cdb9..7cf249581 100644 --- a/src/detection/wifi/wifi_linux.c +++ b/src/detection/wifi/wifi_linux.c @@ -11,46 +11,44 @@ #ifdef FF_HAVE_DBUS // https://people.freedesktop.org/~lkundrak/nm-docs/nm-dbus-types.html#NM80211ApFlags typedef enum { - NM_802_11_AP_FLAGS_NONE = 0x00000000, + NM_802_11_AP_FLAGS_NONE = 0x00000000, NM_802_11_AP_FLAGS_PRIVACY = 0x00000001, - NM_802_11_AP_FLAGS_WPS = 0x00000002, + NM_802_11_AP_FLAGS_WPS = 0x00000002, NM_802_11_AP_FLAGS_WPS_PBC = 0x00000004, NM_802_11_AP_FLAGS_WPS_PIN = 0x00000008, } NM80211ApFlags; // https://people.freedesktop.org/~lkundrak/nm-docs/nm-dbus-types.html#NM80211ApSecurityFlags typedef enum { - NM_802_11_AP_SEC_NONE = 0x00000000, - NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001, - NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002, - NM_802_11_AP_SEC_PAIR_TKIP = 0x00000004, - NM_802_11_AP_SEC_PAIR_CCMP = 0x00000008, - NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010, - NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020, - NM_802_11_AP_SEC_GROUP_TKIP = 0x00000040, - NM_802_11_AP_SEC_GROUP_CCMP = 0x00000080, - NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100, - NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200, - NM_802_11_AP_SEC_KEY_MGMT_SAE = 0x00000400, - NM_802_11_AP_SEC_KEY_MGMT_OWE = 0x00000800, - NM_802_11_AP_SEC_KEY_MGMT_OWE_TM = 0x00001000, + NM_802_11_AP_SEC_NONE = 0x00000000, + NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001, + NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002, + NM_802_11_AP_SEC_PAIR_TKIP = 0x00000004, + NM_802_11_AP_SEC_PAIR_CCMP = 0x00000008, + NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010, + NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020, + NM_802_11_AP_SEC_GROUP_TKIP = 0x00000040, + NM_802_11_AP_SEC_GROUP_CCMP = 0x00000080, + NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100, + NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200, + NM_802_11_AP_SEC_KEY_MGMT_SAE = 0x00000400, + NM_802_11_AP_SEC_KEY_MGMT_OWE = 0x00000800, + NM_802_11_AP_SEC_KEY_MGMT_OWE_TM = 0x00001000, NM_802_11_AP_SEC_KEY_MGMT_EAP_SUITE_B_192 = 0x00002000, } NM80211ApSecurityFlags; -#define FF_DBUS_ITER_CONTINUE(dbus, iterator) \ - { \ - if(!(dbus).lib->ffdbus_message_iter_next(iterator)) \ - break; \ - continue; \ - } +# define FF_DBUS_ITER_CONTINUE(dbus, iterator) \ + { \ + if (!(dbus).lib->ffdbus_message_iter_next(iterator)) \ + break; \ + continue; \ + } -static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer) -{ +static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer) { FF_DEBUG("Starting NetworkManager wifi detection for interface %s", item->inf.description.chars); FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; const char* error = ffDBusLoadData(DBUS_BUS_SYSTEM, &dbus); - if(error) - { + if (error) { FF_DEBUG("Failed to load DBus data: %s", error); return error; } @@ -58,16 +56,14 @@ 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, NULL); - if(!device) - { + if (!device) { FF_DEBUG("GetDeviceByIpIface failed for interface %s", item->inf.description.chars); return "Failed to call GetDeviceByIpIface"; } ffStrbufClear(buffer); DBusMessageIter rootIter; - if(!dbus.lib->ffdbus_message_iter_init(device, &rootIter) || !ffDBusGetString(&dbus, &rootIter, buffer)) - { + if (!dbus.lib->ffdbus_message_iter_init(device, &rootIter) || !ffDBusGetString(&dbus, &rootIter, buffer)) { FF_DEBUG("Failed to initialize message iterator or get device path"); dbus.lib->ffdbus_message_unref(device); return "Failed to get device path"; @@ -76,46 +72,40 @@ static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer) dbus.lib->ffdbus_message_unref(device); } - if (item->conn.txRate == -DBL_MAX) - { + if (item->conn.txRate == -DBL_MAX) { FF_DEBUG("Getting bitrate from NetworkManager"); uint32_t bitrate; - if (ffDBusGetPropertyUint(&dbus, "org.freedesktop.NetworkManager", buffer->chars, "org.freedesktop.NetworkManager.Device.Wireless", "Bitrate", &bitrate)) - { + if (ffDBusGetPropertyUint(&dbus, "org.freedesktop.NetworkManager", buffer->chars, "org.freedesktop.NetworkManager.Device.Wireless", "Bitrate", &bitrate)) { item->conn.txRate = bitrate / 1000.; FF_DEBUG("Got bitrate: %.2f Mbps", item->conn.txRate); - } - else + } else { FF_DEBUG("Failed to get bitrate"); + } } FF_DEBUG("Getting active access point path"); FF_STRBUF_AUTO_DESTROY apPath = ffStrbufCreate(); - if (!ffDBusGetPropertyString(&dbus, "org.freedesktop.NetworkManager", buffer->chars, "org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint", &apPath)) - { + if (!ffDBusGetPropertyString(&dbus, "org.freedesktop.NetworkManager", buffer->chars, "org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint", &apPath)) { FF_DEBUG("Failed to get active access point path"); return "Failed to get active access point path"; } FF_DEBUG("Got access point path: %s", apPath.chars); - if (!item->conn.status.length) - { + if (!item->conn.status.length) { ffStrbufSetStatic(&item->conn.status, "connected"); FF_DEBUG("Setting connection status to 'connected'"); } FF_DEBUG("Getting access point properties"); DBusMessage* reply = ffDBusGetAllProperties(&dbus, "org.freedesktop.NetworkManager", apPath.chars, "org.freedesktop.NetworkManager.AccessPoint"); - if(reply == NULL) - { + if (reply == NULL) { FF_DEBUG("Failed to get access point properties"); return "Failed to get access point properties"; } DBusMessageIter rootIterator; - if(!dbus.lib->ffdbus_message_iter_init(reply, &rootIterator) && - dbus.lib->ffdbus_message_iter_get_arg_type(&rootIterator) != DBUS_TYPE_ARRAY) - { + if (!dbus.lib->ffdbus_message_iter_init(reply, &rootIterator) && + dbus.lib->ffdbus_message_iter_get_arg_type(&rootIterator) != DBUS_TYPE_ARRAY) { FF_DEBUG("Invalid type of access point properties"); dbus.lib->ffdbus_message_unref(reply); return "Invalid type of access point properties"; @@ -129,10 +119,10 @@ static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer) int flagCount = 0; FF_DEBUG("Parsing access point properties"); - while(true) - { - if(dbus.lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DICT_ENTRY) + 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); @@ -142,81 +132,63 @@ static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer) dbus.lib->ffdbus_message_iter_next(&dictIterator); - if (ffStrEquals(key, "Ssid")) - { - if (!item->conn.ssid.length) - { + if (ffStrEquals(key, "Ssid")) { + if (!item->conn.ssid.length) { FF_DEBUG("Found SSID property"); ffDBusGetString(&dbus, &dictIterator, &item->conn.ssid); FF_DEBUG("SSID: %s", item->conn.ssid.chars); } - } - else if (ffStrEquals(key, "HwAddress")) - { - if (!item->conn.bssid.length) - { + } else if (ffStrEquals(key, "HwAddress")) { + if (!item->conn.bssid.length) { FF_DEBUG("Found HwAddress property"); ffDBusGetString(&dbus, &dictIterator, &item->conn.bssid); FF_DEBUG("BSSID: %s", item->conn.bssid.chars); } - } - else if (ffStrEquals(key, "Strength")) - { - if (item->conn.signalQuality == -DBL_MAX) - { + } else if (ffStrEquals(key, "Strength")) { + if (item->conn.signalQuality == -DBL_MAX) { FF_DEBUG("Found Strength property"); uint32_t strengthPercent; - if (ffDBusGetUint(&dbus, &dictIterator, &strengthPercent)) - { + if (ffDBusGetUint(&dbus, &dictIterator, &strengthPercent)) { item->conn.signalQuality = strengthPercent; FF_DEBUG("Signal quality: %u%%", strengthPercent); } } - } - else if (ffStrEquals(key, "Frequency")) - { - if (item->conn.frequency == 0) - { + } else if (ffStrEquals(key, "Frequency")) { + if (item->conn.frequency == 0) { FF_DEBUG("Found Frequency property"); uint32_t frequency; - if (ffDBusGetUint(&dbus, &dictIterator, &frequency)) - { + if (ffDBusGetUint(&dbus, &dictIterator, &frequency)) { item->conn.frequency = (uint16_t) frequency; FF_DEBUG("Frequency: %u MHz", item->conn.frequency); - if (item->conn.channel == 0) - { + if (item->conn.channel == 0) { item->conn.channel = ffWifiFreqToChannel(item->conn.frequency); FF_DEBUG("Calculated channel: %u", item->conn.channel); } } } - } - else if ((ffStrEquals(key, "Flags") && ffDBusGetUint(&dbus, &dictIterator, &flags)) || + } else if ((ffStrEquals(key, "Flags") && ffDBusGetUint(&dbus, &dictIterator, &flags)) || (ffStrEquals(key, "WpaFlags") && ffDBusGetUint(&dbus, &dictIterator, &wpaFlags)) || - (ffStrEquals(key, "RsnFlags") && ffDBusGetUint(&dbus, &dictIterator, &rsnFlags)) - ) + (ffStrEquals(key, "RsnFlags") && ffDBusGetUint(&dbus, &dictIterator, &rsnFlags))) { ++flagCount; + } FF_DBUS_ITER_CONTINUE(dbus, &arrayIterator) } - if (flagCount == 3) - { + if (flagCount == 3) { FF_DEBUG("Determining security type from flags (Flags: 0x%08x, WPA: 0x%08x, RSN: 0x%08x)", - flags, wpaFlags, rsnFlags); - if ((flags & NM_802_11_AP_FLAGS_PRIVACY) && (wpaFlags == NM_802_11_AP_SEC_NONE) - && (rsnFlags == NM_802_11_AP_SEC_NONE)) - { + flags, + wpaFlags, + rsnFlags); + if ((flags & NM_802_11_AP_FLAGS_PRIVACY) && (wpaFlags == NM_802_11_AP_SEC_NONE) && (rsnFlags == NM_802_11_AP_SEC_NONE)) { ffStrbufAppendS(&item->conn.security, "WEP/"); FF_DEBUG("Adding security: WEP"); } - if (wpaFlags != NM_802_11_AP_SEC_NONE) - { + if (wpaFlags != NM_802_11_AP_SEC_NONE) { ffStrbufAppendS(&item->conn.security, "WPA/"); FF_DEBUG("Adding security: WPA"); } - if ((rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_PSK) - || (rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { + if ((rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_PSK) || (rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { ffStrbufAppendS(&item->conn.security, "WPA2/"); FF_DEBUG("Adding security: WPA2"); } @@ -224,23 +196,18 @@ static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer) ffStrbufAppendS(&item->conn.security, "WPA3/"); FF_DEBUG("Adding security: WPA3"); } - if ((rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_OWE) - || (rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_OWE_TM)) { + if ((rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_OWE) || (rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_OWE_TM)) { ffStrbufAppendS(&item->conn.security, "OWE/"); FF_DEBUG("Adding security: OWE"); } - if ((wpaFlags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) - || (rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { + if ((wpaFlags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) || (rsnFlags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { ffStrbufAppendS(&item->conn.security, "802.1X/"); FF_DEBUG("Adding security: 802.1X"); } - if (!item->conn.security.length) - { + if (!item->conn.security.length) { ffStrbufAppendS(&item->conn.security, "Insecure"); FF_DEBUG("No security detected, marking as 'Insecure'"); - } - else - { + } else { ffStrbufTrimRight(&item->conn.security, '/'); FF_DEBUG("Final security string: %s", item->conn.security.chars); } @@ -259,32 +226,22 @@ static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer) } #endif // FF_HAVE_DBUS -static const char* detectWifiWithIw(FFWifiResult* item, FFstrbuf* buffer) -{ +static const char* detectWifiWithIw(FFWifiResult* item, FFstrbuf* buffer) { FF_DEBUG("Starting iw wifi detection for interface %s", item->inf.description.chars); const char* error = NULL; FF_STRBUF_AUTO_DESTROY output = ffStrbufCreate(); FF_DEBUG("Executing 'iw dev %s link'", item->inf.description.chars); - if((error = ffProcessAppendStdOut(&output, (char* const[]){ - "iw", - "dev", - item->inf.description.chars, - "link", - NULL - }))) - { + if ((error = ffProcessAppendStdOut(&output, (char* const[]) {"iw", "dev", item->inf.description.chars, "link", NULL}))) { FF_DEBUG("iw command execution failed: %s", error); return error; } - if(output.length == 0) - { + if (output.length == 0) { FF_DEBUG("iw command output is empty"); return "iw command execution failed"; } - if(!ffParsePropLines(output.chars, "Connected to ", &item->conn.bssid)) - { + if (!ffParsePropLines(output.chars, "Connected to ", &item->conn.bssid)) { FF_DEBUG("Not connected to any access point"); ffStrbufAppendS(&item->conn.status, "disconnected"); return NULL; @@ -296,64 +253,53 @@ static const char* detectWifiWithIw(FFWifiResult* item, FFstrbuf* buffer) ffStrbufUpperCase(&item->conn.bssid); FF_DEBUG("BSSID: %s", item->conn.bssid.chars); - if(ffParsePropLines(output.chars, "SSID: ", &item->conn.ssid)) - { + if (ffParsePropLines(output.chars, "SSID: ", &item->conn.ssid)) { FF_DEBUG("SSID: %s", item->conn.ssid.chars); - if (ffStrbufDecodeHexEscapeSequences(&item->conn.ssid)) + if (ffStrbufDecodeHexEscapeSequences(&item->conn.ssid)) { FF_DEBUG("Decoded SSID: %s", item->conn.ssid.chars); - } - else + } + } else { FF_DEBUG("SSID not found in iw output"); + } ffStrbufClear(buffer); - if(ffParsePropLines(output.chars, "signal: ", buffer)) - { + if (ffParsePropLines(output.chars, "signal: ", buffer)) { int level = (int) ffStrbufToSInt(buffer, INT_MAX); - if (level != INT_MAX) - { - item->conn.signalQuality = level >= -50 ? 100 : level <= -100 ? 0 : (level + 100) * 2; + if (level != INT_MAX) { + item->conn.signalQuality = level >= -50 ? 100 : level <= -100 ? 0 + : (level + 100) * 2; FF_DEBUG("Signal level: %d dBm, quality: %.0f%%", level, item->conn.signalQuality); } } ffStrbufClear(buffer); - if(ffParsePropLines(output.chars, "rx bitrate: ", buffer)) - { + if (ffParsePropLines(output.chars, "rx bitrate: ", buffer)) { item->conn.rxRate = ffStrbufToDouble(buffer, -DBL_MAX); FF_DEBUG("RX bitrate: %.2f Mbps", item->conn.rxRate); } ffStrbufClear(buffer); - if(ffParsePropLines(output.chars, "tx bitrate: ", buffer)) - { + if (ffParsePropLines(output.chars, "tx bitrate: ", buffer)) { item->conn.txRate = ffStrbufToDouble(buffer, -DBL_MAX); FF_DEBUG("TX bitrate: %.2f Mbps (raw: %s)", item->conn.txRate, buffer->chars); - if(ffStrbufContainS(buffer, " EHT-MCS ")) - { + if (ffStrbufContainS(buffer, " EHT-MCS ")) { ffStrbufSetStatic(&item->conn.protocol, "802.11be (Wi-Fi 7)"); FF_DEBUG("Detected protocol: Wi-Fi 7"); - } - else if(ffStrbufContainS(buffer, " HE-MCS ")) - { + } else if (ffStrbufContainS(buffer, " HE-MCS ")) { ffStrbufSetStatic(&item->conn.protocol, "802.11ax (Wi-Fi 6)"); FF_DEBUG("Detected protocol: Wi-Fi 6"); - } - else if(ffStrbufContainS(buffer, " VHT-MCS ")) - { + } else if (ffStrbufContainS(buffer, " VHT-MCS ")) { ffStrbufSetStatic(&item->conn.protocol, "802.11ac (Wi-Fi 5)"); FF_DEBUG("Detected protocol: Wi-Fi 5"); - } - else if(ffStrbufContainS(buffer, " MCS ")) - { + } else if (ffStrbufContainS(buffer, " MCS ")) { ffStrbufSetStatic(&item->conn.protocol, "802.11n (Wi-Fi 4)"); FF_DEBUG("Detected protocol: Wi-Fi 4"); } } ffStrbufClear(buffer); - if(ffParsePropLines(output.chars, "freq: ", buffer)) - { + if (ffParsePropLines(output.chars, "freq: ", buffer)) { item->conn.frequency = (uint16_t) ffStrbufToUInt(buffer, 0); item->conn.channel = ffWifiFreqToChannel(item->conn.frequency); FF_DEBUG("Frequency: %u MHz, Channel: %u", item->conn.frequency, item->conn.channel); @@ -364,17 +310,15 @@ static const char* detectWifiWithIw(FFWifiResult* item, FFstrbuf* buffer) } #if FF_HAVE_LINUX_WIRELESS -#include -#include -#include -#include +# include +# include +# include +# include -static const char* detectWifiWithIoctls(FFWifiResult* item) -{ +static const char* detectWifiWithIoctls(FFWifiResult* item) { FF_DEBUG("Starting ioctl wifi detection for interface %s", item->inf.description.chars); FF_AUTO_CLOSE_FD int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); - if(sock < 0) - { + if (sock < 0) { FF_DEBUG("Failed to create socket: %s", strerror(errno)); return "socket() failed"; } @@ -388,69 +332,61 @@ static const char* detectWifiWithIoctls(FFWifiResult* item) iwr.u.essid.pointer = (caddr_t) item->conn.ssid.chars; iwr.u.essid.length = IW_ESSID_MAX_SIZE + 1; iwr.u.essid.flags = 0; - if(ioctl(sock, SIOCGIWESSID, &iwr) >= 0) - { + if (ioctl(sock, SIOCGIWESSID, &iwr) >= 0) { ffStrbufSetStatic(&item->conn.status, "connected"); ffStrbufRecalculateLength(&item->conn.ssid); FF_DEBUG("SSID: %s", item->conn.ssid.chars); - } - else + } else { FF_DEBUG("Failed to get SSID via ioctl: %s", strerror(errno)); + } // Get protocol name FF_DEBUG("Getting protocol name via ioctl"); - if(ioctl(sock, SIOCGIWNAME, &iwr) >= 0 && !ffStrEqualsIgnCase(iwr.u.name, "IEEE 802.11")) - { - if(ffStrStartsWithIgnCase(iwr.u.name, "IEEE ")) + if (ioctl(sock, SIOCGIWNAME, &iwr) >= 0 && !ffStrEqualsIgnCase(iwr.u.name, "IEEE 802.11")) { + if (ffStrStartsWithIgnCase(iwr.u.name, "IEEE ")) { ffStrbufSetS(&item->conn.protocol, iwr.u.name + strlen("IEEE ")); - else + } else { ffStrbufSetS(&item->conn.protocol, iwr.u.name); + } FF_DEBUG("Protocol: %s", item->conn.protocol.chars); - } - else + } else { FF_DEBUG("Failed to get protocol name via ioctl: %s", strerror(errno)); + } // Get BSSID FF_DEBUG("Getting BSSID via ioctl"); - if(ioctl(sock, SIOCGIWAP, &iwr) >= 0) - { - for(int i = 0; i < 6; ++i) + if (ioctl(sock, SIOCGIWAP, &iwr) >= 0) { + for (int i = 0; i < 6; ++i) { ffStrbufAppendF(&item->conn.bssid, "%.2X:", (uint8_t) iwr.u.ap_addr.sa_data[i]); + } ffStrbufTrimRight(&item->conn.bssid, ':'); FF_DEBUG("BSSID: %s", item->conn.bssid.chars); - } - else + } else { FF_DEBUG("Failed to get BSSID via ioctl: %s", strerror(errno)); + } // Get bitrate FF_DEBUG("Getting bitrate via ioctl"); - if(ioctl(sock, SIOCGIWRATE, &iwr) >= 0) - { + if (ioctl(sock, SIOCGIWRATE, &iwr) >= 0) { item->conn.txRate = iwr.u.bitrate.value / 1000000.; FF_DEBUG("TX bitrate: %.2f Mbps", item->conn.txRate); - } - else + } else { FF_DEBUG("Failed to get bitrate via ioctl: %s", strerror(errno)); + } // Get frequency/channel FF_DEBUG("Getting frequency via ioctl"); - if(ioctl(sock, SIOCGIWFREQ, &iwr) >= 0) - { - if (iwr.u.freq.e == 0 && iwr.u.freq.m <= 1000) - { + if (ioctl(sock, SIOCGIWFREQ, &iwr) >= 0) { + if (iwr.u.freq.e == 0 && iwr.u.freq.m <= 1000) { item->conn.channel = (uint16_t) iwr.u.freq.m; FF_DEBUG("Direct channel value: %u", item->conn.channel); - } - else - { + } else { // convert it to MHz - while (iwr.u.freq.e < 6) - { + while (iwr.u.freq.e < 6) { iwr.u.freq.m /= 10; iwr.u.freq.e++; } - while (iwr.u.freq.e > 6) - { + while (iwr.u.freq.e > 6) { iwr.u.freq.m *= 10; iwr.u.freq.e--; } @@ -458,9 +394,9 @@ static const char* detectWifiWithIoctls(FFWifiResult* item) item->conn.channel = ffWifiFreqToChannel(item->conn.frequency); FF_DEBUG("Frequency: %u MHz, Channel: %u", item->conn.frequency, item->conn.channel); } - } - else + } else { FF_DEBUG("Failed to get frequency via ioctl: %s", strerror(errno)); + } // Get signal strength FF_DEBUG("Getting signal stats via ioctl"); @@ -469,14 +405,14 @@ static const char* detectWifiWithIoctls(FFWifiResult* item) iwr.u.data.length = sizeof(stats); iwr.u.data.flags = 0; - if(ioctl(sock, SIOCGIWSTATS, &iwr) >= 0) - { + if (ioctl(sock, SIOCGIWSTATS, &iwr) >= 0) { int8_t level = (int8_t) stats.qual.level; - item->conn.signalQuality = level >= -50 ? 100 : level <= -100 ? 0 : (level + 100) * 2; + item->conn.signalQuality = level >= -50 ? 100 : level <= -100 ? 0 + : (level + 100) * 2; FF_DEBUG("Signal level: %d dBm, quality: %.0f%%", level, item->conn.signalQuality); - } - else + } else { FF_DEBUG("Failed to get signal stats via ioctl: %s", strerror(errno)); + } // Get security info FF_DEBUG("Getting security info via ioctl"); @@ -484,10 +420,8 @@ static const char* detectWifiWithIoctls(FFWifiResult* item) iwr.u.data.pointer = &iwe; iwr.u.data.length = sizeof(iwe); iwr.u.data.flags = 0; - if(ioctl(sock, SIOCGIWENCODEEXT, &iwr) >= 0) - { - switch(iwe.alg) - { + if (ioctl(sock, SIOCGIWENCODEEXT, &iwr) >= 0) { + switch (iwe.alg) { case IW_ENCODE_ALG_WEP: ffStrbufAppendS(&item->conn.security, "WEP"); FF_DEBUG("Security: WEP"); @@ -513,39 +447,35 @@ static const char* detectWifiWithIoctls(FFWifiResult* item) FF_DEBUG("Security: Unknown (%d)", (int) iwe.alg); break; } - } - else + } else { FF_DEBUG("Failed to get security info via ioctl: %s", strerror(errno)); + } FF_DEBUG("ioctl wifi detection completed"); return NULL; } #endif // FF_HAVE_LINUX_WIRELESS -const char* ffDetectWifi(FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectWifi(FF_MAYBE_UNUSED FFlist* result) { FF_DEBUG("Starting wifi detection"); struct if_nameindex* infs = if_nameindex(); - if(!infs) - { + if (!infs) { FF_DEBUG("if_nameindex() failed: %s", strerror(errno)); return "if_nameindex() failed"; } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - for(struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) - { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { FF_DEBUG("Checking interface: %s (index: %u)", i->if_name, i->if_index); ffStrbufSetF(&buffer, "/sys/class/net/%s/phy80211/", i->if_name); - if(!ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY)) - { + if (!ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY)) { FF_DEBUG("Not a wifi interface (no phy80211 directory)"); continue; } FF_DEBUG("Found wifi interface: %s", i->if_name); - FFWifiResult* item = (FFWifiResult*)ffListAdd(result); + FFWifiResult* item = (FFWifiResult*) ffListAdd(result); ffStrbufInitS(&item->inf.description, i->if_name); ffStrbufInit(&item->inf.status); ffStrbufInit(&item->conn.status); @@ -561,23 +491,20 @@ const char* ffDetectWifi(FF_MAYBE_UNUSED FFlist* result) char operstate; ffStrbufSetF(&buffer, "/sys/class/net/%s/operstate", i->if_name); - if (!ffReadFileData(buffer.chars, 1, &operstate)) - { + if (!ffReadFileData(buffer.chars, 1, &operstate)) { FF_DEBUG("Failed to read operstate file"); continue; } FF_DEBUG("Connection status: %c", operstate); - if (operstate != 'u') - { + if (operstate != 'u') { FF_DEBUG("Skipping interface as it's not up"); ffStrbufSetStatic(&item->conn.status, "disconnected"); ffStrbufSetF(&buffer, "/sys/class/net/%s/flags", i->if_name); char flags[16]; ssize_t len = ffReadFileData(buffer.chars, sizeof(flags), flags); - if (len <= 0) - { + if (len <= 0) { FF_DEBUG("Failed to read flags file"); ffStrbufSetStatic(&item->inf.status, "unknown"); continue; @@ -585,13 +512,10 @@ const char* ffDetectWifi(FF_MAYBE_UNUSED FFlist* result) flags[len] = '\0'; FF_DEBUG("Interface flags: %s", flags); unsigned flagsVal = (unsigned) strtoul(flags, NULL, 16); - if (flagsVal & IFF_UP) - { + if (flagsVal & IFF_UP) { ffStrbufSetStatic(&item->inf.status, "up"); FF_DEBUG("Interface is up but not connected"); - } - else - { + } else { ffStrbufSetStatic(&item->inf.status, "down"); FF_DEBUG("Interface is down"); } @@ -602,19 +526,18 @@ const char* ffDetectWifi(FF_MAYBE_UNUSED FFlist* result) ffStrbufSetStatic(&item->inf.status, "up"); FF_DEBUG("Trying to detect wifi with iw"); - if (detectWifiWithIw(item, &buffer) != NULL) - { + if (detectWifiWithIw(item, &buffer) != NULL) { FF_DEBUG("iw detection failed, trying fallback methods"); - #ifdef FF_HAVE_LINUX_WIRELESS - FF_DEBUG("Trying to detect wifi with ioctls"); - detectWifiWithIoctls(item); - #endif +#ifdef FF_HAVE_LINUX_WIRELESS + FF_DEBUG("Trying to detect wifi with ioctls"); + detectWifiWithIoctls(item); +#endif } - #ifdef FF_HAVE_DBUS - FF_DEBUG("Enhancing wifi info with NetworkManager"); - detectWifiWithNm(item, &buffer); - #endif +#ifdef FF_HAVE_DBUS + FF_DEBUG("Enhancing wifi info with NetworkManager"); + detectWifiWithNm(item, &buffer); +#endif } if_freenameindex(infs); diff --git a/src/detection/wifi/wifi_nbsd.c b/src/detection/wifi/wifi_nbsd.c index acab018c9..a70f2a857 100644 --- a/src/detection/wifi/wifi_nbsd.c +++ b/src/detection/wifi/wifi_nbsd.c @@ -18,21 +18,19 @@ #undef IEEE80211_IS_CHAN_VHT #define IEEE80211_IS_CHAN_VHT(x) (((x)->ic_flags & IEEE80211_CHAN_VHT) != 0) -const char* ffDetectWifi(FFlist* result) -{ +const char* ffDetectWifi(FFlist* result) { struct if_nameindex* infs = if_nameindex(); - if(!infs) { + if (!infs) { return "if_nameindex() failed"; } FF_AUTO_CLOSE_FD int sock = socket(AF_INET, SOCK_DGRAM, 0); - if(sock < 0) { + if (sock < 0) { if_freenameindex(infs); return "socket() failed"; } - for(struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) - { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { if (!ffStrStartsWith(i->if_name, "iwm")) { continue; } @@ -80,8 +78,7 @@ const char* ffDetectWifi(FFlist* result) ireq.i_len = sizeof(bssid); if (ioctl(sock, SIOCG80211, &ireq) >= 0) { - ffStrbufSetF(&item->conn.bssid, "%02X:%02X:%02X:%02X:%02X:%02X", - bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); + ffStrbufSetF(&item->conn.bssid, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); } struct ieee80211_channel curchan = {}; @@ -94,23 +91,24 @@ const char* ffDetectWifi(FFlist* result) item->conn.channel = ffWifiFreqToChannel(curchan.ic_freq); item->conn.frequency = curchan.ic_freq; - #ifdef IEEE80211_IS_CHAN_HE // for future use - if (IEEE80211_IS_CHAN_HE(&curchan)) +#ifdef IEEE80211_IS_CHAN_HE // for future use + if (IEEE80211_IS_CHAN_HE(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11ax (Wi-Fi 6)"); - else - #endif - if (IEEE80211_IS_CHAN_VHT(&curchan)) + } else +#endif + if (IEEE80211_IS_CHAN_VHT(&curchan)) ffStrbufSetStatic(&item->conn.protocol, "802.11ac (Wi-Fi 5)"); - else if (IEEE80211_IS_CHAN_HT(&curchan)) + else if (IEEE80211_IS_CHAN_HT(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11n (Wi-Fi 4)"); - else if (IEEE80211_IS_CHAN_ANYG(&curchan)) + } else if (IEEE80211_IS_CHAN_ANYG(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11g"); - else if (IEEE80211_IS_CHAN_B(&curchan)) + } else if (IEEE80211_IS_CHAN_B(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11b"); - else if (IEEE80211_IS_CHAN_A(&curchan)) + } else if (IEEE80211_IS_CHAN_A(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11a"); - else if (IEEE80211_IS_CHAN_FHSS(&curchan)) + } else if (IEEE80211_IS_CHAN_FHSS(&curchan)) { ffStrbufSetStatic(&item->conn.protocol, "802.11 (FHSS)"); + } } union { @@ -126,10 +124,11 @@ const char* ffDetectWifi(FFlist* result) struct ieee80211req_sta_info* sta = stareq.req.info; if (sta->isi_len != 0) { int8_t rssi = (int8_t) sta->isi_rssi; // Strangely, `sta->isi_rssi` is unsigned - item->conn.signalQuality = (rssi >= -50 ? 100 : rssi <= -100 ? 0 : (rssi + 100) * 2); + item->conn.signalQuality = (rssi >= -50 ? 100 : rssi <= -100 ? 0 + : (rssi + 100) * 2); if (sta->isi_txrate) { - item->conn.txRate = (double)sta->isi_txrate / 2.0; + item->conn.txRate = (double) sta->isi_txrate / 2.0; } } } @@ -139,27 +138,27 @@ const char* ffDetectWifi(FFlist* result) ireq.i_len = 0; if (ioctl(sock, SIOCG80211, &ireq) >= 0) { switch (ireq.i_val) { - case IEEE80211_AUTH_NONE: - ffStrbufSetStatic(&item->conn.security, "Insecure"); - break; - case IEEE80211_AUTH_OPEN: - ffStrbufSetStatic(&item->conn.security, "Open"); - break; - case IEEE80211_AUTH_SHARED: - ffStrbufSetStatic(&item->conn.security, "Shared"); - break; - case IEEE80211_AUTH_8021X: - ffStrbufSetStatic(&item->conn.security, "8021X"); - break; - case IEEE80211_AUTH_AUTO: - ffStrbufSetStatic(&item->conn.security, "Auto"); - break; - case IEEE80211_AUTH_WPA: - ffStrbufSetStatic(&item->conn.security, "WPA"); - break; - default: - ffStrbufSetF(&item->conn.security, "Unknown (%d)", ireq.i_val); - break; + case IEEE80211_AUTH_NONE: + ffStrbufSetStatic(&item->conn.security, "Insecure"); + break; + case IEEE80211_AUTH_OPEN: + ffStrbufSetStatic(&item->conn.security, "Open"); + break; + case IEEE80211_AUTH_SHARED: + ffStrbufSetStatic(&item->conn.security, "Shared"); + break; + case IEEE80211_AUTH_8021X: + ffStrbufSetStatic(&item->conn.security, "8021X"); + break; + case IEEE80211_AUTH_AUTO: + ffStrbufSetStatic(&item->conn.security, "Auto"); + break; + case IEEE80211_AUTH_WPA: + ffStrbufSetStatic(&item->conn.security, "WPA"); + break; + default: + ffStrbufSetF(&item->conn.security, "Unknown (%d)", ireq.i_val); + break; } } } diff --git a/src/detection/wifi/wifi_nosupport.c b/src/detection/wifi/wifi_nosupport.c index cbaa36700..d3ebd4d14 100644 --- a/src/detection/wifi/wifi_nosupport.c +++ b/src/detection/wifi/wifi_nosupport.c @@ -1,6 +1,5 @@ #include "wifi.h" -const char* ffDetectWifi(FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectWifi(FF_MAYBE_UNUSED FFlist* result) { return "Not support on this platform"; } diff --git a/src/detection/wifi/wifi_obsd.c b/src/detection/wifi/wifi_obsd.c index 67c250e28..06b6603ac 100644 --- a/src/detection/wifi/wifi_obsd.c +++ b/src/detection/wifi/wifi_obsd.c @@ -9,20 +9,18 @@ #include #include -const char* ffDetectWifi(FFlist* result) -{ +const char* ffDetectWifi(FFlist* result) { struct if_nameindex* infs = if_nameindex(); - if(!infs) { + if (!infs) { return "if_nameindex() failed"; } FF_AUTO_CLOSE_FD int sock = socket(AF_INET, SOCK_DGRAM, 0); - if(sock < 0) { + if (sock < 0) { return "socket() failed"; } - for(struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) - { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { if (!ffStrStartsWith(i->if_name, "iwm")) { continue; } @@ -59,20 +57,18 @@ const char* ffDetectWifi(FFlist* result) if (nr.nr_nwid_len > 0) { ffStrbufSetStatic(&item->conn.status, "Associated"); - ffStrbufAppendNS(&item->conn.ssid, nr.nr_nwid_len, (char*)nr.nr_nwid); + ffStrbufAppendNS(&item->conn.ssid, nr.nr_nwid_len, (char*) nr.nr_nwid); } else { ffStrbufSetStatic(&item->conn.status, "Not associated"); continue; } - ffStrbufSetF(&item->conn.bssid, "%02X:%02X:%02X:%02X:%02X:%02X", - nr.nr_bssid[0], nr.nr_bssid[1], nr.nr_bssid[2], - nr.nr_bssid[3], nr.nr_bssid[4], nr.nr_bssid[5]); + ffStrbufSetF(&item->conn.bssid, "%02X:%02X:%02X:%02X:%02X:%02X", nr.nr_bssid[0], nr.nr_bssid[1], nr.nr_bssid[2], nr.nr_bssid[3], nr.nr_bssid[4], nr.nr_bssid[5]); item->conn.channel = nr.nr_channel; if (nr.nr_max_rssi) { - item->conn.signalQuality = ((float)nr.nr_rssi / nr.nr_max_rssi) * 100.0; + item->conn.signalQuality = ((float) nr.nr_rssi / nr.nr_max_rssi) * 100.0; } if (nr.nr_flags & IEEE80211_NODEREQ_HT) { @@ -89,19 +85,21 @@ const char* ffDetectWifi(FFlist* result) strlcpy(wpa.i_name, i->if_name, sizeof(wpa.i_name)); if (ioctl(sock, SIOCG80211WPAPARMS, &wpa) >= 0 && wpa.i_enabled) { - if (wpa.i_protos & IEEE80211_WPA_PROTO_WPA2) + if (wpa.i_protos & IEEE80211_WPA_PROTO_WPA2) { ffStrbufSetStatic(&item->conn.security, "WPA2"); - else if (wpa.i_protos & IEEE80211_WPA_PROTO_WPA1) + } else if (wpa.i_protos & IEEE80211_WPA_PROTO_WPA1) { ffStrbufSetStatic(&item->conn.security, "WPA"); + } } else { struct ieee80211_nwkey nwkey = {}; strlcpy(nwkey.i_name, i->if_name, sizeof(nwkey.i_name)); if (ioctl(sock, SIOCG80211NWKEY, &nwkey) >= 0) { - if (nwkey.i_wepon) + if (nwkey.i_wepon) { ffStrbufSetStatic(&item->conn.security, "WEP"); - else + } else { ffStrbufSetStatic(&item->conn.security, "Open"); + } } } } diff --git a/src/detection/wifi/wifi_windows.c b/src/detection/wifi/wifi_windows.c index 99673b626..8969f09ef 100644 --- a/src/detection/wifi/wifi_windows.c +++ b/src/detection/wifi/wifi_windows.c @@ -8,41 +8,39 @@ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch" -static void convertIfStateToString(WLAN_INTERFACE_STATE state, FFstrbuf* result) -{ +static void convertIfStateToString(WLAN_INTERFACE_STATE state, FFstrbuf* result) { switch (state) { - case wlan_interface_state_not_ready: - ffStrbufAppendS(result, "Not ready"); - break; - case wlan_interface_state_connected: - ffStrbufAppendS(result, "Connected"); - break; - case wlan_interface_state_ad_hoc_network_formed: - ffStrbufAppendS(result, "Ad hoc network formed"); - break; - case wlan_interface_state_disconnecting: - ffStrbufAppendS(result, "Disconnecting"); - break; - case wlan_interface_state_disconnected: - ffStrbufAppendS(result, "Disconnected"); - break; - case wlan_interface_state_associating: - ffStrbufAppendS(result, "Associating"); - break; - case wlan_interface_state_discovering: - ffStrbufAppendS(result, "Discovering"); - break; - case wlan_interface_state_authenticating: - ffStrbufAppendS(result, "Authenticating"); - break; - default: - ffStrbufAppendS(result, "Unknown"); - break; + case wlan_interface_state_not_ready: + ffStrbufAppendS(result, "Not ready"); + break; + case wlan_interface_state_connected: + ffStrbufAppendS(result, "Connected"); + break; + case wlan_interface_state_ad_hoc_network_formed: + ffStrbufAppendS(result, "Ad hoc network formed"); + break; + case wlan_interface_state_disconnecting: + ffStrbufAppendS(result, "Disconnecting"); + break; + case wlan_interface_state_disconnected: + ffStrbufAppendS(result, "Disconnected"); + break; + case wlan_interface_state_associating: + ffStrbufAppendS(result, "Associating"); + break; + case wlan_interface_state_discovering: + ffStrbufAppendS(result, "Discovering"); + break; + case wlan_interface_state_authenticating: + ffStrbufAppendS(result, "Authenticating"); + break; + default: + ffStrbufAppendS(result, "Unknown"); + break; } } -const char* ffDetectWifi(FFlist* result) -{ +const char* ffDetectWifi(FFlist* result) { FF_LIBRARY_LOAD_MESSAGE(wlanapi, "wlanapi" FF_LIBRARY_EXTENSION, 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(wlanapi, WlanOpenHandle) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(wlanapi, WlanEnumInterfaces) @@ -56,23 +54,20 @@ const char* ffDetectWifi(FFlist* result) WLAN_INTERFACE_INFO_LIST* ifList = NULL; const char* error = NULL; - if(ffWlanOpenHandle(2, NULL, &curVersion, &hClient) != ERROR_SUCCESS) - { + if (ffWlanOpenHandle(2, NULL, &curVersion, &hClient) != ERROR_SUCCESS) { error = "WlanOpenHandle() failed"; goto exit; } - if(ffWlanEnumInterfaces(hClient, NULL, &ifList) != ERROR_SUCCESS) - { + if (ffWlanEnumInterfaces(hClient, NULL, &ifList) != ERROR_SUCCESS) { error = "WlanEnumInterfaces() failed"; goto exit; } - for(uint32_t index = 0; index < ifList->dwNumberOfItems; ++index) - { - WLAN_INTERFACE_INFO* ifInfo = (WLAN_INTERFACE_INFO*)&ifList->InterfaceInfo[index]; + for (uint32_t index = 0; index < ifList->dwNumberOfItems; ++index) { + WLAN_INTERFACE_INFO* ifInfo = (WLAN_INTERFACE_INFO*) &ifList->InterfaceInfo[index]; - FFWifiResult* item = (FFWifiResult*)ffListAdd(result); + FFWifiResult* item = (FFWifiResult*) ffListAdd(result); ffStrbufInitWS(&item->inf.description, ifInfo->strInterfaceDescription); ffStrbufInit(&item->inf.status); ffStrbufInit(&item->conn.status); @@ -88,33 +83,35 @@ const char* ffDetectWifi(FFlist* result) convertIfStateToString(ifInfo->isState, &item->inf.status); - if(ifInfo->isState != wlan_interface_state_connected) + if (ifInfo->isState != wlan_interface_state_connected) { continue; + } WLAN_CONNECTION_ATTRIBUTES* connInfo = NULL; DWORD bufSize = sizeof(*connInfo); WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_query_only; - if(ffWlanQueryInterface(hClient, - &ifInfo->InterfaceGuid, - wlan_intf_opcode_current_connection, - NULL, - &bufSize, - (PVOID*)&connInfo, - &opCode) != ERROR_SUCCESS - ) continue; + if (ffWlanQueryInterface(hClient, + &ifInfo->InterfaceGuid, + wlan_intf_opcode_current_connection, + NULL, + &bufSize, + (PVOID*) &connInfo, + &opCode) != ERROR_SUCCESS) { + continue; + } convertIfStateToString(connInfo->isState, &item->conn.status); ffStrbufAppendNS(&item->conn.ssid, connInfo->wlanAssociationAttributes.dot11Ssid.uSSIDLength, - (const char *)connInfo->wlanAssociationAttributes.dot11Ssid.ucSSID); + (const char*) connInfo->wlanAssociationAttributes.dot11Ssid.ucSSID); - for (size_t i = 0; i < sizeof(connInfo->wlanAssociationAttributes.dot11Bssid); i++) + for (size_t i = 0; i < sizeof(connInfo->wlanAssociationAttributes.dot11Bssid); i++) { ffStrbufAppendF(&item->conn.bssid, "%.2X:", connInfo->wlanAssociationAttributes.dot11Bssid[i]); + } ffStrbufTrimRight(&item->conn.bssid, ':'); - switch (connInfo->wlanAssociationAttributes.dot11PhyType) - { + switch (connInfo->wlanAssociationAttributes.dot11PhyType) { case dot11_phy_type_fhss: ffStrbufAppendS(&item->conn.protocol, "802.11 (FHSS)"); break; @@ -149,7 +146,7 @@ const char* ffDetectWifi(FFlist* result) ffStrbufAppendS(&item->conn.protocol, "802.11be (Wi-Fi 7)"); break; default: - ffStrbufAppendF(&item->conn.protocol, "Unknown (%u)", (unsigned)connInfo->wlanAssociationAttributes.dot11PhyType); + ffStrbufAppendF(&item->conn.protocol, "Unknown (%u)", (unsigned) connInfo->wlanAssociationAttributes.dot11PhyType); break; } @@ -157,10 +154,8 @@ const char* ffDetectWifi(FFlist* result) item->conn.rxRate = connInfo->wlanAssociationAttributes.ulRxRate / 1000.; item->conn.txRate = connInfo->wlanAssociationAttributes.ulTxRate / 1000.; - if(connInfo->wlanSecurityAttributes.bSecurityEnabled) - { - switch (connInfo->wlanSecurityAttributes.dot11AuthAlgorithm) - { + if (connInfo->wlanSecurityAttributes.bSecurityEnabled) { + switch (connInfo->wlanSecurityAttributes.dot11AuthAlgorithm) { case DOT11_AUTH_ALGO_80211_OPEN: ffStrbufAppendS(&item->conn.security, "802.11 Open"); break; @@ -195,24 +190,25 @@ const char* ffDetectWifi(FFlist* result) ffStrbufAppendS(&item->conn.security, "WPA3-ENT"); break; default: - ffStrbufAppendF(&item->conn.security, "Unknown (%u)", (unsigned)connInfo->wlanSecurityAttributes.dot11AuthAlgorithm); + ffStrbufAppendF(&item->conn.security, "Unknown (%u)", (unsigned) connInfo->wlanSecurityAttributes.dot11AuthAlgorithm); break; } - if(connInfo->wlanSecurityAttributes.bOneXEnabled) + if (connInfo->wlanSecurityAttributes.bOneXEnabled) { ffStrbufAppendS(&item->conn.security, " 802.11X"); - } - else + } + } else { ffStrbufAppendS(&item->conn.security, "Insecure"); + } WLAN_BSS_LIST* bssList = NULL; if (ffWlanGetNetworkBssList(hClient, - &ifInfo->InterfaceGuid, - &connInfo->wlanAssociationAttributes.dot11Ssid, - connInfo->wlanAssociationAttributes.dot11BssType, - connInfo->wlanSecurityAttributes.bSecurityEnabled, - NULL, - &bssList) == ERROR_SUCCESS && bssList->dwNumberOfItems > 0 - ) { + &ifInfo->InterfaceGuid, + &connInfo->wlanAssociationAttributes.dot11Ssid, + connInfo->wlanAssociationAttributes.dot11BssType, + connInfo->wlanSecurityAttributes.bSecurityEnabled, + NULL, + &bssList) == ERROR_SUCCESS && + bssList->dwNumberOfItems > 0) { item->conn.frequency = (uint16_t) (bssList->wlanBssEntries[0].ulChCenterFrequency / 1000); ffWlanFreeMemory(bssList); } @@ -221,22 +217,25 @@ const char* ffDetectWifi(FFlist* result) ULONG* channelNumber = 0; bufSize = sizeof(*channelNumber); - if(ffWlanQueryInterface(hClient, - &ifInfo->InterfaceGuid, - wlan_intf_opcode_channel_number, - NULL, - &bufSize, - (PVOID*)&channelNumber, - &opCode) == ERROR_SUCCESS - ) { + if (ffWlanQueryInterface(hClient, + &ifInfo->InterfaceGuid, + wlan_intf_opcode_channel_number, + NULL, + &bufSize, + (PVOID*) &channelNumber, + &opCode) == ERROR_SUCCESS) { item->conn.channel = (uint16_t) *channelNumber; ffWlanFreeMemory(channelNumber); } } exit: - if(ifList) ffWlanFreeMemory(ifList); - if(hClient) ffWlanCloseHandle(hClient, NULL); + if (ifList) { + ffWlanFreeMemory(ifList); + } + if (hClient) { + ffWlanCloseHandle(hClient, NULL); + } return error; } diff --git a/src/detection/wm/wm_linux.c b/src/detection/wm/wm_linux.c index b3054fe6a..38116a786 100644 --- a/src/detection/wm/wm_linux.c +++ b/src/detection/wm/wm_linux.c @@ -8,45 +8,47 @@ #include "common/debug.h" #include "detection/displayserver/displayserver.h" -const char* ffDetectWMPlugin(FF_MAYBE_UNUSED FFstrbuf* pluginName) -{ +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) -{ +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; + 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; - ++line; --len; +static bool extractHyprlandVersion(const char* line, uint32_t len, void* userdata) { + if (line[0] != 'v') { + return true; + } + ++line; + --len; int count = 0; sscanf(line, "%*d.%*d.%*d%n", &count); - if (count == 0) return true; + if (count == 0) { + return true; + } ffStrbufSetNS((FFstrbuf*) userdata, len, line); return false; } -static const char* getHyprland(FFstrbuf* result) -{ +static const char* getHyprland(FFstrbuf* result) { FF_DEBUG("Detecting Hyprland version"); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - FF_DEBUG("Checking for " FASTFETCH_TARGET_DIR_USR "/include/hyprland/src/version.h" " file"); - if (ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/include/hyprland/src/version.h", result)) - { + FF_DEBUG("Checking for " FASTFETCH_TARGET_DIR_USR "/include/hyprland/src/version.h" + " file"); + if (ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/include/hyprland/src/version.h", result)) { FF_DEBUG("Found version.h file, extracting version"); - if (ffStrbufSubstrAfterFirstS(result, "\n#define GIT_TAG ")) - { + if (ffStrbufSubstrAfterFirstS(result, "\n#define GIT_TAG ")) { ffStrbufSubstrAfterFirstC(result, '"'); ffStrbufSubstrBeforeFirstC(result, '"'); ffStrbufTrimLeft(result, 'v'); @@ -55,9 +57,7 @@ static const char* getHyprland(FFstrbuf* result) } FF_DEBUG("Failed to extract version from version.h"); ffStrbufClear(result); - } - else - { + } else { FF_DEBUG("version.h file not found, trying Hyprland executable"); } @@ -75,12 +75,7 @@ static const char* getHyprland(FFstrbuf* result) } FF_DEBUG("Failed to extract version from binary strings, trying --version option"); - if (ffProcessAppendStdOut(result, (char* const[]){ - buffer.chars, - "--version", - NULL - }) == NULL) - { + if (ffProcessAppendStdOut(result, (char* const[]) {buffer.chars, "--version", NULL}) == NULL) { // Hyprland 0.48.1 built from branch at commit 29e2e59... // Date: ... // Tag: v0.48.1, commits: 5937 @@ -88,13 +83,10 @@ static const char* getHyprland(FFstrbuf* result) FF_DEBUG("Raw version output: %s", result->chars); // Use tag if available - if (ffStrbufSubstrAfterFirstS(result, "\nTag: v")) - { + if (ffStrbufSubstrAfterFirstS(result, "\nTag: v")) { ffStrbufSubstrBeforeFirstC(result, ','); FF_DEBUG("Extracted version from Tag: %s", result->chars); - } - else - { + } else { ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufSubstrBeforeFirstC(result, ' '); FF_DEBUG("Extracted version from output: %s", result->chars); @@ -106,9 +98,10 @@ static const char* getHyprland(FFstrbuf* result) return "Failed to run command `Hyprland --version`"; } -static bool extractSwayVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void *userdata) -{ - if (!ffStrStartsWith(line, "sway version ")) return true; +static bool extractSwayVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void* userdata) { + if (!ffStrStartsWith(line, "sway version ")) { + return true; + } FFstrbuf* result = (FFstrbuf*) userdata; ffStrbufSetNS(result, len - (uint32_t) strlen("sway version "), line + strlen("sway version ")); @@ -116,21 +109,19 @@ static bool extractSwayVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, v return false; } -static const char* getSway(FFstrbuf* result) -{ +static const char* getSway(FFstrbuf* result) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); const char* error = ffFindExecutableInPath("sway", &path); - if (error) return "Failed to find sway executable path"; + if (error) { + return "Failed to find sway executable path"; + } ffBinaryExtractStrings(path.chars, extractSwayVersion, result, (uint32_t) strlen("v0.0.0")); - if (result->length > 0) return NULL; + if (result->length > 0) { + return NULL; + } - if (ffProcessAppendStdOut(result, (char* const[]){ - path.chars, - "--version", - NULL - }) == NULL) - { // sway version 1.10 + if (ffProcessAppendStdOut(result, (char* const[]) {path.chars, "--version", NULL}) == NULL) { // sway version 1.10 ffStrbufSubstrAfterLastC(result, ' '); ffStrbufTrimRightSpace(result); return NULL; @@ -139,21 +130,19 @@ static const char* getSway(FFstrbuf* result) return "Failed to run command `sway --version`"; } -static const char* getLabwc(FFstrbuf* result) -{ +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"; + 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 (result->length > 0) { + return NULL; + } - if (ffProcessAppendStdOut(result, (char* const[]){ - path.chars, - "--version", - NULL - }) == NULL) - { // labwc 0.9.0 (+xwayland +nls +rsvg +libsfdo) + if (ffProcessAppendStdOut(result, (char* const[]) {path.chars, "--version", NULL}) == NULL) { // labwc 0.9.0 (+xwayland +nls +rsvg +libsfdo) ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufSubstrBeforeFirstC(result, ' '); return NULL; @@ -162,14 +151,8 @@ static const char* getLabwc(FFstrbuf* result) return "Failed to run command `labwc --version`"; } -static const char* getNiri(FFstrbuf* result) -{ - if (ffProcessAppendStdOut(result, (char* const[]){ - "niri", - "--version", - NULL - }) == NULL) - { // niri 25.11 (commit b35bcae) +static const char* getNiri(FFstrbuf* result) { + if (ffProcessAppendStdOut(result, (char* const[]) {"niri", "--version", NULL}) == NULL) { // niri 25.11 (commit b35bcae) ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufSubstrBeforeLastC(result, '('); ffStrbufTrimRightSpace(result); @@ -179,14 +162,15 @@ static const char* getNiri(FFstrbuf* result) return "Failed to run command `niri --version`"; } -#ifdef __linux__ -static const char* getWslg(FFstrbuf* result) -{ - if (!ffAppendFileBuffer("/mnt/wslg/versions.txt", result)) +# 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 ")) + if (!ffStrbufStartsWithS(result, "WSLg ")) { return "Failed to find WSLg version"; + } ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrBeforeFirstC(result, '+'); @@ -194,35 +178,34 @@ static const char* getWslg(FFstrbuf* result) ffStrbufTrimLeft(result, ' '); return NULL; } -#endif +# endif #endif // !__ANDROID__ -static bool extractI3Version(const char* line, FF_MAYBE_UNUSED uint32_t len, void *userdata) -{ +static bool extractI3Version(const char* line, FF_MAYBE_UNUSED uint32_t len, void* userdata) { int count = 0; sscanf(line, "%*d.%*d%n", &count); - if (count == 0) return true; + if (count == 0) { + return true; + } ffStrbufSetNS((FFstrbuf*) userdata, len, line); return false; } -static const char* getI3(FFstrbuf* result) -{ +static const char* getI3(FFstrbuf* result) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); const char* error = ffFindExecutableInPath("i3", &path); - if (error) return "Failed to find i3 executable path"; + if (error) { + return "Failed to find i3 executable path"; + } ffBinaryExtractStrings(path.chars, extractI3Version, result, (uint32_t) strlen("0.0")); - if (result->length > 0) return NULL; + if (result->length > 0) { + return NULL; + } - if (ffProcessAppendStdOut(result, (char* const[]){ - path.chars, - "--version", - NULL - }) == NULL) - { // i3 version 1.10 C 2009... + if (ffProcessAppendStdOut(result, (char* const[]) {path.chars, "--version", NULL}) == NULL) { // i3 version 1.10 C 2009... ffStrbufSubstrAfterFirstS(result, "version "); ffStrbufSubstrBeforeFirstC(result, ' '); return NULL; @@ -231,21 +214,19 @@ static const char* getI3(FFstrbuf* result) return "Failed to run command `i3 --version`"; } -static const char* getCtwm(FFstrbuf* result) -{ +static const char* getCtwm(FFstrbuf* result) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); const char* error = ffFindExecutableInPath("ctwm", &path); - if (error) return "Failed to find ctwm executable path"; + if (error) { + return "Failed to find ctwm executable path"; + } ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0")); - if (result->length > 0) return NULL; + if (result->length > 0) { + return NULL; + } - if (ffProcessAppendStdOut(result, (char* const[]){ - path.chars, - "--version", - NULL - }) == NULL) - { // ctwm version 4.0.1\n... + if (ffProcessAppendStdOut(result, (char* const[]) {path.chars, "--version", NULL}) == NULL) { // ctwm version 4.0.1\n... ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrAfterLastC(result, ' '); return NULL; @@ -254,21 +235,19 @@ static const char* getCtwm(FFstrbuf* result) return "Failed to run command `ctwm --version`"; } -static const char* getFvwm(FFstrbuf* result) -{ +static const char* getFvwm(FFstrbuf* result) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); const char* error = ffFindExecutableInPath("fvwm", &path); - if (error) return "Failed to find fvwm executable path"; + if (error) { + return "Failed to find fvwm executable path"; + } ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0")); - if (result->length > 0) return NULL; + if (result->length > 0) { + return NULL; + } - if (ffProcessAppendStdOut(result, (char* const[]){ - path.chars, - "-version", - NULL - }) == NULL) - { // [FVWM][main]: fvwm Version 2.2.5\n... + if (ffProcessAppendStdOut(result, (char* const[]) {path.chars, "-version", NULL}) == NULL) { // [FVWM][main]: fvwm Version 2.2.5\n... ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrAfterLastC(result, ' '); return NULL; @@ -277,21 +256,19 @@ static const char* getFvwm(FFstrbuf* result) return "Failed to run command `fvwm -version`"; } -static const char* getOpenbox(FFstrbuf* result) -{ +static const char* getOpenbox(FFstrbuf* result) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); const char* error = ffFindExecutableInPath("openbox", &path); - if (error) return "Failed to find openbox executable path"; + if (error) { + return "Failed to find openbox executable path"; + } ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0")); - if (result->length > 0) return NULL; + if (result->length > 0) { + return NULL; + } - if (ffProcessAppendStdOut(result, (char* const[]){ - path.chars, - "--version", - NULL - }) == NULL) - { // Openbox 3.6.1\n... + if (ffProcessAppendStdOut(result, (char* const[]) {path.chars, "--version", NULL}) == NULL) { // Openbox 3.6.1\n... ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrAfterLastC(result, ' '); return NULL; @@ -300,43 +277,52 @@ static const char* getOpenbox(FFstrbuf* result) return "Failed to run command `openbox --version`"; } -const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_MAYBE_UNUSED FFWMOptions* options) -{ - if (!wmName) +const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_MAYBE_UNUSED FFWMOptions* options) { + if (!wmName) { return "No WM detected"; + } - #if !__ANDROID__ +#if !__ANDROID__ // Wayland compositors - if (ffStrbufIgnCaseEqualS(wmName, "Hyprland")) + if (ffStrbufIgnCaseEqualS(wmName, "Hyprland")) { return getHyprland(result); + } - if (ffStrbufEqualS(wmName, "sway")) + if (ffStrbufEqualS(wmName, "sway")) { return getSway(result); + } - if (ffStrbufEqualS(wmName, "labwc")) + if (ffStrbufEqualS(wmName, "labwc")) { return getLabwc(result); + } - if (ffStrbufEqualS(wmName, "niri")) + if (ffStrbufEqualS(wmName, "niri")) { return getNiri(result); + } - #if __linux__ - if (ffStrbufEqualS(wmName, "WSLg")) +# if __linux__ + if (ffStrbufEqualS(wmName, "WSLg")) { return getWslg(result); - #endif - #endif + } +# endif +#endif // X11 WMs - if (ffStrbufEqualS(wmName, "i3")) + if (ffStrbufEqualS(wmName, "i3")) { return getI3(result); + } - if (ffStrbufEqualS(wmName, "ctwm")) + if (ffStrbufEqualS(wmName, "ctwm")) { return getCtwm(result); + } - if (ffStrbufEqualS(wmName, "fvwm")) + if (ffStrbufEqualS(wmName, "fvwm")) { return getFvwm(result); + } - if (ffStrbufEqualS(wmName, "Openbox")) + if (ffStrbufEqualS(wmName, "Openbox")) { return getOpenbox(result); + } return "Unsupported WM"; } diff --git a/src/detection/wm/wm_nosupport.c b/src/detection/wm/wm_nosupport.c index 595cdd946..8d9f1bb84 100644 --- a/src/detection/wm/wm_nosupport.c +++ b/src/detection/wm/wm_nosupport.c @@ -1,11 +1,9 @@ #include "wm.h" -const char* ffDetectWMPlugin(FF_MAYBE_UNUSED FFstrbuf* pluginName) -{ +const char* ffDetectWMPlugin(FF_MAYBE_UNUSED FFstrbuf* pluginName) { return "Not supported on this platform"; } -const char* ffDetectWMVersion(FF_MAYBE_UNUSED const FFstrbuf* wmName, FF_MAYBE_UNUSED FFstrbuf* result, FF_MAYBE_UNUSED FFWMOptions* options) -{ +const char* ffDetectWMVersion(FF_MAYBE_UNUSED const FFstrbuf* wmName, FF_MAYBE_UNUSED FFstrbuf* result, FF_MAYBE_UNUSED FFWMOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/wm/wm_windows.c b/src/detection/wm/wm_windows.c index a2bc1852f..8435745bf 100644 --- a/src/detection/wm/wm_windows.c +++ b/src/detection/wm/wm_windows.c @@ -21,8 +21,7 @@ typedef enum { FF_PROCESS_TYPE_CUI = 1 << 3, } FFProcessType; -static bool verifySignature(const wchar_t* filePath) -{ +static bool verifySignature(const wchar_t* filePath) { FF_LIBRARY_LOAD(wintrust, true, "wintrust" FF_LIBRARY_EXTENSION, -1) FF_LIBRARY_LOAD_SYMBOL(wintrust, WinVerifyTrustEx, true) @@ -50,69 +49,72 @@ static bool verifySignature(const wchar_t* filePath) return status == ERROR_SUCCESS; } -static bool isProcessTrusted(DWORD processId, FFProcessType processType, UNICODE_STRING* buffer, size_t bufSize) -{ +static bool isProcessTrusted(DWORD processId, FFProcessType processType, UNICODE_STRING* buffer, size_t bufSize) { FF_AUTO_CLOSE_FD HANDLE hProcess = NULL; if (!NT_SUCCESS(NtOpenProcess(&hProcess, PROCESS_QUERY_LIMITED_INFORMATION, &(OBJECT_ATTRIBUTES) { - .Length = sizeof(OBJECT_ATTRIBUTES), - }, &(CLIENT_ID) { .UniqueProcess = (HANDLE)(uintptr_t) processId }))) + .Length = sizeof(OBJECT_ATTRIBUTES), + }, + &(CLIENT_ID) {.UniqueProcess = (HANDLE) (uintptr_t) processId}))) { return false; + } ULONG size; - if(!NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageFileNameWin32, buffer, (ULONG) bufSize, &size)) || - buffer->Length == 0) return false; + if (!NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageFileNameWin32, buffer, (ULONG) bufSize, &size)) || + buffer->Length == 0) { + return false; + } assert(buffer->MaximumLength >= buffer->Length + 2); // NULL terminated - if (processType & FF_PROCESS_TYPE_WINDOWS_STORE) - { + if (processType & FF_PROCESS_TYPE_WINDOWS_STORE) { static wchar_t windowsAppsPath[MAX_PATH]; static uint32_t windowsAppsPathLen; - if (windowsAppsPathLen == 0) - { + if (windowsAppsPathLen == 0) { PWSTR pPath = NULL; - if(SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, NULL, &pPath))) - { + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, NULL, &pPath))) { windowsAppsPathLen = (uint32_t) wcslen(pPath); memcpy(windowsAppsPath, pPath, windowsAppsPathLen * sizeof(wchar_t)); memcpy(windowsAppsPath + windowsAppsPathLen, L"\\WindowsApps\\", sizeof(L"\\WindowsApps\\")); windowsAppsPathLen += strlen("\\WindowsApps\\"); - } - else - { + } else { windowsAppsPathLen = -1u; } CoTaskMemFree(pPath); } if (windowsAppsPathLen != -1u && - (buffer->Length <= windowsAppsPathLen * sizeof(wchar_t) || // Path is too short to be in WindowsApps - _wcsnicmp(buffer->Buffer, windowsAppsPath, windowsAppsPathLen) != 0) // Path does not start with WindowsApps - ) return false; + (buffer->Length <= windowsAppsPathLen * sizeof(wchar_t) || // Path is too short to be in WindowsApps + _wcsnicmp(buffer->Buffer, windowsAppsPath, windowsAppsPathLen) != 0) // Path does not start with WindowsApps + ) { + return false; + } } - if (processType & FF_PROCESS_TYPE_SIGNED) - { - if (!verifySignature(buffer->Buffer)) return false; + if (processType & FF_PROCESS_TYPE_SIGNED) { + if (!verifySignature(buffer->Buffer)) { + return false; + } } - if (processType & (FF_PROCESS_TYPE_GUI | FF_PROCESS_TYPE_CUI)) - { + if (processType & (FF_PROCESS_TYPE_GUI | FF_PROCESS_TYPE_CUI)) { SECTION_IMAGE_INFORMATION info = {}; - if(!NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageInformation, &info, sizeof(info), &size)) || - size != sizeof(info)) return false; + if (!NT_SUCCESS(NtQueryInformationProcess(hProcess, ProcessImageInformation, &info, sizeof(info), &size)) || + size != sizeof(info)) { + return false; + } - if ((processType & FF_PROCESS_TYPE_GUI) && info.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_GUI) + if ((processType & FF_PROCESS_TYPE_GUI) && info.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_GUI) { return false; - if ((processType & FF_PROCESS_TYPE_CUI) && info.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_CUI) + } + if ((processType & FF_PROCESS_TYPE_CUI) && info.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_CUI) { return false; + } } return true; } -#define ffStrEqualNWS(str, compareTo) (_wcsnicmp(str, L ## compareTo, sizeof(compareTo) - 1) == 0) +#define ffStrEqualNWS(str, compareTo) (_wcsnicmp(str, L##compareTo, sizeof(compareTo) - 1) == 0) -const char* ffDetectWMPlugin(FFstrbuf* pluginName) -{ +const char* ffDetectWMPlugin(FFstrbuf* pluginName) { alignas(UNICODE_STRING) uint8_t buffer[4096]; UNICODE_STRING* filePath = (UNICODE_STRING*) buffer; SYSTEM_PROCESS_INFORMATION* FF_AUTO_FREE pstart = NULL; @@ -120,80 +122,76 @@ const char* ffDetectWMPlugin(FFstrbuf* pluginName) // Multiple attempts in case processes change while // we are in the middle of querying them. ULONG size = 0; - for (int attempts = 0;; ++attempts) - { - if (size) - { - pstart = (SYSTEM_PROCESS_INFORMATION*)realloc(pstart, size); + for (int attempts = 0;; ++attempts) { + if (size) { + pstart = (SYSTEM_PROCESS_INFORMATION*) realloc(pstart, size); assert(pstart); } NTSTATUS status = NtQuerySystemInformation(SystemProcessInformation, pstart, size, &size); - if(NT_SUCCESS(status)) + if (NT_SUCCESS(status)) { break; - else if(status == STATUS_INFO_LENGTH_MISMATCH && attempts < 4) + } else if (status == STATUS_INFO_LENGTH_MISMATCH && attempts < 4) { size += sizeof(SYSTEM_PROCESS_INFORMATION) * 5; - else + } else { return "NtQuerySystemInformation(SystemProcessInformation) failed"; + } } - for (SYSTEM_PROCESS_INFORMATION* ptr = pstart; ; ptr = (SYSTEM_PROCESS_INFORMATION*)((uint8_t*)ptr + ptr->NextEntryOffset)) - { + for (SYSTEM_PROCESS_INFORMATION* ptr = pstart;; ptr = (SYSTEM_PROCESS_INFORMATION*) ((uint8_t*) ptr + ptr->NextEntryOffset)) { assert(ptr->ImageName.Length == 0 || ptr->ImageName.MaximumLength >= ptr->ImageName.Length + 2); // NULL terminated if (ptr->ImageName.Length == strlen("FancyWM-GUI.exe") * sizeof(wchar_t) && ffStrEqualNWS(ptr->ImageName.Buffer, "FancyWM-GUI.exe") && - isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_WINDOWS_STORE | FF_PROCESS_TYPE_GUI, filePath, sizeof(buffer)) - ) { - if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, NULL, pluginName)) + isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_WINDOWS_STORE | FF_PROCESS_TYPE_GUI, filePath, sizeof(buffer))) { + if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, NULL, pluginName)) { ffStrbufPrependS(pluginName, "FancyWM "); - else + } else { ffStrbufSetStatic(pluginName, "FancyWM"); - break; - } - else if (ptr->ImageName.Length == strlen("glazewm-watcher.exe") * sizeof(wchar_t) && - ffStrEqualNWS(ptr->ImageName.Buffer, "glazewm-watcher.exe") && - isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_SIGNED | FF_PROCESS_TYPE_GUI, filePath, sizeof(buffer)) - ) { - if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, NULL, pluginName)) - ffStrbufPrependS(pluginName, "GlazeWM "); - else - ffStrbufSetStatic(pluginName, "GlazeWM"); - break; - } - else if (ptr->ImageName.Length == strlen("komorebi.exe") * sizeof(wchar_t) && - ffStrEqualNWS(ptr->ImageName.Buffer, "komorebi.exe") && - isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_CUI, filePath, sizeof(buffer)) - ) { - if (instance.config.general.detectVersion) - { - FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateNWS(filePath->Length / sizeof(wchar_t), filePath->Buffer); - if (ffProcessAppendStdOut(pluginName, (char *const[]) { - path.chars, - "--version", - NULL, - }) == NULL) - ffStrbufSubstrBeforeFirstC(pluginName, '\n'); } - if (pluginName->length == 0) + break; + } else if (ptr->ImageName.Length == strlen("glazewm-watcher.exe") * sizeof(wchar_t) && + ffStrEqualNWS(ptr->ImageName.Buffer, "glazewm-watcher.exe") && + isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_SIGNED | FF_PROCESS_TYPE_GUI, filePath, sizeof(buffer))) { + if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, NULL, pluginName)) { + ffStrbufPrependS(pluginName, "GlazeWM "); + } else { + ffStrbufSetStatic(pluginName, "GlazeWM"); + } + break; + } else if (ptr->ImageName.Length == strlen("komorebi.exe") * sizeof(wchar_t) && + ffStrEqualNWS(ptr->ImageName.Buffer, "komorebi.exe") && + isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_CUI, filePath, sizeof(buffer))) { + if (instance.config.general.detectVersion) { + FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateNWS(filePath->Length / sizeof(wchar_t), filePath->Buffer); + if (ffProcessAppendStdOut(pluginName, (char* const[]) { + path.chars, + "--version", + NULL, + }) == NULL) { + ffStrbufSubstrBeforeFirstC(pluginName, '\n'); + } + } + if (pluginName->length == 0) { ffStrbufSetStatic(pluginName, "Komorebi"); + } break; } - if (ptr->NextEntryOffset == 0) break; + if (ptr->NextEntryOffset == 0) { + break; + } } return NULL; } -const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_MAYBE_UNUSED FFWMOptions* options) -{ - if (!wmName) +const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_MAYBE_UNUSED FFWMOptions* options) { + if (!wmName) { return "No WM detected"; + } - if (ffStrbufEqualS(wmName, "dwm.exe")) - { + if (ffStrbufEqualS(wmName, "dwm.exe")) { PWSTR pPath = NULL; - if(SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_System, KF_FLAG_DEFAULT, NULL, &pPath))) - { + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_System, KF_FLAG_DEFAULT, NULL, &pPath))) { wchar_t fullPath[MAX_PATH]; wcscpy(fullPath, pPath); wcscat(fullPath, L"\\dwm.exe"); diff --git a/src/detection/wmtheme/wmtheme_linux.c b/src/detection/wmtheme/wmtheme_linux.c index d36bfbaca..adc3cd5aa 100644 --- a/src/detection/wmtheme/wmtheme_linux.c +++ b/src/detection/wmtheme/wmtheme_linux.c @@ -8,18 +8,14 @@ #include "detection/gtk_qt/gtk_qt.h" #include "detection/displayserver/displayserver.h" -static bool detectWMThemeFromConfigFile(const char* configFile, const char* themeRegex, const char* defaultValue, FFstrbuf* themeOrError) -{ - if(!ffParsePropFileConfig(configFile, themeRegex, themeOrError)) - { +static bool detectWMThemeFromConfigFile(const char* configFile, const char* themeRegex, const char* defaultValue, FFstrbuf* themeOrError) { + if (!ffParsePropFileConfig(configFile, themeRegex, themeOrError)) { ffStrbufAppendF(themeOrError, "Config file %s doesn't exist", configFile); return false; } - if(themeOrError->length == 0) - { - if(defaultValue == NULL) - { + if (themeOrError->length == 0) { + if (defaultValue == NULL) { ffStrbufAppendF(themeOrError, "Couldn't find WM theme in %s", configFile); return false; } @@ -32,22 +28,22 @@ static bool detectWMThemeFromConfigFile(const char* configFile, const char* them uint32_t idx = 0; idx = ffStrbufFirstIndexS(themeOrError, "qml_"); - if(idx != themeOrError->length) + if (idx != themeOrError->length) { ffStrbufSubstrAfter(themeOrError, idx + 3); + } idx = ffStrbufFirstIndexS(themeOrError, "svg__"); - if(idx != themeOrError->length) + if (idx != themeOrError->length) { ffStrbufSubstrAfter(themeOrError, idx + 4); + } return true; } -static bool detectWMThemeFromSettings(const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey, FFstrbuf* themeOrError) -{ +static bool detectWMThemeFromSettings(const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey, FFstrbuf* themeOrError) { const char* theme = ffSettingsGetGnome(dconfKey, gsettingsSchemaName, gsettingsPath, gsettingsKey, FF_VARIANT_TYPE_STRING).strValue; - if(!ffStrSet(theme)) - { + if (!ffStrSet(theme)) { ffStrbufAppendS(themeOrError, "Couldn't find WM theme in DConf or GSettings"); return false; } @@ -56,19 +52,21 @@ static bool detectWMThemeFromSettings(const char* dconfKey, const char* gsetting return true; } -static bool detectGTKThemeAsWMTheme(FFstrbuf* themeOrError) -{ +static bool detectGTKThemeAsWMTheme(FFstrbuf* themeOrError) { const FFGTKResult* gtk = ffDetectGTK4(); - if(gtk->theme.length > 0) + if (gtk->theme.length > 0) { goto ok; + } gtk = ffDetectGTK3(); - if(gtk->theme.length > 0) + if (gtk->theme.length > 0) { goto ok; + } gtk = ffDetectGTK2(); - if(gtk->theme.length > 0) + if (gtk->theme.length > 0) { goto ok; + } ffStrbufAppendS(themeOrError, "Couldn't detect GTK4/3/2 theme"); return false; @@ -78,11 +76,9 @@ ok: return true; } -static bool detectMutter(FFstrbuf* themeOrError) -{ +static bool detectMutter(FFstrbuf* themeOrError) { 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)) - { + if (ffStrSet(theme)) { ffStrbufAppendS(themeOrError, theme); return true; } @@ -90,25 +86,21 @@ static bool detectMutter(FFstrbuf* themeOrError) return detectGTKThemeAsWMTheme(themeOrError); } -static bool detectMuffin(FFstrbuf* themeOrError) -{ +static bool detectMuffin(FFstrbuf* themeOrError) { 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) - { + if (name == NULL && theme == NULL) { ffStrbufAppendS(themeOrError, "Couldn't find muffin theme in GSettings / DConf"); return false; } - if(name == NULL) - { + if (name == NULL) { ffStrbufAppendS(themeOrError, theme); return true; } - if(theme == NULL) - { + if (theme == NULL) { ffStrbufAppendS(themeOrError, name); return true; } @@ -117,12 +109,10 @@ static bool detectMuffin(FFstrbuf* themeOrError) return true; } -static bool detectXFWM4(FFstrbuf* themeOrError) -{ +static bool detectXFWM4(FFstrbuf* themeOrError) { const char* theme = ffSettingsGetXFConf("xfwm4", "/general/theme", FF_VARIANT_TYPE_STRING).strValue; - if(theme == NULL) - { + if (theme == NULL) { ffStrbufAppendS(themeOrError, "Couldn't find xfwm4::/general/theme in XFConf"); return false; } @@ -131,50 +121,53 @@ static bool detectXFWM4(FFstrbuf* themeOrError) return true; } -static bool detectOpenbox(const FFstrbuf* dePrettyName, FFstrbuf* themeOrError) -{ +static bool detectOpenbox(const FFstrbuf* dePrettyName, FFstrbuf* themeOrError) { FF_STRBUF_AUTO_DESTROY absolutePath = ffStrbufCreateA(64); - const char *configFileSubpath = "openbox/rc.xml"; - if (ffStrbufIgnCaseEqualS(dePrettyName, "LXQt")) + const char* configFileSubpath = "openbox/rc.xml"; + if (ffStrbufIgnCaseEqualS(dePrettyName, "LXQt")) { configFileSubpath = "openbox/lxqt-rc.xml"; - else if (ffStrbufIgnCaseEqualS(dePrettyName, "LXDE")) + } else if (ffStrbufIgnCaseEqualS(dePrettyName, "LXDE")) { configFileSubpath = "openbox/lxde-rc.xml"; + } - if (!ffSearchUserConfigFile(&instance.state.platform.configDirs, configFileSubpath, &absolutePath)) - { + if (!ffSearchUserConfigFile(&instance.state.platform.configDirs, configFileSubpath, &absolutePath)) { ffStrbufAppendF(themeOrError, "Couldn't find config file \"%s\"", configFileSubpath); return false; } FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); - if (!ffReadFileBuffer(absolutePath.chars, &content)) - { + if (!ffReadFileBuffer(absolutePath.chars, &content)) { ffStrbufAppendF(themeOrError, "Couldn't read \"%s\"", absolutePath.chars); return false; } - const char *themeStart = strstr(content.chars, ""); - if (themeStart == NULL) + const char* themeStart = strstr(content.chars, ""); + if (themeStart == NULL) { goto theme_not_found; + } - const char *themeEnd = strstr(themeStart, ""); - if (__builtin_expect(themeEnd == NULL, false)) // very rare case + const char* themeEnd = strstr(themeStart, ""); + if (__builtin_expect(themeEnd == NULL, false)) { // very rare case goto theme_not_found; + } - const char *nameStart = strstr(themeStart, ""); - if (nameStart == NULL) + const char* nameStart = strstr(themeStart, ""); + if (nameStart == NULL) { goto name_not_found; + } - const char *nameEnd = strstr(nameStart, ""); - if (nameEnd == NULL || nameEnd > themeEnd) // (nameEnd > themeEnd) means name is not a theme's child + const char* nameEnd = strstr(nameStart, ""); + if (nameEnd == NULL || nameEnd > themeEnd) { // (nameEnd > themeEnd) means name is not a theme's child goto name_not_found; + } nameStart += strlen(""); - ffStrbufAppendNS(themeOrError, (uint32_t)(nameEnd - nameStart), nameStart); + ffStrbufAppendNS(themeOrError, (uint32_t) (nameEnd - nameStart), nameStart); ffStrbufTrim(themeOrError, ' '); - if(themeOrError->length == 0) + if (themeOrError->length == 0) { goto name_not_found; + } return true; @@ -187,44 +180,45 @@ name_not_found: return false; } -bool ffDetectWmTheme(FFstrbuf* themeOrError) -{ +bool ffDetectWmTheme(FFstrbuf* themeOrError) { const FFDisplayServerResult* wm = ffConnectDisplayServer(); - if(wm->wmPrettyName.length == 0) - { + if (wm->wmPrettyName.length == 0) { ffStrbufAppendS(themeOrError, "WM Theme needs successful WM detection"); return false; } - if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_KWIN)) + if (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_KWIN)) { return detectWMThemeFromConfigFile("kwinrc", "theme =", "Breeze", themeOrError); - - if( - ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_XFWM4) || - (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, "labwc") && ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_XFCE4)) - ) - return detectXFWM4(themeOrError); - - if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MUTTER)) - { - if( - ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_GNOME) || - ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_GNOME_CLASSIC) - ) - return detectMutter(themeOrError); - else - return detectGTKThemeAsWMTheme(themeOrError); } - if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MUFFIN)) + if ( + ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_XFWM4) || + (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, "labwc") && ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_XFCE4))) { + return detectXFWM4(themeOrError); + } + + if (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MUTTER)) { + if ( + ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_GNOME) || + ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_GNOME_CLASSIC)) { + return detectMutter(themeOrError); + } else { + return detectGTKThemeAsWMTheme(themeOrError); + } + } + + if (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MUFFIN)) { return detectMuffin(themeOrError); + } - if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MARCO)) + if (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MARCO)) { return detectWMThemeFromSettings("/org/mate/Marco/general/theme", "org.mate.Marco.general", NULL, "theme", themeOrError); + } - if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_OPENBOX)) + if (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_OPENBOX)) { return detectOpenbox(&wm->dePrettyName, themeOrError); + } ffStrbufAppendS(themeOrError, "Unknown WM: "); ffStrbufAppend(themeOrError, &wm->wmPrettyName); diff --git a/src/detection/wmtheme/wmtheme_nosupport.c b/src/detection/wmtheme/wmtheme_nosupport.c index 2b899e98c..8cba51acf 100644 --- a/src/detection/wmtheme/wmtheme_nosupport.c +++ b/src/detection/wmtheme/wmtheme_nosupport.c @@ -1,8 +1,7 @@ #include "fastfetch.h" #include "wmtheme.h" -bool ffDetectWmTheme(FFstrbuf* themeOrError) -{ +bool ffDetectWmTheme(FFstrbuf* themeOrError) { ffStrbufAppendS(themeOrError, "Not supported on this platform"); return false; } diff --git a/src/detection/wmtheme/wmtheme_windows.c b/src/detection/wmtheme/wmtheme_windows.c index 4b953673e..5d16a84bb 100644 --- a/src/detection/wmtheme/wmtheme_windows.c +++ b/src/detection/wmtheme/wmtheme_windows.c @@ -2,77 +2,124 @@ #include "wmtheme.h" #include "common/windows/registry.h" -const char* colorHexToString(DWORD hex) -{ - switch(hex) - { - case 0x696cc3: return "Yellow gold"; - case 0xff8c00: return "Gold"; - case 0xf7630c: return "Orange bright"; - case 0xca5010: return "Orange dark"; - case 0xda3b01: return "Rust"; - case 0xef6950: return "Pale rust"; - case 0xd13438: return "Brick red"; - case 0xff4343: return "Mod red"; - case 0xe74856: return "Pale red"; - case 0xe81123: return "Red"; - case 0xea005e: return "Rose bright"; - case 0xc30052: return "Rose"; - case 0xe3008c: return "Plum light"; - case 0xbf0077: return "Plum"; - case 0xc239b3: return "Orchid light"; - case 0x9a0089: return "Orchid"; - case 0x0078d4: return "Blue"; - case 0x0063b1: return "Navy blue"; - case 0x8d8bd7: return "Purple shadow"; - case 0x6b69d6: return "Purple shadow dark"; - case 0x8764b8: return "Iris pastel"; - case 0x744da9: return "Iris Spring"; - case 0xb146c2: return "Violet red light"; - case 0x881798: return "Violet red"; - case 0x0099bc: return "Cool blue bright"; - case 0x2d7d9a: return "Cool blue"; - case 0x00b7c3: return "Seafoam"; - case 0x038387: return "Seafoam teal"; - case 0x00b294: return "Mint light"; - case 0x018574: return "Mint dark"; - case 0x00cc6a: return "Turf green"; - case 0x10893e: return "Sport green"; - case 0x7a7574: return "Gray"; - case 0x5d5a58: return "Gray brown"; - case 0x68768a: return "Steel blue"; - case 0x515c6b: return "Metal blue"; - case 0x567c73: return "Pale moss"; - case 0x486860: return "Moss"; - case 0x498205: return "Meadow green"; - case 0x107c10: return "Green"; - case 0x767676: return "Overcast"; - case 0x4c4a48: return "Storm"; - case 0x69797e: return "Blue gray"; - case 0x4a5459: return "Gray dark"; - case 0x647c64: return "Liddy green"; - case 0x4c574e: return "Sage"; - case 0x807143: return "Camouflage desert"; - case 0x766c59: return "Camouflage"; - case 0x000000: return "Black"; - case 0xFFFFFF: return "White"; - default: return NULL; +const char* colorHexToString(DWORD hex) { + switch (hex) { + case 0x696cc3: + return "Yellow gold"; + case 0xff8c00: + return "Gold"; + case 0xf7630c: + return "Orange bright"; + case 0xca5010: + return "Orange dark"; + case 0xda3b01: + return "Rust"; + case 0xef6950: + return "Pale rust"; + case 0xd13438: + return "Brick red"; + case 0xff4343: + return "Mod red"; + case 0xe74856: + return "Pale red"; + case 0xe81123: + return "Red"; + case 0xea005e: + return "Rose bright"; + case 0xc30052: + return "Rose"; + case 0xe3008c: + return "Plum light"; + case 0xbf0077: + return "Plum"; + case 0xc239b3: + return "Orchid light"; + case 0x9a0089: + return "Orchid"; + case 0x0078d4: + return "Blue"; + case 0x0063b1: + return "Navy blue"; + case 0x8d8bd7: + return "Purple shadow"; + case 0x6b69d6: + return "Purple shadow dark"; + case 0x8764b8: + return "Iris pastel"; + case 0x744da9: + return "Iris Spring"; + case 0xb146c2: + return "Violet red light"; + case 0x881798: + return "Violet red"; + case 0x0099bc: + return "Cool blue bright"; + case 0x2d7d9a: + return "Cool blue"; + case 0x00b7c3: + return "Seafoam"; + case 0x038387: + return "Seafoam teal"; + case 0x00b294: + return "Mint light"; + case 0x018574: + return "Mint dark"; + case 0x00cc6a: + return "Turf green"; + case 0x10893e: + return "Sport green"; + case 0x7a7574: + return "Gray"; + case 0x5d5a58: + return "Gray brown"; + case 0x68768a: + return "Steel blue"; + case 0x515c6b: + return "Metal blue"; + case 0x567c73: + return "Pale moss"; + case 0x486860: + return "Moss"; + case 0x498205: + return "Meadow green"; + case 0x107c10: + return "Green"; + case 0x767676: + return "Overcast"; + case 0x4c4a48: + return "Storm"; + case 0x69797e: + return "Blue gray"; + case 0x4a5459: + return "Gray dark"; + case 0x647c64: + return "Liddy green"; + case 0x4c574e: + return "Sage"; + case 0x807143: + return "Camouflage desert"; + case 0x766c59: + return "Camouflage"; + case 0x000000: + return "Black"; + case 0xFFFFFF: + return "White"; + default: + return NULL; } } -bool ffDetectWmTheme(FFstrbuf* themeOrError) -{ +bool ffDetectWmTheme(FFstrbuf* themeOrError) { { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes", &hKey, NULL)) - { + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes", &hKey, NULL)) { FF_STRBUF_AUTO_DESTROY theme = ffStrbufCreate(); - if (ffRegReadStrbuf(hKey, L"CurrentTheme", &theme, NULL)) - { + if (ffRegReadStrbuf(hKey, L"CurrentTheme", &theme, NULL)) { ffStrbufSubstrBeforeLastC(&theme, '.'); ffStrbufSubstrAfterLastC(&theme, '\\'); - if(isalpha(theme.chars[0])) - theme.chars[0] = (char)toupper(theme.chars[0]); + if (isalpha(theme.chars[0])) { + theme.chars[0] = (char) toupper(theme.chars[0]); + } ffStrbufAppend(themeOrError, &theme); } @@ -83,47 +130,51 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError) uint32_t rgbColor; uint32_t bgrColor; FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\DWM", &hKey, NULL)) - { - if (ffRegReadUint(hKey, L"AccentColor", &bgrColor, NULL)) + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\DWM", &hKey, NULL)) { + if (ffRegReadUint(hKey, L"AccentColor", &bgrColor, NULL)) { rgbColor = ((bgrColor & 0xFF) << 16) | (bgrColor & 0xFF00) | ((bgrColor >> 16) & 0xFF); - else if (ffRegReadUint(hKey, L"ColorizationColor", &rgbColor, NULL)) + } else if (ffRegReadUint(hKey, L"ColorizationColor", &rgbColor, NULL)) { rgbColor &= 0xFFFFFF; - else + } else { break; + } + } else { + break; } - else break; - if (themeOrError->length > 0) ffStrbufAppendS(themeOrError, " - "); + if (themeOrError->length > 0) { + ffStrbufAppendS(themeOrError, " - "); + } const char* text = colorHexToString(rgbColor); - if (text) + if (text) { ffStrbufAppendS(themeOrError, text); - else - ffStrbufAppendF(themeOrError, "#%06lX", (long)rgbColor); + } else { + ffStrbufAppendF(themeOrError, "#%06lX", (long) rgbColor); + } } while (false); { FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", &hKey, NULL)) - { + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", &hKey, NULL)) { uint32_t system = 1, apps = 1; if (ffRegReadValues(hKey, 2, (FFRegValueArg[]) { - FF_ARG(system, L"SystemUsesLightTheme"), - FF_ARG(apps, L"AppsUseLightTheme"), - }, NULL)) - { + FF_ARG(system, L"SystemUsesLightTheme"), + FF_ARG(apps, L"AppsUseLightTheme"), + }, + NULL)) { bool paren = themeOrError->length > 0; - if (paren) + if (paren) { ffStrbufAppendS(themeOrError, " ("); + } ffStrbufAppendF(themeOrError, "System: %s, Apps: %s", system ? "Light" : "Dark", apps ? "Light" : "Dark"); - if (paren) + if (paren) { ffStrbufAppendC(themeOrError, ')'); + } } } } - if(themeOrError->length == 0) - { + if (themeOrError->length == 0) { ffStrbufSetStatic(themeOrError, "Failed to find current theme"); return false; } diff --git a/src/detection/zpool/libzfs_simplified.h b/src/detection/zpool/libzfs_simplified.h index 49302c16d..5faf4ec73 100644 --- a/src/detection/zpool/libzfs_simplified.h +++ b/src/detection/zpool/libzfs_simplified.h @@ -36,13 +36,13 @@ typedef int boolean_t; typedef struct libzfs_handle libzfs_handle_t; typedef struct zpool_handle zpool_handle_t; -typedef int (*zpool_iter_f)(zpool_handle_t *, void *); +typedef int (*zpool_iter_f)(zpool_handle_t*, void*); -extern libzfs_handle_t *libzfs_init(void); -extern void libzfs_fini(libzfs_handle_t *); -extern int zpool_iter(libzfs_handle_t *, zpool_iter_f, void *); -extern zpool_prop_t zpool_name_to_prop(const char *); +extern libzfs_handle_t* libzfs_init(void); +extern void libzfs_fini(libzfs_handle_t*); +extern int zpool_iter(libzfs_handle_t*, zpool_iter_f, void*); +extern zpool_prop_t zpool_name_to_prop(const char*); // https://github.com/openzfs/zfs/blob/06c73cffabc30b61a695988ec8e290f43cb3768d/lib/libzfs/libzfs_pool.c#L300 -extern uint64_t zpool_get_prop_int(zpool_handle_t *zhp, zpool_prop_t prop, zprop_source_t *srctype); -extern int zpool_get_prop(zpool_handle_t *zhp, zpool_prop_t prop, char *buf, size_t len, zprop_source_t *srctype, boolean_t literal); -extern void zpool_close(zpool_handle_t *); +extern uint64_t zpool_get_prop_int(zpool_handle_t* zhp, zpool_prop_t prop, zprop_source_t* srctype); +extern int zpool_get_prop(zpool_handle_t* zhp, zpool_prop_t prop, char* buf, size_t len, zprop_source_t* srctype, boolean_t literal); +extern void zpool_close(zpool_handle_t*); diff --git a/src/detection/zpool/zpool.c b/src/detection/zpool/zpool.c index 2f4a4a83f..dfd5f9a04 100644 --- a/src/detection/zpool/zpool.c +++ b/src/detection/zpool/zpool.c @@ -2,23 +2,22 @@ #if FF_HAVE_LIBZFS -#include "common/kmod.h" +# include "common/kmod.h" -#ifdef __sun -#include - #ifndef __illumos__ - // On Solaris 11, zpool_get_prop has only 5 arguments. #2173 - #define ffzpool_get_prop(zhp, prop, buf, len, srctype, literal) \ - ffzpool_get_prop(zhp, prop, buf, len, srctype) - #endif -#else -#include "libzfs_simplified.h" -#endif +# ifdef __sun +# include +# ifndef __illumos__ +// On Solaris 11, zpool_get_prop has only 5 arguments. #2173 +# define ffzpool_get_prop(zhp, prop, buf, len, srctype, literal) \ + ffzpool_get_prop(zhp, prop, buf, len, srctype) +# endif +# else +# include "libzfs_simplified.h" +# endif -#include "common/library.h" +# include "common/library.h" -typedef struct FFZfsData -{ +typedef struct FFZfsData { FF_LIBRARY_SYMBOL(libzfs_fini) FF_LIBRARY_SYMBOL(zpool_get_prop_int) FF_LIBRARY_SYMBOL(zpool_get_prop) @@ -41,29 +40,28 @@ typedef struct FFZfsData FFlist* result; } FFZfsData; -static inline void cleanLibzfs(FFZfsData* data) -{ - if (data->fflibzfs_fini && data->handle) - { +static inline void cleanLibzfs(FFZfsData* data) { + if (data->fflibzfs_fini && data->handle) { data->fflibzfs_fini(data->handle); data->handle = NULL; } } -static int enumZpoolCallback(zpool_handle_t* zpool, void* param) -{ +static int enumZpoolCallback(zpool_handle_t* zpool, void* param) { FFZfsData* data = (FFZfsData*) param; zprop_source_t source; FFZpoolResult* item = ffListAdd(data->result); char buf[1024]; - if (data->ffzpool_get_prop(zpool, data->props.name, buf, ARRAY_SIZE(buf), &source, false) == 0) + if (data->ffzpool_get_prop(zpool, data->props.name, buf, ARRAY_SIZE(buf), &source, false) == 0) { ffStrbufInitS(&item->name, buf); - else + } else { ffStrbufInitStatic(&item->name, "unknown"); - if (data->ffzpool_get_prop(zpool, data->props.health, buf, ARRAY_SIZE(buf), &source, false) == 0) + } + if (data->ffzpool_get_prop(zpool, data->props.health, buf, ARRAY_SIZE(buf), &source, false) == 0) { ffStrbufInitS(&item->state, buf); - else + } else { ffStrbufInitStatic(&item->state, "unknown"); + } item->guid = data->ffzpool_get_prop_int(zpool, data->props.guid, &source); item->total = data->ffzpool_get_prop_int(zpool, data->props.size, &source); item->used = item->total - data->ffzpool_get_prop_int(zpool, data->props.free, &source); @@ -75,15 +73,15 @@ static int enumZpoolCallback(zpool_handle_t* zpool, void* param) return 0; } -const char* ffDetectZpool(FFlist* result /* list of FFZpoolResult */) -{ +const char* ffDetectZpool(FFlist* result /* list of FFZpoolResult */) { FF_LIBRARY_LOAD_MESSAGE(libzfs, "libzfs" FF_LIBRARY_EXTENSION, 6); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libzfs, libzfs_init); libzfs_handle_t* handle = fflibzfs_init(); - if (!handle) - { - if (!ffKmodLoaded("zfs")) return "`zfs` kernel module is not loaded"; + if (!handle) { + if (!ffKmodLoaded("zfs")) { + return "`zfs` kernel module is not loaded"; + } return "libzfs_init() failed"; } @@ -94,11 +92,12 @@ const char* ffDetectZpool(FFlist* result /* list of FFZpoolResult */) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libzfs, zpool_name_to_prop); - #define FF_QUERY_ZPOOL_PROP_FROM_NAME(prop_name) do { \ - data.props.prop_name = ffzpool_name_to_prop(#prop_name); \ - if (data.props.prop_name < 0) \ - return "Failed to query prop: " #prop_name; \ - } while (false) +# define FF_QUERY_ZPOOL_PROP_FROM_NAME(prop_name) \ + do { \ + data.props.prop_name = ffzpool_name_to_prop(#prop_name); \ + if (data.props.prop_name < 0) \ + return "Failed to query prop: " #prop_name; \ + } while (false) FF_QUERY_ZPOOL_PROP_FROM_NAME(name); FF_QUERY_ZPOOL_PROP_FROM_NAME(health); FF_QUERY_ZPOOL_PROP_FROM_NAME(guid); @@ -107,7 +106,7 @@ const char* ffDetectZpool(FFlist* result /* list of FFZpoolResult */) FF_QUERY_ZPOOL_PROP_FROM_NAME(allocated); FF_QUERY_ZPOOL_PROP_FROM_NAME(fragmentation); FF_QUERY_ZPOOL_PROP_FROM_NAME(readonly); - #undef FF_QUERY_ZPOOL_PROP_FROM_NAME +# undef FF_QUERY_ZPOOL_PROP_FROM_NAME FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libzfs, zpool_iter); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libzfs, data, libzfs_fini); @@ -115,16 +114,16 @@ const char* ffDetectZpool(FFlist* result /* list of FFZpoolResult */) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libzfs, data, zpool_get_prop); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libzfs, data, zpool_close); - if (ffzpool_iter(handle, enumZpoolCallback, &data) < 0) + if (ffzpool_iter(handle, enumZpoolCallback, &data) < 0) { return "zpool_iter() failed"; + } return NULL; } #else -const char* ffDetectZpool(FF_MAYBE_UNUSED FFlist* result) -{ +const char* ffDetectZpool(FF_MAYBE_UNUSED FFlist* result) { return "fastfetch was compiled without libzfs support"; } diff --git a/src/detection/zpool/zpool.h b/src/detection/zpool/zpool.h index bc2d4061a..2e6523fed 100644 --- a/src/detection/zpool/zpool.h +++ b/src/detection/zpool/zpool.h @@ -3,8 +3,7 @@ #include "fastfetch.h" #include "modules/zpool/option.h" -typedef struct FFZpoolResult -{ +typedef struct FFZpoolResult { FFstrbuf name; FFstrbuf state; uint64_t guid; diff --git a/src/fastfetch.c b/src/fastfetch.c index b63119097..2e9148bc3 100644 --- a/src/fastfetch.c +++ b/src/fastfetch.c @@ -15,29 +15,26 @@ #include #include -static void printCommandFormatHelpJson(void) -{ +static void printCommandFormatHelpJson(void) { yyjson_mut_doc* doc = yyjson_mut_doc_new(NULL); yyjson_mut_val* root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); - for (uint32_t i = 0; i <= 'Z' - 'A'; ++i) - { - for (FFModuleBaseInfo** modules = ffModuleInfos[i]; *modules; ++modules) - { + for (uint32_t i = 0; i <= 'Z' - 'A'; ++i) { + for (FFModuleBaseInfo** modules = ffModuleInfos[i]; *modules; ++modules) { FFModuleBaseInfo* baseInfo = *modules; - if (!baseInfo->formatArgs.count) continue; + if (!baseInfo->formatArgs.count) { + continue; + } FF_STRBUF_AUTO_DESTROY type = ffStrbufCreateS(baseInfo->name); ffStrbufLowerCase(&type); ffStrbufAppendS(&type, "Format"); yyjson_mut_val* obj = yyjson_mut_obj(doc); - if (yyjson_mut_obj_add(root, yyjson_mut_strbuf(doc, &type), obj)) - { + if (yyjson_mut_obj_add(root, yyjson_mut_strbuf(doc, &type), obj)) { FF_STRBUF_AUTO_DESTROY content = ffStrbufCreateF("Output format of the module `%s`. See Wiki for formatting syntax\n", baseInfo->name); - for (unsigned i = 0; i < baseInfo->formatArgs.count; i++) - { + for (unsigned i = 0; i < baseInfo->formatArgs.count; i++) { const FFModuleFormatArg* arg = &baseInfo->formatArgs.args[i]; ffStrbufAppendF(&content, " %u. {%s}: %s\n", i + 1, arg->name, arg->desc); } @@ -52,32 +49,27 @@ static void printCommandFormatHelpJson(void) yyjson_mut_doc_free(doc); } -static void printCommandFormatHelp(const char* command) -{ +static void printCommandFormatHelp(const char* command) { FF_STRBUF_AUTO_DESTROY type = ffStrbufCreateNS((uint32_t) (strlen(command) - strlen("-format")), command); ffStrbufLowerCase(&type); - for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(command[0]) - 'A']; *modules; ++modules) - { + for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(command[0]) - 'A']; *modules; ++modules) { FFModuleBaseInfo* baseInfo = *modules; - if (ffStrbufIgnCaseEqualS(&type, baseInfo->name)) - { - if (baseInfo->formatArgs.count > 0) - { + if (ffStrbufIgnCaseEqualS(&type, baseInfo->name)) { + if (baseInfo->formatArgs.count > 0) { FF_STRBUF_AUTO_DESTROY variable = ffStrbufCreate(); printf("-- In config file: { \"type\": \"%s\", \"format\": \"{}\" }\n", type.chars); printf("Sets the format string for %s output.\n", baseInfo->name); puts("To see how a format string is constructed, take a look at https://github.com/fastfetch-cli/fastfetch/wiki/Format-String-Guide."); puts("The following variables are passed:"); - for (unsigned i = 0; i < baseInfo->formatArgs.count; i++) - { + for (unsigned i = 0; i < baseInfo->formatArgs.count; i++) { const FFModuleFormatArg* arg = &baseInfo->formatArgs.args[i]; ffStrbufSetF(&variable, "{%s}", arg->name); printf("%20s: %s\n", variable.chars, arg->desc); } - } - else + } else { fprintf(stderr, "Error: Module '%s' doesn't support output formatting\n", baseInfo->name); + } return; } } @@ -85,94 +77,96 @@ static void printCommandFormatHelp(const char* command) fprintf(stderr, "Error: Module '%s' is not supported\n", type.chars); } -static void printFullHelp() -{ +static void printFullHelp() { fputs("Fastfetch is a neofetch-like tool for fetching system information and displaying them in a pretty way\n\n", stdout); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[1;4mUsage:\e[m \e[1mfastfetch\e[m \e[3m\e[m\n\n", stdout); - else + } else { fputs("Usage: fastfetch \n\n", stdout); + } yyjson_doc* doc = yyjson_read(FASTFETCH_DATATEXT_JSON_HELP, strlen(FASTFETCH_DATATEXT_JSON_HELP), YYJSON_READ_NOFLAG); assert(doc); yyjson_val *groupKey, *flagArr; size_t groupIdx, groupMax; - yyjson_obj_foreach(yyjson_doc_get_root(doc), groupIdx, groupMax, groupKey, flagArr) - { - if (!instance.config.display.pipe) + yyjson_obj_foreach (yyjson_doc_get_root(doc), groupIdx, groupMax, groupKey, flagArr) { + if (!instance.config.display.pipe) { fputs("\e[1;4m", stdout); + } printf("%s options:", yyjson_get_str(groupKey)); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[m", stdout); + } putchar('\n'); yyjson_val* flagObj; size_t flagIdx, flagMax; - yyjson_arr_foreach(flagArr, flagIdx, flagMax, flagObj) - { + yyjson_arr_foreach (flagArr, flagIdx, flagMax, flagObj) { yyjson_val* shortKey = yyjson_obj_get(flagObj, "short"); - if (shortKey) - { + if (shortKey) { fputs(" ", stdout); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[1m", stdout); + } printf("-%s", yyjson_get_str(shortKey)); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[m", stdout); + } fputs(", ", stdout); - } - else - { + } else { fputs(" ", stdout); } yyjson_val* longKey = yyjson_obj_get(flagObj, "long"); assert(longKey); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[1m", stdout); + } printf("--%s", yyjson_get_str(longKey)); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[m", stdout); + } yyjson_val* argObj = yyjson_obj_get(flagObj, "arg"); - if (argObj) - { + if (argObj) { yyjson_val* typeKey = yyjson_obj_get(argObj, "type"); assert(typeKey); yyjson_val* optionalKey = yyjson_obj_get(argObj, "optional"); bool optional = optionalKey && yyjson_get_bool(optionalKey); putchar(' '); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[3m", stdout); + } printf("<%s%s>", optional ? "?" : "", yyjson_get_str(typeKey)); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[m", stdout); + } } yyjson_val* descKey = yyjson_obj_get(flagObj, "desc"); assert(descKey); - if (yyjson_is_arr(descKey)) - { - if (instance.config.display.pipe) + if (yyjson_is_arr(descKey)) { + if (instance.config.display.pipe) { putchar(':'); + } yyjson_val* descStr; size_t descIdx, descMax; - yyjson_arr_foreach(descKey, descIdx, descMax, descStr) - { - if (!instance.config.display.pipe) + yyjson_arr_foreach (descKey, descIdx, descMax, descStr) { + if (!instance.config.display.pipe) { printf("\e[46G%s\n", yyjson_get_str(descStr)); - else + } else { printf(" %s", yyjson_get_str(descStr)); + } } - if (instance.config.display.pipe) + if (instance.config.display.pipe) { putchar('\n'); - } - else - { - if (!instance.config.display.pipe) + } + } else { + if (!instance.config.display.pipe) { fputs("\e[46G", stdout); - else + } else { fputs(": ", stdout); + } puts(yyjson_get_str(descKey)); } } @@ -189,103 +183,102 @@ For detailed information on logo options, module configuration, and formatting, https://github.com/fastfetch-cli/fastfetch/wiki/Configuration"); } -static bool printSpecificCommandHelp(const char* command) -{ +static bool printSpecificCommandHelp(const char* command) { yyjson_doc* doc = yyjson_read(FASTFETCH_DATATEXT_JSON_HELP, strlen(FASTFETCH_DATATEXT_JSON_HELP), YYJSON_READ_NOFLAG); assert(doc); yyjson_val *groupKey, *flagArr; size_t groupIdx, groupMax; - yyjson_obj_foreach(yyjson_doc_get_root(doc), groupIdx, groupMax, groupKey, flagArr) - { + yyjson_obj_foreach (yyjson_doc_get_root(doc), groupIdx, groupMax, groupKey, flagArr) { yyjson_val* flagObj; size_t flagIdx, flagMax; - yyjson_arr_foreach(flagArr, flagIdx, flagMax, flagObj) - { + yyjson_arr_foreach (flagArr, flagIdx, flagMax, flagObj) { yyjson_val* pseudo = yyjson_obj_get(flagObj, "pseudo"); - if (pseudo && yyjson_get_bool(pseudo)) + if (pseudo && yyjson_get_bool(pseudo)) { continue; + } yyjson_val* longKey = yyjson_obj_get(flagObj, "long"); assert(longKey); - if (ffStrEqualsIgnCase(command, yyjson_get_str(longKey))) - { + if (ffStrEqualsIgnCase(command, yyjson_get_str(longKey))) { puts(yyjson_get_str(yyjson_obj_get(flagObj, "desc"))); printf("%10s: ", "Usage"); yyjson_val* shortKey = yyjson_obj_get(flagObj, "short"); - if (shortKey) - { - if (!instance.config.display.pipe) + if (shortKey) { + if (!instance.config.display.pipe) { fputs("\e[1m", stdout); + } printf("-%s", yyjson_get_str(shortKey)); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[m", stdout); + } fputs(", ", stdout); } - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[1m", stdout); + } printf("--%s", yyjson_get_str(longKey)); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[m", stdout); + } yyjson_val* argObj = yyjson_obj_get(flagObj, "arg"); - if (argObj) - { + if (argObj) { yyjson_val* typeKey = yyjson_obj_get(argObj, "type"); assert(typeKey); yyjson_val* optionalKey = yyjson_obj_get(argObj, "optional"); bool optional = optionalKey && yyjson_get_bool(optionalKey); putchar(' '); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[3m", stdout); + } printf("<%s%s>", optional ? "?" : "", yyjson_get_str(typeKey)); - if (!instance.config.display.pipe) + if (!instance.config.display.pipe) { fputs("\e[m", stdout); + } putchar('\n'); yyjson_val* defaultKey = yyjson_obj_get(argObj, "default"); - if (defaultKey) - { - if (ffStrEqualsIgnCase(yyjson_get_str(typeKey), "structure")) + if (defaultKey) { + if (ffStrEqualsIgnCase(yyjson_get_str(typeKey), "structure")) { printf("%10s: %s\n", "Default", FASTFETCH_DATATEXT_STRUCTURE); - else if (yyjson_is_bool(defaultKey)) + } else if (yyjson_is_bool(defaultKey)) { printf("%10s: %s\n", "Default", yyjson_get_bool(defaultKey) ? "true" : "false"); - else if (yyjson_is_num(defaultKey)) + } else if (yyjson_is_num(defaultKey)) { printf("%10s: %d\n", "Default", yyjson_get_int(defaultKey)); - else if (yyjson_is_str(defaultKey)) + } else if (yyjson_is_str(defaultKey)) { printf("%10s: %s\n", "Default", yyjson_get_str(defaultKey)); - else + } else { printf("%10s: Unknown\n", "Default"); + } } yyjson_val* enumKey = yyjson_obj_get(argObj, "enum"); - if (enumKey) - { + if (enumKey) { printf("%10s:\n", "Options"); yyjson_val *optKey, *optVal; size_t optIdx, optMax; - yyjson_obj_foreach(enumKey, optIdx, optMax, optKey, optVal) + yyjson_obj_foreach (enumKey, optIdx, optMax, optKey, optVal) { printf("%12s: %s\n", yyjson_get_str(optKey), yyjson_get_str(optVal)); + } } - } - else + } else { putchar('\n'); + } yyjson_val* remarkKey = yyjson_obj_get(flagObj, "remark"); - if (remarkKey) - { - if (yyjson_is_str(remarkKey)) + if (remarkKey) { + if (yyjson_is_str(remarkKey)) { printf("%10s: %s\n", "Remark", yyjson_get_str(remarkKey)); - else if (yyjson_is_arr(remarkKey) && yyjson_arr_size(remarkKey) > 0) - { + } else if (yyjson_is_arr(remarkKey) && yyjson_arr_size(remarkKey) > 0) { yyjson_val* remarkStr; size_t remarkIdx, remarkMax; - yyjson_arr_foreach(remarkKey, remarkIdx, remarkMax, remarkStr) - { - if (remarkIdx == 0) + yyjson_arr_foreach (remarkKey, remarkIdx, remarkMax, remarkStr) { + if (remarkIdx == 0) { printf("%10s: %s\n", "Remark", yyjson_get_str(remarkStr)); - else + } else { printf(" %s\n", yyjson_get_str(remarkStr)); + } } } } @@ -300,28 +293,25 @@ static bool printSpecificCommandHelp(const char* command) return false; } -static void printCommandHelp(const char* command) -{ - if(command == NULL) +static void printCommandHelp(const char* command) { + if (command == NULL) { printFullHelp(); - else if(ffStrEqualsIgnCase(command, "format-json")) + } else if (ffStrEqualsIgnCase(command, "format-json")) { printCommandFormatHelpJson(); - else if(ffCharIsEnglishAlphabet(command[0]) && ffStrEndsWithIgnCase(command, "-format")) // -format + } else if (ffCharIsEnglishAlphabet(command[0]) && ffStrEndsWithIgnCase(command, "-format")) { // -format printCommandFormatHelp(command); - else if(!printSpecificCommandHelp(command)) + } else if (!printSpecificCommandHelp(command)) { fprintf(stderr, "Error: No specific help for command '%s' provided\n", command); + } } -static void listAvailablePresets(bool pretty) -{ - FF_LIST_FOR_EACH(FFstrbuf, path, instance.state.platform.dataDirs) - { +static void listAvailablePresets(bool pretty) { + FF_LIST_FOR_EACH (FFstrbuf, path, instance.state.platform.dataDirs) { ffStrbufAppendS(path, "fastfetch/presets/"); ffListFilesRecursively(path->chars, pretty); } - if (instance.state.platform.exePath.length) - { + if (instance.state.platform.exePath.length) { FF_STRBUF_AUTO_DESTROY absolutePath = ffStrbufCreateCopy(&instance.state.platform.exePath); ffStrbufSubstrBeforeLastC(&absolutePath, '/'); ffStrbufAppendS(&absolutePath, "/presets/"); @@ -329,19 +319,15 @@ static void listAvailablePresets(bool pretty) } } -static void listAvailableLogos(void) -{ - FF_LIST_FOR_EACH(FFstrbuf, path, instance.state.platform.dataDirs) - { +static void listAvailableLogos(void) { + FF_LIST_FOR_EACH (FFstrbuf, path, instance.state.platform.dataDirs) { ffStrbufAppendS(path, "fastfetch/logos/"); ffListFilesRecursively(path->chars, true); } } -static void listConfigPaths(void) -{ - FF_LIST_FOR_EACH(FFstrbuf, folder, instance.state.platform.configDirs) - { +static void listConfigPaths(void) { + FF_LIST_FOR_EACH (FFstrbuf, folder, instance.state.platform.configDirs) { bool exists = false; uint32_t length = folder->length + (uint32_t) strlen("fastfetch") + 1 /* trailing slash */; ffStrbufAppendS(folder, "fastfetch/config.jsonc"); @@ -351,33 +337,28 @@ static void listConfigPaths(void) } } -static void listDataPaths(void) -{ - FF_LIST_FOR_EACH(FFstrbuf, folder, instance.state.platform.dataDirs) - { +static void listDataPaths(void) { + FF_LIST_FOR_EACH (FFstrbuf, folder, instance.state.platform.dataDirs) { ffStrbufAppendS(folder, "fastfetch/"); puts(folder->chars); } } -static void listModules(bool pretty) -{ +static void listModules(bool pretty) { unsigned count = 0; - for (int i = 0; i <= 'Z' - 'A'; ++i) - { - for (FFModuleBaseInfo** modules = ffModuleInfos[i]; *modules; ++modules) - { + for (int i = 0; i <= 'Z' - 'A'; ++i) { + for (FFModuleBaseInfo** modules = ffModuleInfos[i]; *modules; ++modules) { ++count; - if (pretty) + if (pretty) { printf("%d)%s%-14s: %s\n", count, count > 9 ? " " : " ", (*modules)->name, (*modules)->description); - else + } else { printf("%s:%s\n", (*modules)->name, (*modules)->description); + } } } } -static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) -{ +static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) { assert(!data->configDoc); { @@ -385,20 +366,18 @@ static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) data->configDoc = path ? yyjson_read_file(path, flg, NULL, &error) : yyjson_read_fp(stdin, flg, NULL, &error); - if (!data->configDoc) - { - if (error.code != YYJSON_READ_ERROR_FILE_OPEN) - { - if (path) - { + if (!data->configDoc) { + if (error.code != YYJSON_READ_ERROR_FILE_OPEN) { + if (path) { size_t row = 0, col = error.pos; FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); - if (ffAppendFileBuffer(path, &content)) + if (ffAppendFileBuffer(path, &content)) { yyjson_locate_pos(content.chars, content.length, error.pos, &row, &col, NULL); + } fprintf(stderr, "Error: failed to parse JSON config file `%s` at (%zu, %zu): %s\n", path, row, col, error.msg); - } - else + } else { fprintf(stderr, "Error: failed to parse JSON from stdin at %zu: %s\n", error.pos, error.msg); + } exit(477); } @@ -410,16 +389,16 @@ static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) const char* error = NULL; yyjson_val* const root = yyjson_doc_get_root(data->configDoc); - if (!yyjson_is_obj(root)) + if (!yyjson_is_obj(root)) { error = "Invalid JSON config format. Root value must be an object"; + } if ( error || (error = ffOptionsParseLogoJsonConfig(&instance.config.logo, root)) || (error = ffOptionsParseGeneralJsonConfig(&instance.config.general, root)) || (error = ffOptionsParseDisplayJsonConfig(&instance.config.display, root)) || - false - ) { + false) { fprintf(stderr, "JsonConfig Error: %s\n", error); exit(477); } @@ -428,19 +407,14 @@ static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) return true; } - -static void generateConfigFile(FFdata* data, bool force, const char* filePath, bool fullConfig) -{ - if (data->resultDoc) - { +static void generateConfigFile(FFdata* data, bool force, const char* filePath, bool fullConfig) { + if (data->resultDoc) { fprintf(stderr, "Error: duplicated `--gen-config` or `--format json` flags found\n"); exit(477); } - if (!filePath) - { - if (instance.state.platform.configDirs.length == 0) - { + if (!filePath) { + if (instance.state.platform.configDirs.length == 0) { fprintf(stderr, "Error: No config directory found to generate config file in. Use --gen-config to specify a path\n"); exit(477); } @@ -449,14 +423,11 @@ static void generateConfigFile(FFdata* data, bool force, const char* filePath, b ffStrbufEnsureFixedLengthFree(&data->genConfigPath, configDir->length + strlen("fastfetch/config.jsonc")); ffStrbufSet(&data->genConfigPath, configDir); ffStrbufAppendS(&data->genConfigPath, "fastfetch/config.jsonc"); - } - else - { + } else { ffStrbufSetS(&data->genConfigPath, filePath); } - if (!force && ffPathExists(data->genConfigPath.chars, FF_PATHTYPE_ANY)) - { + if (!force && ffPathExists(data->genConfigPath.chars, FF_PATHTYPE_ANY)) { fprintf(stderr, "Error: file `%s` exists. Use `--gen-config%s-force` to overwrite\n", data->genConfigPath.chars, fullConfig ? "-full" : ""); exit(477); } @@ -465,32 +436,29 @@ static void generateConfigFile(FFdata* data, bool force, const char* filePath, b data->resultDoc = yyjson_mut_doc_new(NULL); } -static void optionParseConfigFile(FFdata* data, const char* key, const char* value) -{ - if (data->configLoaded) - { +static void optionParseConfigFile(FFdata* data, const char* key, const char* value) { + if (data->configLoaded) { fprintf(stderr, "Error: only one config file can be loaded\n"); exit(413); } data->configLoaded = true; - if(value == NULL) - { + if (value == NULL) { fprintf(stderr, "Error: usage: %s \n", key); exit(413); } - if (value[0] == '\0' || ffStrEqualsIgnCase(value, "none")) + if (value[0] == '\0' || ffStrEqualsIgnCase(value, "none")) { return; + } - if (value[0] == '-' && value[1] == '\0') - { + if (value[0] == '-' && value[1] == '\0') { parseJsoncFile(data, NULL, false); return; } - //Try to load as an absolute path + // Try to load as an absolute path FF_STRBUF_AUTO_DESTROY absolutePath = ffStrbufCreateA(128); ffStrbufSetS(&absolutePath, value); @@ -498,82 +466,91 @@ static void optionParseConfigFile(FFdata* data, const char* key, const char* val bool jsonc = !strictJson && ffStrbufEndsWithIgnCaseS(&absolutePath, ".jsonc"); bool json5 = !strictJson && !jsonc && ffStrbufEndsWithIgnCaseS(&absolutePath, ".json5"); bool needExtension = !strictJson && !jsonc && !json5; - if (needExtension) + if (needExtension) { ffStrbufAppendS(&absolutePath, ".jsonc"); + } yyjson_read_flag flag = strictJson ? 0 : jsonc - ? YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS - : YYJSON_READ_JSON5; + ? YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS + : YYJSON_READ_JSON5; - if (parseJsoncFile(data, absolutePath.chars, flag)) return; + if (parseJsoncFile(data, absolutePath.chars, flag)) { + return; + } - //Try to load as a relative path with the config directory + // Try to load as a relative path with the config directory - FF_LIST_FOR_EACH(FFstrbuf, path, instance.state.platform.configDirs) - { + FF_LIST_FOR_EACH (FFstrbuf, path, instance.state.platform.configDirs) { ffStrbufSet(&absolutePath, path); ffStrbufAppendS(&absolutePath, "fastfetch/"); ffStrbufAppendS(&absolutePath, value); - if (needExtension) + if (needExtension) { ffStrbufAppendS(&absolutePath, ".jsonc"); + } - if (parseJsoncFile(data, absolutePath.chars, flag)) return; + if (parseJsoncFile(data, absolutePath.chars, flag)) { + return; + } } - //Try to load as a preset + // Try to load as a preset - FF_LIST_FOR_EACH(FFstrbuf, path, instance.state.platform.dataDirs) - { + FF_LIST_FOR_EACH (FFstrbuf, path, instance.state.platform.dataDirs) { ffStrbufSet(&absolutePath, path); ffStrbufAppendS(&absolutePath, "fastfetch/presets/"); ffStrbufAppendS(&absolutePath, value); - if (needExtension) + if (needExtension) { ffStrbufAppendS(&absolutePath, ".jsonc"); + } - if (parseJsoncFile(data, absolutePath.chars, flag)) return; + if (parseJsoncFile(data, absolutePath.chars, flag)) { + return; + } } - //Try to load as a relative path with the directory of fastfetch binary, for Windows support + // Try to load as a relative path with the directory of fastfetch binary, for Windows support - if (instance.state.platform.exePath.length) - { + if (instance.state.platform.exePath.length) { uint32_t lastSlash = ffStrbufLastIndexC(&instance.state.platform.exePath, '/') + 1; assert(lastSlash < instance.state.platform.exePath.length); // Try {exePath}/ ffStrbufSetNS(&absolutePath, lastSlash, instance.state.platform.exePath.chars); ffStrbufAppendS(&absolutePath, value); - if (needExtension) + if (needExtension) { ffStrbufAppendS(&absolutePath, ".jsonc"); - if (parseJsoncFile(data, absolutePath.chars, flag)) return; + } + if (parseJsoncFile(data, absolutePath.chars, flag)) { + return; + } // Try {exePath}/presets/ ffStrbufSubstrBefore(&absolutePath, lastSlash); ffStrbufAppendS(&absolutePath, "presets/"); ffStrbufAppendS(&absolutePath, value); - if (needExtension) + if (needExtension) { ffStrbufAppendS(&absolutePath, ".jsonc"); - if (parseJsoncFile(data, absolutePath.chars, flag)) return; + } + if (parseJsoncFile(data, absolutePath.chars, flag)) { + return; + } } - //File not found + // File not found fprintf(stderr, "Error: couldn't find config: %s\n", value); exit(414); } -static void printVersion() -{ +static void printVersion() { FFVersionResult* result = &ffVersionResult; printf("%s %s%s%s (%s)\n", result->projectName, result->version, result->versionTweak, result->debugMode ? "-debug" : "", result->architecture); } -static void enableJsonOutput(FFdata* data) -{ - if (data->resultDoc) - { +static void enableJsonOutput(FFdata* data) { + if (data->resultDoc) { fprintf(stderr, "Error: duplicated `--gen-config` or `--format json` flags found\n"); exit(477); } @@ -583,249 +560,228 @@ static void enableJsonOutput(FFdata* data) yyjson_mut_doc_set_root(data->resultDoc, yyjson_mut_arr(data->resultDoc)); } -static void parseCommand(FFdata* data, char* key, char* value) -{ - if(ffStrEqualsIgnCase(key, "-h") || ffStrEqualsIgnCase(key, "--help")) - { +static void parseCommand(FFdata* data, char* key, char* value) { + if (ffStrEqualsIgnCase(key, "-h") || ffStrEqualsIgnCase(key, "--help")) { printCommandHelp(value); exit(0); } - if(ffStrEqualsIgnCase(key, "--help-raw")) - { + if (ffStrEqualsIgnCase(key, "--help-raw")) { puts(FASTFETCH_DATATEXT_JSON_HELP); exit(0); - } - else if(ffStrEqualsIgnCase(key, "-v") || ffStrEqualsIgnCase(key, "--version")) - { + } else if (ffStrEqualsIgnCase(key, "-v") || ffStrEqualsIgnCase(key, "--version")) { printVersion(); exit(0); - } - else if(ffStrEqualsIgnCase(key, "--version-raw")) - { + } else if (ffStrEqualsIgnCase(key, "--version-raw")) { puts(FASTFETCH_PROJECT_VERSION); exit(0); - } - else if(ffStrStartsWithIgnCase(key, "--print-")) - { + } else if (ffStrStartsWithIgnCase(key, "--print-")) { const char* subkey = key + strlen("--print-"); - if(ffStrEndsWithIgnCase(subkey, "structure")) + if (ffStrEndsWithIgnCase(subkey, "structure")) { puts(FASTFETCH_DATATEXT_STRUCTURE); - else if(ffStrEqualsIgnCase(subkey, "logos")) + } else if (ffStrEqualsIgnCase(subkey, "logos")) { ffLogoBuiltinPrint(); - else - { + } else { fprintf(stderr, "Error: unsupported print option: %s\n", key); exit(415); } exit(0); - } - else if(ffStrStartsWithIgnCase(key, "--list-")) - { + } else if (ffStrStartsWithIgnCase(key, "--list-")) { const char* subkey = key + strlen("--list-"); - if(ffStrEqualsIgnCase(subkey, "modules")) + if (ffStrEqualsIgnCase(subkey, "modules")) { listModules(!value || !ffStrEqualsIgnCase(value, "autocompletion")); - else if(ffStrEqualsIgnCase(subkey, "presets")) + } else if (ffStrEqualsIgnCase(subkey, "presets")) { listAvailablePresets(!value || !ffStrEqualsIgnCase(value, "autocompletion")); - else if(ffStrEqualsIgnCase(subkey, "config-paths")) + } else if (ffStrEqualsIgnCase(subkey, "config-paths")) { listConfigPaths(); - else if(ffStrEqualsIgnCase(subkey, "data-paths")) + } else if (ffStrEqualsIgnCase(subkey, "data-paths")) { listDataPaths(); - else if(ffStrEqualsIgnCase(subkey, "features")) + } else if (ffStrEqualsIgnCase(subkey, "features")) { ffListFeatures(); - else if(ffStrEqualsIgnCase(subkey, "logos")) - { - if (value) - { - if (ffStrEqualsIgnCase(value, "autocompletion")) + } else if (ffStrEqualsIgnCase(subkey, "logos")) { + if (value) { + if (ffStrEqualsIgnCase(value, "autocompletion")) { ffLogoBuiltinListAutocompletion(); - else if (ffStrEqualsIgnCase(value, "builtin")) + } else if (ffStrEqualsIgnCase(value, "builtin")) { ffLogoBuiltinList(); - else if (ffStrEqualsIgnCase(value, "custom")) + } else if (ffStrEqualsIgnCase(value, "custom")) { listAvailableLogos(); - else - { + } else { fprintf(stderr, "Error: unsupported logo type: %s\n", value); exit(415); } - } - else - { + } else { puts("Builtin logos:"); ffLogoBuiltinList(); puts("\nCustom logos:"); listAvailableLogos(); } - } - else - { + } else { fprintf(stderr, "Error: unsupported list option: %s\n", key); exit(415); } exit(0); - } - else if(ffStrEqualsIgnCase(key, "--gen-config")) + } else if (ffStrEqualsIgnCase(key, "--gen-config")) { generateConfigFile(data, false, value, false); - else if(ffStrEqualsIgnCase(key, "--gen-config-force")) + } else if (ffStrEqualsIgnCase(key, "--gen-config-force")) { generateConfigFile(data, true, value, false); - else if(ffStrEqualsIgnCase(key, "--gen-config-full")) + } else if (ffStrEqualsIgnCase(key, "--gen-config-full")) { generateConfigFile(data, false, value, true); - else if(ffStrEqualsIgnCase(key, "--gen-config-full-force")) + } else if (ffStrEqualsIgnCase(key, "--gen-config-full-force")) { generateConfigFile(data, true, value, true); - else if(ffStrEqualsIgnCase(key, "-c") || ffStrEqualsIgnCase(key, "--config")) + } else if (ffStrEqualsIgnCase(key, "-c") || ffStrEqualsIgnCase(key, "--config")) { optionParseConfigFile(data, key, value); - else if(ffStrEqualsIgnCase(key, "-j") || ffStrEqualsIgnCase(key, "--json")) - { - if (ffOptionParseBoolean(value)) enableJsonOutput(data); - } - else if(ffStrEqualsIgnCase(key, "--format")) - { + } else if (ffStrEqualsIgnCase(key, "-j") || ffStrEqualsIgnCase(key, "--json")) { + if (ffOptionParseBoolean(value)) { + enableJsonOutput(data); + } + } else if (ffStrEqualsIgnCase(key, "--format")) { if (!!ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "default", false}, - { "json", true }, - {}, - })) enableJsonOutput(data); - } - else if(ffStrEqualsIgnCase(key, "--dynamic-interval")) + {"default", false}, + {"json", true}, + {}, + })) { + enableJsonOutput(data); + } + } else if (ffStrEqualsIgnCase(key, "--dynamic-interval")) { instance.state.dynamicInterval = ffOptionParseUInt32(key, value); // seconds to milliseconds - else + } else { return; + } // Don't parse it again in parseOption. // This is necessary because parseOption doesn't understand this option and will result in an unknown option error. key[0] = '\0'; - if (value) value[0] = '\0'; + if (value) { + value[0] = '\0'; + } } -static void parseOption(FFdata* data, const char* key, const char* value) -{ - if(ffStrEqualsIgnCase(key, "-s") || ffStrEqualsIgnCase(key, "--structure")) +static void parseOption(FFdata* data, const char* key, const char* value) { + if (ffStrEqualsIgnCase(key, "-s") || ffStrEqualsIgnCase(key, "--structure")) { ffOptionParseString(key, value, &data->structure); + } - else if( + else if ( ffOptionsParseGeneralCommandLine(&instance.config.general, key, value) || ffOptionsParseLogoCommandLine(&instance.config.logo, key, value) || ffOptionsParseDisplayCommandLine(&instance.config.display, key, value) || - ffParseModuleOptions(key, value) - ) {} + ffParseModuleOptions(key, value)) { + } - else if(ffStrEqualsIgnCase(key, "--structure-disabled")) + else if (ffStrEqualsIgnCase(key, "--structure-disabled")) { ffOptionParseString(key, value, &data->structureDisabled); + } - else - { + else { fprintf(stderr, "Error: unknown option: %s\n", key); exit(400); } } -static void parseConfigFiles(FFdata* data) -{ - if (__builtin_expect(data->genConfigPath.length == 0, true)) - { - FF_LIST_FOR_EACH(FFstrbuf, dir, instance.state.platform.configDirs) - { +static void parseConfigFiles(FFdata* data) { + if (__builtin_expect(data->genConfigPath.length == 0, true)) { + FF_LIST_FOR_EACH (FFstrbuf, dir, instance.state.platform.configDirs) { uint32_t dirLength = dir->length; ffStrbufAppendS(dir, "fastfetch/config.jsonc"); bool success = parseJsoncFile(data, dir->chars, YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS); ffStrbufSubstrBefore(dir, dirLength); - if (success) return; + if (success) { + return; + } ffStrbufAppendS(dir, "fastfetch/config.json5"); success = parseJsoncFile(data, dir->chars, YYJSON_READ_JSON5); ffStrbufSubstrBefore(dir, dirLength); - if (success) return; + if (success) { + return; + } } } } -static void parseArguments(FFdata* data, int argc, char** argv, void (*parser)(FFdata* data, char* key, char* value)) -{ - for(int i = 1; i < argc; i++) - { +static void parseArguments(FFdata* data, int argc, char** argv, void (*parser)(FFdata* data, char* key, char* value)) { + for (int i = 1; i < argc; i++) { const char* key = argv[i]; - if(*key == '\0') + if (*key == '\0') { continue; // has been handled by parseCommand + } - if(*key != '-') - { + if (*key != '-') { fprintf(stderr, "Error: invalid option: %s. An option must start with `-`\n", key); exit(400); } - if(i == argc - 1 || ( - argv[i + 1][0] == '-' && - argv[i + 1][1] != '\0' && // `-` is used as an alias for `/dev/stdin` - !ffStrEqualsIgnCase(argv[i], "--separator-string") // Separator string can start with a - - )) { + if (i == argc - 1 || (argv[i + 1][0] == '-' && argv[i + 1][1] != '\0' && // `-` is used as an alias for `/dev/stdin` + !ffStrEqualsIgnCase(argv[i], "--separator-string") // Separator string can start with a - + )) { parser(data, argv[i], NULL); - } - else - { + } else { parser(data, argv[i], argv[i + 1]); ++i; } } } -static void run(FFdata* data) -{ +static void run(FFdata* data) { const bool useJsonConfig = data->structure.length == 0 && data->configDoc; - if (useJsonConfig) + if (useJsonConfig) { ffPrintJsonConfig(data, true /* prepare */); - else - { - //If we don't have a custom structure, use the default one - if(data->structure.length == 0) + } else { + // If we don't have a custom structure, use the default one + if (data->structure.length == 0) { ffStrbufAppendS(&data->structure, FASTFETCH_DATATEXT_STRUCTURE); // Cannot use `ffStrbufSetStatic` here because we will modify the string + } ffPrepareCommandOption(data); } ffStart(); - if (!data->resultDoc) + if (!data->resultDoc) { ffLogoPrint(); + } - #if defined(_WIN32) - if (!instance.config.display.noBuffer) fflush(stdout); - #endif +#if defined(_WIN32) + if (!instance.config.display.noBuffer) { + fflush(stdout); + } +#endif - while (true) - { - if (useJsonConfig) + while (true) { + if (useJsonConfig) { ffPrintJsonConfig(data, false); - else + } else { ffPrintCommandOption(data); + } - if (instance.state.dynamicInterval > 0) - { + if (instance.state.dynamicInterval > 0) { fflush(stdout); ffTimeSleep(instance.state.dynamicInterval); fputs("\e[H", stdout); - } - else + } else { break; + } - if (useJsonConfig) + if (useJsonConfig) { ffPrintJsonConfig(data, true /* prepare */); - else + } else { ffPrepareCommandOption(data); + } } - if (data->resultDoc) + if (data->resultDoc) { yyjson_mut_write_fp(stdout, data->resultDoc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, NULL, NULL); - else - { - if (instance.config.logo.printRemaining) + } else { + if (instance.config.logo.printRemaining) { ffLogoPrintRemaining(); + } ffFinish(); } } -static void writeConfigFile(FFdata* data) -{ +static void writeConfigFile(FFdata* data) { const FFstrbuf* filename = &data->genConfigPath; yyjson_mut_doc* doc = data->resultDoc; @@ -833,45 +789,39 @@ static void writeConfigFile(FFdata* data) yyjson_mut_doc_set_root(doc, root); yyjson_mut_obj_add_str(doc, root, "$schema", "https://github.com/fastfetch-cli/fastfetch/raw/master/doc/json_schema.json"); - if (data->docType == FF_RESULT_DOC_TYPE_CONFIG_FULL) - { + if (data->docType == FF_RESULT_DOC_TYPE_CONFIG_FULL) { ffOptionsGenerateLogoJsonConfig(data, &instance.config.logo); ffOptionsGenerateDisplayJsonConfig(data, &instance.config.display); ffOptionsGenerateGeneralJsonConfig(data, &instance.config.general); } ffMigrateCommandOptionToJsonc(data); - if (ffStrbufEqualS(filename, "-")) + if (ffStrbufEqualS(filename, "-")) { yyjson_mut_write_fp(stdout, doc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, NULL, NULL); - else - { + } else { size_t len; FF_AUTO_FREE const char* str = yyjson_mut_write(doc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, &len); - if (!str) - { + if (!str) { printf("Error: failed to generate config file\n"); exit(1); } - if (ffWriteFileData(filename->chars, len, str)) - { + if (ffWriteFileData(filename->chars, len, str)) { printf("✓ Configuration file generated: `%s`\n" "* Tip: Use a JSON schema-aware editor for better editing experience\n" - "* Documentation: https://github.com/fastfetch-cli/fastfetch/wiki/Configuration\n", filename->chars); - } - else - { + "* Documentation: https://github.com/fastfetch-cli/fastfetch/wiki/Configuration\n", + filename->chars); + } else { printf("Error: failed to write file in `%s`\n", filename->chars); exit(1); } } } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { ffInitInstance(); atexit(ffDestroyInstance); - //Data stores things only needed for the configuration of fastfetch + // Data stores things only needed for the configuration of fastfetch FFdata data = { .structure = ffStrbufCreate(), .structureDisabled = ffStrbufCreate(), @@ -879,20 +829,21 @@ int main(int argc, char** argv) }; parseArguments(&data, argc, argv, parseCommand); - if(instance.state.dynamicInterval && data.resultDoc) - { + if (instance.state.dynamicInterval && data.resultDoc) { fprintf(stderr, "Error: --dynamic-interval cannot be used with --json\n"); exit(400); } - if(!data.configLoaded && !getenv("NO_CONFIG")) + if (!data.configLoaded && !getenv("NO_CONFIG")) { parseConfigFiles(&data); + } parseArguments(&data, argc, argv, (void*) parseOption); - if (__builtin_expect(data.genConfigPath.length == 0, true)) + if (__builtin_expect(data.genConfigPath.length == 0, true)) { run(&data); - else + } else { writeConfigFile(&data); + } ffStrbufDestroy(&data.structure); ffStrbufDestroy(&data.structureDisabled); diff --git a/src/fastfetch.h b/src/fastfetch.h index 3b09b7e4d..91609c7b5 100644 --- a/src/fastfetch.h +++ b/src/fastfetch.h @@ -6,7 +6,7 @@ #include #ifdef _MSC_VER - #define __attribute__(x) +# define __attribute__(x) #endif #include "common/arrayUtils.h" @@ -19,16 +19,13 @@ #include "options/display.h" #include "options/general.h" - -typedef struct FFconfig -{ +typedef struct FFconfig { FFOptionsLogo logo; FFOptionsDisplay display; FFOptionsGeneral general; } FFconfig; -typedef struct FFstate -{ +typedef struct FFstate { uint32_t logoWidth; uint32_t logoHeight; uint32_t keysHeight; @@ -38,8 +35,7 @@ typedef struct FFstate FFPlatform platform; } FFstate; -typedef struct FFinstance -{ +typedef struct FFinstance { FFconfig config; FFstate state; } FFinstance; diff --git a/src/flashfetch.c b/src/flashfetch.c index 736295e80..75ffe7cbd 100644 --- a/src/flashfetch.c +++ b/src/flashfetch.c @@ -4,13 +4,12 @@ #include "logo/logo.h" #include "modules/modules.h" -#define MODULE_OPTION(name) \ +#define MODULE_OPTION(name) \ __attribute__((cleanup(ffDestroy##name##Options))) FF##name##Options options; \ ffInit##name##Options(&options); // A dirty replicate of neofetch; demonstration only. -int main(void) -{ +int main(void) { ffInitInstance(); // Init everything // Modify global config here if needed diff --git a/src/logo/builtin.c b/src/logo/builtin.c index 5315fdd45..7a53a49d1 100644 --- a/src/logo/builtin.c +++ b/src/logo/builtin.c @@ -164,37 +164,25 @@ static const FFlogo A[] = { .colorTitle = FF_COLOR_FG_YELLOW, }, // Amazon - { - .names = {"Amazon"}, - .lines = FASTFETCH_DATATEXT_LOGO_AMAZON, - .colors = { - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_WHITE, - } - }, + {.names = {"Amazon"}, .lines = FASTFETCH_DATATEXT_LOGO_AMAZON, .colors = { + FF_COLOR_FG_YELLOW, + FF_COLOR_FG_WHITE, + }}, // AmazonLinux - { - .names = {"Amazon Linux", "amzn"}, - .lines = FASTFETCH_DATATEXT_LOGO_AMAZON_LINUX, - .colors = { - FF_COLOR_FG_WHITE, - FF_COLOR_FG_256 "178", - } - }, + {.names = {"Amazon Linux", "amzn"}, .lines = FASTFETCH_DATATEXT_LOGO_AMAZON_LINUX, .colors = { + FF_COLOR_FG_WHITE, + FF_COLOR_FG_256 "178", + }}, // Amiga - { - .names = {"Amiga"}, - .lines = FASTFETCH_DATATEXT_LOGO_AMIGA, - .colors = { - FF_COLOR_FG_RED, - FF_COLOR_FG_LIGHT_RED, - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_BLUE, - FF_COLOR_FG_CYAN, - FF_COLOR_FG_LIGHT_YELLOW, - FF_COLOR_FG_GREEN, - } - }, + {.names = {"Amiga"}, .lines = FASTFETCH_DATATEXT_LOGO_AMIGA, .colors = { + FF_COLOR_FG_RED, + FF_COLOR_FG_LIGHT_RED, + FF_COLOR_FG_YELLOW, + FF_COLOR_FG_BLUE, + FF_COLOR_FG_CYAN, + FF_COLOR_FG_LIGHT_YELLOW, + FF_COLOR_FG_GREEN, + }}, // AmogOS { .names = {"AmogOS"}, @@ -649,12 +637,7 @@ static const FFlogo A[] = { { .names = {"AsteroidOS"}, .lines = FASTFETCH_DATATEXT_LOGO_ASTEROIDOS, - .colors = { - FF_COLOR_FG_256 "160", - FF_COLOR_FG_256 "208", - FF_COLOR_FG_256 "202", - FF_COLOR_FG_256 "214" - }, + .colors = {FF_COLOR_FG_256 "160", FF_COLOR_FG_256 "208", FF_COLOR_FG_256 "202", FF_COLOR_FG_256 "214"}, .colorKeys = FF_COLOR_FG_256 "160", .colorTitle = FF_COLOR_FG_256 "208", }, @@ -734,14 +717,10 @@ static const FFlogo A[] = { }, }, // Azos - { - .names = {"Azos"}, - .lines = FASTFETCH_DATATEXT_LOGO_AZOS, - .colors = { - FF_COLOR_FG_CYAN, - FF_COLOR_FG_RED, - } - }, + {.names = {"Azos"}, .lines = FASTFETCH_DATATEXT_LOGO_AZOS, .colors = { + FF_COLOR_FG_CYAN, + FF_COLOR_FG_RED, + }}, // LAST {}, }; @@ -752,10 +731,10 @@ static const FFlogo B[] = { .names = {"bedrock"}, .lines = FASTFETCH_DATATEXT_LOGO_BEDROCK, .colors = { - FF_COLOR_FG_LIGHT_BLACK, //grey + FF_COLOR_FG_LIGHT_BLACK, // grey FF_COLOR_FG_DEFAULT, }, - .colorKeys = FF_COLOR_FG_LIGHT_BLACK, //grey + .colorKeys = FF_COLOR_FG_LIGHT_BLACK, // grey .colorTitle = FF_COLOR_FG_DEFAULT, }, // BedrockSmall @@ -764,10 +743,10 @@ static const FFlogo B[] = { .lines = FASTFETCH_DATATEXT_LOGO_BEDROCK_SMALL, .type = FF_LOGO_LINE_TYPE_SMALL_BIT, .colors = { - FF_COLOR_FG_LIGHT_BLACK, //grey + FF_COLOR_FG_LIGHT_BLACK, // grey FF_COLOR_FG_DEFAULT, }, - .colorKeys = FF_COLOR_FG_LIGHT_BLACK, //grey + .colorKeys = FF_COLOR_FG_LIGHT_BLACK, // grey .colorTitle = FF_COLOR_FG_DEFAULT, }, // BigLinux @@ -887,7 +866,7 @@ static const FFlogo B[] = { .names = {"Bredos"}, .lines = FASTFETCH_DATATEXT_LOGO_BREDOS, .colors = { - FF_COLOR_FG_RGB "198;151;66", //grey + FF_COLOR_FG_RGB "198;151;66", // grey }, .colorKeys = FF_COLOR_FG_RGB "198;151;66", .colorTitle = FF_COLOR_FG_RGB "198;151;66", @@ -1049,13 +1028,7 @@ static const FFlogo C[] = { { .names = {"Cereus", "Cereus Linux"}, .lines = FASTFETCH_DATATEXT_LOGO_CEREUS, - .colors = { - FF_COLOR_FG_256 "173", - FF_COLOR_FG_256 "108", - FF_COLOR_FG_256 "71", - FF_COLOR_FG_256 "151", - FF_COLOR_FG_256 "72" - }, + .colors = {FF_COLOR_FG_256 "173", FF_COLOR_FG_256 "108", FF_COLOR_FG_256 "71", FF_COLOR_FG_256 "151", FF_COLOR_FG_256 "72"}, .colorKeys = FF_COLOR_FG_256 "108", .colorTitle = FF_COLOR_MODE_BOLD FF_COLOR_FG_WHITE, }, @@ -1073,10 +1046,7 @@ static const FFlogo C[] = { { .names = {"ChaletOS"}, .lines = FASTFETCH_DATATEXT_LOGO_CHALETOS, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_BLUE, FF_COLOR_FG_WHITE}, .colorKeys = FF_COLOR_FG_BLUE, .colorTitle = FF_COLOR_FG_DEFAULT, }, @@ -1199,19 +1169,13 @@ static const FFlogo C[] = { { .names = {"Codex Linux"}, .lines = FASTFETCH_DATATEXT_LOGO_CODEX, - .colors = { - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_WHITE}, }, // Condres { .names = {"Condres"}, .lines = FASTFETCH_DATATEXT_LOGO_CONDRES, - .colors = { - FF_COLOR_FG_GREEN, - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_CYAN - }, + .colors = {FF_COLOR_FG_GREEN, FF_COLOR_FG_YELLOW, FF_COLOR_FG_CYAN}, .colorKeys = FF_COLOR_FG_GREEN, .colorTitle = FF_COLOR_FG_YELLOW, }, @@ -1231,11 +1195,7 @@ static const FFlogo C[] = { { .names = {"common-torizon"}, .lines = FASTFETCH_DATATEXT_LOGO_TORIZONCORE, - .colors = { - FF_COLOR_FG_LIGHT_WHITE, - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_BLUE - }, + .colors = {FF_COLOR_FG_LIGHT_WHITE, FF_COLOR_FG_YELLOW, FF_COLOR_FG_BLUE}, }, // Cosmic DE { @@ -1628,10 +1588,7 @@ static const FFlogo E[] = { { .names = {"Endless"}, .lines = FASTFETCH_DATATEXT_LOGO_ENDLESS, - .colors = { - FF_COLOR_FG_RED, - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_RED, FF_COLOR_FG_WHITE}, .colorKeys = FF_COLOR_FG_RED, .colorTitle = FF_COLOR_FG_DEFAULT, }, @@ -1699,11 +1656,11 @@ static const FFlogo E[] = { .names = {"eweOS"}, .lines = FASTFETCH_DATATEXT_LOGO_EWEOS, .colors = { - FF_COLOR_FG_WHITE, - FF_COLOR_FG_LIGHT_YELLOW, - FF_COLOR_FG_LIGHT_RED, - FF_COLOR_FG_LIGHT_BLACK, - FF_COLOR_FG_RED, + FF_COLOR_FG_WHITE, + FF_COLOR_FG_LIGHT_YELLOW, + FF_COLOR_FG_LIGHT_RED, + FF_COLOR_FG_LIGHT_BLACK, + FF_COLOR_FG_RED, }, }, // Exherbo @@ -1932,9 +1889,7 @@ static const FFlogo F[] = { { .names = {"FreeMiNT"}, .lines = FASTFETCH_DATATEXT_LOGO_FREEMINT, - .colors = { - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_WHITE}, .colorKeys = FF_COLOR_FG_DEFAULT, .colorTitle = FF_COLOR_FG_DEFAULT, }, @@ -2216,11 +2171,7 @@ static const FFlogo H[] = { { .names = {"HamoniKR"}, .lines = FASTFETCH_DATATEXT_LOGO_HAMONIKR, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_WHITE, - FF_COLOR_FG_256 "99" - }, + .colors = {FF_COLOR_FG_BLUE, FF_COLOR_FG_WHITE, FF_COLOR_FG_256 "99"}, .colorKeys = FF_COLOR_FG_BLUE, .colorTitle = FF_COLOR_FG_DEFAULT, }, @@ -2495,23 +2446,12 @@ static const FFlogo K[] = { .colorTitle = FF_COLOR_FG_DEFAULT, }, // KernelOS - { - .names = {"KernelOS"}, - .lines = FASTFETCH_DATATEXT_LOGO_KERNELOS, - .colors = { - FF_COLOR_FG_RED, - FF_COLOR_FG_MAGENTA, - } - }, + {.names = {"KernelOS"}, .lines = FASTFETCH_DATATEXT_LOGO_KERNELOS, .colors = { + FF_COLOR_FG_RED, + FF_COLOR_FG_MAGENTA, + }}, // KDELinux - { - .names = {"kdelinux", "kde-linux"}, - .lines = FASTFETCH_DATATEXT_LOGO_KDELINUX, - .colors = { - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_WHITE - } - }, + {.names = {"kdelinux", "kde-linux"}, .lines = FASTFETCH_DATATEXT_LOGO_KDELINUX, .colors = {FF_COLOR_FG_YELLOW, FF_COLOR_FG_WHITE}}, // KDE Neon { .names = {"KDE Neon"}, // Distro ID is "neon"; Distro name is "KDE Neon" @@ -2616,12 +2556,7 @@ static const FFlogo K[] = { { .names = {"Kylin", "kylin"}, .lines = FASTFETCH_DATATEXT_LOGO_KYLIN, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_CYAN, - FF_COLOR_FG_WHITE, - FF_COLOR_FG_LIGHT_BLACK - }, + .colors = {FF_COLOR_FG_BLUE, FF_COLOR_FG_CYAN, FF_COLOR_FG_WHITE, FF_COLOR_FG_LIGHT_BLACK}, .colorKeys = FF_COLOR_FG_BLUE, .colorTitle = FF_COLOR_FG_BLUE, }, @@ -3491,15 +3426,11 @@ static const FFlogo O[] = { }, }, // OmniOS - { - .names = {"OmniOS"}, - .lines = FASTFETCH_DATATEXT_LOGO_OMNIOS, - .colors = { - FF_COLOR_FG_WHITE, - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_LIGHT_BLACK, - } - }, + {.names = {"OmniOS"}, .lines = FASTFETCH_DATATEXT_LOGO_OMNIOS, .colors = { + FF_COLOR_FG_WHITE, + FF_COLOR_FG_YELLOW, + FF_COLOR_FG_LIGHT_BLACK, + }}, // OpenKylin { .names = {"openkylin", "open-kylin"}, @@ -3751,14 +3682,10 @@ static const FFlogo O[] = { }, }, // OS/2 Warp - { - .names = {"OS2Warp"}, - .lines = FASTFETCH_DATATEXT_LOGO_OS2WARP, - .colors = { - FF_COLOR_FG_LIGHT_WHITE, - FF_COLOR_FG_LIGHT_BLUE, - } - }, + {.names = {"OS2Warp"}, .lines = FASTFETCH_DATATEXT_LOGO_OS2WARP, .colors = { + FF_COLOR_FG_LIGHT_WHITE, + FF_COLOR_FG_LIGHT_BLUE, + }}, // OS_Elbrus { .names = {"OS Elbrus"}, @@ -3953,9 +3880,7 @@ static const FFlogo P[] = { { .names = {"Peropesis", "Peropesis Linux"}, .lines = FASTFETCH_DATATEXT_LOGO_PEROPESIS, - .colors = { - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_WHITE}, }, // PhyOS { @@ -3987,12 +3912,7 @@ static const FFlogo P[] = { { .names = {"PNM Linux"}, .lines = FASTFETCH_DATATEXT_LOGO_PNM_LINUX, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_RED, - FF_COLOR_FG_WHITE, - FF_COLOR_FG_256 "202" - }, + .colors = {FF_COLOR_FG_BLUE, FF_COLOR_FG_RED, FF_COLOR_FG_WHITE, FF_COLOR_FG_256 "202"}, }, // Pop { @@ -4048,10 +3968,7 @@ static const FFlogo P[] = { { .names = {"Proxmox", "pve"}, .lines = FASTFETCH_DATATEXT_LOGO_PROXMOX, - .colors = { - FF_COLOR_FG_WHITE, - FF_COLOR_FG_256 "202" - }, + .colors = {FF_COLOR_FG_WHITE, FF_COLOR_FG_256 "202"}, .colorKeys = FF_COLOR_FG_DEFAULT, .colorTitle = FF_COLOR_FG_256 "202", }, @@ -4575,14 +4492,10 @@ static const FFlogo S[] = { }, }, // Siduction - { - .names = {"Siduction"}, - .lines = FASTFETCH_DATATEXT_LOGO_SIDUCTION, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_WHITE, - } - }, + {.names = {"Siduction"}, .lines = FASTFETCH_DATATEXT_LOGO_SIDUCTION, .colors = { + FF_COLOR_FG_BLUE, + FF_COLOR_FG_WHITE, + }}, // SkiffOS { .names = {"SkiffOS"}, @@ -4593,24 +4506,15 @@ static const FFlogo S[] = { }, }, // SleeperOS - { - .names = {"SleeperOS"}, - .lines = FASTFETCH_DATATEXT_LOGO_SLEEPEROS, - .colors = { - FF_COLOR_FG_CYAN, - FF_COLOR_FG_WHITE, - } - }, + {.names = {"SleeperOS"}, .lines = FASTFETCH_DATATEXT_LOGO_SLEEPEROS, .colors = { + FF_COLOR_FG_CYAN, + FF_COLOR_FG_WHITE, + }}, // SleeperOS - { - .names = {"SleeperOS_small"}, - .type = FF_LOGO_LINE_TYPE_SMALL_BIT, - .lines = FASTFETCH_DATATEXT_LOGO_SLEEPEROS_SMALL, - .colors = { - FF_COLOR_FG_CYAN, - FF_COLOR_FG_WHITE, - } - }, + {.names = {"SleeperOS_small"}, .type = FF_LOGO_LINE_TYPE_SMALL_BIT, .lines = FASTFETCH_DATATEXT_LOGO_SLEEPEROS_SMALL, .colors = { + FF_COLOR_FG_CYAN, + FF_COLOR_FG_WHITE, + }}, // Slitaz { .names = {"Slitaz"}, @@ -4733,10 +4637,7 @@ static const FFlogo S[] = { { .names = {"Sparky"}, .lines = FASTFETCH_DATATEXT_LOGO_SPARKY, - .colors = { - FF_COLOR_FG_RED, - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_RED, FF_COLOR_FG_WHITE}, }, // Star { @@ -4771,10 +4672,7 @@ static const FFlogo S[] = { { .names = {"SteamDeck"}, .lines = FASTFETCH_DATATEXT_LOGO_STEAMDECK, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_BLUE, FF_COLOR_FG_WHITE}, .colorKeys = FF_COLOR_FG_BLUE, .colorTitle = FF_COLOR_FG_BLUE, }, @@ -4782,10 +4680,7 @@ static const FFlogo S[] = { { .names = {"SteamDeck_small"}, .lines = FASTFETCH_DATATEXT_LOGO_STEAMDECK_SMALL, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_BLUE, FF_COLOR_FG_WHITE}, .colorKeys = FF_COLOR_FG_BLUE, .colorTitle = FF_COLOR_FG_BLUE, }, @@ -4793,10 +4688,7 @@ static const FFlogo S[] = { { .names = {"SteamDeckOled"}, .lines = FASTFETCH_DATATEXT_LOGO_STEAMDECK, - .colors = { - FF_COLOR_FG_RED, - FF_COLOR_FG_WHITE - }, + .colors = {FF_COLOR_FG_RED, FF_COLOR_FG_WHITE}, .colorKeys = FF_COLOR_FG_RED, .colorTitle = FF_COLOR_FG_RED, }, @@ -4924,11 +4816,7 @@ static const FFlogo T[] = { { .names = {"Torizon OS", "TorizonCore"}, .lines = FASTFETCH_DATATEXT_LOGO_TORIZONCORE, - .colors = { - FF_COLOR_FG_LIGHT_WHITE, - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_BLUE - }, + .colors = {FF_COLOR_FG_LIGHT_WHITE, FF_COLOR_FG_YELLOW, FF_COLOR_FG_BLUE}, }, // Trisquel { @@ -5217,17 +5105,13 @@ static const FFlogo U[] = { .colorTitle = FF_COLOR_FG_BLUE, }, // UrukOS - { - .names = {"UrukOS"}, - .lines = FASTFETCH_DATATEXT_LOGO_URUKOS, - .colors = { - FF_COLOR_FG_LIGHT_BLUE, - FF_COLOR_FG_LIGHT_BLUE, - FF_COLOR_FG_WHITE, - FF_COLOR_FG_LIGHT_BLUE, - FF_COLOR_FG_BLUE, - } - }, + {.names = {"UrukOS"}, .lines = FASTFETCH_DATATEXT_LOGO_URUKOS, .colors = { + FF_COLOR_FG_LIGHT_BLUE, + FF_COLOR_FG_LIGHT_BLUE, + FF_COLOR_FG_WHITE, + FF_COLOR_FG_LIGHT_BLUE, + FF_COLOR_FG_BLUE, + }}, // Uwuntu { .names = {"uwuntu"}, @@ -5499,8 +5383,7 @@ static const FFlogo X[] = { FF_COLOR_FG_BLACK, FF_COLOR_FG_BLUE, FF_COLOR_FG_YELLOW, - } - }, + }}, // Xenia { .names = {"Xenia"}, @@ -5513,29 +5396,20 @@ static const FFlogo X[] = { .colorTitle = FF_COLOR_FG_RED, }, // Xenia_old - { - .names = {"Xenia_old"}, - .lines = FASTFETCH_DATATEXT_LOGO_XENIA_OLD, - .type = FF_LOGO_LINE_TYPE_ALTER_BIT, - .colors = { - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_GREEN, - FF_COLOR_FG_RED, - } - }, - //XeroArch - { - .names = {"XeroArch"}, - .lines = FASTFETCH_DATATEXT_LOGO_XEROARCH, - .colors = { - FF_COLOR_FG_256 "50", - FF_COLOR_FG_256 "14", - FF_COLOR_FG_256 "50", - FF_COLOR_FG_256 "93", - FF_COLOR_FG_256 "16", - FF_COLOR_FG_256 "15", - } - }, + {.names = {"Xenia_old"}, .lines = FASTFETCH_DATATEXT_LOGO_XENIA_OLD, .type = FF_LOGO_LINE_TYPE_ALTER_BIT, .colors = { + FF_COLOR_FG_YELLOW, + FF_COLOR_FG_GREEN, + FF_COLOR_FG_RED, + }}, + // XeroArch + {.names = {"XeroArch"}, .lines = FASTFETCH_DATATEXT_LOGO_XEROARCH, .colors = { + FF_COLOR_FG_256 "50", + FF_COLOR_FG_256 "14", + FF_COLOR_FG_256 "50", + FF_COLOR_FG_256 "93", + FF_COLOR_FG_256 "16", + FF_COLOR_FG_256 "15", + }}, // Xferience { .names = {"Xferience"}, @@ -5554,25 +5428,17 @@ static const FFlogo X[] = { FF_COLOR_FG_DEFAULT, }, }, - //Xray_OS - { - .names = {"Xray_OS"}, - .lines = FASTFETCH_DATATEXT_LOGO_XRAY_OS, - .colors = { - FF_COLOR_FG_256 "15", - FF_COLOR_FG_256 "14", - FF_COLOR_FG_256 "16", - } - }, + // Xray_OS + {.names = {"Xray_OS"}, .lines = FASTFETCH_DATATEXT_LOGO_XRAY_OS, .colors = { + FF_COLOR_FG_256 "15", + FF_COLOR_FG_256 "14", + FF_COLOR_FG_256 "16", + }}, // Xinux - { - .names = {"Xinux"}, - .lines = FASTFETCH_DATATEXT_LOGO_XINUX, - .colors = { - FF_COLOR_FG_BLUE, - FF_COLOR_FG_CYAN, - } - }, + {.names = {"Xinux"}, .lines = FASTFETCH_DATATEXT_LOGO_XINUX, .colors = { + FF_COLOR_FG_BLUE, + FF_COLOR_FG_CYAN, + }}, // LAST {}, }; @@ -5612,7 +5478,7 @@ static const FFlogo Z[] = { }, // Zraxyl { - .names = {"Zraxyl" }, + .names = {"Zraxyl"}, .lines = FASTFETCH_DATATEXT_LOGO_ZRAXYL, .colors = { FF_COLOR_FG_BLUE, @@ -5625,5 +5491,30 @@ static const FFlogo Z[] = { }; const FFlogo* ffLogoBuiltins[] = { - A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, }; diff --git a/src/logo/image/im6.c b/src/logo/image/im6.c index 4893eeaad..f7559a479 100644 --- a/src/logo/image/im6.c +++ b/src/logo/image/im6.c @@ -1,26 +1,24 @@ #ifdef FF_HAVE_IMAGEMAGICK6 -#include "image.h" -#include "common/library.h" +# include "image.h" +# include "common/library.h" -#include +# include static FF_LIBRARY_SYMBOL(ResizeImage) -static void* logoResize(const void* image, size_t width, size_t height, void* exceptionInfo) -{ + static void* logoResize(const void* image, size_t width, size_t height, void* exceptionInfo) { return ffResizeImage(image, width, height, UndefinedFilter, 1.0, exceptionInfo); } -FFLogoImageResult ffLogoPrintImageIM6(FFLogoRequestData* requestData) -{ +FFLogoImageResult ffLogoPrintImageIM6(FFLogoRequestData* requestData) { FF_LIBRARY_LOAD(imageMagick, FF_LOGO_IMAGE_RESULT_INIT_ERROR, "libMagickCore-6.Q16HDRI" FF_LIBRARY_EXTENSION, 8, "libMagickCore-6.Q16" FF_LIBRARY_EXTENSION, 8) FF_LIBRARY_LOAD_SYMBOL_ADDRESS(imageMagick, ffResizeImage, ResizeImage, FF_LOGO_IMAGE_RESULT_INIT_ERROR) FFLogoImageResult result = ffLogoPrintImageImpl(requestData, &(FFIMData) { - .resizeFunc = logoResize, - .library = imageMagick, - }); + .resizeFunc = logoResize, + .library = imageMagick, + }); imageMagick = NULL; // leak imageMagick to prevent fastfetch from crashing #552 return result; diff --git a/src/logo/image/im7.c b/src/logo/image/im7.c index b33c0ccf9..4eae9dd99 100644 --- a/src/logo/image/im7.c +++ b/src/logo/image/im7.c @@ -1,30 +1,25 @@ #ifdef FF_HAVE_IMAGEMAGICK7 -#include "image.h" -#include "common/library.h" +# include "image.h" +# include "common/library.h" -#include +# include static FF_LIBRARY_SYMBOL(ResizeImage) -static void* logoResize(const void* image, size_t width, size_t height, void* exceptionInfo) -{ + static void* logoResize(const void* image, size_t width, size_t height, void* exceptionInfo) { return ffResizeImage(image, width, height, UndefinedFilter, exceptionInfo); } -FFLogoImageResult ffLogoPrintImageIM7(FFLogoRequestData* requestData) -{ - FF_LIBRARY_LOAD(imageMagick, FF_LOGO_IMAGE_RESULT_INIT_ERROR, - "libMagickCore-7.Q16HDRI" FF_LIBRARY_EXTENSION, 11, - "libMagickCore-7.Q16" FF_LIBRARY_EXTENSION, 11, - "libMagickCore-7.Q16HDRI-10" FF_LIBRARY_EXTENSION, -1 // Required for Windows +FFLogoImageResult ffLogoPrintImageIM7(FFLogoRequestData* requestData) { + FF_LIBRARY_LOAD(imageMagick, FF_LOGO_IMAGE_RESULT_INIT_ERROR, "libMagickCore-7.Q16HDRI" FF_LIBRARY_EXTENSION, 11, "libMagickCore-7.Q16" FF_LIBRARY_EXTENSION, 11, "libMagickCore-7.Q16HDRI-10" FF_LIBRARY_EXTENSION, -1 // Required for Windows ) FF_LIBRARY_LOAD_SYMBOL_ADDRESS(imageMagick, ffResizeImage, ResizeImage, FF_LOGO_IMAGE_RESULT_INIT_ERROR) FFLogoImageResult result = ffLogoPrintImageImpl(requestData, &(FFIMData) { - .resizeFunc = logoResize, - .library = imageMagick, - }); + .resizeFunc = logoResize, + .library = imageMagick, + }); imageMagick = NULL; // leak imageMagick to prevent fastfetch from crashing #552 return result; diff --git a/src/logo/image/image.c b/src/logo/image/image.c index 17b4e1ed6..b5da3e077 100644 --- a/src/logo/image/image.c +++ b/src/logo/image/image.c @@ -10,23 +10,22 @@ #include #ifdef __APPLE__ - #include +# include #elif _WIN32 - #include +# include #elif __linux__ - #include +# include #elif __sun - #include +# include #endif -static bool printImageIterm(bool printError) -{ +static bool printImageIterm(bool printError) { const FFOptionsLogo* options = &instance.config.logo; FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if(!ffAppendFileBuffer(options->source.chars, &buf)) - { - if (printError) + if (!ffAppendFileBuffer(options->source.chars, &buf)) { + if (printError) { fputs("Logo (iterm): Failed to load image file\n", stderr); + } return false; } @@ -41,95 +40,78 @@ static bool printImageIterm(bool printError) FF_STRBUF_AUTO_DESTROY base64 = ffBase64EncodeStrbuf(&buf); ffStrbufClear(&buf); - if (!options->width || !options->height) - { - if (options->position == FF_LOGO_POSITION_LEFT) - { - ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", - (unsigned) options->paddingTop + 1, - (unsigned) options->paddingLeft + 1 - ); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + if (!options->width || !options->height) { + if (options->position == FF_LOGO_POSITION_LEFT) { + ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", (unsigned) options->paddingTop + 1, (unsigned) options->paddingLeft + 1); + } else if (options->position == FF_LOGO_POSITION_TOP) { ffStrbufAppendNC(&buf, options->paddingTop, '\n'); ffStrbufAppendNC(&buf, options->paddingLeft, ' '); - } - else if (options->position == FF_LOGO_POSITION_RIGHT) - { - if (!options->width) - { - if (printError) + } else if (options->position == FF_LOGO_POSITION_RIGHT) { + if (!options->width) { + if (printError) { fputs("Logo (iterm): Must set logo width when using position right\n", stderr); + } return false; } ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;9999999H\e[%uD", (unsigned) options->paddingTop + 1, (unsigned) options->paddingRight + options->width); } - if (inTmux) + if (inTmux) { ffStrbufAppendS(&buf, "\ePtmux;\e"); + } - if (options->width) + if (options->width) { ffStrbufAppendF(&buf, "\e]1337;File=inline=1;width=%u:%s\a", (unsigned) options->width, base64.chars); - else + } else { ffStrbufAppendF(&buf, "\e]1337;File=inline=1:%s\a", base64.chars); - if (inTmux) + } + if (inTmux) { ffStrbufAppendS(&buf, "\e\\"); + } ffWriteFDBuffer(FFUnixFD2NativeFD(STDOUT_FILENO), &buf); - if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) - { + if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) { uint16_t X = 0, Y = 0; const char* error = ffGetTerminalResponse("\e[6n", 2, "%*[^0-9]%hu;%huR", &Y, &X); - if (error) - { + if (error) { fprintf(stderr, "\nLogo (iterm): fail to query cursor position: %s\n", error); return true; // We already printed image logo, don't print ascii logo then } - if (X < options->paddingLeft + options->width) + if (X < options->paddingLeft + options->width) { X = (uint16_t) (options->paddingLeft + options->width); - if (options->position == FF_LOGO_POSITION_LEFT) + } + if (options->position == FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = X + options->paddingRight - 1; + } instance.state.logoHeight = Y; fputs("\e[H", stdout); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffPrintCharTimes('\n', options->paddingRight); } - } - else - { + } else { ffStrbufAppendNC(&buf, options->paddingTop, '\n'); - if (options->position == FF_LOGO_POSITION_RIGHT) + if (options->position == FF_LOGO_POSITION_RIGHT) { ffStrbufAppendF(&buf, "\e[9999999C\e[%uD", (unsigned) options->paddingRight + options->width); - else if (options->paddingLeft) + } else if (options->paddingLeft) { ffStrbufAppendF(&buf, "\e[%uC", (unsigned) options->paddingLeft); - if (inTmux) + } + if (inTmux) { ffStrbufAppendS(&buf, "\ePtmux;\e"); - ffStrbufAppendF(&buf, "\e]1337;File=inline=1;width=%u;height=%u;preserveAspectRatio=%u:%s\a", - (unsigned) options->width, - (unsigned) options->height, - (unsigned) options->preserveAspectRatio, - base64.chars - ); - if (inTmux) + } + ffStrbufAppendF(&buf, "\e]1337;File=inline=1;width=%u;height=%u;preserveAspectRatio=%u:%s\a", (unsigned) options->width, (unsigned) options->height, (unsigned) options->preserveAspectRatio, base64.chars); + if (inTmux) { ffStrbufAppendS(&buf, "\e\\"); + } ffStrbufAppendC(&buf, '\n'); - if (options->position == FF_LOGO_POSITION_LEFT) - { + if (options->position == FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = options->width + options->paddingLeft + options->paddingRight; instance.state.logoHeight = options->paddingTop + options->height; ffStrbufAppendF(&buf, "\e[%uA", (unsigned) instance.state.logoHeight); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffStrbufAppendNC(&buf, options->paddingRight, '\n'); - } - else if (options->position == FF_LOGO_POSITION_RIGHT) - { + } else if (options->position == FF_LOGO_POSITION_RIGHT) { instance.state.logoWidth = instance.state.logoHeight = 0; ffStrbufAppendF(&buf, "\e[1G\e[%uA", (unsigned) options->height); } @@ -139,14 +121,13 @@ static bool printImageIterm(bool printError) return true; } -static bool printImageKittyIcat(bool printError) -{ +static bool printImageKittyIcat(bool printError) { const FFOptionsLogo* options = &instance.config.logo; - if (!ffPathExists(options->source.chars, FF_PATHTYPE_FILE)) - { - if (printError) + if (!ffPathExists(options->source.chars, FF_PATHTYPE_FILE)) { + if (printError) { fputs("Logo (kitty-icat): Failed to load image file\n", stderr); + } return false; } @@ -154,31 +135,22 @@ static bool printImageKittyIcat(bool printError) FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (options->position == FF_LOGO_POSITION_LEFT) - { - ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", - (unsigned) options->paddingTop + 1, - (unsigned) options->paddingLeft + 1 - ); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { - if (!options->width) - { + if (options->position == FF_LOGO_POSITION_LEFT) { + ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", (unsigned) options->paddingTop + 1, (unsigned) options->paddingLeft + 1); + } else if (options->position == FF_LOGO_POSITION_TOP) { + if (!options->width) { ffStrbufAppendNC(&buf, options->paddingTop, '\n'); ffStrbufAppendNC(&buf, options->paddingLeft, ' '); - } - else - { - if (printError) + } else { + if (printError) { fputs("Logo (kitty-icat): position top is not supported when logo width is set\n", stderr); + } return false; } - } - else if (options->position == FF_LOGO_POSITION_RIGHT) - { - if (printError) + } else if (options->position == FF_LOGO_POSITION_RIGHT) { + if (printError) { fputs("Logo (kitty-icat): position right is not supported\n", stderr); + } return false; } @@ -186,8 +158,7 @@ static bool printImageKittyIcat(bool printError) const char* error = NULL; - if (options->width) - { + if (options->width) { char place[64]; snprintf(place, ARRAY_SIZE(place), @@ -197,62 +168,58 @@ static bool printImageKittyIcat(bool printError) options->paddingLeft + 1, options->paddingTop + 1); - error = ffProcessAppendStdOut(&buf, (char* []) { - "kitten", - "icat", - "-n", - "--align=center", - place, - "--scale-up", - options->source.chars, - NULL, - }); + error = ffProcessAppendStdOut(&buf, (char*[]) { + "kitten", + "icat", + "-n", + "--align=center", + place, + "--scale-up", + options->source.chars, + NULL, + }); + } else { + error = ffProcessAppendStdOut(&buf, (char*[]) { + "kitten", + "icat", + "-n", + "--align=left", + options->source.chars, + NULL, + }); } - else - { - error = ffProcessAppendStdOut(&buf, (char* []) { - "kitten", - "icat", - "-n", - "--align=left", - options->source.chars, - NULL, - }); - } - if (error) - { - if (printError) + if (error) { + if (printError) { fprintf(stderr, "Logo (kitty-icat): running `kitten icat` failed %s\n", error); + } return false; } - if (buf.length == prevLength) - { - if (printError) + if (buf.length == prevLength) { + if (printError) { fputs("Logo (kitty-icat): `kitten icat` returned empty output\n", stderr); + } return false; } ffWriteFDBuffer(FFUnixFD2NativeFD(STDOUT_FILENO), &buf); - if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) - { + if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) { uint16_t X = 0, Y = 0; const char* error = ffGetTerminalResponse("\e[6n", 2, "%*[^0-9]%hu;%huR", &Y, &X); - if (error) - { + if (error) { fprintf(stderr, "\nLogo (kitty-icat): fail to query cursor position: %s\n", error); return true; // We already printed image logo, don't print ascii logo then } - if (X < options->paddingLeft + options->width) + if (X < options->paddingLeft + options->width) { X = (uint16_t) (options->paddingLeft + options->width); - if (options->position == FF_LOGO_POSITION_LEFT) + } + if (options->position == FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = X + options->paddingRight - 1; + } instance.state.logoHeight = Y; fputs("\e[H", stdout); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffPrintCharTimes('\n', options->paddingRight); } @@ -260,14 +227,13 @@ static bool printImageKittyIcat(bool printError) return true; } -static bool printImageKittyDirect(bool printError) -{ +static bool printImageKittyDirect(bool printError) { const FFOptionsLogo* options = &instance.config.logo; - if (!ffPathExists(options->source.chars, FF_PATHTYPE_FILE)) - { - if (printError) + if (!ffPathExists(options->source.chars, FF_PATHTYPE_FILE)) { + if (printError) { fputs("Logo (kitty-direct): Failed to load image file\n", stderr); + } return false; } @@ -282,102 +248,88 @@ static bool printImageKittyDirect(bool printError) FF_STRBUF_AUTO_DESTROY base64 = ffBase64EncodeStrbuf(&options->source); FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (!options->width || !options->height) - { - if (options->position == FF_LOGO_POSITION_LEFT) - { + if (!options->width || !options->height) { + if (options->position == FF_LOGO_POSITION_LEFT) { // We must clear the entre screen to make sure that terminal buffer won't scroll up - ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", - (unsigned) options->paddingTop + 1, - (unsigned) options->paddingLeft + 1 - ); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", (unsigned) options->paddingTop + 1, (unsigned) options->paddingLeft + 1); + } else if (options->position == FF_LOGO_POSITION_TOP) { ffStrbufAppendNC(&buf, options->paddingTop, '\n'); ffStrbufAppendNC(&buf, options->paddingLeft, ' '); - } - else if (options->position == FF_LOGO_POSITION_RIGHT) - { - if (!options->width) - { - if (printError) + } else if (options->position == FF_LOGO_POSITION_RIGHT) { + if (!options->width) { + if (printError) { fputs("Logo (iterm): Must set logo width when using position right\n", stderr); + } return false; } ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;9999999H\e[%uD", (unsigned) options->paddingTop + 1, (unsigned) options->paddingRight + options->width); } - if (inTmux) + if (inTmux) { ffStrbufAppendS(&buf, "\ePtmux;\e"); - if (options->width) + } + if (options->width) { ffStrbufAppendF(&buf, "\e_Ga=T,f=100,t=f,c=%u;%s", (unsigned) options->width, base64.chars); - else + } else { ffStrbufAppendF(&buf, "\e_Ga=T,f=100,t=f;%s", base64.chars); - if (inTmux) + } + if (inTmux) { ffStrbufAppendC(&buf, '\e'); + } ffStrbufAppendS(&buf, "\e\\"); - if (inTmux) + if (inTmux) { ffStrbufAppendS(&buf, "\e\\"); + } ffWriteFDBuffer(FFUnixFD2NativeFD(STDOUT_FILENO), &buf); - if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) - { + if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) { uint16_t X = 0, Y = 0; const char* error = ffGetTerminalResponse("\e[6n", 2, "%*[^0-9]%hu;%huR", &Y, &X); - if (error) - { - if (printError) + if (error) { + if (printError) { fprintf(stderr, "\nLogo (kitty-direct): fail to query cursor position: %s\n", error); + } return true; // We already printed image logo, don't print ascii logo then } - if (X < options->paddingLeft + options->width) + if (X < options->paddingLeft + options->width) { X = (uint16_t) (options->paddingLeft + options->width); - if (options->position == FF_LOGO_POSITION_LEFT) + } + if (options->position == FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = X + options->paddingRight - 1; + } instance.state.logoHeight = Y; fputs("\e[H", stdout); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffPrintCharTimes('\n', options->paddingRight); } - } - else - { + } else { ffStrbufAppendNC(&buf, options->paddingTop, '\n'); - if (options->position == FF_LOGO_POSITION_RIGHT) + if (options->position == FF_LOGO_POSITION_RIGHT) { ffStrbufAppendF(&buf, "\e[9999999C\e[%uD", (unsigned) options->paddingRight + options->width); - else if (options->paddingLeft) + } else if (options->paddingLeft) { ffStrbufAppendF(&buf, "\e[%uC", (unsigned) options->paddingLeft); + } - if (inTmux) + if (inTmux) { ffStrbufAppendS(&buf, "\ePtmux;\e"); + } - ffStrbufAppendF(&buf, "\e_Ga=T,f=100,t=f,c=%u,r=%u;%s\e\\", - (unsigned) options->width, - (unsigned) options->height, - base64.chars - ); - if (inTmux) + ffStrbufAppendF(&buf, "\e_Ga=T,f=100,t=f,c=%u,r=%u;%s\e\\", (unsigned) options->width, (unsigned) options->height, base64.chars); + if (inTmux) { ffStrbufAppendS(&buf, "\e\\"); + } ffStrbufAppendC(&buf, '\n'); - if (options->position == FF_LOGO_POSITION_LEFT) - { + if (options->position == FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = options->width + options->paddingLeft + options->paddingRight; instance.state.logoHeight = options->paddingTop + options->height; ffStrbufAppendF(&buf, "\e[%uA", (unsigned) instance.state.logoHeight); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffStrbufAppendNC(&buf, options->paddingRight, '\n'); - } - else if (options->position == FF_LOGO_POSITION_RIGHT) - { + } else if (options->position == FF_LOGO_POSITION_RIGHT) { instance.state.logoWidth = instance.state.logoHeight = 0; ffStrbufAppendF(&buf, "\e[1G\e[%uA", (unsigned) options->height); } @@ -390,44 +342,43 @@ static bool printImageKittyDirect(bool printError) #if defined(FF_HAVE_IMAGEMAGICK7) || defined(FF_HAVE_IMAGEMAGICK6) -#define FF_KITTY_MAX_CHUNK_SIZE 4096 +# define FF_KITTY_MAX_CHUNK_SIZE 4096 -#define FF_CACHE_FILE_HEIGHT "height" -#define FF_CACHE_FILE_WIDTH "width" -#define FF_CACHE_FILE_SIXEL "sixel" -#define FF_CACHE_FILE_KITTY_COMPRESSED "kittyc" -#define FF_CACHE_FILE_KITTY_UNCOMPRESSED "kittyu" -#define FF_CACHE_FILE_CHAFA "chafa" +# define FF_CACHE_FILE_HEIGHT "height" +# define FF_CACHE_FILE_WIDTH "width" +# define FF_CACHE_FILE_SIXEL "sixel" +# define FF_CACHE_FILE_KITTY_COMPRESSED "kittyc" +# define FF_CACHE_FILE_KITTY_UNCOMPRESSED "kittyu" +# define FF_CACHE_FILE_CHAFA "chafa" -#include -#include -#include +# include +# include +# include -#ifndef _WIN32 -#include -#else -#include -#include "common/path.h" -#endif +# ifndef _WIN32 +# include +# else +# include +# include "common/path.h" +# endif -#ifdef FF_HAVE_ZLIB -#include "common/library.h" -#include -#include +# ifdef FF_HAVE_ZLIB +# include "common/library.h" +# include +# include -static bool compressBlob(void** blob, size_t* length) -{ +static bool compressBlob(void** blob, size_t* length) { FF_LIBRARY_LOAD(zlib, false, "libz" FF_LIBRARY_EXTENSION, 2) FF_LIBRARY_LOAD_SYMBOL(zlib, compressBound, false) FF_LIBRARY_LOAD_SYMBOL(zlib, compress2, false) uLong compressedLength = ffcompressBound(*length); void* compressed = malloc(compressedLength); - if(compressed == NULL) + if (compressed == NULL) { return false; + } - if(ffcompress2(compressed, &compressedLength, *blob, *length, Z_BEST_COMPRESSION) != Z_OK) - { + if (ffcompress2(compressed, &compressedLength, *blob, *length, Z_BEST_COMPRESSION) != Z_OK) { free(compressed); return false; } @@ -439,17 +390,16 @@ static bool compressBlob(void** blob, size_t* length) return true; } -#endif // FF_HAVE_ZLIB +# endif // FF_HAVE_ZLIB -//We use only the defines from here, that are exactly the same in both versions -#ifdef FF_HAVE_IMAGEMAGICK7 - #include -#else - #include -#endif +// We use only the defines from here, that are exactly the same in both versions +# ifdef FF_HAVE_IMAGEMAGICK7 +# include +# else +# include +# endif -typedef struct ImageData -{ +typedef struct ImageData { FF_LIBRARY_SYMBOL(CopyMagickString) FF_LIBRARY_SYMBOL(ImageToBlob) FF_LIBRARY_SYMBOL(Base64Encode) @@ -459,13 +409,12 @@ typedef struct ImageData ExceptionInfo* exceptionInfo; } ImageData; -static inline bool checkAllocationResult(void* data, size_t length) -{ - if(data == NULL) +static inline bool checkAllocationResult(void* data, size_t length) { + if (data == NULL) { return false; + } - if(length == 0) - { + if (length == 0) { free(data); return false; } @@ -473,65 +422,65 @@ static inline bool checkAllocationResult(void* data, size_t length) return true; } -static void writeCacheStrbuf(FFLogoRequestData* requestData, const FFstrbuf* value, const char* cacheFileName) -{ +static void writeCacheStrbuf(FFLogoRequestData* requestData, const FFstrbuf* value, const char* cacheFileName) { uint32_t cacheDirLength = requestData->cacheDir.length; ffStrbufAppendS(&requestData->cacheDir, cacheFileName); ffWriteFileBuffer(requestData->cacheDir.chars, value); ffStrbufSubstrBefore(&requestData->cacheDir, cacheDirLength); } -static void writeCacheUint32(FFLogoRequestData* requestData, uint32_t value, const char* cacheFileName) -{ +static void writeCacheUint32(FFLogoRequestData* requestData, uint32_t value, const char* cacheFileName) { FFstrbuf content; content.chars = (char*) &value; content.length = sizeof(value); writeCacheStrbuf(requestData, &content, cacheFileName); } -static void printImagePixels(FFLogoRequestData* requestData, const FFstrbuf* result, const char* cacheFileName) -{ +static void printImagePixels(FFLogoRequestData* requestData, const FFstrbuf* result, const char* cacheFileName) { const FFOptionsLogo* options = &instance.config.logo; - //Calculate character dimensions + // Calculate character dimensions instance.state.logoWidth = requestData->logoCharacterWidth + options->paddingLeft + options->paddingRight; instance.state.logoHeight = requestData->logoCharacterHeight + options->paddingTop - 1; - //Write cache files + // Write cache files writeCacheStrbuf(requestData, result, cacheFileName); - if(options->width == 0) + if (options->width == 0) { writeCacheUint32(requestData, requestData->logoCharacterWidth, FF_CACHE_FILE_WIDTH); + } - if(options->height == 0) + if (options->height == 0) { writeCacheUint32(requestData, requestData->logoCharacterHeight, FF_CACHE_FILE_HEIGHT); + } - //Write result to stdout + // Write result to stdout ffPrintCharTimes('\n', options->paddingTop); - if (options->position == FF_LOGO_POSITION_RIGHT) + if (options->position == FF_LOGO_POSITION_RIGHT) { printf("\e[9999999C\e[%uD", (unsigned) options->paddingRight + requestData->logoCharacterWidth); - else if (options->paddingLeft) + } else if (options->paddingLeft) { printf("\e[%uC", (unsigned) options->paddingLeft); + } fflush(stdout); ffWriteFDBuffer(FFUnixFD2NativeFD(STDOUT_FILENO), result); - if (options->position != FF_LOGO_POSITION_TOP) - { - //Go to upper left corner + if (options->position != FF_LOGO_POSITION_TOP) { + // Go to upper left corner printf("\e[1G\e[%uA", instance.state.logoHeight); } - if (options->position != FF_LOGO_POSITION_LEFT) + if (options->position != FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = instance.state.logoHeight = 0; + } } -static bool printImageSixel(FFLogoRequestData* requestData, const ImageData* imageData) -{ +static bool printImageSixel(FFLogoRequestData* requestData, const ImageData* imageData) { imageData->ffCopyMagickString(imageData->imageInfo->magick, "SIXEL", 6); size_t length; void* blob = imageData->ffImageToBlob(imageData->imageInfo, imageData->image, &length, imageData->exceptionInfo); - if(!checkAllocationResult(blob, length)) + if (!checkAllocationResult(blob, length)) { return false; + } FFstrbuf result; result.chars = (char*) blob; @@ -543,14 +492,14 @@ static bool printImageSixel(FFLogoRequestData* requestData, const ImageData* ima return true; } -static void appendKittyChunk(FFstrbuf* result, const char** blob, size_t* length, bool printEscapeCode) -{ +static void appendKittyChunk(FFstrbuf* result, const char** blob, size_t* length, bool printEscapeCode) { uint32_t chunkSize = *length > FF_KITTY_MAX_CHUNK_SIZE ? FF_KITTY_MAX_CHUNK_SIZE : (uint32_t) *length; - if(printEscapeCode) + if (printEscapeCode) { ffStrbufAppendS(result, "\033_G"); - else + } else { ffStrbufAppendC(result, ','); + } ffStrbufAppendS(result, chunkSize != *length ? "m=1" : "m=0"); ffStrbufAppendC(result, ';'); @@ -560,25 +509,26 @@ static void appendKittyChunk(FFstrbuf* result, const char** blob, size_t* length *blob += chunkSize; } -static bool printImageKitty(FFLogoRequestData* requestData, const ImageData* imageData) -{ +static bool printImageKitty(FFLogoRequestData* requestData, const ImageData* imageData) { imageData->ffCopyMagickString(imageData->imageInfo->magick, "RGBA", 5); size_t length; void* blob = imageData->ffImageToBlob(imageData->imageInfo, imageData->image, &length, imageData->exceptionInfo); - if(!checkAllocationResult(blob, length)) + if (!checkAllocationResult(blob, length)) { return false; + } - #ifdef FF_HAVE_ZLIB - bool isCompressed = compressBlob(&blob, &length); - #else - bool isCompressed = false; - #endif +# ifdef FF_HAVE_ZLIB + bool isCompressed = compressBlob(&blob, &length); +# else + bool isCompressed = false; +# endif char* chars = imageData->ffBase64Encode(blob, length, &length); free(blob); - if(!checkAllocationResult(chars, length)) + if (!checkAllocationResult(chars, length)) { return false; + } FF_STRBUF_AUTO_DESTROY result = ffStrbufCreateA((uint32_t) (length + 1024)); @@ -586,11 +536,13 @@ static bool printImageKitty(FFLogoRequestData* requestData, const ImageData* ima size_t remainingLength = length; ffStrbufAppendF(&result, "\033_Ga=T,f=32,s=%u,v=%u", requestData->logoPixelWidth, requestData->logoPixelHeight); - if(isCompressed) + if (isCompressed) { ffStrbufAppendS(&result, ",o=z"); + } appendKittyChunk(&result, ¤tPos, &remainingLength, false); - while(remainingLength > 0) + while (remainingLength > 0) { appendKittyChunk(&result, ¤tPos, &remainingLength, true); + } printImagePixels(requestData, &result, isCompressed ? FF_CACHE_FILE_KITTY_COMPRESSED : FF_CACHE_FILE_KITTY_UNCOMPRESSED); @@ -598,13 +550,10 @@ static bool printImageKitty(FFLogoRequestData* requestData, const ImageData* ima return true; } -#ifdef FF_HAVE_CHAFA -#include -static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* imageData) -{ - FF_LIBRARY_LOAD(chafa, false, - "libchafa" FF_LIBRARY_EXTENSION, 1, - "libchafa-0" FF_LIBRARY_EXTENSION, -1 // Required for Windows +# ifdef FF_HAVE_CHAFA +# include +static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* imageData) { + FF_LIBRARY_LOAD(chafa, false, "libchafa" FF_LIBRARY_EXTENSION, 1, "libchafa-0" FF_LIBRARY_EXTENSION, -1 // Required for Windows ) FF_LIBRARY_LOAD_SYMBOL(chafa, chafa_symbol_map_new, false) FF_LIBRARY_LOAD_SYMBOL(chafa, chafa_symbol_map_apply_selectors, false) @@ -621,41 +570,43 @@ static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* ima imageData->ffCopyMagickString(imageData->imageInfo->magick, "RGBA", 5); size_t length; void* blob = imageData->ffImageToBlob(imageData->imageInfo, imageData->image, &length, imageData->exceptionInfo); - if(!checkAllocationResult(blob, length)) + if (!checkAllocationResult(blob, length)) { return false; + } ChafaSymbolMap* symbolMap = ffchafa_symbol_map_new(); GError* error = NULL; - if(!ffchafa_symbol_map_apply_selectors(symbolMap, instance.config.logo.chafaSymbols.chars, &error)) + if (!ffchafa_symbol_map_apply_selectors(symbolMap, instance.config.logo.chafaSymbols.chars, &error)) { fputs(error->message, stderr); + } ChafaCanvasConfig* canvasConfig = ffchafa_canvas_config_new(); ffchafa_canvas_config_set_geometry(canvasConfig, (gint) requestData->logoCharacterWidth, (gint) requestData->logoCharacterHeight); ffchafa_canvas_config_set_symbol_map(canvasConfig, symbolMap); - if(instance.config.logo.chafaFgOnly) - { + if (instance.config.logo.chafaFgOnly) { FF_LIBRARY_LOAD_SYMBOL_LAZY(chafa, chafa_canvas_config_set_fg_only_enabled); - if(ffchafa_canvas_config_set_fg_only_enabled) + if (ffchafa_canvas_config_set_fg_only_enabled) { ffchafa_canvas_config_set_fg_only_enabled(canvasConfig, true); + } } - if(instance.config.logo.chafaCanvasMode < CHAFA_CANVAS_MODE_MAX) - { + if (instance.config.logo.chafaCanvasMode < CHAFA_CANVAS_MODE_MAX) { FF_LIBRARY_LOAD_SYMBOL_LAZY(chafa, chafa_canvas_config_set_canvas_mode); - if(ffchafa_canvas_config_set_canvas_mode) + if (ffchafa_canvas_config_set_canvas_mode) { ffchafa_canvas_config_set_canvas_mode(canvasConfig, (ChafaCanvasMode) instance.config.logo.chafaCanvasMode); + } } - if(instance.config.logo.chafaColorSpace < CHAFA_COLOR_SPACE_MAX) - { + if (instance.config.logo.chafaColorSpace < CHAFA_COLOR_SPACE_MAX) { FF_LIBRARY_LOAD_SYMBOL_LAZY(chafa, chafa_canvas_config_set_color_space) - if(ffchafa_canvas_config_set_color_space) + if (ffchafa_canvas_config_set_color_space) { ffchafa_canvas_config_set_color_space(canvasConfig, (ChafaColorSpace) instance.config.logo.chafaColorSpace); + } } - if(instance.config.logo.chafaDitherMode < CHAFA_DITHER_MODE_MAX) - { + if (instance.config.logo.chafaDitherMode < CHAFA_DITHER_MODE_MAX) { FF_LIBRARY_LOAD_SYMBOL_LAZY(chafa, chafa_canvas_config_set_dither_mode) - if(ffchafa_canvas_config_set_dither_mode) + if (ffchafa_canvas_config_set_dither_mode) { ffchafa_canvas_config_set_dither_mode(canvasConfig, (ChafaDitherMode) instance.config.logo.chafaDitherMode); + } } ChafaCanvas* canvas = ffchafa_canvas_new(canvasConfig); @@ -665,8 +616,7 @@ static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* ima blob, (gint) imageData->image->columns, (gint) imageData->image->rows, - (gint) imageData->image->columns * 4 - ); + (gint) imageData->image->columns * 4); GString* str = ffchafa_canvas_print(canvas, NULL); FFstrbuf result; @@ -679,13 +629,14 @@ static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* ima // FIXME: These functions must be imported from `libglib` dlls on Windows FF_LIBRARY_LOAD_SYMBOL_LAZY(chafa, g_string_free); - if(ffg_string_free) + if (ffg_string_free) { ffg_string_free(str, TRUE); - if(error) - { + } + if (error) { FF_LIBRARY_LOAD_SYMBOL_LAZY(chafa, g_error_free) - if(ffg_error_free) + if (ffg_error_free) { ffg_error_free(error); + } } ffchafa_canvas_unref(canvas); @@ -694,10 +645,9 @@ static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* ima return true; } -#endif +# endif -FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFIMData* imData) -{ +FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFIMData* imData) { FF_LIBRARY_LOAD_SYMBOL(imData->library, MagickCoreGenesis, FF_LOGO_IMAGE_RESULT_INIT_ERROR) FF_LIBRARY_LOAD_SYMBOL(imData->library, MagickCoreTerminus, FF_LOGO_IMAGE_RESULT_INIT_ERROR) FF_LIBRARY_LOAD_SYMBOL(imData->library, AcquireExceptionInfo, FF_LOGO_IMAGE_RESULT_INIT_ERROR) @@ -716,15 +666,13 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI ffMagickCoreGenesis(NULL, MagickFalse); imageData.exceptionInfo = ffAcquireExceptionInfo(); - if(imageData.exceptionInfo == NULL) - { + if (imageData.exceptionInfo == NULL) { ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; } ImageInfo* imageInfoIn = ffAcquireImageInfo(); - if(imageInfoIn == NULL) - { + if (imageInfoIn == NULL) { ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; @@ -735,28 +683,25 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI imageData.image = ffReadImage(imageInfoIn, imageData.exceptionInfo); ffDestroyImageInfo(imageInfoIn); - if(imageData.image == NULL) - { + if (imageData.image == NULL) { ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; } - if(requestData->logoPixelWidth == 0 && requestData->logoPixelHeight == 0) - { + if (requestData->logoPixelWidth == 0 && requestData->logoPixelHeight == 0) { requestData->logoPixelWidth = (uint32_t) imageData.image->columns; requestData->logoPixelHeight = (uint32_t) imageData.image->rows; - } - else if(requestData->logoPixelWidth == 0) + } else if (requestData->logoPixelWidth == 0) { requestData->logoPixelWidth = (uint32_t) ((double) imageData.image->columns / (double) imageData.image->rows * requestData->logoPixelHeight); - else if(requestData->logoPixelHeight == 0) + } else if (requestData->logoPixelHeight == 0) { requestData->logoPixelHeight = (uint32_t) ((double) imageData.image->rows / (double) imageData.image->columns * requestData->logoPixelWidth); + } requestData->logoCharacterWidth = (uint32_t) ceil((double) requestData->logoPixelWidth / requestData->characterPixelWidth); requestData->logoCharacterHeight = (uint32_t) ceil((double) requestData->logoPixelHeight / requestData->characterPixelHeight); - if(requestData->logoPixelWidth == 0 || requestData->logoPixelHeight == 0 || requestData->logoCharacterWidth == 0 || requestData->logoCharacterHeight == 0) - { + if (requestData->logoPixelWidth == 0 || requestData->logoPixelHeight == 0 || requestData->logoCharacterWidth == 0 || requestData->logoCharacterHeight == 0) { ffDestroyImage(imageData.image); ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); @@ -765,8 +710,7 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI Image* resized = imData->resizeFunc(imageData.image, requestData->logoPixelWidth, requestData->logoPixelHeight, imageData.exceptionInfo); ffDestroyImage(imageData.image); - if(resized == NULL) - { + if (resized == NULL) { ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; @@ -774,8 +718,7 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI imageData.image = resized; imageData.imageInfo = ffAcquireImageInfo(); - if(imageData.imageInfo == NULL) - { + if (imageData.imageInfo == NULL) { ffDestroyImage(imageData.image); ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); @@ -783,16 +726,15 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI } bool printSuccessful = false; - if(requestData->type == FF_LOGO_TYPE_IMAGE_CHAFA) - { - #ifdef FF_HAVE_CHAFA - printSuccessful = printImageChafa(requestData, &imageData); - #endif - } - else if(requestData->type == FF_LOGO_TYPE_IMAGE_KITTY) + if (requestData->type == FF_LOGO_TYPE_IMAGE_CHAFA) { +# ifdef FF_HAVE_CHAFA + printSuccessful = printImageChafa(requestData, &imageData); +# endif + } else if (requestData->type == FF_LOGO_TYPE_IMAGE_KITTY) { printSuccessful = printImageKitty(requestData, &imageData); - else if(requestData->type == FF_LOGO_TYPE_IMAGE_SIXEL) + } else if (requestData->type == FF_LOGO_TYPE_IMAGE_SIXEL) { printSuccessful = printImageSixel(requestData, &imageData); + } ffDestroyImageInfo(imageData.imageInfo); ffDestroyImage(imageData.image); @@ -802,167 +744,162 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI return printSuccessful ? FF_LOGO_IMAGE_RESULT_SUCCESS : FF_LOGO_IMAGE_RESULT_RUN_ERROR; } -static FFNativeFD getCacheFD(FFLogoRequestData* requestData, const char* fileName) -{ +static FFNativeFD getCacheFD(FFLogoRequestData* requestData, const char* fileName) { uint32_t cacheDirLength = requestData->cacheDir.length; ffStrbufAppendS(&requestData->cacheDir, fileName); - #ifndef _WIN32 +# ifndef _WIN32 int fd = open(requestData->cacheDir.chars, O_RDONLY - #ifdef O_CLOEXEC +# ifdef O_CLOEXEC | O_CLOEXEC - #endif +# endif ); - #else - HANDLE fd = CreateFileA(requestData->cacheDir.chars, GENERIC_READ, - FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - #endif +# else + HANDLE fd = CreateFileA(requestData->cacheDir.chars, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +# endif ffStrbufSubstrBefore(&requestData->cacheDir, cacheDirLength); return fd; } -static void readCachedStrbuf(FFLogoRequestData* requestData, FFstrbuf* result, const char* cacheFileName) -{ +static void readCachedStrbuf(FFLogoRequestData* requestData, FFstrbuf* result, const char* cacheFileName) { uint32_t cacheDirLength = requestData->cacheDir.length; ffStrbufAppendS(&requestData->cacheDir, cacheFileName); ffAppendFileBuffer(requestData->cacheDir.chars, result); ffStrbufSubstrBefore(&requestData->cacheDir, cacheDirLength); } -static uint32_t readCachedUint32(FFLogoRequestData* requestData, const char* cacheFileName) -{ +static uint32_t readCachedUint32(FFLogoRequestData* requestData, const char* cacheFileName) { FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); readCachedStrbuf(requestData, &content, cacheFileName); uint32_t result = 0; - if(content.length != sizeof(result)) + if (content.length != sizeof(result)) { return 0; + } memcpy(&result, content.chars, sizeof(result)); return result; } -static bool printCachedChars(FFLogoRequestData* requestData) -{ +static bool printCachedChars(FFLogoRequestData* requestData) { FF_STRBUF_AUTO_DESTROY content = ffStrbufCreateA(32768); - if(requestData->type == FF_LOGO_TYPE_IMAGE_CHAFA) + if (requestData->type == FF_LOGO_TYPE_IMAGE_CHAFA) { readCachedStrbuf(requestData, &content, FF_CACHE_FILE_CHAFA); + } - if(content.length == 0) + if (content.length == 0) { return false; + } ffLogoPrintChars(content.chars, false); return true; } -static bool printCachedPixel(FFLogoRequestData* requestData) -{ +static bool printCachedPixel(FFLogoRequestData* requestData) { FFOptionsLogo* options = &instance.config.logo; requestData->logoCharacterWidth = options->width; - if(requestData->logoCharacterWidth == 0) - { + if (requestData->logoCharacterWidth == 0) { requestData->logoCharacterWidth = readCachedUint32(requestData, FF_CACHE_FILE_WIDTH); - if(requestData->logoCharacterWidth == 0) + if (requestData->logoCharacterWidth == 0) { return false; + } } requestData->logoCharacterHeight = options->height; - if(requestData->logoCharacterHeight == 0) - { + if (requestData->logoCharacterHeight == 0) { requestData->logoCharacterHeight = readCachedUint32(requestData, FF_CACHE_FILE_HEIGHT); - if(requestData->logoCharacterHeight == 0) + if (requestData->logoCharacterHeight == 0) { return false; + } } FF_AUTO_CLOSE_FD FFNativeFD fd = FF_INVALID_FD; - if(requestData->type == FF_LOGO_TYPE_IMAGE_KITTY) - { + if (requestData->type == FF_LOGO_TYPE_IMAGE_KITTY) { fd = getCacheFD(requestData, FF_CACHE_FILE_KITTY_COMPRESSED); - if(!ffIsValidNativeFD(fd)) + if (!ffIsValidNativeFD(fd)) { fd = getCacheFD(requestData, FF_CACHE_FILE_KITTY_UNCOMPRESSED); - } - else if(requestData->type == FF_LOGO_TYPE_IMAGE_SIXEL) + } + } else if (requestData->type == FF_LOGO_TYPE_IMAGE_SIXEL) { fd = getCacheFD(requestData, FF_CACHE_FILE_SIXEL); + } - if(!ffIsValidNativeFD(fd)) + if (!ffIsValidNativeFD(fd)) { return false; + } ffPrintCharTimes('\n', options->paddingTop); - if (options->position == FF_LOGO_POSITION_RIGHT) + if (options->position == FF_LOGO_POSITION_RIGHT) { printf("\e[9999999C\e[%uD", (unsigned) options->paddingRight + requestData->logoCharacterWidth); - else if (options->paddingLeft) + } else if (options->paddingLeft) { printf("\e[%uC", (unsigned) options->paddingLeft); + } fflush(stdout); bool sent = false; - #ifdef __linux__ +# ifdef __linux__ struct stat st; - if (fstat(fd, &st) >= 0) - { - while (st.st_size > 0) - { + if (fstat(fd, &st) >= 0) { + while (st.st_size > 0) { ssize_t bytes = sendfile(STDOUT_FILENO, fd, NULL, (size_t) st.st_size); - if (bytes > 0) - { + if (bytes > 0) { sent = true; st.st_size -= bytes; - } - else + } else { break; + } } } - #endif +# endif - if (!sent) - { + if (!sent) { char buffer[32768]; ssize_t readBytes; - while((readBytes = ffReadFDData(fd, sizeof(buffer), buffer)) > 0) + while ((readBytes = ffReadFDData(fd, sizeof(buffer), buffer)) > 0) { ffWriteFDData(FFUnixFD2NativeFD(STDOUT_FILENO), (size_t) readBytes, buffer); + } } instance.state.logoWidth = requestData->logoCharacterWidth + options->paddingLeft + options->paddingRight; instance.state.logoHeight = requestData->logoCharacterHeight + options->paddingTop; - if (options->position != FF_LOGO_POSITION_TOP) - { - //Go to upper left corner + if (options->position != FF_LOGO_POSITION_TOP) { + // Go to upper left corner printf("\e[1G\e[%uA", instance.state.logoHeight); } - if (options->position != FF_LOGO_POSITION_LEFT) + if (options->position != FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = instance.state.logoHeight = 0; + } return true; } -static bool printCached(FFLogoRequestData* requestData) -{ - if(requestData->type == FF_LOGO_TYPE_IMAGE_CHAFA) +static bool printCached(FFLogoRequestData* requestData) { + if (requestData->type == FF_LOGO_TYPE_IMAGE_CHAFA) { return printCachedChars(requestData); - else + } else { return printCachedPixel(requestData); + } } -static bool getCharacterPixelDimensions(FFLogoRequestData* requestData) -{ - #ifdef _WIN32 +static bool getCharacterPixelDimensions(FFLogoRequestData* requestData) { +# ifdef _WIN32 - CONSOLE_FONT_INFOEX cfi = { .cbSize = sizeof(cfi) }; - if(GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi)) // Only works for ConHost + CONSOLE_FONT_INFOEX cfi = {.cbSize = sizeof(cfi)}; + if (GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi)) // Only works for ConHost { requestData->characterPixelWidth = cfi.dwFontSize.X; requestData->characterPixelHeight = cfi.dwFontSize.Y; } - if (requestData->characterPixelWidth > 1.0 && requestData->characterPixelHeight > 1.0) + if (requestData->characterPixelWidth > 1.0 && requestData->characterPixelHeight > 1.0) { return true; - #endif + } +# endif FFTerminalSizeResult termSize = {}; - if (ffDetectTerminalSize(&termSize)) - { + if (ffDetectTerminalSize(&termSize)) { requestData->characterPixelWidth = termSize.width / (double) termSize.columns; requestData->characterPixelHeight = termSize.height / (double) termSize.rows; } @@ -970,17 +907,16 @@ static bool getCharacterPixelDimensions(FFLogoRequestData* requestData) return requestData->characterPixelWidth > 1.0 && requestData->characterPixelHeight > 1.0; } -static bool printImageIfExistsSlowPath(FFLogoType type, bool printError) -{ +static bool printImageIfExistsSlowPath(FFLogoType type, bool printError) { FFLogoRequestData requestData; requestData.type = type; requestData.characterPixelWidth = 1; requestData.characterPixelHeight = 1; - if(!getCharacterPixelDimensions(&requestData)) - { - if(printError) + if (!getCharacterPixelDimensions(&requestData)) { + if (printError) { fputs("Logo: getCharacterPixelDimensions() failed\n", stderr); + } return false; } @@ -993,106 +929,110 @@ static bool printImageIfExistsSlowPath(FFLogoType type, bool printError) ffStrbufEnsureFree(&requestData.cacheDir, PATH_MAX); char* filePath = requestData.cacheDir.chars + requestData.cacheDir.length; - if(realpath(instance.config.logo.source.chars, filePath) == NULL) - { - //We can safely return here, because if realpath failed, we surely won't be able to read the file + if (realpath(instance.config.logo.source.chars, filePath) == NULL) { + // We can safely return here, because if realpath failed, we surely won't be able to read the file ffStrbufDestroy(&requestData.cacheDir); - if(printError) + if (printError) { fputs("Logo: Querying realpath of the image source failed\n", stderr); + } return false; } - #ifdef _WIN32 +# ifdef _WIN32 filePath[1] = filePath[0]; // Drive Name filePath[0] = '/'; - #endif +# endif ffStrbufRecalculateLength(&requestData.cacheDir); ffStrbufEnsureEndsWithC(&requestData.cacheDir, '/'); ffStrbufAppendF(&requestData.cacheDir, "%u*%u/", requestData.logoPixelWidth, requestData.logoPixelHeight); - if(!instance.config.logo.recache && printCached(&requestData)) - { + if (!instance.config.logo.recache && printCached(&requestData)) { ffStrbufDestroy(&requestData.cacheDir); return true; } FFLogoImageResult result = FF_LOGO_IMAGE_RESULT_INIT_ERROR; - #ifdef FF_HAVE_IMAGEMAGICK7 - result = ffLogoPrintImageIM7(&requestData); - #endif +# ifdef FF_HAVE_IMAGEMAGICK7 + result = ffLogoPrintImageIM7(&requestData); +# endif - #ifdef FF_HAVE_IMAGEMAGICK6 - if(result == FF_LOGO_IMAGE_RESULT_INIT_ERROR) - result = ffLogoPrintImageIM6(&requestData); - #endif +# ifdef FF_HAVE_IMAGEMAGICK6 + if (result == FF_LOGO_IMAGE_RESULT_INIT_ERROR) { + result = ffLogoPrintImageIM6(&requestData); + } +# endif ffStrbufDestroy(&requestData.cacheDir); - if(result == FF_LOGO_IMAGE_RESULT_SUCCESS) + if (result == FF_LOGO_IMAGE_RESULT_SUCCESS) { return true; + } - if(printError) - { - if(result == FF_LOGO_IMAGE_RESULT_INIT_ERROR) + if (printError) { + if (result == FF_LOGO_IMAGE_RESULT_INIT_ERROR) { fputs("Logo: Image Magick library not found\n", stderr); - else + } else { fputs("Logo: Failed to load / convert the image source\n", stderr); + } } return false; } -#endif //FF_HAVE_IMAGEMAGICK{6, 7} +#endif // FF_HAVE_IMAGEMAGICK{6, 7} -bool ffLogoPrintImageIfExists(FFLogoType type, bool printError) -{ - if(instance.config.display.pipe) - { - if(printError) +bool ffLogoPrintImageIfExists(FFLogoType type, bool printError) { + if (instance.config.display.pipe) { + if (printError) { fputs("Logo: Image logo is not supported in pipe mode\n", stderr); + } return false; } - if(!ffPathExists(instance.config.logo.source.chars, FF_PATHTYPE_FILE)) - { - if(printError) + if (!ffPathExists(instance.config.logo.source.chars, FF_PATHTYPE_FILE)) { + if (printError) { fprintf(stderr, "Logo: Image source \"%s\" does not exist\n", instance.config.logo.source.chars); + } return false; } const char* term = getenv("TERM"); - if((term && ffStrEquals(term, "screen")) || getenv("ZELLIJ")) - { - if(printError) + if ((term && ffStrEquals(term, "screen")) || getenv("ZELLIJ")) { + if (printError) { fputs("Logo: Image logo is not supported in terminal multiplexers\n", stderr); + } return false; } - if(type == FF_LOGO_TYPE_IMAGE_ITERM) + if (type == FF_LOGO_TYPE_IMAGE_ITERM) { return printImageIterm(printError); + } - if(type == FF_LOGO_TYPE_IMAGE_KITTY_DIRECT) + if (type == FF_LOGO_TYPE_IMAGE_KITTY_DIRECT) { return printImageKittyDirect(printError); + } - if(type == FF_LOGO_TYPE_IMAGE_KITTY_ICAT) + if (type == FF_LOGO_TYPE_IMAGE_KITTY_ICAT) { return printImageKittyIcat(printError); + } - #if !defined(FF_HAVE_CHAFA) - if(type == FF_LOGO_TYPE_IMAGE_CHAFA) - { - if(printError) - fputs("Logo: Chafa support is not compiled in\n", stderr); - return false; +#if !defined(FF_HAVE_CHAFA) + if (type == FF_LOGO_TYPE_IMAGE_CHAFA) { + if (printError) { + fputs("Logo: Chafa support is not compiled in\n", stderr); } - #endif - - #if !defined(FF_HAVE_IMAGEMAGICK7) && !defined(FF_HAVE_IMAGEMAGICK6) - if(printError) - fputs("Logo: Image Magick support is not compiled in\n", stderr); return false; - #else - return printImageIfExistsSlowPath(type, printError); - #endif + } +#endif + +#if !defined(FF_HAVE_IMAGEMAGICK7) && !defined(FF_HAVE_IMAGEMAGICK6) + if (printError) { + fputs("Logo: Image Magick support is not compiled in\n", stderr); + } + return false; +#else + return printImageIfExistsSlowPath(type, printError); +#endif } diff --git a/src/logo/image/image.h b/src/logo/image/image.h index 58a2f6289..3b00695eb 100644 --- a/src/logo/image/image.h +++ b/src/logo/image/image.h @@ -4,15 +4,13 @@ #if defined(FF_HAVE_IMAGEMAGICK7) || defined(FF_HAVE_IMAGEMAGICK6) -typedef enum __attribute__((__packed__)) FFLogoImageResult -{ - FF_LOGO_IMAGE_RESULT_SUCCESS, //Logo printed - FF_LOGO_IMAGE_RESULT_INIT_ERROR, //Failed to load library, try again with next IM version - FF_LOGO_IMAGE_RESULT_RUN_ERROR //Failed to load / convert image, cancel whole sixel code +typedef enum __attribute__((__packed__)) FFLogoImageResult { + FF_LOGO_IMAGE_RESULT_SUCCESS, // Logo printed + FF_LOGO_IMAGE_RESULT_INIT_ERROR, // Failed to load library, try again with next IM version + FF_LOGO_IMAGE_RESULT_RUN_ERROR // Failed to load / convert image, cancel whole sixel code } FFLogoImageResult; -typedef struct FFLogoRequestData -{ +typedef struct FFLogoRequestData { FFLogoType type; FFstrbuf cacheDir; @@ -26,10 +24,9 @@ typedef struct FFLogoRequestData uint32_t logoCharacterWidth; } FFLogoRequestData; -typedef struct FFIMData -{ +typedef struct FFIMData { void* library; - void*(*resizeFunc)(const void* image, size_t width, size_t height, void* exceptionInfo); + void* (*resizeFunc)(const void* image, size_t width, size_t height, void* exceptionInfo); } FFIMData; FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFIMData* imData); @@ -41,6 +38,6 @@ FFLogoImageResult ffLogoPrintImageIM7(FFLogoRequestData* requestData); #endif #ifdef FF_HAVE_IMAGEMAGICK6 -#include +# include FFLogoImageResult ffLogoPrintImageIM6(FFLogoRequestData* requestData); #endif diff --git a/src/logo/logo.c b/src/logo/logo.c index d4c682a1f..8a23f0070 100644 --- a/src/logo/logo.c +++ b/src/logo/logo.c @@ -12,31 +12,21 @@ #include #include -static bool ffLogoPrintCharsRaw(const char* data, size_t length, bool printError) -{ +static bool ffLogoPrintCharsRaw(const char* data, size_t length, bool printError) { FFOptionsLogo* options = &instance.config.logo; FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (!options->width || !options->height) - { - if (options->position == FF_LOGO_POSITION_LEFT) - { - ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", - (unsigned) options->paddingTop + 1, - (unsigned) options->paddingLeft + 1 - ); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + if (!options->width || !options->height) { + if (options->position == FF_LOGO_POSITION_LEFT) { + ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;%uH", (unsigned) options->paddingTop + 1, (unsigned) options->paddingLeft + 1); + } else if (options->position == FF_LOGO_POSITION_TOP) { ffStrbufAppendNC(&buf, options->paddingTop, '\n'); ffStrbufAppendNC(&buf, options->paddingLeft, ' '); - } - else if (options->position == FF_LOGO_POSITION_RIGHT) - { - if (!options->width) - { - if (printError) + } else if (options->position == FF_LOGO_POSITION_RIGHT) { + if (!options->width) { + if (printError) { fputs("Logo (image-raw): Must set logo width when using position right\n", stderr); + } return false; } ffStrbufAppendF(&buf, "\e[2J\e[3J\e[%u;9999999H\e[%uD", (unsigned) options->paddingTop + 1, (unsigned) options->paddingRight + options->width); @@ -44,57 +34,48 @@ static bool ffLogoPrintCharsRaw(const char* data, size_t length, bool printError ffStrbufAppendNS(&buf, (uint32_t) length, data); ffWriteFDBuffer(FFUnixFD2NativeFD(STDOUT_FILENO), &buf); - if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) - { + if (options->position == FF_LOGO_POSITION_LEFT || options->position == FF_LOGO_POSITION_RIGHT) { uint16_t X = 0, Y = 0; // Windows Terminal doesn't report `\e` for some reason const char* error = ffGetTerminalResponse("\e[6n", 2, "%*[^0-9]%hu;%huR", &Y, &X); // %*[^0-9]: ignore optional \e[ - if (error) - { - if (printError) + if (error) { + if (printError) { fprintf(stderr, "\nLogo (image-raw): fail to query cursor position: %s\n", error); + } return true; } - if (options->position == FF_LOGO_POSITION_LEFT) - { - if (options->width + options->paddingLeft > X) + if (options->position == FF_LOGO_POSITION_LEFT) { + if (options->width + options->paddingLeft > X) { X = (uint16_t) (options->width + options->paddingLeft); + } instance.state.logoWidth = X + instance.config.logo.paddingRight - 1; } instance.state.logoHeight = Y; fputs("\e[H", stdout); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffPrintCharTimes('\n', options->paddingRight); } - } - else - { + } else { ffStrbufAppendNC(&buf, options->paddingTop, '\n'); - if (options->position == FF_LOGO_POSITION_RIGHT) + if (options->position == FF_LOGO_POSITION_RIGHT) { ffStrbufAppendF(&buf, "\e[9999999C\e[%uD", (unsigned) options->paddingRight + options->width); - else if (options->paddingLeft) + } else if (options->paddingLeft) { ffStrbufAppendF(&buf, "\e[%uC", (unsigned) options->paddingLeft); + } ffStrbufAppendNS(&buf, (uint32_t) length, data); ffStrbufAppendC(&buf, '\n'); - if (options->position == FF_LOGO_POSITION_LEFT) - { + if (options->position == FF_LOGO_POSITION_LEFT) { instance.state.logoWidth = options->width + options->paddingLeft + options->paddingRight; instance.state.logoHeight = options->paddingTop + options->height; ffStrbufAppendF(&buf, "\e[%uA", (unsigned) instance.state.logoHeight); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffStrbufAppendNC(&buf, options->paddingRight, '\n'); - } - else if (options->position == FF_LOGO_POSITION_RIGHT) - { + } else if (options->position == FF_LOGO_POSITION_RIGHT) { instance.state.logoWidth = instance.state.logoHeight = 0; ffStrbufAppendF(&buf, "\e[%uA", (unsigned) options->height); } @@ -106,197 +87,202 @@ static bool ffLogoPrintCharsRaw(const char* data, size_t length, bool printError // If result is NULL, calculate logo width // Returns logo height -static uint32_t logoAppendChars(const char* data, bool doColorReplacement, FFstrbuf* result) -{ +static uint32_t logoAppendChars(const char* data, bool doColorReplacement, FFstrbuf* result) { FFOptionsLogo* options = &instance.config.logo; uint32_t currentlineLength = options->type == FF_LOGO_TYPE_IMAGE_CHAFA ? 0 : options->width; // For chafa, unit of options->width is pixels uint32_t logoHeight = 0; - if (result) - { - if (options->position != FF_LOGO_POSITION_RIGHT) + if (result) { + if (options->position != FF_LOGO_POSITION_RIGHT) { ffStrbufAppendNC(result, options->paddingLeft, ' '); - else + } else { ffStrbufAppendF(result, "\e[9999999C\e[%dD", options->paddingRight + instance.state.logoWidth); + } } - while(*data != '\0') - { - //We are at the end of a line. Print paddings and update max line length - if(*data == '\n' || (*data == '\r' && *(data + 1) == '\n')) - { - //We have \r\n, skip the \r - if(*data == '\r') + while (*data != '\0') { + // We are at the end of a line. Print paddings and update max line length + if (*data == '\n' || (*data == '\r' && *(data + 1) == '\n')) { + // We have \r\n, skip the \r + if (*data == '\r') { ++data; - - if(result) ffStrbufAppendC(result, '\n'); - ++data; - - if (result) - { - if (options->position != FF_LOGO_POSITION_RIGHT) - ffStrbufAppendNC(result, options->paddingLeft, ' '); - else - ffStrbufAppendF(result, "\e[9999999C\e[%dD", options->paddingRight + instance.state.logoWidth); } - if(currentlineLength > instance.state.logoWidth) + if (result) { + ffStrbufAppendC(result, '\n'); + } + ++data; + + if (result) { + if (options->position != FF_LOGO_POSITION_RIGHT) { + ffStrbufAppendNC(result, options->paddingLeft, ' '); + } else { + ffStrbufAppendF(result, "\e[9999999C\e[%dD", options->paddingRight + instance.state.logoWidth); + } + } + + if (currentlineLength > instance.state.logoWidth) { instance.state.logoWidth = currentlineLength; + } currentlineLength = 0; ++logoHeight; continue; } - //Always print tabs as 4 spaces, to have consistent spacing - if(*data == '\t') - { - if(result) ffStrbufAppendNC(result, 4, ' '); + // Always print tabs as 4 spaces, to have consistent spacing + if (*data == '\t') { + if (result) { + ffStrbufAppendNC(result, 4, ' '); + } ++data; continue; } - //We have an escape sequence directly as bytes. We print it, but don't increase the line length - if(*data == '\e' && *(data + 1) == '[') - { + // We have an escape sequence directly as bytes. We print it, but don't increase the line length + if (*data == '\e' && *(data + 1) == '[') { const char* start = data; - if(result) ffStrbufAppendS(result, "\e["); + if (result) { + ffStrbufAppendS(result, "\e["); + } data += 2; - while(ffCharIsDigit(*data) || *data == ';') - { - if(result) ffStrbufAppendC(result, *data); // number + while (ffCharIsDigit(*data) || *data == ';') { + if (result) { + ffStrbufAppendC(result, *data); // number + } ++data; } - //We have a valid control sequence, print it and continue with next char - if(isascii(*data)) - { - if(result) ffStrbufAppendC(result, *data); // single letter, end of control sequence + // We have a valid control sequence, print it and continue with next char + if (isascii(*data)) { + if (result) { + ffStrbufAppendC(result, *data); // single letter, end of control sequence + } ++data; continue; } - //Invalid control sequence, try to get most accurate length + // Invalid control sequence, try to get most accurate length currentlineLength += (uint32_t) (data - start - 1); //-1 for \033 which for sure doesn't take any space - //Don't continue here, print the char after the letters with the unicode printing + // Don't continue here, print the char after the letters with the unicode printing } - //We have a fastfetch color placeholder. Replace it with the esacape sequence, don't increase the line length - if(doColorReplacement && *data == '$') - { + // We have a fastfetch color placeholder. Replace it with the esacape sequence, don't increase the line length + if (doColorReplacement && *data == '$') { ++data; - //If we have $$, or $\0, print it as single $ - if(*data == '$' || *data == '\0') - { - if(result) ffStrbufAppendC(result, '$'); + // If we have $$, or $\0, print it as single $ + if (*data == '$' || *data == '\0') { + if (result) { + ffStrbufAppendC(result, '$'); + } ++currentlineLength; ++data; continue; } - if(!instance.config.display.pipe) - { - //Map the number to an array index, so that '1' -> 0, '2' -> 1, etc. + if (!instance.config.display.pipe) { + // Map the number to an array index, so that '1' -> 0, '2' -> 1, etc. int index = *data - '1'; - //If the index is valid, print the color. Otherwise continue as normal - if(index < 0 || index >= FASTFETCH_LOGO_MAX_COLORS) - { - if(result) ffStrbufAppendC(result, '$'); + // If the index is valid, print the color. Otherwise continue as normal + if (index < 0 || index >= FASTFETCH_LOGO_MAX_COLORS) { + if (result) { + ffStrbufAppendC(result, '$'); + } ++currentlineLength; - //Don't continue here, we want to print the current char as unicode - } - else - { - if(result) ffStrbufAppendF(result, "\e[%sm", options->colors[index].chars); + // Don't continue here, we want to print the current char as unicode + } else { + if (result) { + ffStrbufAppendF(result, "\e[%sm", options->colors[index].chars); + } ++data; continue; } - } - else - { + } else { ++data; continue; } } - //Do the printing, respecting unicode + // Do the printing, respecting unicode ++currentlineLength; int codepoint = (unsigned char) *data; uint8_t bytes; - if(codepoint <= 127) + if (codepoint <= 127) { bytes = 1; - else if((codepoint & 0xE0) == 0xC0) + } else if ((codepoint & 0xE0) == 0xC0) { bytes = 2; - else if((codepoint & 0xF0) == 0xE0) + } else if ((codepoint & 0xF0) == 0xE0) { bytes = 3; - else if((codepoint & 0xF8) == 0xF0) + } else if ((codepoint & 0xF8) == 0xF0) { bytes = 4; - else - bytes = 1; //Invalid utf8, print it as is, byte by byte + } else { + bytes = 1; // Invalid utf8, print it as is, byte by byte + } - for(uint8_t i = 0; i < bytes; ++i) - { - if(*data == '\0') + for (uint8_t i = 0; i < bytes; ++i) { + if (*data == '\0') { break; + } - if(result) ffStrbufAppendC(result, *data); + if (result) { + ffStrbufAppendC(result, *data); + } ++data; } } - //Happens if the last line is the longest - if(currentlineLength > instance.state.logoWidth) + // Happens if the last line is the longest + if (currentlineLength > instance.state.logoWidth) { instance.state.logoWidth = currentlineLength; + } return options->type != FF_LOGO_TYPE_IMAGE_CHAFA && options->height > logoHeight ? options->height : logoHeight; } -void ffLogoPrintChars(const char* data, bool doColorReplacement) -{ +void ffLogoPrintChars(const char* data, bool doColorReplacement) { FFOptionsLogo* options = &instance.config.logo; - if (options->position == FF_LOGO_POSITION_RIGHT) + if (options->position == FF_LOGO_POSITION_RIGHT) { logoAppendChars(data, doColorReplacement, NULL); + } FF_STRBUF_AUTO_DESTROY result = ffStrbufCreateA(2048); - if (!instance.config.display.pipe && instance.config.display.brightColor) + if (!instance.config.display.pipe && instance.config.display.brightColor) { ffStrbufAppendS(&result, FASTFETCH_TEXT_MODIFIER_BOLT); + } ffStrbufAppendNC(&result, options->paddingTop, '\n'); - //Use logoColor[0] as the default color - if(doColorReplacement && !instance.config.display.pipe) + // Use logoColor[0] as the default color + if (doColorReplacement && !instance.config.display.pipe) { ffStrbufAppendF(&result, "\e[%sm", options->colors[0].chars); + } instance.state.logoHeight = options->paddingTop + logoAppendChars(data, doColorReplacement, &result); - if(!instance.config.display.pipe) + if (!instance.config.display.pipe) { ffStrbufAppendS(&result, FASTFETCH_TEXT_MODIFIER_RESET); + } - if(options->position == FF_LOGO_POSITION_LEFT) - { + if (options->position == FF_LOGO_POSITION_LEFT) { instance.state.logoWidth += options->paddingLeft + options->paddingRight; - //Go to the leftmost position and go up the height + // Go to the leftmost position and go up the height ffStrbufAppendF(&result, "\e[1G\e[%uA", instance.state.logoHeight); - } - else if(options->position == FF_LOGO_POSITION_RIGHT) - { + } else if (options->position == FF_LOGO_POSITION_RIGHT) { instance.state.logoWidth = 0; - //Go to the leftmost position and go up the height + // Go to the leftmost position and go up the height ffStrbufAppendF(&result, "\e[1G\e[%uA", instance.state.logoHeight); - } - else if (options->position == FF_LOGO_POSITION_TOP) - { + } else if (options->position == FF_LOGO_POSITION_TOP) { instance.state.logoWidth = instance.state.logoHeight = 0; ffStrbufAppendNC(&result, options->paddingRight, '\n'); } @@ -304,207 +290,205 @@ void ffLogoPrintChars(const char* data, bool doColorReplacement) ffWriteFDBuffer(FFUnixFD2NativeFD(STDOUT_FILENO), &result); } -static void logoApplyColors(const FFlogo* logo, bool replacement) -{ - if(instance.config.display.colorTitle.length == 0) +static void logoApplyColors(const FFlogo* logo, bool replacement) { + if (instance.config.display.colorTitle.length == 0) { ffStrbufAppendS(&instance.config.display.colorTitle, logo->colorTitle ?: logo->colors[0]); + } - if(instance.config.display.colorKeys.length == 0) + if (instance.config.display.colorKeys.length == 0) { ffStrbufAppendS(&instance.config.display.colorKeys, logo->colorKeys ?: logo->colors[1]); + } - if (replacement) - { + if (replacement) { FFOptionsLogo* options = &instance.config.logo; const char* const* colors = logo->colors; - for(int i = 0; *colors != NULL && i < FASTFETCH_LOGO_MAX_COLORS; i++, colors++) - { - if(options->colors[i].length == 0) + for (int i = 0; *colors != NULL && i < FASTFETCH_LOGO_MAX_COLORS; i++, colors++) { + if (options->colors[i].length == 0) { ffStrbufAppendS(&options->colors[i], *colors); + } } } } -static bool logoHasName(const FFlogo* logo, const FFstrbuf* name, bool small) -{ - for( +static bool logoHasName(const FFlogo* logo, const FFstrbuf* name, bool small) { + for ( const char* const* logoName = logo->names; *logoName != NULL && logoName <= &logo->names[FASTFETCH_LOGO_MAX_NAMES]; - ++logoName - ) { - if(small) - { + ++logoName) { + if (small) { uint32_t logoNameLength = (uint32_t) (strlen(*logoName) - strlen("_small")); - if(name->length == logoNameLength && strncasecmp(*logoName, name->chars, logoNameLength) == 0) return true; + if (name->length == logoNameLength && strncasecmp(*logoName, name->chars, logoNameLength) == 0) { + return true; + } } - if(ffStrbufIgnCaseEqualS(name, *logoName)) + if (ffStrbufIgnCaseEqualS(name, *logoName)) { return true; + } } return false; } -static const FFlogo* logoGetBuiltin(const FFstrbuf* name, FFLogoSize size) -{ - if (name->length == 0 || !isalpha(name->chars[0])) +static const FFlogo* logoGetBuiltin(const FFstrbuf* name, FFLogoSize size) { + if (name->length == 0 || !isalpha(name->chars[0])) { return NULL; + } - for(const FFlogo* logo = ffLogoBuiltins[toupper(name->chars[0]) - 'A']; *logo->names; ++logo) - { - switch (size) - { + for (const FFlogo* logo = ffLogoBuiltins[toupper(name->chars[0]) - 'A']; *logo->names; ++logo) { + switch (size) { // Never use alternate logos case FF_LOGO_SIZE_NORMAL: - if(logo->type != FF_LOGO_LINE_TYPE_NORMAL) continue; + if (logo->type != FF_LOGO_LINE_TYPE_NORMAL) { + continue; + } break; case FF_LOGO_SIZE_SMALL: - if(logo->type != FF_LOGO_LINE_TYPE_SMALL_BIT) continue; + if (logo->type != FF_LOGO_LINE_TYPE_SMALL_BIT) { + continue; + } break; default: break; } - if(logoHasName(logo, name, size == FF_LOGO_SIZE_SMALL)) + if (logoHasName(logo, name, size == FF_LOGO_SIZE_SMALL)) { return logo; + } } return NULL; } -static const FFlogo* logoGetBuiltinDetected(FFLogoSize size) -{ +static const FFlogo* logoGetBuiltinDetected(FFLogoSize size) { const FFOSResult* os = ffDetectOS(); const FFlogo* logo = logoGetBuiltin(&os->id, size); - if(logo != NULL) + if (logo != NULL) { return logo; + } logo = logoGetBuiltin(&os->name, size); - if(logo != NULL) + if (logo != NULL) { return logo; + } - if (ffStrbufContainC(&os->idLike, ' ')) - { + if (ffStrbufContainC(&os->idLike, ' ')) { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); for ( uint32_t start = 0, end = ffStrbufFirstIndexC(&os->idLike, ' '); true; - start = end + 1, end = ffStrbufNextIndexC(&os->idLike, start, ' ') - ) - { + start = end + 1, end = ffStrbufNextIndexC(&os->idLike, start, ' ')) { ffStrbufSetNS(&buf, end - start, os->idLike.chars + start); logo = logoGetBuiltin(&buf, size); - if(logo != NULL) + if (logo != NULL) { return logo; + } - if (end >= os->idLike.length) + if (end >= os->idLike.length) { break; + } } - } - else - { + } else { logo = logoGetBuiltin(&os->idLike, size); - if(logo != NULL) + if (logo != NULL) { return logo; + } } logo = logoGetBuiltin(&instance.state.platform.sysinfo.name, size); - if(logo != NULL) + if (logo != NULL) { return logo; + } return &ffLogoUnknown; } -static void logoPrintStruct(const FFlogo* logo) -{ +static void logoPrintStruct(const FFlogo* logo) { logoApplyColors(logo, true); ffLogoPrintChars(logo->lines, true); } -static void logoPrintNone(void) -{ - if (!instance.config.display.pipe) +static void logoPrintNone(void) { + if (!instance.config.display.pipe) { logoApplyColors(logoGetBuiltinDetected(FF_LOGO_SIZE_NORMAL), false); + } instance.state.logoHeight = 0; instance.state.logoWidth = 0; } -static bool logoPrintBuiltinIfExists(const FFstrbuf* name, FFLogoSize size) -{ - if(name->chars[0] == '~' || name->chars[0] == '.' || name->chars[0] == '/' - #if _WIN32 +static bool logoPrintBuiltinIfExists(const FFstrbuf* name, FFLogoSize size) { + if (name->chars[0] == '~' || name->chars[0] == '.' || name->chars[0] == '/' +#if _WIN32 || (ffCharIsEnglishAlphabet(name->chars[0]) && name->chars[1] == ':') // Windows drive letter - #endif +#endif ) return false; // Paths - if(ffStrbufIgnCaseEqualS(name, "none")) - { + if (ffStrbufIgnCaseEqualS(name, "none")) { logoPrintNone(); return true; } const FFlogo* logo = ffLogoGetBuiltinForName(name, size); - if(logo == NULL) + if (logo == NULL) { return false; + } logoPrintStruct(logo); return true; } -static inline void logoPrintDetected(FFLogoSize size) -{ +static inline void logoPrintDetected(FFLogoSize size) { logoPrintStruct(logoGetBuiltinDetected(size)); } -static bool logoPrintData(bool doColorReplacement, FFstrbuf* source) -{ - if(source->length == 0) +static bool logoPrintData(bool doColorReplacement, FFstrbuf* source) { + if (source->length == 0) { return false; + } logoApplyColors(logoGetBuiltinDetected(FF_LOGO_SIZE_NORMAL), doColorReplacement); ffLogoPrintChars(source->chars, doColorReplacement); return true; } -static bool updateLogoPath(void) -{ +static bool updateLogoPath(void) { FFOptionsLogo* options = &instance.config.logo; - if(ffPathExists(options->source.chars, FF_PATHTYPE_FILE)) + if (ffPathExists(options->source.chars, FF_PATHTYPE_FILE)) { return true; + } - if (ffStrbufEqualS(&options->source, "-")) // stdin + if (ffStrbufEqualS(&options->source, "-")) { // stdin return true; + } - if (ffStrbufIgnCaseEqualS(&options->source, "media-cover")) - { + if (ffStrbufIgnCaseEqualS(&options->source, "media-cover")) { const FFMediaResult* media = ffDetectMedia(true); - if (media->cover.length == 0) + if (media->cover.length == 0) { return false; + } ffStrbufSet(&options->source, &media->cover); return true; } FF_STRBUF_AUTO_DESTROY fullPath = ffStrbufCreateA(128); - if (ffPathExpandEnv(options->source.chars, &fullPath) && ffPathExists(fullPath.chars, FF_PATHTYPE_FILE)) - { + if (ffPathExpandEnv(options->source.chars, &fullPath) && ffPathExists(fullPath.chars, FF_PATHTYPE_FILE)) { ffStrbufDestroy(&options->source); ffStrbufInitMove(&options->source, &fullPath); return true; } - FF_LIST_FOR_EACH(FFstrbuf, dataDir, instance.state.platform.dataDirs) - { - //We need to copy it, because multiple threads might be using dataDirs at the same time + FF_LIST_FOR_EACH (FFstrbuf, dataDir, instance.state.platform.dataDirs) { + // We need to copy it, because multiple threads might be using dataDirs at the same time ffStrbufSet(&fullPath, dataDir); ffStrbufAppendS(&fullPath, "fastfetch/logos/"); ffStrbufAppend(&fullPath, &options->source); - if(ffPathExists(fullPath.chars, FF_PATHTYPE_FILE)) - { + if (ffPathExists(fullPath.chars, FF_PATHTYPE_FILE)) { ffStrbufDestroy(&options->source); ffStrbufInitMove(&options->source, &fullPath); return true; @@ -514,132 +498,129 @@ static bool updateLogoPath(void) return false; } -static bool logoPrintFileIfExists(bool doColorReplacement, bool raw) -{ +static bool logoPrintFileIfExists(bool doColorReplacement, bool raw) { FFOptionsLogo* options = &instance.config.logo; FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); - if(ffStrbufEqualS(&options->source, "-") - ? !ffAppendFDBuffer(FFUnixFD2NativeFD(STDIN_FILENO), &content) - : !ffAppendFileBuffer(options->source.chars, &content) - ) - { - if (instance.config.display.showErrors) + if (ffStrbufEqualS(&options->source, "-") + ? !ffAppendFDBuffer(FFUnixFD2NativeFD(STDIN_FILENO), &content) + : !ffAppendFileBuffer(options->source.chars, &content)) { + if (instance.config.display.showErrors) { fprintf(stderr, "Logo: Failed to load file content from logo source: %s\n", options->source.chars); + } return false; } logoApplyColors(logoGetBuiltinDetected(FF_LOGO_SIZE_NORMAL), doColorReplacement); - if(raw) + if (raw) { return ffLogoPrintCharsRaw(content.chars, content.length, instance.config.display.showErrors); + } ffLogoPrintChars(content.chars, doColorReplacement); return true; } -static bool logoPrintImageIfExists(FFLogoType logo, bool printError) -{ - if(!ffLogoPrintImageIfExists(logo, printError)) +static bool logoPrintImageIfExists(FFLogoType logo, bool printError) { + if (!ffLogoPrintImageIfExists(logo, printError)) { return false; + } logoApplyColors(logoGetBuiltinDetected(FF_LOGO_SIZE_NORMAL), false); return true; } -static bool logoTryKnownType(void) -{ +static bool logoTryKnownType(void) { FFOptionsLogo* options = &instance.config.logo; - if(options->type == FF_LOGO_TYPE_NONE) - { + if (options->type == FF_LOGO_TYPE_NONE) { logoPrintNone(); return true; } - if(options->type == FF_LOGO_TYPE_BUILTIN) + if (options->type == FF_LOGO_TYPE_BUILTIN) { return logoPrintBuiltinIfExists(&options->source, FF_LOGO_SIZE_UNKNOWN); + } - if(options->type == FF_LOGO_TYPE_SMALL) + if (options->type == FF_LOGO_TYPE_SMALL) { return logoPrintBuiltinIfExists(&options->source, FF_LOGO_SIZE_SMALL); + } - if(options->type == FF_LOGO_TYPE_DATA) + if (options->type == FF_LOGO_TYPE_DATA) { return logoPrintData(true, &options->source); + } - if(options->type == FF_LOGO_TYPE_DATA_RAW) + if (options->type == FF_LOGO_TYPE_DATA_RAW) { return logoPrintData(false, &options->source); + } - if(options->type == FF_LOGO_TYPE_COMMAND_RAW) - { + if (options->type == FF_LOGO_TYPE_COMMAND_RAW) { FF_STRBUF_AUTO_DESTROY source = ffStrbufCreate(); - const char* error = ffProcessAppendStdOut(&source, (char* const[]){ - #ifdef _WIN32 - "cmd.exe", "/c", - #else - "/bin/sh", "-c", - #endif - options->source.chars, - NULL - }); + const char* error = ffProcessAppendStdOut(&source, (char* const[]) { +#ifdef _WIN32 + "cmd.exe", "/c", +#else + "/bin/sh", "-c", +#endif + options->source.chars, + NULL}); - if (error) - { - if (instance.config.display.showErrors) + if (error) { + if (instance.config.display.showErrors) { fprintf(stderr, "Logo: failed to execute command `%s`: %s\n", options->source.chars, error); + } return false; } return logoPrintData(false, &source); } - //We sure have a file, resolve relative paths - if (!updateLogoPath()) - { - if (instance.config.display.showErrors) + // We sure have a file, resolve relative paths + if (!updateLogoPath()) { + if (instance.config.display.showErrors) { fprintf(stderr, "Logo: Failed to resolve logo source: %s\n", options->source.chars); + } return false; } - if(options->type == FF_LOGO_TYPE_FILE) + if (options->type == FF_LOGO_TYPE_FILE) { return logoPrintFileIfExists(true, false); + } - if(options->type == FF_LOGO_TYPE_FILE_RAW) + if (options->type == FF_LOGO_TYPE_FILE_RAW) { return logoPrintFileIfExists(false, false); + } - if(options->type == FF_LOGO_TYPE_IMAGE_RAW) + if (options->type == FF_LOGO_TYPE_IMAGE_RAW) { return logoPrintFileIfExists(false, true); + } return logoPrintImageIfExists(options->type, instance.config.display.showErrors); } -void ffLogoPrint(void) -{ +void ffLogoPrint(void) { const FFOptionsLogo* options = &instance.config.logo; - if (options->type == FF_LOGO_TYPE_NONE) - { + if (options->type == FF_LOGO_TYPE_NONE) { logoPrintNone(); return; } - //If the source is not set, we can directly print the detected logo. - if(options->source.length == 0) - { + // If the source is not set, we can directly print the detected logo. + if (options->source.length == 0) { logoPrintDetected(options->type == FF_LOGO_TYPE_SMALL ? FF_LOGO_SIZE_SMALL : FF_LOGO_SIZE_NORMAL); return; } - //If the source and source type is set to something else than auto, always print with the set type. - if(options->source.length > 0 && options->type != FF_LOGO_TYPE_AUTO) - { - if(!logoTryKnownType()) - { - if (instance.config.display.showErrors) - { + // If the source and source type is set to something else than auto, always print with the set type. + if (options->source.length > 0 && options->type != FF_LOGO_TYPE_AUTO) { + if (!logoTryKnownType()) { + if (instance.config.display.showErrors) { // Image logo should have been handled - if(options->type == FF_LOGO_TYPE_BUILTIN || options->type == FF_LOGO_TYPE_SMALL) + if (options->type == FF_LOGO_TYPE_BUILTIN || options->type == FF_LOGO_TYPE_SMALL) { fprintf(stderr, "Logo: Failed to load %s logo: %s\n", options->type == FF_LOGO_TYPE_BUILTIN ? "builtin" : "builtin small", options->source.chars); + } } logoPrintDetected(FF_LOGO_SIZE_UNKNOWN); @@ -647,134 +628,128 @@ void ffLogoPrint(void) return; } - //If source matches the name of a builtin logo, print it and return. - if(logoPrintBuiltinIfExists(&options->source, FF_LOGO_SIZE_UNKNOWN)) + // If source matches the name of a builtin logo, print it and return. + if (logoPrintBuiltinIfExists(&options->source, FF_LOGO_SIZE_UNKNOWN)) { return; + } - //Make sure the logo path is set correctly. - if (updateLogoPath()) - { - if (ffStrbufEndsWithIgnCaseS(&options->source, ".raw")) - { - if(logoPrintFileIfExists(false, true)) + // Make sure the logo path is set correctly. + if (updateLogoPath()) { + if (ffStrbufEndsWithIgnCaseS(&options->source, ".raw")) { + if (logoPrintFileIfExists(false, true)) { return; + } } - if (!ffStrbufEndsWithIgnCaseS(&options->source, ".txt")) - { + if (!ffStrbufEndsWithIgnCaseS(&options->source, ".txt")) { const FFTerminalResult* terminal = ffDetectTerminal(); - //Terminal emulators that support kitty graphics protocol. + // Terminal emulators that support kitty graphics protocol. bool supportsKitty = ffStrbufIgnCaseEqualS(&terminal->processName, "kitty") || ffStrbufIgnCaseEqualS(&terminal->processName, "konsole") || ffStrbufIgnCaseEqualS(&terminal->processName, "wezterm") || ffStrbufIgnCaseEqualS(&terminal->processName, "wayst") || ffStrbufIgnCaseEqualS(&terminal->processName, "ghostty") || - #ifdef __APPLE__ +#ifdef __APPLE__ ffStrbufIgnCaseEqualS(&terminal->processName, "WarpTerminal") || - #else +#else ffStrbufIgnCaseEqualS(&terminal->processName, "warp") || - #endif +#endif false; - //Try to load the logo as an image. If it succeeds, print it and return. - if(logoPrintImageIfExists(supportsKitty ? FF_LOGO_TYPE_IMAGE_KITTY : FF_LOGO_TYPE_IMAGE_CHAFA, false)) + // Try to load the logo as an image. If it succeeds, print it and return. + if (logoPrintImageIfExists(supportsKitty ? FF_LOGO_TYPE_IMAGE_KITTY : FF_LOGO_TYPE_IMAGE_CHAFA, false)) { return; + } } - //Try to load the logo as a file. If it succeeds, print it and return. - if(logoPrintFileIfExists(true, false)) + // Try to load the logo as a file. If it succeeds, print it and return. + if (logoPrintFileIfExists(true, false)) { return; - } - else - { - if (instance.config.display.showErrors) + } + } else { + if (instance.config.display.showErrors) { fprintf(stderr, "Logo: Failed to resolve logo source: %s\n", options->source.chars); + } } logoPrintDetected(FF_LOGO_SIZE_UNKNOWN); } -void ffLogoPrintLine(void) -{ - if(instance.state.logoWidth > 0) +void ffLogoPrintLine(void) { + if (instance.state.logoWidth > 0) { printf("\033[%uC", instance.state.logoWidth); + } - if (instance.state.dynamicInterval > 0) + if (instance.state.dynamicInterval > 0) { fputs("\033[K", stdout); // Clear to the end of the line + } ++instance.state.keysHeight; } -void ffLogoPrintRemaining(void) -{ - if (instance.state.keysHeight <= instance.state.logoHeight) +void ffLogoPrintRemaining(void) { + if (instance.state.keysHeight <= instance.state.logoHeight) { ffPrintCharTimes('\n', instance.state.logoHeight - instance.state.keysHeight + 1); + } instance.state.keysHeight = instance.state.logoHeight + 1; } -void ffLogoBuiltinPrint(void) -{ +void ffLogoBuiltinPrint(void) { FFOptionsLogo* options = &instance.config.logo; options->position = FF_LOGO_POSITION_TOP; options->paddingRight = 2; // empty line after logo printing FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - for(uint8_t ch = 0; ch < 26; ++ch) - { - for(const FFlogo* logo = ffLogoBuiltins[ch]; *logo->names; ++logo) - { - if (instance.config.display.pipe) + for (uint8_t ch = 0; ch < 26; ++ch) { + for (const FFlogo* logo = ffLogoBuiltins[ch]; *logo->names; ++logo) { + if (instance.config.display.pipe) { ffStrbufSetF(&buf, "%s:\n", logo->names[0]); - else + } else { ffStrbufSetF(&buf, "\e[%sm%s:\e[0m\n", logo->colors[0], logo->names[0]); + } ffWriteFDBuffer(FFUnixFD2NativeFD(STDOUT_FILENO), &buf); logoPrintStruct(logo); - for(uint8_t i = 0; i < FASTFETCH_LOGO_MAX_COLORS; i++) + for (uint8_t i = 0; i < FASTFETCH_LOGO_MAX_COLORS; i++) { ffStrbufClear(&options->colors[i]); + } } } } -void ffLogoBuiltinList(void) -{ +void ffLogoBuiltinList(void) { uint32_t counter = 0; - for(uint8_t ch = 0; ch < 26; ++ch) - { - for(const FFlogo* logo = ffLogoBuiltins[ch]; *logo->names; ++logo) - { + for (uint8_t ch = 0; ch < 26; ++ch) { + for (const FFlogo* logo = ffLogoBuiltins[ch]; *logo->names; ++logo) { ++counter; printf("%u)%s ", counter, counter < 10 ? " " : ""); - for( + for ( const char* const* names = logo->names; *names != NULL && names <= &logo->names[FASTFETCH_LOGO_MAX_NAMES]; - ++names - ) + ++names) { printf("\"%s\" ", *names); + } putchar('\n'); } } } -void ffLogoBuiltinListAutocompletion(void) -{ - for(uint8_t ch = 0; ch < 26; ++ch) - { - for(const FFlogo* logo = ffLogoBuiltins[ch]; *logo->names; ++logo) +void ffLogoBuiltinListAutocompletion(void) { + for (uint8_t ch = 0; ch < 26; ++ch) { + for (const FFlogo* logo = ffLogoBuiltins[ch]; *logo->names; ++logo) { printf("%s\n", logo->names[0]); + } } } -const FFlogo* ffLogoGetBuiltinForName(const FFstrbuf* name, FFLogoSize size) -{ +const FFlogo* ffLogoGetBuiltinForName(const FFstrbuf* name, FFLogoSize size) { return ffStrbufEqualS(name, "?") ? &ffLogoUnknown : logoGetBuiltin(name, size); } -const FFlogo* ffLogoGetBuiltinDetected(FFLogoSize size) -{ +const FFlogo* ffLogoGetBuiltinDetected(FFLogoSize size) { return logoGetBuiltinDetected(size); } diff --git a/src/logo/logo.h b/src/logo/logo.h index e36047509..193c76d7f 100644 --- a/src/logo/logo.h +++ b/src/logo/logo.h @@ -2,23 +2,20 @@ #include "fastfetch.h" -typedef enum __attribute__((__packed__)) FFLogoLineType -{ +typedef enum __attribute__((__packed__)) FFLogoLineType { FF_LOGO_LINE_TYPE_NORMAL = 0, FF_LOGO_LINE_TYPE_SMALL_BIT = 1 << 0, // The names of small logo must end with `_small` or `-small` FF_LOGO_LINE_TYPE_ALTER_BIT = 1 << 1, FF_LOGO_LINE_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFLogoLineType; -typedef enum __attribute__((__packed__)) FFLogoSize -{ +typedef enum __attribute__((__packed__)) FFLogoSize { FF_LOGO_SIZE_UNKNOWN, FF_LOGO_SIZE_NORMAL, FF_LOGO_SIZE_SMALL, } FFLogoSize; -typedef struct FFlogo -{ +typedef struct FFlogo { const char* lines; const char* names[FASTFETCH_LOGO_MAX_NAMES]; const char* colors[FASTFETCH_LOGO_MAX_COLORS]; @@ -27,7 +24,7 @@ typedef struct FFlogo FFLogoLineType type; } FFlogo; -//logo.c +// logo.c void ffLogoPrint(void); void ffLogoPrintChars(const char* data, bool doColorReplacement); void ffLogoPrintLine(void); @@ -38,9 +35,9 @@ void ffLogoBuiltinListAutocompletion(void); const FFlogo* ffLogoGetBuiltinForName(const FFstrbuf* name, FFLogoSize size); const FFlogo* ffLogoGetBuiltinDetected(FFLogoSize size); -//builtin.c +// builtin.c extern const FFlogo* ffLogoBuiltins[]; extern const FFlogo ffLogoUnknown; -//image/image.c +// image/image.c bool ffLogoPrintImageIfExists(FFLogoType type, bool printError); diff --git a/src/modules/battery/battery.c b/src/modules/battery/battery.c index a74162b5d..ea19ff176 100644 --- a/src/modules/battery/battery.c +++ b/src/modules/battery/battery.c @@ -7,30 +7,26 @@ #include "detection/battery/battery.h" #include "modules/battery/battery.h" -static void printBattery(FFBatteryOptions* options, FFBatteryResult* result, uint8_t index) -{ +static void printBattery(FFBatteryOptions* options, FFBatteryResult* result, uint8_t index) { FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); - if (options->moduleArgs.key.length == 0) - { - if (result->modelName.length > 0) + if (options->moduleArgs.key.length == 0) { + if (result->modelName.length > 0) { ffStrbufSetF(&key, "%s (%s)", FF_BATTERY_MODULE_NAME, result->modelName.chars); - else + } else { ffStrbufSetS(&key, FF_BATTERY_MODULE_NAME); - } - else - { + } + } else { ffStrbufClear(&key); FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(result->modelName, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(result->modelName, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); @@ -39,51 +35,47 @@ static void printBattery(FFBatteryOptions* options, FFBatteryResult* result, uin result->status.length > 0 && ffStrbufIgnCaseCompS(&result->status, "Unknown") != 0; - if(result->capacity >= 0) - { - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + if (result->capacity >= 0) { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&str, result->capacity, options->percent, &options->moduleArgs); } - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) - { - if(str.length > 0) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { + if (str.length > 0) { ffStrbufAppendC(&str, ' '); + } ffPercentAppendNum(&str, result->capacity, options->percent, str.length > 0, &options->moduleArgs); } - if(result->timeRemaining > 0) - { - if(str.length > 0) + if (result->timeRemaining > 0) { + if (str.length > 0) { ffStrbufAppendS(&str, " ("); + } ffDurationAppendNum((uint32_t) result->timeRemaining, &str); ffStrbufAppendS(&str, " remaining)"); } } - if(showStatus) - { - if(str.length > 0) + if (showStatus) { + if (str.length > 0) { ffStrbufAppendF(&str, " [%s]", result->status.chars); - else + } else { ffStrbufAppend(&str, &result->status); + } } - if(result->temperature != FF_BATTERY_TEMP_UNSET) - { - if(str.length > 0) + if (result->temperature != FF_BATTERY_TEMP_UNSET) { + if (str.length > 0) { ffStrbufAppendS(&str, " - "); + } ffTempsAppendNum(result->temperature, &str, options->tempConfig, &options->moduleArgs); } ffStrbufPutTo(&str, stdout); - } - else - { + } else { uint32_t timeRemaining = result->timeRemaining < 0 ? 0 : (uint32_t) result->timeRemaining; uint32_t seconds = timeRemaining % 60; timeRemaining /= 60; @@ -94,62 +86,60 @@ static void printBattery(FFBatteryOptions* options, FFBatteryResult* result, uin uint32_t days = timeRemaining; FF_STRBUF_AUTO_DESTROY capacityNum = ffStrbufCreate(); - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&capacityNum, result->capacity, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY capacityBar = ffStrbufCreate(); - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&capacityBar, result->capacity, options->percent, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY tempStr = ffStrbufCreate(); ffTempsAppendNum(result->temperature, &tempStr, options->tempConfig, &options->moduleArgs); FF_STRBUF_AUTO_DESTROY timeStr = ffStrbufCreate(); - if (result->timeRemaining > 0) + if (result->timeRemaining > 0) { ffDurationAppendNum((uint32_t) result->timeRemaining, &timeStr); + } FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(result->manufacturer, "manufacturer"), - FF_ARG(result->modelName, "model-name"), - FF_ARG(result->technology, "technology"), - FF_ARG(capacityNum, "capacity"), - FF_ARG(result->status, "status"), - FF_ARG(tempStr, "temperature"), - FF_ARG(result->cycleCount, "cycle-count"), - FF_ARG(result->serial, "serial"), - FF_ARG(result->manufactureDate, "manufacture-date"), - FF_ARG(capacityBar, "capacity-bar"), - FF_ARG(days, "time-days"), - FF_ARG(hours, "time-hours"), - FF_ARG(minutes, "time-minutes"), - FF_ARG(seconds, "time-seconds"), - FF_ARG(timeStr, "time-formatted"), - })); + FF_ARG(result->manufacturer, "manufacturer"), + FF_ARG(result->modelName, "model-name"), + FF_ARG(result->technology, "technology"), + FF_ARG(capacityNum, "capacity"), + FF_ARG(result->status, "status"), + FF_ARG(tempStr, "temperature"), + FF_ARG(result->cycleCount, "cycle-count"), + FF_ARG(result->serial, "serial"), + FF_ARG(result->manufactureDate, "manufacture-date"), + FF_ARG(capacityBar, "capacity-bar"), + FF_ARG(days, "time-days"), + FF_ARG(hours, "time-hours"), + FF_ARG(minutes, "time-minutes"), + FF_ARG(seconds, "time-seconds"), + FF_ARG(timeStr, "time-formatted"), + })); } } -bool ffPrintBattery(FFBatteryOptions* options) -{ +bool ffPrintBattery(FFBatteryOptions* options) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFBatteryResult)); const char* error = ffDetectBattery(options, &results); - if (error) - { + if (error) { ffPrintError(FF_BATTERY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(results.length == 0) - { + if (results.length == 0) { ffPrintError(FF_BATTERY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", "No batteries found"); return false; } - for(uint32_t i = 0; i < results.length; i++) - { + for (uint32_t i = 0; i < results.length; i++) { FFBatteryResult* result = FF_LIST_GET(FFBatteryResult, results, i); printBattery(options, result, results.length == 1 ? 0 : (uint8_t) (i + 1)); } - FF_LIST_FOR_EACH(FFBatteryResult, result, results) - { + FF_LIST_FOR_EACH (FFBatteryResult, result, results) { ffStrbufDestroy(&result->manufacturer); ffStrbufDestroy(&result->modelName); ffStrbufDestroy(&result->technology); @@ -160,60 +150,56 @@ bool ffPrintBattery(FFBatteryOptions* options) return true; } -void ffParseBatteryJsonObject(FFBatteryOptions* options, yyjson_val* module) -{ +void ffParseBatteryJsonObject(FFBatteryOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - #ifdef _WIN32 - if (unsafe_yyjson_equals_str(key, "useSetupApi")) - { +#ifdef _WIN32 + if (unsafe_yyjson_equals_str(key, "useSetupApi")) { options->useSetupApi = yyjson_get_bool(val); continue; } - #endif +#endif - if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) + if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) { continue; + } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_BATTERY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBatteryJsonConfig(FFBatteryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBatteryJsonConfig(FFBatteryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - #ifdef _WIN32 - yyjson_mut_obj_add_bool(doc, module, "useSetupApi", options->useSetupApi); - #endif +#ifdef _WIN32 + yyjson_mut_obj_add_bool(doc, module, "useSetupApi", options->useSetupApi); +#endif ffTempsGenerateJsonConfig(doc, module, options->temp, options->tempConfig); ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateBatteryJsonResult(FFBatteryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBatteryJsonResult(FFBatteryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFBatteryResult)); const char* error = ffDetectBattery(options, &results); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFBatteryResult, battery, results) - { + FF_LIST_FOR_EACH (FFBatteryResult, battery, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_real(doc, obj, "capacity", battery->capacity); yyjson_mut_obj_add_strbuf(doc, obj, "manufacturer", &battery->manufacturer); @@ -222,19 +208,20 @@ bool ffGenerateBatteryJsonResult(FFBatteryOptions* options, yyjson_mut_doc* doc, yyjson_mut_obj_add_strbuf(doc, obj, "status", &battery->status); yyjson_mut_obj_add_strbuf(doc, obj, "technology", &battery->technology); yyjson_mut_obj_add_strbuf(doc, obj, "serial", &battery->serial); - if (battery->temperature != FF_BATTERY_TEMP_UNSET) + if (battery->temperature != FF_BATTERY_TEMP_UNSET) { yyjson_mut_obj_add_real(doc, obj, "temperature", battery->temperature); - else + } else { yyjson_mut_obj_add_null(doc, obj, "temperature"); + } yyjson_mut_obj_add_uint(doc, obj, "cycleCount", battery->cycleCount); - if (battery->timeRemaining > 0) + if (battery->timeRemaining > 0) { yyjson_mut_obj_add_int(doc, obj, "timeRemaining", battery->timeRemaining); - else + } else { yyjson_mut_obj_add_null(doc, obj, "timeRemaining"); + } } - FF_LIST_FOR_EACH(FFBatteryResult, battery, results) - { + FF_LIST_FOR_EACH (FFBatteryResult, battery, results) { ffStrbufDestroy(&battery->manufacturer); ffStrbufDestroy(&battery->manufactureDate); ffStrbufDestroy(&battery->modelName); @@ -246,20 +233,18 @@ bool ffGenerateBatteryJsonResult(FFBatteryOptions* options, yyjson_mut_doc* doc, return true; } -void ffInitBatteryOptions(FFBatteryOptions* options) -{ +void ffInitBatteryOptions(FFBatteryOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); options->temp = false; - options->tempConfig = (FFColorRangeConfig) { 60, 80 }; - options->percent = (FFPercentageModuleConfig) { 50, 20, 0 }; + options->tempConfig = (FFColorRangeConfig) {60, 80}; + options->percent = (FFPercentageModuleConfig) {50, 20, 0}; - #ifdef _WIN32 - options->useSetupApi = false; - #endif +#ifdef _WIN32 + options->useSetupApi = false; +#endif } -void ffDestroyBatteryOptions(FFBatteryOptions* options) -{ +void ffDestroyBatteryOptions(FFBatteryOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -288,5 +273,4 @@ FFModuleBaseInfo ffBatteryModuleInfo = { {"Battery time remaining minutes", "time-minutes"}, {"Battery time remaining seconds", "time-seconds"}, {"Battery time remaining (formatted)", "time-formatted"}, - })) -}; + }))}; diff --git a/src/modules/battery/option.h b/src/modules/battery/option.h index 1ac5b97be..9f01ffb66 100644 --- a/src/modules/battery/option.h +++ b/src/modules/battery/option.h @@ -3,17 +3,16 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFBatteryOptions -{ +typedef struct FFBatteryOptions { FFModuleArgs moduleArgs; bool temp; FFColorRangeConfig tempConfig; FFPercentageModuleConfig percent; - #ifdef _WIN32 - bool useSetupApi; - #endif +#ifdef _WIN32 + bool useSetupApi; +#endif } FFBatteryOptions; static_assert(sizeof(FFBatteryOptions) <= FF_OPTION_MAX_SIZE, "FFBatteryOptions size exceeds maximum allowed size"); diff --git a/src/modules/bios/bios.c b/src/modules/bios/bios.c index 576d95131..5c7923ed4 100644 --- a/src/modules/bios/bios.c +++ b/src/modules/bios/bios.c @@ -4,8 +4,7 @@ #include "detection/bios/bios.h" #include "modules/bios/bios.h" -bool ffPrintBios(FFBiosOptions* options) -{ +bool ffPrintBios(FFBiosOptions* options) { bool success = false; FFBiosResult bios; ffStrbufInit(&bios.date); @@ -18,54 +17,48 @@ bool ffPrintBios(FFBiosOptions* options) FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); - if(error) - { + if (error) { ffPrintError(FF_BIOS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if(bios.version.length == 0) - { + if (bios.version.length == 0) { ffPrintError(FF_BIOS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "bios_version is not set."); goto exit; } - if(options->moduleArgs.key.length == 0) - { - if(bios.type.length == 0) + if (options->moduleArgs.key.length == 0) { + if (bios.type.length == 0) { ffStrbufSetStatic(&bios.type, "Unknown"); - else if (ffStrbufIgnCaseEqualS(&bios.type, "BIOS")) + } else if (ffStrbufIgnCaseEqualS(&bios.type, "BIOS")) { ffStrbufSetStatic(&bios.type, "Legacy"); + } ffStrbufSetF(&key, FF_BIOS_MODULE_NAME " (%s)", bios.type.chars); - } - else - { + } else { ffStrbufClear(&key); FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(bios.type, "type"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(bios.type, "type"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffStrbufWriteTo(&bios.version, stdout); - if (bios.release.length) + if (bios.release.length) { printf(" (%s)\n", bios.release.chars); - else + } else { putchar('\n'); - } - else - { + } + } else { FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(bios.date, "date"), - FF_ARG(bios.release, "release"), - FF_ARG(bios.vendor, "vendor"), - FF_ARG(bios.version, "version"), - FF_ARG(bios.type, "type"), - })); + FF_ARG(bios.date, "date"), + FF_ARG(bios.release, "release"), + FF_ARG(bios.vendor, "vendor"), + FF_ARG(bios.version, "version"), + FF_ARG(bios.type, "type"), + })); } success = true; @@ -79,26 +72,23 @@ exit: return success; } -void ffParseBiosJsonObject(FFBiosOptions* options, yyjson_val* module) -{ +void ffParseBiosJsonObject(FFBiosOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_BIOS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBiosJsonConfig(FFBiosOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBiosJsonConfig(FFBiosOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBiosJsonResult(FF_MAYBE_UNUSED FFBiosOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBiosJsonResult(FF_MAYBE_UNUSED FFBiosOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFBiosResult bios; ffStrbufInit(&bios.date); @@ -109,8 +99,7 @@ bool ffGenerateBiosJsonResult(FF_MAYBE_UNUSED FFBiosOptions* options, yyjson_mut const char* error = ffDetectBios(&bios); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } @@ -132,13 +121,11 @@ exit: return success; } -void ffInitBiosOptions(FFBiosOptions* options) -{ +void ffInitBiosOptions(FFBiosOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyBiosOptions(FFBiosOptions* options) -{ +void ffDestroyBiosOptions(FFBiosOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -157,5 +144,4 @@ FFModuleBaseInfo ffBiosModuleInfo = { {"Bios vendor", "vendor"}, {"Bios version", "version"}, {"Firmware type", "type"}, - })) -}; + }))}; diff --git a/src/modules/bios/option.h b/src/modules/bios/option.h index 000803569..aae4c8c16 100644 --- a/src/modules/bios/option.h +++ b/src/modules/bios/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFBiosOptions -{ +typedef struct FFBiosOptions { FFModuleArgs moduleArgs; } FFBiosOptions; diff --git a/src/modules/bluetooth/bluetooth.c b/src/modules/bluetooth/bluetooth.c index 3534103a3..04e1f3628 100644 --- a/src/modules/bluetooth/bluetooth.c +++ b/src/modules/bluetooth/bluetooth.c @@ -5,91 +5,85 @@ #include "detection/bluetooth/bluetooth.h" #include "modules/bluetooth/bluetooth.h" -static void printDevice(FFBluetoothOptions* options, const FFBluetoothResult* device, uint8_t index) -{ +static void printDevice(FFBluetoothOptions* options, const FFBluetoothResult* device, uint8_t index) { FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_BLUETOOTH_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); bool showBatteryLevel = device->battery > 0 && device->battery <= 100; - if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_BAR_BIT)) - { + if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_BAR_BIT)) { ffPercentAppendBar(&buffer, device->battery, options->percent, &options->moduleArgs); ffStrbufAppendC(&buffer, ' '); } - if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppend(&buffer, &device->name); + } - if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_NUM_BIT)) - { - if (buffer.length) + if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_NUM_BIT)) { + if (buffer.length) { ffStrbufAppendC(&buffer, ' '); + } ffPercentAppendNum(&buffer, device->battery, options->percent, buffer.length > 0, &options->moduleArgs); } - if (!device->connected) + if (!device->connected) { ffStrbufAppendS(&buffer, " [disconnected]"); + } ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY percentageNum = ffStrbufCreate(); - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&percentageNum, device->battery, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY percentageBar = ffStrbufCreate(); - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&percentageBar, device->battery, options->percent, &options->moduleArgs); + } FF_PRINT_FORMAT_CHECKED(FF_BLUETOOTH_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(device->name, "name"), - FF_ARG(device->address, "address"), - FF_ARG(device->type, "type"), - FF_ARG(percentageNum, "battery-percentage"), - FF_ARG(device->connected, "connected"), - FF_ARG(percentageBar, "battery-percentage-bar"), - })); + FF_ARG(device->name, "name"), + FF_ARG(device->address, "address"), + FF_ARG(device->type, "type"), + FF_ARG(percentageNum, "battery-percentage"), + FF_ARG(device->connected, "connected"), + FF_ARG(percentageBar, "battery-percentage-bar"), + })); } } -bool ffPrintBluetooth(FFBluetoothOptions* options) -{ - FF_LIST_AUTO_DESTROY devices = ffListCreate(sizeof (FFBluetoothResult)); +bool ffPrintBluetooth(FFBluetoothOptions* options) { + FF_LIST_AUTO_DESTROY devices = ffListCreate(sizeof(FFBluetoothResult)); const char* error = ffDetectBluetooth(options, &devices); - if(error) - { + if (error) { ffPrintError(FF_BLUETOOTH_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } FF_LIST_AUTO_DESTROY filtered = ffListCreate(sizeof(FFBluetoothResult*)); - FF_LIST_FOR_EACH(FFBluetoothResult, device, devices) - { - if(!device->connected && !options->showDisconnected) + FF_LIST_FOR_EACH (FFBluetoothResult, device, devices) { + if (!device->connected && !options->showDisconnected) { continue; + } - *(FFBluetoothResult**)ffListAdd(&filtered) = device; + *(FFBluetoothResult**) ffListAdd(&filtered) = device; } - if(filtered.length == 0) - { + if (filtered.length == 0) { ffPrintError(FF_BLUETOOTH_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No bluetooth devices found"); } - for(uint32_t i = 0; i < filtered.length; i++) - { + for (uint32_t i = 0; i < filtered.length; i++) { uint8_t index = (uint8_t) (filtered.length == 1 ? 0 : i + 1); printDevice(options, *FF_LIST_GET(FFBluetoothResult*, filtered, i), index); } - FF_LIST_FOR_EACH(FFBluetoothResult, device, devices) - { + FF_LIST_FOR_EACH (FFBluetoothResult, device, devices) { ffStrbufDestroy(&device->name); ffStrbufDestroy(&device->type); ffStrbufDestroy(&device->address); @@ -97,30 +91,28 @@ bool ffPrintBluetooth(FFBluetoothOptions* options) return true; } -void ffParseBluetoothJsonObject(FFBluetoothOptions* options, yyjson_val* module) -{ +void ffParseBluetoothJsonObject(FFBluetoothOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "showDisconnected")) - { + if (unsafe_yyjson_equals_str(key, "showDisconnected")) { options->showDisconnected = yyjson_get_bool(val); continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_BLUETOOTH_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBluetoothJsonConfig(FFBluetoothOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBluetoothJsonConfig(FFBluetoothOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "showDisconnected", options->showDisconnected); @@ -128,21 +120,18 @@ void ffGenerateBluetoothJsonConfig(FFBluetoothOptions* options, yyjson_mut_doc* ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateBluetoothJsonResult(FFBluetoothOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBluetoothJsonResult(FFBluetoothOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFBluetoothResult)); const char* error = ffDetectBluetooth(options, &results); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFBluetoothResult, item, results) - { + FF_LIST_FOR_EACH (FFBluetoothResult, item, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "address", &item->address); yyjson_mut_obj_add_uint(doc, obj, "battery", item->battery); @@ -151,8 +140,7 @@ bool ffGenerateBluetoothJsonResult(FFBluetoothOptions* options, yyjson_mut_doc* yyjson_mut_obj_add_strbuf(doc, obj, "type", &item->type); } - FF_LIST_FOR_EACH(FFBluetoothResult, device, results) - { + FF_LIST_FOR_EACH (FFBluetoothResult, device, results) { ffStrbufDestroy(&device->name); ffStrbufDestroy(&device->type); ffStrbufDestroy(&device->address); @@ -160,15 +148,13 @@ bool ffGenerateBluetoothJsonResult(FFBluetoothOptions* options, yyjson_mut_doc* return true; } -void ffInitBluetoothOptions(FFBluetoothOptions* options) -{ +void ffInitBluetoothOptions(FFBluetoothOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); options->showDisconnected = false; - options->percent = (FFPercentageModuleConfig) { 50, 20, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 20, 0}; } -void ffDestroyBluetoothOptions(FFBluetoothOptions* options) -{ +void ffDestroyBluetoothOptions(FFBluetoothOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -188,5 +174,4 @@ FFModuleBaseInfo ffBluetoothModuleInfo = { {"Battery percentage number", "battery-percentage"}, {"Is connected", "connected"}, {"Battery percentage bar", "battery-percentage-bar"}, - })) -}; + }))}; diff --git a/src/modules/bluetooth/option.h b/src/modules/bluetooth/option.h index 516c0d8b4..1f11d295c 100644 --- a/src/modules/bluetooth/option.h +++ b/src/modules/bluetooth/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFBluetoothOptions -{ +typedef struct FFBluetoothOptions { FFModuleArgs moduleArgs; bool showDisconnected; diff --git a/src/modules/bluetoothradio/bluetoothradio.c b/src/modules/bluetoothradio/bluetoothradio.c index eda2466c2..9ef4a6641 100644 --- a/src/modules/bluetoothradio/bluetoothradio.c +++ b/src/modules/bluetoothradio/bluetoothradio.c @@ -7,97 +7,115 @@ #define FF_BLUETOOTHRADIO_DISPLAY_NAME "Bluetooth Radio" -static void printDevice(FFBluetoothRadioOptions* options, const FFBluetoothRadioResult* radio, uint8_t index) -{ +static void printDevice(FFBluetoothRadioOptions* options, const FFBluetoothRadioResult* radio, uint8_t index) { FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); - if (options->moduleArgs.key.length == 0) - { + if (options->moduleArgs.key.length == 0) { ffStrbufAppendF(&key, "%s (%s)", FF_BLUETOOTHRADIO_DISPLAY_NAME, radio->name.chars); - } - else - { + } else { FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(radio->name, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(radio->name, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } const char* version = NULL; - switch (radio->lmpVersion < 0 ? -radio->lmpVersion : radio->lmpVersion) - { - case 0: version = "1.0b"; break; - case 1: version = "1.1"; break; - case 2: version = "1.2"; break; - case 3: version = "2.0"; break; - case 4: version = "2.1"; break; - case 5: version = "3.0"; break; - case 6: version = "4.0"; break; - case 7: version = "4.1"; break; - case 8: version = "4.2"; break; - case 9: version = "5.0"; break; - case 10: version = "5.1"; break; - case 11: version = "5.2"; break; - case 12: version = "5.3"; break; - case 13: version = "5.4"; break; + switch (radio->lmpVersion < 0 ? -radio->lmpVersion : radio->lmpVersion) { + case 0: + version = "1.0b"; + break; + case 1: + version = "1.1"; + break; + case 2: + version = "1.2"; + break; + case 3: + version = "2.0"; + break; + case 4: + version = "2.1"; + break; + case 5: + version = "3.0"; + break; + case 6: + version = "4.0"; + break; + case 7: + version = "4.1"; + break; + case 8: + version = "4.2"; + break; + case 9: + version = "5.0"; + break; + case 10: + version = "5.1"; + break; + case 11: + version = "5.2"; + break; + case 12: + version = "5.3"; + break; + case 13: + version = "5.4"; + break; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); - if (version) + if (version) { printf("Bluetooth %s%s (%s)\n", version, (radio->lmpVersion < 0 ? "+" : ""), radio->vendor.chars); - else + } else { ffStrbufPutTo(&radio->vendor, stdout); - } - else - { + } + } else { FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(radio->name, "name"), - FF_ARG(radio->address, "address"), - FF_ARG(radio->lmpVersion, "lmp-version"), - FF_ARG(radio->lmpSubversion, "lmp-subversion"), - FF_ARG(version, "version"), - FF_ARG(radio->vendor, "vendor"), - FF_ARG(radio->discoverable, "discoverable"), - FF_ARG(radio->connectable, "connectable"), - })); + FF_ARG(radio->name, "name"), + FF_ARG(radio->address, "address"), + FF_ARG(radio->lmpVersion, "lmp-version"), + FF_ARG(radio->lmpSubversion, "lmp-subversion"), + FF_ARG(version, "version"), + FF_ARG(radio->vendor, "vendor"), + FF_ARG(radio->discoverable, "discoverable"), + FF_ARG(radio->connectable, "connectable"), + })); } } -bool ffPrintBluetoothRadio(FFBluetoothRadioOptions* options) -{ - FF_LIST_AUTO_DESTROY radios = ffListCreate(sizeof (FFBluetoothRadioResult)); +bool ffPrintBluetoothRadio(FFBluetoothRadioOptions* options) { + FF_LIST_AUTO_DESTROY radios = ffListCreate(sizeof(FFBluetoothRadioResult)); const char* error = ffDetectBluetoothRadio(&radios); - if(error) - { + if (error) { ffPrintError(FF_BLUETOOTHRADIO_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } uint8_t index = 0; - FF_LIST_FOR_EACH(FFBluetoothRadioResult, radio, radios) - { - if (!radio->enabled) + FF_LIST_FOR_EACH (FFBluetoothRadioResult, radio, radios) { + if (!radio->enabled) { continue; + } index++; printDevice(options, radio, index); } - if (index == 0) - { - if (radios.length > 0) + if (index == 0) { + if (radios.length > 0) { ffPrintError(FF_BLUETOOTHRADIO_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Bluetooth radios found but none enabled"); - else + } else { ffPrintError(FF_BLUETOOTHRADIO_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No devices detected"); + } } - FF_LIST_FOR_EACH(FFBluetoothRadioResult, radio, radios) - { + FF_LIST_FOR_EACH (FFBluetoothRadioResult, radio, radios) { ffStrbufDestroy(&radio->name); ffStrbufDestroy(&radio->address); ffStrbufDestroy(&radio->vendor); @@ -105,58 +123,54 @@ bool ffPrintBluetoothRadio(FFBluetoothRadioOptions* options) return true; } -void ffParseBluetoothRadioJsonObject(FFBluetoothRadioOptions* options, yyjson_val* module) -{ +void ffParseBluetoothRadioJsonObject(FFBluetoothRadioOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_BLUETOOTHRADIO_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBluetoothRadioJsonConfig(FFBluetoothRadioOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBluetoothRadioJsonConfig(FFBluetoothRadioOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBluetoothRadioJsonResult(FF_MAYBE_UNUSED FFBluetoothRadioOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBluetoothRadioJsonResult(FF_MAYBE_UNUSED FFBluetoothRadioOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFBluetoothRadioResult)); const char* error = ffDetectBluetoothRadio(&results); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFBluetoothRadioResult, item, results) - { + FF_LIST_FOR_EACH (FFBluetoothRadioResult, item, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &item->name); yyjson_mut_obj_add_strbuf(doc, obj, "address", &item->address); - if (item->lmpVersion == INT_MIN) + if (item->lmpVersion == INT_MIN) { yyjson_mut_obj_add_null(doc, obj, "lmpVersion"); - else + } else { yyjson_mut_obj_add_int(doc, obj, "lmpVersion", item->lmpVersion); - if (item->lmpSubversion == INT_MIN) + } + if (item->lmpSubversion == INT_MIN) { yyjson_mut_obj_add_null(doc, obj, "lmpSubversion"); - else + } else { yyjson_mut_obj_add_int(doc, obj, "lmpSubversion", item->lmpSubversion); + } yyjson_mut_obj_add_strbuf(doc, obj, "vendor", &item->vendor); yyjson_mut_obj_add_bool(doc, obj, "enabled", item->enabled); yyjson_mut_obj_add_bool(doc, obj, "discoverable", item->discoverable); yyjson_mut_obj_add_bool(doc, obj, "connectable", item->connectable); } - FF_LIST_FOR_EACH(FFBluetoothRadioResult, radio, results) - { + FF_LIST_FOR_EACH (FFBluetoothRadioResult, radio, results) { ffStrbufDestroy(&radio->name); ffStrbufDestroy(&radio->address); ffStrbufDestroy(&radio->vendor); @@ -165,13 +179,11 @@ bool ffGenerateBluetoothRadioJsonResult(FF_MAYBE_UNUSED FFBluetoothRadioOptions* return true; } -void ffInitBluetoothRadioOptions(FFBluetoothRadioOptions* options) -{ +void ffInitBluetoothRadioOptions(FFBluetoothRadioOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰐻"); } -void ffDestroyBluetoothRadioOptions(FFBluetoothRadioOptions* options) -{ +void ffDestroyBluetoothRadioOptions(FFBluetoothRadioOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -193,5 +205,4 @@ FFModuleBaseInfo ffBluetoothRadioModuleInfo = { {"Vendor", "vendor"}, {"Discoverable", "discoverable"}, {"Connectable / Pairable", "connectable"}, - })) -}; + }))}; diff --git a/src/modules/bluetoothradio/option.h b/src/modules/bluetoothradio/option.h index 1b718b834..579e89953 100644 --- a/src/modules/bluetoothradio/option.h +++ b/src/modules/bluetoothradio/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFBluetoothRadioOptions -{ +typedef struct FFBluetoothRadioOptions { FFModuleArgs moduleArgs; } FFBluetoothRadioOptions; diff --git a/src/modules/board/board.c b/src/modules/board/board.c index 2cf1becec..932dbc99c 100644 --- a/src/modules/board/board.c +++ b/src/modules/board/board.c @@ -4,8 +4,7 @@ #include "detection/board/board.h" #include "modules/board/board.h" -bool ffPrintBoard(FFBoardOptions* options) -{ +bool ffPrintBoard(FFBoardOptions* options) { bool success = false; FFBoardResult result; ffStrbufInit(&result.name); @@ -14,34 +13,30 @@ bool ffPrintBoard(FFBoardOptions* options) ffStrbufInit(&result.serial); const char* error = ffDetectBoard(&result); - if(error) - { + if (error) { ffPrintError(FF_BOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if(result.name.length == 0) - { + if (result.name.length == 0) { ffPrintError(FF_BOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "board_name is not set."); goto exit; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_BOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result.name, stdout); - if (result.version.length) + if (result.version.length) { printf(" (%s)", result.version.chars); + } putchar('\n'); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_BOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result.name, "name"), - FF_ARG(result.vendor, "vendor"), - FF_ARG(result.version, "version"), - FF_ARG(result.serial, "serial"), - })); + FF_ARG(result.name, "name"), + FF_ARG(result.vendor, "vendor"), + FF_ARG(result.version, "version"), + FF_ARG(result.serial, "serial"), + })); } success = true; @@ -53,26 +48,23 @@ exit: return success; } -void ffParseBoardJsonObject(FFBoardOptions* options, yyjson_val* module) -{ +void ffParseBoardJsonObject(FFBoardOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_BOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBoardJsonConfig(FFBoardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBoardJsonConfig(FFBoardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBoardJsonResult(FF_MAYBE_UNUSED FFBoardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBoardJsonResult(FF_MAYBE_UNUSED FFBoardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFBoardResult board; ffStrbufInit(&board.name); @@ -82,14 +74,12 @@ bool ffGenerateBoardJsonResult(FF_MAYBE_UNUSED FFBoardOptions* options, yyjson_m const char* error = ffDetectBoard(&board); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } - if (board.name.length == 0) - { + if (board.name.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "board_name is not set."); goto exit; } @@ -109,13 +99,11 @@ exit: return success; } -void ffInitBoardOptions(FFBoardOptions* options) -{ +void ffInitBoardOptions(FFBoardOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyBoardOptions(FFBoardOptions* options) -{ +void ffDestroyBoardOptions(FFBoardOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -133,5 +121,4 @@ FFModuleBaseInfo ffBoardModuleInfo = { {"Board vendor", "vendor"}, {"Board version", "version"}, {"Board serial number", "serial"}, - })) -}; + }))}; diff --git a/src/modules/board/option.h b/src/modules/board/option.h index bcc69adf3..c45ddd8f1 100644 --- a/src/modules/board/option.h +++ b/src/modules/board/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFBoardOptions -{ +typedef struct FFBoardOptions { FFModuleArgs moduleArgs; } FFBoardOptions; diff --git a/src/modules/bootmgr/bootmgr.c b/src/modules/bootmgr/bootmgr.c index a2b6242ac..e42d642a9 100644 --- a/src/modules/bootmgr/bootmgr.c +++ b/src/modules/bootmgr/bootmgr.c @@ -4,8 +4,7 @@ #include "detection/bootmgr/bootmgr.h" #include "modules/bootmgr/bootmgr.h" -bool ffPrintBootmgr(FFBootmgrOptions* options) -{ +bool ffPrintBootmgr(FFBootmgrOptions* options) { bool success = false; FFBootmgrResult bootmgr = { .name = ffStrbufCreate(), @@ -14,38 +13,33 @@ bool ffPrintBootmgr(FFBootmgrOptions* options) const char* error = ffDetectBootmgr(&bootmgr); - if(error) - { + if (error) { ffPrintError(FF_BOOTMGR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; - } - else - { + } else { FF_STRBUF_AUTO_DESTROY firmwareName = ffStrbufCreateCopy(&bootmgr.firmware); - #ifndef __APPLE__ +#ifndef __APPLE__ ffStrbufSubstrAfterLastC(&firmwareName, '\\'); - #else +#else ffStrbufSubstrAfterLastC(&firmwareName, '/'); - #endif +#endif - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_BOOTMGR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&bootmgr.name, stdout); - if (firmwareName.length > 0) + if (firmwareName.length > 0) { printf(" - %s\n", firmwareName.chars); - else + } else { putchar('\n'); - } - else - { + } + } else { FF_PRINT_FORMAT_CHECKED(FF_BOOTMGR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(bootmgr.name, "name"), - FF_ARG(bootmgr.firmware, "firmware-path"), - FF_ARG(firmwareName, "firmware-name"), - FF_ARG(bootmgr.secureBoot, "secure-boot"), - FF_ARG(bootmgr.order, "order"), - })); + FF_ARG(bootmgr.name, "name"), + FF_ARG(bootmgr.firmware, "firmware-path"), + FF_ARG(firmwareName, "firmware-name"), + FF_ARG(bootmgr.secureBoot, "secure-boot"), + FF_ARG(bootmgr.order, "order"), + })); } } success = true; @@ -57,26 +51,23 @@ exit: return success; } -void ffParseBootmgrJsonObject(FFBootmgrOptions* options, yyjson_val* module) -{ +void ffParseBootmgrJsonObject(FFBootmgrOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_BOOTMGR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBootmgrJsonConfig(FFBootmgrOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBootmgrJsonConfig(FFBootmgrOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBootmgrJsonResult(FF_MAYBE_UNUSED FFBootmgrOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBootmgrJsonResult(FF_MAYBE_UNUSED FFBootmgrOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFBootmgrResult bootmgr = { .name = ffStrbufCreate(), @@ -85,8 +76,7 @@ bool ffGenerateBootmgrJsonResult(FF_MAYBE_UNUSED FFBootmgrOptions* options, yyjs const char* error = ffDetectBootmgr(&bootmgr); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } @@ -104,13 +94,11 @@ exit: return success; } -void ffInitBootmgrOptions(FFBootmgrOptions* options) -{ +void ffInitBootmgrOptions(FFBootmgrOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyBootmgrOptions(FFBootmgrOptions* options) -{ +void ffDestroyBootmgrOptions(FFBootmgrOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -129,5 +117,4 @@ FFModuleBaseInfo ffBootmgrModuleInfo = { {"Firmware file name", "firmware-name"}, {"Is secure boot enabled", "secure-boot"}, {"Boot order", "order"}, - })) -}; + }))}; diff --git a/src/modules/bootmgr/option.h b/src/modules/bootmgr/option.h index e27e71efd..2a01fb49f 100644 --- a/src/modules/bootmgr/option.h +++ b/src/modules/bootmgr/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFBootmgrOptions -{ +typedef struct FFBootmgrOptions { FFModuleArgs moduleArgs; } FFBootmgrOptions; diff --git a/src/modules/break/break.c b/src/modules/break/break.c index e3b958782..183509e31 100644 --- a/src/modules/break/break.c +++ b/src/modules/break/break.c @@ -2,32 +2,28 @@ #include "logo/logo.h" #include "modules/break/break.h" -bool ffPrintBreak(FF_MAYBE_UNUSED FFBreakOptions* options) -{ +bool ffPrintBreak(FF_MAYBE_UNUSED FFBreakOptions* options) { ffLogoPrintLine(); putchar('\n'); return true; } -void ffParseBreakJsonObject(FF_MAYBE_UNUSED FFBreakOptions* options, FF_MAYBE_UNUSED yyjson_val* module) -{ +void ffParseBreakJsonObject(FF_MAYBE_UNUSED FFBreakOptions* options, FF_MAYBE_UNUSED yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) + yyjson_obj_foreach (module, idx, max, key, val) { + if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) { continue; + } ffPrintError(FF_BREAK_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffInitBreakOptions(FF_MAYBE_UNUSED FFBreakOptions* options) -{ +void ffInitBreakOptions(FF_MAYBE_UNUSED FFBreakOptions* options) { } -void ffDestroyBreakOptions(FF_MAYBE_UNUSED FFBreakOptions* options) -{ +void ffDestroyBreakOptions(FF_MAYBE_UNUSED FFBreakOptions* options) { } FFModuleBaseInfo ffBreakModuleInfo = { diff --git a/src/modules/break/option.h b/src/modules/break/option.h index e5acbf20d..90a44dff8 100644 --- a/src/modules/break/option.h +++ b/src/modules/break/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFBreakOptions -{ +typedef struct FFBreakOptions { } FFBreakOptions; static_assert(sizeof(FFBreakOptions) <= FF_OPTION_MAX_SIZE, "FFBreakOptions size exceeds maximum allowed size"); diff --git a/src/modules/brightness/brightness.c b/src/modules/brightness/brightness.c index bac45b25d..2f2c3b444 100644 --- a/src/modules/brightness/brightness.c +++ b/src/modules/brightness/brightness.c @@ -5,34 +5,30 @@ #include "detection/brightness/brightness.h" #include "modules/brightness/brightness.h" -bool ffPrintBrightness(FFBrightnessOptions* options) -{ +bool ffPrintBrightness(FFBrightnessOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFBrightnessResult)); const char* error = ffDetectBrightness(options, &result); - if(error) - { + if (error) { ffPrintError(FF_BRIGHTNESS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(result.length == 0) - { + if (result.length == 0) { ffPrintError(FF_BRIGHTNESS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No result is detected."); return false; } FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if (options->compact) - { + if (options->compact) { FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); - FF_LIST_FOR_EACH(FFBrightnessResult, item, result) - { - if(str.length > 0) + FF_LIST_FOR_EACH (FFBrightnessResult, item, result) { + if (str.length > 0) { ffStrbufAppendC(&str, ' '); + } const double percent = (item->current - item->min) / (item->max - item->min) * 100; ffPercentAppendNum(&str, percent, options->percent, false, &options->moduleArgs); @@ -46,38 +42,32 @@ bool ffPrintBrightness(FFBrightnessOptions* options) FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); uint32_t index = 0; - FF_LIST_FOR_EACH(FFBrightnessResult, item, result) - { - if (options->moduleArgs.key.length == 0) - { + FF_LIST_FOR_EACH (FFBrightnessResult, item, result) { + if (options->moduleArgs.key.length == 0) { ffStrbufAppendF(&key, "%s (%s)", FF_BRIGHTNESS_MODULE_NAME, item->name.chars); - } - else - { + } else { uint32_t moduleIndex = result.length == 1 ? 0 : index + 1; FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(moduleIndex, "index"), - FF_ARG(item->name, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(moduleIndex, "index"), + FF_ARG(item->name, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } const double percent = (item->current - item->min) / (item->max - item->min) * 100; - if (options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&str, percent, options->percent, &options->moduleArgs); } - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) - { - if(str.length > 0) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { + if (str.length > 0) { ffStrbufAppendC(&str, ' '); + } ffPercentAppendNum(&str, percent, options->percent, str.length > 0, &options->moduleArgs); } @@ -85,25 +75,25 @@ bool ffPrintBrightness(FFBrightnessOptions* options) ffStrbufAppendS(&str, item->builtin ? " [Built-in]" : " [External]"); ffStrbufPutTo(&str, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY valueNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&valueNum, percent, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY valueBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&valueBar, percent, options->percent, &options->moduleArgs); + } FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(valueNum, "percentage"), - FF_ARG(item->name, "name"), - FF_ARG(item->max, "max"), - FF_ARG(item->min, "min"), - FF_ARG(item->current, "current"), - FF_ARG(valueBar, "percentage-bar"), - FF_ARG(item->builtin, "is-builtin"), - })); + FF_ARG(valueNum, "percentage"), + FF_ARG(item->name, "name"), + FF_ARG(item->max, "max"), + FF_ARG(item->min, "min"), + FF_ARG(item->current, "current"), + FF_ARG(valueBar, "percentage-bar"), + FF_ARG(item->builtin, "is-builtin"), + })); } ffStrbufClear(&key); @@ -114,36 +104,33 @@ bool ffPrintBrightness(FFBrightnessOptions* options) return true; } -void ffParseBrightnessJsonObject(FFBrightnessOptions* options, yyjson_val* module) -{ +void ffParseBrightnessJsonObject(FFBrightnessOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "ddcciSleep")) - { + if (unsafe_yyjson_equals_str(key, "ddcciSleep")) { options->ddcciSleep = (uint32_t) yyjson_get_uint(val); continue; } - if (unsafe_yyjson_equals_str(key, "compact")) - { + if (unsafe_yyjson_equals_str(key, "compact")) { options->compact = (uint32_t) yyjson_get_bool(val); continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_BRIGHTNESS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBrightnessJsonConfig(FFBrightnessOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBrightnessJsonConfig(FFBrightnessOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_uint(doc, module, "ddcciSleep", options->ddcciSleep); @@ -153,14 +140,12 @@ void ffGenerateBrightnessJsonConfig(FFBrightnessOptions* options, yyjson_mut_doc yyjson_mut_obj_add_bool(doc, module, "compact", options->compact); } -bool ffGenerateBrightnessJsonResult(FF_MAYBE_UNUSED FFBrightnessOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBrightnessJsonResult(FF_MAYBE_UNUSED FFBrightnessOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFBrightnessResult)); const char* error = ffDetectBrightness(options, &result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -168,8 +153,7 @@ bool ffGenerateBrightnessJsonResult(FF_MAYBE_UNUSED FFBrightnessOptions* options yyjson_mut_val* arr = yyjson_mut_arr(doc); yyjson_mut_obj_add_val(doc, module, "result", arr); - FF_LIST_FOR_EACH(FFBrightnessResult, item, result) - { + FF_LIST_FOR_EACH (FFBrightnessResult, item, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &item->name); yyjson_mut_obj_add_real(doc, obj, "max", item->max); @@ -178,25 +162,22 @@ bool ffGenerateBrightnessJsonResult(FF_MAYBE_UNUSED FFBrightnessOptions* options yyjson_mut_obj_add_bool(doc, obj, "builtin", item->builtin); } - FF_LIST_FOR_EACH(FFBrightnessResult, item, result) - { + FF_LIST_FOR_EACH (FFBrightnessResult, item, result) { ffStrbufDestroy(&item->name); } return true; } -void ffInitBrightnessOptions(FFBrightnessOptions* options) -{ +void ffInitBrightnessOptions(FFBrightnessOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰯪"); options->ddcciSleep = 10; - options->percent = (FFPercentageModuleConfig) { 100, 100, 0 }; + options->percent = (FFPercentageModuleConfig) {100, 100, 0}; options->compact = false; } -void ffDestroyBrightnessOptions(FFBrightnessOptions* options) -{ +void ffDestroyBrightnessOptions(FFBrightnessOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -217,5 +198,4 @@ FFModuleBaseInfo ffBrightnessModuleInfo = { {"Current brightness value", "current"}, {"Screen brightness (percentage bar)", "percentage-bar"}, {"Is built-in screen", "is-builtin"}, - })) -}; + }))}; diff --git a/src/modules/brightness/option.h b/src/modules/brightness/option.h index 4ff3843e7..a31228d88 100644 --- a/src/modules/brightness/option.h +++ b/src/modules/brightness/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFBrightnessOptions -{ +typedef struct FFBrightnessOptions { FFModuleArgs moduleArgs; uint32_t ddcciSleep; // ms diff --git a/src/modules/btrfs/btrfs.c b/src/modules/btrfs/btrfs.c index a76ca73b0..8e93ad0ce 100644 --- a/src/modules/btrfs/btrfs.c +++ b/src/modules/btrfs/btrfs.c @@ -6,29 +6,25 @@ #include "detection/btrfs/btrfs.h" #include "modules/btrfs/btrfs.h" -static void printBtrfs(FFBtrfsOptions* options, FFBtrfsResult* result, uint8_t index) -{ +static void printBtrfs(FFBtrfsOptions* options, FFBtrfsResult* result, uint8_t index) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (options->moduleArgs.key.length == 0) - { - if (result->name.length > 0) + if (options->moduleArgs.key.length == 0) { + if (result->name.length > 0) { ffStrbufSetF(&buffer, "%s (%s)", FF_BTRFS_MODULE_NAME, result->name.chars); - else + } else { ffStrbufSetS(&buffer, FF_BTRFS_MODULE_NAME); - } - else - { + } + } else { ffStrbufClear(&buffer); FF_PARSE_FORMAT_STRING_CHECKED(&buffer, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(result->name, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(result->name, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } uint64_t used = 0, allocated = 0, total = result->totalSize; - for (uint32_t i = 0; i < ARRAY_SIZE(result->allocation); ++i) - { + for (uint32_t i = 0; i < ARRAY_SIZE(result->allocation); ++i) { uint64_t times = result->allocation[i].copies; used += result->allocation[i].used * times; allocated += result->allocation[i].total * times; @@ -46,8 +42,7 @@ static void printBtrfs(FFBtrfsOptions* options, FFBtrfsResult* result, uint8_t i FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(buffer.chars, index, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffStrbufClear(&buffer); @@ -57,22 +52,24 @@ static void printBtrfs(FFBtrfsOptions* options, FFBtrfsResult* result, uint8_t i ffPercentAppendNum(&buffer, allocatedPercentage, options->percent, false, &options->moduleArgs); ffStrbufAppendF(&buffer, " allocated)"); ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY usedPercentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&usedPercentageNum, usedPercentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY usedPercentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&usedPercentageBar, usedPercentage, options->percent, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY allocatedPercentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&allocatedPercentageNum, allocatedPercentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY allocatedPercentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&allocatedPercentageBar, allocatedPercentage, options->percent, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY nodeSizePretty = ffStrbufCreate(); ffSizeAppendNum(result->nodeSize, &nodeSizePretty); @@ -80,49 +77,44 @@ static void printBtrfs(FFBtrfsOptions* options, FFBtrfsResult* result, uint8_t i ffSizeAppendNum(result->sectorSize, §orSizePretty); FF_PRINT_FORMAT_CHECKED(buffer.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(result->name, "name"), - FF_ARG(result->uuid, "uuid"), - FF_ARG(result->devices, "devices"), - FF_ARG(result->features, "features"), - FF_ARG(usedPretty, "used"), - FF_ARG(allocatedPretty, "allocated"), - FF_ARG(totalPretty, "total"), - FF_ARG(usedPercentageNum, "used-percentage"), - FF_ARG(allocatedPercentageNum, "allocated-percentage"), - FF_ARG(usedPercentageBar, "used-percentage-bar"), - FF_ARG(allocatedPercentageBar, "allocated-percentage-bar"), - FF_ARG(nodeSizePretty, "node-size"), - FF_ARG(sectorSizePretty, "sector-size"), - })); + FF_ARG(result->name, "name"), + FF_ARG(result->uuid, "uuid"), + FF_ARG(result->devices, "devices"), + FF_ARG(result->features, "features"), + FF_ARG(usedPretty, "used"), + FF_ARG(allocatedPretty, "allocated"), + FF_ARG(totalPretty, "total"), + FF_ARG(usedPercentageNum, "used-percentage"), + FF_ARG(allocatedPercentageNum, "allocated-percentage"), + FF_ARG(usedPercentageBar, "used-percentage-bar"), + FF_ARG(allocatedPercentageBar, "allocated-percentage-bar"), + FF_ARG(nodeSizePretty, "node-size"), + FF_ARG(sectorSizePretty, "sector-size"), + })); } } -bool ffPrintBtrfs(FFBtrfsOptions* options) -{ +bool ffPrintBtrfs(FFBtrfsOptions* options) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFBtrfsResult)); const char* error = ffDetectBtrfs(&results); - if (error) - { + if (error) { ffPrintError(FF_BTRFS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(results.length == 0) - { + if (results.length == 0) { ffPrintError(FF_BTRFS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", "No btrfs drive found"); return false; } - for(uint32_t i = 0; i < results.length; i++) - { + for (uint32_t i = 0; i < results.length; i++) { FFBtrfsResult* result = FF_LIST_GET(FFBtrfsResult, results, i); uint8_t index = results.length == 1 ? 0 : (uint8_t) (i + 1); printBtrfs(options, result, index); } - FF_LIST_FOR_EACH(FFBtrfsResult, result, results) - { + FF_LIST_FOR_EACH (FFBtrfsResult, result, results) { ffStrbufDestroy(&result->name); ffStrbufDestroy(&result->uuid); ffStrbufDestroy(&result->devices); @@ -132,44 +124,40 @@ bool ffPrintBtrfs(FFBtrfsOptions* options) return true; } -void ffParseBtrfsJsonObject(FFBtrfsOptions* options, yyjson_val* module) -{ +void ffParseBtrfsJsonObject(FFBtrfsOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_BTRFS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateBtrfsJsonConfig(FFBtrfsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateBtrfsJsonConfig(FFBtrfsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateBtrfsJsonResult(FF_MAYBE_UNUSED FFBtrfsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateBtrfsJsonResult(FF_MAYBE_UNUSED FFBtrfsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFBtrfsResult)); const char* error = ffDetectBtrfs(&results); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFBtrfsResult, btrfs, results) - { + FF_LIST_FOR_EACH (FFBtrfsResult, btrfs, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &btrfs->name); yyjson_mut_obj_add_strbuf(doc, obj, "uuid", &btrfs->uuid); @@ -180,8 +168,7 @@ bool ffGenerateBtrfsJsonResult(FF_MAYBE_UNUSED FFBtrfsOptions* options, yyjson_m yyjson_mut_obj_add_uint(doc, obj, "sectorSize", btrfs->sectorSize); yyjson_mut_obj_add_uint(doc, obj, "totalSize", btrfs->totalSize); yyjson_mut_val* allocation = yyjson_mut_obj_add_arr(doc, obj, "allocation"); - for (uint32_t i = 0; i < ARRAY_SIZE(btrfs->allocation); ++i) - { + for (uint32_t i = 0; i < ARRAY_SIZE(btrfs->allocation); ++i) { yyjson_mut_val* item = yyjson_mut_arr_add_obj(doc, allocation); yyjson_mut_obj_add_str(doc, item, "type", btrfs->allocation[i].type); yyjson_mut_obj_add_str(doc, item, "profile", btrfs->allocation[i].profile); @@ -191,8 +178,7 @@ bool ffGenerateBtrfsJsonResult(FF_MAYBE_UNUSED FFBtrfsOptions* options, yyjson_m } } - FF_LIST_FOR_EACH(FFBtrfsResult, btrfs, results) - { + FF_LIST_FOR_EACH (FFBtrfsResult, btrfs, results) { ffStrbufDestroy(&btrfs->name); ffStrbufDestroy(&btrfs->uuid); ffStrbufDestroy(&btrfs->devices); @@ -202,14 +188,12 @@ bool ffGenerateBtrfsJsonResult(FF_MAYBE_UNUSED FFBtrfsOptions* options, yyjson_m return true; } -void ffInitBtrfsOptions(FFBtrfsOptions* options) -{ +void ffInitBtrfsOptions(FFBtrfsOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󱑛"); - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; } -void ffDestroyBtrfsOptions(FFBtrfsOptions* options) -{ +void ffDestroyBtrfsOptions(FFBtrfsOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -236,5 +220,4 @@ FFModuleBaseInfo ffBtrfsModuleInfo = { {"Allocated percentage bar", "allocated-percentage-bar"}, {"Node size", "node-size"}, {"Sector size", "sector-size"}, - })) -}; + }))}; diff --git a/src/modules/btrfs/option.h b/src/modules/btrfs/option.h index 019eacb19..0530cefef 100644 --- a/src/modules/btrfs/option.h +++ b/src/modules/btrfs/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFBtrfsOptions -{ +typedef struct FFBtrfsOptions { FFModuleArgs moduleArgs; FFPercentageModuleConfig percent; diff --git a/src/modules/camera/camera.c b/src/modules/camera/camera.c index 6d87f02f1..37c66b409 100644 --- a/src/modules/camera/camera.c +++ b/src/modules/camera/camera.c @@ -5,62 +5,53 @@ #include "detection/camera/camera.h" #include "modules/camera/camera.h" -static void printDevice(FFCameraOptions* options, const FFCameraResult* device, uint8_t index) -{ - if(options->moduleArgs.outputFormat.length == 0) - { +static void printDevice(FFCameraOptions* options, const FFCameraResult* device, uint8_t index) { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_CAMERA_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&device->name, stdout); - if (device->colorspace.length > 0) - { + if (device->colorspace.length > 0) { fputs(" - ", stdout); ffStrbufWriteTo(&device->colorspace, stdout); } - if (device->width > 0 && device->height > 0) + if (device->width > 0 && device->height > 0) { printf(" (%ux%u px)\n", (unsigned) device->width, (unsigned) device->height); - else + } else { putchar('\n'); - } - else - { + } + } else { FF_PRINT_FORMAT_CHECKED(FF_CAMERA_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, (((FFformatarg[]) { - FF_ARG(device->name, "name"), - FF_ARG(device->vendor, "vendor"), - FF_ARG(device->colorspace, "colorspace"), - FF_ARG(device->id, "id"), - FF_ARG(device->width, "width"), - FF_ARG(device->height, "height"), - }))); + FF_ARG(device->name, "name"), + FF_ARG(device->vendor, "vendor"), + FF_ARG(device->colorspace, "colorspace"), + FF_ARG(device->id, "id"), + FF_ARG(device->width, "width"), + FF_ARG(device->height, "height"), + }))); } } -bool ffPrintCamera(FFCameraOptions* options) -{ +bool ffPrintCamera(FFCameraOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFCameraResult)); const char* error = ffDetectCamera(&result); - if (error) - { + if (error) { ffPrintError(FF_CAMERA_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if (result.length == 0) - { + if (result.length == 0) { ffPrintError(FF_CAMERA_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No camera found"); return false; } - for(uint32_t i = 0; i < result.length; i++) - { + for (uint32_t i = 0; i < result.length; i++) { uint8_t index = (uint8_t) (result.length == 1 ? 0 : i + 1); printDevice(options, FF_LIST_GET(FFCameraResult, result, i), index); } - FF_LIST_FOR_EACH(FFCameraResult, dev, result) - { + FF_LIST_FOR_EACH (FFCameraResult, dev, result) { ffStrbufDestroy(&dev->name); ffStrbufDestroy(&dev->id); ffStrbufDestroy(&dev->colorspace); @@ -69,39 +60,34 @@ bool ffPrintCamera(FFCameraOptions* options) return true; } -void ffParseCameraJsonObject(FFCameraOptions* options, yyjson_val* module) -{ +void ffParseCameraJsonObject(FFCameraOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_CAMERA_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateCameraJsonConfig(FFCameraOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateCameraJsonConfig(FFCameraOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateCameraJsonResult(FF_MAYBE_UNUSED FFCameraOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateCameraJsonResult(FF_MAYBE_UNUSED FFCameraOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFCameraResult)); const char* error = ffDetectCamera(&result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFCameraResult, dev, result) - { + FF_LIST_FOR_EACH (FFCameraResult, dev, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &dev->name); yyjson_mut_obj_add_strbuf(doc, obj, "vendor", &dev->vendor); @@ -111,8 +97,7 @@ bool ffGenerateCameraJsonResult(FF_MAYBE_UNUSED FFCameraOptions* options, yyjson yyjson_mut_obj_add_uint(doc, obj, "height", dev->height); } - FF_LIST_FOR_EACH(FFCameraResult, dev, result) - { + FF_LIST_FOR_EACH (FFCameraResult, dev, result) { ffStrbufDestroy(&dev->name); ffStrbufDestroy(&dev->id); ffStrbufDestroy(&dev->colorspace); @@ -121,13 +106,11 @@ bool ffGenerateCameraJsonResult(FF_MAYBE_UNUSED FFCameraOptions* options, yyjson return true; } -void ffInitCameraOptions(FFCameraOptions* options) -{ +void ffInitCameraOptions(FFCameraOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰄀"); } -void ffDestroyCameraOptions(FFCameraOptions* options) -{ +void ffDestroyCameraOptions(FFCameraOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -147,5 +130,4 @@ FFModuleBaseInfo ffCameraModuleInfo = { {"Identifier", "id"}, {"Width (in px)", "width"}, {"Height (in px)", "height"}, - })) -}; + }))}; diff --git a/src/modules/camera/option.h b/src/modules/camera/option.h index 6a2481fe8..51eb29f86 100644 --- a/src/modules/camera/option.h +++ b/src/modules/camera/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFCameraOptions -{ +typedef struct FFCameraOptions { FFModuleArgs moduleArgs; } FFCameraOptions; diff --git a/src/modules/chassis/chassis.c b/src/modules/chassis/chassis.c index 39b34a25b..aef714ece 100644 --- a/src/modules/chassis/chassis.c +++ b/src/modules/chassis/chassis.c @@ -4,8 +4,7 @@ #include "detection/chassis/chassis.h" #include "modules/chassis/chassis.h" -bool ffPrintChassis(FFChassisOptions* options) -{ +bool ffPrintChassis(FFChassisOptions* options) { bool success = false; FFChassisResult result; @@ -16,34 +15,30 @@ bool ffPrintChassis(FFChassisOptions* options) const char* error = ffDetectChassis(&result); - if(error) - { + if (error) { ffPrintError(FF_CHASSIS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if(result.type.length == 0) - { + if (result.type.length == 0) { ffPrintError(FF_CHASSIS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "chassis_type is not set by O.E.M."); goto exit; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_CHASSIS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result.type, stdout); - if (result.version.length) + if (result.version.length) { printf(" (%s)", result.version.chars); + } putchar('\n'); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_CHASSIS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result.type, "type"), - FF_ARG(result.vendor, "vendor"), - FF_ARG(result.version, "version"), - FF_ARG(result.serial, "serial"), - })); + FF_ARG(result.type, "type"), + FF_ARG(result.vendor, "vendor"), + FF_ARG(result.version, "version"), + FF_ARG(result.serial, "serial"), + })); } success = true; @@ -55,26 +50,23 @@ exit: return success; } -void ffParseChassisJsonObject(FFChassisOptions* options, yyjson_val* module) -{ +void ffParseChassisJsonObject(FFChassisOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_CHASSIS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateChassisJsonConfig(FFChassisOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateChassisJsonConfig(FFChassisOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateChassisJsonResult(FF_MAYBE_UNUSED FFChassisOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateChassisJsonResult(FF_MAYBE_UNUSED FFChassisOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFChassisResult result; ffStrbufInit(&result.type); @@ -84,14 +76,12 @@ bool ffGenerateChassisJsonResult(FF_MAYBE_UNUSED FFChassisOptions* options, yyjs const char* error = ffDetectChassis(&result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } - if(result.type.length == 0) - { + if (result.type.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "chassis_type is not set by O.E.M."); goto exit; } @@ -111,13 +101,11 @@ exit: return success; } -void ffInitChassisOptions(FFChassisOptions* options) -{ +void ffInitChassisOptions(FFChassisOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyChassisOptions(FFChassisOptions* options) -{ +void ffDestroyChassisOptions(FFChassisOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } diff --git a/src/modules/chassis/option.h b/src/modules/chassis/option.h index b3100653f..dc5422773 100644 --- a/src/modules/chassis/option.h +++ b/src/modules/chassis/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFChassisOptions -{ +typedef struct FFChassisOptions { FFModuleArgs moduleArgs; } FFChassisOptions; diff --git a/src/modules/colors/colors.c b/src/modules/colors/colors.c index c546e0a01..02c28d8ec 100644 --- a/src/modules/colors/colors.c +++ b/src/modules/colors/colors.c @@ -6,140 +6,136 @@ #include "logo/logo.h" #include "modules/colors/colors.h" -static inline uint8_t min(uint8_t a, uint8_t b) -{ +static inline uint8_t min(uint8_t a, uint8_t b) { return a < b ? a : b; } -static inline uint8_t max(uint8_t a, uint8_t b) -{ +static inline uint8_t max(uint8_t a, uint8_t b) { return a > b ? a : b; } -bool ffPrintColors(FFColorsOptions* options) -{ +bool ffPrintColors(FFColorsOptions* options) { bool flag = false; FF_STRBUF_AUTO_DESTROY result = ffStrbufCreateA(128); - if (options->symbol == FF_COLORS_SYMBOL_BLOCK || options->symbol == FF_COLORS_SYMBOL_BACKGROUND) - { - if (options->brightness != FF_COLORS_BRIGHTNESS_LIGHT) - { + if (options->symbol == FF_COLORS_SYMBOL_BLOCK || options->symbol == FF_COLORS_SYMBOL_BACKGROUND) { + if (options->brightness != FF_COLORS_BRIGHTNESS_LIGHT) { // 3%d: Set the foreground color - for(uint8_t i = options->block.range[0]; i <= min(options->block.range[1], 7); i++) - { - if (options->symbol == FF_COLORS_SYMBOL_BLOCK) - { - if (!instance.config.display.pipe) + for (uint8_t i = options->block.range[0]; i <= min(options->block.range[1], 7); i++) { + if (options->symbol == FF_COLORS_SYMBOL_BLOCK) { + if (!instance.config.display.pipe) { ffStrbufAppendF(&result, "\e[3%dm", i); - for (uint8_t j = 0; j < options->block.width; j++) + } + for (uint8_t j = 0; j < options->block.width; j++) { ffStrbufAppendS(&result, "█"); - } - else - { + } + } else { ffStrbufAppendF(&result, "\e[4%dm", i); ffStrbufAppendNC(&result, options->block.width, ' '); } } } - if (result.length > 0) - { + if (result.length > 0) { ffPrintLogoAndKey(FF_COLORS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); flag = true; - if (options->paddingLeft > 0) + if (options->paddingLeft > 0) { ffPrintCharTimes(' ', options->paddingLeft); + } - if (!instance.config.display.pipe || options->symbol == FF_COLORS_SYMBOL_BACKGROUND) + if (!instance.config.display.pipe || options->symbol == FF_COLORS_SYMBOL_BACKGROUND) { ffStrbufAppendS(&result, FASTFETCH_TEXT_MODIFIER_RESET); + } ffStrbufPutTo(&result, stdout); ffStrbufClear(&result); } - #ifdef __linux__ +#ifdef __linux__ // Required by Linux Console for light background to work - if (options->symbol == FF_COLORS_SYMBOL_BACKGROUND) - { + if (options->symbol == FF_COLORS_SYMBOL_BACKGROUND) { const char* term = getenv("TERM"); // Should be "linux", however some terminal mulitplexer overrides $TERM - if (term && !ffStrStartsWith(term, "xterm")) + if (term && !ffStrStartsWith(term, "xterm")) { ffStrbufAppendS(&result, "\e[5m"); + } } - #endif +#endif - if (options->brightness != FF_COLORS_BRIGHTNESS_NORMAL) - { + if (options->brightness != FF_COLORS_BRIGHTNESS_NORMAL) { // 9%d: Set the foreground to the bright color - for (uint8_t i = max(options->block.range[0], 8); i <= options->block.range[1]; i++) - { - if (options->symbol == FF_COLORS_SYMBOL_BLOCK) - { - if(!instance.config.display.pipe) + for (uint8_t i = max(options->block.range[0], 8); i <= options->block.range[1]; i++) { + if (options->symbol == FF_COLORS_SYMBOL_BLOCK) { + if (!instance.config.display.pipe) { ffStrbufAppendF(&result, "\e[9%dm", i - 8); - for (uint8_t j = 0; j < options->block.width; j++) + } + for (uint8_t j = 0; j < options->block.width; j++) { ffStrbufAppendS(&result, "█"); - } - else - { + } + } else { ffStrbufAppendF(&result, "\e[10%dm", i - 8); ffStrbufAppendNC(&result, options->block.width, ' '); } } } - } - else - { + } else { const char* symbol; - switch (options->symbol) - { - case FF_COLORS_SYMBOL_CIRCLE: symbol = "● "; break; - case FF_COLORS_SYMBOL_DIAMOND: symbol = "◆ "; break; - case FF_COLORS_SYMBOL_TRIANGLE: symbol = "▲ "; break; - case FF_COLORS_SYMBOL_SQUARE: symbol = "■ "; break; - case FF_COLORS_SYMBOL_STAR: symbol = "★ "; break; - default: symbol = "███ "; break; + switch (options->symbol) { + case FF_COLORS_SYMBOL_CIRCLE: + symbol = "● "; + break; + case FF_COLORS_SYMBOL_DIAMOND: + symbol = "◆ "; + break; + case FF_COLORS_SYMBOL_TRIANGLE: + symbol = "▲ "; + break; + case FF_COLORS_SYMBOL_SQUARE: + symbol = "■ "; + break; + case FF_COLORS_SYMBOL_STAR: + symbol = "★ "; + break; + default: + symbol = "███ "; + break; } - if (options->brightness == FF_COLORS_BRIGHTNESS_DEFAULT) - { - for (int i = 8; i >= 1; --i) - { - if (!instance.config.display.pipe) + if (options->brightness == FF_COLORS_BRIGHTNESS_DEFAULT) { + for (int i = 8; i >= 1; --i) { + if (!instance.config.display.pipe) { ffStrbufAppendF(&result, "\e[" FF_COLOR_FG_256 "%dm", i); + } ffStrbufAppendS(&result, symbol); } - } - else - { - for (int i = 0; i <= 7; ++i) - { - if (!instance.config.display.pipe) + } else { + for (int i = 0; i <= 7; ++i) { + if (!instance.config.display.pipe) { ffStrbufAppendF(&result, "\e[%c%dm", options->brightness == FF_COLORS_BRIGHTNESS_NORMAL ? '3' : '9', i); + } ffStrbufAppendS(&result, symbol); } } ffStrbufTrimRight(&result, ' '); } - if (result.length > 0) - { - if (flag) + if (result.length > 0) { + if (flag) { ffLogoPrintLine(); - else - { + } else { ffPrintLogoAndKey(FF_COLORS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); flag = true; } - if (options->paddingLeft > 0) + if (options->paddingLeft > 0) { ffPrintCharTimes(' ', options->paddingLeft); - if (!instance.config.display.pipe || options->symbol == FF_COLORS_SYMBOL_BACKGROUND) + } + if (!instance.config.display.pipe || options->symbol == FF_COLORS_SYMBOL_BACKGROUND) { ffStrbufAppendS(&result, FASTFETCH_TEXT_MODIFIER_RESET); + } ffStrbufPutTo(&result, stdout); } - if (!flag) - { + if (!flag) { ffPrintError(FF_COLORS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", "Nothing to print"); return false; } @@ -147,66 +143,60 @@ bool ffPrintColors(FFColorsOptions* options) return true; } -void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) -{ +void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) - continue; - - if (unsafe_yyjson_equals_str(key, "symbol")) - { - int value; - const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "block", FF_COLORS_SYMBOL_BLOCK }, - { "background", FF_COLORS_SYMBOL_BACKGROUND }, - { "circle", FF_COLORS_SYMBOL_CIRCLE }, - { "diamond", FF_COLORS_SYMBOL_DIAMOND }, - { "triangle", FF_COLORS_SYMBOL_TRIANGLE }, - { "square", FF_COLORS_SYMBOL_SQUARE }, - { "star", FF_COLORS_SYMBOL_STAR }, - {}, - }); - if (error) - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else - options->symbol = (FFColorsSymbol) value; + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; } - if (unsafe_yyjson_equals_str(key, "paddingLeft")) - { + if (unsafe_yyjson_equals_str(key, "symbol")) { + int value; + const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { + {"block", FF_COLORS_SYMBOL_BLOCK}, + {"background", FF_COLORS_SYMBOL_BACKGROUND}, + {"circle", FF_COLORS_SYMBOL_CIRCLE}, + {"diamond", FF_COLORS_SYMBOL_DIAMOND}, + {"triangle", FF_COLORS_SYMBOL_TRIANGLE}, + {"square", FF_COLORS_SYMBOL_SQUARE}, + {"star", FF_COLORS_SYMBOL_STAR}, + {}, + }); + if (error) { + ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); + } else { + options->symbol = (FFColorsSymbol) value; + } + continue; + } + + if (unsafe_yyjson_equals_str(key, "paddingLeft")) { options->paddingLeft = (uint32_t) yyjson_get_uint(val); continue; } - if (unsafe_yyjson_equals_str(key, "block")) - { - if (!yyjson_is_obj(val)) + if (unsafe_yyjson_equals_str(key, "block")) { + if (!yyjson_is_obj(val)) { ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: must be an object", unsafe_yyjson_get_str(key)); - else - { + } else { yyjson_val* width = yyjson_obj_get(val, "width"); - if (width) + if (width) { options->block.width = (uint8_t) yyjson_get_uint(width); + } yyjson_val* range = yyjson_obj_get(val, "range"); - if (range) - { - if (!yyjson_is_arr(range) || yyjson_arr_size(range) != 2) + if (range) { + if (!yyjson_is_arr(range) || yyjson_arr_size(range) != 2) { ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: must be an array of 2 elements", unsafe_yyjson_get_str(key)); - else - { + } else { uint8_t start = (uint8_t) yyjson_get_uint(yyjson_arr_get(range, 0)); uint8_t end = (uint8_t) yyjson_get_uint(yyjson_arr_get(range, 1)); - if (start > end) + if (start > end) { ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: range[0] > range[1]", unsafe_yyjson_get_str(key)); - else if (end > 15) + } else if (end > 15) { ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: range[1] > 15", unsafe_yyjson_get_str(key)); - else - { + } else { options->block.range[0] = start; options->block.range[1] = end; } @@ -216,19 +206,19 @@ void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) continue; } - if (unsafe_yyjson_equals_str(key, "brightness")) - { + if (unsafe_yyjson_equals_str(key, "brightness")) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "default", FF_COLORS_BRIGHTNESS_DEFAULT }, - { "normal", FF_COLORS_BRIGHTNESS_NORMAL }, - { "light", FF_COLORS_BRIGHTNESS_LIGHT }, - {}, - }); - if (error) + {"default", FF_COLORS_BRIGHTNESS_DEFAULT}, + {"normal", FF_COLORS_BRIGHTNESS_NORMAL}, + {"light", FF_COLORS_BRIGHTNESS_LIGHT}, + {}, + }); + if (error) { ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else + } else { options->brightness = (FFColorsBrightness) value; + } continue; } @@ -236,20 +226,30 @@ void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) } } -void ffGenerateColorsJsonConfig(FFColorsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateColorsJsonConfig(FFColorsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_remove_key(module, "format"); // Not supported - switch (options->symbol) - { - case FF_COLORS_SYMBOL_CIRCLE: yyjson_mut_obj_add_str(doc, module, "symbol", "circle"); break; - case FF_COLORS_SYMBOL_DIAMOND: yyjson_mut_obj_add_str(doc, module, "symbol", "diamond"); break; - case FF_COLORS_SYMBOL_TRIANGLE: yyjson_mut_obj_add_str(doc, module, "symbol", "triangle"); break; - case FF_COLORS_SYMBOL_SQUARE: yyjson_mut_obj_add_str(doc, module, "symbol", "square"); break; - case FF_COLORS_SYMBOL_STAR: yyjson_mut_obj_add_str(doc, module, "symbol", "star"); break; - default: yyjson_mut_obj_add_str(doc, module, "symbol", "block"); break; + switch (options->symbol) { + case FF_COLORS_SYMBOL_CIRCLE: + yyjson_mut_obj_add_str(doc, module, "symbol", "circle"); + break; + case FF_COLORS_SYMBOL_DIAMOND: + yyjson_mut_obj_add_str(doc, module, "symbol", "diamond"); + break; + case FF_COLORS_SYMBOL_TRIANGLE: + yyjson_mut_obj_add_str(doc, module, "symbol", "triangle"); + break; + case FF_COLORS_SYMBOL_SQUARE: + yyjson_mut_obj_add_str(doc, module, "symbol", "square"); + break; + case FF_COLORS_SYMBOL_STAR: + yyjson_mut_obj_add_str(doc, module, "symbol", "star"); + break; + default: + yyjson_mut_obj_add_str(doc, module, "symbol", "block"); + break; } yyjson_mut_obj_add_uint(doc, module, "paddingLeft", options->paddingLeft); @@ -260,26 +260,25 @@ void ffGenerateColorsJsonConfig(FFColorsOptions* options, yyjson_mut_doc* doc, y yyjson_mut_obj_add_uint(doc, block, "width", options->block.width); yyjson_mut_val* range = yyjson_mut_obj_add_arr(doc, block, "range"); - for (uint8_t i = 0; i < 2; i++) + for (uint8_t i = 0; i < 2; i++) { yyjson_mut_arr_add_uint(doc, range, options->block.range[i]); + } } } -void ffInitColorsOptions(FFColorsOptions* options) -{ +void ffInitColorsOptions(FFColorsOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); ffStrbufSetStatic(&options->moduleArgs.key, " "); options->symbol = FF_COLORS_SYMBOL_BACKGROUND; options->paddingLeft = 0; options->block = (FFBlockConfig) { .width = 3, - .range = { 0, 15 }, + .range = {0, 15}, }; options->brightness = FF_COLORS_BRIGHTNESS_DEFAULT; } -void ffDestroyColorsOptions(FFColorsOptions* options) -{ +void ffDestroyColorsOptions(FFColorsOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } diff --git a/src/modules/colors/option.h b/src/modules/colors/option.h index 6155976a3..ea366716e 100644 --- a/src/modules/colors/option.h +++ b/src/modules/colors/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef enum __attribute__((__packed__)) FFColorsSymbol -{ +typedef enum __attribute__((__packed__)) FFColorsSymbol { FF_COLORS_SYMBOL_BLOCK, FF_COLORS_SYMBOL_BACKGROUND, FF_COLORS_SYMBOL_CIRCLE, @@ -13,21 +12,18 @@ typedef enum __attribute__((__packed__)) FFColorsSymbol FF_COLORS_SYMBOL_STAR, } FFColorsSymbol; -typedef struct FFBlockConfig -{ +typedef struct FFBlockConfig { uint8_t width; uint8_t range[2]; } FFBlockConfig; -typedef enum __attribute__((__packed__)) FFColorsBrightness -{ +typedef enum __attribute__((__packed__)) FFColorsBrightness { FF_COLORS_BRIGHTNESS_DEFAULT, FF_COLORS_BRIGHTNESS_NORMAL, FF_COLORS_BRIGHTNESS_LIGHT, } FFColorsBrightness; -typedef struct FFColorsOptions -{ +typedef struct FFColorsOptions { FFModuleArgs moduleArgs; FFColorsSymbol symbol; diff --git a/src/modules/command/command.c b/src/modules/command/command.c index b39f4cd6f..f26355d90 100644 --- a/src/modules/command/command.c +++ b/src/modules/command/command.c @@ -3,102 +3,78 @@ #include "modules/command/command.h" #include "detection/command/command.h" -bool ffPrintCommand(FFCommandOptions* options) -{ +bool ffPrintCommand(FFCommandOptions* options) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); const char* error = ffDetectCommand(options, &result); - if (error) - { + if (error) { ffPrintError(FF_COMMAND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if (!result.length) - { + if (!result.length) { ffPrintError(FF_COMMAND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No result generated"); return false; } - if (options->splitLines) - { + if (options->splitLines) { uint8_t index = 0; char* line = NULL; size_t len = 0; - while (ffStrbufGetline(&line, &len, &result)) - { - if (options->moduleArgs.outputFormat.length == 0) - { + while (ffStrbufGetline(&line, &len, &result)) { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_COMMAND_MODULE_NAME, ++index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); puts(line); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_COMMAND_MODULE_NAME, ++index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(line, "result") - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_COMMAND_MODULE_NAME, ++index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) {FF_ARG(line, "result")})); } } - } - else - { - if (options->moduleArgs.outputFormat.length == 0) - { + } else { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_COMMAND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&result, stdout); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_COMMAND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result, "result") - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_COMMAND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) {FF_ARG(result, "result")})); } } return true; } -void ffParseCommandJsonObject(FFCommandOptions* options, yyjson_val* module) -{ +void ffParseCommandJsonObject(FFCommandOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "shell")) - { + if (unsafe_yyjson_equals_str(key, "shell")) { ffStrbufSetJsonVal(&options->shell, val); continue; } - if (unsafe_yyjson_equals_str(key, "param")) - { + if (unsafe_yyjson_equals_str(key, "param")) { ffStrbufSetJsonVal(&options->param, val); continue; } - if (unsafe_yyjson_equals_str(key, "text")) - { + if (unsafe_yyjson_equals_str(key, "text")) { ffStrbufSetJsonVal(&options->text, val); continue; } - if (unsafe_yyjson_equals_str(key, "useStdErr")) - { + if (unsafe_yyjson_equals_str(key, "useStdErr")) { options->useStdErr = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "parallel")) - { + if (unsafe_yyjson_equals_str(key, "parallel")) { options->parallel = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "splitLines")) - { + if (unsafe_yyjson_equals_str(key, "splitLines")) { options->splitLines = yyjson_get_bool(val); continue; } @@ -107,8 +83,7 @@ void ffParseCommandJsonObject(FFCommandOptions* options, yyjson_val* module) } } -void ffGenerateCommandJsonConfig(FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateCommandJsonConfig(FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_strbuf(doc, module, "shell", &options->shell); @@ -119,54 +94,50 @@ void ffGenerateCommandJsonConfig(FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_obj_add_bool(doc, module, "splitLines", options->splitLines); } -bool ffGenerateCommandJsonResult(FF_MAYBE_UNUSED FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateCommandJsonResult(FF_MAYBE_UNUSED FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); const char* error = ffDetectCommand(options, &result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } - if(!result.length) - { + if (!result.length) { yyjson_mut_obj_add_str(doc, module, "error", "No result generated"); return false; } - if (options->splitLines) - { + if (options->splitLines) { yyjson_mut_val* jsonArray = yyjson_mut_obj_add_arr(doc, module, "result"); char* line = NULL; size_t len = 0; - while (ffStrbufGetline(&line, &len, &result)) + while (ffStrbufGetline(&line, &len, &result)) { yyjson_mut_arr_add_strncpy(doc, jsonArray, line, len); - } - else + } + } else { yyjson_mut_obj_add_strbuf(doc, module, "result", &result); + } return true; } -void ffInitCommandOptions(FFCommandOptions* options) -{ +void ffInitCommandOptions(FFCommandOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); ffStrbufInitStatic(&options->shell, - #ifdef _WIN32 +#ifdef _WIN32 "cmd.exe" - #else +#else "/bin/sh" - #endif +#endif ); ffStrbufInitStatic(&options->param, - #ifdef _WIN32 +#ifdef _WIN32 "/c" - #else +#else "-c" - #endif +#endif ); ffStrbufInit(&options->text); options->useStdErr = false; @@ -174,8 +145,7 @@ void ffInitCommandOptions(FFCommandOptions* options) options->splitLines = false; } -void ffDestroyCommandOptions(FFCommandOptions* options) -{ +void ffDestroyCommandOptions(FFCommandOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->shell); ffStrbufDestroy(&options->param); @@ -193,5 +163,4 @@ FFModuleBaseInfo ffCommandModuleInfo = { .generateJsonConfig = (void*) ffGenerateCommandJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Command result", "result"}, - })) -}; + }))}; diff --git a/src/modules/command/option.h b/src/modules/command/option.h index 06f3b05b3..6b2108fb7 100644 --- a/src/modules/command/option.h +++ b/src/modules/command/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFCommandOptions -{ +typedef struct FFCommandOptions { FFModuleArgs moduleArgs; FFstrbuf shell; diff --git a/src/modules/cpu/cpu.c b/src/modules/cpu/cpu.c index fb154b5f7..18cdf51de 100644 --- a/src/modules/cpu/cpu.c +++ b/src/modules/cpu/cpu.c @@ -6,13 +6,11 @@ #include "detection/cpu/cpu.h" #include "modules/cpu/cpu.h" -static int sortCores(const FFCPUCore* a, const FFCPUCore* b) -{ - return (int)b->freq - (int)a->freq; +static int sortCores(const FFCPUCore* a, const FFCPUCore* b) { + return (int) b->freq - (int) a->freq; } -bool ffPrintCPU(FFCPUOptions* options) -{ +bool ffPrintCPU(FFCPUOptions* options) { bool success = false; FFCPUResult cpu = { .temperature = FF_CPU_TEMP_UNSET, @@ -24,73 +22,66 @@ bool ffPrintCPU(FFCPUOptions* options) const char* error = ffDetectCPU(options, &cpu); - if(error) - { + if (error) { ffPrintError(FF_CPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); - } - else if(cpu.vendor.length == 0 && cpu.name.length == 0 && cpu.coresOnline <= 1) - { + } else if (cpu.vendor.length == 0 && cpu.name.length == 0 && cpu.coresOnline <= 1) { ffPrintError(FF_CPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No CPU detected"); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY coreTypes = ffStrbufCreate(); - if (options->showPeCoreCount) - { + if (options->showPeCoreCount) { uint32_t typeCount = 0; - while (cpu.coreTypes[typeCount].count != 0 && typeCount < ARRAY_SIZE(cpu.coreTypes)) typeCount++; - if (typeCount > 0) - { + while (cpu.coreTypes[typeCount].count != 0 && typeCount < ARRAY_SIZE(cpu.coreTypes)) { + typeCount++; + } + if (typeCount > 0) { qsort(cpu.coreTypes, typeCount, sizeof(cpu.coreTypes[0]), (void*) sortCores); - for (uint32_t i = 0; i < typeCount; i++) + for (uint32_t i = 0; i < typeCount; i++) { ffStrbufAppendF(&coreTypes, "%s%u", i == 0 ? "" : "+", cpu.coreTypes[i].count); + } } } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_CPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); - if(cpu.packages > 1) + if (cpu.packages > 1) { ffStrbufAppendF(&str, "%u x ", cpu.packages); + } - if(cpu.name.length > 0) + if (cpu.name.length > 0) { ffStrbufAppend(&str, &cpu.name); - else if(cpu.vendor.length > 0) - { + } else if (cpu.vendor.length > 0) { ffStrbufAppend(&str, &cpu.vendor); ffStrbufAppendS(&str, " CPU"); - } - else + } else { ffStrbufAppendS(&str, "Unknown"); + } - if(coreTypes.length > 0) + if (coreTypes.length > 0) { ffStrbufAppendF(&str, " (%s)", coreTypes.chars); - else if(cpu.coresOnline > 1) + } else if (cpu.coresOnline > 1) { ffStrbufAppendF(&str, " (%u)", cpu.coresOnline); + } uint32_t freq = cpu.frequencyMax; - if(freq == 0) + if (freq == 0) { freq = cpu.frequencyBase; - if(freq > 0) - { + } + if (freq > 0) { ffStrbufAppendS(&str, " @ "); ffFreqAppendNum(freq, &str); } - if(cpu.temperature != FF_CPU_TEMP_UNSET) - { + if (cpu.temperature != FF_CPU_TEMP_UNSET) { ffStrbufAppendS(&str, " - "); ffTempsAppendNum(cpu.temperature, &str, options->tempConfig, &options->moduleArgs); } ffStrbufPutTo(&str, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY freqBase = ffStrbufCreate(); ffFreqAppendNum(cpu.frequencyBase, &freqBase); FF_STRBUF_AUTO_DESTROY freqMax = ffStrbufCreate(); @@ -98,20 +89,20 @@ bool ffPrintCPU(FFCPUOptions* options) FF_STRBUF_AUTO_DESTROY tempStr = ffStrbufCreate(); ffTempsAppendNum(cpu.temperature, &tempStr, options->tempConfig, &options->moduleArgs); - FF_PRINT_FORMAT_CHECKED(FF_CPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(cpu.name, "name"), - FF_ARG(cpu.vendor, "vendor"), - FF_ARG(cpu.coresPhysical, "cores-physical"), - FF_ARG(cpu.coresLogical, "cores-logical"), - FF_ARG(cpu.coresOnline, "cores-online"), - FF_ARG(freqBase, "freq-base"), - FF_ARG(freqMax, "freq-max"), - FF_ARG(tempStr, "temperature"), - FF_ARG(coreTypes, "core-types"), - FF_ARG(cpu.packages, "packages"), - FF_ARG(cpu.march, "march"), - FF_ARG(cpu.numaNodes, "numa-nodes"), - })); + FF_PRINT_FORMAT_CHECKED(FF_CPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(cpu.name, "name"), + FF_ARG(cpu.vendor, "vendor"), + FF_ARG(cpu.coresPhysical, "cores-physical"), + FF_ARG(cpu.coresLogical, "cores-logical"), + FF_ARG(cpu.coresOnline, "cores-online"), + FF_ARG(freqBase, "freq-base"), + FF_ARG(freqMax, "freq-max"), + FF_ARG(tempStr, "temperature"), + FF_ARG(coreTypes, "core-types"), + FF_ARG(cpu.packages, "packages"), + FF_ARG(cpu.march, "march"), + FF_ARG(cpu.numaNodes, "numa-nodes"), + })); } success = true; } @@ -122,32 +113,29 @@ bool ffPrintCPU(FFCPUOptions* options) return success; } -void ffParseCPUJsonObject(FFCPUOptions* options, yyjson_val* module) -{ +void ffParseCPUJsonObject(FFCPUOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) + if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) { continue; + } - if (unsafe_yyjson_equals_str(key, "tempSensor")) - { + if (unsafe_yyjson_equals_str(key, "tempSensor")) { ffStrbufSetJsonVal(&options->tempSensor, val); continue; } - if (unsafe_yyjson_equals_str(key, "freqNdigits")) - { + if (unsafe_yyjson_equals_str(key, "freqNdigits")) { ffPrintError(FF_CPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "modules.CPU.freqNdigits has been moved to display.freq.ndigits"); continue; } - if (unsafe_yyjson_equals_str(key, "showPeCoreCount")) - { + if (unsafe_yyjson_equals_str(key, "showPeCoreCount")) { options->showPeCoreCount = yyjson_get_bool(val); continue; } @@ -156,8 +144,7 @@ void ffParseCPUJsonObject(FFCPUOptions* options, yyjson_val* module) } } -void ffGenerateCPUJsonConfig(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateCPUJsonConfig(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); ffTempsGenerateJsonConfig(doc, module, options->temp, options->tempConfig); @@ -165,8 +152,7 @@ void ffGenerateCPUJsonConfig(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_ yyjson_mut_obj_add_bool(doc, module, "showPeCoreCount", options->showPeCoreCount); } -bool ffGenerateCPUJsonResult(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateCPUJsonResult(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFCPUResult cpu = { .temperature = FF_CPU_TEMP_UNSET, @@ -178,23 +164,19 @@ bool ffGenerateCPUJsonResult(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_ const char* error = ffDetectCPU(options, &cpu); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); - } - else if(cpu.vendor.length == 0 && cpu.name.length == 0 && cpu.coresOnline <= 1) - { + } else if (cpu.vendor.length == 0 && cpu.name.length == 0 && cpu.coresOnline <= 1) { yyjson_mut_obj_add_str(doc, module, "error", "No CPU detected"); - } - else - { + } else { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); yyjson_mut_obj_add_strbuf(doc, obj, "cpu", &cpu.name); yyjson_mut_obj_add_strbuf(doc, obj, "vendor", &cpu.vendor); - if (cpu.packages == 0) + if (cpu.packages == 0) { yyjson_mut_obj_add_null(doc, obj, "packages"); - else + } else { yyjson_mut_obj_add_uint(doc, obj, "packages", cpu.packages); + } yyjson_mut_val* cores = yyjson_mut_obj_add_obj(doc, obj, "cores"); yyjson_mut_obj_add_uint(doc, cores, "physical", cpu.coresPhysical); @@ -206,27 +188,29 @@ bool ffGenerateCPUJsonResult(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_ yyjson_mut_obj_add_uint(doc, frequency, "max", cpu.frequencyMax); yyjson_mut_val* coreTypes = yyjson_mut_obj_add_arr(doc, obj, "coreTypes"); - for (uint32_t i = 0; i < ARRAY_SIZE(cpu.coreTypes) && cpu.coreTypes[i].count > 0; i++) - { + for (uint32_t i = 0; i < ARRAY_SIZE(cpu.coreTypes) && cpu.coreTypes[i].count > 0; i++) { yyjson_mut_val* core = yyjson_mut_arr_add_obj(doc, coreTypes); yyjson_mut_obj_add_uint(doc, core, "count", cpu.coreTypes[i].count); yyjson_mut_obj_add_uint(doc, core, "freq", cpu.coreTypes[i].freq); } - if (cpu.temperature != FF_CPU_TEMP_UNSET) + if (cpu.temperature != FF_CPU_TEMP_UNSET) { yyjson_mut_obj_add_real(doc, obj, "temperature", cpu.temperature); - else + } else { yyjson_mut_obj_add_null(doc, obj, "temperature"); + } - if (cpu.march) + if (cpu.march) { yyjson_mut_obj_add_str(doc, obj, "march", cpu.march); - else + } else { yyjson_mut_obj_add_null(doc, obj, "march"); + } - if (cpu.numaNodes > 0) + if (cpu.numaNodes > 0) { yyjson_mut_obj_add_uint(doc, obj, "numaNodes", cpu.numaNodes); - else + } else { yyjson_mut_obj_add_null(doc, obj, "numaNodes"); + } success = true; } @@ -237,17 +221,15 @@ bool ffGenerateCPUJsonResult(FFCPUOptions* options, yyjson_mut_doc* doc, yyjson_ return success; } -void ffInitCPUOptions(FFCPUOptions* options) -{ +void ffInitCPUOptions(FFCPUOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); ffStrbufInit(&options->tempSensor); options->temp = false; - options->tempConfig = (FFColorRangeConfig) { 60, 80 }; + options->tempConfig = (FFColorRangeConfig) {60, 80}; options->showPeCoreCount = false; } -void ffDestroyCPUOptions(FFCPUOptions* options) -{ +void ffDestroyCPUOptions(FFCPUOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->tempSensor); } @@ -274,5 +256,4 @@ FFModuleBaseInfo ffCPUModuleInfo = { {"Processor package count", "packages"}, {"CPU microarchitecture", "march"}, {"NUMA node count", "numa-nodes"}, - })) -}; + }))}; diff --git a/src/modules/cpu/option.h b/src/modules/cpu/option.h index 428b40a6b..037863527 100644 --- a/src/modules/cpu/option.h +++ b/src/modules/cpu/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFCPUOptions -{ +typedef struct FFCPUOptions { FFModuleArgs moduleArgs; FFstrbuf tempSensor; diff --git a/src/modules/cpucache/cpucache.c b/src/modules/cpucache/cpucache.c index 7996d3c11..f888362bf 100644 --- a/src/modules/cpucache/cpucache.c +++ b/src/modules/cpucache/cpucache.c @@ -7,102 +7,100 @@ #define FF_CPUCACHE_DISPLAY_NAME "CPU Cache" -static void printCPUCacheNormal(const FFCPUCacheResult* result, FFCPUCacheOptions* options) -{ +static void printCPUCacheNormal(const FFCPUCacheResult* result, FFCPUCacheOptions* options) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); char levelStr[4] = "L"; - for (uint32_t i = 0; i < ARRAY_SIZE(result->caches) && result->caches[i].length > 0; i++) - { + for (uint32_t i = 0; i < ARRAY_SIZE(result->caches) && result->caches[i].length > 0; i++) { ffStrbufClear(&key); levelStr[1] = (char) ('1' + i); - if (options->moduleArgs.key.length == 0) + if (options->moduleArgs.key.length == 0) { ffStrbufAppendF(&key, "%s (%s)", FF_CPUCACHE_DISPLAY_NAME, levelStr); - else - { + } else { uint32_t index = i + 1; FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(levelStr, "level"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(levelStr, "level"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } ffStrbufClear(&buffer); uint32_t sum = 0; - FF_LIST_FOR_EACH(FFCPUCache, src, result->caches[i]) - { + FF_LIST_FOR_EACH (FFCPUCache, src, result->caches[i]) { char typeStr = '?'; - switch (src->type) - { - case FF_CPU_CACHE_TYPE_DATA: typeStr = 'D'; break; - case FF_CPU_CACHE_TYPE_INSTRUCTION: typeStr = 'I'; break; - case FF_CPU_CACHE_TYPE_UNIFIED: typeStr = 'U'; break; - case FF_CPU_CACHE_TYPE_TRACE: typeStr = 'T'; break; + switch (src->type) { + case FF_CPU_CACHE_TYPE_DATA: + typeStr = 'D'; + break; + case FF_CPU_CACHE_TYPE_INSTRUCTION: + typeStr = 'I'; + break; + case FF_CPU_CACHE_TYPE_UNIFIED: + typeStr = 'U'; + break; + case FF_CPU_CACHE_TYPE_TRACE: + typeStr = 'T'; + break; } - if (buffer.length) + if (buffer.length) { ffStrbufAppendS(&buffer, ", "); - if (src->num > 1) + } + if (src->num > 1) { ffStrbufAppendF(&buffer, "%ux", src->num); + } ffSizeAppendNum(src->size, &buffer); ffStrbufAppendF(&buffer, " (%c)", typeStr); sum += src->size * src->num; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY buffer2 = ffStrbufCreate(); ffSizeAppendNum(sum, &buffer2); FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(buffer, "result"), - FF_ARG(buffer2, "sum"), - })); + FF_ARG(buffer, "result"), + FF_ARG(buffer2, "sum"), + })); } } } -static void printCPUCacheCompact(const FFCPUCacheResult* result, FFCPUCacheOptions* options) -{ +static void printCPUCacheCompact(const FFCPUCacheResult* result, FFCPUCacheOptions* options) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); uint64_t sum = 0; - for (uint32_t i = 0; i < ARRAY_SIZE(result->caches) && result->caches[i].length > 0; i++) - { - if (buffer.length) + for (uint32_t i = 0; i < ARRAY_SIZE(result->caches) && result->caches[i].length > 0; i++) { + if (buffer.length) { ffStrbufAppendS(&buffer, ", "); + } uint32_t value = 0; - FF_LIST_FOR_EACH(FFCPUCache, src, result->caches[i]) + FF_LIST_FOR_EACH (FFCPUCache, src, result->caches[i]) { value += src->size * src->num; + } ffSizeAppendNum(value, &buffer); ffStrbufAppendF(&buffer, " (L%u)", i + 1); sum += value; } - if (options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_CPUCACHE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY buffer2 = ffStrbufCreate(); ffSizeAppendNum(sum, &buffer2); FF_PRINT_FORMAT_CHECKED(FF_CPUCACHE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(buffer, "result"), - FF_ARG(buffer2, "sum"), - })); + FF_ARG(buffer, "result"), + FF_ARG(buffer2, "sum"), + })); } } -bool ffPrintCPUCache(FFCPUCacheOptions* options) -{ +bool ffPrintCPUCache(FFCPUCacheOptions* options) { bool success = false; FFCPUCacheResult result = { .caches = { @@ -115,16 +113,16 @@ bool ffPrintCPUCache(FFCPUCacheOptions* options) const char* error = ffDetectCPUCache(&result); - if(error) - { + if (error) { ffPrintError(FF_CPUCACHE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if (!options->compact) + if (!options->compact) { printCPUCacheNormal(&result, options); - else + } else { printCPUCacheCompact(&result, options); + } success = true; exit: @@ -136,17 +134,15 @@ exit: return success; } -void ffParseCPUCacheJsonObject(FFCPUCacheOptions* options, yyjson_val* module) -{ +void ffParseCPUCacheJsonObject(FFCPUCacheOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "compact")) - { + if (unsafe_yyjson_equals_str(key, "compact")) { options->compact = yyjson_get_bool(val); continue; } @@ -155,15 +151,13 @@ void ffParseCPUCacheJsonObject(FFCPUCacheOptions* options, yyjson_val* module) } } -void ffGenerateCPUCacheJsonConfig(FFCPUCacheOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateCPUCacheJsonConfig(FFCPUCacheOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "compact", options->compact); } -bool ffGenerateCPUCacheJsonResult(FF_MAYBE_UNUSED FFCPUCacheOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateCPUCacheJsonResult(FF_MAYBE_UNUSED FFCPUCacheOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFCPUCacheResult result = { .caches = { @@ -176,29 +170,33 @@ bool ffGenerateCPUCacheJsonResult(FF_MAYBE_UNUSED FFCPUCacheOptions* options, yy const char* error = ffDetectCPUCache(&result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } yyjson_mut_val* caches = yyjson_mut_obj_add_obj(doc, module, "result"); - for (uint32_t i = 0; i < ARRAY_SIZE(result.caches) && result.caches[i].length > 0; i++) - { + for (uint32_t i = 0; i < ARRAY_SIZE(result.caches) && result.caches[i].length > 0; i++) { yyjson_mut_val* level = yyjson_mut_obj_add_arr(doc, caches, &"l1\0l2\0l3\0l4\0"[i * 3]); - FF_LIST_FOR_EACH(FFCPUCache, src, result.caches[i]) - { + FF_LIST_FOR_EACH (FFCPUCache, src, result.caches[i]) { yyjson_mut_val* item = yyjson_mut_arr_add_obj(doc, level); yyjson_mut_obj_add_uint(doc, item, "size", src->size); yyjson_mut_obj_add_uint(doc, item, "num", src->num); const char* typeStr = "unknown"; - switch (src->type) - { - case FF_CPU_CACHE_TYPE_DATA: typeStr = "data"; break; - case FF_CPU_CACHE_TYPE_INSTRUCTION: typeStr = "instruction"; break; - case FF_CPU_CACHE_TYPE_UNIFIED: typeStr = "unified"; break; - case FF_CPU_CACHE_TYPE_TRACE: typeStr = "trace"; break; + switch (src->type) { + case FF_CPU_CACHE_TYPE_DATA: + typeStr = "data"; + break; + case FF_CPU_CACHE_TYPE_INSTRUCTION: + typeStr = "instruction"; + break; + case FF_CPU_CACHE_TYPE_UNIFIED: + typeStr = "unified"; + break; + case FF_CPU_CACHE_TYPE_TRACE: + typeStr = "trace"; + break; } yyjson_mut_obj_add_uint(doc, item, "lineSize", src->lineSize); yyjson_mut_obj_add_str(doc, item, "type", typeStr); @@ -214,15 +212,13 @@ exit: return success; } -void ffInitCPUCacheOptions(FFCPUCacheOptions* options) -{ +void ffInitCPUCacheOptions(FFCPUCacheOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); options->compact = false; } -void ffDestroyCPUCacheOptions(FFCPUCacheOptions* options) -{ +void ffDestroyCPUCacheOptions(FFCPUCacheOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -238,5 +234,4 @@ FFModuleBaseInfo ffCPUCacheModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Separate result", "result"}, {"Sum result", "sum"}, - })) -}; + }))}; diff --git a/src/modules/cpucache/option.h b/src/modules/cpucache/option.h index f53acf691..186df9a4c 100644 --- a/src/modules/cpucache/option.h +++ b/src/modules/cpucache/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFCPUCacheOptions -{ +typedef struct FFCPUCacheOptions { FFModuleArgs moduleArgs; bool compact; diff --git a/src/modules/cpuusage/cpuusage.c b/src/modules/cpuusage/cpuusage.c index 0013336c8..9eedeae8f 100644 --- a/src/modules/cpuusage/cpuusage.c +++ b/src/modules/cpuusage/cpuusage.c @@ -7,13 +7,11 @@ #define FF_CPUUSAGE_DISPLAY_NAME "CPU Usage" -bool ffPrintCPUUsage(FFCPUUsageOptions* options) -{ +bool ffPrintCPUUsage(FFCPUUsageOptions* options) { FF_LIST_AUTO_DESTROY percentages = ffListCreate(sizeof(double)); const char* error = ffGetCpuUsageResult(options, &percentages); - if(error) - { + if (error) { ffPrintError(FF_CPUUSAGE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } @@ -22,24 +20,22 @@ bool ffPrintCPUUsage(FFCPUUsageOptions* options) uint32_t maxIndex = 999, minIndex = 999; uint32_t index = 0, valueCount = 0; - FF_LIST_FOR_EACH(double, percent, percentages) - { - if (*percent == *percent) - { + FF_LIST_FOR_EACH (double, percent, percentages) { + if (*percent == *percent) { sumValue += *percent; - #if _WIN32 +#if _WIN32 // Windows may return values greater than 100%, cap them to 100% - if (*percent > 100) *percent = 100; - #endif + if (*percent > 100) { + *percent = 100; + } +#endif - if (*percent > maxValue) - { + if (*percent > maxValue) { maxValue = *percent; maxIndex = index; } - if (*percent < minValue) - { + if (*percent < minValue) { minValue = *percent; minIndex = index; } @@ -48,106 +44,106 @@ bool ffPrintCPUUsage(FFCPUUsageOptions* options) ++index; } double avgValue = sumValue / (double) valueCount; - #if _WIN32 +#if _WIN32 // See above comment - if (avgValue > 100) avgValue = 100; - #endif + if (avgValue > 100) { + avgValue = 100; + } +#endif FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_CPUUSAGE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); - if (!options->separate) - { - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (!options->separate) { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&str, avgValue, options->percent, &options->moduleArgs); - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) - { - if(str.length > 0) + } + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { + if (str.length > 0) { ffStrbufAppendC(&str, ' '); + } ffPercentAppendNum(&str, avgValue, options->percent, str.length > 0, &options->moduleArgs); } - } - else - { - FF_LIST_FOR_EACH(double, percent, percentages) - { - if(str.length > 0) + } else { + FF_LIST_FOR_EACH (double, percent, percentages) { + if (str.length > 0) { ffStrbufAppendC(&str, ' '); + } ffPercentAppendNum(&str, *percent, options->percent, false, &options->moduleArgs); } } ffStrbufPutTo(&str, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY avgNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&avgNum, avgValue, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY avgBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&avgBar, avgValue, options->percent, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY minNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&minNum, minValue, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY minBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&minBar, minValue, options->percent, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY maxNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&maxNum, maxValue, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY maxBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&maxBar, maxValue, options->percent, &options->moduleArgs); + } - FF_PRINT_FORMAT_CHECKED(FF_CPUUSAGE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(avgNum, "avg"), - FF_ARG(maxNum, "max"), - FF_ARG(maxIndex, "max-index"), - FF_ARG(minNum, "min"), - FF_ARG(minIndex, "min-index"), - FF_ARG(avgBar, "avg-bar"), - FF_ARG(maxBar, "max-bar"), - FF_ARG(minBar, "min-bar"), - })); + FF_PRINT_FORMAT_CHECKED(FF_CPUUSAGE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(avgNum, "avg"), + FF_ARG(maxNum, "max"), + FF_ARG(maxIndex, "max-index"), + FF_ARG(minNum, "min"), + FF_ARG(minIndex, "min-index"), + FF_ARG(avgBar, "avg-bar"), + FF_ARG(maxBar, "max-bar"), + FF_ARG(minBar, "min-bar"), + })); } return true; } -void ffParseCPUUsageJsonObject(FFCPUUsageOptions* options, yyjson_val* module) -{ +void ffParseCPUUsageJsonObject(FFCPUUsageOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "separate")) - { + if (unsafe_yyjson_equals_str(key, "separate")) { options->separate = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "waitTime")) - { + if (unsafe_yyjson_equals_str(key, "waitTime")) { options->waitTime = (uint32_t) yyjson_get_uint(val); continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_CPUUSAGE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateCPUUsageJsonConfig(FFCPUUsageOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateCPUUsageJsonConfig(FFCPUUsageOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "separate", options->separate); @@ -157,35 +153,30 @@ void ffGenerateCPUUsageJsonConfig(FFCPUUsageOptions* options, yyjson_mut_doc* do yyjson_mut_obj_add_uint(doc, module, "waitTime", options->waitTime); } -bool ffGenerateCPUUsageJsonResult(FFCPUUsageOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateCPUUsageJsonResult(FFCPUUsageOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY percentages = ffListCreate(sizeof(double)); const char* error = ffGetCpuUsageResult(options, &percentages); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* result = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(double, percent, percentages) - { + FF_LIST_FOR_EACH (double, percent, percentages) { yyjson_mut_arr_add_real(doc, result, *percent); } return true; } -void ffInitCPUUsageOptions(FFCPUUsageOptions* options) -{ +void ffInitCPUUsageOptions(FFCPUUsageOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰓅"); options->separate = false; - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; options->waitTime = 200; } -void ffDestroyCPUUsageOptions(FFCPUUsageOptions* options) -{ +void ffDestroyCPUUsageOptions(FFCPUUsageOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -207,5 +198,4 @@ FFModuleBaseInfo ffCPUUsageModuleInfo = { {"CPU usage (percentage bar, average)", "avg-bar"}, {"CPU usage (percentage bar, maximum)", "max-bar"}, {"CPU usage (percentage bar, minimum)", "min-bar"}, - })) -}; + }))}; diff --git a/src/modules/cpuusage/option.h b/src/modules/cpuusage/option.h index dc19fbe76..da9512b42 100644 --- a/src/modules/cpuusage/option.h +++ b/src/modules/cpuusage/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFCPUUsageOptions -{ +typedef struct FFCPUUsageOptions { FFModuleArgs moduleArgs; bool separate; diff --git a/src/modules/cursor/cursor.c b/src/modules/cursor/cursor.c index 2cec14031..1900fc0c8 100644 --- a/src/modules/cursor/cursor.c +++ b/src/modules/cursor/cursor.c @@ -4,8 +4,7 @@ #include "detection/cursor/cursor.h" #include "modules/cursor/cursor.h" -bool ffPrintCursor(FFCursorOptions* options) -{ +bool ffPrintCursor(FFCursorOptions* options) { bool success = false; FFCursorResult result; ffStrbufInit(&result.error); @@ -14,33 +13,31 @@ bool ffPrintCursor(FFCursorOptions* options) ffDetectCursor(&result); - if(result.error.length) + if (result.error.length) { ffPrintError(FF_CURSOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", result.error.chars); - else - { + } else { ffStrbufRemoveIgnCaseEndS(&result.theme, "cursors"); ffStrbufRemoveIgnCaseEndS(&result.theme, "cursor"); ffStrbufTrimRight(&result.theme, '_'); ffStrbufTrimRight(&result.theme, '-'); - if(result.theme.length == 0) + if (result.theme.length == 0) { ffStrbufAppendS(&result.theme, "default"); + } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_CURSOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result.theme, stdout); - if(result.size.length > 0 && !ffStrbufEqualS(&result.size, "0")) + if (result.size.length > 0 && !ffStrbufEqualS(&result.size, "0")) { printf(" (%spx)", result.size.chars); + } putchar('\n'); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_CURSOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result.theme, "theme"), - FF_ARG(result.size, "size"), - })); + FF_ARG(result.theme, "theme"), + FF_ARG(result.size, "size"), + })); } success = true; @@ -53,26 +50,23 @@ bool ffPrintCursor(FFCursorOptions* options) return success; } -void ffParseCursorJsonObject(FFCursorOptions* options, yyjson_val* module) -{ +void ffParseCursorJsonObject(FFCursorOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_CURSOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateCursorJsonConfig(FFCursorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateCursorJsonConfig(FFCursorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateCursorJsonResult(FF_MAYBE_UNUSED FFCursorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateCursorJsonResult(FF_MAYBE_UNUSED FFCursorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFCursorResult result; ffStrbufInit(&result.error); @@ -81,12 +75,9 @@ bool ffGenerateCursorJsonResult(FF_MAYBE_UNUSED FFCursorOptions* options, yyjson ffDetectCursor(&result); - if (result.error.length) - { + if (result.error.length) { yyjson_mut_obj_add_strbuf(doc, module, "error", &result.error); - } - else - { + } else { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); yyjson_mut_obj_add_strbuf(doc, obj, "theme", &result.theme); yyjson_mut_obj_add_strbuf(doc, obj, "size", &result.size); @@ -100,13 +91,11 @@ bool ffGenerateCursorJsonResult(FF_MAYBE_UNUSED FFCursorOptions* options, yyjson return success; } -void ffInitCursorOptions(FFCursorOptions* options) -{ +void ffInitCursorOptions(FFCursorOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰆿"); } -void ffDestroyCursorOptions(FFCursorOptions* options) -{ +void ffDestroyCursorOptions(FFCursorOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } diff --git a/src/modules/cursor/option.h b/src/modules/cursor/option.h index 3f02c567c..1a8e17267 100644 --- a/src/modules/cursor/option.h +++ b/src/modules/cursor/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFCursorOptions -{ +typedef struct FFCursorOptions { FFModuleArgs moduleArgs; } FFCursorOptions; diff --git a/src/modules/custom/custom.c b/src/modules/custom/custom.c index 95a9bd5c0..036921553 100644 --- a/src/modules/custom/custom.c +++ b/src/modules/custom/custom.c @@ -4,38 +4,33 @@ #include "common/stringUtils.h" #include "modules/custom/custom.h" -bool ffPrintCustom(FFCustomOptions* options) -{ +bool ffPrintCustom(FFCustomOptions* options) { ffPrintFormat(FF_CUSTOM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, 0, ((FFformatarg[]) {})); return true; } -void ffGenerateCustomJsonConfig(FFCustomOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateCustomJsonConfig(FFCustomOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -void ffParseCustomJsonObject(FFCustomOptions* options, yyjson_val* module) -{ +void ffParseCustomJsonObject(FFCustomOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_CUSTOM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffInitCustomOptions(FFCustomOptions* options) -{ +void ffInitCustomOptions(FFCustomOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); ffStrbufSetStatic(&options->moduleArgs.key, " "); } -void ffDestroyCustomOptions(FFCustomOptions* options) -{ +void ffDestroyCustomOptions(FFCustomOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } diff --git a/src/modules/custom/option.h b/src/modules/custom/option.h index c66ccee7d..2a7e5e422 100644 --- a/src/modules/custom/option.h +++ b/src/modules/custom/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFCustomOptions -{ +typedef struct FFCustomOptions { FFModuleArgs moduleArgs; } FFCustomOptions; diff --git a/src/modules/datetime/datetime.c b/src/modules/datetime/datetime.c index ebcee3e90..ffdf78f6b 100644 --- a/src/modules/datetime/datetime.c +++ b/src/modules/datetime/datetime.c @@ -10,36 +10,34 @@ #define FF_DATETIME_DISPLAY_NAME "Date & Time" -typedef struct FFDateTimeResult -{ - //Examples for 21.02.2022 - 15:18:37 - uint16_t year; //2022 - uint8_t yearShort; //22 - uint8_t month; //2 - char monthPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //02 - char monthName[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //February - char monthNameShort[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //Feb - uint8_t week; //8 - char weekday[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //Monday - char weekdayShort[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //Mon - uint16_t dayInYear; //52 - uint8_t dayInMonth; //21 - uint8_t dayInWeek; //1 - char dayPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //01 - uint8_t hour; //15 - char hourPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //15 - uint8_t hour12; //3 - char hour12Pretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //03 - uint8_t minute; //18 - char minutePretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //18 - uint8_t second; //37 - char secondPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; //37 +typedef struct FFDateTimeResult { + // Examples for 21.02.2022 - 15:18:37 + uint16_t year; // 2022 + uint8_t yearShort; // 22 + uint8_t month; // 2 + char monthPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // 02 + char monthName[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // February + char monthNameShort[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // Feb + uint8_t week; // 8 + char weekday[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // Monday + char weekdayShort[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // Mon + uint16_t dayInYear; // 52 + uint8_t dayInMonth; // 21 + uint8_t dayInWeek; // 1 + char dayPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // 01 + uint8_t hour; // 15 + char hourPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // 15 + uint8_t hour12; // 3 + char hour12Pretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // 03 + uint8_t minute; // 18 + char minutePretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // 18 + uint8_t second; // 37 + char secondPretty[FASTFETCH_STRBUF_DEFAULT_ALLOC]; // 37 char offsetFromUtc[FASTFETCH_STRBUF_DEFAULT_ALLOC]; char timezoneName[FASTFETCH_STRBUF_DEFAULT_ALLOC]; } FFDateTimeResult; -static void printDateTimeFormat(struct tm* tm, const FFModuleArgs* moduleArgs) -{ +static void printDateTimeFormat(struct tm* tm, const FFModuleArgs* moduleArgs) { FFDateTimeResult result; result.year = (uint16_t) (tm->tm_year + 1900); @@ -67,46 +65,44 @@ static void printDateTimeFormat(struct tm* tm, const FFModuleArgs* moduleArgs) strftime(result.timezoneName, sizeof(result.timezoneName), "%Z", tm); FF_PRINT_FORMAT_CHECKED(FF_DATETIME_DISPLAY_NAME, 0, moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result.year, "year"), // 1 - FF_ARG(result.yearShort, "year-short"), // 2 - FF_ARG(result.month, "month"), // 3 - FF_ARG(result.monthPretty, "month-pretty"), // 4 - FF_ARG(result.monthName, "month-name"), // 5 - FF_ARG(result.monthNameShort, "month-name-short"), // 6 - FF_ARG(result.week, "week"), // 7 - FF_ARG(result.weekday, "weekday"), // 8 - FF_ARG(result.weekdayShort, "weekday-short"), // 9 - FF_ARG(result.dayInYear, "day-in-year"), // 10 - FF_ARG(result.dayInMonth, "day-in-month"), // 11 - FF_ARG(result.dayInWeek, "day-in-week"), // 12 - FF_ARG(result.hour, "hour"), // 13 - FF_ARG(result.hourPretty, "hour-pretty"), // 14 - FF_ARG(result.hour12, "hour-12"), // 15 - FF_ARG(result.hour12Pretty, "hour-12-pretty"), // 16 - FF_ARG(result.minute, "minute"), // 17 - FF_ARG(result.minutePretty, "minute-pretty"), // 18 - FF_ARG(result.second, "second"), // 19 - FF_ARG(result.secondPretty, "second-pretty"), // 20 - FF_ARG(result.offsetFromUtc, "offset-from-utc"), // 21 - FF_ARG(result.timezoneName, "timezone-name"), // 22 - FF_ARG(result.dayPretty, "day-pretty"), // 23 - })); + FF_ARG(result.year, "year"), // 1 + FF_ARG(result.yearShort, "year-short"), // 2 + FF_ARG(result.month, "month"), // 3 + FF_ARG(result.monthPretty, "month-pretty"), // 4 + FF_ARG(result.monthName, "month-name"), // 5 + FF_ARG(result.monthNameShort, "month-name-short"), // 6 + FF_ARG(result.week, "week"), // 7 + FF_ARG(result.weekday, "weekday"), // 8 + FF_ARG(result.weekdayShort, "weekday-short"), // 9 + FF_ARG(result.dayInYear, "day-in-year"), // 10 + FF_ARG(result.dayInMonth, "day-in-month"), // 11 + FF_ARG(result.dayInWeek, "day-in-week"), // 12 + FF_ARG(result.hour, "hour"), // 13 + FF_ARG(result.hourPretty, "hour-pretty"), // 14 + FF_ARG(result.hour12, "hour-12"), // 15 + FF_ARG(result.hour12Pretty, "hour-12-pretty"), // 16 + FF_ARG(result.minute, "minute"), // 17 + FF_ARG(result.minutePretty, "minute-pretty"), // 18 + FF_ARG(result.second, "second"), // 19 + FF_ARG(result.secondPretty, "second-pretty"), // 20 + FF_ARG(result.offsetFromUtc, "offset-from-utc"), // 21 + FF_ARG(result.timezoneName, "timezone-name"), // 22 + FF_ARG(result.dayPretty, "day-pretty"), // 23 + })); } -bool ffPrintDateTime(FFDateTimeOptions* options) -{ +bool ffPrintDateTime(FFDateTimeOptions* options) { uint64_t msNow = ffTimeGetNow(); time_t sNow = (time_t) (msNow / 1000); struct tm* tm = localtime(&sNow); - if(options->moduleArgs.outputFormat.length > 0) - { + if (options->moduleArgs.outputFormat.length > 0) { printDateTimeFormat(tm, &options->moduleArgs); return true; } char buffer[32]; - if (strftime(buffer, ARRAY_SIZE(buffer), "%F %T", tm) == 0) //yyyy-MM-dd HH:mm:ss + if (strftime(buffer, ARRAY_SIZE(buffer), "%F %T", tm) == 0) // yyyy-MM-dd HH:mm:ss { ffPrintError(FF_DATETIME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "strftime() failed"); return false; @@ -118,37 +114,32 @@ bool ffPrintDateTime(FFDateTimeOptions* options) return true; } -void ffParseDateTimeJsonObject(FFDateTimeOptions* options, yyjson_val* module) -{ +void ffParseDateTimeJsonObject(FFDateTimeOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_DATETIME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateDateTimeJsonConfig(FFDateTimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateDateTimeJsonConfig(FFDateTimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateDateTimeJsonResult(FF_MAYBE_UNUSED FFDateTimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateDateTimeJsonResult(FF_MAYBE_UNUSED FFDateTimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_obj_add_strcpy(doc, module, "result", ffTimeToFullStr(ffTimeGetNow())); return true; } -void ffInitDateTimeOptions(FFDateTimeOptions* options) -{ +void ffInitDateTimeOptions(FFDateTimeOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyDateTimeOptions(FFDateTimeOptions* options) -{ +void ffDestroyDateTimeOptions(FFDateTimeOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -185,5 +176,4 @@ FFModuleBaseInfo ffDateTimeModuleInfo = { {"Offset from UTC in the ISO 8601 format", "offset-from-utc"}, {"Locale-dependent timezone name or abbreviation", "timezone-name"}, {"Day in month with leading zero", "day-pretty"}, - })) -}; + }))}; diff --git a/src/modules/datetime/option.h b/src/modules/datetime/option.h index fffd5dc51..a060b01b9 100644 --- a/src/modules/datetime/option.h +++ b/src/modules/datetime/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFDateTimeOptions -{ +typedef struct FFDateTimeOptions { FFModuleArgs moduleArgs; } FFDateTimeOptions; diff --git a/src/modules/de/de.c b/src/modules/de/de.c index a6776a13c..a5eb40e9f 100644 --- a/src/modules/de/de.c +++ b/src/modules/de/de.c @@ -5,12 +5,10 @@ #include "detection/de/de.h" #include "modules/de/de.h" -bool ffPrintDE(FFDEOptions* options) -{ +bool ffPrintDE(FFDEOptions* options) { const FFDisplayServerResult* result = ffConnectDisplayServer(); - if(result->dePrettyName.length == 0) - { + if (result->dePrettyName.length == 0) { ffPrintError(FF_DE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No DE found"); return false; } @@ -18,43 +16,33 @@ bool ffPrintDE(FFDEOptions* options) FF_STRBUF_AUTO_DESTROY version = ffStrbufCreate(); ffDetectDEVersion(&result->dePrettyName, &version, options); - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_DE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result->dePrettyName, stdout); - if(version.length > 0) - { + if (version.length > 0) { putchar(' '); ffStrbufWriteTo(&version, stdout); } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_DE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result->deProcessName, "process-name"), - FF_ARG(result->dePrettyName, "pretty-name"), - FF_ARG(version, "version") - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_DE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) {FF_ARG(result->deProcessName, "process-name"), FF_ARG(result->dePrettyName, "pretty-name"), FF_ARG(version, "version")})); } return true; } -void ffParseDEJsonObject(FFDEOptions* options, yyjson_val* module) -{ +void ffParseDEJsonObject(FFDEOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "slowVersionDetection")) - { + if (unsafe_yyjson_equals_str(key, "slowVersionDetection")) { ffPrintError(FF_DE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Key `slowVersionDetection` is deprecated, it's always true"); continue; } @@ -63,17 +51,14 @@ void ffParseDEJsonObject(FFDEOptions* options, yyjson_val* module) } } -void ffGenerateDEJsonConfig(FFDEOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateDEJsonConfig(FFDEOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateDEJsonResult(FF_MAYBE_UNUSED FFDEOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateDEJsonResult(FF_MAYBE_UNUSED FFDEOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFDisplayServerResult* result = ffConnectDisplayServer(); - if(result->dePrettyName.length == 0) - { + if (result->dePrettyName.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "No DE found"); return false; } @@ -88,13 +73,11 @@ bool ffGenerateDEJsonResult(FF_MAYBE_UNUSED FFDEOptions* options, yyjson_mut_doc return true; } -void ffInitDEOptions(FFDEOptions* options) -{ +void ffInitDEOptions(FFDEOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyDEOptions(FFDEOptions* options) -{ +void ffDestroyDEOptions(FFDEOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -111,5 +94,4 @@ FFModuleBaseInfo ffDEModuleInfo = { {"DE process name", "process-name"}, {"DE pretty name", "pretty-name"}, {"DE version", "version"}, - })) -}; + }))}; diff --git a/src/modules/de/option.h b/src/modules/de/option.h index 1c0188b8c..c6113add3 100644 --- a/src/modules/de/option.h +++ b/src/modules/de/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFDEOptions -{ +typedef struct FFDEOptions { FFModuleArgs moduleArgs; } FFDEOptions; diff --git a/src/modules/disk/disk.c b/src/modules/disk/disk.c index 65f9aaefa..874abcd9b 100644 --- a/src/modules/disk/disk.c +++ b/src/modules/disk/disk.c @@ -7,54 +7,45 @@ #include "modules/disk/disk.h" #ifndef _WIN32 - #include +# include #endif #pragma GCC diagnostic ignored "-Wsign-conversion" -static void printDisk(FFDiskOptions* options, const FFDisk* disk, uint32_t index) -{ +static void printDisk(FFDiskOptions* options, const FFDisk* disk, uint32_t index) { FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); - if(options->moduleArgs.key.length == 0) - { + if (options->moduleArgs.key.length == 0) { ffStrbufSetF(&key, "%s (%s)", FF_DISK_MODULE_NAME, disk->mountpoint.chars); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY mountpointLink = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY nameLink = ffStrbufCreate(); - #ifdef __linux__ - if (getenv("WSL_DISTRO_NAME") != NULL && getenv("WT_SESSION") != NULL) - { - if (ffStrbufEqualS(&disk->filesystem, "9p") && ffStrbufStartsWithS(&disk->mountpoint, "/mnt/")) - { +#ifdef __linux__ + if (getenv("WSL_DISTRO_NAME") != NULL && getenv("WT_SESSION") != NULL) { + if (ffStrbufEqualS(&disk->filesystem, "9p") && ffStrbufStartsWithS(&disk->mountpoint, "/mnt/")) { ffStrbufSetF(&mountpointLink, "\e]8;;file:///%c:/\e\\%s\e]8;;\e\\", disk->mountpoint.chars[5], disk->mountpoint.chars); ffStrbufSetF(&nameLink, "\e]8;;file:///%c:/\e\\%s\e]8;;\e\\", disk->mountpoint.chars[5], disk->name.chars); - } - else - { + } else { ffStrbufSetF(&mountpointLink, "\e]8;;file:////wsl.localhost/%s%s\e\\%s\e]8;;\e\\", getenv("WSL_DISTRO_NAME"), disk->mountpoint.chars, disk->mountpoint.chars); ffStrbufSetF(&nameLink, "\e]8;;file:////wsl.localhost/%s%s\e\\%s\e]8;;\e\\", getenv("WSL_DISTRO_NAME"), disk->mountpoint.chars, disk->name.chars); } - } - else - #endif + } else +#endif { ffStrbufSetF(&mountpointLink, "\e]8;;file://%s\e\\%s\e]8;;\e\\", disk->mountpoint.chars, disk->mountpoint.chars); ffStrbufSetF(&nameLink, "\e]8;;file://%s\e\\%s\e]8;;\e\\", disk->mountpoint.chars, disk->name.chars); } FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(disk->mountpoint, "mountpoint"), - FF_ARG(disk->name, "name"), - FF_ARG(disk->mountFrom, "mount-from"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - FF_ARG(index, "index"), - FF_ARG(disk->filesystem, "filesystem"), - FF_ARG(mountpointLink, "mountpoint-link"), - FF_ARG(nameLink, "name-link"), - })); + FF_ARG(disk->mountpoint, "mountpoint"), + FF_ARG(disk->name, "name"), + FF_ARG(disk->mountFrom, "mount-from"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + FF_ARG(index, "index"), + FF_ARG(disk->filesystem, "filesystem"), + FF_ARG(mountpointLink, "mountpoint-link"), + FF_ARG(nameLink, "name-link"), + })); } FF_STRBUF_AUTO_DESTROY usedPretty = ffStrbufCreate(); @@ -66,50 +57,50 @@ static void printDisk(FFDiskOptions* options, const FFDisk* disk, uint32_t index double bytesPercentage = disk->bytesTotal > 0 ? (double) disk->bytesUsed / (double) disk->bytesTotal * 100.0 : 0; FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); - if(disk->bytesTotal > 0) - { - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + if (disk->bytesTotal > 0) { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&str, bytesPercentage, options->percent, &options->moduleArgs); ffStrbufAppendC(&str, ' '); } - if(!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppendF(&str, "%s / %s ", usedPretty.chars, totalPretty.chars); + } - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) - { + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&str, bytesPercentage, options->percent, str.length > 0, &options->moduleArgs); ffStrbufAppendC(&str, ' '); } - } - else + } else { ffStrbufAppendS(&str, "Unknown "); + } - if(!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) - { - if(disk->filesystem.length) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { + if (disk->filesystem.length) { ffStrbufAppendF(&str, "- %s ", disk->filesystem.chars); + } ffStrbufAppendC(&str, '['); - if(disk->type & FF_DISK_VOLUME_TYPE_EXTERNAL_BIT) + if (disk->type & FF_DISK_VOLUME_TYPE_EXTERNAL_BIT) { ffStrbufAppendS(&str, "External, "); - if(disk->type & FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT) + } + if (disk->type & FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT) { ffStrbufAppendS(&str, "Subvolume, "); - if(disk->type & FF_DISK_VOLUME_TYPE_HIDDEN_BIT) + } + if (disk->type & FF_DISK_VOLUME_TYPE_HIDDEN_BIT) { ffStrbufAppendS(&str, "Hidden, "); - if(disk->type & FF_DISK_VOLUME_TYPE_READONLY_BIT) + } + if (disk->type & FF_DISK_VOLUME_TYPE_READONLY_BIT) { ffStrbufAppendS(&str, "Read-only, "); - if (str.chars[str.length - 1] == '[') + } + if (str.chars[str.length - 1] == '[') { ffStrbufSubstrBefore(&str, str.length - 1); - else - { + } else { ffStrbufTrimRight(&str, ' '); str.chars[str.length - 1] = ']'; } @@ -117,23 +108,25 @@ static void printDisk(FFDiskOptions* options, const FFDisk* disk, uint32_t index ffStrbufTrimRight(&str, ' '); ffStrbufPutTo(&str, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY bytesPercentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&bytesPercentageNum, bytesPercentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY bytesPercentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&bytesPercentageBar, bytesPercentage, options->percent, &options->moduleArgs); + } double filesPercentage = disk->filesTotal > 0 ? ((double) disk->filesUsed / (double) disk->filesTotal) * 100.0 : 0; FF_STRBUF_AUTO_DESTROY filesPercentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&filesPercentageNum, filesPercentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY filesPercentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&filesPercentageBar, filesPercentage, options->percent, &options->moduleArgs); + } bool isExternal = !!(disk->type & FF_DISK_VOLUME_TYPE_EXTERNAL_BIT); bool isHidden = !!(disk->type & FF_DISK_VOLUME_TYPE_HIDDEN_BIT); @@ -159,64 +152,60 @@ static void printDisk(FFDiskOptions* options, const FFDisk* disk, uint32_t index FFTimeGetAgeResult age = ffTimeGetAge(disk->createTime, now); FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(usedPretty, "size-used"), - FF_ARG(totalPretty, "size-total"), - FF_ARG(bytesPercentageNum, "size-percentage"), - FF_ARG(disk->filesUsed, "files-used"), - FF_ARG(disk->filesTotal, "files-total"), - FF_ARG(filesPercentageNum, "files-percentage"), - FF_ARG(isExternal, "is-external"), - FF_ARG(isHidden, "is-hidden"), - FF_ARG(disk->filesystem, "filesystem"), - FF_ARG(disk->name, "name"), - FF_ARG(isReadOnly, "is-readonly"), - {FF_ARG_TYPE_STRING, ffTimeToShortStr(disk->createTime), "create-time"}, - FF_ARG(bytesPercentageBar, "size-percentage-bar"), - FF_ARG(filesPercentageBar, "files-percentage-bar"), - FF_ARG(days, "days"), - FF_ARG(hours, "hours"), - FF_ARG(minutes, "minutes"), - FF_ARG(seconds, "seconds"), - FF_ARG(milliseconds, "milliseconds"), - FF_ARG(disk->mountpoint, "mountpoint"), - FF_ARG(disk->mountFrom, "mount-from"), - FF_ARG(age.years, "years"), - FF_ARG(age.daysOfYear, "days-of-year"), - FF_ARG(age.yearsFraction, "years-fraction"), - FF_ARG(freePretty, "size-free"), - FF_ARG(availPretty, "size-available"), - })); + FF_ARG(usedPretty, "size-used"), + FF_ARG(totalPretty, "size-total"), + FF_ARG(bytesPercentageNum, "size-percentage"), + FF_ARG(disk->filesUsed, "files-used"), + FF_ARG(disk->filesTotal, "files-total"), + FF_ARG(filesPercentageNum, "files-percentage"), + FF_ARG(isExternal, "is-external"), + FF_ARG(isHidden, "is-hidden"), + FF_ARG(disk->filesystem, "filesystem"), + FF_ARG(disk->name, "name"), + FF_ARG(isReadOnly, "is-readonly"), + {FF_ARG_TYPE_STRING, ffTimeToShortStr(disk->createTime), "create-time"}, + FF_ARG(bytesPercentageBar, "size-percentage-bar"), + FF_ARG(filesPercentageBar, "files-percentage-bar"), + FF_ARG(days, "days"), + FF_ARG(hours, "hours"), + FF_ARG(minutes, "minutes"), + FF_ARG(seconds, "seconds"), + FF_ARG(milliseconds, "milliseconds"), + FF_ARG(disk->mountpoint, "mountpoint"), + FF_ARG(disk->mountFrom, "mount-from"), + FF_ARG(age.years, "years"), + FF_ARG(age.daysOfYear, "days-of-year"), + FF_ARG(age.yearsFraction, "years-fraction"), + FF_ARG(freePretty, "size-free"), + FF_ARG(availPretty, "size-available"), + })); } } -bool ffPrintDisk(FFDiskOptions* options) -{ - FF_LIST_AUTO_DESTROY disks = ffListCreate(sizeof (FFDisk)); +bool ffPrintDisk(FFDiskOptions* options) { + FF_LIST_AUTO_DESTROY disks = ffListCreate(sizeof(FFDisk)); const char* error = ffDetectDisks(options, &disks); - if(error) - { + if (error) { ffPrintError(FF_DISK_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(disks.length == 0) - { + if (disks.length == 0) { ffPrintError(FF_DISK_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No disks found"); return false; } uint32_t index = 0; - FF_LIST_FOR_EACH(FFDisk, disk, disks) - { - if(__builtin_expect(options->folders.length == 0, 1) && (disk->type & ~options->showTypes)) + FF_LIST_FOR_EACH (FFDisk, disk, disks) { + if (__builtin_expect(options->folders.length == 0, 1) && (disk->type & ~options->showTypes)) { continue; + } printDisk(options, disk, ++index); } - FF_LIST_FOR_EACH(FFDisk, disk, disks) - { + FF_LIST_FOR_EACH (FFDisk, disk, disks) { ffStrbufDestroy(&disk->mountFrom); ffStrbufDestroy(&disk->mountpoint); ffStrbufDestroy(&disk->filesystem); @@ -226,24 +215,20 @@ bool ffPrintDisk(FFDiskOptions* options) return true; } -static bool setSeparatedList(FFstrbuf* strbuf, yyjson_val* val, char separator) -{ - if (yyjson_is_str(val)) - { +static bool setSeparatedList(FFstrbuf* strbuf, yyjson_val* val, char separator) { + if (yyjson_is_str(val)) { ffStrbufSetJsonVal(strbuf, val); return true; } - if (yyjson_is_arr(val)) - { + if (yyjson_is_arr(val)) { ffStrbufClear(strbuf); - yyjson_val *elem; + yyjson_val* elem; size_t eidx, emax; - yyjson_arr_foreach(val, eidx, emax, elem) - { - if (yyjson_is_str(elem)) - { - if (strbuf->length > 0) + yyjson_arr_foreach (val, eidx, emax, elem) { + if (yyjson_is_str(elem)) { + if (strbuf->length > 0) { ffStrbufAppendC(strbuf, separator); + } ffStrbufAppendJsonVal(strbuf, elem); } } @@ -252,105 +237,101 @@ static bool setSeparatedList(FFstrbuf* strbuf, yyjson_val* val, char separator) return false; } -void ffParseDiskJsonObject(FFDiskOptions* options, yyjson_val* module) -{ +void ffParseDiskJsonObject(FFDiskOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "folders")) - { + if (unsafe_yyjson_equals_str(key, "folders")) { setSeparatedList(&options->folders, val, FF_DISK_FOLDER_SEPARATOR); continue; } - if (unsafe_yyjson_equals_str(key, "hideFolders")) - { + if (unsafe_yyjson_equals_str(key, "hideFolders")) { setSeparatedList(&options->hideFolders, val, FF_DISK_FOLDER_SEPARATOR); continue; } - if (unsafe_yyjson_equals_str(key, "hideFS")) - { + if (unsafe_yyjson_equals_str(key, "hideFS")) { setSeparatedList(&options->hideFS, val, ':'); continue; } - if (unsafe_yyjson_equals_str(key, "showRegular")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showRegular")) { + if (yyjson_get_bool(val)) { options->showTypes |= FF_DISK_VOLUME_TYPE_REGULAR_BIT; - else + } else { options->showTypes &= ~FF_DISK_VOLUME_TYPE_REGULAR_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showExternal")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showExternal")) { + if (yyjson_get_bool(val)) { options->showTypes |= FF_DISK_VOLUME_TYPE_EXTERNAL_BIT; - else + } else { options->showTypes &= ~FF_DISK_VOLUME_TYPE_EXTERNAL_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showHidden")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showHidden")) { + if (yyjson_get_bool(val)) { options->showTypes |= FF_DISK_VOLUME_TYPE_HIDDEN_BIT; - else + } else { options->showTypes &= ~FF_DISK_VOLUME_TYPE_HIDDEN_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showSubvolumes")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showSubvolumes")) { + if (yyjson_get_bool(val)) { options->showTypes |= FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT; - else + } else { options->showTypes &= ~FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showReadOnly")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showReadOnly")) { + if (yyjson_get_bool(val)) { options->showTypes |= FF_DISK_VOLUME_TYPE_READONLY_BIT; - else + } else { options->showTypes &= ~FF_DISK_VOLUME_TYPE_READONLY_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showUnknown")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showUnknown")) { + if (yyjson_get_bool(val)) { options->showTypes |= FF_DISK_VOLUME_TYPE_UNKNOWN_BIT; - else + } else { options->showTypes &= ~FF_DISK_VOLUME_TYPE_UNKNOWN_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "useAvailable")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "useAvailable")) { + if (yyjson_get_bool(val)) { options->calcType = FF_DISK_CALC_TYPE_AVAILABLE; - else + } else { options->calcType = FF_DISK_CALC_TYPE_FREE; + } continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_DISK_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateDiskJsonConfig(FFDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateDiskJsonConfig(FFDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "showRegular", !!(options->showTypes & FF_DISK_VOLUME_TYPE_REGULAR_BIT)); @@ -376,21 +357,18 @@ void ffGenerateDiskJsonConfig(FFDiskOptions* options, yyjson_mut_doc* doc, yyjso ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateDiskJsonResult(FFDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ - FF_LIST_AUTO_DESTROY disks = ffListCreate(sizeof (FFDisk)); +bool ffGenerateDiskJsonResult(FFDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { + FF_LIST_AUTO_DESTROY disks = ffListCreate(sizeof(FFDisk)); const char* error = ffDetectDisks(options, &disks); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFDisk, item, disks) - { + FF_LIST_FOR_EACH (FFDisk, item, disks) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_val* bytes = yyjson_mut_obj_add_obj(doc, obj, "bytes"); @@ -400,13 +378,10 @@ bool ffGenerateDiskJsonResult(FFDiskOptions* options, yyjson_mut_doc* doc, yyjso yyjson_mut_obj_add_uint(doc, bytes, "used", item->bytesUsed); yyjson_mut_val* files = yyjson_mut_obj_add_obj(doc, obj, "files"); - if (item->filesTotal == 0 && item->filesUsed == 0) - { + if (item->filesTotal == 0 && item->filesUsed == 0) { yyjson_mut_obj_add_null(doc, files, "total"); yyjson_mut_obj_add_null(doc, files, "used"); - } - else - { + } else { yyjson_mut_obj_add_uint(doc, files, "total", item->filesTotal); yyjson_mut_obj_add_uint(doc, files, "used", item->filesUsed); } @@ -416,28 +391,34 @@ bool ffGenerateDiskJsonResult(FFDiskOptions* options, yyjson_mut_doc* doc, yyjso yyjson_mut_obj_add_strbuf(doc, obj, "mountFrom", &item->mountFrom); yyjson_mut_obj_add_strbuf(doc, obj, "name", &item->name); yyjson_mut_val* typeArr = yyjson_mut_obj_add_arr(doc, obj, "volumeType"); - if(item->type & FF_DISK_VOLUME_TYPE_REGULAR_BIT) + if (item->type & FF_DISK_VOLUME_TYPE_REGULAR_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "Regular"); - if(item->type & FF_DISK_VOLUME_TYPE_EXTERNAL_BIT) + } + if (item->type & FF_DISK_VOLUME_TYPE_EXTERNAL_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "External"); - if(item->type & FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT) + } + if (item->type & FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "Subvolume"); - if(item->type & FF_DISK_VOLUME_TYPE_HIDDEN_BIT) + } + if (item->type & FF_DISK_VOLUME_TYPE_HIDDEN_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "Hidden"); - if(item->type & FF_DISK_VOLUME_TYPE_READONLY_BIT) + } + if (item->type & FF_DISK_VOLUME_TYPE_READONLY_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "Read-only"); - if(item->type & FF_DISK_VOLUME_TYPE_UNKNOWN_BIT) + } + if (item->type & FF_DISK_VOLUME_TYPE_UNKNOWN_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "Unknown"); + } const char* pstr = ffTimeToFullStr(item->createTime); - if (*pstr) + if (*pstr) { yyjson_mut_obj_add_strcpy(doc, obj, "createTime", pstr); - else + } else { yyjson_mut_obj_add_null(doc, obj, "createTime"); + } } - FF_LIST_FOR_EACH(FFDisk, item, disks) - { + FF_LIST_FOR_EACH (FFDisk, item, disks) { ffStrbufDestroy(&item->mountpoint); ffStrbufDestroy(&item->mountFrom); ffStrbufDestroy(&item->filesystem); @@ -447,24 +428,22 @@ bool ffGenerateDiskJsonResult(FFDiskOptions* options, yyjson_mut_doc* doc, yyjso return true; } -void ffInitDiskOptions(FFDiskOptions* options) -{ +void ffInitDiskOptions(FFDiskOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); ffStrbufInit(&options->folders); - #if _WIN32 || __APPLE__ || __ANDROID__ +#if _WIN32 || __APPLE__ || __ANDROID__ ffStrbufInit(&options->hideFolders); - #else +#else ffStrbufInitS(&options->hideFolders, "/efi:/boot:/boot/*"); - #endif +#endif ffStrbufInit(&options->hideFS); options->showTypes = FF_DISK_VOLUME_TYPE_REGULAR_BIT | FF_DISK_VOLUME_TYPE_EXTERNAL_BIT | FF_DISK_VOLUME_TYPE_READONLY_BIT; options->calcType = FF_DISK_CALC_TYPE_FREE; - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; } -void ffDestroyDiskOptions(FFDiskOptions* options) -{ +void ffDestroyDiskOptions(FFDiskOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->folders); ffStrbufDestroy(&options->hideFolders); @@ -507,5 +486,4 @@ FFModuleBaseInfo ffDiskModuleInfo = { {"Years fraction after creation", "years-fraction"}, {"Size free", "size-free"}, {"Size available", "size-available"}, - })) -}; + }))}; diff --git a/src/modules/disk/option.h b/src/modules/disk/option.h index f4ec16f93..e978897d3 100644 --- a/src/modules/disk/option.h +++ b/src/modules/disk/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef enum __attribute__((__packed__)) FFDiskVolumeType -{ +typedef enum __attribute__((__packed__)) FFDiskVolumeType { FF_DISK_VOLUME_TYPE_NONE = 0, FF_DISK_VOLUME_TYPE_REGULAR_BIT = 1 << 0, FF_DISK_VOLUME_TYPE_HIDDEN_BIT = 1 << 1, @@ -15,14 +14,12 @@ typedef enum __attribute__((__packed__)) FFDiskVolumeType FF_DISK_VOLUME_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFDiskVolumeType; -typedef enum __attribute__((__packed__)) FFDiskCalcType -{ +typedef enum __attribute__((__packed__)) FFDiskCalcType { FF_DISK_CALC_TYPE_FREE, FF_DISK_CALC_TYPE_AVAILABLE, } FFDiskCalcType; -typedef struct FFDiskOptions -{ +typedef struct FFDiskOptions { FFModuleArgs moduleArgs; FFstrbuf folders; diff --git a/src/modules/diskio/diskio.c b/src/modules/diskio/diskio.c index 8aa1d9914..1f6ee31e7 100644 --- a/src/modules/diskio/diskio.c +++ b/src/modules/diskio/diskio.c @@ -7,36 +7,29 @@ #define FF_DISKIO_DISPLAY_NAME "Disk IO" -static int sortDevices(const FFDiskIOResult* left, const FFDiskIOResult* right) -{ +static int sortDevices(const FFDiskIOResult* left, const FFDiskIOResult* right) { return ffStrbufComp(&left->name, &right->name); } -static void formatKey(const FFDiskIOOptions* options, FFDiskIOResult* dev, uint32_t index, FFstrbuf* key) -{ - if(options->moduleArgs.key.length == 0) - { +static void formatKey(const FFDiskIOOptions* options, FFDiskIOResult* dev, uint32_t index, FFstrbuf* key) { + if (options->moduleArgs.key.length == 0) { ffStrbufSetF(key, FF_DISKIO_DISPLAY_NAME " (%s)", dev->name.length ? dev->name.chars : dev->devPath.chars); - } - else - { + } else { ffStrbufClear(key); - FF_PARSE_FORMAT_STRING_CHECKED(key, &options->moduleArgs.key, ((FFformatarg[]){ - FF_ARG(index, "index"), - FF_ARG(dev->name, "name"), - FF_ARG(dev->devPath, "dev-path"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_PARSE_FORMAT_STRING_CHECKED(key, &options->moduleArgs.key, ((FFformatarg[]) { + FF_ARG(index, "index"), + FF_ARG(dev->name, "name"), + FF_ARG(dev->devPath, "dev-path"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } } -bool ffPrintDiskIO(FFDiskIOOptions* options) -{ +bool ffPrintDiskIO(FFDiskIOOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFDiskIOResult)); const char* error = ffDetectDiskIO(&result, options); - if(error) - { + if (error) { ffPrintError(FF_DISKIO_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, "%s", error); return false; } @@ -48,48 +41,51 @@ bool ffPrintDiskIO(FFDiskIOOptions* options) FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY buffer2 = ffStrbufCreate(); - FF_LIST_FOR_EACH(FFDiskIOResult, dev, result) - { + FF_LIST_FOR_EACH (FFDiskIOResult, dev, result) { formatKey(options, dev, result.length == 1 ? 0 : index + 1, &key); ffStrbufClear(&buffer); - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffSizeAppendNum(dev->bytesRead, &buffer); - if (!options->detectTotal) ffStrbufAppendS(&buffer, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer, "/s"); + } ffStrbufAppendS(&buffer, " (R) - "); ffSizeAppendNum(dev->bytesWritten, &buffer); - if (!options->detectTotal) ffStrbufAppendS(&buffer, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer, "/s"); + } ffStrbufAppendS(&buffer, " (W)"); ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { ffSizeAppendNum(dev->bytesRead, &buffer); - if (!options->detectTotal) ffStrbufAppendS(&buffer, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer, "/s"); + } ffStrbufClear(&buffer2); ffSizeAppendNum(dev->bytesWritten, &buffer2); - if (!options->detectTotal) ffStrbufAppendS(&buffer2, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer2, "/s"); + } - FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]){ - FF_ARG(buffer, "size-read"), - FF_ARG(buffer2, "size-written"), - FF_ARG(dev->name, "name"), - FF_ARG(dev->devPath, "dev-path"), - FF_ARG(dev->bytesRead, "bytes-read"), - FF_ARG(dev->bytesWritten, "bytes-written"), - FF_ARG(dev->readCount, "read-count"), - FF_ARG(dev->writeCount, "write-count"), - })); + FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { + FF_ARG(buffer, "size-read"), + FF_ARG(buffer2, "size-written"), + FF_ARG(dev->name, "name"), + FF_ARG(dev->devPath, "dev-path"), + FF_ARG(dev->bytesRead, "bytes-read"), + FF_ARG(dev->bytesWritten, "bytes-written"), + FF_ARG(dev->readCount, "read-count"), + FF_ARG(dev->writeCount, "write-count"), + })); } ++index; } - FF_LIST_FOR_EACH(FFDiskIOResult, dev, result) - { + FF_LIST_FOR_EACH (FFDiskIOResult, dev, result) { ffStrbufDestroy(&dev->name); ffStrbufDestroy(&dev->devPath); } @@ -97,29 +93,25 @@ bool ffPrintDiskIO(FFDiskIOOptions* options) return true; } -void ffParseDiskIOJsonObject(FFDiskIOOptions* options, yyjson_val* module) -{ +void ffParseDiskIOJsonObject(FFDiskIOOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "namePrefix")) - { + if (unsafe_yyjson_equals_str(key, "namePrefix")) { ffStrbufSetJsonVal(&options->namePrefix, val); continue; } - if (unsafe_yyjson_equals_str(key, "detectTotal")) - { + if (unsafe_yyjson_equals_str(key, "detectTotal")) { options->detectTotal = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "waitTime")) - { + if (unsafe_yyjson_equals_str(key, "waitTime")) { options->waitTime = (uint32_t) yyjson_get_uint(val); continue; } @@ -128,8 +120,7 @@ void ffParseDiskIOJsonObject(FFDiskIOOptions* options, yyjson_val* module) } } -void ffGenerateDiskIOJsonConfig(FFDiskIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateDiskIOJsonConfig(FFDiskIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_strbuf(doc, module, "namePrefix", &options->namePrefix); @@ -139,20 +130,17 @@ void ffGenerateDiskIOJsonConfig(FFDiskIOOptions* options, yyjson_mut_doc* doc, y yyjson_mut_obj_add_uint(doc, module, "waitTime", options->waitTime); } -bool ffGenerateDiskIOJsonResult(FFDiskIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateDiskIOJsonResult(FFDiskIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFDiskIOResult)); const char* error = ffDetectDiskIO(&result, options); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFDiskIOResult, dev, result) - { + FF_LIST_FOR_EACH (FFDiskIOResult, dev, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &dev->name); yyjson_mut_obj_add_strbuf(doc, obj, "devPath", &dev->devPath); @@ -162,8 +150,7 @@ bool ffGenerateDiskIOJsonResult(FFDiskIOOptions* options, yyjson_mut_doc* doc, y yyjson_mut_obj_add_uint(doc, obj, "writeCount", dev->writeCount); } - FF_LIST_FOR_EACH(FFDiskIOResult, dev, result) - { + FF_LIST_FOR_EACH (FFDiskIOResult, dev, result) { ffStrbufDestroy(&dev->name); ffStrbufDestroy(&dev->devPath); } @@ -171,8 +158,7 @@ bool ffGenerateDiskIOJsonResult(FFDiskIOOptions* options, yyjson_mut_doc* doc, y return true; } -void ffInitDiskIOOptions(FFDiskIOOptions* options) -{ +void ffInitDiskIOOptions(FFDiskIOOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰓅"); ffStrbufInit(&options->namePrefix); @@ -180,8 +166,7 @@ void ffInitDiskIOOptions(FFDiskIOOptions* options) options->waitTime = 1000; } -void ffDestroyDiskIOOptions(FFDiskIOOptions* options) -{ +void ffDestroyDiskIOOptions(FFDiskIOOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->namePrefix); } @@ -204,5 +189,4 @@ FFModuleBaseInfo ffDiskIOModuleInfo = { {"Size of data written [per second] (in bytes)", "bytes-written"}, {"Number of reads", "read-count"}, {"Number of writes", "write-count"}, - })) -}; + }))}; diff --git a/src/modules/diskio/option.h b/src/modules/diskio/option.h index 5de458fa3..5d417044e 100644 --- a/src/modules/diskio/option.h +++ b/src/modules/diskio/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFDiskIOOptions -{ +typedef struct FFDiskIOOptions { FFModuleArgs moduleArgs; FFstrbuf namePrefix; diff --git a/src/modules/display/display.c b/src/modules/display/display.c index f92ed7e49..91f4fbc80 100644 --- a/src/modules/display/display.c +++ b/src/modules/display/display.c @@ -7,63 +7,50 @@ #include -static int sortByNameAsc(FFDisplayResult* a, FFDisplayResult* b) -{ +static int sortByNameAsc(FFDisplayResult* a, FFDisplayResult* b) { return ffStrbufComp(&a->name, &b->name); } -static int sortByNameDesc(FFDisplayResult* a, FFDisplayResult* b) -{ +static int sortByNameDesc(FFDisplayResult* a, FFDisplayResult* b) { return -ffStrbufComp(&a->name, &b->name); } -bool ffPrintDisplay(FFDisplayOptions* options) -{ +bool ffPrintDisplay(FFDisplayOptions* options) { const FFDisplayServerResult* dsResult = ffConnectDisplayServer(); - if(dsResult->displays.length == 0) - { + if (dsResult->displays.length == 0) { ffPrintError(FF_DISPLAY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Couldn't detect display"); return false; } - if (options->order != FF_DISPLAY_ORDER_NONE) - { + if (options->order != FF_DISPLAY_ORDER_NONE) { ffListSort((FFlist*) &dsResult->displays, (void*) (options->order == FF_DISPLAY_ORDER_ASC ? sortByNameAsc : sortByNameDesc)); } - if (options->compactType != FF_DISPLAY_COMPACT_TYPE_NONE) - { + if (options->compactType != FF_DISPLAY_COMPACT_TYPE_NONE) { ffPrintLogoAndKey(FF_DISPLAY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - FF_LIST_FOR_EACH(FFDisplayResult, result, dsResult->displays) - { - if (options->compactType & FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT) - { + FF_LIST_FOR_EACH (FFDisplayResult, result, dsResult->displays) { + if (options->compactType & FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT) { ffStrbufAppendF(&buffer, "%ix%i", result->width, result->height); - } - else - { + } else { uint32_t scaledWidth = (result->width * 96 + result->dpi / 2) / result->dpi; uint32_t scaledHeight = (result->height * 96 + result->dpi / 2) / result->dpi; ffStrbufAppendF(&buffer, "%ix%i", scaledWidth, scaledHeight); } - if (options->compactType & FF_DISPLAY_COMPACT_TYPE_REFRESH_RATE_BIT) - { - if (result->refreshRate > 0) - { + if (options->compactType & FF_DISPLAY_COMPACT_TYPE_REFRESH_RATE_BIT) { + if (result->refreshRate > 0) { const char* space = instance.config.display.freqSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : ""; - if (options->preciseRefreshRate) + if (options->preciseRefreshRate) { ffStrbufAppendF(&buffer, " @ %g%sHz", result->refreshRate, space); - else + } else { ffStrbufAppendF(&buffer, " @ %i%sHz", (uint32_t) (result->refreshRate + 0.5), space); + } } ffStrbufAppendS(&buffer, ", "); - } - else - { + } else { ffStrbufAppendC(&buffer, ' '); } } @@ -75,30 +62,28 @@ bool ffPrintDisplay(FFDisplayOptions* options) FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); - for(uint32_t i = 0; i < dsResult->displays.length; i++) - { + for (uint32_t i = 0; i < dsResult->displays.length; i++) { FFDisplayResult* result = FF_LIST_GET(FFDisplayResult, dsResult->displays, i); uint32_t moduleIndex = dsResult->displays.length == 1 ? 0 : i + 1; - const char* displayType = result->type == FF_DISPLAY_TYPE_UNKNOWN ? NULL : result->type == FF_DISPLAY_TYPE_BUILTIN ? "Built-in" : "External"; + const char* displayType = result->type == FF_DISPLAY_TYPE_UNKNOWN ? NULL : result->type == FF_DISPLAY_TYPE_BUILTIN ? "Built-in" + : "External"; ffStrbufClear(&key); - if(options->moduleArgs.key.length == 0) - { - if (result->name.length) + if (options->moduleArgs.key.length == 0) { + if (result->name.length) { ffStrbufAppendF(&key, "%s (%s)", FF_DISPLAY_MODULE_NAME, result->name.chars); - else if (moduleIndex > 0) + } else if (moduleIndex > 0) { ffStrbufAppendF(&key, "%s (%d)", FF_DISPLAY_MODULE_NAME, moduleIndex); - else + } else { ffStrbufAppendS(&key, FF_DISPLAY_MODULE_NAME); - } - else - { + } + } else { FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(moduleIndex, "index"), - FF_ARG(result->name, "name"), - FF_ARG(displayType, "type"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(moduleIndex, "index"), + FF_ARG(result->name, "name"), + FF_ARG(displayType, "type"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); @@ -107,180 +92,172 @@ bool ffPrintDisplay(FFDisplayOptions* options) uint32_t scaledHeight = (result->height * 96 + result->dpi / 2) / result->dpi; double scaleFactor = (double) result->dpi / 96.; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffStrbufAppendF(&buffer, "%ix%i", result->width, result->height); - if(result->dpi != 96) - { + if (result->dpi != 96) { ffStrbufAppendS(&buffer, " @ "); ffStrbufAppendDouble(&buffer, scaleFactor, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros == FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS); ffStrbufAppendC(&buffer, 'x'); } - if (inch > 1) + if (inch > 1) { ffStrbufAppendF(&buffer, " in %i\"", (uint32_t) (inch + 0.5)); + } - if(result->refreshRate > 0) - { + if (result->refreshRate > 0) { ffStrbufAppendS(&buffer, ", "); - if(options->preciseRefreshRate) + if (options->preciseRefreshRate) { ffStrbufAppendDouble(&buffer, result->refreshRate, 3, false); - else + } else { ffStrbufAppendSInt(&buffer, (int) (result->refreshRate + 0.5)); + } ffStrbufAppendS(&buffer, instance.config.display.freqSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "Hz" : " Hz"); } bool flag = false; - if (result->type != FF_DISPLAY_TYPE_UNKNOWN) - { + if (result->type != FF_DISPLAY_TYPE_UNKNOWN) { ffStrbufAppendS(&buffer, result->type == FF_DISPLAY_TYPE_BUILTIN ? " [Built-in" : " [External"); flag = true; } - if (result->hdrStatus == FF_DISPLAY_HDR_STATUS_ENABLED) - { + if (result->hdrStatus == FF_DISPLAY_HDR_STATUS_ENABLED) { ffStrbufAppendS(&buffer, flag ? ", HDR" : " [HDR"); flag = true; } - if (flag) + if (flag) { ffStrbufAppendS(&buffer, "]"); + } - if(moduleIndex > 0 && result->primary) + if (moduleIndex > 0 && result->primary) { ffStrbufAppendS(&buffer, " *"); + } ffStrbufPutTo(&buffer, stdout); ffStrbufClear(&buffer); - } - else - { + } else { double ppi = inch == 0 ? 0 : sqrt(result->width * result->width + result->height * result->height) / inch; bool hdrEnabled = result->hdrStatus == FF_DISPLAY_HDR_STATUS_ENABLED; bool hdrCompatible = result->hdrStatus == FF_DISPLAY_HDR_STATUS_SUPPORTED || result->hdrStatus == FF_DISPLAY_HDR_STATUS_ENABLED; uint32_t iInch = (uint32_t) (inch + 0.5), iPpi = (uint32_t) (ppi + 0.5); char refreshRate[16]; - if(result->refreshRate > 0) - { - if(options->preciseRefreshRate) + if (result->refreshRate > 0) { + if (options->preciseRefreshRate) { snprintf(refreshRate, ARRAY_SIZE(refreshRate), "%g", ((int) (result->refreshRate * 1000 + 0.5)) / 1000.0); - else + } else { snprintf(refreshRate, ARRAY_SIZE(refreshRate), "%i", (uint32_t) (result->refreshRate + 0.5)); - } - else + } + } else { refreshRate[0] = 0; + } char preferredRefreshRate[16]; - if(result->preferredRefreshRate > 0) - { - if(options->preciseRefreshRate) + if (result->preferredRefreshRate > 0) { + if (options->preciseRefreshRate) { snprintf(preferredRefreshRate, ARRAY_SIZE(preferredRefreshRate), "%g", ((int) (result->preferredRefreshRate * 1000 + 0.5)) / 1000.0); - else + } else { snprintf(preferredRefreshRate, ARRAY_SIZE(preferredRefreshRate), "%i", (uint32_t) (result->preferredRefreshRate + 0.5)); - } - else + } + } else { preferredRefreshRate[0] = 0; + } char buf[32]; - if (result->serial) - { + if (result->serial) { const uint8_t* nums = (uint8_t*) &result->serial; snprintf(buf, ARRAY_SIZE(buf), "%2X-%2X-%2X-%2X", nums[0], nums[1], nums[2], nums[3]); - } - else + } else { buf[0] = '\0'; + } FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(result->width, "width"), - FF_ARG(result->height, "height"), - FF_ARG(refreshRate, "refresh-rate"), - FF_ARG(scaledWidth, "scaled-width"), - FF_ARG(scaledHeight, "scaled-height"), - FF_ARG(result->name, "name"), - FF_ARG(displayType, "type"), - FF_ARG(result->rotation, "rotation"), - FF_ARG(result->primary, "is-primary"), - FF_ARG(result->physicalWidth, "physical-width"), - FF_ARG(result->physicalHeight, "physical-height"), - FF_ARG(iInch, "inch"), - FF_ARG(iPpi, "ppi"), - FF_ARG(result->bitDepth, "bit-depth"), - FF_ARG(hdrEnabled, "hdr-enabled"), - FF_ARG(result->manufactureYear, "manufacture-year"), - FF_ARG(result->manufactureWeek, "manufacture-week"), - FF_ARG(buf, "serial"), - FF_ARG(result->platformApi, "platform-api"), - FF_ARG(hdrCompatible, "hdr-compatible"), - FF_ARG(scaleFactor, "scale-factor"), - FF_ARG(result->preferredWidth, "preferred-width"), - FF_ARG(result->preferredHeight, "preferred-height"), - FF_ARG(preferredRefreshRate, "preferred-refresh-rate"), - FF_ARG(result->dpi, "dpi"), - })); + FF_ARG(result->width, "width"), + FF_ARG(result->height, "height"), + FF_ARG(refreshRate, "refresh-rate"), + FF_ARG(scaledWidth, "scaled-width"), + FF_ARG(scaledHeight, "scaled-height"), + FF_ARG(result->name, "name"), + FF_ARG(displayType, "type"), + FF_ARG(result->rotation, "rotation"), + FF_ARG(result->primary, "is-primary"), + FF_ARG(result->physicalWidth, "physical-width"), + FF_ARG(result->physicalHeight, "physical-height"), + FF_ARG(iInch, "inch"), + FF_ARG(iPpi, "ppi"), + FF_ARG(result->bitDepth, "bit-depth"), + FF_ARG(hdrEnabled, "hdr-enabled"), + FF_ARG(result->manufactureYear, "manufacture-year"), + FF_ARG(result->manufactureWeek, "manufacture-week"), + FF_ARG(buf, "serial"), + FF_ARG(result->platformApi, "platform-api"), + FF_ARG(hdrCompatible, "hdr-compatible"), + FF_ARG(scaleFactor, "scale-factor"), + FF_ARG(result->preferredWidth, "preferred-width"), + FF_ARG(result->preferredHeight, "preferred-height"), + FF_ARG(preferredRefreshRate, "preferred-refresh-rate"), + FF_ARG(result->dpi, "dpi"), + })); } } return true; } -void ffParseDisplayJsonObject(FFDisplayOptions* options, yyjson_val* module) -{ +void ffParseDisplayJsonObject(FFDisplayOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "compactType")) - { - if (yyjson_is_null(val)) + if (unsafe_yyjson_equals_str(key, "compactType")) { + if (yyjson_is_null(val)) { options->compactType = FF_DISPLAY_COMPACT_TYPE_NONE; - else - { + } else { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "none", FF_DISPLAY_COMPACT_TYPE_NONE }, - { "original", FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT }, - { "scaled", FF_DISPLAY_COMPACT_TYPE_SCALED_BIT }, - { "original-with-refresh-rate", FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT | FF_DISPLAY_COMPACT_TYPE_REFRESH_RATE_BIT }, - { "scaled-with-refresh-rate", FF_DISPLAY_COMPACT_TYPE_SCALED_BIT | FF_DISPLAY_COMPACT_TYPE_REFRESH_RATE_BIT }, - {}, - }); - if (error) + {"none", FF_DISPLAY_COMPACT_TYPE_NONE}, + {"original", FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT}, + {"scaled", FF_DISPLAY_COMPACT_TYPE_SCALED_BIT}, + {"original-with-refresh-rate", FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT | FF_DISPLAY_COMPACT_TYPE_REFRESH_RATE_BIT}, + {"scaled-with-refresh-rate", FF_DISPLAY_COMPACT_TYPE_SCALED_BIT | FF_DISPLAY_COMPACT_TYPE_REFRESH_RATE_BIT}, + {}, + }); + if (error) { ffPrintError(FF_DISPLAY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else + } else { options->compactType = (FFDisplayCompactType) value; + } } continue; } - if (unsafe_yyjson_equals_str(key, "preciseRefreshRate")) - { + if (unsafe_yyjson_equals_str(key, "preciseRefreshRate")) { options->preciseRefreshRate = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "order")) - { - if (yyjson_is_null(val)) + if (unsafe_yyjson_equals_str(key, "order")) { + if (yyjson_is_null(val)) { options->order = FF_DISPLAY_ORDER_NONE; - else - { + } else { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "asc", FF_DISPLAY_ORDER_ASC }, - { "desc", FF_DISPLAY_ORDER_DESC }, - { "none", FF_DISPLAY_ORDER_NONE }, - {}, - }); - if (error) + {"asc", FF_DISPLAY_ORDER_ASC}, + {"desc", FF_DISPLAY_ORDER_DESC}, + {"none", FF_DISPLAY_ORDER_NONE}, + {}, + }); + if (error) { ffPrintError(FF_DISPLAY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else + } else { options->order = (FFDisplayOrder) value; + } } continue; } @@ -289,12 +266,10 @@ void ffParseDisplayJsonObject(FFDisplayOptions* options, yyjson_val* module) } } -void ffGenerateDisplayJsonConfig(FFDisplayOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateDisplayJsonConfig(FFDisplayOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - switch ((int) options->compactType) - { + switch ((int) options->compactType) { case FF_DISPLAY_COMPACT_TYPE_NONE: yyjson_mut_obj_add_str(doc, module, "compactType", "none"); break; @@ -314,8 +289,7 @@ void ffGenerateDisplayJsonConfig(FFDisplayOptions* options, yyjson_mut_doc* doc, yyjson_mut_obj_add_bool(doc, module, "preciseRefreshRate", options->preciseRefreshRate); - switch (options->order) - { + switch (options->order) { case FF_DISPLAY_ORDER_NONE: yyjson_mut_obj_add_null(doc, module, "order"); break; @@ -328,19 +302,16 @@ void ffGenerateDisplayJsonConfig(FFDisplayOptions* options, yyjson_mut_doc* doc, } } -bool ffGenerateDisplayJsonResult(FF_MAYBE_UNUSED FFDisplayOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateDisplayJsonResult(FF_MAYBE_UNUSED FFDisplayOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFDisplayServerResult* dsResult = ffConnectDisplayServer(); - if(dsResult->displays.length == 0) - { + if (dsResult->displays.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "Couldn't detect display"); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFDisplayResult, item, dsResult->displays) - { + FF_LIST_FOR_EACH (FFDisplayResult, item, dsResult->displays) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_uint(doc, obj, "id", item->id); yyjson_mut_obj_add_strbuf(doc, obj, "name", &item->name); @@ -351,19 +322,20 @@ bool ffGenerateDisplayJsonResult(FF_MAYBE_UNUSED FFDisplayOptions* options, yyjs yyjson_mut_obj_add_uint(doc, output, "height", item->height); yyjson_mut_obj_add_real(doc, output, "refreshRate", item->refreshRate); - if (item->drrStatus == FF_DISPLAY_DRR_STATUS_UNKNOWN) + if (item->drrStatus == FF_DISPLAY_DRR_STATUS_UNKNOWN) { yyjson_mut_obj_add_null(doc, output, "drrStatus"); - else switch (item->drrStatus) - { - case FF_DISPLAY_DRR_STATUS_DISABLED: - yyjson_mut_obj_add_str(doc, output, "drrStatus", "Disabled"); - break; - case FF_DISPLAY_DRR_STATUS_ENABLED: - yyjson_mut_obj_add_str(doc, output, "drrStatus", "Enabled"); - break; - default: - yyjson_mut_obj_add_str(doc, output, "drrStatus", "Unknown"); - break; + } else { + switch (item->drrStatus) { + case FF_DISPLAY_DRR_STATUS_DISABLED: + yyjson_mut_obj_add_str(doc, output, "drrStatus", "Disabled"); + break; + case FF_DISPLAY_DRR_STATUS_ENABLED: + yyjson_mut_obj_add_str(doc, output, "drrStatus", "Enabled"); + break; + default: + yyjson_mut_obj_add_str(doc, output, "drrStatus", "Unknown"); + break; + } } yyjson_mut_obj_add_uint(doc, output, "dpi", item->dpi); @@ -384,26 +356,26 @@ bool ffGenerateDisplayJsonResult(FF_MAYBE_UNUSED FFDisplayOptions* options, yyjs yyjson_mut_obj_add_uint(doc, obj, "rotation", item->rotation); yyjson_mut_obj_add_uint(doc, obj, "bitDepth", item->bitDepth); - if (item->hdrStatus == FF_DISPLAY_HDR_STATUS_UNKNOWN) + if (item->hdrStatus == FF_DISPLAY_HDR_STATUS_UNKNOWN) { yyjson_mut_obj_add_null(doc, obj, "hdrStatus"); - else switch (item->hdrStatus) - { - case FF_DISPLAY_HDR_STATUS_UNSUPPORTED: - yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Unsupported"); - break; - case FF_DISPLAY_HDR_STATUS_SUPPORTED: - yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Supported"); - break; - case FF_DISPLAY_HDR_STATUS_ENABLED: - yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Enabled"); - break; - default: - yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Unknown"); - break; + } else { + switch (item->hdrStatus) { + case FF_DISPLAY_HDR_STATUS_UNSUPPORTED: + yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Unsupported"); + break; + case FF_DISPLAY_HDR_STATUS_SUPPORTED: + yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Supported"); + break; + case FF_DISPLAY_HDR_STATUS_ENABLED: + yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Enabled"); + break; + default: + yyjson_mut_obj_add_str(doc, obj, "hdrStatus", "Unknown"); + break; + } } - switch (item->type) - { + switch (item->type) { case FF_DISPLAY_TYPE_BUILTIN: yyjson_mut_obj_add_str(doc, obj, "type", "Builtin"); break; @@ -415,21 +387,19 @@ bool ffGenerateDisplayJsonResult(FF_MAYBE_UNUSED FFDisplayOptions* options, yyjs break; } - if (item->manufactureYear) - { + if (item->manufactureYear) { yyjson_mut_val* manufactureDate = yyjson_mut_obj_add_obj(doc, obj, "manufactureDate"); yyjson_mut_obj_add_uint(doc, manufactureDate, "year", item->manufactureYear); yyjson_mut_obj_add_uint(doc, manufactureDate, "week", item->manufactureWeek); - } - else - { + } else { yyjson_mut_obj_add_null(doc, obj, "manufactureDate"); } - if (item->serial) + if (item->serial) { yyjson_mut_obj_add_uint(doc, obj, "serial", item->serial); - else + } else { yyjson_mut_obj_add_null(doc, obj, "serial"); + } yyjson_mut_obj_add_str(doc, obj, "platformApi", item->platformApi); } @@ -437,16 +407,14 @@ bool ffGenerateDisplayJsonResult(FF_MAYBE_UNUSED FFDisplayOptions* options, yyjs return true; } -void ffInitDisplayOptions(FFDisplayOptions* options) -{ +void ffInitDisplayOptions(FFDisplayOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰍹"); options->compactType = FF_DISPLAY_COMPACT_TYPE_NONE; options->preciseRefreshRate = false; options->order = FF_DISPLAY_ORDER_NONE; } -void ffDestroyDisplayOptions(FFDisplayOptions* options) -{ +void ffDestroyDisplayOptions(FFDisplayOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -485,5 +453,4 @@ FFModuleBaseInfo ffDisplayModuleInfo = { {"Screen preferred height (in pixels)", "preferred-height"}, {"Screen preferred refresh rate (in Hz)", "preferred-refresh-rate"}, {"DPI", "dpi"}, - })) -}; + }))}; diff --git a/src/modules/display/option.h b/src/modules/display/option.h index 12ad3c5ec..a1601ba1b 100644 --- a/src/modules/display/option.h +++ b/src/modules/display/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef enum __attribute__((__packed__)) FFDisplayCompactType -{ +typedef enum __attribute__((__packed__)) FFDisplayCompactType { FF_DISPLAY_COMPACT_TYPE_NONE = 0, FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT = 1 << 0, FF_DISPLAY_COMPACT_TYPE_SCALED_BIT = 1 << 1, @@ -11,15 +10,13 @@ typedef enum __attribute__((__packed__)) FFDisplayCompactType FF_DISPLAY_COMPACT_TYPE_UNSIGNED = UINT8_MAX, } FFDisplayCompactType; -typedef enum __attribute__((__packed__)) FFDisplayOrder -{ +typedef enum __attribute__((__packed__)) FFDisplayOrder { FF_DISPLAY_ORDER_NONE, FF_DISPLAY_ORDER_ASC, FF_DISPLAY_ORDER_DESC, } FFDisplayOrder; -typedef struct FFDisplayOptions -{ +typedef struct FFDisplayOptions { FFModuleArgs moduleArgs; FFDisplayCompactType compactType; diff --git a/src/modules/dns/dns.c b/src/modules/dns/dns.c index 428419f23..bd698fdab 100644 --- a/src/modules/dns/dns.c +++ b/src/modules/dns/dns.c @@ -4,83 +4,79 @@ #include "detection/dns/dns.h" #include "modules/dns/dns.h" -bool ffPrintDNS(FFDNSOptions* options) -{ +bool ffPrintDNS(FFDNSOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFstrbuf)); const char* error = ffDetectDNS(options, &result); - if (error) - { + if (error) { ffPrintError(FF_DNS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if (result.length == 0) - { + if (result.length == 0) { ffPrintError(FF_DNS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "NO DNS servers detected"); return false; } FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - FF_LIST_FOR_EACH(FFstrbuf, item, result) - { - if (!ffStrbufContainC(item, '.')) continue; // IPv4 - if (buf.length) + FF_LIST_FOR_EACH (FFstrbuf, item, result) { + if (!ffStrbufContainC(item, '.')) { + continue; // IPv4 + } + if (buf.length) { ffStrbufAppendC(&buf, ' '); + } ffStrbufAppend(&buf, item); } - FF_LIST_FOR_EACH(FFstrbuf, item, result) - { - if (!ffStrbufContainC(item, ':')) continue; // IPv6 - if (buf.length) + FF_LIST_FOR_EACH (FFstrbuf, item, result) { + if (!ffStrbufContainC(item, ':')) { + continue; // IPv6 + } + if (buf.length) { ffStrbufAppendC(&buf, ' '); + } ffStrbufAppend(&buf, item); } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_DNS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&buf, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_DNS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(buf, "result"), - })); + FF_ARG(buf, "result"), + })); } - FF_LIST_FOR_EACH(FFstrbuf, item, result) - { + FF_LIST_FOR_EACH (FFstrbuf, item, result) { ffStrbufDestroy(item); } return true; } -void ffParseDNSJsonObject(FFDNSOptions* options, yyjson_val* module) -{ +void ffParseDNSJsonObject(FFDNSOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "showType")) - { + if (unsafe_yyjson_equals_str(key, "showType")) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "both", FF_DNS_TYPE_BOTH }, - { "ipv4", FF_DNS_TYPE_IPV4_BIT }, - { "ipv6", FF_DNS_TYPE_IPV6_BIT }, - {}, - }); - if (error) + {"both", FF_DNS_TYPE_BOTH}, + {"ipv4", FF_DNS_TYPE_IPV4_BIT}, + {"ipv6", FF_DNS_TYPE_IPV6_BIT}, + {}, + }); + if (error) { ffPrintError(FF_DNS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else + } else { options->showType = (FFDNSShowType) value; + } continue; } @@ -88,12 +84,10 @@ void ffParseDNSJsonObject(FFDNSOptions* options, yyjson_val* module) } } -void ffGenerateDNSJsonConfig(FFDNSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateDNSJsonConfig(FFDNSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - switch ((uint8_t) options->showType) - { + switch ((uint8_t) options->showType) { case FF_DNS_TYPE_IPV4_BIT: yyjson_mut_obj_add_str(doc, module, "showType", "ipv4"); break; @@ -106,42 +100,36 @@ void ffGenerateDNSJsonConfig(FFDNSOptions* options, yyjson_mut_doc* doc, yyjson_ } } -bool ffGenerateDNSJsonResult(FFDNSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateDNSJsonResult(FFDNSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFstrbuf)); const char* error = ffDetectDNS(options, &result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFstrbuf, item, result) - { + FF_LIST_FOR_EACH (FFstrbuf, item, result) { yyjson_mut_arr_add_strbuf(doc, arr, item); } - FF_LIST_FOR_EACH(FFstrbuf, item, result) - { + FF_LIST_FOR_EACH (FFstrbuf, item, result) { ffStrbufDestroy(item); } return true; } -void ffInitDNSOptions(FFDNSOptions* options) -{ +void ffInitDNSOptions(FFDNSOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰇖"); options->showType = FF_DNS_TYPE_BOTH; } -void ffDestroyDNSOptions(FFDNSOptions* options) -{ +void ffDestroyDNSOptions(FFDNSOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -156,5 +144,4 @@ FFModuleBaseInfo ffDNSModuleInfo = { .generateJsonConfig = (void*) ffGenerateDNSJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"DNS result", "result"}, - })) -}; + }))}; diff --git a/src/modules/dns/option.h b/src/modules/dns/option.h index bc3bd5690..6747428ba 100644 --- a/src/modules/dns/option.h +++ b/src/modules/dns/option.h @@ -9,8 +9,7 @@ typedef enum __attribute__((__packed__)) FFDNSShowType { FF_DNS_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFDNSShowType; -typedef struct FFDNSOptions -{ +typedef struct FFDNSOptions { FFModuleArgs moduleArgs; FFDNSShowType showType; diff --git a/src/modules/editor/editor.c b/src/modules/editor/editor.c index c6ab33fcb..2ab41ef04 100644 --- a/src/modules/editor/editor.c +++ b/src/modules/editor/editor.c @@ -5,8 +5,7 @@ #include "detection/editor/editor.h" #include "modules/editor/editor.h" -bool ffPrintEditor(FFEditorOptions* options) -{ +bool ffPrintEditor(FFEditorOptions* options) { FFEditorResult result = { .type = "Unknown", .name = ffStrbufCreate(), @@ -16,36 +15,30 @@ bool ffPrintEditor(FFEditorOptions* options) }; const char* error = ffDetectEditor(&result); - if (error) - { + if (error) { ffPrintError(FF_EDITOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if (options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_EDITOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (result.exe.length) - { + if (result.exe.length) { ffStrbufWriteTo(&result.exe, stdout); - if (result.version.length) + if (result.version.length) { printf(" %s", result.version.chars); - } - else - { + } + } else { ffStrbufWriteTo(&result.name, stdout); } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_EDITOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result.type, "type"), - FF_ARG(result.name, "name"), - FF_ARG(result.exe, "exe-name"), - FF_ARG(result.path, "path"), - FF_ARG(result.version, "version"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_EDITOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result.type, "type"), + FF_ARG(result.name, "name"), + FF_ARG(result.exe, "exe-name"), + FF_ARG(result.path, "path"), + FF_ARG(result.version, "version"), + })); } ffStrbufDestroy(&result.name); @@ -56,26 +49,23 @@ bool ffPrintEditor(FFEditorOptions* options) return true; } -void ffParseEditorJsonObject(FFEditorOptions* options, yyjson_val* module) -{ +void ffParseEditorJsonObject(FFEditorOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_EDITOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateEditorJsonConfig(FFEditorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateEditorJsonConfig(FFEditorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateEditorJsonResult(FF_MAYBE_UNUSED FFEditorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateEditorJsonResult(FF_MAYBE_UNUSED FFEditorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFEditorResult result = { .name = ffStrbufCreate(), .path = ffStrbufCreate(), @@ -84,8 +74,7 @@ bool ffGenerateEditorJsonResult(FF_MAYBE_UNUSED FFEditorOptions* options, yyjson const char* error = ffDetectEditor(&result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -105,13 +94,11 @@ bool ffGenerateEditorJsonResult(FF_MAYBE_UNUSED FFEditorOptions* options, yyjson return true; } -void ffInitEditorOptions(FFEditorOptions* options) -{ +void ffInitEditorOptions(FFEditorOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󱞎"); } -void ffDestroyEditorOptions(FFEditorOptions* options) -{ +void ffDestroyEditorOptions(FFEditorOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -130,5 +117,4 @@ FFModuleBaseInfo ffEditorModuleInfo = { {"Exe name of real path", "exe-name"}, {"Full path of real path", "path"}, {"Version", "version"}, - })) -}; + }))}; diff --git a/src/modules/editor/option.h b/src/modules/editor/option.h index f7c545f84..e812ca9ff 100644 --- a/src/modules/editor/option.h +++ b/src/modules/editor/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFEditorOptions -{ +typedef struct FFEditorOptions { FFModuleArgs moduleArgs; } FFEditorOptions; diff --git a/src/modules/font/font.c b/src/modules/font/font.c index 56d939c1b..b5873dd94 100644 --- a/src/modules/font/font.c +++ b/src/modules/font/font.c @@ -4,103 +4,93 @@ #include "detection/font/font.h" #include "modules/font/font.h" -bool ffPrintFont(FFFontOptions* options) -{ +bool ffPrintFont(FFFontOptions* options) { bool success = false; FFFontResult font; - for(uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) + for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { ffStrbufInit(&font.fonts[i]); + } ffStrbufInit(&font.display); const char* error = ffDetectFont(&font); - if(error) - { + if (error) { ffPrintError(FF_FONT_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); - } - else - { - if(options->moduleArgs.outputFormat.length == 0) - { + } else { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_FONT_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&font.display, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_FONT_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(font.fonts[0], "font1"), - FF_ARG(font.fonts[1], "font2"), - FF_ARG(font.fonts[2], "font3"), - FF_ARG(font.fonts[3], "font4"), - FF_ARG(font.display, "combined"), - })); + FF_ARG(font.fonts[0], "font1"), + FF_ARG(font.fonts[1], "font2"), + FF_ARG(font.fonts[2], "font3"), + FF_ARG(font.fonts[3], "font4"), + FF_ARG(font.display, "combined"), + })); } success = true; } ffStrbufDestroy(&font.display); - for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) + for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { ffStrbufDestroy(&font.fonts[i]); + } return success; } -void ffParseFontJsonObject(FFFontOptions* options, yyjson_val* module) -{ +void ffParseFontJsonObject(FFFontOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_FONT_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateFontJsonConfig(FFFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateFontJsonConfig(FFFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateFontJsonResult(FF_MAYBE_UNUSED FFFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateFontJsonResult(FF_MAYBE_UNUSED FFFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFFontResult font; - for(uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) + for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { ffStrbufInit(&font.fonts[i]); + } ffStrbufInit(&font.display); const char* error = ffDetectFont(&font); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); - } - else - { + } else { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); yyjson_mut_obj_add_strbuf(doc, obj, "display", &font.display); yyjson_mut_val* fontsArr = yyjson_mut_obj_add_arr(doc, obj, "fonts"); - for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) + for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { yyjson_mut_arr_add_strbuf(doc, fontsArr, &font.fonts[i]); + } success = true; } ffStrbufDestroy(&font.display); - for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) + for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { ffStrbufDestroy(&font.fonts[i]); + } return success; } -void ffInitFontOptions(FFFontOptions* options) -{ +void ffInitFontOptions(FFFontOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyFontOptions(FFFontOptions* options) -{ +void ffDestroyFontOptions(FFFontOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -119,5 +109,4 @@ FFModuleBaseInfo ffFontModuleInfo = { {"Font 3", "font3"}, {"Font 4", "font4"}, {"Combined fonts for display", "combined"}, - })) -}; + }))}; diff --git a/src/modules/font/option.h b/src/modules/font/option.h index 6c942e7dd..b2e2753e4 100644 --- a/src/modules/font/option.h +++ b/src/modules/font/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFFontOptions -{ +typedef struct FFFontOptions { FFModuleArgs moduleArgs; } FFFontOptions; diff --git a/src/modules/gamepad/gamepad.c b/src/modules/gamepad/gamepad.c index 87fcc1be9..8ee59bb95 100644 --- a/src/modules/gamepad/gamepad.c +++ b/src/modules/gamepad/gamepad.c @@ -5,105 +5,91 @@ #include "detection/gamepad/gamepad.h" #include "modules/gamepad/gamepad.h" -static void printDevice(FFGamepadOptions* options, const FFGamepadDevice* device, uint8_t index) -{ +static void printDevice(FFGamepadOptions* options, const FFGamepadDevice* device, uint8_t index) { FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_GAMEPAD_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); bool showBatteryLevel = device->battery > 0 && device->battery <= 100; - if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_BAR_BIT)) - { + if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_BAR_BIT)) { ffPercentAppendBar(&buffer, device->battery, options->percent, &options->moduleArgs); ffStrbufAppendC(&buffer, ' '); } - if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppend(&buffer, &device->name); + } - if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_NUM_BIT)) - { - if (buffer.length) + if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_NUM_BIT)) { + if (buffer.length) { ffStrbufAppendC(&buffer, ' '); + } ffPercentAppendNum(&buffer, device->battery, options->percent, buffer.length > 0, &options->moduleArgs); } ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY percentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&percentageNum, device->battery, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY percentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&percentageBar, device->battery, options->percent, &options->moduleArgs); + } FF_PRINT_FORMAT_CHECKED(FF_GAMEPAD_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(device->name, "name"), - FF_ARG(device->serial, "serial"), - FF_ARG(percentageNum, "battery-percentage"), - FF_ARG(percentageBar, "battery-percentage-bar"), - })); + FF_ARG(device->name, "name"), + FF_ARG(device->serial, "serial"), + FF_ARG(percentageNum, "battery-percentage"), + FF_ARG(percentageBar, "battery-percentage-bar"), + })); } } -bool ffPrintGamepad(FFGamepadOptions* options) -{ +bool ffPrintGamepad(FFGamepadOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFGamepadDevice)); const char* error = ffDetectGamepad(&result); - if(error) - { + if (error) { ffPrintError(FF_GAMEPAD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(!result.length) - { + if (!result.length) { ffPrintError(FF_GAMEPAD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No devices detected"); return false; } FF_LIST_AUTO_DESTROY filtered = ffListCreate(sizeof(FFGamepadDevice*)); - FF_LIST_FOR_EACH(FFGamepadDevice, device, result) - { + FF_LIST_FOR_EACH (FFGamepadDevice, device, result) { bool ignored = false; - FF_LIST_FOR_EACH(FFstrbuf, ignore, options->ignores) - { - if(ffStrbufStartsWithIgnCase(&device->name, ignore)) - { + FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) { + if (ffStrbufStartsWithIgnCase(&device->name, ignore)) { ignored = true; break; } } - if(!ignored) - { + if (!ignored) { FFGamepadDevice** ptr = ffListAdd(&filtered); *ptr = device; } } bool ret = true; - if(!filtered.length) - { + if (!filtered.length) { ffPrintError(FF_GAMEPAD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "All devices are ignored"); ret = false; - } - else - { + } else { uint8_t index = 0; - FF_LIST_FOR_EACH(FFGamepadDevice*, pdevice, filtered) - { + FF_LIST_FOR_EACH (FFGamepadDevice*, pdevice, filtered) { FFGamepadDevice* device = *pdevice; printDevice(options, device, filtered.length > 1 ? ++index : 0); } - FF_LIST_FOR_EACH(FFGamepadDevice, device, result) - { + FF_LIST_FOR_EACH (FFGamepadDevice, device, result) { ffStrbufDestroy(&device->serial); ffStrbufDestroy(&device->name); } @@ -112,23 +98,19 @@ bool ffPrintGamepad(FFGamepadOptions* options) return ret; } -void ffParseGamepadJsonObject(FFGamepadOptions* options, yyjson_val* module) -{ +void ffParseGamepadJsonObject(FFGamepadOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "ignores")) - { - yyjson_val *elem; + if (unsafe_yyjson_equals_str(key, "ignores")) { + yyjson_val* elem; size_t eidx, emax; - yyjson_arr_foreach(val, eidx, emax, elem) - { - if (yyjson_is_str(elem)) - { + yyjson_arr_foreach (val, eidx, emax, elem) { + if (yyjson_is_str(elem)) { FFstrbuf* strbuf = ffListAdd(&options->ignores); ffStrbufInitJsonVal(strbuf, elem); } @@ -136,50 +118,45 @@ void ffParseGamepadJsonObject(FFGamepadOptions* options, yyjson_val* module) continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_GAMEPAD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateGamepadJsonConfig(FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateGamepadJsonConfig(FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - if (options->ignores.length > 0) - { + if (options->ignores.length > 0) { yyjson_mut_val* ignores = yyjson_mut_obj_add_arr(doc, module, "ignores"); - FF_LIST_FOR_EACH(FFstrbuf, strbuf, options->ignores) + FF_LIST_FOR_EACH (FFstrbuf, strbuf, options->ignores) { yyjson_mut_arr_append(ignores, yyjson_mut_strncpy(doc, strbuf->chars, strbuf->length)); + } } ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateGamepadJsonResult(FF_MAYBE_UNUSED FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateGamepadJsonResult(FF_MAYBE_UNUSED FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFGamepadDevice)); const char* error = ffDetectGamepad(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFGamepadDevice, device, result) - { + FF_LIST_FOR_EACH (FFGamepadDevice, device, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "serial", &device->serial); yyjson_mut_obj_add_strbuf(doc, obj, "name", &device->name); bool ignored = false; - FF_LIST_FOR_EACH(FFstrbuf, ignore, options->ignores) - { - if(ffStrbufStartsWithIgnCase(&device->name, ignore)) - { + FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) { + if (ffStrbufStartsWithIgnCase(&device->name, ignore)) { ignored = true; break; } @@ -187,8 +164,7 @@ bool ffGenerateGamepadJsonResult(FF_MAYBE_UNUSED FFGamepadOptions* options, yyjs yyjson_mut_obj_add_bool(doc, obj, "ignored", ignored); } - FF_LIST_FOR_EACH(FFGamepadDevice, device, result) - { + FF_LIST_FOR_EACH (FFGamepadDevice, device, result) { ffStrbufDestroy(&device->serial); ffStrbufDestroy(&device->name); } @@ -196,20 +172,19 @@ bool ffGenerateGamepadJsonResult(FF_MAYBE_UNUSED FFGamepadOptions* options, yyjs return true; } -void ffInitGamepadOptions(FFGamepadOptions* options) -{ +void ffInitGamepadOptions(FFGamepadOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰺵"); ffListInit(&options->ignores, sizeof(FFstrbuf)); - options->percent = (FFPercentageModuleConfig) { 50, 20, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 20, 0}; } -void ffDestroyGamepadOptions(FFGamepadOptions* options) -{ +void ffDestroyGamepadOptions(FFGamepadOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); - FF_LIST_FOR_EACH(FFstrbuf, str, options->ignores) + FF_LIST_FOR_EACH (FFstrbuf, str, options->ignores) { ffStrbufDestroy(str); + } ffListDestroy(&options->ignores); } @@ -227,5 +202,4 @@ FFModuleBaseInfo ffGamepadModuleInfo = { {"Serial number", "serial"}, {"Battery percentage num", "battery-percentage"}, {"Battery percentage bar", "battery-percentage-bar"}, - })) -}; + }))}; diff --git a/src/modules/gamepad/option.h b/src/modules/gamepad/option.h index 6425bf00f..64728c085 100644 --- a/src/modules/gamepad/option.h +++ b/src/modules/gamepad/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/FFlist.h" -typedef struct FFGamepadOptions -{ +typedef struct FFGamepadOptions { FFModuleArgs moduleArgs; FFlist ignores; // List of FFstrbuf diff --git a/src/modules/gpu/gpu.c b/src/modules/gpu/gpu.c index d9fd55065..cdfa2c7c4 100644 --- a/src/modules/gpu/gpu.c +++ b/src/modules/gpu/gpu.c @@ -11,70 +11,65 @@ #include -static void printGPUResult(FFGPUOptions* options, uint8_t index, const FFGPUResult* gpu) -{ +static void printGPUResult(FFGPUOptions* options, uint8_t index, const FFGPUResult* gpu) { const char* type; - switch (gpu->type) - { - case FF_GPU_TYPE_INTEGRATED: type = "Integrated"; break; - case FF_GPU_TYPE_DISCRETE: type = "Discrete"; break; - default: type = "Unknown"; break; + switch (gpu->type) { + case FF_GPU_TYPE_INTEGRATED: + type = "Integrated"; + break; + case FF_GPU_TYPE_DISCRETE: + type = "Discrete"; + break; + default: + type = "Unknown"; + break; } FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_GPU_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY output = ffStrbufCreate(); - if(gpu->vendor.length > 0 && !ffStrbufStartsWithIgnCase(&gpu->name, &gpu->vendor)) - { + if (gpu->vendor.length > 0 && !ffStrbufStartsWithIgnCase(&gpu->name, &gpu->vendor)) { ffStrbufAppend(&output, &gpu->vendor); ffStrbufAppendC(&output, ' '); } ffStrbufAppend(&output, &gpu->name); - if(gpu->coreCount != FF_GPU_CORE_COUNT_UNSET) + if (gpu->coreCount != FF_GPU_CORE_COUNT_UNSET) { ffStrbufAppendF(&output, " (%d)", gpu->coreCount); + } - if(gpu->frequency > 0) - { + if (gpu->frequency > 0) { ffStrbufAppendS(&output, " @ "); ffFreqAppendNum(gpu->frequency, &output); } - if(gpu->temperature != FF_GPU_TEMP_UNSET) - { + if (gpu->temperature != FF_GPU_TEMP_UNSET) { ffStrbufAppendS(&output, " - "); ffTempsAppendNum(gpu->temperature, &output, options->tempConfig, &options->moduleArgs); } - if(gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET && gpu->dedicated.total != 0) - { + if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET && gpu->dedicated.total != 0) { ffStrbufAppendS(&output, " ("); - if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) - { - if(gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) - { + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { + if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) { ffSizeAppendNum(gpu->dedicated.used, &output); ffStrbufAppendS(&output, " / "); } ffSizeAppendNum(gpu->dedicated.total, &output); } - if(gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) - { + if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) { double percent = (double) gpu->dedicated.used / (double) gpu->dedicated.total * 100.0; - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) - { + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffStrbufAppendS(&output, ", "); ffPercentAppendNum(&output, percent, options->percent, false, &options->moduleArgs); } - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffStrbufAppendS(&output, " "); ffPercentAppendBar(&output, percent, options->percent, &options->moduleArgs); } @@ -82,43 +77,52 @@ static void printGPUResult(FFGPUOptions* options, uint8_t index, const FFGPUResu ffStrbufAppendC(&output, ')'); } - if (gpu->type != FF_GPU_TYPE_UNKNOWN) + if (gpu->type != FF_GPU_TYPE_UNKNOWN) { ffStrbufAppendF(&output, " [%s]", type); + } ffStrbufPutTo(&output, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY tempStr = ffStrbufCreate(); ffTempsAppendNum(gpu->temperature, &tempStr, options->tempConfig, &options->moduleArgs); FF_STRBUF_AUTO_DESTROY dTotal = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY dUsed = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY dPercentNum = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY dPercentBar = ffStrbufCreate(); - if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) ffSizeAppendNum(gpu->dedicated.total, &dTotal); - if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) ffSizeAppendNum(gpu->dedicated.used, &dUsed); - if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET && gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) - { + if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) { + ffSizeAppendNum(gpu->dedicated.total, &dTotal); + } + if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) { + ffSizeAppendNum(gpu->dedicated.used, &dUsed); + } + if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET && gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) { double percent = (double) gpu->dedicated.used / (double) gpu->dedicated.total * 100.0; - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&dPercentNum, percent, options->percent, false, &options->moduleArgs); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + } + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&dPercentBar, percent, options->percent, &options->moduleArgs); + } } FF_STRBUF_AUTO_DESTROY sTotal = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY sUsed = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY sPercentNum = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY sPercentBar = ffStrbufCreate(); - if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) ffSizeAppendNum(gpu->shared.total, &sTotal); - if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) ffSizeAppendNum(gpu->shared.used, &sUsed); - if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET && gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) - { + if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) { + ffSizeAppendNum(gpu->shared.total, &sTotal); + } + if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) { + ffSizeAppendNum(gpu->shared.used, &sUsed); + } + if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET && gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) { double percent = (double) gpu->shared.used / (double) gpu->shared.total * 100.0; - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&sPercentNum, percent, options->percent, false, &options->moduleArgs); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + } + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&sPercentBar, percent, options->percent, &options->moduleArgs); + } } FF_STRBUF_AUTO_DESTROY frequency = ffStrbufCreate(); @@ -126,45 +130,44 @@ static void printGPUResult(FFGPUOptions* options, uint8_t index, const FFGPUResu FF_STRBUF_AUTO_DESTROY coreUsageNum = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY coreUsageBar = ffStrbufCreate(); - if (gpu->coreUsage != FF_GPU_CORE_USAGE_UNSET) - { - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (gpu->coreUsage != FF_GPU_CORE_USAGE_UNSET) { + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&coreUsageNum, gpu->coreUsage, options->percent, false, &options->moduleArgs); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + } + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&coreUsageBar, gpu->coreUsage, options->percent, &options->moduleArgs); + } } FF_PRINT_FORMAT_CHECKED(FF_GPU_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(gpu->vendor, "vendor"), - FF_ARG(gpu->name, "name"), - FF_ARG(gpu->driver, "driver"), - FF_ARG(tempStr, "temperature"), - FF_ARG(gpu->coreCount, "core-count"), - FF_ARG(type, "type"), - FF_ARG(dTotal, "dedicated-total"), - FF_ARG(dUsed, "dedicated-used"), - FF_ARG(sTotal, "shared-total"), - FF_ARG(sUsed, "shared-used"), - FF_ARG(gpu->platformApi, "platform-api"), - FF_ARG(frequency, "frequency"), - FF_ARG(index, "index"), - FF_ARG(dPercentNum, "dedicated-percentage-num"), - FF_ARG(dPercentBar, "dedicated-percentage-bar"), - FF_ARG(sPercentNum, "shared-percentage-num"), - FF_ARG(sPercentBar, "shared-percentage-bar"), - FF_ARG(coreUsageNum, "core-usage-num"), - FF_ARG(coreUsageBar, "core-usage-bar"), - FF_ARG(gpu->memoryType, "memory-type"), - })); + FF_ARG(gpu->vendor, "vendor"), + FF_ARG(gpu->name, "name"), + FF_ARG(gpu->driver, "driver"), + FF_ARG(tempStr, "temperature"), + FF_ARG(gpu->coreCount, "core-count"), + FF_ARG(type, "type"), + FF_ARG(dTotal, "dedicated-total"), + FF_ARG(dUsed, "dedicated-used"), + FF_ARG(sTotal, "shared-total"), + FF_ARG(sUsed, "shared-used"), + FF_ARG(gpu->platformApi, "platform-api"), + FF_ARG(frequency, "frequency"), + FF_ARG(index, "index"), + FF_ARG(dPercentNum, "dedicated-percentage-num"), + FF_ARG(dPercentBar, "dedicated-percentage-bar"), + FF_ARG(sPercentNum, "shared-percentage-num"), + FF_ARG(sPercentBar, "shared-percentage-bar"), + FF_ARG(coreUsageNum, "core-usage-num"), + FF_ARG(coreUsageBar, "core-usage-bar"), + FF_ARG(gpu->memoryType, "memory-type"), + })); } } -bool ffPrintGPU(FFGPUOptions* options) -{ - FF_LIST_AUTO_DESTROY gpus = ffListCreate(sizeof (FFGPUResult)); +bool ffPrintGPU(FFGPUOptions* options) { + FF_LIST_AUTO_DESTROY gpus = ffListCreate(sizeof(FFGPUResult)); const char* error = ffDetectGPU(options, &gpus); - if (error) - { + if (error) { ffPrintError(FF_GPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } @@ -172,28 +175,31 @@ bool ffPrintGPU(FFGPUOptions* options) FF_LIST_AUTO_DESTROY selectedGPUs; ffListInitA(&selectedGPUs, sizeof(const FFGPUResult*), gpus.length); - FF_LIST_FOR_EACH(FFGPUResult, gpu, gpus) - { - if(gpu->type == FF_GPU_TYPE_UNKNOWN && options->hideType == FF_GPU_TYPE_UNKNOWN) + FF_LIST_FOR_EACH (FFGPUResult, gpu, gpus) { + if (gpu->type == FF_GPU_TYPE_UNKNOWN && options->hideType == FF_GPU_TYPE_UNKNOWN) { continue; + } - if(gpu->type == FF_GPU_TYPE_INTEGRATED && options->hideType == FF_GPU_TYPE_INTEGRATED) + if (gpu->type == FF_GPU_TYPE_INTEGRATED && options->hideType == FF_GPU_TYPE_INTEGRATED) { continue; + } - if(gpu->type == FF_GPU_TYPE_DISCRETE && options->hideType == FF_GPU_TYPE_DISCRETE) + if (gpu->type == FF_GPU_TYPE_DISCRETE && options->hideType == FF_GPU_TYPE_DISCRETE) { continue; + } - * (const FFGPUResult**) ffListAdd(&selectedGPUs) = gpu; + *(const FFGPUResult**) ffListAdd(&selectedGPUs) = gpu; } - for(uint32_t i = 0; i < selectedGPUs.length; i++) + for (uint32_t i = 0; i < selectedGPUs.length; i++) { printGPUResult(options, selectedGPUs.length == 1 ? 0 : (uint8_t) (i + 1), *FF_LIST_GET(const FFGPUResult*, selectedGPUs, i)); + } - if(selectedGPUs.length == 0) + if (selectedGPUs.length == 0) { ffPrintError(FF_GPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No GPUs found"); + } - FF_LIST_FOR_EACH(FFGPUResult, gpu, gpus) - { + FF_LIST_FOR_EACH (FFGPUResult, gpu, gpus) { ffStrbufDestroy(&gpu->vendor); ffStrbufDestroy(&gpu->name); ffStrbufDestroy(&gpu->driver); @@ -204,79 +210,76 @@ bool ffPrintGPU(FFGPUOptions* options) return true; } -void ffParseGPUJsonObject(FFGPUOptions* options, yyjson_val* module) -{ +void ffParseGPUJsonObject(FFGPUOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) + if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) { continue; + } - if (unsafe_yyjson_equals_str(key, "driverSpecific")) - { + if (unsafe_yyjson_equals_str(key, "driverSpecific")) { options->driverSpecific = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "detectionMethod")) - { + if (unsafe_yyjson_equals_str(key, "detectionMethod")) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "auto", FF_GPU_DETECTION_METHOD_AUTO }, - { "pci", FF_GPU_DETECTION_METHOD_PCI }, - { "vulkan", FF_GPU_DETECTION_METHOD_VULKAN }, - { "opencl", FF_GPU_DETECTION_METHOD_OPENCL }, - { "opengl", FF_GPU_DETECTION_METHOD_OPENGL }, - {}, - }); - if (error) + {"auto", FF_GPU_DETECTION_METHOD_AUTO}, + {"pci", FF_GPU_DETECTION_METHOD_PCI}, + {"vulkan", FF_GPU_DETECTION_METHOD_VULKAN}, + {"opencl", FF_GPU_DETECTION_METHOD_OPENCL}, + {"opengl", FF_GPU_DETECTION_METHOD_OPENGL}, + {}, + }); + if (error) { ffPrintError(FF_GPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else + } else { options->detectionMethod = (FFGPUDetectionMethod) value; - continue; - } - - if (unsafe_yyjson_equals_str(key, "hideType")) - { - if (yyjson_is_null(val)) - options->hideType = FF_GPU_TYPE_NONE; - else - { - int value; - const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "none", FF_GPU_TYPE_NONE }, - { "unknown", FF_GPU_TYPE_UNKNOWN }, - { "integrated", FF_GPU_TYPE_INTEGRATED }, - { "discrete", FF_GPU_TYPE_DISCRETE }, - {}, - }); - if (error) - ffPrintError(FF_GPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else - options->hideType = (FFGPUType) value; } continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (unsafe_yyjson_equals_str(key, "hideType")) { + if (yyjson_is_null(val)) { + options->hideType = FF_GPU_TYPE_NONE; + } else { + int value; + const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { + {"none", FF_GPU_TYPE_NONE}, + {"unknown", FF_GPU_TYPE_UNKNOWN}, + {"integrated", FF_GPU_TYPE_INTEGRATED}, + {"discrete", FF_GPU_TYPE_DISCRETE}, + {}, + }); + if (error) { + ffPrintError(FF_GPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); + } else { + options->hideType = (FFGPUType) value; + } + } continue; + } + + if (ffPercentParseJsonObject(key, val, &options->percent)) { + continue; + } ffPrintError(FF_GPU_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateGPUJsonConfig(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateGPUJsonConfig(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "driverSpecific", options->driverSpecific); - switch (options->detectionMethod) - { + switch (options->detectionMethod) { case FF_GPU_DETECTION_METHOD_AUTO: yyjson_mut_obj_add_str(doc, module, "detectionMethod", "auto"); break; @@ -296,8 +299,7 @@ void ffGenerateGPUJsonConfig(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_ ffTempsGenerateJsonConfig(doc, module, options->temp, options->tempConfig); - switch (options->hideType) - { + switch (options->hideType) { case FF_GPU_TYPE_NONE: yyjson_mut_obj_add_str(doc, module, "hideType", "none"); break; @@ -315,98 +317,110 @@ void ffGenerateGPUJsonConfig(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_ ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateGPUJsonResult(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ - FF_LIST_AUTO_DESTROY gpus = ffListCreate(sizeof (FFGPUResult)); +bool ffGenerateGPUJsonResult(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { + FF_LIST_AUTO_DESTROY gpus = ffListCreate(sizeof(FFGPUResult)); const char* error = ffDetectGPU(options, &gpus); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFGPUResult, gpu, gpus) - { + FF_LIST_FOR_EACH (FFGPUResult, gpu, gpus) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); - if (gpu->index != FF_GPU_INDEX_UNSET) + if (gpu->index != FF_GPU_INDEX_UNSET) { yyjson_mut_obj_add_uint(doc, obj, "index", gpu->index); - else + } else { yyjson_mut_obj_add_null(doc, obj, "index"); + } - if (gpu->coreCount != FF_GPU_CORE_COUNT_UNSET) + if (gpu->coreCount != FF_GPU_CORE_COUNT_UNSET) { yyjson_mut_obj_add_int(doc, obj, "coreCount", gpu->coreCount); - else + } else { yyjson_mut_obj_add_null(doc, obj, "coreCount"); + } - if (gpu->coreUsage != FF_GPU_CORE_USAGE_UNSET) + if (gpu->coreUsage != FF_GPU_CORE_USAGE_UNSET) { yyjson_mut_obj_add_real(doc, obj, "coreUsage", gpu->coreUsage); - else + } else { yyjson_mut_obj_add_null(doc, obj, "coreUsage"); + } yyjson_mut_val* memoryObj = yyjson_mut_obj_add_obj(doc, obj, "memory"); yyjson_mut_val* dedicatedObj = yyjson_mut_obj_add_obj(doc, memoryObj, "dedicated"); - if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) + if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, dedicatedObj, "total", gpu->dedicated.total); - else + } else { yyjson_mut_obj_add_null(doc, dedicatedObj, "total"); + } - if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) + if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, dedicatedObj, "used", gpu->dedicated.used); - else + } else { yyjson_mut_obj_add_null(doc, dedicatedObj, "used"); + } yyjson_mut_val* sharedObj = yyjson_mut_obj_add_obj(doc, memoryObj, "shared"); - if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) + if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, sharedObj, "total", gpu->shared.total); - else + } else { yyjson_mut_obj_add_null(doc, sharedObj, "total"); - if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) + } + if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, sharedObj, "used", gpu->shared.used); - else + } else { yyjson_mut_obj_add_null(doc, sharedObj, "used"); + } - if (gpu->memoryType.length) + if (gpu->memoryType.length) { yyjson_mut_obj_add_strbuf(doc, memoryObj, "type", &gpu->memoryType); - else + } else { yyjson_mut_obj_add_null(doc, memoryObj, "type"); + } yyjson_mut_obj_add_strbuf(doc, obj, "driver", &gpu->driver); yyjson_mut_obj_add_strbuf(doc, obj, "name", &gpu->name); - if(gpu->temperature != FF_GPU_TEMP_UNSET) + if (gpu->temperature != FF_GPU_TEMP_UNSET) { yyjson_mut_obj_add_real(doc, obj, "temperature", gpu->temperature); - else + } else { yyjson_mut_obj_add_null(doc, obj, "temperature"); + } const char* type; - switch (gpu->type) - { - case FF_GPU_TYPE_INTEGRATED: type = "Integrated"; break; - case FF_GPU_TYPE_DISCRETE: type = "Discrete"; break; - default: type = NULL; break; + switch (gpu->type) { + case FF_GPU_TYPE_INTEGRATED: + type = "Integrated"; + break; + case FF_GPU_TYPE_DISCRETE: + type = "Discrete"; + break; + default: + type = NULL; + break; } - if (type) + if (type) { yyjson_mut_obj_add_str(doc, obj, "type", type); - else + } else { yyjson_mut_obj_add_null(doc, obj, "type"); + } yyjson_mut_obj_add_strbuf(doc, obj, "vendor", &gpu->vendor); yyjson_mut_obj_add_strbuf(doc, obj, "platformApi", &gpu->platformApi); - if (gpu->frequency != FF_GPU_FREQUENCY_UNSET) + if (gpu->frequency != FF_GPU_FREQUENCY_UNSET) { yyjson_mut_obj_add_uint(doc, obj, "frequency", gpu->frequency); - else + } else { yyjson_mut_obj_add_null(doc, obj, "frequency"); + } yyjson_mut_obj_add_uint(doc, obj, "deviceId", gpu->deviceId); } - FF_LIST_FOR_EACH(FFGPUResult, gpu, gpus) - { + FF_LIST_FOR_EACH (FFGPUResult, gpu, gpus) { ffStrbufDestroy(&gpu->vendor); ffStrbufDestroy(&gpu->name); ffStrbufDestroy(&gpu->driver); @@ -417,26 +431,24 @@ bool ffGenerateGPUJsonResult(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_ return true; } -void ffInitGPUOptions(FFGPUOptions* options) -{ +void ffInitGPUOptions(FFGPUOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰾲"); options->driverSpecific = false; options->detectionMethod = - #if defined(__x86_64__) || defined(__i386__) +#if defined(__x86_64__) || defined(__i386__) FF_GPU_DETECTION_METHOD_PCI - #else +#else FF_GPU_DETECTION_METHOD_AUTO - #endif - ; +#endif + ; options->temp = false; options->hideType = FF_GPU_TYPE_NONE; - options->tempConfig = (FFColorRangeConfig) { 60, 80 }; - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->tempConfig = (FFColorRangeConfig) {60, 80}; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; } -void ffDestroyGPUOptions(FFGPUOptions* options) -{ +void ffDestroyGPUOptions(FFGPUOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } diff --git a/src/modules/gpu/option.h b/src/modules/gpu/option.h index 0d1d0fac8..720a525da 100644 --- a/src/modules/gpu/option.h +++ b/src/modules/gpu/option.h @@ -3,16 +3,14 @@ #include "common/option.h" #include "common/percent.h" -typedef enum __attribute__((__packed__)) FFGPUType -{ - FF_GPU_TYPE_NONE, // Indicates no specific GPU type. Useful as a hide filter only. - FF_GPU_TYPE_UNKNOWN, // Indicates an unknown or unrecognized GPU type. +typedef enum __attribute__((__packed__)) FFGPUType { + FF_GPU_TYPE_NONE, // Indicates no specific GPU type. Useful as a hide filter only. + FF_GPU_TYPE_UNKNOWN, // Indicates an unknown or unrecognized GPU type. FF_GPU_TYPE_INTEGRATED, FF_GPU_TYPE_DISCRETE, } FFGPUType; -typedef enum __attribute__((__packed__)) FFGPUDetectionMethod -{ +typedef enum __attribute__((__packed__)) FFGPUDetectionMethod { FF_GPU_DETECTION_METHOD_AUTO, FF_GPU_DETECTION_METHOD_PCI, FF_GPU_DETECTION_METHOD_VULKAN, @@ -20,8 +18,7 @@ typedef enum __attribute__((__packed__)) FFGPUDetectionMethod FF_GPU_DETECTION_METHOD_OPENGL, } FFGPUDetectionMethod; -typedef struct FFGPUOptions -{ +typedef struct FFGPUOptions { FFModuleArgs moduleArgs; FFGPUType hideType; diff --git a/src/modules/host/host.c b/src/modules/host/host.c index cf45e174c..96306e5c1 100644 --- a/src/modules/host/host.c +++ b/src/modules/host/host.c @@ -4,8 +4,7 @@ #include "detection/host/host.h" #include "modules/host/host.h" -bool ffPrintHost(FFHostOptions* options) -{ +bool ffPrintHost(FFHostOptions* options) { bool success = false; FFHostResult host; ffStrbufInit(&host.family); @@ -17,45 +16,42 @@ bool ffPrintHost(FFHostOptions* options) ffStrbufInit(&host.vendor); const char* error = ffDetectHost(&host); - if(error) - { + if (error) { ffPrintError(FF_HOST_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if(host.name.length == 0 && host.family.length == 0) - { + if (host.name.length == 0 && host.family.length == 0) { ffPrintError(FF_HOST_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "neither product_family nor product_name is set by O.E.M."); goto exit; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_HOST_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY output = ffStrbufCreate(); - if(host.name.length > 0) + if (host.name.length > 0) { ffStrbufAppend(&output, &host.name); - else + } else { ffStrbufAppend(&output, &host.family); + } - if(host.version.length > 0) + if (host.version.length > 0) { ffStrbufAppendF(&output, " (%s)", host.version.chars); + } ffStrbufPutTo(&output, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_HOST_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(host.family, "family"), - FF_ARG(host.name, "name"), - FF_ARG(host.version, "version"), - FF_ARG(host.sku, "sku"), - FF_ARG(host.vendor, "vendor"), - FF_ARG(host.serial, "serial"), - FF_ARG(host.uuid, "uuid"), - })); + FF_ARG(host.family, "family"), + FF_ARG(host.name, "name"), + FF_ARG(host.version, "version"), + FF_ARG(host.sku, "sku"), + FF_ARG(host.vendor, "vendor"), + FF_ARG(host.serial, "serial"), + FF_ARG(host.uuid, "uuid"), + })); } success = true; @@ -71,26 +67,23 @@ exit: return success; } -void ffParseHostJsonObject(FFHostOptions* options, yyjson_val* module) -{ +void ffParseHostJsonObject(FFHostOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_HOST_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateHostJsonConfig(FFHostOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateHostJsonConfig(FFHostOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateHostJsonResult(FF_MAYBE_UNUSED FFHostOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateHostJsonResult(FF_MAYBE_UNUSED FFHostOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFHostResult host; ffStrbufInit(&host.family); @@ -102,14 +95,12 @@ bool ffGenerateHostJsonResult(FF_MAYBE_UNUSED FFHostOptions* options, yyjson_mut ffStrbufInit(&host.vendor); const char* error = ffDetectHost(&host); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } - if (host.family.length == 0 && host.name.length == 0) - { + if (host.family.length == 0 && host.name.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "neither product_family nor product_name is set by O.E.M."); goto exit; } @@ -136,13 +127,11 @@ exit: return success; } -void ffInitHostOptions(FFHostOptions* options) -{ +void ffInitHostOptions(FFHostOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰌢"); } -void ffDestroyHostOptions(FFHostOptions* options) -{ +void ffDestroyHostOptions(FFHostOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -163,5 +152,4 @@ FFModuleBaseInfo ffHostModuleInfo = { {"Product vendor", "vendor"}, {"Product serial number", "serial"}, {"Product uuid", "uuid"}, - })) -}; + }))}; diff --git a/src/modules/host/option.h b/src/modules/host/option.h index 2516f864c..e46c0ebe8 100644 --- a/src/modules/host/option.h +++ b/src/modules/host/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFHostOptions -{ +typedef struct FFHostOptions { FFModuleArgs moduleArgs; } FFHostOptions; diff --git a/src/modules/icons/icons.c b/src/modules/icons/icons.c index 98dfad3b1..314e68197 100644 --- a/src/modules/icons/icons.c +++ b/src/modules/icons/icons.c @@ -4,8 +4,7 @@ #include "detection/icons/icons.h" #include "modules/icons/icons.h" -bool ffPrintIcons(FFIconsOptions* options) -{ +bool ffPrintIcons(FFIconsOptions* options) { bool success = false; FFIconsResult result = { .icons1 = ffStrbufCreate(), @@ -13,31 +12,28 @@ bool ffPrintIcons(FFIconsOptions* options) }; const char* error = ffDetectIcons(&result); - if(error) - { + if (error) { ffPrintError(FF_ICONS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_ICONS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (result.icons1.length) + if (result.icons1.length) { ffStrbufWriteTo(&result.icons1, stdout); - if (result.icons2.length) - { - if (result.icons1.length) + } + if (result.icons2.length) { + if (result.icons1.length) { fputs(", ", stdout); + } ffStrbufWriteTo(&result.icons2, stdout); } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_ICONS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result.icons1, "icons1"), - FF_ARG(result.icons2, "icons2"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_ICONS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result.icons1, "icons1"), + FF_ARG(result.icons2, "icons2"), + })); } success = true; @@ -48,35 +44,30 @@ exit: return success; } -void ffParseIconsJsonObject(FFIconsOptions* options, yyjson_val* module) -{ +void ffParseIconsJsonObject(FFIconsOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_ICONS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateIconsJsonConfig(FFIconsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateIconsJsonConfig(FFIconsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateIconsJsonResult(FF_MAYBE_UNUSED FFIconsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateIconsJsonResult(FF_MAYBE_UNUSED FFIconsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFIconsResult result = { .icons1 = ffStrbufCreate(), - .icons2 = ffStrbufCreate() - }; + .icons2 = ffStrbufCreate()}; const char* error = ffDetectIcons(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } @@ -93,13 +84,11 @@ exit: return success; } -void ffInitIconsOptions(FFIconsOptions* options) -{ +void ffInitIconsOptions(FFIconsOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyIconsOptions(FFIconsOptions* options) -{ +void ffDestroyIconsOptions(FFIconsOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -115,5 +104,4 @@ FFModuleBaseInfo ffIconsModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Icons part 1", "icons1"}, {"Icons part 2", "icons2"}, - })) -}; + }))}; diff --git a/src/modules/icons/option.h b/src/modules/icons/option.h index 966bba5f5..29b82ab3b 100644 --- a/src/modules/icons/option.h +++ b/src/modules/icons/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFIconsOptions -{ +typedef struct FFIconsOptions { FFModuleArgs moduleArgs; } FFIconsOptions; diff --git a/src/modules/initsystem/initsystem.c b/src/modules/initsystem/initsystem.c index f61698340..efa35bf22 100644 --- a/src/modules/initsystem/initsystem.c +++ b/src/modules/initsystem/initsystem.c @@ -6,8 +6,7 @@ #define FF_INITSYSTEM_DISPLAY_NAME "Init System" -bool ffPrintInitSystem(FFInitSystemOptions* options) -{ +bool ffPrintInitSystem(FFInitSystemOptions* options) { bool success = false; FFInitSystemResult result = { .name = ffStrbufCreate(), @@ -18,29 +17,26 @@ bool ffPrintInitSystem(FFInitSystemOptions* options) const char* error = ffDetectInitSystem(&result); - if(error) - { + if (error) { ffPrintError(FF_INITSYSTEM_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_INITSYSTEM_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result.name, stdout); - if (result.version.length) + if (result.version.length) { printf(" %s\n", result.version.chars); - else + } else { putchar('\n'); - } - else - { + } + } else { FF_PRINT_FORMAT_CHECKED(FF_INITSYSTEM_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result.name, "name"), - FF_ARG(result.exe, "exe"), - FF_ARG(result.version, "version"), - FF_ARG(result.pid, "pid"), - })); + FF_ARG(result.name, "name"), + FF_ARG(result.exe, "exe"), + FF_ARG(result.version, "version"), + FF_ARG(result.pid, "pid"), + })); } success = true; @@ -52,26 +48,23 @@ exit: return success; } -void ffParseInitSystemJsonObject(FFInitSystemOptions* options, yyjson_val* module) -{ +void ffParseInitSystemJsonObject(FFInitSystemOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_INITSYSTEM_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateInitSystemJsonConfig(FFInitSystemOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateInitSystemJsonConfig(FFInitSystemOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateInitSystemJsonResult(FF_MAYBE_UNUSED FFInitSystemOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateInitSystemJsonResult(FF_MAYBE_UNUSED FFInitSystemOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFInitSystemResult result = { .name = ffStrbufCreate(), @@ -82,8 +75,7 @@ bool ffGenerateInitSystemJsonResult(FF_MAYBE_UNUSED FFInitSystemOptions* options const char* error = ffDetectInitSystem(&result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } @@ -102,13 +94,11 @@ exit: return success; } -void ffInitInitSystemOptions(FFInitSystemOptions* options) -{ +void ffInitInitSystemOptions(FFInitSystemOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰿄"); } -void ffDestroyInitSystemOptions(FFInitSystemOptions* options) -{ +void ffDestroyInitSystemOptions(FFInitSystemOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -126,5 +116,4 @@ FFModuleBaseInfo ffInitSystemModuleInfo = { {"Init system exe path", "exe"}, {"Init system version path", "version"}, {"Init system pid", "pid"}, - })) -}; + }))}; diff --git a/src/modules/initsystem/option.h b/src/modules/initsystem/option.h index 54c10158e..f59284916 100644 --- a/src/modules/initsystem/option.h +++ b/src/modules/initsystem/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFInitSystemOptions -{ +typedef struct FFInitSystemOptions { FFModuleArgs moduleArgs; } FFInitSystemOptions; diff --git a/src/modules/kernel/kernel.c b/src/modules/kernel/kernel.c index fc26de782..93f828648 100644 --- a/src/modules/kernel/kernel.c +++ b/src/modules/kernel/kernel.c @@ -4,50 +4,43 @@ #include "common/stringUtils.h" #include "modules/kernel/kernel.h" -bool ffPrintKernel(FFKernelOptions* options) -{ +bool ffPrintKernel(FFKernelOptions* options) { const FFPlatformSysinfo* info = &instance.state.platform.sysinfo; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_KERNEL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); printf("%s %s\n", info->name.chars, info->release.chars); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); ffSizeAppendNum(info->pageSize, &str); - FF_PRINT_FORMAT_CHECKED(FF_KERNEL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(info->name, "sysname"), - FF_ARG(info->release, "release"), - FF_ARG(info->version, "version"), - FF_ARG(info->architecture, "arch"), - FF_ARG(str, "page-size"), - })); + FF_PRINT_FORMAT_CHECKED(FF_KERNEL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(info->name, "sysname"), + FF_ARG(info->release, "release"), + FF_ARG(info->version, "version"), + FF_ARG(info->architecture, "arch"), + FF_ARG(str, "page-size"), + })); } return true; } -void ffParseKernelJsonObject(FFKernelOptions* options, yyjson_val* module) -{ +void ffParseKernelJsonObject(FFKernelOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_KERNEL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateKernelJsonConfig(FFKernelOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateKernelJsonConfig(FFKernelOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateKernelJsonResult(FF_MAYBE_UNUSED FFKernelOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateKernelJsonResult(FF_MAYBE_UNUSED FFKernelOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFPlatformSysinfo* info = &instance.state.platform.sysinfo; yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); @@ -60,13 +53,11 @@ bool ffGenerateKernelJsonResult(FF_MAYBE_UNUSED FFKernelOptions* options, yyjson return true; } -void ffInitKernelOptions(FFKernelOptions* options) -{ +void ffInitKernelOptions(FFKernelOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyKernelOptions(FFKernelOptions* options) -{ +void ffDestroyKernelOptions(FFKernelOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -86,5 +77,4 @@ FFModuleBaseInfo ffKernelModuleInfo = { {"Architecture", "arch"}, {"Display version", "display-version"}, {"Page size", "page-size"}, - })) -}; + }))}; diff --git a/src/modules/kernel/option.h b/src/modules/kernel/option.h index 2b2b27d7e..a6520a952 100644 --- a/src/modules/kernel/option.h +++ b/src/modules/kernel/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFKernelOptions -{ +typedef struct FFKernelOptions { FFModuleArgs moduleArgs; } FFKernelOptions; diff --git a/src/modules/keyboard/keyboard.c b/src/modules/keyboard/keyboard.c index b3b2e28d9..1f94ad437 100644 --- a/src/modules/keyboard/keyboard.c +++ b/src/modules/keyboard/keyboard.c @@ -5,70 +5,55 @@ #include "detection/keyboard/keyboard.h" #include "modules/keyboard/keyboard.h" -static void printDevice(FFKeyboardOptions* options, const FFKeyboardDevice* device, uint8_t index) -{ - if(options->moduleArgs.outputFormat.length == 0) - { +static void printDevice(FFKeyboardOptions* options, const FFKeyboardDevice* device, uint8_t index) { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_KEYBOARD_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&device->name, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_KEYBOARD_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(device->name, "name"), - FF_ARG(device->serial, "serial"), - })); + FF_ARG(device->name, "name"), + FF_ARG(device->serial, "serial"), + })); } } -bool ffPrintKeyboard(FFKeyboardOptions* options) -{ +bool ffPrintKeyboard(FFKeyboardOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFKeyboardDevice)); const char* error = ffDetectKeyboard(&result); - if(error) - { + if (error) { ffPrintError(FF_KEYBOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(!result.length) - { + if (!result.length) { ffPrintError(FF_KEYBOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No devices detected"); return false; } FF_LIST_AUTO_DESTROY filtered = ffListCreate(sizeof(FFKeyboardDevice*)); - FF_LIST_FOR_EACH(FFKeyboardDevice, device, result) - { + FF_LIST_FOR_EACH (FFKeyboardDevice, device, result) { bool ignored = false; - FF_LIST_FOR_EACH(FFstrbuf, ignore, options->ignores) - { - if(ffStrbufStartsWithIgnCase(&device->name, ignore)) - { + FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) { + if (ffStrbufStartsWithIgnCase(&device->name, ignore)) { ignored = true; break; } } - if(!ignored) - { + if (!ignored) { FFKeyboardDevice** ptr = ffListAdd(&filtered); *ptr = device; } } bool ret = true; - if(!filtered.length) - { + if (!filtered.length) { ffPrintError(FF_KEYBOARD_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "All devices are ignored"); ret = false; - } - else - { + } else { uint8_t index = 0; - FF_LIST_FOR_EACH(FFKeyboardDevice*, pdevice, filtered) - { + FF_LIST_FOR_EACH (FFKeyboardDevice*, pdevice, filtered) { FFKeyboardDevice* device = *pdevice; printDevice(options, device, filtered.length > 1 ? ++index : 0); ffStrbufDestroy(&device->serial); @@ -79,23 +64,19 @@ bool ffPrintKeyboard(FFKeyboardOptions* options) return ret; } -void ffParseKeyboardJsonObject(FFKeyboardOptions* options, yyjson_val* module) -{ +void ffParseKeyboardJsonObject(FFKeyboardOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "ignores")) - { - yyjson_val *elem; + if (unsafe_yyjson_equals_str(key, "ignores")) { + yyjson_val* elem; size_t eidx, emax; - yyjson_arr_foreach(val, eidx, emax, elem) - { - if (yyjson_is_str(elem)) - { + yyjson_arr_foreach (val, eidx, emax, elem) { + if (yyjson_is_str(elem)) { FFstrbuf* strbuf = ffListAdd(&options->ignores); ffStrbufInitJsonVal(strbuf, elem); } @@ -107,42 +88,36 @@ void ffParseKeyboardJsonObject(FFKeyboardOptions* options, yyjson_val* module) } } -void ffGenerateKeyboardJsonConfig(FFKeyboardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateKeyboardJsonConfig(FFKeyboardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - if (options->ignores.length > 0) - { + if (options->ignores.length > 0) { yyjson_mut_val* ignores = yyjson_mut_obj_add_arr(doc, module, "ignores"); - FF_LIST_FOR_EACH(FFstrbuf, strbuf, options->ignores) + FF_LIST_FOR_EACH (FFstrbuf, strbuf, options->ignores) { yyjson_mut_arr_append(ignores, yyjson_mut_strncpy(doc, strbuf->chars, strbuf->length)); + } } } -bool ffGenerateKeyboardJsonResult(FF_MAYBE_UNUSED FFKeyboardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateKeyboardJsonResult(FF_MAYBE_UNUSED FFKeyboardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFKeyboardDevice)); const char* error = ffDetectKeyboard(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFKeyboardDevice, device, result) - { + FF_LIST_FOR_EACH (FFKeyboardDevice, device, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "serial", &device->serial); yyjson_mut_obj_add_strbuf(doc, obj, "name", &device->name); bool ignored = false; - FF_LIST_FOR_EACH(FFstrbuf, ignore, options->ignores) - { - if(ffStrbufStartsWithIgnCase(&device->name, ignore)) - { + FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) { + if (ffStrbufStartsWithIgnCase(&device->name, ignore)) { ignored = true; break; } @@ -150,8 +125,7 @@ bool ffGenerateKeyboardJsonResult(FF_MAYBE_UNUSED FFKeyboardOptions* options, yy yyjson_mut_obj_add_bool(doc, obj, "ignored", ignored); } - FF_LIST_FOR_EACH(FFKeyboardDevice, device, result) - { + FF_LIST_FOR_EACH (FFKeyboardDevice, device, result) { ffStrbufDestroy(&device->serial); ffStrbufDestroy(&device->name); } @@ -159,19 +133,18 @@ bool ffGenerateKeyboardJsonResult(FF_MAYBE_UNUSED FFKeyboardOptions* options, yy return true; } -void ffInitKeyboardOptions(FFKeyboardOptions* options) -{ +void ffInitKeyboardOptions(FFKeyboardOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); ffListInit(&options->ignores, sizeof(FFstrbuf)); } -void ffDestroyKeyboardOptions(FFKeyboardOptions* options) -{ +void ffDestroyKeyboardOptions(FFKeyboardOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); - FF_LIST_FOR_EACH(FFstrbuf, str, options->ignores) + FF_LIST_FOR_EACH (FFstrbuf, str, options->ignores) { ffStrbufDestroy(str); + } ffListDestroy(&options->ignores); } @@ -187,5 +160,4 @@ FFModuleBaseInfo ffKeyboardModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Name", "name"}, {"Serial number", "serial"}, - })) -}; + }))}; diff --git a/src/modules/keyboard/option.h b/src/modules/keyboard/option.h index a454da331..5d691d520 100644 --- a/src/modules/keyboard/option.h +++ b/src/modules/keyboard/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/FFlist.h" -typedef struct FFKeyboardOptions -{ +typedef struct FFKeyboardOptions { FFModuleArgs moduleArgs; FFlist ignores; // List of FFstrbuf diff --git a/src/modules/lm/lm.c b/src/modules/lm/lm.c index 742793b6f..89cc693a3 100644 --- a/src/modules/lm/lm.c +++ b/src/modules/lm/lm.c @@ -4,8 +4,7 @@ #include "detection/lm/lm.h" #include "modules/lm/lm.h" -bool ffPrintLM(FFLMOptions* options) -{ +bool ffPrintLM(FFLMOptions* options) { bool success = false; FFLMResult result; ffStrbufInit(&result.service); @@ -13,35 +12,32 @@ bool ffPrintLM(FFLMOptions* options) ffStrbufInit(&result.version); const char* error = ffDetectLM(&result); - if(error) - { + if (error) { ffPrintError(FF_LM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } - if(result.service.length == 0) - { + if (result.service.length == 0) { ffPrintError(FF_LM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No LM service found"); goto exit; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_LM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result.service, stdout); - if(result.version.length) + if (result.version.length) { printf(" %s", result.version.chars); - if(result.type.length) + } + if (result.type.length) { printf(" (%s)", result.type.chars); + } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_LM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result.service, "service"), - FF_ARG(result.type, "type"), - FF_ARG(result.version, "version"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_LM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result.service, "service"), + FF_ARG(result.type, "type"), + FF_ARG(result.version, "version"), + })); } success = true; @@ -53,26 +49,23 @@ exit: return success; } -void ffParseLMJsonObject(FFLMOptions* options, yyjson_val* module) -{ +void ffParseLMJsonObject(FFLMOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_LM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateLMJsonConfig(FFLMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateLMJsonConfig(FFLMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateLMJsonResult(FF_MAYBE_UNUSED FFLMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateLMJsonResult(FF_MAYBE_UNUSED FFLMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFLMResult result; ffStrbufInit(&result.service); @@ -80,14 +73,12 @@ bool ffGenerateLMJsonResult(FF_MAYBE_UNUSED FFLMOptions* options, yyjson_mut_doc ffStrbufInit(&result.version); const char* error = ffDetectLM(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); goto exit; } - if(result.service.length == 0) - { + if (result.service.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "No LM service found"); goto exit; } @@ -106,13 +97,11 @@ exit: return success; } -void ffInitLMOptions(FFLMOptions* options) -{ +void ffInitLMOptions(FFLMOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰧨"); } -void ffDestroyLMOptions(FFLMOptions* options) -{ +void ffDestroyLMOptions(FFLMOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -129,5 +118,4 @@ FFModuleBaseInfo ffLMModuleInfo = { {"LM service", "service"}, {"LM type", "type"}, {"LM version", "version"}, - })) -}; + }))}; diff --git a/src/modules/lm/option.h b/src/modules/lm/option.h index 21a4ad8b7..918ae9bef 100644 --- a/src/modules/lm/option.h +++ b/src/modules/lm/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFLMOptions -{ +typedef struct FFLMOptions { FFModuleArgs moduleArgs; } FFLMOptions; diff --git a/src/modules/loadavg/loadavg.c b/src/modules/loadavg/loadavg.c index b7262c64f..1c14b03b2 100644 --- a/src/modules/loadavg/loadavg.c +++ b/src/modules/loadavg/loadavg.c @@ -6,26 +6,20 @@ #include "detection/cpu/cpu.h" #include "modules/loadavg/loadavg.h" -bool ffPrintLoadavg(FFLoadavgOptions* options) -{ - double result[3] = { 0.0 / 0.0, 0.0 / 0.0, 0.0 / 0.0 }; +bool ffPrintLoadavg(FFLoadavgOptions* options) { + double result[3] = {0.0 / 0.0, 0.0 / 0.0, 0.0 / 0.0}; const char* error = ffDetectLoadavg(result); - if(error) - { + if (error) { ffPrintError(FF_LOADAVG_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { - if (options->compact) - { + if (options->moduleArgs.outputFormat.length == 0) { + if (options->compact) { ffPrintLogoAndKey(FF_LOADAVG_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); printf("%.*f, %.*f, %.*f\n", options->ndigits, result[0], options->ndigits, result[1], options->ndigits, result[2]); - } - else - { + } else { FFCPUResult cpu = { .temperature = FF_CPU_TEMP_UNSET, .frequencyMax = 0, @@ -36,21 +30,18 @@ bool ffPrintLoadavg(FFLoadavgOptions* options) ffDetectCPU(&(FFCPUOptions) {}, &cpu); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - for (uint32_t index = 0; index < 3; index++) - { - uint32_t duration = index == 0 ? 1 : index == 1 ? 5 : 15; - if (options->moduleArgs.key.length == 0) - { + for (uint32_t index = 0; index < 3; index++) { + uint32_t duration = index == 0 ? 1 : index == 1 ? 5 + : 15; + if (options->moduleArgs.key.length == 0) { ffStrbufSetF(&buffer, "%s (%d min)", FF_LOADAVG_MODULE_NAME, duration); - } - else - { + } else { ffStrbufClear(&buffer); FF_PARSE_FORMAT_STRING_CHECKED(&buffer, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(duration, "duration"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(duration, "duration"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } ffPrintLogoAndKey(buffer.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); @@ -59,69 +50,65 @@ bool ffPrintLoadavg(FFLoadavgOptions* options) double percent = result[index] * 100 / cpu.coresOnline; FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&buffer, percent, options->percent, &options->moduleArgs); + } - if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) - { - if (buffer.length > 0) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { + if (buffer.length > 0) { ffStrbufAppendC(&buffer, ' '); + } ffStrbufAppendF(&buffer, "%.*f", options->ndigits, result[index]); } - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) - { - if (buffer.length > 0) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { + if (buffer.length > 0) { ffStrbufAppendC(&buffer, ' '); + } ffPercentAppendNum(&buffer, percent, options->percent, buffer.length > 0, &options->moduleArgs); } ffStrbufPutTo(&buffer, stdout); } } - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_LOADAVG_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result[0], "loadavg1"), - FF_ARG(result[1], "loadavg2"), - FF_ARG(result[2], "loadavg3"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_LOADAVG_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result[0], "loadavg1"), + FF_ARG(result[1], "loadavg2"), + FF_ARG(result[2], "loadavg3"), + })); } return true; } -void ffParseLoadavgJsonObject(FFLoadavgOptions* options, yyjson_val* module) -{ +void ffParseLoadavgJsonObject(FFLoadavgOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "ndigits")) - { + if (unsafe_yyjson_equals_str(key, "ndigits")) { options->ndigits = (uint8_t) yyjson_get_uint(val); continue; } - if (unsafe_yyjson_equals_str(key, "compact")) - { + if (unsafe_yyjson_equals_str(key, "compact")) { options->compact = yyjson_get_bool(val); continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_LOADAVG_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateLoadavgJsonConfig(FFLoadavgOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateLoadavgJsonConfig(FFLoadavgOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_uint(doc, module, "ndigits", options->ndigits); @@ -131,35 +118,32 @@ void ffGenerateLoadavgJsonConfig(FFLoadavgOptions* options, yyjson_mut_doc* doc, ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateLoadavgJsonResult(FF_MAYBE_UNUSED FFLoadavgOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ - double result[3] = { 0.0 / 0.0, 0.0 / 0.0, 0.0 / 0.0 }; +bool ffGenerateLoadavgJsonResult(FF_MAYBE_UNUSED FFLoadavgOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { + double result[3] = {0.0 / 0.0, 0.0 / 0.0, 0.0 / 0.0}; const char* error = ffDetectLoadavg(result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - for (size_t i = 0; i < 3; i++) + for (size_t i = 0; i < 3; i++) { yyjson_mut_arr_add_real(doc, arr, result[i]); + } return true; } -void ffInitLoadavgOptions(FFLoadavgOptions* options) -{ +void ffInitLoadavgOptions(FFLoadavgOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; options->ndigits = 2; options->compact = true; } -void ffDestroyLoadavgOptions(FFLoadavgOptions* options) -{ +void ffDestroyLoadavgOptions(FFLoadavgOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -176,5 +160,4 @@ FFModuleBaseInfo ffLoadavgModuleInfo = { {"Load average over 1min", "loadavg1"}, {"Load average over 5min", "loadavg2"}, {"Load average over 15min", "loadavg3"}, - })) -}; + }))}; diff --git a/src/modules/loadavg/option.h b/src/modules/loadavg/option.h index 947b310db..b66d42281 100644 --- a/src/modules/loadavg/option.h +++ b/src/modules/loadavg/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFLoadavgOptions -{ +typedef struct FFLoadavgOptions { FFModuleArgs moduleArgs; FFPercentageModuleConfig percent; diff --git a/src/modules/locale/locale.c b/src/modules/locale/locale.c index 12d783533..c23ebb02d 100644 --- a/src/modules/locale/locale.c +++ b/src/modules/locale/locale.c @@ -3,64 +3,52 @@ #include "detection/locale/locale.h" #include "modules/locale/locale.h" -bool ffPrintLocale(FFLocaleOptions* options) -{ +bool ffPrintLocale(FFLocaleOptions* options) { FF_STRBUF_AUTO_DESTROY locale = ffStrbufCreate(); const char* error = ffDetectLocale(&locale); - if(error) - { + if (error) { ffPrintError(FF_LOCALE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_LOCALE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&locale, stdout); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_LOCALE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(locale, "result") - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_LOCALE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) {FF_ARG(locale, "result")})); } return true; } -void ffParseLocaleJsonObject(FFLocaleOptions* options, yyjson_val* module) -{ +void ffParseLocaleJsonObject(FFLocaleOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_LOCALE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateLocaleJsonConfig(FFLocaleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateLocaleJsonConfig(FFLocaleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateLocaleJsonResult(FF_MAYBE_UNUSED FFLocaleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateLocaleJsonResult(FF_MAYBE_UNUSED FFLocaleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY locale = ffStrbufCreate(); const char* error = ffDetectLocale(&locale); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } - if(locale.length == 0) - { + if (locale.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "No locale found"); return false; } @@ -70,13 +58,11 @@ bool ffGenerateLocaleJsonResult(FF_MAYBE_UNUSED FFLocaleOptions* options, yyjson return true; } -void ffInitLocaleOptions(FFLocaleOptions* options) -{ +void ffInitLocaleOptions(FFLocaleOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyLocaleOptions(FFLocaleOptions* options) -{ +void ffDestroyLocaleOptions(FFLocaleOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -91,5 +77,4 @@ FFModuleBaseInfo ffLocaleModuleInfo = { .generateJsonConfig = (void*) ffGenerateLocaleJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Locale code", "result"}, - })) -}; + }))}; diff --git a/src/modules/locale/option.h b/src/modules/locale/option.h index 236d61ee3..19cc9f2be 100644 --- a/src/modules/locale/option.h +++ b/src/modules/locale/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFLocaleOptions -{ +typedef struct FFLocaleOptions { FFModuleArgs moduleArgs; } FFLocaleOptions; diff --git a/src/modules/localip/localip.c b/src/modules/localip/localip.c index 8eac79a6f..872b6c436 100644 --- a/src/modules/localip/localip.c +++ b/src/modules/localip/localip.c @@ -7,110 +7,104 @@ #define FF_LOCALIP_DISPLAY_NAME "Local IP" #pragma GCC diagnostic ignored "-Wsign-conversion" -static int sortIps(const FFLocalIpResult* left, const FFLocalIpResult* right) -{ +static int sortIps(const FFLocalIpResult* left, const FFLocalIpResult* right) { return ffStrbufComp(&left->name, &right->name); } -static void formatKey(const FFLocalIpOptions* options, FFLocalIpResult* ip, uint32_t index, FFstrbuf* key) -{ - if(options->moduleArgs.key.length == 0) - { - if(!ip->name.length) +static void formatKey(const FFLocalIpOptions* options, FFLocalIpResult* ip, uint32_t index, FFstrbuf* key) { + if (options->moduleArgs.key.length == 0) { + if (!ip->name.length) { ffStrbufSetF(&ip->name, "unknown %u", (unsigned) index); + } ffStrbufSetF(key, FF_LOCALIP_DISPLAY_NAME " (%s)", ip->name.chars); - } - else - { + } else { ffStrbufClear(key); FF_PARSE_FORMAT_STRING_CHECKED(key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(ip->name, "ifname"), - FF_ARG(ip->mac, "mac"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(ip->name, "ifname"), + FF_ARG(ip->mac, "mac"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } } -static void appendSpeed(FFLocalIpResult* ip, FFstrbuf* strbuf) -{ - if (ip->speed >= 1000000) - { +static void appendSpeed(FFLocalIpResult* ip, FFstrbuf* strbuf) { + if (ip->speed >= 1000000) { ffStrbufAppendDouble(strbuf, ip->speed / 1e6, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros == FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS); ffStrbufAppendS(strbuf, " Tbps"); - } - else if (ip->speed >= 1000) - { + } else if (ip->speed >= 1000) { ffStrbufAppendDouble(strbuf, ip->speed / 1e3, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros == FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS); ffStrbufAppendS(strbuf, " Gbps"); - } - else + } else { ffStrbufAppendF(strbuf, "%u Mbps", (unsigned) ip->speed); + } } -static void printIp(FFLocalIpResult* ip, bool markDefaultRoute, FFstrbuf* buffer) -{ - if (ip->ipv4.length) - { +static void printIp(FFLocalIpResult* ip, bool markDefaultRoute, FFstrbuf* buffer) { + if (ip->ipv4.length) { ffStrbufAppend(buffer, &ip->ipv4); } - if (ip->ipv6.length) - { - if (buffer->length) ffStrbufAppendC(buffer, ' '); + if (ip->ipv6.length) { + if (buffer->length) { + ffStrbufAppendC(buffer, ' '); + } ffStrbufAppend(buffer, &ip->ipv6); } - if (ip->mac.length) - { - if (buffer->length) + if (ip->mac.length) { + if (buffer->length) { ffStrbufAppendF(buffer, " (%s)", ip->mac.chars); - else + } else { ffStrbufAppend(buffer, &ip->mac); - } - if (ip->mtu > 0 || ip->speed > 0) - { - bool flag = buffer->length > 0; - if (flag) - ffStrbufAppendS(buffer, " ["); - if (ip->speed > 0) - { - if (ip->mtu > 0) - ffStrbufAppendS(buffer, "Speed "); - appendSpeed(ip, buffer); - if (ip->mtu > 0) - ffStrbufAppendS(buffer, " / MTU "); } - if (ip->mtu > 0) - ffStrbufAppendF(buffer, "%u", (unsigned) ip->mtu); - if (flag) - ffStrbufAppendC(buffer, ']'); } - if (ip->flags.length) - { + if (ip->mtu > 0 || ip->speed > 0) { bool flag = buffer->length > 0; - if (flag) ffStrbufAppendS(buffer, " <"); - ffStrbufAppend(buffer, &ip->flags); - if (flag) - ffStrbufAppendC(buffer, '>'); + if (flag) { + ffStrbufAppendS(buffer, " ["); + } + if (ip->speed > 0) { + if (ip->mtu > 0) { + ffStrbufAppendS(buffer, "Speed "); + } + appendSpeed(ip, buffer); + if (ip->mtu > 0) { + ffStrbufAppendS(buffer, " / MTU "); + } + } + if (ip->mtu > 0) { + ffStrbufAppendF(buffer, "%u", (unsigned) ip->mtu); + } + if (flag) { + ffStrbufAppendC(buffer, ']'); + } } - if (markDefaultRoute && ip->defaultRoute) + if (ip->flags.length) { + bool flag = buffer->length > 0; + if (flag) { + ffStrbufAppendS(buffer, " <"); + } + ffStrbufAppend(buffer, &ip->flags); + if (flag) { + ffStrbufAppendC(buffer, '>'); + } + } + if (markDefaultRoute && ip->defaultRoute) { ffStrbufAppendS(buffer, " *"); + } } -bool ffPrintLocalIp(FFLocalIpOptions* options) -{ +bool ffPrintLocalIp(FFLocalIpOptions* options) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFLocalIpResult)); const char* error = ffDetectLocalIps(options, &results); - if(error) - { + if (error) { ffPrintError(FF_LOCALIP_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(results.length == 0) - { + if (results.length == 0) { ffPrintError(FF_LOCALIP_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Failed to detect any IPs"); return false; } @@ -119,55 +113,48 @@ bool ffPrintLocalIp(FFLocalIpOptions* options) FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (options->showType & FF_LOCALIP_TYPE_COMPACT_BIT) - { + if (options->showType & FF_LOCALIP_TYPE_COMPACT_BIT) { ffPrintLogoAndKey(FF_LOCALIP_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - FF_LIST_FOR_EACH(FFLocalIpResult, ip, results) - { - if (buffer.length) + FF_LIST_FOR_EACH (FFLocalIpResult, ip, results) { + if (buffer.length) { ffStrbufAppendS(&buffer, " - "); + } printIp(ip, false, &buffer); } ffStrbufPutTo(&buffer, stdout); ffStrbufClear(&buffer); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); uint32_t index = 0; - FF_LIST_FOR_EACH(FFLocalIpResult, ip, results) - { + FF_LIST_FOR_EACH (FFLocalIpResult, ip, results) { formatKey(options, ip, results.length == 1 ? 0 : index + 1, &key); - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); printIp(ip, !(options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT), &buffer); ffStrbufPutTo(&buffer, stdout); - } - else - { - if (ip->speed > 0) + } else { + if (ip->speed > 0) { appendSpeed(ip, &buffer); - FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]){ - FF_ARG(ip->ipv4, "ipv4"), - FF_ARG(ip->ipv6, "ipv6"), - FF_ARG(ip->mac, "mac"), - FF_ARG(ip->name, "ifname"), - FF_ARG(ip->defaultRoute, "is-default-route"), - FF_ARG(ip->mtu, "mtu"), - FF_ARG(buffer, "speed"), - FF_ARG(ip->flags, "flags"), - })); + } + FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { + FF_ARG(ip->ipv4, "ipv4"), + FF_ARG(ip->ipv6, "ipv6"), + FF_ARG(ip->mac, "mac"), + FF_ARG(ip->name, "ifname"), + FF_ARG(ip->defaultRoute, "is-default-route"), + FF_ARG(ip->mtu, "mtu"), + FF_ARG(buffer, "speed"), + FF_ARG(ip->flags, "flags"), + })); } ++index; ffStrbufClear(&buffer); } } - FF_LIST_FOR_EACH(FFLocalIpResult, ip, results) - { + FF_LIST_FOR_EACH (FFLocalIpResult, ip, results) { ffStrbufDestroy(&ip->name); ffStrbufDestroy(&ip->ipv4); ffStrbufDestroy(&ip->ipv6); @@ -178,49 +165,44 @@ bool ffPrintLocalIp(FFLocalIpOptions* options) return true; } -void ffParseLocalIpJsonObject(FFLocalIpOptions* options, yyjson_val* module) -{ +void ffParseLocalIpJsonObject(FFLocalIpOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) - continue; - - if (unsafe_yyjson_equals_str(key, "showIpv4")) - { - if (yyjson_get_bool(val)) - options->showType |= FF_LOCALIP_TYPE_IPV4_BIT; - else - options->showType &= ~FF_LOCALIP_TYPE_IPV4_BIT; + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; } - if (unsafe_yyjson_equals_str(key, "showIpv6")) - { - if (yyjson_is_bool(val)) - { - options->ipv6Type = FF_LOCALIP_IPV6_TYPE_AUTO; - if (unsafe_yyjson_get_bool(val)) - options->showType |= FF_LOCALIP_TYPE_IPV6_BIT; - else - options->showType &= ~FF_LOCALIP_TYPE_IPV6_BIT; + if (unsafe_yyjson_equals_str(key, "showIpv4")) { + if (yyjson_get_bool(val)) { + options->showType |= FF_LOCALIP_TYPE_IPV4_BIT; + } else { + options->showType &= ~FF_LOCALIP_TYPE_IPV4_BIT; } - else if (yyjson_is_str(val)) - { + continue; + } + + if (unsafe_yyjson_equals_str(key, "showIpv6")) { + if (yyjson_is_bool(val)) { + options->ipv6Type = FF_LOCALIP_IPV6_TYPE_AUTO; + if (unsafe_yyjson_get_bool(val)) { + options->showType |= FF_LOCALIP_TYPE_IPV6_BIT; + } else { + options->showType &= ~FF_LOCALIP_TYPE_IPV6_BIT; + } + } else if (yyjson_is_str(val)) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "auto", FF_LOCALIP_IPV6_TYPE_AUTO }, - { "gua", FF_LOCALIP_IPV6_TYPE_GUA_BIT }, - { "ula", FF_LOCALIP_IPV6_TYPE_ULA_BIT }, - { "lla", FF_LOCALIP_IPV6_TYPE_LLA_BIT }, - { "unknown", FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT }, - {}, - }); - if (error) + {"auto", FF_LOCALIP_IPV6_TYPE_AUTO}, + {"gua", FF_LOCALIP_IPV6_TYPE_GUA_BIT}, + {"ula", FF_LOCALIP_IPV6_TYPE_ULA_BIT}, + {"lla", FF_LOCALIP_IPV6_TYPE_LLA_BIT}, + {"unknown", FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT}, + {}, + }); + if (error) { ffPrintError(FF_LOCALIP_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else - { + } else { options->showType |= FF_LOCALIP_TYPE_IPV6_BIT; options->ipv6Type = (FFLocalIpIpv6Type) value; } @@ -228,89 +210,88 @@ void ffParseLocalIpJsonObject(FFLocalIpOptions* options, yyjson_val* module) continue; } - if (unsafe_yyjson_equals_str(key, "showMac")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showMac")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_MAC_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_MAC_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showLoop")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showLoop")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_LOOP_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_LOOP_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showPrefixLen")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showPrefixLen")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_PREFIX_LEN_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_PREFIX_LEN_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showMtu")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showMtu")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_MTU_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_MTU_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showSpeed")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showSpeed")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_SPEED_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_SPEED_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showFlags")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showFlags")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_FLAGS_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_FLAGS_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "compact")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "compact")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_COMPACT_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_COMPACT_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "defaultRouteOnly")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "defaultRouteOnly")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "showAllIps")) - { - if (yyjson_get_bool(val)) + if (unsafe_yyjson_equals_str(key, "showAllIps")) { + if (yyjson_get_bool(val)) { options->showType |= FF_LOCALIP_TYPE_ALL_IPS_BIT; - else + } else { options->showType &= ~FF_LOCALIP_TYPE_ALL_IPS_BIT; + } continue; } - if (unsafe_yyjson_equals_str(key, "namePrefix")) - { + if (unsafe_yyjson_equals_str(key, "namePrefix")) { ffStrbufSetJsonVal(&options->namePrefix, val); continue; } @@ -319,24 +300,31 @@ void ffParseLocalIpJsonObject(FFLocalIpOptions* options, yyjson_val* module) } } -void ffGenerateLocalIpJsonConfig(FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateLocalIpJsonConfig(FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "showIpv4", !!(options->showType & FF_LOCALIP_TYPE_IPV4_BIT)); - if (options->ipv6Type == FF_LOCALIP_IPV6_TYPE_AUTO) + if (options->ipv6Type == FF_LOCALIP_IPV6_TYPE_AUTO) { yyjson_mut_obj_add_bool(doc, module, "showIpv6", !!(options->showType & FF_LOCALIP_TYPE_IPV6_BIT)); - else - { + } else { const char* str = NULL; - switch (options->ipv6Type) - { - case FF_LOCALIP_IPV6_TYPE_GUA_BIT: str = "gua"; break; - case FF_LOCALIP_IPV6_TYPE_ULA_BIT: str = "ula"; break; - case FF_LOCALIP_IPV6_TYPE_LLA_BIT: str = "lla"; break; - case FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT: str = "unknown"; break; - default: str = "auto"; break; + switch (options->ipv6Type) { + case FF_LOCALIP_IPV6_TYPE_GUA_BIT: + str = "gua"; + break; + case FF_LOCALIP_IPV6_TYPE_ULA_BIT: + str = "ula"; + break; + case FF_LOCALIP_IPV6_TYPE_LLA_BIT: + str = "lla"; + break; + case FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT: + str = "unknown"; + break; + default: + str = "auto"; + break; } yyjson_mut_obj_add_str(doc, module, "showIpv6", str); } @@ -362,47 +350,50 @@ void ffGenerateLocalIpJsonConfig(FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_obj_add_strbuf(doc, module, "namePrefix", &options->namePrefix); } -bool ffGenerateLocalIpJsonResult(FF_MAYBE_UNUSED FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateLocalIpJsonResult(FF_MAYBE_UNUSED FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFLocalIpResult)); const char* error = ffDetectLocalIps(options, &results); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFLocalIpResult, ip, results) - { + FF_LIST_FOR_EACH (FFLocalIpResult, ip, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &ip->name); - if (options->showType & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_IPV6_BIT)) - { + if (options->showType & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_IPV6_BIT)) { yyjson_mut_val* defaultRoute = yyjson_mut_obj_add_obj(doc, obj, "defaultRoute"); - if (options->showType & FF_LOCALIP_TYPE_IPV4_BIT) + if (options->showType & FF_LOCALIP_TYPE_IPV4_BIT) { yyjson_mut_obj_add_bool(doc, defaultRoute, "ipv4", !!(ip->defaultRoute & FF_LOCALIP_TYPE_IPV4_BIT)); - if (options->showType & FF_LOCALIP_TYPE_IPV6_BIT) + } + if (options->showType & FF_LOCALIP_TYPE_IPV6_BIT) { yyjson_mut_obj_add_bool(doc, defaultRoute, "ipv6", !!(ip->defaultRoute & FF_LOCALIP_TYPE_IPV6_BIT)); + } } - if (options->showType & FF_LOCALIP_TYPE_IPV4_BIT) + if (options->showType & FF_LOCALIP_TYPE_IPV4_BIT) { yyjson_mut_obj_add_strbuf(doc, obj, "ipv4", &ip->ipv4); - if (options->showType & FF_LOCALIP_TYPE_IPV6_BIT) + } + if (options->showType & FF_LOCALIP_TYPE_IPV6_BIT) { yyjson_mut_obj_add_strbuf(doc, obj, "ipv6", &ip->ipv6); - if (options->showType & FF_LOCALIP_TYPE_MAC_BIT) + } + if (options->showType & FF_LOCALIP_TYPE_MAC_BIT) { yyjson_mut_obj_add_strbuf(doc, obj, "mac", &ip->mac); - if (options->showType & FF_LOCALIP_TYPE_MTU_BIT) + } + if (options->showType & FF_LOCALIP_TYPE_MTU_BIT) { yyjson_mut_obj_add_int(doc, obj, "mtu", ip->mtu); - if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) + } + if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) { yyjson_mut_obj_add_int(doc, obj, "speed", ip->speed); - if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT) + } + if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT) { yyjson_mut_obj_add_strbuf(doc, obj, "flags", &ip->flags); + } } - FF_LIST_FOR_EACH(FFLocalIpResult, ip, results) - { + FF_LIST_FOR_EACH (FFLocalIpResult, ip, results) { ffStrbufDestroy(&ip->name); ffStrbufDestroy(&ip->ipv4); ffStrbufDestroy(&ip->ipv6); @@ -413,21 +404,19 @@ bool ffGenerateLocalIpJsonResult(FF_MAYBE_UNUSED FFLocalIpOptions* options, yyjs return true; } -void ffInitLocalIpOptions(FFLocalIpOptions* options) -{ +void ffInitLocalIpOptions(FFLocalIpOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰩟"); options->showType = FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_PREFIX_LEN_BIT - #if !__ANDROID__ /*Permission denied*/ - | FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT - #endif - ; +#if !__ANDROID__ /*Permission denied*/ + | FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT +#endif + ; options->ipv6Type = FF_LOCALIP_IPV6_TYPE_AUTO; ffStrbufInit(&options->namePrefix); } -void ffDestroyLocalIpOptions(FFLocalIpOptions* options) -{ +void ffDestroyLocalIpOptions(FFLocalIpOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->namePrefix); } @@ -450,5 +439,4 @@ FFModuleBaseInfo ffLocalIPModuleInfo = { {"MTU size in bytes", "mtu"}, {"Link speed (formatted)", "speed"}, {"Interface flags", "flags"}, - })) -}; + }))}; diff --git a/src/modules/localip/option.h b/src/modules/localip/option.h index 18205263c..e220b0e73 100644 --- a/src/modules/localip/option.h +++ b/src/modules/localip/option.h @@ -2,41 +2,38 @@ #include "common/option.h" -typedef enum __attribute__((__packed__)) FFLocalIpType -{ +typedef enum __attribute__((__packed__)) FFLocalIpType { FF_LOCALIP_TYPE_NONE, - FF_LOCALIP_TYPE_LOOP_BIT = 1 << 0, - FF_LOCALIP_TYPE_IPV4_BIT = 1 << 1, - FF_LOCALIP_TYPE_IPV6_BIT = 1 << 2, - FF_LOCALIP_TYPE_MAC_BIT = 1 << 3, - FF_LOCALIP_TYPE_PREFIX_LEN_BIT = 1 << 4, - FF_LOCALIP_TYPE_MTU_BIT = 1 << 5, - FF_LOCALIP_TYPE_SPEED_BIT = 1 << 6, - FF_LOCALIP_TYPE_FLAGS_BIT = 1 << 7, + FF_LOCALIP_TYPE_LOOP_BIT = 1 << 0, + FF_LOCALIP_TYPE_IPV4_BIT = 1 << 1, + FF_LOCALIP_TYPE_IPV6_BIT = 1 << 2, + FF_LOCALIP_TYPE_MAC_BIT = 1 << 3, + FF_LOCALIP_TYPE_PREFIX_LEN_BIT = 1 << 4, + FF_LOCALIP_TYPE_MTU_BIT = 1 << 5, + FF_LOCALIP_TYPE_SPEED_BIT = 1 << 6, + FF_LOCALIP_TYPE_FLAGS_BIT = 1 << 7, - FF_LOCALIP_TYPE_COMPACT_BIT = 1 << 10, + FF_LOCALIP_TYPE_COMPACT_BIT = 1 << 10, FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT = 1 << 11, - FF_LOCALIP_TYPE_ALL_IPS_BIT = 1 << 12, - FF_LOCALIP_TYPE_FORCE_UNSIGNED = UINT16_MAX, + FF_LOCALIP_TYPE_ALL_IPS_BIT = 1 << 12, + FF_LOCALIP_TYPE_FORCE_UNSIGNED = UINT16_MAX, } FFLocalIpType; static_assert(sizeof(FFLocalIpType) == sizeof(uint16_t), ""); -typedef enum __attribute__((__packed__)) FFLocalIpIpv6Type -{ - FF_LOCALIP_IPV6_TYPE_NONE = 0b00000000, - FF_LOCALIP_IPV6_TYPE_GUA_BIT = 0b00000001, - FF_LOCALIP_IPV6_TYPE_ULA_BIT = 0b00000010, - FF_LOCALIP_IPV6_TYPE_LLA_BIT = 0b00000100, - FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT = 0b00001000, // IPv4-mapped, loopback, etc. +typedef enum __attribute__((__packed__)) FFLocalIpIpv6Type { + FF_LOCALIP_IPV6_TYPE_NONE = 0b00000000, + FF_LOCALIP_IPV6_TYPE_GUA_BIT = 0b00000001, + FF_LOCALIP_IPV6_TYPE_ULA_BIT = 0b00000010, + FF_LOCALIP_IPV6_TYPE_LLA_BIT = 0b00000100, + FF_LOCALIP_IPV6_TYPE_UNKNOWN_BIT = 0b00001000, // IPv4-mapped, loopback, etc. FF_LOCALIP_IPV6_TYPE_SECONDARY_BIT = 0b01000000, // Temporary, duplicated, etc. FF_LOCALIP_IPV6_TYPE_PREFERRED_BIT = 0b10000000, // PREFER_SOURCE (manually set) - FF_LOCALIP_IPV6_TYPE_TYPE_MASK = 0b00011111, - FF_LOCALIP_IPV6_TYPE_AUTO = 0b11111111, // Used for detect option + FF_LOCALIP_IPV6_TYPE_TYPE_MASK = 0b00011111, + FF_LOCALIP_IPV6_TYPE_AUTO = 0b11111111, // Used for detect option } FFLocalIpIpv6Type; static_assert(sizeof(FFLocalIpIpv6Type) == sizeof(uint8_t), ""); -typedef struct FFLocalIpOptions -{ +typedef struct FFLocalIpOptions { FFModuleArgs moduleArgs; FFLocalIpType showType; diff --git a/src/modules/logo/logo.c b/src/modules/logo/logo.c index a6fbc7d50..e71e47aa2 100644 --- a/src/modules/logo/logo.c +++ b/src/modules/logo/logo.c @@ -3,33 +3,29 @@ #include "modules/logo/logo.h" #include "options/logo.h" -bool ffPrintLogo(FF_MAYBE_UNUSED FFLogoOptions* options) -{ +bool ffPrintLogo(FF_MAYBE_UNUSED FFLogoOptions* options) { ffPrintError(FF_LOGO_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_DEFAULT, "Supported in JSON format only"); return false; } -void ffParseLogoJsonObject(FF_MAYBE_UNUSED FFLogoOptions* options, FF_MAYBE_UNUSED yyjson_val* module) -{ +void ffParseLogoJsonObject(FF_MAYBE_UNUSED FFLogoOptions* options, FF_MAYBE_UNUSED yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) + yyjson_obj_foreach (module, idx, max, key, val) { + if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) { continue; + } ffPrintError(FF_LOGO_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -bool ffGenerateLogoJsonResult(FF_MAYBE_UNUSED FFLogoOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateLogoJsonResult(FF_MAYBE_UNUSED FFLogoOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFLogoSize size = FF_LOGO_SIZE_UNKNOWN; FFOptionsLogo* logoOptions = &instance.config.logo; - if (logoOptions->type == FF_LOGO_TYPE_SMALL) + if (logoOptions->type == FF_LOGO_TYPE_SMALL) { size = FF_LOGO_SIZE_SMALL; - else if (logoOptions->type != FF_LOGO_TYPE_BUILTIN && logoOptions->type != FF_LOGO_TYPE_AUTO) - { + } else if (logoOptions->type != FF_LOGO_TYPE_BUILTIN && logoOptions->type != FF_LOGO_TYPE_AUTO) { yyjson_mut_obj_add_str(doc, module, "error", "Only 'builtin' and 'small' logo types are supported"); return false; } @@ -38,8 +34,7 @@ bool ffGenerateLogoJsonResult(FF_MAYBE_UNUSED FFLogoOptions* options, yyjson_mut ? ffLogoGetBuiltinForName(&logoOptions->source, size) : ffLogoGetBuiltinDetected(size); - if (!logo) - { + if (!logo) { yyjson_mut_obj_add_str(doc, module, "error", "No built-in logo found for the specified name/size"); return false; } @@ -49,33 +44,36 @@ bool ffGenerateLogoJsonResult(FF_MAYBE_UNUSED FFLogoOptions* options, yyjson_mut yyjson_mut_obj_add_str(doc, obj, "lines", logo->lines); yyjson_mut_val* namesArr = yyjson_mut_obj_add_arr(doc, obj, "names"); - for (size_t i = 0; i < FASTFETCH_LOGO_MAX_NAMES && logo->names[i]; i++) + for (size_t i = 0; i < FASTFETCH_LOGO_MAX_NAMES && logo->names[i]; i++) { yyjson_mut_arr_add_str(doc, namesArr, logo->names[i]); + } yyjson_mut_val* colorsArr = yyjson_mut_obj_add_arr(doc, obj, "colors"); - for (size_t i = 0; i < FASTFETCH_LOGO_MAX_COLORS && logo->colors[i]; i++) + for (size_t i = 0; i < FASTFETCH_LOGO_MAX_COLORS && logo->colors[i]; i++) { yyjson_mut_arr_add_str(doc, colorsArr, logo->colors[i]); + } yyjson_mut_obj_add_str(doc, obj, "colorKeys", logo->colorKeys); yyjson_mut_obj_add_str(doc, obj, "colorTitle", logo->colorTitle); yyjson_mut_val* typeArr = yyjson_mut_obj_add_arr(doc, obj, "type"); - if (logo->type & FF_LOGO_LINE_TYPE_NORMAL) + if (logo->type & FF_LOGO_LINE_TYPE_NORMAL) { yyjson_mut_arr_add_str(doc, typeArr, "normal"); - if (logo->type & FF_LOGO_LINE_TYPE_SMALL_BIT) + } + if (logo->type & FF_LOGO_LINE_TYPE_SMALL_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "small"); - if (logo->type & FF_LOGO_LINE_TYPE_ALTER_BIT) + } + if (logo->type & FF_LOGO_LINE_TYPE_ALTER_BIT) { yyjson_mut_arr_add_str(doc, typeArr, "alter"); + } return true; } -void ffInitLogoOptions(FF_MAYBE_UNUSED FFLogoOptions* options) -{ +void ffInitLogoOptions(FF_MAYBE_UNUSED FFLogoOptions* options) { } -void ffDestroyLogoOptions(FF_MAYBE_UNUSED FFLogoOptions* options) -{ +void ffDestroyLogoOptions(FF_MAYBE_UNUSED FFLogoOptions* options) { } FFModuleBaseInfo ffLogoModuleInfo = { diff --git a/src/modules/logo/option.h b/src/modules/logo/option.h index 92e254e40..605cdfed2 100644 --- a/src/modules/logo/option.h +++ b/src/modules/logo/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFLogoOptions -{ +typedef struct FFLogoOptions { } FFLogoOptions; static_assert(sizeof(FFLogoOptions) <= FF_OPTION_MAX_SIZE, "FFLogoOptions size exceeds maximum allowed size"); diff --git a/src/modules/media/media.c b/src/modules/media/media.c index 252b84b5a..5b9277c5b 100644 --- a/src/modules/media/media.c +++ b/src/modules/media/media.c @@ -6,132 +6,147 @@ #include -static inline bool shouldIgnoreChar(char c) -{ +static inline bool shouldIgnoreChar(char c) { return isblank(c) || c == '-' || c == '.'; } -static bool artistInSongTitle(const FFstrbuf* song, const FFstrbuf* artist) -{ +static bool artistInSongTitle(const FFstrbuf* song, const FFstrbuf* artist) { uint32_t artistIndex = 0; uint32_t songIndex = 0; - while(true) - { - while(shouldIgnoreChar(song->chars[songIndex])) + while (true) { + while (shouldIgnoreChar(song->chars[songIndex])) { ++songIndex; + } - while(shouldIgnoreChar(artist->chars[artistIndex])) + while (shouldIgnoreChar(artist->chars[artistIndex])) { ++artistIndex; + } - if(artist->chars[artistIndex] == '\0') + if (artist->chars[artistIndex] == '\0') { return true; + } - if(song->chars[songIndex] == '\0') + if (song->chars[songIndex] == '\0') { return false; + } - if(tolower(song->chars[songIndex]) != tolower(artist->chars[artistIndex])) + if (tolower(song->chars[songIndex]) != tolower(artist->chars[artistIndex])) { return false; + } ++artistIndex; ++songIndex; } - //Unreachable + // Unreachable return false; } -bool ffPrintMedia(FFMediaOptions* options) -{ +bool ffPrintMedia(FFMediaOptions* options) { const FFMediaResult* media = ffDetectMedia(false); - if(media->error.length > 0) - { + if (media->error.length > 0) { ffPrintError(FF_MEDIA_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", media->error.chars); return false; } FF_STRBUF_AUTO_DESTROY songPretty = ffStrbufCreateCopy(&media->song); const char* removeStrings[] = { - "(Official Music Video)", "(Official Video)", "(Music Video)", "(Official HD Video)", - "[Official Music Video]", "[Official Video]", "[Music Video]", "[Official HD Video]", - "| Official Music Video", "| Official Video", "| Music Video", "| Official HD Video", - "[Official Audio]", "[Audio]", "(Audio)", "| Official Audio", "| Audio", "| OFFICIAL AUDIO", - "(Lyric Video)", "(Official Lyric Video)", "(Lyrics)", - "[Lyric Video]", "[Official Lyric Video]", "[Lyrics]", - "| Lyric Video", "| Official Lyric Video", "| Lyrics", + "(Official Music Video)", + "(Official Video)", + "(Music Video)", + "(Official HD Video)", + "[Official Music Video]", + "[Official Video]", + "[Music Video]", + "[Official HD Video]", + "| Official Music Video", + "| Official Video", + "| Music Video", + "| Official HD Video", + "[Official Audio]", + "[Audio]", + "(Audio)", + "| Official Audio", + "| Audio", + "| OFFICIAL AUDIO", + "(Lyric Video)", + "(Official Lyric Video)", + "(Lyrics)", + "[Lyric Video]", + "[Official Lyric Video]", + "[Lyrics]", + "| Lyric Video", + "| Official Lyric Video", + "| Lyrics", }; ffStrbufRemoveStrings(&songPretty, ARRAY_SIZE(removeStrings), removeStrings); ffStrbufTrimRight(&songPretty, ' '); - if(songPretty.length == 0) + if (songPretty.length == 0) { ffStrbufAppend(&songPretty, &media->song); + } - if(options->moduleArgs.outputFormat.length == 0) - { - //We don't expose artistPretty to the format, as it might be empty (when the think that the artist is already in the song title) + if (options->moduleArgs.outputFormat.length == 0) { + // We don't expose artistPretty to the format, as it might be empty (when the think that the artist is already in the song title) FF_STRBUF_AUTO_DESTROY artistPretty = ffStrbufCreateCopy(&media->artist); ffStrbufRemoveIgnCaseEndS(&artistPretty, " - Topic"); ffStrbufRemoveIgnCaseEndS(&artistPretty, "VEVO"); ffStrbufTrimRight(&artistPretty, ' '); - if(artistInSongTitle(&songPretty, &artistPretty)) + if (artistInSongTitle(&songPretty, &artistPretty)) { ffStrbufClear(&artistPretty); + } ffPrintLogoAndKey(FF_MEDIA_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if(artistPretty.length > 0) - { + if (artistPretty.length > 0) { ffStrbufWriteTo(&artistPretty, stdout); fputs(" - ", stdout); } - if (media->status.length > 0) + if (media->status.length > 0) { ffStrbufAppendF(&songPretty, " (%s)", media->status.chars); + } ffStrbufPutTo(&songPretty, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_MEDIA_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(songPretty, "combined"), - FF_ARG(media->song, "title"), - FF_ARG(media->artist, "artist"), - FF_ARG(media->album, "album"), - FF_ARG(media->status, "status"), - FF_ARG(media->player, "player-name"), - FF_ARG(media->playerId, "player-id"), - FF_ARG(media->url, "url"), - })); + FF_ARG(songPretty, "combined"), + FF_ARG(media->song, "title"), + FF_ARG(media->artist, "artist"), + FF_ARG(media->album, "album"), + FF_ARG(media->status, "status"), + FF_ARG(media->player, "player-name"), + FF_ARG(media->playerId, "player-id"), + FF_ARG(media->url, "url"), + })); } return true; } -void ffParseMediaJsonObject(FFMediaOptions* options, yyjson_val* module) -{ +void ffParseMediaJsonObject(FFMediaOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_MEDIA_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateMediaJsonConfig(FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateMediaJsonConfig(FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateMediaJsonResult(FF_MAYBE_UNUSED FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateMediaJsonResult(FF_MAYBE_UNUSED FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFMediaResult* media = ffDetectMedia(false); - if(media->error.length > 0) - { + if (media->error.length > 0) { yyjson_mut_obj_add_strbuf(doc, module, "error", &media->error); return false; } @@ -143,10 +158,11 @@ bool ffGenerateMediaJsonResult(FF_MAYBE_UNUSED FFMediaOptions* options, yyjson_m yyjson_mut_obj_add_strbuf(doc, song, "artist", &media->artist); yyjson_mut_obj_add_strbuf(doc, song, "album", &media->album); yyjson_mut_obj_add_strbuf(doc, song, "status", &media->status); - if (media->cover.length > 0) + if (media->cover.length > 0) { yyjson_mut_obj_add_strbuf(doc, song, "cover", &media->cover); - else + } else { yyjson_mut_obj_add_null(doc, song, "cover"); + } yyjson_mut_val* player = yyjson_mut_obj_add_obj(doc, obj, "player"); yyjson_mut_obj_add_strbuf(doc, player, "name", &media->player); @@ -156,13 +172,11 @@ bool ffGenerateMediaJsonResult(FF_MAYBE_UNUSED FFMediaOptions* options, yyjson_m return true; } -void ffInitMediaOptions(FFMediaOptions* options) -{ +void ffInitMediaOptions(FFMediaOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyMediaOptions(FFMediaOptions* options) -{ +void ffDestroyMediaOptions(FFMediaOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -181,5 +195,4 @@ FFModuleBaseInfo ffMediaModuleInfo = { {"Artist name", "artist"}, {"Album name", "album"}, {"Status", "status"}, - })) -}; + }))}; diff --git a/src/modules/media/option.h b/src/modules/media/option.h index e90ee854f..a8841f96e 100644 --- a/src/modules/media/option.h +++ b/src/modules/media/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFMediaOptions -{ +typedef struct FFMediaOptions { FFModuleArgs moduleArgs; } FFMediaOptions; diff --git a/src/modules/memory/memory.c b/src/modules/memory/memory.c index 7f86de480..7aed68060 100644 --- a/src/modules/memory/memory.c +++ b/src/modules/memory/memory.c @@ -6,13 +6,11 @@ #include "detection/memory/memory.h" #include "modules/memory/memory.h" -bool ffPrintMemory(FFMemoryOptions* options) -{ +bool ffPrintMemory(FFMemoryOptions* options) { FFMemoryResult storage = {}; const char* error = ffDetectMemory(&storage); - if(error) - { + if (error) { ffPrintError(FF_MEMORY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } @@ -28,81 +26,77 @@ bool ffPrintMemory(FFMemoryOptions* options) : (double) storage.bytesUsed / (double) storage.bytesTotal * 100.0; FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_MEMORY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (storage.bytesTotal == 0) + if (storage.bytesTotal == 0) { puts("Disabled"); - else - { + } else { FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&str, percentage, options->percent, &options->moduleArgs); ffStrbufAppendC(&str, ' '); } - if(!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppendF(&str, "%s / %s ", usedPretty.chars, totalPretty.chars); + } - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&str, percentage, options->percent, str.length > 0, &options->moduleArgs); + } ffStrbufTrimRight(&str, ' '); ffStrbufPutTo(&str, stdout); } - } - else - { + } else { FF_STRBUF_AUTO_DESTROY percentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&percentageNum, percentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY percentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&percentageBar, percentage, options->percent, &options->moduleArgs); + } - FF_PRINT_FORMAT_CHECKED(FF_MEMORY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(usedPretty, "used"), - FF_ARG(totalPretty, "total"), - FF_ARG(percentageNum, "percentage"), - FF_ARG(percentageBar, "percentage-bar"), - })); + FF_PRINT_FORMAT_CHECKED(FF_MEMORY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(usedPretty, "used"), + FF_ARG(totalPretty, "total"), + FF_ARG(percentageNum, "percentage"), + FF_ARG(percentageBar, "percentage-bar"), + })); } return true; } -void ffParseMemoryJsonObject(FFMemoryOptions* options, yyjson_val* module) -{ +void ffParseMemoryJsonObject(FFMemoryOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_MEMORY_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateMemoryJsonConfig(FFMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateMemoryJsonConfig(FFMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateMemoryJsonResult(FF_MAYBE_UNUSED FFMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateMemoryJsonResult(FF_MAYBE_UNUSED FFMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFMemoryResult storage = {}; const char* error = ffDetectMemory(&storage); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -114,14 +108,12 @@ bool ffGenerateMemoryJsonResult(FF_MAYBE_UNUSED FFMemoryOptions* options, yyjson return true; } -void ffInitMemoryOptions(FFMemoryOptions* options) -{ +void ffInitMemoryOptions(FFMemoryOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; } -void ffDestroyMemoryOptions(FFMemoryOptions* options) -{ +void ffDestroyMemoryOptions(FFMemoryOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -139,5 +131,4 @@ FFModuleBaseInfo ffMemoryModuleInfo = { {"Total size", "total"}, {"Percentage used (num)", "percentage"}, {"Percentage used (bar)", "percentage-bar"}, - })) -}; + }))}; diff --git a/src/modules/memory/option.h b/src/modules/memory/option.h index 243847f5f..e612a986b 100644 --- a/src/modules/memory/option.h +++ b/src/modules/memory/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFMemoryOptions -{ +typedef struct FFMemoryOptions { FFModuleArgs moduleArgs; FFPercentageModuleConfig percent; diff --git a/src/modules/modules.c b/src/modules/modules.c index cae08a06e..fe72923af 100644 --- a/src/modules/modules.c +++ b/src/modules/modules.c @@ -179,5 +179,30 @@ static FFModuleBaseInfo* Z[] = { }; FFModuleBaseInfo** ffModuleInfos[] = { - A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, }; diff --git a/src/modules/monitor/monitor.c b/src/modules/monitor/monitor.c index eaab1241b..1e8f431e5 100644 --- a/src/modules/monitor/monitor.c +++ b/src/modules/monitor/monitor.c @@ -6,79 +6,73 @@ #include -bool ffPrintMonitor(FFMonitorOptions* options) -{ +bool ffPrintMonitor(FFMonitorOptions* options) { const FFDisplayServerResult* result = ffConnectDisplayServer(); - if(!result->displays.length) - { + if (!result->displays.length) { ffPrintError(FF_MONITOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No display detected"); return false; } FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); uint32_t index = 0; - FF_LIST_FOR_EACH(FFDisplayResult, display, result->displays) - { + FF_LIST_FOR_EACH (FFDisplayResult, display, result->displays) { double inch = sqrt(display->physicalWidth * display->physicalWidth + display->physicalHeight * display->physicalHeight) / 25.4; double ppi = sqrt(display->width * display->width + display->height * display->height) / inch; bool hdrCompatible = display->hdrStatus == FF_DISPLAY_HDR_STATUS_SUPPORTED || display->hdrStatus == FF_DISPLAY_HDR_STATUS_ENABLED; ffStrbufClear(&key); - if(options->moduleArgs.key.length == 0) - { + if (options->moduleArgs.key.length == 0) { ffStrbufAppendS(&key, FF_MONITOR_MODULE_NAME); - if (display->name.length > 0) + if (display->name.length > 0) { ffStrbufAppendF(&key, " (%s)", display->name.chars); - } - else - { + } + } else { uint32_t moduleIndex = result->displays.length == 1 ? 0 : index + 1; FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(moduleIndex, "index"), - FF_ARG(display->name, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(moduleIndex, "index"), + FF_ARG(display->name, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); printf("%ux%u px", display->width, display->height); - if (display->refreshRate > 0) + if (display->refreshRate > 0) { printf(" @ %g Hz", ((int) (display->refreshRate * 1000 + 0.5)) / 1000.0); - if (inch > 0) + } + if (inch > 0) { printf(" - %ux%u mm (%.2f inches, %.2f ppi)", display->physicalWidth, display->physicalHeight, inch, ppi); - if (hdrCompatible) + } + if (hdrCompatible) { fputs(" [HDR Compatible]", stdout); + } putchar('\n'); - } - else - { + } else { char buf[32]; - if (display->serial) - { + if (display->serial) { const uint8_t* nums = (uint8_t*) &display->serial; snprintf(buf, sizeof(buf), "%2X-%2X-%2X-%2X", nums[0], nums[1], nums[2], nums[3]); - } - else + } else { buf[0] = '\0'; + } FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(display->name, "name"), - FF_ARG(display->width, "width"), - FF_ARG(display->height, "height"), - FF_ARG(display->physicalWidth, "physical-width"), - FF_ARG(display->physicalHeight, "physical-height"), - FF_ARG(inch, "inch"), - FF_ARG(ppi, "ppi"), - FF_ARG(display->manufactureYear, "manufacture-year"), - FF_ARG(display->manufactureWeek, "manufacture-week"), - FF_ARG(buf, "serial"), - FF_ARG(display->refreshRate, "refresh-rate"), - FF_ARG(hdrCompatible, "hdr-compatible"), - })); + FF_ARG(display->name, "name"), + FF_ARG(display->width, "width"), + FF_ARG(display->height, "height"), + FF_ARG(display->physicalWidth, "physical-width"), + FF_ARG(display->physicalHeight, "physical-height"), + FF_ARG(inch, "inch"), + FF_ARG(ppi, "ppi"), + FF_ARG(display->manufactureYear, "manufacture-year"), + FF_ARG(display->manufactureWeek, "manufacture-week"), + FF_ARG(buf, "serial"), + FF_ARG(display->refreshRate, "refresh-rate"), + FF_ARG(hdrCompatible, "hdr-compatible"), + })); } ffStrbufDestroy(&display->name); @@ -88,37 +82,32 @@ bool ffPrintMonitor(FFMonitorOptions* options) return true; } -void ffParseMonitorJsonObject(FFMonitorOptions* options, yyjson_val* module) -{ +void ffParseMonitorJsonObject(FFMonitorOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_MONITOR_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateMonitorJsonConfig(FFMonitorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateMonitorJsonConfig(FFMonitorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateMonitorJsonResult(FF_MAYBE_UNUSED FFMonitorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateMonitorJsonResult(FF_MAYBE_UNUSED FFMonitorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_obj_add_str(doc, module, "error", "Monitor module is an alias of Display module"); return false; } -void ffInitMonitorOptions(FFMonitorOptions* options) -{ +void ffInitMonitorOptions(FFMonitorOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰹑"); } -void ffDestroyMonitorOptions(FFMonitorOptions* options) -{ +void ffDestroyMonitorOptions(FFMonitorOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -144,5 +133,4 @@ FFModuleBaseInfo ffMonitorModuleInfo = { {"Serial number", "serial"}, {"Maximum refresh rate in Hz", "refresh-rate"}, {"True if the display is HDR compatible", "hdr-compatible"}, - })) -}; + }))}; diff --git a/src/modules/monitor/option.h b/src/modules/monitor/option.h index 07905ecba..46f485948 100644 --- a/src/modules/monitor/option.h +++ b/src/modules/monitor/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFMonitorOptions -{ +typedef struct FFMonitorOptions { FFModuleArgs moduleArgs; } FFMonitorOptions; diff --git a/src/modules/mouse/mouse.c b/src/modules/mouse/mouse.c index 10491ad92..9778d4e48 100644 --- a/src/modules/mouse/mouse.c +++ b/src/modules/mouse/mouse.c @@ -5,77 +5,61 @@ #include "detection/mouse/mouse.h" #include "modules/mouse/mouse.h" -static void printDevice(FFMouseOptions* options, const FFMouseDevice* device, uint8_t index) -{ - if(options->moduleArgs.outputFormat.length == 0) - { +static void printDevice(FFMouseOptions* options, const FFMouseDevice* device, uint8_t index) { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_MOUSE_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&device->name, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_MOUSE_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(device->name, "name"), - FF_ARG(device->serial, "serial"), - })); + FF_ARG(device->name, "name"), + FF_ARG(device->serial, "serial"), + })); } } -bool ffPrintMouse(FFMouseOptions* options) -{ +bool ffPrintMouse(FFMouseOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFMouseDevice)); const char* error = ffDetectMouse(&result); - if(error) - { + if (error) { ffPrintError(FF_MOUSE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(!result.length) - { + if (!result.length) { ffPrintError(FF_MOUSE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No devices detected"); return false; } FF_LIST_AUTO_DESTROY filtered = ffListCreate(sizeof(FFMouseDevice*)); - FF_LIST_FOR_EACH(FFMouseDevice, device, result) - { + FF_LIST_FOR_EACH (FFMouseDevice, device, result) { bool ignored = false; - FF_LIST_FOR_EACH(FFstrbuf, ignore, options->ignores) - { - if(ffStrbufStartsWithIgnCase(&device->name, ignore)) - { + FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) { + if (ffStrbufStartsWithIgnCase(&device->name, ignore)) { ignored = true; break; } } - if(!ignored) - { + if (!ignored) { FFMouseDevice** ptr = ffListAdd(&filtered); *ptr = device; } } bool ret = true; - if(!filtered.length) - { + if (!filtered.length) { ffPrintError(FF_MOUSE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "All devices are ignored"); ret = false; - } - else - { + } else { uint8_t index = 0; - FF_LIST_FOR_EACH(FFMouseDevice*, pdevice, filtered) - { + FF_LIST_FOR_EACH (FFMouseDevice*, pdevice, filtered) { FFMouseDevice* device = *pdevice; printDevice(options, device, filtered.length > 1 ? ++index : 0); } } - FF_LIST_FOR_EACH(FFMouseDevice, device, result) - { + FF_LIST_FOR_EACH (FFMouseDevice, device, result) { ffStrbufDestroy(&device->serial); ffStrbufDestroy(&device->name); } @@ -83,23 +67,19 @@ bool ffPrintMouse(FFMouseOptions* options) return ret; } -void ffParseMouseJsonObject(FFMouseOptions* options, yyjson_val* module) -{ +void ffParseMouseJsonObject(FFMouseOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "ignores")) - { - yyjson_val *elem; + if (unsafe_yyjson_equals_str(key, "ignores")) { + yyjson_val* elem; size_t eidx, emax; - yyjson_arr_foreach(val, eidx, emax, elem) - { - if (yyjson_is_str(elem)) - { + yyjson_arr_foreach (val, eidx, emax, elem) { + if (yyjson_is_str(elem)) { FFstrbuf* strbuf = ffListAdd(&options->ignores); ffStrbufInitJsonVal(strbuf, elem); } @@ -111,42 +91,36 @@ void ffParseMouseJsonObject(FFMouseOptions* options, yyjson_val* module) } } -void ffGenerateMouseJsonConfig(FFMouseOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateMouseJsonConfig(FFMouseOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - if (options->ignores.length > 0) - { + if (options->ignores.length > 0) { yyjson_mut_val* ignores = yyjson_mut_obj_add_arr(doc, module, "ignores"); - FF_LIST_FOR_EACH(FFstrbuf, strbuf, options->ignores) + FF_LIST_FOR_EACH (FFstrbuf, strbuf, options->ignores) { yyjson_mut_arr_append(ignores, yyjson_mut_strncpy(doc, strbuf->chars, strbuf->length)); + } } } -bool ffGenerateMouseJsonResult(FF_MAYBE_UNUSED FFMouseOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateMouseJsonResult(FF_MAYBE_UNUSED FFMouseOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFMouseDevice)); const char* error = ffDetectMouse(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFMouseDevice, device, result) - { + FF_LIST_FOR_EACH (FFMouseDevice, device, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "serial", &device->serial); yyjson_mut_obj_add_strbuf(doc, obj, "name", &device->name); bool ignored = false; - FF_LIST_FOR_EACH(FFstrbuf, ignore, options->ignores) - { - if(ffStrbufStartsWithIgnCase(&device->name, ignore)) - { + FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) { + if (ffStrbufStartsWithIgnCase(&device->name, ignore)) { ignored = true; break; } @@ -154,8 +128,7 @@ bool ffGenerateMouseJsonResult(FF_MAYBE_UNUSED FFMouseOptions* options, yyjson_m yyjson_mut_obj_add_bool(doc, obj, "ignored", ignored); } - FF_LIST_FOR_EACH(FFMouseDevice, device, result) - { + FF_LIST_FOR_EACH (FFMouseDevice, device, result) { ffStrbufDestroy(&device->serial); ffStrbufDestroy(&device->name); } @@ -163,19 +136,18 @@ bool ffGenerateMouseJsonResult(FF_MAYBE_UNUSED FFMouseOptions* options, yyjson_m return true; } -void ffInitMouseOptions(FFMouseOptions* options) -{ +void ffInitMouseOptions(FFMouseOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰍽"); ffListInit(&options->ignores, sizeof(FFstrbuf)); } -void ffDestroyMouseOptions(FFMouseOptions* options) -{ +void ffDestroyMouseOptions(FFMouseOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); - FF_LIST_FOR_EACH(FFstrbuf, str, options->ignores) + FF_LIST_FOR_EACH (FFstrbuf, str, options->ignores) { ffStrbufDestroy(str); + } ffListDestroy(&options->ignores); } @@ -191,5 +163,4 @@ FFModuleBaseInfo ffMouseModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Mouse name", "name"}, {"Mouse serial number", "serial"}, - })) -}; + }))}; diff --git a/src/modules/mouse/option.h b/src/modules/mouse/option.h index bea872c40..ec2c26ee3 100644 --- a/src/modules/mouse/option.h +++ b/src/modules/mouse/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/FFlist.h" -typedef struct FFMouseOptions -{ +typedef struct FFMouseOptions { FFModuleArgs moduleArgs; FFlist ignores; // List of FFstrbuf diff --git a/src/modules/netio/netio.c b/src/modules/netio/netio.c index 1b56abc63..33bcc7acf 100644 --- a/src/modules/netio/netio.c +++ b/src/modules/netio/netio.c @@ -7,38 +7,32 @@ #define FF_NETIO_DISPLAY_NAME "Network IO" -static int sortInfs(const FFNetIOResult* left, const FFNetIOResult* right) -{ +static int sortInfs(const FFNetIOResult* left, const FFNetIOResult* right) { return ffStrbufComp(&left->name, &right->name); } -static void formatKey(const FFNetIOOptions* options, FFNetIOResult* inf, uint32_t index, FFstrbuf* key) -{ - if(options->moduleArgs.key.length == 0) - { - if(!inf->name.length) +static void formatKey(const FFNetIOOptions* options, FFNetIOResult* inf, uint32_t index, FFstrbuf* key) { + if (options->moduleArgs.key.length == 0) { + if (!inf->name.length) { ffStrbufSetF(&inf->name, "unknown %u", (unsigned) index); + } ffStrbufSetF(key, FF_NETIO_DISPLAY_NAME " (%s)", inf->name.chars); - } - else - { + } else { ffStrbufClear(key); - FF_PARSE_FORMAT_STRING_CHECKED(key, &options->moduleArgs.key, ((FFformatarg[]){ - FF_ARG(index, "index"), - FF_ARG(inf->name, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_PARSE_FORMAT_STRING_CHECKED(key, &options->moduleArgs.key, ((FFformatarg[]) { + FF_ARG(index, "index"), + FF_ARG(inf->name, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } } -bool ffPrintNetIO(FFNetIOOptions* options) -{ +bool ffPrintNetIO(FFNetIOOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFNetIOResult)); const char* error = ffDetectNetIO(&result, options); - if(error) - { + if (error) { ffPrintError(FF_NETIO_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } @@ -50,90 +44,89 @@ bool ffPrintNetIO(FFNetIOOptions* options) FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY buffer2 = ffStrbufCreate(); - FF_LIST_FOR_EACH(FFNetIOResult, inf, result) - { + FF_LIST_FOR_EACH (FFNetIOResult, inf, result) { formatKey(options, inf, result.length == 1 ? 0 : index + 1, &key); ffStrbufClear(&buffer); - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffSizeAppendNum(inf->rxBytes, &buffer); - if (!options->detectTotal) ffStrbufAppendS(&buffer, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer, "/s"); + } ffStrbufAppendS(&buffer, " (IN) - "); ffSizeAppendNum(inf->txBytes, &buffer); - if (!options->detectTotal) ffStrbufAppendS(&buffer, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer, "/s"); + } ffStrbufAppendS(&buffer, " (OUT)"); - if (inf->defaultRoute && !options->defaultRouteOnly) + if (inf->defaultRoute && !options->defaultRouteOnly) { ffStrbufAppendS(&buffer, " *"); + } ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { ffStrbufClear(&buffer2); ffSizeAppendNum(inf->rxBytes, &buffer); - if (!options->detectTotal) ffStrbufAppendS(&buffer, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer, "/s"); + } ffSizeAppendNum(inf->txBytes, &buffer2); - if (!options->detectTotal) ffStrbufAppendS(&buffer2, "/s"); + if (!options->detectTotal) { + ffStrbufAppendS(&buffer2, "/s"); + } - FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]){ - FF_ARG(buffer, "rx-size"), - FF_ARG(buffer2, "tx-size"), - FF_ARG(inf->name, "ifname"), - FF_ARG(inf->defaultRoute, "is-default-route"), - FF_ARG(inf->txBytes, "tx-bytes"), - FF_ARG(inf->rxBytes, "rx-bytes"), - FF_ARG(inf->txPackets, "tx-packets"), - FF_ARG(inf->rxPackets, "rx-packets"), - FF_ARG(inf->rxErrors, "rx-errors"), - FF_ARG(inf->txErrors, "tx-errors"), - FF_ARG(inf->rxDrops, "rx-drops"), - FF_ARG(inf->txDrops, "tx-drops"), - })); + FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { + FF_ARG(buffer, "rx-size"), + FF_ARG(buffer2, "tx-size"), + FF_ARG(inf->name, "ifname"), + FF_ARG(inf->defaultRoute, "is-default-route"), + FF_ARG(inf->txBytes, "tx-bytes"), + FF_ARG(inf->rxBytes, "rx-bytes"), + FF_ARG(inf->txPackets, "tx-packets"), + FF_ARG(inf->rxPackets, "rx-packets"), + FF_ARG(inf->rxErrors, "rx-errors"), + FF_ARG(inf->txErrors, "tx-errors"), + FF_ARG(inf->rxDrops, "rx-drops"), + FF_ARG(inf->txDrops, "tx-drops"), + })); } ++index; } - FF_LIST_FOR_EACH(FFNetIOResult, inf, result) - { + FF_LIST_FOR_EACH (FFNetIOResult, inf, result) { ffStrbufDestroy(&inf->name); } return true; } -void ffParseNetIOJsonObject(FFNetIOOptions* options, yyjson_val* module) -{ +void ffParseNetIOJsonObject(FFNetIOOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "namePrefix")) - { + if (unsafe_yyjson_equals_str(key, "namePrefix")) { ffStrbufSetJsonVal(&options->namePrefix, val); continue; } - if (unsafe_yyjson_equals_str(key, "defaultRouteOnly")) - { + if (unsafe_yyjson_equals_str(key, "defaultRouteOnly")) { options->defaultRouteOnly = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "detectTotal")) - { + if (unsafe_yyjson_equals_str(key, "detectTotal")) { options->detectTotal = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "waitTime")) - { + if (unsafe_yyjson_equals_str(key, "waitTime")) { options->waitTime = (uint32_t) yyjson_get_uint(val); continue; } @@ -142,8 +135,7 @@ void ffParseNetIOJsonObject(FFNetIOOptions* options, yyjson_val* module) } } -void ffGenerateNetIOJsonConfig(FFNetIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateNetIOJsonConfig(FFNetIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_strbuf(doc, module, "namePrefix", &options->namePrefix); @@ -155,20 +147,17 @@ void ffGenerateNetIOJsonConfig(FFNetIOOptions* options, yyjson_mut_doc* doc, yyj yyjson_mut_obj_add_uint(doc, module, "waitTime", options->waitTime); } -bool ffGenerateNetIOJsonResult(FFNetIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateNetIOJsonResult(FFNetIOOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFNetIOResult)); const char* error = ffDetectNetIO(&result, options); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFNetIOResult, counter, result) - { + FF_LIST_FOR_EACH (FFNetIOResult, counter, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &counter->name); yyjson_mut_obj_add_bool(doc, obj, "defaultRoute", counter->defaultRoute); @@ -182,32 +171,29 @@ bool ffGenerateNetIOJsonResult(FFNetIOOptions* options, yyjson_mut_doc* doc, yyj yyjson_mut_obj_add_uint(doc, obj, "txDrops", counter->txDrops); } - FF_LIST_FOR_EACH(FFNetIOResult, inf, result) - { + FF_LIST_FOR_EACH (FFNetIOResult, inf, result) { ffStrbufDestroy(&inf->name); } return true; } -void ffInitNetIOOptions(FFNetIOOptions* options) -{ +void ffInitNetIOOptions(FFNetIOOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰾆"); ffStrbufInit(&options->namePrefix); options->defaultRouteOnly = - #if __ANDROID__ - false - #else - true - #endif - ; +#if __ANDROID__ + false +#else + true +#endif + ; options->detectTotal = false; options->waitTime = 1000; } -void ffDestroyNetIOOptions(FFNetIOOptions* options) -{ +void ffDestroyNetIOOptions(FFNetIOOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->namePrefix); } @@ -234,5 +220,4 @@ FFModuleBaseInfo ffNetIOModuleInfo = { {"Number of errors sent [per second]", "tx-errors"}, {"Number of packets dropped when receiving [per second]", "rx-drops"}, {"Number of packets dropped when sending [per second]", "tx-drops"}, - })) -}; + }))}; diff --git a/src/modules/netio/option.h b/src/modules/netio/option.h index 61ffa37d5..f5552c1a2 100644 --- a/src/modules/netio/option.h +++ b/src/modules/netio/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFNetIOOptions -{ +typedef struct FFNetIOOptions { FFModuleArgs moduleArgs; FFstrbuf namePrefix; diff --git a/src/modules/opencl/opencl.c b/src/modules/opencl/opencl.c index 7700d4d4f..088c0dc83 100644 --- a/src/modules/opencl/opencl.c +++ b/src/modules/opencl/opencl.c @@ -5,57 +5,48 @@ #include "detection/gpu/gpu.h" #include "modules/opencl/opencl.h" -bool ffPrintOpenCL(FFOpenCLOptions* options) -{ +bool ffPrintOpenCL(FFOpenCLOptions* options) { FFOpenCLResult* result = ffDetectOpenCL(); - if(result->error != NULL) - { + if (result->error != NULL) { ffPrintError(FF_OPENCL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", result->error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_OPENCL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&result->version, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_OPENCL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result->version, "version"), - FF_ARG(result->name, "name"), - FF_ARG(result->vendor, "vendor"), - })); + FF_ARG(result->version, "version"), + FF_ARG(result->name, "name"), + FF_ARG(result->vendor, "vendor"), + })); } return true; } -void ffParseOpenCLJsonObject(FFOpenCLOptions* options, yyjson_val* module) -{ +void ffParseOpenCLJsonObject(FFOpenCLOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_OPENCL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateOpenCLJsonConfig(FFOpenCLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateOpenCLJsonConfig(FFOpenCLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateOpenCLJsonResult(FF_MAYBE_UNUSED FFOpenCLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateOpenCLJsonResult(FF_MAYBE_UNUSED FFOpenCLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFOpenCLResult* result = ffDetectOpenCL(); - if(result->error != NULL) - { + if (result->error != NULL) { yyjson_mut_obj_add_str(doc, module, "error", result->error); return false; } @@ -66,18 +57,19 @@ bool ffGenerateOpenCLJsonResult(FF_MAYBE_UNUSED FFOpenCLOptions* options, yyjson yyjson_mut_obj_add_strbuf(doc, obj, "vendor", &result->vendor); yyjson_mut_val* gpus = yyjson_mut_obj_add_arr(doc, obj, "gpus"); - FF_LIST_FOR_EACH(FFGPUResult, gpu, result->gpus) - { + FF_LIST_FOR_EACH (FFGPUResult, gpu, result->gpus) { yyjson_mut_val* gpuObj = yyjson_mut_arr_add_obj(doc, gpus); - yyjson_mut_obj_add_str(doc, gpuObj, "type", gpu->type == FF_GPU_TYPE_UNKNOWN ? "Unknown" : gpu->type == FF_GPU_TYPE_INTEGRATED ? "Integrated" : "Discrete"); + yyjson_mut_obj_add_str(doc, gpuObj, "type", gpu->type == FF_GPU_TYPE_UNKNOWN ? "Unknown" : gpu->type == FF_GPU_TYPE_INTEGRATED ? "Integrated" + : "Discrete"); yyjson_mut_obj_add_strbuf(doc, gpuObj, "vendor", &gpu->vendor); yyjson_mut_obj_add_strbuf(doc, gpuObj, "name", &gpu->name); yyjson_mut_obj_add_strbuf(doc, gpuObj, "driver", &gpu->driver); yyjson_mut_obj_add_strbuf(doc, gpuObj, "platformApi", &gpu->platformApi); - if (gpu->coreCount != FF_GPU_CORE_COUNT_UNSET) + if (gpu->coreCount != FF_GPU_CORE_COUNT_UNSET) { yyjson_mut_obj_add_int(doc, gpuObj, "coreCount", gpu->coreCount); - else + } else { yyjson_mut_obj_add_null(doc, gpuObj, "coreCount"); + } yyjson_mut_obj_add_uint(doc, gpuObj, "frequency", gpu->frequency); @@ -85,28 +77,32 @@ bool ffGenerateOpenCLJsonResult(FF_MAYBE_UNUSED FFOpenCLOptions* options, yyjson { yyjson_mut_val* dedicatedMemory = yyjson_mut_obj_add_obj(doc, memoryObj, "dedicated"); - if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) + if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, dedicatedMemory, "total", gpu->dedicated.total); - else + } else { yyjson_mut_obj_add_null(doc, dedicatedMemory, "total"); + } - if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) + if (gpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, dedicatedMemory, "used", gpu->dedicated.total); - else + } else { yyjson_mut_obj_add_null(doc, dedicatedMemory, "used"); + } } { yyjson_mut_val* sharedMemory = yyjson_mut_obj_add_obj(doc, memoryObj, "shared"); - if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) + if (gpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, sharedMemory, "total", gpu->shared.total); - else + } else { yyjson_mut_obj_add_null(doc, sharedMemory, "total"); + } - if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) + if (gpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, sharedMemory, "used", gpu->shared.used); - else + } else { yyjson_mut_obj_add_null(doc, sharedMemory, "used"); + } } yyjson_mut_obj_add_uint(doc, gpuObj, "deviceId", gpu->deviceId); @@ -115,13 +111,11 @@ bool ffGenerateOpenCLJsonResult(FF_MAYBE_UNUSED FFOpenCLOptions* options, yyjson return true; } -void ffInitOpenCLOptions(FFOpenCLOptions* options) -{ +void ffInitOpenCLOptions(FFOpenCLOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyOpenCLOptions(FFOpenCLOptions* options) -{ +void ffDestroyOpenCLOptions(FFOpenCLOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -138,5 +132,4 @@ FFModuleBaseInfo ffOpenCLModuleInfo = { {"Platform version", "version"}, {"Platform name", "name"}, {"Platform vendor", "vendor"}, - })) -}; + }))}; diff --git a/src/modules/opencl/option.h b/src/modules/opencl/option.h index 2fd7dff26..aa624c652 100644 --- a/src/modules/opencl/option.h +++ b/src/modules/opencl/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFOpenCLOptions -{ +typedef struct FFOpenCLOptions { FFModuleArgs moduleArgs; } FFOpenCLOptions; diff --git a/src/modules/opengl/opengl.c b/src/modules/opengl/opengl.c index 9160e8f77..157d49d78 100644 --- a/src/modules/opengl/opengl.c +++ b/src/modules/opengl/opengl.c @@ -4,8 +4,7 @@ #include "detection/opengl/opengl.h" #include "modules/opengl/opengl.h" -bool ffPrintOpenGL(FFOpenGLOptions* options) -{ +bool ffPrintOpenGL(FFOpenGLOptions* options) { bool success = false; FFOpenGLResult result; ffStrbufInit(&result.version); @@ -15,26 +14,20 @@ bool ffPrintOpenGL(FFOpenGLOptions* options) ffStrbufInit(&result.library); const char* error = ffDetectOpenGL(options, &result); - if(error) - { + if (error) { ffPrintError(FF_OPENGL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); - } - else - { - if(options->moduleArgs.outputFormat.length == 0) - { + } else { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_OPENGL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); puts(result.version.chars); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_OPENGL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result.version, "version"), - FF_ARG(result.renderer, "renderer"), - FF_ARG(result.vendor, "vendor"), - FF_ARG(result.slv, "slv"), - FF_ARG(result.library, "library"), - })); + FF_ARG(result.version, "version"), + FF_ARG(result.renderer, "renderer"), + FF_ARG(result.vendor, "vendor"), + FF_ARG(result.slv, "slv"), + FF_ARG(result.library, "library"), + })); } success = true; } @@ -48,28 +41,27 @@ bool ffPrintOpenGL(FFOpenGLOptions* options) return success; } -void ffParseOpenGLJsonObject(FFOpenGLOptions* options, yyjson_val* module) -{ +void ffParseOpenGLJsonObject(FFOpenGLOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "library")) - { + if (unsafe_yyjson_equals_str(key, "library")) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "auto", FF_OPENGL_LIBRARY_AUTO }, - { "egl", FF_OPENGL_LIBRARY_EGL }, - { "glx", FF_OPENGL_LIBRARY_GLX }, - {}, - }); - if (error) + {"auto", FF_OPENGL_LIBRARY_AUTO}, + {"egl", FF_OPENGL_LIBRARY_EGL}, + {"glx", FF_OPENGL_LIBRARY_GLX}, + {}, + }); + if (error) { ffPrintError(FF_OPENGL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else + } else { options->library = (FFOpenGLLibrary) value; + } continue; } @@ -77,26 +69,23 @@ void ffParseOpenGLJsonObject(FFOpenGLOptions* options, yyjson_val* module) } } -void ffGenerateOpenGLJsonConfig(FFOpenGLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateOpenGLJsonConfig(FFOpenGLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - switch (options->library) - { - case FF_OPENGL_LIBRARY_AUTO: - yyjson_mut_obj_add_str(doc, module, "library", "auto"); - break; - case FF_OPENGL_LIBRARY_EGL: - yyjson_mut_obj_add_str(doc, module, "library", "egl"); - break; - case FF_OPENGL_LIBRARY_GLX: - yyjson_mut_obj_add_str(doc, module, "library", "glx"); - break; + switch (options->library) { + case FF_OPENGL_LIBRARY_AUTO: + yyjson_mut_obj_add_str(doc, module, "library", "auto"); + break; + case FF_OPENGL_LIBRARY_EGL: + yyjson_mut_obj_add_str(doc, module, "library", "egl"); + break; + case FF_OPENGL_LIBRARY_GLX: + yyjson_mut_obj_add_str(doc, module, "library", "glx"); + break; } } -bool ffGenerateOpenGLJsonResult(FF_MAYBE_UNUSED FFOpenGLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateOpenGLJsonResult(FF_MAYBE_UNUSED FFOpenGLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFOpenGLResult result; ffStrbufInit(&result.version); @@ -106,12 +95,9 @@ bool ffGenerateOpenGLJsonResult(FF_MAYBE_UNUSED FFOpenGLOptions* options, yyjson ffStrbufInit(&result.library); const char* error = ffDetectOpenGL(options, &result); - if(error != NULL) - { + if (error != NULL) { yyjson_mut_obj_add_str(doc, module, "error", error); - } - else - { + } else { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); yyjson_mut_obj_add_strbuf(doc, obj, "version", &result.version); yyjson_mut_obj_add_strbuf(doc, obj, "renderer", &result.renderer); @@ -130,15 +116,13 @@ bool ffGenerateOpenGLJsonResult(FF_MAYBE_UNUSED FFOpenGLOptions* options, yyjson return success; } -void ffInitOpenGLOptions(FFOpenGLOptions* options) -{ +void ffInitOpenGLOptions(FFOpenGLOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); options->library = FF_OPENGL_LIBRARY_AUTO; } -void ffDestroyOpenGLOptions(FFOpenGLOptions* options) -{ +void ffDestroyOpenGLOptions(FFOpenGLOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -157,5 +141,4 @@ FFModuleBaseInfo ffOpenGLModuleInfo = { {"OpenGL vendor", "vendor"}, {"OpenGL shading language version", "slv"}, {"OpenGL library used", "library"}, - })) -}; + }))}; diff --git a/src/modules/opengl/option.h b/src/modules/opengl/option.h index cc4b6ef46..e368d67ba 100644 --- a/src/modules/opengl/option.h +++ b/src/modules/opengl/option.h @@ -2,15 +2,13 @@ #include "common/option.h" -typedef enum __attribute__((__packed__)) FFOpenGLLibrary -{ +typedef enum __attribute__((__packed__)) FFOpenGLLibrary { FF_OPENGL_LIBRARY_AUTO, FF_OPENGL_LIBRARY_EGL, FF_OPENGL_LIBRARY_GLX, } FFOpenGLLibrary; -typedef struct FFOpenGLOptions -{ +typedef struct FFOpenGLOptions { FFModuleArgs moduleArgs; FFOpenGLLibrary library; diff --git a/src/modules/os/option.h b/src/modules/os/option.h index c7142b237..46c7a1b78 100644 --- a/src/modules/os/option.h +++ b/src/modules/os/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFOSOptions -{ +typedef struct FFOSOptions { FFModuleArgs moduleArgs; } FFOSOptions; diff --git a/src/modules/os/os.c b/src/modules/os/os.c index 09f2009c1..e948eac18 100644 --- a/src/modules/os/os.c +++ b/src/modules/os/os.c @@ -7,140 +7,123 @@ #include -static void buildOutputDefault(const FFOSResult* os, FFstrbuf* result) -{ - //Create the basic output - if(os->name.length > 0) +static void buildOutputDefault(const FFOSResult* os, FFstrbuf* result) { + // Create the basic output + if (os->name.length > 0) { ffStrbufAppend(result, &os->name); - else if(os->prettyName.length > 0) + } else if (os->prettyName.length > 0) { ffStrbufAppend(result, &os->prettyName); - else if(os->id.length > 0) + } else if (os->id.length > 0) { ffStrbufAppend(result, &os->id); - else + } else { ffStrbufAppend(result, &instance.state.platform.sysinfo.name); + } - //Append code name if it is missing - if(os->codename.length > 0 && !ffStrbufContainIgnCase(result, &os->codename)) - { + // Append code name if it is missing + if (os->codename.length > 0 && !ffStrbufContainIgnCase(result, &os->codename)) { ffStrbufAppendC(result, ' '); ffStrbufAppend(result, &os->codename); } - //Append version if it is missing - if(os->versionID.length > 0 && !ffStrbufContainIgnCase(result, &os->versionID)) - { + // Append version if it is missing + if (os->versionID.length > 0 && !ffStrbufContainIgnCase(result, &os->versionID)) { ffStrbufAppendC(result, ' '); ffStrbufAppend(result, &os->versionID); - } - else if(os->versionID.length == 0 && os->version.length > 0 && !ffStrbufContainIgnCase(result, &os->version)) - { + } else if (os->versionID.length == 0 && os->version.length > 0 && !ffStrbufContainIgnCase(result, &os->version)) { ffStrbufAppendC(result, ' '); ffStrbufAppend(result, &os->version); } - //Append variant if it is missing - if(os->variant.length > 0 && !ffStrbufContainIgnCase(result, &os->variant)) - { + // Append variant if it is missing + if (os->variant.length > 0 && !ffStrbufContainIgnCase(result, &os->variant)) { ffStrbufAppendS(result, " ("); ffStrbufAppend(result, &os->variant); ffStrbufAppendC(result, ')'); - } - else if(os->variant.length == 0 && os->variantID.length > 0 && !ffStrbufContainIgnCase(result, &os->variantID)) - { + } else if (os->variant.length == 0 && os->variantID.length > 0 && !ffStrbufContainIgnCase(result, &os->variantID)) { ffStrbufAppendS(result, " ("); ffStrbufAppend(result, &os->variantID); ffStrbufAppendC(result, ')'); } } -bool ffPrintOS(FFOSOptions* options) -{ +bool ffPrintOS(FFOSOptions* options) { const FFOSResult* os = ffDetectOS(); - if(os->name.length == 0 && os->prettyName.length == 0 && os->id.length == 0) - { + if (os->name.length == 0 && os->prettyName.length == 0 && os->id.length == 0) { ffPrintError(FF_OS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Could not detect OS"); return false; } FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); - if(options->moduleArgs.key.length == 0) + if (options->moduleArgs.key.length == 0) { ffStrbufSetStatic(&key, FF_OS_MODULE_NAME); - else - { + } else { FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(instance.state.platform.sysinfo.name, "sysname"), - FF_ARG(os->name, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(instance.state.platform.sysinfo.name, "sysname"), + FF_ARG(os->name, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); - if(os->prettyName.length > 0) + if (os->prettyName.length > 0) { ffStrbufAppend(&result, &os->prettyName); - else + } else { buildOutputDefault(os, &result); + } - //Append architecture if it is missing - if(!ffStrbufContainIgnCase(&result, &instance.state.platform.sysinfo.architecture)) - { + // Append architecture if it is missing + if (!ffStrbufContainIgnCase(&result, &instance.state.platform.sysinfo.architecture)) { ffStrbufAppendC(&result, ' '); ffStrbufAppend(&result, &instance.state.platform.sysinfo.architecture); } ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffStrbufPutTo(&result, stdout); - } - else - { - FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]){ - FF_ARG(instance.state.platform.sysinfo.name, "sysname"), - FF_ARG(os->name, "name"), - FF_ARG(os->prettyName, "pretty-name"), - FF_ARG(os->id, "id"), - FF_ARG(os->idLike, "id-like"), - FF_ARG(os->variant, "variant"), - FF_ARG(os->variantID, "variant-id"), - FF_ARG(os->version, "version"), - FF_ARG(os->versionID, "version-id"), - FF_ARG(os->codename, "codename"), - FF_ARG(os->buildID, "build-id"), - FF_ARG(instance.state.platform.sysinfo.architecture, "arch"), - FF_ARG(instance.state.platform.sysinfo.release, "kernel-release"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { + FF_ARG(instance.state.platform.sysinfo.name, "sysname"), + FF_ARG(os->name, "name"), + FF_ARG(os->prettyName, "pretty-name"), + FF_ARG(os->id, "id"), + FF_ARG(os->idLike, "id-like"), + FF_ARG(os->variant, "variant"), + FF_ARG(os->variantID, "variant-id"), + FF_ARG(os->version, "version"), + FF_ARG(os->versionID, "version-id"), + FF_ARG(os->codename, "codename"), + FF_ARG(os->buildID, "build-id"), + FF_ARG(instance.state.platform.sysinfo.architecture, "arch"), + FF_ARG(instance.state.platform.sysinfo.release, "kernel-release"), + })); } return true; } -void ffParseOSJsonObject(FFOSOptions* options, yyjson_val* module) -{ +void ffParseOSJsonObject(FFOSOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_OS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateOSJsonConfig(FFOSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateOSJsonConfig(FFOSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateOSJsonResult(FF_MAYBE_UNUSED FFOSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateOSJsonResult(FF_MAYBE_UNUSED FFOSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFOSResult* os = ffDetectOS(); - if(os->name.length == 0 && os->prettyName.length == 0 && os->id.length == 0) - { + if (os->name.length == 0 && os->prettyName.length == 0 && os->id.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "Could not detect OS"); return false; } @@ -160,33 +143,31 @@ bool ffGenerateOSJsonResult(FF_MAYBE_UNUSED FFOSOptions* options, yyjson_mut_doc return true; } -void ffInitOSOptions(FFOSOptions* options) -{ +void ffInitOSOptions(FFOSOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, - #ifdef _WIN32 - "" - #elif __APPLE__ - "" - #elif __FreeBSD__ - "󰣠" - #elif __ANDROID__ - "" - #elif __linux__ - "" - #elif __sun - "" - #elif __OpenBSD__ - "" - #elif __Haiku__ - "" - #else - "󰢻" - #endif +#ifdef _WIN32 + "" +#elif __APPLE__ + "" +#elif __FreeBSD__ + "󰣠" +#elif __ANDROID__ + "" +#elif __linux__ + "" +#elif __sun + "" +#elif __OpenBSD__ + "" +#elif __Haiku__ + "" +#else + "󰢻" +#endif ); } -void ffDestroyOSOptions(FFOSOptions* options) -{ +void ffDestroyOSOptions(FFOSOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -212,5 +193,4 @@ FFModuleBaseInfo ffOSModuleInfo = { {"Version codename of the OS", "codename"}, {"Build ID of the OS", "build-id"}, {"Architecture of the OS", "arch"}, - })) -}; + }))}; diff --git a/src/modules/packages/option.h b/src/modules/packages/option.h index 45c049710..212ff84e2 100644 --- a/src/modules/packages/option.h +++ b/src/modules/packages/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef enum __attribute__((__packed__)) FFPackagesFlags -{ +typedef enum __attribute__((__packed__)) FFPackagesFlags { FF_PACKAGES_FLAG_NONE = 0, FF_PACKAGES_FLAG_APK_BIT = 1ULL << 0, FF_PACKAGES_FLAG_BREW_BIT = 1ULL << 1, @@ -42,8 +41,7 @@ typedef enum __attribute__((__packed__)) FFPackagesFlags } FFPackagesFlags; static_assert(sizeof(FFPackagesFlags) == sizeof(uint64_t), ""); -typedef struct FFPackagesOptions -{ +typedef struct FFPackagesOptions { FFModuleArgs moduleArgs; FFPackagesFlags disabled; diff --git a/src/modules/packages/packages.c b/src/modules/packages/packages.c index 6552d53d0..8d414cb34 100644 --- a/src/modules/packages/packages.c +++ b/src/modules/packages/packages.c @@ -4,15 +4,13 @@ #include "detection/packages/packages.h" #include "modules/packages/packages.h" -bool ffPrintPackages(FFPackagesOptions* options) -{ +bool ffPrintPackages(FFPackagesOptions* options) { FFPackagesResult counts = {}; ffStrbufInit(&counts.pacmanBranch); const char* error = ffDetectPackages(&counts, options); - if(error) - { + if (error) { ffPrintError(FF_PACKAGES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } @@ -25,50 +23,47 @@ bool ffPrintPackages(FFPackagesOptions* options) uint32_t amAll = counts.amSystem + counts.amUser; uint32_t scoopAll = counts.scoopUser + counts.scoopGlobal; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_PACKAGES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - #define FF_PRINT_PACKAGE_NAME(var, name) {\ - if(counts.var > 0) \ - { \ - printf("%u (%s)", counts.var, (name)); \ - if((all -= counts.var) > 0) \ - fputs(", ", stdout); \ - } \ - } +#define FF_PRINT_PACKAGE_NAME(var, name) \ + { \ + if (counts.var > 0) { \ + printf("%u (%s)", counts.var, (name)); \ + if ((all -= counts.var) > 0) \ + fputs(", ", stdout); \ + } \ + } - #define FF_PRINT_PACKAGE(name) FF_PRINT_PACKAGE_NAME(name, #name) +#define FF_PRINT_PACKAGE(name) FF_PRINT_PACKAGE_NAME(name, #name) - #define FF_PRINT_PACKAGE_ALL(name) {\ - if(name ## All > 0) \ - { \ - printf("%u (%s)", name ## All, #name); \ - if((all -= name ## All) > 0) \ - fputs(", ", stdout); \ - } \ - } +#define FF_PRINT_PACKAGE_ALL(name) \ + { \ + if (name##All > 0) { \ + printf("%u (%s)", name##All, #name); \ + if ((all -= name##All) > 0) \ + fputs(", ", stdout); \ + } \ + } uint32_t all = counts.all; - if(counts.pacman > 0) - { + if (counts.pacman > 0) { printf("%u (pacman)", counts.pacman); - if(counts.pacmanBranch.length > 0) + if (counts.pacmanBranch.length > 0) { printf("[%s]", counts.pacmanBranch.chars); - if((all -= counts.pacman) > 0) + } + if ((all -= counts.pacman) > 0) { printf(", "); + } }; FF_PRINT_PACKAGE(dpkg) FF_PRINT_PACKAGE(rpm) FF_PRINT_PACKAGE(emerge) FF_PRINT_PACKAGE(eopkg) FF_PRINT_PACKAGE(xbps) - if (options->combined) - { + if (options->combined) { FF_PRINT_PACKAGE_ALL(nix); - } - else - { + } else { FF_PRINT_PACKAGE_NAME(nixSystem, "nix-system") FF_PRINT_PACKAGE_NAME(nixUser, "nix-user") FF_PRINT_PACKAGE_NAME(nixDefault, "nix-default") @@ -77,41 +72,29 @@ bool ffPrintPackages(FFPackagesOptions* options) FF_PRINT_PACKAGE(pkg) FF_PRINT_PACKAGE(pkgsrc) FF_PRINT_PACKAGE(kiss) - if (options->combined) - { + if (options->combined) { FF_PRINT_PACKAGE_ALL(hpkg) - } - else - { + } else { FF_PRINT_PACKAGE_NAME(hpkgSystem, counts.hpkgUser ? "hpkg-system" : "hpkg") FF_PRINT_PACKAGE_NAME(hpkgUser, "hpkg-user") } - if (options->combined) - { + if (options->combined) { FF_PRINT_PACKAGE_ALL(flatpak); - } - else - { + } else { FF_PRINT_PACKAGE_NAME(flatpakSystem, counts.flatpakUser ? "flatpak-system" : "flatpak") FF_PRINT_PACKAGE_NAME(flatpakUser, "flatpak-user") } FF_PRINT_PACKAGE(snap) - if (options->combined) - { + if (options->combined) { FF_PRINT_PACKAGE_ALL(brew); - } - else - { + } else { FF_PRINT_PACKAGE_NAME(brew, "brew") FF_PRINT_PACKAGE_NAME(brewCask, "brew-cask") } FF_PRINT_PACKAGE(macports) - if (options->combined) - { + if (options->combined) { FF_PRINT_PACKAGE_ALL(scoop); - } - else - { + } else { FF_PRINT_PACKAGE_NAME(scoopUser, counts.scoopGlobal ? "scoop-user" : "scoop") FF_PRINT_PACKAGE_NAME(scoopGlobal, "scoop-global") } @@ -120,24 +103,18 @@ bool ffPrintPackages(FFPackagesOptions* options) FF_PRINT_PACKAGE(paludis) FF_PRINT_PACKAGE(winget) FF_PRINT_PACKAGE(opkg) - if (options->combined) - { + if (options->combined) { FF_PRINT_PACKAGE_ALL(am); - } - else - { + } else { FF_PRINT_PACKAGE_NAME(amSystem, "am") FF_PRINT_PACKAGE_NAME(amUser, "appman") } FF_PRINT_PACKAGE(sorcery) FF_PRINT_PACKAGE(lpkg) FF_PRINT_PACKAGE(lpkgbuild) - if (options->combined) - { + if (options->combined) { FF_PRINT_PACKAGE_ALL(guix); - } - else - { + } else { FF_PRINT_PACKAGE_NAME(guixSystem, "guix-system") FF_PRINT_PACKAGE_NAME(guixUser, "guix-user") FF_PRINT_PACKAGE_NAME(guixHome, "guix-home") @@ -150,60 +127,58 @@ bool ffPrintPackages(FFPackagesOptions* options) FF_PRINT_PACKAGE(moss) putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_PACKAGES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(counts.all, "all"), - FF_ARG(counts.pacman, "pacman"), - FF_ARG(counts.pacmanBranch, "pacman-branch"), - FF_ARG(counts.dpkg, "dpkg"), - FF_ARG(counts.rpm, "rpm"), - FF_ARG(counts.emerge, "emerge"), - FF_ARG(counts.eopkg, "eopkg"), - FF_ARG(counts.xbps, "xbps"), - FF_ARG(counts.nixSystem, "nix-system"), - FF_ARG(counts.nixUser, "nix-user"), - FF_ARG(counts.nixDefault, "nix-default"), - FF_ARG(counts.apk, "apk"), - FF_ARG(counts.pkg, "pkg"), - FF_ARG(counts.flatpakSystem, "flatpak-system"), - FF_ARG(counts.flatpakUser, "flatpak-user"), - FF_ARG(counts.snap, "snap"), - FF_ARG(counts.brew, "brew"), - FF_ARG(counts.brewCask, "brew-cask"), - FF_ARG(counts.macports, "macports"), - FF_ARG(counts.scoopUser, "scoop-user"), - FF_ARG(counts.scoopGlobal, "scoop-global"), - FF_ARG(counts.choco, "choco"), - FF_ARG(counts.pkgtool, "pkgtool"), - FF_ARG(counts.paludis, "paludis"), - FF_ARG(counts.winget, "winget"), - FF_ARG(counts.opkg, "opkg"), - FF_ARG(counts.amSystem, "am-system"), - FF_ARG(counts.sorcery, "sorcery"), - FF_ARG(counts.lpkg, "lpkg"), - FF_ARG(counts.lpkgbuild, "lpkgbuild"), - FF_ARG(counts.guixSystem, "guix-system"), - FF_ARG(counts.guixUser, "guix-user"), - FF_ARG(counts.guixHome, "guix-home"), - FF_ARG(counts.linglong, "linglong"), - FF_ARG(counts.pacstall, "pacstall"), - FF_ARG(counts.mport, "mport"), - FF_ARG(counts.amUser, "am-user"), - FF_ARG(counts.pkgsrc, "pkgsrc"), - FF_ARG(counts.hpkgSystem, "hpkg-system"), - FF_ARG(counts.hpkgUser, "hpkg-user"), - FF_ARG(counts.pisi, "pisi"), - FF_ARG(counts.soar, "soar"), - FF_ARG(counts.kiss, "kiss"), - FF_ARG(counts.moss, "moss"), - FF_ARG(nixAll, "nix-all"), - FF_ARG(flatpakAll, "flatpak-all"), - FF_ARG(brewAll, "brew-all"), - FF_ARG(guixAll, "guix-all"), - FF_ARG(hpkgAll, "hpkg-all"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_PACKAGES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(counts.all, "all"), + FF_ARG(counts.pacman, "pacman"), + FF_ARG(counts.pacmanBranch, "pacman-branch"), + FF_ARG(counts.dpkg, "dpkg"), + FF_ARG(counts.rpm, "rpm"), + FF_ARG(counts.emerge, "emerge"), + FF_ARG(counts.eopkg, "eopkg"), + FF_ARG(counts.xbps, "xbps"), + FF_ARG(counts.nixSystem, "nix-system"), + FF_ARG(counts.nixUser, "nix-user"), + FF_ARG(counts.nixDefault, "nix-default"), + FF_ARG(counts.apk, "apk"), + FF_ARG(counts.pkg, "pkg"), + FF_ARG(counts.flatpakSystem, "flatpak-system"), + FF_ARG(counts.flatpakUser, "flatpak-user"), + FF_ARG(counts.snap, "snap"), + FF_ARG(counts.brew, "brew"), + FF_ARG(counts.brewCask, "brew-cask"), + FF_ARG(counts.macports, "macports"), + FF_ARG(counts.scoopUser, "scoop-user"), + FF_ARG(counts.scoopGlobal, "scoop-global"), + FF_ARG(counts.choco, "choco"), + FF_ARG(counts.pkgtool, "pkgtool"), + FF_ARG(counts.paludis, "paludis"), + FF_ARG(counts.winget, "winget"), + FF_ARG(counts.opkg, "opkg"), + FF_ARG(counts.amSystem, "am-system"), + FF_ARG(counts.sorcery, "sorcery"), + FF_ARG(counts.lpkg, "lpkg"), + FF_ARG(counts.lpkgbuild, "lpkgbuild"), + FF_ARG(counts.guixSystem, "guix-system"), + FF_ARG(counts.guixUser, "guix-user"), + FF_ARG(counts.guixHome, "guix-home"), + FF_ARG(counts.linglong, "linglong"), + FF_ARG(counts.pacstall, "pacstall"), + FF_ARG(counts.mport, "mport"), + FF_ARG(counts.amUser, "am-user"), + FF_ARG(counts.pkgsrc, "pkgsrc"), + FF_ARG(counts.hpkgSystem, "hpkg-system"), + FF_ARG(counts.hpkgUser, "hpkg-user"), + FF_ARG(counts.pisi, "pisi"), + FF_ARG(counts.soar, "soar"), + FF_ARG(counts.kiss, "kiss"), + FF_ARG(counts.moss, "moss"), + FF_ARG(nixAll, "nix-all"), + FF_ARG(flatpakAll, "flatpak-all"), + FF_ARG(brewAll, "brew-all"), + FF_ARG(guixAll, "guix-all"), + FF_ARG(hpkgAll, "hpkg-all"), + })); } ffStrbufDestroy(&counts.pacmanBranch); @@ -211,87 +186,111 @@ bool ffPrintPackages(FFPackagesOptions* options) return true; } -void ffParsePackagesJsonObject(FFPackagesOptions* options, yyjson_val* module) -{ +void ffParsePackagesJsonObject(FFPackagesOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "disabled")) - { - if (!yyjson_is_null(val) && !yyjson_is_arr(val)) - { + if (unsafe_yyjson_equals_str(key, "disabled")) { + if (!yyjson_is_null(val) && !yyjson_is_arr(val)) { ffPrintError(FF_PACKAGES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid JSON value for %s", unsafe_yyjson_get_str(key)); continue; } options->disabled = FF_PACKAGES_FLAG_NONE; - if (yyjson_is_arr(val)) - { + if (yyjson_is_arr(val)) { yyjson_val* flagObj; size_t flagIdx, flagMax; - yyjson_arr_foreach(val, flagIdx, flagMax, flagObj) - { - if (!yyjson_is_str(flagObj)) - { + yyjson_arr_foreach (val, flagIdx, flagMax, flagObj) { + if (!yyjson_is_str(flagObj)) { ffPrintError(FF_PACKAGES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid JSON value for %s", unsafe_yyjson_get_str(key)); continue; } const char* flag = unsafe_yyjson_get_str(flagObj); - #define FF_TEST_PACKAGE_NAME(name) else if (ffStrEqualsIgnCase(flag, #name)) { options->disabled |= FF_PACKAGES_FLAG_ ## name ## _BIT; } - switch (toupper(flag[0])) - { - case 'A': if (false); +#define FF_TEST_PACKAGE_NAME(name) \ + else if (ffStrEqualsIgnCase(flag, #name)) { \ + options->disabled |= FF_PACKAGES_FLAG_##name##_BIT; \ + } + switch (toupper(flag[0])) { + case 'A': + if (false) + ; FF_TEST_PACKAGE_NAME(APK) FF_TEST_PACKAGE_NAME(AM) break; - case 'B': if (false); + case 'B': + if (false) + ; FF_TEST_PACKAGE_NAME(BREW) break; - case 'C': if (false); + case 'C': + if (false) + ; FF_TEST_PACKAGE_NAME(CHOCO) break; - case 'D': if (false); + case 'D': + if (false) + ; FF_TEST_PACKAGE_NAME(DPKG) break; - case 'E': if (false); + case 'E': + if (false) + ; FF_TEST_PACKAGE_NAME(EMERGE) FF_TEST_PACKAGE_NAME(EOPKG) break; - case 'F': if (false); + case 'F': + if (false) + ; FF_TEST_PACKAGE_NAME(FLATPAK) break; - case 'G': if (false); + case 'G': + if (false) + ; FF_TEST_PACKAGE_NAME(GUIX) break; - case 'H': if (false); + case 'H': + if (false) + ; FF_TEST_PACKAGE_NAME(HPKG) break; - case 'K': if (false); + case 'K': + if (false) + ; FF_TEST_PACKAGE_NAME(KISS) break; - case 'L': if (false); + case 'L': + if (false) + ; FF_TEST_PACKAGE_NAME(LPKG) FF_TEST_PACKAGE_NAME(LPKGBUILD) FF_TEST_PACKAGE_NAME(LINGLONG) break; - case 'M': if (false); + case 'M': + if (false) + ; FF_TEST_PACKAGE_NAME(MACPORTS) FF_TEST_PACKAGE_NAME(MPORT) FF_TEST_PACKAGE_NAME(MOSS) break; - case 'N': if (false); + case 'N': + if (false) + ; FF_TEST_PACKAGE_NAME(NIX) break; - case 'O': if (false); + case 'O': + if (false) + ; FF_TEST_PACKAGE_NAME(OPKG) break; - case 'P': if (false); + case 'P': + if (false) + ; FF_TEST_PACKAGE_NAME(PACMAN) FF_TEST_PACKAGE_NAME(PACSTALL) FF_TEST_PACKAGE_NAME(PALUDIS) @@ -300,30 +299,37 @@ void ffParsePackagesJsonObject(FFPackagesOptions* options, yyjson_val* module) FF_TEST_PACKAGE_NAME(PKGTOOL) FF_TEST_PACKAGE_NAME(PKGSRC) break; - case 'R': if (false); + case 'R': + if (false) + ; FF_TEST_PACKAGE_NAME(RPM) break; - case 'S': if (false); + case 'S': + if (false) + ; FF_TEST_PACKAGE_NAME(SCOOP) FF_TEST_PACKAGE_NAME(SNAP) FF_TEST_PACKAGE_NAME(SOAR) FF_TEST_PACKAGE_NAME(SORCERY) break; - case 'W': if (false); + case 'W': + if (false) + ; FF_TEST_PACKAGE_NAME(WINGET) break; - case 'X': if (false); + case 'X': + if (false) + ; FF_TEST_PACKAGE_NAME(XBPS) break; } - #undef FF_TEST_PACKAGE_NAME +#undef FF_TEST_PACKAGE_NAME } continue; } } - if (unsafe_yyjson_equals_str(key, "combined")) - { + if (unsafe_yyjson_equals_str(key, "combined")) { options->combined = yyjson_get_bool(val); continue; } @@ -332,18 +338,19 @@ void ffParsePackagesJsonObject(FFPackagesOptions* options, yyjson_val* module) } } -void ffGeneratePackagesJsonConfig(FFPackagesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGeneratePackagesJsonConfig(FFPackagesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "disabled"); - #define FF_TEST_PACKAGE_NAME(name) else if ((options->disabled & FF_PACKAGES_FLAG_ ## name ## _BIT)) { \ - ffStrbufSetS(&buf, #name); \ - ffStrbufLowerCase(&buf); \ - yyjson_mut_arr_add_strbuf(doc, arr, &buf); \ +#define FF_TEST_PACKAGE_NAME(name) \ + else if ((options->disabled & FF_PACKAGES_FLAG_##name##_BIT)) { \ + ffStrbufSetS(&buf, #name); \ + ffStrbufLowerCase(&buf); \ + yyjson_mut_arr_add_strbuf(doc, arr, &buf); \ } - if (false); + if (false) + ; FF_TEST_PACKAGE_NAME(AM) FF_TEST_PACKAGE_NAME(APK) FF_TEST_PACKAGE_NAME(BREW) @@ -377,27 +384,25 @@ void ffGeneratePackagesJsonConfig(FFPackagesOptions* options, yyjson_mut_doc* do FF_TEST_PACKAGE_NAME(SORCERY) FF_TEST_PACKAGE_NAME(WINGET) FF_TEST_PACKAGE_NAME(XBPS) - #undef FF_TEST_PACKAGE_NAME +#undef FF_TEST_PACKAGE_NAME yyjson_mut_obj_add_bool(doc, module, "combined", options->combined); } -bool ffGeneratePackagesJsonResult(FF_MAYBE_UNUSED FFPackagesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGeneratePackagesJsonResult(FF_MAYBE_UNUSED FFPackagesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFPackagesResult counts = {}; ffStrbufInit(&counts.pacmanBranch); const char* error = ffDetectPackages(&counts, options); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); - #define FF_APPEND_PACKAGE_COUNT(name) yyjson_mut_obj_add_uint(doc, obj, #name, counts.name); +#define FF_APPEND_PACKAGE_COUNT(name) yyjson_mut_obj_add_uint(doc, obj, #name, counts.name); FF_APPEND_PACKAGE_COUNT(all) FF_APPEND_PACKAGE_COUNT(amSystem) @@ -445,16 +450,14 @@ bool ffGeneratePackagesJsonResult(FF_MAYBE_UNUSED FFPackagesOptions* options, yy return true; } -void ffInitPackagesOptions(FFPackagesOptions* options) -{ +void ffInitPackagesOptions(FFPackagesOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰏖"); options->disabled = FF_PACKAGES_DISABLE_LIST; options->combined = false; } -void ffDestroyPackagesOptions(FFPackagesOptions* options) -{ +void ffDestroyPackagesOptions(FFPackagesOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -517,5 +520,4 @@ FFModuleBaseInfo ffPackagesModuleInfo = { {"Total number of all brew packages", "brew-all"}, {"Total number of all guix packages", "guix-all"}, {"Total number of all hpkg packages", "hpkg-all"}, - })) -}; + }))}; diff --git a/src/modules/physicaldisk/option.h b/src/modules/physicaldisk/option.h index 3951f0610..c4421c998 100644 --- a/src/modules/physicaldisk/option.h +++ b/src/modules/physicaldisk/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFPhysicalDiskOptions -{ +typedef struct FFPhysicalDiskOptions { FFModuleArgs moduleArgs; FFstrbuf namePrefix; diff --git a/src/modules/physicaldisk/physicaldisk.c b/src/modules/physicaldisk/physicaldisk.c index 1980842ba..e5964ea68 100644 --- a/src/modules/physicaldisk/physicaldisk.c +++ b/src/modules/physicaldisk/physicaldisk.c @@ -8,36 +8,29 @@ #define FF_PHYSICALDISK_DISPLAY_NAME "Physical Disk" -static int sortDevices(const FFPhysicalDiskResult* left, const FFPhysicalDiskResult* right) -{ +static int sortDevices(const FFPhysicalDiskResult* left, const FFPhysicalDiskResult* right) { return ffStrbufComp(&left->name, &right->name); } -static void formatKey(const FFPhysicalDiskOptions* options, FFPhysicalDiskResult* dev, uint32_t index, FFstrbuf* key) -{ - if(options->moduleArgs.key.length == 0) - { +static void formatKey(const FFPhysicalDiskOptions* options, FFPhysicalDiskResult* dev, uint32_t index, FFstrbuf* key) { + if (options->moduleArgs.key.length == 0) { ffStrbufSetF(key, FF_PHYSICALDISK_DISPLAY_NAME " (%s)", dev->name.length ? dev->name.chars : dev->devPath.chars); - } - else - { + } else { ffStrbufClear(key); - FF_PARSE_FORMAT_STRING_CHECKED(key, &options->moduleArgs.key, ((FFformatarg[]){ - FF_ARG(index, "index"), - FF_ARG(dev->name, "name"), - FF_ARG(dev->devPath, "dev-path"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_PARSE_FORMAT_STRING_CHECKED(key, &options->moduleArgs.key, ((FFformatarg[]) { + FF_ARG(index, "index"), + FF_ARG(dev->name, "name"), + FF_ARG(dev->devPath, "dev-path"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } } -bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) -{ +bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFPhysicalDiskResult)); const char* error = ffDetectPhysicalDisk(&result, options); - if(error) - { + if (error) { ffPrintError(FF_PHYSICALDISK_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } @@ -48,8 +41,7 @@ bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - FF_LIST_FOR_EACH(FFPhysicalDiskResult, dev, result) - { + FF_LIST_FOR_EACH (FFPhysicalDiskResult, dev, result) { formatKey(options, dev, result.length == 1 ? 0 : index + 1, &key); ffStrbufClear(&buffer); ffSizeAppendNum(dev->size, &buffer); @@ -57,74 +49,71 @@ bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) const char* physicalType = dev->type & FF_PHYSICALDISK_TYPE_HDD ? "HDD" : dev->type & FF_PHYSICALDISK_TYPE_SSD - ? "SSD" - : ""; + ? "SSD" + : ""; const char* removableType = dev->type & FF_PHYSICALDISK_TYPE_REMOVABLE ? "Removable" : dev->type & FF_PHYSICALDISK_TYPE_FIXED - ? "Fixed" - : ""; + ? "Fixed" + : ""; const char* readOnlyType = dev->type & FF_PHYSICALDISK_TYPE_READONLY ? "Read-only" : ""; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); - if (physicalType[0] || removableType[0] || readOnlyType[0]) - { + if (physicalType[0] || removableType[0] || readOnlyType[0]) { ffStrbufAppendS(&buffer, " ["); - if (physicalType[0]) + if (physicalType[0]) { ffStrbufAppendS(&buffer, physicalType); - if (removableType[0]) - { - if (buffer.chars[buffer.length - 1] != '[') + } + if (removableType[0]) { + if (buffer.chars[buffer.length - 1] != '[') { ffStrbufAppendS(&buffer, ", "); + } ffStrbufAppendS(&buffer, removableType); } - if (readOnlyType[0]) - { - if (buffer.chars[buffer.length - 1] != '[') + if (readOnlyType[0]) { + if (buffer.chars[buffer.length - 1] != '[') { ffStrbufAppendS(&buffer, ", "); + } ffStrbufAppendS(&buffer, readOnlyType); } ffStrbufAppendC(&buffer, ']'); } - if (dev->temperature != FF_PHYSICALDISK_TEMP_UNSET) - { - if(buffer.length > 0) + if (dev->temperature != FF_PHYSICALDISK_TEMP_UNSET) { + if (buffer.length > 0) { ffStrbufAppendS(&buffer, " - "); + } ffTempsAppendNum(dev->temperature, &buffer, options->tempConfig, &options->moduleArgs); } ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY tempStr = ffStrbufCreate(); ffTempsAppendNum(dev->temperature, &tempStr, options->tempConfig, &options->moduleArgs); - if (dev->type & FF_PHYSICALDISK_TYPE_READWRITE) + if (dev->type & FF_PHYSICALDISK_TYPE_READWRITE) { readOnlyType = "Read-write"; - FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]){ - FF_ARG(buffer, "size"), - FF_ARG(dev->name, "name"), - FF_ARG(dev->interconnect, "interconnect"), - FF_ARG(dev->devPath, "dev-path"), - FF_ARG(dev->serial, "serial"), - FF_ARG(physicalType, "physical-type"), - FF_ARG(removableType, "removable-type"), - FF_ARG(readOnlyType, "readonly-type"), - FF_ARG(dev->revision, "revision"), - FF_ARG(tempStr, "temperature"), - })); + } + FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { + FF_ARG(buffer, "size"), + FF_ARG(dev->name, "name"), + FF_ARG(dev->interconnect, "interconnect"), + FF_ARG(dev->devPath, "dev-path"), + FF_ARG(dev->serial, "serial"), + FF_ARG(physicalType, "physical-type"), + FF_ARG(removableType, "removable-type"), + FF_ARG(readOnlyType, "readonly-type"), + FF_ARG(dev->revision, "revision"), + FF_ARG(tempStr, "temperature"), + })); } ++index; } - FF_LIST_FOR_EACH(FFPhysicalDiskResult, dev, result) - { + FF_LIST_FOR_EACH (FFPhysicalDiskResult, dev, result) { ffStrbufDestroy(&dev->name); ffStrbufDestroy(&dev->interconnect); ffStrbufDestroy(&dev->devPath); @@ -135,30 +124,28 @@ bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) return true; } -void ffParsePhysicalDiskJsonObject(FFPhysicalDiskOptions* options, yyjson_val* module) -{ +void ffParsePhysicalDiskJsonObject(FFPhysicalDiskOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "namePrefix")) - { + if (unsafe_yyjson_equals_str(key, "namePrefix")) { ffStrbufSetJsonVal(&options->namePrefix, val); continue; } - if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) + if (ffTempsParseJsonObject(key, val, &options->temp, &options->tempConfig)) { continue; + } ffPrintError(FF_PHYSICALDISK_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGeneratePhysicalDiskJsonConfig(FFPhysicalDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGeneratePhysicalDiskJsonConfig(FFPhysicalDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_strbuf(doc, module, "namePrefix", &options->namePrefix); @@ -166,59 +153,59 @@ void ffGeneratePhysicalDiskJsonConfig(FFPhysicalDiskOptions* options, yyjson_mut ffTempsGenerateJsonConfig(doc, module, options->temp, options->tempConfig); } -bool ffGeneratePhysicalDiskJsonResult(FFPhysicalDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGeneratePhysicalDiskJsonResult(FFPhysicalDiskOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFPhysicalDiskResult)); const char* error = ffDetectPhysicalDisk(&result, options); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFPhysicalDiskResult, dev, result) - { + FF_LIST_FOR_EACH (FFPhysicalDiskResult, dev, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &dev->name); yyjson_mut_obj_add_strbuf(doc, obj, "devPath", &dev->devPath); yyjson_mut_obj_add_strbuf(doc, obj, "interconnect", &dev->interconnect); - if (dev->type & FF_PHYSICALDISK_TYPE_HDD) + if (dev->type & FF_PHYSICALDISK_TYPE_HDD) { yyjson_mut_obj_add_str(doc, obj, "kind", "HDD"); - else if (dev->type & FF_PHYSICALDISK_TYPE_SSD) + } else if (dev->type & FF_PHYSICALDISK_TYPE_SSD) { yyjson_mut_obj_add_str(doc, obj, "kind", "SSD"); - else + } else { yyjson_mut_obj_add_null(doc, obj, "kind"); + } yyjson_mut_obj_add_uint(doc, obj, "size", dev->size); yyjson_mut_obj_add_strbuf(doc, obj, "serial", &dev->serial); - if (dev->type & FF_PHYSICALDISK_TYPE_REMOVABLE) + if (dev->type & FF_PHYSICALDISK_TYPE_REMOVABLE) { yyjson_mut_obj_add_bool(doc, obj, "removable", true); - else if (dev->type & FF_PHYSICALDISK_TYPE_FIXED) + } else if (dev->type & FF_PHYSICALDISK_TYPE_FIXED) { yyjson_mut_obj_add_bool(doc, obj, "removable", false); - else + } else { yyjson_mut_obj_add_null(doc, obj, "removable"); + } - if (dev->type & FF_PHYSICALDISK_TYPE_READONLY) + if (dev->type & FF_PHYSICALDISK_TYPE_READONLY) { yyjson_mut_obj_add_bool(doc, obj, "readOnly", true); - else if (dev->type & FF_PHYSICALDISK_TYPE_READWRITE) + } else if (dev->type & FF_PHYSICALDISK_TYPE_READWRITE) { yyjson_mut_obj_add_bool(doc, obj, "readOnly", false); - else + } else { yyjson_mut_obj_add_null(doc, obj, "readOnly"); + } yyjson_mut_obj_add_strbuf(doc, obj, "revision", &dev->revision); - if (dev->temperature != FF_PHYSICALDISK_TEMP_UNSET) + if (dev->temperature != FF_PHYSICALDISK_TEMP_UNSET) { yyjson_mut_obj_add_real(doc, obj, "temperature", dev->temperature); - else + } else { yyjson_mut_obj_add_null(doc, obj, "temperature"); + } } - FF_LIST_FOR_EACH(FFPhysicalDiskResult, dev, result) - { + FF_LIST_FOR_EACH (FFPhysicalDiskResult, dev, result) { ffStrbufDestroy(&dev->name); ffStrbufDestroy(&dev->interconnect); ffStrbufDestroy(&dev->devPath); @@ -229,17 +216,15 @@ bool ffGeneratePhysicalDiskJsonResult(FFPhysicalDiskOptions* options, yyjson_mut return true; } -void ffInitPhysicalDiskOptions(FFPhysicalDiskOptions* options) -{ +void ffInitPhysicalDiskOptions(FFPhysicalDiskOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰋊"); ffStrbufInit(&options->namePrefix); options->temp = false; - options->tempConfig = (FFColorRangeConfig) { 50, 70 }; + options->tempConfig = (FFColorRangeConfig) {50, 70}; } -void ffDestroyPhysicalDiskOptions(FFPhysicalDiskOptions* options) -{ +void ffDestroyPhysicalDiskOptions(FFPhysicalDiskOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->namePrefix); } @@ -264,5 +249,4 @@ FFModuleBaseInfo ffPhysicalDiskModuleInfo = { {"Device kind (Read-only or Read-write)", "readonly-type"}, {"Product revision", "revision"}, {"Device temperature (formatted)", "temperature"}, - })) -}; + }))}; diff --git a/src/modules/physicalmemory/option.h b/src/modules/physicalmemory/option.h index 6c5e6ad82..faaff9568 100644 --- a/src/modules/physicalmemory/option.h +++ b/src/modules/physicalmemory/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFPhysicalMemoryOptions -{ +typedef struct FFPhysicalMemoryOptions { FFModuleArgs moduleArgs; bool showEmptySlots; } FFPhysicalMemoryOptions; diff --git a/src/modules/physicalmemory/physicalmemory.c b/src/modules/physicalmemory/physicalmemory.c index c487c3bdf..7d35ed659 100644 --- a/src/modules/physicalmemory/physicalmemory.c +++ b/src/modules/physicalmemory/physicalmemory.c @@ -6,96 +6,91 @@ #define FF_PHYSICALMEMORY_DISPLAY_NAME "Physical Memory" -bool ffPrintPhysicalMemory(FFPhysicalMemoryOptions* options) -{ +bool ffPrintPhysicalMemory(FFPhysicalMemoryOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFPhysicalMemoryResult)); const char* error = ffDetectPhysicalMemory(&result); - if(error) - { + if (error) { ffPrintError(FF_PHYSICALMEMORY_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if (result.length == 0) - { + if (result.length == 0) { ffPrintError(FF_PHYSICALMEMORY_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No physical memory detected"); return false; } FF_LIST_AUTO_DESTROY filtered = ffListCreate(sizeof(FFPhysicalMemoryResult*)); - FF_LIST_FOR_EACH(FFPhysicalMemoryResult, device, result) - { - if (!options->showEmptySlots && !device->installed) + FF_LIST_FOR_EACH (FFPhysicalMemoryResult, device, result) { + if (!options->showEmptySlots && !device->installed) { continue; + } *(FFPhysicalMemoryResult**) ffListAdd(&filtered) = device; } - if (filtered.length == 0) - { + if (filtered.length == 0) { ffPrintError(FF_PHYSICALMEMORY_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No installed physical memory detected"); return false; } FF_STRBUF_AUTO_DESTROY prettySize = ffStrbufCreate(); - for (uint32_t i = 0; i < filtered.length; ++i) - { + for (uint32_t i = 0; i < filtered.length; ++i) { FFPhysicalMemoryResult* device = *FF_LIST_GET(FFPhysicalMemoryResult*, filtered, i); ffStrbufClear(&prettySize); - if (device->installed) + if (device->installed) { ffSizeAppendNum(device->size, &prettySize); + } - if (options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_PHYSICALMEMORY_DISPLAY_NAME, filtered.length == 1 ? 0 : (uint8_t) (i + 1), &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (device->installed) - { + if (device->installed) { fputs(prettySize.chars, stdout); fputs(" - ", stdout); ffStrbufWriteTo(&device->type, stdout); - if (device->maxSpeed > 0) + if (device->maxSpeed > 0) { printf("-%u", device->maxSpeed); - if (device->runningSpeed > 0 && device->runningSpeed != device->maxSpeed) + } + if (device->runningSpeed > 0 && device->runningSpeed != device->maxSpeed) { printf(" @ %u MT/s", device->runningSpeed); - if (device->vendor.length > 0) + } + if (device->vendor.length > 0) { printf(" (%s)", device->vendor.chars); - if (device->ecc) + } + if (device->ecc) { fputs(" - ECC", stdout); - } - else - { + } + } else { fputs("Empty", stdout); - if (device->formFactor.length > 0) + if (device->formFactor.length > 0) { printf(" - %s", device->formFactor.chars); - if (device->locator.length > 0) + } + if (device->locator.length > 0) { printf(" (%s)", device->locator.chars); + } } putchar('\n'); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_PHYSICALMEMORY_DISPLAY_NAME, (uint8_t) (i + 1), &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(device->size, "bytes"), - FF_ARG(prettySize, "size"), - FF_ARG(device->maxSpeed, "max-speed"), - FF_ARG(device->runningSpeed, "running-speed"), - FF_ARG(device->type, "type"), - FF_ARG(device->formFactor, "form-factor"), - FF_ARG(device->locator, "locator"), - FF_ARG(device->vendor, "vendor"), - FF_ARG(device->serial, "serial"), - FF_ARG(device->partNumber, "part-number"), - FF_ARG(device->ecc, "is-ecc-enabled"), - FF_ARG(device->installed, "is-installed"), - })); + FF_ARG(device->size, "bytes"), + FF_ARG(prettySize, "size"), + FF_ARG(device->maxSpeed, "max-speed"), + FF_ARG(device->runningSpeed, "running-speed"), + FF_ARG(device->type, "type"), + FF_ARG(device->formFactor, "form-factor"), + FF_ARG(device->locator, "locator"), + FF_ARG(device->vendor, "vendor"), + FF_ARG(device->serial, "serial"), + FF_ARG(device->partNumber, "part-number"), + FF_ARG(device->ecc, "is-ecc-enabled"), + FF_ARG(device->installed, "is-installed"), + })); } } - FF_LIST_FOR_EACH(FFPhysicalMemoryResult, device, result) - { + FF_LIST_FOR_EACH (FFPhysicalMemoryResult, device, result) { ffStrbufDestroy(&device->type); ffStrbufDestroy(&device->locator); ffStrbufDestroy(&device->formFactor); @@ -107,17 +102,15 @@ bool ffPrintPhysicalMemory(FFPhysicalMemoryOptions* options) return true; } -void ffParsePhysicalMemoryJsonObject(FFPhysicalMemoryOptions* options, yyjson_val* module) -{ +void ffParsePhysicalMemoryJsonObject(FFPhysicalMemoryOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "showEmptySlots")) - { + if (unsafe_yyjson_equals_str(key, "showEmptySlots")) { options->showEmptySlots = yyjson_get_bool(val); continue; } @@ -126,26 +119,22 @@ void ffParsePhysicalMemoryJsonObject(FFPhysicalMemoryOptions* options, yyjson_va } } -void ffGeneratePhysicalMemoryJsonConfig(FFPhysicalMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGeneratePhysicalMemoryJsonConfig(FFPhysicalMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "showEmptySlots", options->showEmptySlots); } -bool ffGeneratePhysicalMemoryJsonResult(FF_MAYBE_UNUSED FFPhysicalMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGeneratePhysicalMemoryJsonResult(FF_MAYBE_UNUSED FFPhysicalMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFPhysicalMemoryResult)); const char* error = ffDetectPhysicalMemory(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFPhysicalMemoryResult, device, result) - { + FF_LIST_FOR_EACH (FFPhysicalMemoryResult, device, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_uint(doc, obj, "size", device->size); yyjson_mut_obj_add_bool(doc, obj, "installed", device->installed); @@ -160,8 +149,7 @@ bool ffGeneratePhysicalMemoryJsonResult(FF_MAYBE_UNUSED FFPhysicalMemoryOptions* yyjson_mut_obj_add_bool(doc, obj, "ecc", device->ecc); } - FF_LIST_FOR_EACH(FFPhysicalMemoryResult, device, result) - { + FF_LIST_FOR_EACH (FFPhysicalMemoryResult, device, result) { ffStrbufDestroy(&device->type); ffStrbufDestroy(&device->locator); ffStrbufDestroy(&device->formFactor); @@ -173,14 +161,12 @@ bool ffGeneratePhysicalMemoryJsonResult(FF_MAYBE_UNUSED FFPhysicalMemoryOptions* return true; } -void ffInitPhysicalMemoryOptions(FFPhysicalMemoryOptions* options) -{ +void ffInitPhysicalMemoryOptions(FFPhysicalMemoryOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰑭"); options->showEmptySlots = false; } -void ffDestroyPhysicalMemoryOptions(FFPhysicalMemoryOptions* options) -{ +void ffDestroyPhysicalMemoryOptions(FFPhysicalMemoryOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -206,5 +192,4 @@ FFModuleBaseInfo ffPhysicalMemoryModuleInfo = { {"Part number", "part-number"}, {"True if ECC enabled", "is-ecc-enabled"}, {"True if a memory module is installed in the slot", "is-installed"}, - })) -}; + }))}; diff --git a/src/modules/player/option.h b/src/modules/player/option.h index 9d55821fd..17aa9ba8d 100644 --- a/src/modules/player/option.h +++ b/src/modules/player/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFPlayerOptions -{ +typedef struct FFPlayerOptions { FFModuleArgs moduleArgs; } FFPlayerOptions; diff --git a/src/modules/player/player.c b/src/modules/player/player.c index 35887d93e..f5d2083a2 100644 --- a/src/modules/player/player.c +++ b/src/modules/player/player.c @@ -8,112 +8,103 @@ #define FF_PLAYER_DISPLAY_NAME "Media Player" -bool ffPrintPlayer(FFPlayerOptions* options) -{ +bool ffPrintPlayer(FFPlayerOptions* options) { const FFMediaResult* media = ffDetectMedia(false); - if(media->error.length > 0) - { + if (media->error.length > 0) { ffPrintError(FF_PLAYER_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", media->error.chars); return false; } - if (media->player.length == 0) - { + if (media->player.length == 0) { ffPrintError(FF_PLAYER_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No media player detected"); return false; } FF_STRBUF_AUTO_DESTROY playerPretty = ffStrbufCreate(); - if (media->url.length > 0) - { - //If we are on a website, prepend the website name - if( + if (media->url.length > 0) { + // If we are on a website, prepend the website name + if ( ffStrbufIgnCaseEqualS(&media->playerId, "spotify") || - ffStrbufIgnCaseEqualS(&media->playerId, "vlc") - ) {} // do noting, surely not a website, even if the url is set - else if(ffStrbufStartsWithS(&media->url, "https://www.")) + ffStrbufIgnCaseEqualS(&media->playerId, "vlc")) { + } // do noting, surely not a website, even if the url is set + else if (ffStrbufStartsWithS(&media->url, "https://www.")) { ffStrbufAppendS(&playerPretty, media->url.chars + 12); - else if(ffStrbufStartsWithS(&media->url, "http://www.")) + } else if (ffStrbufStartsWithS(&media->url, "http://www.")) { ffStrbufAppendS(&playerPretty, media->url.chars + 11); - else if(ffStrbufStartsWithS(&media->url, "https://")) + } else if (ffStrbufStartsWithS(&media->url, "https://")) { ffStrbufAppendS(&playerPretty, media->url.chars + 8); - else if(ffStrbufStartsWithS(&media->url, "http://")) + } else if (ffStrbufStartsWithS(&media->url, "http://")) { ffStrbufAppendS(&playerPretty, media->url.chars + 7); + } } - //If we found a website name, make it more pretty - if(playerPretty.length > 0) - { - ffStrbufSubstrBeforeFirstC(&playerPretty, '/'); //Remove the path - ffStrbufSubstrBeforeLastC(&playerPretty, '.'); //Remove the TLD + // If we found a website name, make it more pretty + if (playerPretty.length > 0) { + ffStrbufSubstrBeforeFirstC(&playerPretty, '/'); // Remove the path + ffStrbufSubstrBeforeLastC(&playerPretty, '.'); // Remove the TLD } - //Check again for length, as we may have removed everything. + // Check again for length, as we may have removed everything. bool playerPrettyIsCustom = playerPretty.length > 0; - //If we don't have subdomains, it is usually more pretty to capitalize the first letter. - if(playerPrettyIsCustom && ffStrbufFirstIndexC(&playerPretty, '.') == playerPretty.length) + // If we don't have subdomains, it is usually more pretty to capitalize the first letter. + if (playerPrettyIsCustom && ffStrbufFirstIndexC(&playerPretty, '.') == playerPretty.length) { playerPretty.chars[0] = (char) toupper(playerPretty.chars[0]); + } - if(playerPrettyIsCustom) + if (playerPrettyIsCustom) { ffStrbufAppendS(&playerPretty, " ("); + } ffStrbufAppend(&playerPretty, &media->player); - if(playerPrettyIsCustom) + if (playerPrettyIsCustom) { ffStrbufAppendC(&playerPretty, ')'); + } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_PLAYER_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&playerPretty, stdout); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_PLAYER_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(playerPretty, "player"), - FF_ARG(media->player, "name"), - FF_ARG(media->playerId, "id"), - FF_ARG(media->url, "url"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_PLAYER_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(playerPretty, "player"), + FF_ARG(media->player, "name"), + FF_ARG(media->playerId, "id"), + FF_ARG(media->url, "url"), + })); } return true; } -void ffParsePlayerJsonObject(FFPlayerOptions* options, yyjson_val* module) -{ +void ffParsePlayerJsonObject(FFPlayerOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_PLAYER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGeneratePlayerJsonConfig(FFPlayerOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGeneratePlayerJsonConfig(FFPlayerOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGeneratePlayerJsonResult(FF_MAYBE_UNUSED FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGeneratePlayerJsonResult(FF_MAYBE_UNUSED FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_obj_add_str(doc, module, "error", "Player module is an alias of Media module"); return false; } -void ffInitPlayerOptions(FFPlayerOptions* options) -{ +void ffInitPlayerOptions(FFPlayerOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰥠"); } -void ffDestroyPlayerOptions(FFPlayerOptions* options) -{ +void ffDestroyPlayerOptions(FFPlayerOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -131,5 +122,4 @@ FFModuleBaseInfo ffPlayerModuleInfo = { {"Player name", "name"}, {"Player Identifier", "id"}, {"URL name", "url"}, - })) -}; + }))}; diff --git a/src/modules/poweradapter/option.h b/src/modules/poweradapter/option.h index 303bbba73..6f2875442 100644 --- a/src/modules/poweradapter/option.h +++ b/src/modules/poweradapter/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFPowerAdapterOptions -{ +typedef struct FFPowerAdapterOptions { FFModuleArgs moduleArgs; } FFPowerAdapterOptions; diff --git a/src/modules/poweradapter/poweradapter.c b/src/modules/poweradapter/poweradapter.c index 48da15038..997369b64 100644 --- a/src/modules/poweradapter/poweradapter.c +++ b/src/modules/poweradapter/poweradapter.c @@ -6,47 +6,41 @@ #define FF_POWERADAPTER_DISPLAY_NAME "Power Adapter" -bool ffPrintPowerAdapter(FFPowerAdapterOptions* options) -{ +bool ffPrintPowerAdapter(FFPowerAdapterOptions* options) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFPowerAdapterResult)); const char* error = ffDetectPowerAdapter(&results); - if (error) - { + if (error) { ffPrintError(FF_POWERADAPTER_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(results.length == 0) - { + if (results.length == 0) { ffPrintError(FF_POWERADAPTER_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No power adapters found"); return false; } - for(uint8_t i = 0; i < (uint8_t) results.length; i++) - { + for (uint8_t i = 0; i < (uint8_t) results.length; i++) { FFPowerAdapterResult* result = FF_LIST_GET(FFPowerAdapterResult, results, i); - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_POWERADAPTER_DISPLAY_NAME, i, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if(result->name.length > 0) + if (result->name.length > 0) { puts(result->name.chars); - else + } else { printf("%dW\n", result->watts); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_POWERADAPTER_DISPLAY_NAME, i, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result->watts, "watts"), - FF_ARG(result->name, "name"), - FF_ARG(result->manufacturer, "manufacturer"), - FF_ARG(result->modelName, "model-name"), - FF_ARG(result->description, "description"), - FF_ARG(result->serial, "serial"), - })); + } + } else { + FF_PRINT_FORMAT_CHECKED(FF_POWERADAPTER_DISPLAY_NAME, i, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result->watts, "watts"), + FF_ARG(result->name, "name"), + FF_ARG(result->manufacturer, "manufacturer"), + FF_ARG(result->modelName, "model-name"), + FF_ARG(result->description, "description"), + FF_ARG(result->serial, "serial"), + })); } ffStrbufDestroy(&result->manufacturer); @@ -59,39 +53,34 @@ bool ffPrintPowerAdapter(FFPowerAdapterOptions* options) return true; } -void ffGeneratePowerAdapterJsonConfig(FFPowerAdapterOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGeneratePowerAdapterJsonConfig(FFPowerAdapterOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -void ffParsePowerAdapterJsonObject(FFPowerAdapterOptions* options, yyjson_val* module) -{ +void ffParsePowerAdapterJsonObject(FFPowerAdapterOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_POWERADAPTER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -bool ffGeneratePowerAdapterJsonResult(FF_MAYBE_UNUSED FFPowerAdapterOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGeneratePowerAdapterJsonResult(FF_MAYBE_UNUSED FFPowerAdapterOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFPowerAdapterResult)); const char* error = ffDetectPowerAdapter(&results); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFPowerAdapterResult, item, results) - { + FF_LIST_FOR_EACH (FFPowerAdapterResult, item, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "description", &item->description); yyjson_mut_obj_add_strbuf(doc, obj, "manufacturer", &item->manufacturer); @@ -101,8 +90,7 @@ bool ffGeneratePowerAdapterJsonResult(FF_MAYBE_UNUSED FFPowerAdapterOptions* opt yyjson_mut_obj_add_int(doc, obj, "watts", item->watts); } - FF_LIST_FOR_EACH(FFPowerAdapterResult, item, results) - { + FF_LIST_FOR_EACH (FFPowerAdapterResult, item, results) { ffStrbufDestroy(&item->manufacturer); ffStrbufDestroy(&item->description); ffStrbufDestroy(&item->modelName); @@ -113,13 +101,11 @@ bool ffGeneratePowerAdapterJsonResult(FF_MAYBE_UNUSED FFPowerAdapterOptions* opt return true; } -void ffInitPowerAdapterOptions(FFPowerAdapterOptions* options) -{ +void ffInitPowerAdapterOptions(FFPowerAdapterOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰚥"); } -void ffDestroyPowerAdapterOptions(FFPowerAdapterOptions* options) -{ +void ffDestroyPowerAdapterOptions(FFPowerAdapterOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -139,5 +125,4 @@ FFModuleBaseInfo ffPowerAdapterModuleInfo = { {"Power adapter model", "model"}, {"Power adapter description", "description"}, {"Power adapter serial number", "serial"}, - })) -}; + }))}; diff --git a/src/modules/processes/option.h b/src/modules/processes/option.h index 0b59f9df3..2ee25634d 100644 --- a/src/modules/processes/option.h +++ b/src/modules/processes/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFProcessesOptions -{ +typedef struct FFProcessesOptions { FFModuleArgs moduleArgs; } FFProcessesOptions; diff --git a/src/modules/processes/processes.c b/src/modules/processes/processes.c index a199cad4c..fd1f96b4d 100644 --- a/src/modules/processes/processes.c +++ b/src/modules/processes/processes.c @@ -4,58 +4,47 @@ #include "detection/processes/processes.h" #include "modules/processes/processes.h" -bool ffPrintProcesses(FFProcessesOptions* options) -{ +bool ffPrintProcesses(FFProcessesOptions* options) { uint32_t numProcesses = 0; const char* error = ffDetectProcesses(&numProcesses); - if(error) - { + if (error) { ffPrintError(FF_PROCESSES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_PROCESSES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); printf("%u\n", numProcesses); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_PROCESSES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(numProcesses, "result") - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_PROCESSES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) {FF_ARG(numProcesses, "result")})); } return true; } -void ffParseProcessesJsonObject(FFProcessesOptions* options, yyjson_val* module) -{ +void ffParseProcessesJsonObject(FFProcessesOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_PROCESSES_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateProcessesJsonConfig(FFProcessesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateProcessesJsonConfig(FFProcessesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateProcessesJsonResult(FF_MAYBE_UNUSED FFProcessesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateProcessesJsonResult(FF_MAYBE_UNUSED FFProcessesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { uint32_t result; const char* error = ffDetectProcesses(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -65,13 +54,11 @@ bool ffGenerateProcessesJsonResult(FF_MAYBE_UNUSED FFProcessesOptions* options, return true; } -void ffInitProcessesOptions(FFProcessesOptions* options) -{ +void ffInitProcessesOptions(FFProcessesOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyProcessesOptions(FFProcessesOptions* options) -{ +void ffDestroyProcessesOptions(FFProcessesOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -85,6 +72,4 @@ FFModuleBaseInfo ffProcessesModuleInfo = { .generateJsonResult = (void*) ffGenerateProcessesJsonResult, .generateJsonConfig = (void*) ffGenerateProcessesJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { - {"Process count", "result"} - })) -}; + {"Process count", "result"}}))}; diff --git a/src/modules/publicip/option.h b/src/modules/publicip/option.h index e3118cb28..aca723629 100644 --- a/src/modules/publicip/option.h +++ b/src/modules/publicip/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFPublicIPOptions -{ +typedef struct FFPublicIPOptions { FFModuleArgs moduleArgs; FFstrbuf url; diff --git a/src/modules/publicip/publicip.c b/src/modules/publicip/publicip.c index 619f191e4..4f5e338bb 100644 --- a/src/modules/publicip/publicip.c +++ b/src/modules/publicip/publicip.c @@ -6,33 +6,29 @@ #define FF_PUBLICIP_DISPLAY_NAME "Public IP" -bool ffPrintPublicIp(FFPublicIPOptions* options) -{ +bool ffPrintPublicIp(FFPublicIPOptions* options) { FFPublicIpResult result; ffStrbufInit(&result.ip); ffStrbufInit(&result.location); const char* error = ffDetectPublicIp(options, &result); - if (error) - { + if (error) { ffPrintError(FF_PUBLICIP_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if (options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_PUBLICIP_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (result.location.length) + if (result.location.length) { printf("%s (%s)\n", result.ip.chars, result.location.chars); - else + } else { ffStrbufPutTo(&result.ip, stdout); - } - else - { + } + } else { FF_PRINT_FORMAT_CHECKED(FF_PUBLICIP_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result.ip, "ip"), - FF_ARG(result.location, "location"), - })); + FF_ARG(result.ip, "ip"), + FF_ARG(result.location, "location"), + })); } ffStrbufDestroy(&result.ip); @@ -41,29 +37,25 @@ bool ffPrintPublicIp(FFPublicIPOptions* options) return true; } -void ffParsePublicIpJsonObject(FFPublicIPOptions* options, yyjson_val* module) -{ +void ffParsePublicIpJsonObject(FFPublicIPOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "url")) - { + if (unsafe_yyjson_equals_str(key, "url")) { ffStrbufSetJsonVal(&options->url, val); continue; } - if (unsafe_yyjson_equals_str(key, "timeout")) - { + if (unsafe_yyjson_equals_str(key, "timeout")) { options->timeout = (uint32_t) yyjson_get_uint(val); continue; } - if (unsafe_yyjson_equals_str(key, "ipv6")) - { + if (unsafe_yyjson_equals_str(key, "ipv6")) { options->ipv6 = yyjson_get_bool(val); continue; } @@ -72,8 +64,7 @@ void ffParsePublicIpJsonObject(FFPublicIPOptions* options, yyjson_val* module) } } -void ffGeneratePublicIpJsonConfig(FFPublicIPOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGeneratePublicIpJsonConfig(FFPublicIPOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_strbuf(doc, module, "url", &options->url); @@ -83,15 +74,13 @@ void ffGeneratePublicIpJsonConfig(FFPublicIPOptions* options, yyjson_mut_doc* do yyjson_mut_obj_add_bool(doc, module, "ipv6", options->ipv6); } -bool ffGeneratePublicIpJsonResult(FFPublicIPOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGeneratePublicIpJsonResult(FFPublicIPOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFPublicIpResult result; ffStrbufInit(&result.ip); ffStrbufInit(&result.location); const char* error = ffDetectPublicIp(options, &result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -106,8 +95,7 @@ bool ffGeneratePublicIpJsonResult(FFPublicIPOptions* options, yyjson_mut_doc* do return true; } -void ffInitPublicIpOptions(FFPublicIPOptions* options) -{ +void ffInitPublicIpOptions(FFPublicIPOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰩠"); ffStrbufInit(&options->url); @@ -115,8 +103,7 @@ void ffInitPublicIpOptions(FFPublicIPOptions* options) options->ipv6 = false; } -void ffDestroyPublicIpOptions(FFPublicIPOptions* options) -{ +void ffDestroyPublicIpOptions(FFPublicIPOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->url); @@ -134,5 +121,4 @@ FFModuleBaseInfo ffPublicIPModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Public IP address", "ip"}, {"Location", "location"}, - })) -}; + }))}; diff --git a/src/modules/separator/option.h b/src/modules/separator/option.h index a8b31379d..510132c10 100644 --- a/src/modules/separator/option.h +++ b/src/modules/separator/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFSeparatorOptions -{ +typedef struct FFSeparatorOptions { FFstrbuf string; FFstrbuf outputColor; uint32_t times; diff --git a/src/modules/separator/separator.c b/src/modules/separator/separator.c index a04ae8c36..aa8d13e49 100644 --- a/src/modules/separator/separator.c +++ b/src/modules/separator/separator.c @@ -10,113 +10,102 @@ #include #if __SIZEOF_WCHAR_T__ == 4 - static inline size_t mbrtoc32(uint32_t* restrict pc32, const char* restrict s, size_t n, mbstate_t* restrict ps) - { - return mbrtowc((wchar_t*) pc32, s, n, ps); - } +static inline size_t mbrtoc32(uint32_t* restrict pc32, const char* restrict s, size_t n, mbstate_t* restrict ps) { + return mbrtowc((wchar_t*) pc32, s, n, ps); +} #else - #include +# include #endif -static uint8_t getMbrWidth(const char* mbstr, uint32_t length, const char** next, mbstate_t* state) -{ +static uint8_t getMbrWidth(const char* mbstr, uint32_t length, const char** next, mbstate_t* state) { if (__builtin_expect((uint8_t) *mbstr < 0x80, true)) // ASCII fast path { - if (next) *next = mbstr + 1; + if (next) { + *next = mbstr + 1; + } return 1; } uint32_t c32; uint32_t len = (uint32_t) mbrtoc32(&c32, mbstr, length, state); - if (len >= (uint32_t) -3) - { + if (len >= (uint32_t) -3) { // Invalid or incomplete multibyte sequence - if (next) *next = mbstr + 1; + if (next) { + *next = mbstr + 1; + } return 1; } - if (next) *next = mbstr + len; + if (next) { + *next = mbstr + len; + } int width = mk_wcwidth(c32); return width < 0 ? 0 : (uint8_t) width; } -static uint32_t getWcsWidth(const FFstrbuf* mbstr) -{ +static uint32_t getWcsWidth(const FFstrbuf* mbstr) { mbstate_t state = {}; uint32_t remainLength = mbstr->length; uint32_t result = 0; const char* ptr = mbstr->chars; - while (remainLength > 0 && *ptr != '\0') - { + while (remainLength > 0 && *ptr != '\0') { const char* lastPtr = NULL; result += getMbrWidth(ptr, remainLength, &lastPtr, &state); - remainLength -= (uint32_t)(lastPtr - ptr); + remainLength -= (uint32_t) (lastPtr - ptr); ptr = lastPtr; } return result > 0 ? (uint32_t) result : mbstr->length; } -bool ffPrintSeparator(FFSeparatorOptions* options) -{ +bool ffPrintSeparator(FFSeparatorOptions* options) { ffLogoPrintLine(); - if(options->outputColor.length && !instance.config.display.pipe) + if (options->outputColor.length && !instance.config.display.pipe) { ffPrintColor(&options->outputColor); + } - if (options->times > 0) - { - if(__builtin_expect(options->string.length == 1, 1)) + if (options->times > 0) { + if (__builtin_expect(options->string.length == 1, 1)) { ffPrintCharTimes(options->string.chars[0], options->times); - else - { - for (uint32_t i = 0; i < options->times; i++) - { + } else { + for (uint32_t i = 0; i < options->times; i++) { fputs(options->string.chars, stdout); } } - } - else - { + } else { setlocale(LC_CTYPE, ""); const FFPlatform* platform = &instance.state.platform; - uint32_t titleLength = 1 // @ - + getWcsWidth(&platform->userName) // user name + uint32_t titleLength = 1 // @ + + getWcsWidth(&platform->userName) // user name + (instance.state.titleFqdn ? platform->hostName.length : ffStrbufFirstIndexC(&platform->hostName, '.')); // host name - if(__builtin_expect(options->string.length == 1, 1)) - { + if (__builtin_expect(options->string.length == 1, 1)) { ffPrintCharTimes(options->string.chars[0], titleLength); - } - else - { + } else { uint32_t wcsLength = getWcsWidth(&options->string); int remaining = (int) titleLength; - //Write the whole separator as often as it fits fully into titleLength - for (; remaining >= (int) wcsLength; remaining -= (int) wcsLength) + // Write the whole separator as often as it fits fully into titleLength + for (; remaining >= (int) wcsLength; remaining -= (int) wcsLength) { ffStrbufWriteTo(&options->string, stdout); + } - if (remaining > 0) - { - //Write as much of the separator as needed to fill titleLength - if (wcsLength != options->string.length) - { + if (remaining > 0) { + // Write as much of the separator as needed to fill titleLength + if (wcsLength != options->string.length) { // Unicode chars const char* ptr = options->string.chars; mbstate_t state = {}; const char* next = NULL; - while (remaining > 0 && *ptr != '\0') - { - remaining -= (int) getMbrWidth(ptr, (uint32_t)(options->string.length - (ptr - options->string.chars)), &next, &state); + while (remaining > 0 && *ptr != '\0') { + remaining -= (int) getMbrWidth(ptr, (uint32_t) (options->string.length - (ptr - options->string.chars)), &next, &state); ptr = next; } fwrite(options->string.chars, (size_t) (ptr - options->string.chars), 1, stdout); - } - else - { + } else { fwrite(options->string.chars, (size_t) remaining, 1, stdout); } } @@ -124,42 +113,38 @@ bool ffPrintSeparator(FFSeparatorOptions* options) setlocale(LC_CTYPE, "C"); } - if(options->outputColor.length && !instance.config.display.pipe) + if (options->outputColor.length && !instance.config.display.pipe) { fputs(FASTFETCH_TEXT_MODIFIER_RESET, stdout); + } putchar('\n'); return true; } -void ffParseSeparatorJsonObject(FFSeparatorOptions* options, yyjson_val* module) -{ +void ffParseSeparatorJsonObject(FFSeparatorOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) + yyjson_obj_foreach (module, idx, max, key, val) { + if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) { continue; + } - if (unsafe_yyjson_equals_str(key, "string")) - { + if (unsafe_yyjson_equals_str(key, "string")) { ffStrbufSetJsonVal(&options->string, val); continue; } - if (unsafe_yyjson_equals_str(key, "outputColor")) - { + if (unsafe_yyjson_equals_str(key, "outputColor")) { ffOptionParseColor(yyjson_get_str(val), &options->outputColor); continue; } - if (unsafe_yyjson_equals_str(key, "times")) - { + if (unsafe_yyjson_equals_str(key, "times")) { options->times = (uint32_t) yyjson_get_uint(val); continue; } - if (unsafe_yyjson_equals_str(key, "length")) - { + if (unsafe_yyjson_equals_str(key, "length")) { ffPrintError(FF_SEPARATOR_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "The option length has been renamed to times."); continue; } @@ -168,22 +153,19 @@ void ffParseSeparatorJsonObject(FFSeparatorOptions* options, yyjson_val* module) } } -void ffGenerateSeparatorJsonConfig(FFSeparatorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateSeparatorJsonConfig(FFSeparatorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_obj_add_strbuf(doc, module, "string", &options->string); yyjson_mut_obj_add_strbuf(doc, module, "outputColor", &options->outputColor); yyjson_mut_obj_add_uint(doc, module, "times", options->times); } -void ffInitSeparatorOptions(FFSeparatorOptions* options) -{ +void ffInitSeparatorOptions(FFSeparatorOptions* options) { ffStrbufInitStatic(&options->string, "-"); ffStrbufInit(&options->outputColor); options->times = 0; } -void ffDestroySeparatorOptions(FFSeparatorOptions* options) -{ +void ffDestroySeparatorOptions(FFSeparatorOptions* options) { ffStrbufDestroy(&options->string); } diff --git a/src/modules/shell/option.h b/src/modules/shell/option.h index 49ec83f51..bd8ed2409 100644 --- a/src/modules/shell/option.h +++ b/src/modules/shell/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFShellOptions -{ +typedef struct FFShellOptions { FFModuleArgs moduleArgs; } FFShellOptions; diff --git a/src/modules/shell/shell.c b/src/modules/shell/shell.c index b4d3c238a..c79d086ef 100644 --- a/src/modules/shell/shell.c +++ b/src/modules/shell/shell.c @@ -4,70 +4,60 @@ #include "detection/terminalshell/terminalshell.h" #include "modules/shell/shell.h" -bool ffPrintShell(FFShellOptions* options) -{ +bool ffPrintShell(FFShellOptions* options) { const FFShellResult* result = ffDetectShell(); - if(result->processName.length == 0) - { + if (result->processName.length == 0) { ffPrintError(FF_SHELL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Couldn't detect shell"); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_SHELL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result->prettyName, stdout); - if(result->version.length > 0) - { + if (result->version.length > 0) { putchar(' '); ffStrbufWriteTo(&result->version, stdout); } putchar('\n'); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_SHELL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result->processName, "process-name"), - FF_ARG(result->exe, "exe"), - FF_ARG(result->exeName, "exe-name"), - FF_ARG(result->version, "version"), - FF_ARG(result->pid, "pid"), - FF_ARG(result->prettyName, "pretty-name"), - FF_ARG(result->exePath, "exe-path"), - FF_ARG(result->tty, "tty"), - })); + FF_ARG(result->processName, "process-name"), + FF_ARG(result->exe, "exe"), + FF_ARG(result->exeName, "exe-name"), + FF_ARG(result->version, "version"), + FF_ARG(result->pid, "pid"), + FF_ARG(result->prettyName, "pretty-name"), + FF_ARG(result->exePath, "exe-path"), + FF_ARG(result->tty, "tty"), + })); } return true; } -void ffParseShellJsonObject(FFShellOptions* options, yyjson_val* module) -{ +void ffParseShellJsonObject(FFShellOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_SHELL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateShellJsonConfig(FFShellOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateShellJsonConfig(FFShellOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateShellJsonResult(FF_MAYBE_UNUSED FFShellOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateShellJsonResult(FF_MAYBE_UNUSED FFShellOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFShellResult* result = ffDetectShell(); - if(result->processName.length == 0) - { + if (result->processName.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "Couldn't detect shell"); return false; } @@ -81,21 +71,20 @@ bool ffGenerateShellJsonResult(FF_MAYBE_UNUSED FFShellOptions* options, yyjson_m yyjson_mut_obj_add_strbuf(doc, obj, "processName", &result->processName); yyjson_mut_obj_add_strbuf(doc, obj, "prettyName", &result->prettyName); yyjson_mut_obj_add_strbuf(doc, obj, "version", &result->version); - if (result->tty >= 0) + if (result->tty >= 0) { yyjson_mut_obj_add_int(doc, obj, "tty", result->tty); - else + } else { yyjson_mut_obj_add_null(doc, obj, "tty"); + } return true; } -void ffInitShellOptions(FFShellOptions* options) -{ +void ffInitShellOptions(FFShellOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyShellOptions(FFShellOptions* options) -{ +void ffDestroyShellOptions(FFShellOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -117,5 +106,4 @@ FFModuleBaseInfo ffShellModuleInfo = { {"Shell pretty name", "pretty-name"}, {"Shell full exe path", "exe-path"}, {"Shell tty used", "tty"}, - })) -}; + }))}; diff --git a/src/modules/sound/option.h b/src/modules/sound/option.h index 0c9f0fd4f..aaf641c4b 100644 --- a/src/modules/sound/option.h +++ b/src/modules/sound/option.h @@ -3,15 +3,13 @@ #include "common/option.h" #include "common/percent.h" -typedef enum __attribute__((__packed__)) FFSoundType -{ +typedef enum __attribute__((__packed__)) FFSoundType { FF_SOUND_TYPE_MAIN, FF_SOUND_TYPE_ACTIVE, FF_SOUND_TYPE_ALL, } FFSoundType; -typedef struct FFSoundOptions -{ +typedef struct FFSoundOptions { FFModuleArgs moduleArgs; FFSoundType soundType; diff --git a/src/modules/sound/sound.c b/src/modules/sound/sound.c index 99898b48a..4f402058e 100644 --- a/src/modules/sound/sound.c +++ b/src/modules/sound/sound.c @@ -5,76 +5,71 @@ #include "detection/sound/sound.h" #include "modules/sound/sound.h" -static void printDevice(FFSoundOptions* options, const FFSoundDevice* device, uint8_t index) -{ +static void printDevice(FFSoundOptions* options, const FFSoundDevice* device, uint8_t index) { FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_SOUND_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); - if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppend(&str, &device->name); + } - if(device->volume != FF_SOUND_VOLUME_UNKNOWN) - { - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { - if (str.length) + if (device->volume != FF_SOUND_VOLUME_UNKNOWN) { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { + if (str.length) { ffStrbufAppendC(&str, ' '); + } ffPercentAppendBar(&str, device->volume, options->percent, &options->moduleArgs); } - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) - { - if (str.length) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { + if (str.length) { ffStrbufAppendC(&str, ' '); + } ffPercentAppendNum(&str, device->volume, options->percent, str.length > 0, &options->moduleArgs); } } - if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) - { - if (device->main && index > 0) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { + if (device->main && index > 0) { ffStrbufAppendS(&str, " (*)"); + } } ffStrbufPutTo(&str, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY percentageNum = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY percentageBar = ffStrbufCreate(); - if(device->volume != FF_SOUND_VOLUME_UNKNOWN) - { - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (device->volume != FF_SOUND_VOLUME_UNKNOWN) { + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&percentageNum, device->volume, options->percent, false, &options->moduleArgs); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + } + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&percentageBar, device->volume, options->percent, &options->moduleArgs); + } } FF_PRINT_FORMAT_CHECKED(FF_SOUND_MODULE_NAME, index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(device->main, "is-main"), - FF_ARG(device->name, "name"), - FF_ARG(percentageNum, "volume-percentage"), - FF_ARG(device->identifier, "identifier"), - FF_ARG(percentageBar, "volume-percentage-bar"), - FF_ARG(device->platformApi, "platform-api"), - })); + FF_ARG(device->main, "is-main"), + FF_ARG(device->name, "name"), + FF_ARG(percentageNum, "volume-percentage"), + FF_ARG(device->identifier, "identifier"), + FF_ARG(percentageBar, "volume-percentage-bar"), + FF_ARG(device->platformApi, "platform-api"), + })); } } -bool ffPrintSound(FFSoundOptions* options) -{ +bool ffPrintSound(FFSoundOptions* options) { bool success = false; FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFSoundDevice)); const char* error = ffDetectSound(&result); - if(error) - { + if (error) { ffPrintError(FF_SOUND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); goto exit; } @@ -82,35 +77,39 @@ bool ffPrintSound(FFSoundOptions* options) { FF_LIST_AUTO_DESTROY filtered = ffListCreate(sizeof(FFSoundDevice*)); - FF_LIST_FOR_EACH(FFSoundDevice, device, result) - { - switch (options->soundType) - { - case FF_SOUND_TYPE_MAIN: if (!device->main) continue; break; - case FF_SOUND_TYPE_ACTIVE: if (!device->active) continue; break; - case FF_SOUND_TYPE_ALL: break; + FF_LIST_FOR_EACH (FFSoundDevice, device, result) { + switch (options->soundType) { + case FF_SOUND_TYPE_MAIN: + if (!device->main) { + continue; + } + break; + case FF_SOUND_TYPE_ACTIVE: + if (!device->active) { + continue; + } + break; + case FF_SOUND_TYPE_ALL: + break; } - *(FFSoundDevice**)ffListAdd(&filtered) = device; + *(FFSoundDevice**) ffListAdd(&filtered) = device; } - if(filtered.length == 0) - { + if (filtered.length == 0) { ffPrintError(FF_SOUND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No active sound devices found"); goto exit; } uint8_t index = 1; - FF_LIST_FOR_EACH(FFSoundDevice*, device, filtered) - { + FF_LIST_FOR_EACH (FFSoundDevice*, device, filtered) { printDevice(options, *device, filtered.length == 1 ? 0 : index++); } } success = true; exit: - FF_LIST_FOR_EACH(FFSoundDevice, device, result) - { + FF_LIST_FOR_EACH (FFSoundDevice, device, result) { ffStrbufDestroy(&device->identifier); ffStrbufDestroy(&device->name); ffStrbufDestroy(&device->platformApi); @@ -119,44 +118,42 @@ exit: return success; } -void ffParseSoundJsonObject(FFSoundOptions* options, yyjson_val* module) -{ +void ffParseSoundJsonObject(FFSoundOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) - continue; - - if (unsafe_yyjson_equals_str(key, "soundType")) - { - int value; - const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "main", FF_SOUND_TYPE_MAIN }, - { "active", FF_SOUND_TYPE_ACTIVE }, - { "all", FF_SOUND_TYPE_ALL }, - {}, - }); - if (error) - ffPrintError(FF_SOUND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); - else - options->soundType = (FFSoundType) value; + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (unsafe_yyjson_equals_str(key, "soundType")) { + int value; + const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { + {"main", FF_SOUND_TYPE_MAIN}, + {"active", FF_SOUND_TYPE_ACTIVE}, + {"all", FF_SOUND_TYPE_ALL}, + {}, + }); + if (error) { + ffPrintError(FF_SOUND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); + } else { + options->soundType = (FFSoundType) value; + } continue; + } + + if (ffPercentParseJsonObject(key, val, &options->percent)) { + continue; + } ffPrintError(FF_SOUND_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateSoundJsonConfig(FFSoundOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateSoundJsonConfig(FFSoundOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); - switch (options->soundType) - { + switch (options->soundType) { case FF_SOUND_TYPE_MAIN: yyjson_mut_obj_add_str(doc, module, "soundType", "main"); break; @@ -171,36 +168,33 @@ void ffGenerateSoundJsonConfig(FFSoundOptions* options, yyjson_mut_doc* doc, yyj ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateSoundJsonResult(FF_MAYBE_UNUSED FFSoundOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateSoundJsonResult(FF_MAYBE_UNUSED FFSoundOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFSoundDevice)); const char* error = ffDetectSound(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFSoundDevice, item, result) - { + FF_LIST_FOR_EACH (FFSoundDevice, item, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_bool(doc, obj, "active", item->active); yyjson_mut_obj_add_bool(doc, obj, "main", item->main); - if (item->volume != FF_SOUND_VOLUME_UNKNOWN) + if (item->volume != FF_SOUND_VOLUME_UNKNOWN) { yyjson_mut_obj_add_uint(doc, obj, "volume", item->volume); - else + } else { yyjson_mut_obj_add_null(doc, obj, "volume"); + } yyjson_mut_obj_add_strbuf(doc, obj, "name", &item->name); yyjson_mut_obj_add_strbuf(doc, obj, "identifier", &item->identifier); yyjson_mut_obj_add_strbuf(doc, obj, "platformApi", &item->platformApi); } - FF_LIST_FOR_EACH(FFSoundDevice, device, result) - { + FF_LIST_FOR_EACH (FFSoundDevice, device, result) { ffStrbufDestroy(&device->identifier); ffStrbufDestroy(&device->name); ffStrbufDestroy(&device->platformApi); @@ -209,16 +203,14 @@ bool ffGenerateSoundJsonResult(FF_MAYBE_UNUSED FFSoundOptions* options, yyjson_m return true; } -void ffInitSoundOptions(FFSoundOptions* options) -{ +void ffInitSoundOptions(FFSoundOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); options->soundType = FF_SOUND_TYPE_MAIN; - options->percent = (FFPercentageModuleConfig) { 80, 90, 0 }; + options->percent = (FFPercentageModuleConfig) {80, 90, 0}; } -void ffDestroySoundOptions(FFSoundOptions* options) -{ +void ffDestroySoundOptions(FFSoundOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -238,5 +230,4 @@ FFModuleBaseInfo ffSoundModuleInfo = { {"Identifier", "identifier"}, {"Volume (in percentage bar)", "volume-percentage-bar"}, {"Platform API used", "platform-api"}, - })) -}; + }))}; diff --git a/src/modules/swap/option.h b/src/modules/swap/option.h index 2d9691100..860da9c28 100644 --- a/src/modules/swap/option.h +++ b/src/modules/swap/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFSwapOptions -{ +typedef struct FFSwapOptions { FFModuleArgs moduleArgs; FFPercentageModuleConfig percent; diff --git a/src/modules/swap/swap.c b/src/modules/swap/swap.c index 1511b6a4f..ff48980ef 100644 --- a/src/modules/swap/swap.c +++ b/src/modules/swap/swap.c @@ -6,25 +6,22 @@ #include "detection/swap/swap.h" #include "modules/swap/swap.h" -void printSwap(FFSwapOptions* options, uint8_t index, FFSwapResult* storage) -{ +void printSwap(FFSwapOptions* options, uint8_t index, FFSwapResult* storage) { FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate(); - if (options->moduleArgs.key.length == 0) - { - if (storage->name.length > 0) + if (options->moduleArgs.key.length == 0) { + if (storage->name.length > 0) { ffStrbufSetF(&key, "%s (%s)", FF_SWAP_MODULE_NAME, storage->name.chars); - else + } else { ffStrbufSetS(&key, FF_SWAP_MODULE_NAME); - } - else - { + } + } else { ffStrbufClear(&key); FF_PARSE_FORMAT_STRING_CHECKED(&key, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(storage->name, "name"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(storage->name, "name"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } FF_STRBUF_AUTO_DESTROY usedPretty = ffStrbufCreate(); @@ -38,86 +35,76 @@ void printSwap(FFSwapOptions* options, uint8_t index, FFSwapResult* storage) : (double) storage->bytesUsed / (double) storage->bytesTotal * 100.0; FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); FF_STRBUF_AUTO_DESTROY str = ffStrbufCreate(); - if (storage->bytesTotal == 0) - { - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + if (storage->bytesTotal == 0) { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&str, 0, options->percent, &options->moduleArgs); ffStrbufAppendC(&str, ' '); } - if(!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppendS(&str, "Disabled"); - else + } else { ffPercentAppendNum(&str, 0, options->percent, str.length > 0, &options->moduleArgs); - } - else - { - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + } + } else { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&str, percentage, options->percent, &options->moduleArgs); ffStrbufAppendC(&str, ' '); } - if(!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppendF(&str, "%s / %s ", usedPretty.chars, totalPretty.chars); + } - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&str, percentage, options->percent, str.length > 0, &options->moduleArgs); + } } ffStrbufTrimRight(&str, ' '); ffStrbufPutTo(&str, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY percentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&percentageNum, percentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY percentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&percentageBar, percentage, options->percent, &options->moduleArgs); - FF_PRINT_FORMAT_CHECKED(key.chars, index, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]){ - FF_ARG(usedPretty, "used"), - FF_ARG(totalPretty, "total"), - FF_ARG(percentageNum, "percentage"), - FF_ARG(percentageBar, "percentage-bar"), - FF_ARG(storage->name, "name"), - })); + } + FF_PRINT_FORMAT_CHECKED(key.chars, index, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { + FF_ARG(usedPretty, "used"), + FF_ARG(totalPretty, "total"), + FF_ARG(percentageNum, "percentage"), + FF_ARG(percentageBar, "percentage-bar"), + FF_ARG(storage->name, "name"), + })); } } -bool ffPrintSwap(FFSwapOptions* options) -{ +bool ffPrintSwap(FFSwapOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFSwapResult)); const char* error = ffDetectSwap(&result); - if(error) - { + if (error) { ffPrintError(FF_SWAP_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if (options->separate) - { + if (options->separate) { uint8_t index = 0; - FF_LIST_FOR_EACH(FFSwapResult, storage, result) - { + FF_LIST_FOR_EACH (FFSwapResult, storage, result) { ++index; printSwap(options, index, storage); } - } - else - { + } else { FFSwapResult total = { .name = ffStrbufCreate(), }; - FF_LIST_FOR_EACH(FFSwapResult, storage, result) - { + FF_LIST_FOR_EACH (FFSwapResult, storage, result) { total.bytesUsed += storage->bytesUsed; total.bytesTotal += storage->bytesTotal; } @@ -125,28 +112,26 @@ bool ffPrintSwap(FFSwapOptions* options) ffStrbufDestroy(&total.name); } - FF_LIST_FOR_EACH(FFSwapResult, storage, result) - { + FF_LIST_FOR_EACH (FFSwapResult, storage, result) { ffStrbufDestroy(&storage->name); } return true; } -void ffParseSwapJsonObject(FFSwapOptions* options, yyjson_val* module) -{ +void ffParseSwapJsonObject(FFSwapOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } - if (unsafe_yyjson_equals_str(key, "separate")) - { + if (unsafe_yyjson_equals_str(key, "separate")) { options->separate = yyjson_get_bool(val); continue; } @@ -155,51 +140,44 @@ void ffParseSwapJsonObject(FFSwapOptions* options, yyjson_val* module) } } -void ffGenerateSwapJsonConfig(FFSwapOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateSwapJsonConfig(FFSwapOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffPercentGenerateJsonConfig(doc, module, options->percent); ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "separate", options->separate); } -bool ffGenerateSwapJsonResult(FF_MAYBE_UNUSED FFSwapOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateSwapJsonResult(FF_MAYBE_UNUSED FFSwapOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFSwapResult)); const char* error = ffDetectSwap(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFSwapResult, storage, result) - { + FF_LIST_FOR_EACH (FFSwapResult, storage, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &storage->name); yyjson_mut_obj_add_uint(doc, obj, "used", storage->bytesUsed); yyjson_mut_obj_add_uint(doc, obj, "total", storage->bytesTotal); } - FF_LIST_FOR_EACH(FFSwapResult, storage, result) - { + FF_LIST_FOR_EACH (FFSwapResult, storage, result) { ffStrbufDestroy(&storage->name); } return true; } -void ffInitSwapOptions(FFSwapOptions* options) -{ +void ffInitSwapOptions(FFSwapOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰓡"); - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; options->separate = false; } -void ffDestroySwapOptions(FFSwapOptions* options) -{ +void ffDestroySwapOptions(FFSwapOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -218,5 +196,4 @@ FFModuleBaseInfo ffSwapModuleInfo = { {"Percentage used (num)", "percentage"}, {"Percentage used (bar)", "percentage-bar"}, {"Name", "name"}, - })) -}; + }))}; diff --git a/src/modules/terminal/option.h b/src/modules/terminal/option.h index 49b005e03..79f69705f 100644 --- a/src/modules/terminal/option.h +++ b/src/modules/terminal/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFTerminalOptions -{ +typedef struct FFTerminalOptions { FFModuleArgs moduleArgs; } FFTerminalOptions; diff --git a/src/modules/terminal/terminal.c b/src/modules/terminal/terminal.c index 4595b729c..78c523ccb 100644 --- a/src/modules/terminal/terminal.c +++ b/src/modules/terminal/terminal.c @@ -4,66 +4,58 @@ #include "detection/terminalshell/terminalshell.h" #include "modules/terminal/terminal.h" -bool ffPrintTerminal(FFTerminalOptions* options) -{ +bool ffPrintTerminal(FFTerminalOptions* options) { const FFTerminalResult* result = ffDetectTerminal(); - if(result->processName.length == 0) - { + if (result->processName.length == 0) { ffPrintError(FF_TERMINAL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Couldn't detect terminal"); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_TERMINAL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if(result->version.length) + if (result->version.length) { printf("%s %s\n", result->prettyName.chars, result->version.chars); - else + } else { ffStrbufPutTo(&result->prettyName, stdout); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_TERMINAL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result->processName, "process-name"), - FF_ARG(result->exe, "exe"), - FF_ARG(result->exeName, "exe-name"), - FF_ARG(result->pid, "pid"), - FF_ARG(result->prettyName, "pretty-name"), - FF_ARG(result->version, "version"), - FF_ARG(result->exePath, "exe-path"), - FF_ARG(result->tty, "tty"), - })); + } + } else { + FF_PRINT_FORMAT_CHECKED(FF_TERMINAL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result->processName, "process-name"), + FF_ARG(result->exe, "exe"), + FF_ARG(result->exeName, "exe-name"), + FF_ARG(result->pid, "pid"), + FF_ARG(result->prettyName, "pretty-name"), + FF_ARG(result->version, "version"), + FF_ARG(result->exePath, "exe-path"), + FF_ARG(result->tty, "tty"), + })); } return true; } -void ffParseTerminalJsonObject(FFTerminalOptions* options, yyjson_val* module) -{ +void ffParseTerminalJsonObject(FFTerminalOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_TERMINAL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateTerminalJsonConfig(FFTerminalOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateTerminalJsonConfig(FFTerminalOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalJsonResult(FF_MAYBE_UNUSED FFTerminalOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateTerminalJsonResult(FF_MAYBE_UNUSED FFTerminalOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFTerminalResult* result = ffDetectTerminal(); - if(result->processName.length == 0) - { + if (result->processName.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "Couldn't detect terminal"); return false; } @@ -82,13 +74,11 @@ bool ffGenerateTerminalJsonResult(FF_MAYBE_UNUSED FFTerminalOptions* options, yy return true; } -void ffInitTerminalOptions(FFTerminalOptions* options) -{ +void ffInitTerminalOptions(FFTerminalOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyTerminalOptions(FFTerminalOptions* options) -{ +void ffDestroyTerminalOptions(FFTerminalOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -110,5 +100,4 @@ FFModuleBaseInfo ffTerminalModuleInfo = { {"Terminal version", "version"}, {"Terminal full exe path", "exe-path"}, {"Terminal tty / pts used", "tty"}, - })) -}; + }))}; diff --git a/src/modules/terminalfont/option.h b/src/modules/terminalfont/option.h index db652adce..6da3d1e61 100644 --- a/src/modules/terminalfont/option.h +++ b/src/modules/terminalfont/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFTerminalFontOptions -{ +typedef struct FFTerminalFontOptions { FFModuleArgs moduleArgs; } FFTerminalFontOptions; diff --git a/src/modules/terminalfont/terminalfont.c b/src/modules/terminalfont/terminalfont.c index e0f02874c..c2e28330d 100644 --- a/src/modules/terminalfont/terminalfont.c +++ b/src/modules/terminalfont/terminalfont.c @@ -6,39 +6,31 @@ #define FF_TERMINALFONT_DISPLAY_NAME "Terminal Font" -bool ffPrintTerminalFont(FFTerminalFontOptions* options) -{ +bool ffPrintTerminalFont(FFTerminalFontOptions* options) { bool success = false; FFTerminalFontResult terminalFont; ffFontInit(&terminalFont.font); ffFontInit(&terminalFont.fallback); ffStrbufInit(&terminalFont.error); - if(!ffDetectTerminalFont(&terminalFont)) - { + if (!ffDetectTerminalFont(&terminalFont)) { ffPrintError(FF_TERMINALFONT_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", terminalFont.error.chars); - } - else - { - if(options->moduleArgs.outputFormat.length == 0) - { + } else { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_TERMINALFONT_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&terminalFont.font.pretty, stdout); - if(terminalFont.fallback.pretty.length) - { + if (terminalFont.fallback.pretty.length) { fputs(" / ", stdout); ffStrbufWriteTo(&terminalFont.fallback.pretty, stdout); } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_TERMINALFONT_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(terminalFont.font.pretty, "combined"), - FF_ARG(terminalFont.font.name, "name"), - FF_ARG(terminalFont.font.size, "size"), - FF_ARG(terminalFont.font.styles, "styles"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_TERMINALFONT_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(terminalFont.font.pretty, "combined"), + FF_ARG(terminalFont.font.name, "name"), + FF_ARG(terminalFont.font.size, "size"), + FF_ARG(terminalFont.font.styles, "styles"), + })); } success = true; } @@ -50,44 +42,39 @@ bool ffPrintTerminalFont(FFTerminalFontOptions* options) return success; } -void ffParseTerminalFontJsonObject(FFTerminalFontOptions* options, yyjson_val* module) -{ +void ffParseTerminalFontJsonObject(FFTerminalFontOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_TERMINALFONT_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateTerminalFontJsonConfig(FFTerminalFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateTerminalFontJsonConfig(FFTerminalFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalFontJsonResult(FF_MAYBE_UNUSED FFTerminalFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateTerminalFontJsonResult(FF_MAYBE_UNUSED FFTerminalFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFTerminalFontResult result; ffFontInit(&result.font); ffFontInit(&result.fallback); ffStrbufInit(&result.error); - if(!ffDetectTerminalFont(&result)) + if (!ffDetectTerminalFont(&result)) { yyjson_mut_obj_add_strbuf(doc, module, "error", &result.error); - else - { + } else { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); yyjson_mut_val* font = yyjson_mut_obj_add_obj(doc, obj, "font"); yyjson_mut_obj_add_strbuf(doc, font, "name", &result.font.name); yyjson_mut_obj_add_strbuf(doc, font, "size", &result.font.size); yyjson_mut_val* fontStyles = yyjson_mut_obj_add_arr(doc, font, "styles"); - FF_LIST_FOR_EACH(FFstrbuf, style, result.font.styles) - { + FF_LIST_FOR_EACH (FFstrbuf, style, result.font.styles) { yyjson_mut_arr_add_strbuf(doc, fontStyles, style); } yyjson_mut_obj_add_strbuf(doc, font, "pretty", &result.font.pretty); @@ -96,8 +83,7 @@ bool ffGenerateTerminalFontJsonResult(FF_MAYBE_UNUSED FFTerminalFontOptions* opt yyjson_mut_obj_add_strbuf(doc, fallback, "name", &result.fallback.name); yyjson_mut_obj_add_strbuf(doc, fallback, "size", &result.fallback.size); yyjson_mut_val* fallbackStyles = yyjson_mut_obj_add_arr(doc, fallback, "styles"); - FF_LIST_FOR_EACH(FFstrbuf, style, result.fallback.styles) - { + FF_LIST_FOR_EACH (FFstrbuf, style, result.fallback.styles) { yyjson_mut_arr_add_strbuf(doc, fallbackStyles, style); } yyjson_mut_obj_add_strbuf(doc, fallback, "pretty", &result.fallback.pretty); @@ -110,13 +96,11 @@ bool ffGenerateTerminalFontJsonResult(FF_MAYBE_UNUSED FFTerminalFontOptions* opt return success; } -void ffInitTerminalFontOptions(FFTerminalFontOptions* options) -{ +void ffInitTerminalFontOptions(FFTerminalFontOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyTerminalFontOptions(FFTerminalFontOptions* options) -{ +void ffDestroyTerminalFontOptions(FFTerminalFontOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } diff --git a/src/modules/terminalsize/option.h b/src/modules/terminalsize/option.h index 518856a8c..482f7548f 100644 --- a/src/modules/terminalsize/option.h +++ b/src/modules/terminalsize/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFTerminalSizeOptions -{ +typedef struct FFTerminalSizeOptions { FFModuleArgs moduleArgs; } FFTerminalSizeOptions; diff --git a/src/modules/terminalsize/terminalsize.c b/src/modules/terminalsize/terminalsize.c index 413060995..73eb8d312 100644 --- a/src/modules/terminalsize/terminalsize.c +++ b/src/modules/terminalsize/terminalsize.c @@ -6,62 +6,54 @@ #define FF_TERMINALSIZE_DISPLAY_NAME "Terminal Size" -bool ffPrintTerminalSize(FFTerminalSizeOptions* options) -{ +bool ffPrintTerminalSize(FFTerminalSizeOptions* options) { FFTerminalSizeResult result = {}; - if(!ffDetectTerminalSize(&result)) - { + if (!ffDetectTerminalSize(&result)) { ffPrintError(FF_TERMINALSIZE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Failed to detect terminal size"); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_TERMINALSIZE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); printf("%u columns x %u rows", result.columns, result.rows); - if (result.width != 0 && result.height != 0) + if (result.width != 0 && result.height != 0) { printf(" (%upx x %upx)", result.width, result.height); + } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_TERMINALSIZE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result.rows, "rows"), - FF_ARG(result.columns, "columns"), - FF_ARG(result.width, "width"), - FF_ARG(result.height, "height"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_TERMINALSIZE_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result.rows, "rows"), + FF_ARG(result.columns, "columns"), + FF_ARG(result.width, "width"), + FF_ARG(result.height, "height"), + })); } return true; } -void ffParseTerminalSizeJsonObject(FFTerminalSizeOptions* options, yyjson_val* module) -{ +void ffParseTerminalSizeJsonObject(FFTerminalSizeOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_TERMINALSIZE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateTerminalSizeJsonConfig(FFTerminalSizeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateTerminalSizeJsonConfig(FFTerminalSizeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalSizeJsonResult(FF_MAYBE_UNUSED FFTerminalSizeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateTerminalSizeJsonResult(FF_MAYBE_UNUSED FFTerminalSizeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFTerminalSizeResult result; - if(!ffDetectTerminalSize(&result)) - { + if (!ffDetectTerminalSize(&result)) { yyjson_mut_obj_add_str(doc, module, "error", "Failed to detect terminal size"); return false; } @@ -75,13 +67,11 @@ bool ffGenerateTerminalSizeJsonResult(FF_MAYBE_UNUSED FFTerminalSizeOptions* opt return true; } -void ffInitTerminalSizeOptions(FFTerminalSizeOptions* options) -{ +void ffInitTerminalSizeOptions(FFTerminalSizeOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰲎"); } -void ffDestroyTerminalSizeOptions(FFTerminalSizeOptions* options) -{ +void ffDestroyTerminalSizeOptions(FFTerminalSizeOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } diff --git a/src/modules/terminaltheme/option.h b/src/modules/terminaltheme/option.h index 3d8cdc252..25a0cc336 100644 --- a/src/modules/terminaltheme/option.h +++ b/src/modules/terminaltheme/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFTerminalThemeOptions -{ +typedef struct FFTerminalThemeOptions { FFModuleArgs moduleArgs; } FFTerminalThemeOptions; diff --git a/src/modules/terminaltheme/terminaltheme.c b/src/modules/terminaltheme/terminaltheme.c index f20233d4c..1468b9bef 100644 --- a/src/modules/terminaltheme/terminaltheme.c +++ b/src/modules/terminaltheme/terminaltheme.c @@ -8,66 +8,61 @@ #define FF_TERMINALTHEME_DISPLAY_NAME "Terminal Theme" -bool ffPrintTerminalTheme(FFTerminalThemeOptions* options) -{ +bool ffPrintTerminalTheme(FFTerminalThemeOptions* options) { FFTerminalThemeResult result = {}; - if(!ffDetectTerminalTheme(&result, false)) - { + if (!ffDetectTerminalTheme(&result, false)) { ffPrintError(FF_TERMINALTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Failed to detect terminal theme"); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_TERMINALTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); printf("#%02" PRIX16 "%02" PRIX16 "%02" PRIX16 " (FG) - #%02" PRIX16 "%02" PRIX16 "%02" PRIX16 " (BG) [%s]\n", - result.fg.r, result.fg.g, result.fg.b, - result.bg.r, result.bg.g, result.bg.b, + result.fg.r, + result.fg.g, + result.fg.b, + result.bg.r, + result.bg.g, + result.bg.b, result.bg.dark ? "Dark" : "Light"); - } - else - { + } else { char fg[32], bg[32]; const char* fgType = result.fg.dark ? "Dark" : "Light"; const char* bgType = result.bg.dark ? "Dark" : "Light"; snprintf(fg, ARRAY_SIZE(fg), "#%02" PRIX16 "%02" PRIX16 "%02" PRIX16, result.fg.r, result.fg.g, result.fg.b); snprintf(bg, ARRAY_SIZE(bg), "#%02" PRIX16 "%02" PRIX16 "%02" PRIX16, result.bg.r, result.bg.g, result.bg.b); - FF_PRINT_FORMAT_CHECKED(FF_TERMINALTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(fg, "fg-color"), - FF_ARG(fgType, "fg-type"), - FF_ARG(bg, "bg-color"), - FF_ARG(bgType, "bg-type"), - })); + FF_PRINT_FORMAT_CHECKED(FF_TERMINALTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(fg, "fg-color"), + FF_ARG(fgType, "fg-type"), + FF_ARG(bg, "bg-color"), + FF_ARG(bgType, "bg-type"), + })); } return true; } -void ffParseTerminalThemeJsonObject(FFTerminalThemeOptions* options, yyjson_val* module) -{ +void ffParseTerminalThemeJsonObject(FFTerminalThemeOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_TERMINALTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateTerminalThemeJsonConfig(FFTerminalThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateTerminalThemeJsonConfig(FFTerminalThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalThemeJsonResult(FF_MAYBE_UNUSED FFTerminalThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateTerminalThemeJsonResult(FF_MAYBE_UNUSED FFTerminalThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFTerminalThemeResult result = {}; - if(!ffDetectTerminalTheme(&result, false)) - { + if (!ffDetectTerminalTheme(&result, false)) { yyjson_mut_obj_add_str(doc, module, "error", "Failed to detect terminal theme"); return false; } @@ -89,13 +84,11 @@ bool ffGenerateTerminalThemeJsonResult(FF_MAYBE_UNUSED FFTerminalThemeOptions* o return true; } -void ffInitTerminalThemeOptions(FFTerminalThemeOptions* options) -{ +void ffInitTerminalThemeOptions(FFTerminalThemeOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰔎"); } -void ffDestroyTerminalThemeOptions(FFTerminalThemeOptions* options) -{ +void ffDestroyTerminalThemeOptions(FFTerminalThemeOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -113,5 +106,4 @@ FFModuleBaseInfo ffTerminalThemeModuleInfo = { {"Terminal foreground type (Dark / Light)", "fg-type"}, {"Terminal background color", "bg-color"}, {"Terminal background type (Dark / Light)", "bg-type"}, - })) -}; + }))}; diff --git a/src/modules/theme/option.h b/src/modules/theme/option.h index ca232bfb9..66a68baa3 100644 --- a/src/modules/theme/option.h +++ b/src/modules/theme/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFThemeOptions -{ +typedef struct FFThemeOptions { FFModuleArgs moduleArgs; } FFThemeOptions; diff --git a/src/modules/theme/theme.c b/src/modules/theme/theme.c index 751873ee3..e119f9b5f 100644 --- a/src/modules/theme/theme.c +++ b/src/modules/theme/theme.c @@ -4,39 +4,34 @@ #include "detection/theme/theme.h" #include "modules/theme/theme.h" -bool ffPrintTheme(FFThemeOptions* options) -{ +bool ffPrintTheme(FFThemeOptions* options) { FFThemeResult result = { .theme1 = ffStrbufCreate(), - .theme2 = ffStrbufCreate() - }; + .theme2 = ffStrbufCreate()}; const char* error = ffDetectTheme(&result); - if(error) - { + if (error) { ffPrintError(FF_THEME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_THEME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (result.theme1.length) + if (result.theme1.length) { ffStrbufWriteTo(&result.theme1, stdout); - if (result.theme2.length) - { - if (result.theme1.length) + } + if (result.theme2.length) { + if (result.theme1.length) { fputs(", ", stdout); + } ffStrbufWriteTo(&result.theme2, stdout); } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_THEME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result.theme1, "theme1"), - FF_ARG(result.theme2, "theme2"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_THEME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result.theme1, "theme1"), + FF_ARG(result.theme2, "theme2"), + })); } ffStrbufDestroy(&result.theme1); @@ -44,34 +39,29 @@ bool ffPrintTheme(FFThemeOptions* options) return true; } -void ffParseThemeJsonObject(FFThemeOptions* options, yyjson_val* module) -{ +void ffParseThemeJsonObject(FFThemeOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_THEME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateThemeJsonConfig(FFThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateThemeJsonConfig(FFThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateThemeJsonResult(FF_MAYBE_UNUSED FFThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateThemeJsonResult(FF_MAYBE_UNUSED FFThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFThemeResult result = { .theme1 = ffStrbufCreate(), - .theme2 = ffStrbufCreate() - }; + .theme2 = ffStrbufCreate()}; const char* error = ffDetectTheme(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -86,13 +76,11 @@ bool ffGenerateThemeJsonResult(FF_MAYBE_UNUSED FFThemeOptions* options, yyjson_m return true; } -void ffInitThemeOptions(FFThemeOptions* options) -{ +void ffInitThemeOptions(FFThemeOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰉼"); } -void ffDestroyThemeOptions(FFThemeOptions* options) -{ +void ffDestroyThemeOptions(FFThemeOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -108,5 +96,4 @@ FFModuleBaseInfo ffThemeModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Theme part 1", "theme1"}, {"Theme part 2", "theme2"}, - })) -}; + }))}; diff --git a/src/modules/title/option.h b/src/modules/title/option.h index 16505d39b..e66fdbab4 100644 --- a/src/modules/title/option.h +++ b/src/modules/title/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFTitleOptions -{ +typedef struct FFTitleOptions { FFModuleArgs moduleArgs; FFstrbuf colorUser; diff --git a/src/modules/title/title.c b/src/modules/title/title.c index 75c261b8b..df7a1a447 100644 --- a/src/modules/title/title.c +++ b/src/modules/title/title.c @@ -3,125 +3,124 @@ #include "common/textModifier.h" #include "modules/title/title.h" -static void appendText(FFstrbuf* output, const FFstrbuf* text, const FFstrbuf* color) -{ - if (!instance.config.display.pipe) - { - if (instance.config.display.brightColor) +static void appendText(FFstrbuf* output, const FFstrbuf* text, const FFstrbuf* color) { + if (!instance.config.display.pipe) { + if (instance.config.display.brightColor) { ffStrbufAppendS(output, FASTFETCH_TEXT_MODIFIER_BOLT); - if (color->length > 0) + } + if (color->length > 0) { ffStrbufAppendF(output, "\e[%sm", color->chars); - else if (instance.config.display.colorTitle.length > 0) + } else if (instance.config.display.colorTitle.length > 0) { ffStrbufAppendF(output, "\e[%sm", instance.config.display.colorTitle.chars); + } } ffStrbufAppend(output, text); - if(!instance.config.display.pipe) + if (!instance.config.display.pipe) { ffStrbufAppendS(output, FASTFETCH_TEXT_MODIFIER_RESET); + } } -bool ffPrintTitle(FFTitleOptions* options) -{ +bool ffPrintTitle(FFTitleOptions* options) { FF_STRBUF_AUTO_DESTROY userNameColored = ffStrbufCreate(); appendText(&userNameColored, &instance.state.platform.userName, &options->colorUser); FF_STRBUF_AUTO_DESTROY hostName = ffStrbufCreateCopy(&instance.state.platform.hostName); - if (!options->fqdn) + if (!options->fqdn) { ffStrbufSubstrBeforeFirstC(&hostName, '.'); + } instance.state.titleFqdn = options->fqdn; FF_STRBUF_AUTO_DESTROY hostNameColored = ffStrbufCreate(); appendText(&hostNameColored, &hostName, &options->colorHost); FF_STRBUF_AUTO_DESTROY atColored = ffStrbufCreate(); - if (!instance.config.display.pipe && options->colorAt.length > 0) - { + if (!instance.config.display.pipe && options->colorAt.length > 0) { ffStrbufAppendF(&atColored, "\e[%sm", options->colorAt.chars); ffStrbufAppendC(&atColored, '@'); ffStrbufAppendS(&atColored, FASTFETCH_TEXT_MODIFIER_RESET); - } - else + } else { ffStrbufAppendC(&atColored, '@'); + } - if (options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_TITLE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&userNameColored, stdout); ffStrbufWriteTo(&atColored, stdout); ffStrbufPutTo(&hostNameColored, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY cwdTilde = ffStrbufCreate(); if ( - #if _WIN32 - ffStrbufStartsWithIgnCase - #else - ffStrbufStartsWith - #endif - (&instance.state.platform.cwd, &instance.state.platform.homeDir)) - { +#if _WIN32 + ffStrbufStartsWithIgnCase +#else + ffStrbufStartsWith +#endif + (&instance.state.platform.cwd, &instance.state.platform.homeDir)) { ffStrbufAppendS(&cwdTilde, "~/"); ffStrbufAppendNS(&cwdTilde, instance.state.platform.cwd.length - instance.state.platform.homeDir.length, &instance.state.platform.cwd.chars[instance.state.platform.homeDir.length]); - } - else + } else { ffStrbufSet(&cwdTilde, &instance.state.platform.cwd); - if (cwdTilde.length > 1) ffStrbufTrimRight(&cwdTilde, '/'); + } + if (cwdTilde.length > 1) { + ffStrbufTrimRight(&cwdTilde, '/'); + } - FF_PRINT_FORMAT_CHECKED(FF_TITLE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(instance.state.platform.userName, "user-name"), - FF_ARG(hostName, "host-name"), - FF_ARG(instance.state.platform.homeDir, "home-dir"), - FF_ARG(instance.state.platform.exePath, "exe-path"), - FF_ARG(instance.state.platform.userShell, "user-shell"), - FF_ARG(userNameColored, "user-name-colored"), - FF_ARG(atColored, "at-symbol-colored"), - FF_ARG(hostNameColored, "host-name-colored"), - FF_ARG(instance.state.platform.fullUserName, "full-user-name"), - #ifndef _WIN32 - FF_ARG(instance.state.platform.uid, "user-id"), - #else - FF_ARG(instance.state.platform.sid, "user-id"), - #endif - FF_ARG(instance.state.platform.pid, "pid"), - FF_ARG(cwdTilde, "cwd"), - })); + FF_PRINT_FORMAT_CHECKED(FF_TITLE_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(instance.state.platform.userName, "user-name"), + FF_ARG(hostName, "host-name"), + FF_ARG(instance.state.platform.homeDir, "home-dir"), + FF_ARG(instance.state.platform.exePath, "exe-path"), + FF_ARG(instance.state.platform.userShell, "user-shell"), + FF_ARG(userNameColored, "user-name-colored"), + FF_ARG(atColored, "at-symbol-colored"), + FF_ARG(hostNameColored, "host-name-colored"), + FF_ARG(instance.state.platform.fullUserName, "full-user-name"), +#ifndef _WIN32 + FF_ARG(instance.state.platform.uid, "user-id"), +#else + FF_ARG(instance.state.platform.sid, "user-id"), +#endif + FF_ARG(instance.state.platform.pid, "pid"), + FF_ARG(cwdTilde, "cwd"), + })); } return true; } -void ffParseTitleJsonObject(FFTitleOptions* options, yyjson_val* module) -{ +void ffParseTitleJsonObject(FFTitleOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "fqdn")) - { + if (unsafe_yyjson_equals_str(key, "fqdn")) { options->fqdn = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "color")) - { - if (!yyjson_is_obj(val)) + if (unsafe_yyjson_equals_str(key, "color")) { + if (!yyjson_is_obj(val)) { continue; + } yyjson_val* color = yyjson_obj_get(val, "user"); - if (color) + if (color) { ffOptionParseColor(yyjson_get_str(color), &options->colorUser); + } color = yyjson_obj_get(val, "at"); - if (color) + if (color) { ffOptionParseColor(yyjson_get_str(color), &options->colorAt); + } color = yyjson_obj_get(val, "host"); - if (color) + if (color) { ffOptionParseColor(yyjson_get_str(color), &options->colorHost); + } continue; } @@ -129,8 +128,7 @@ void ffParseTitleJsonObject(FFTitleOptions* options, yyjson_val* module) } } -void ffGenerateTitleJsonConfig(FFTitleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateTitleJsonConfig(FFTitleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "fqdn", options->fqdn); @@ -141,14 +139,13 @@ void ffGenerateTitleJsonConfig(FFTitleOptions* options, yyjson_mut_doc* doc, yyj yyjson_mut_obj_add_strbuf(doc, color, "host", &options->colorHost); } -bool ffGenerateTitleJsonResult(FF_MAYBE_UNUSED FFTitleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateTitleJsonResult(FF_MAYBE_UNUSED FFTitleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); - #ifdef _WIN32 +#ifdef _WIN32 yyjson_mut_obj_add_strbuf(doc, obj, "userId", &instance.state.platform.sid); - #else +#else yyjson_mut_obj_add_uint(doc, obj, "userId", instance.state.platform.uid); - #endif +#endif yyjson_mut_obj_add_strbuf(doc, obj, "userName", &instance.state.platform.userName); yyjson_mut_obj_add_strbuf(doc, obj, "fullUserName", &instance.state.platform.fullUserName); yyjson_mut_obj_add_strbuf(doc, obj, "hostName", &instance.state.platform.hostName); @@ -161,8 +158,7 @@ bool ffGenerateTitleJsonResult(FF_MAYBE_UNUSED FFTitleOptions* options, yyjson_m return true; } -void ffInitTitleOptions(FFTitleOptions* options) -{ +void ffInitTitleOptions(FFTitleOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); ffStrbufSetStatic(&options->moduleArgs.key, " "); @@ -172,8 +168,7 @@ void ffInitTitleOptions(FFTitleOptions* options) ffStrbufInit(&options->colorHost); } -void ffDestroyTitleOptions(FFTitleOptions* options) -{ +void ffDestroyTitleOptions(FFTitleOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->colorUser); ffStrbufDestroy(&options->colorAt); @@ -202,5 +197,4 @@ FFModuleBaseInfo ffTitleModuleInfo = { {"UID (*nix) / SID (Windows)", "user-id"}, {"PID of current process", "pid"}, {"CWD with home dir replaced by `~`", "cwd"}, - })) -}; + }))}; diff --git a/src/modules/tpm/option.h b/src/modules/tpm/option.h index 19fb79029..d40806fc7 100644 --- a/src/modules/tpm/option.h +++ b/src/modules/tpm/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFTPMOptions -{ +typedef struct FFTPMOptions { FFModuleArgs moduleArgs; } FFTPMOptions; diff --git a/src/modules/tpm/tpm.c b/src/modules/tpm/tpm.c index 748d4cd03..e7fb17dbe 100644 --- a/src/modules/tpm/tpm.c +++ b/src/modules/tpm/tpm.c @@ -4,34 +4,29 @@ #include "detection/tpm/tpm.h" #include "modules/tpm/tpm.h" -bool ffPrintTPM(FFTPMOptions* options) -{ +bool ffPrintTPM(FFTPMOptions* options) { FFTPMResult result = { .version = ffStrbufCreate(), - .description = ffStrbufCreate() - }; + .description = ffStrbufCreate()}; const char* error = ffDetectTPM(&result); - if(error) - { + if (error) { ffPrintError(FF_TPM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_TPM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (result.description.length > 0) + if (result.description.length > 0) { ffStrbufPutTo(&result.description, stdout); - else + } else { ffStrbufPutTo(&result.version, stdout); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_TPM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result.version, "version"), - FF_ARG(result.description, "description"), - })); + } + } else { + FF_PRINT_FORMAT_CHECKED(FF_TPM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result.version, "version"), + FF_ARG(result.description, "description"), + })); } ffStrbufDestroy(&result.version); @@ -40,34 +35,29 @@ bool ffPrintTPM(FFTPMOptions* options) return true; } -void ffParseTPMJsonObject(FFTPMOptions* options, yyjson_val* module) -{ +void ffParseTPMJsonObject(FFTPMOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_TPM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateTPMJsonConfig(FFTPMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateTPMJsonConfig(FFTPMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTPMJsonResult(FF_MAYBE_UNUSED FFTPMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateTPMJsonResult(FF_MAYBE_UNUSED FFTPMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFTPMResult result = { .version = ffStrbufCreate(), - .description = ffStrbufCreate() - }; + .description = ffStrbufCreate()}; const char* error = ffDetectTPM(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -82,13 +72,11 @@ bool ffGenerateTPMJsonResult(FF_MAYBE_UNUSED FFTPMOptions* options, yyjson_mut_d return true; } -void ffInitTPMOptions(FFTPMOptions* options) -{ +void ffInitTPMOptions(FFTPMOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyTPMOptions(FFTPMOptions* options) -{ +void ffDestroyTPMOptions(FFTPMOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -104,5 +92,4 @@ FFModuleBaseInfo ffTPMModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"TPM device version", "version"}, {"TPM general description", "description"}, - })) -}; + }))}; diff --git a/src/modules/uptime/option.h b/src/modules/uptime/option.h index 4235995c5..34be61a29 100644 --- a/src/modules/uptime/option.h +++ b/src/modules/uptime/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFUptimeOptions -{ +typedef struct FFUptimeOptions { FFModuleArgs moduleArgs; } FFUptimeOptions; diff --git a/src/modules/uptime/uptime.c b/src/modules/uptime/uptime.c index 95da11501..6d3cf439a 100644 --- a/src/modules/uptime/uptime.c +++ b/src/modules/uptime/uptime.c @@ -6,14 +6,12 @@ #include "detection/uptime/uptime.h" #include "modules/uptime/uptime.h" -bool ffPrintUptime(FFUptimeOptions* options) -{ +bool ffPrintUptime(FFUptimeOptions* options) { FFUptimeResult result = {}; const char* error = ffDetectUptime(&result); - if(error) - { + if (error) { ffPrintError(FF_UPTIME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } @@ -22,13 +20,10 @@ bool ffPrintUptime(FFUptimeOptions* options) FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); ffDurationAppendNum((uptime + 500) / 1000, &buffer); - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_UPTIME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { uint32_t milliseconds = (uint32_t) (uptime % 1000); uptime /= 1000; uint32_t seconds = (uint32_t) (uptime % 60); @@ -41,48 +36,33 @@ bool ffPrintUptime(FFUptimeOptions* options) FFTimeGetAgeResult age = ffTimeGetAge(result.bootTime, ffTimeGetNow()); - FF_PRINT_FORMAT_CHECKED(FF_UPTIME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(days, "days"), - FF_ARG(hours, "hours"), - FF_ARG(minutes, "minutes"), - FF_ARG(seconds, "seconds"), - FF_ARG(milliseconds, "milliseconds"), - {FF_ARG_TYPE_STRING, ffTimeToShortStr(result.bootTime), "boot-time"}, - FF_ARG(age.years, "years"), - FF_ARG(age.daysOfYear, "days-of-year"), - FF_ARG(age.yearsFraction, "years-fraction"), - FF_ARG(buffer, "formatted") - })); + FF_PRINT_FORMAT_CHECKED(FF_UPTIME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) {FF_ARG(days, "days"), FF_ARG(hours, "hours"), FF_ARG(minutes, "minutes"), FF_ARG(seconds, "seconds"), FF_ARG(milliseconds, "milliseconds"), {FF_ARG_TYPE_STRING, ffTimeToShortStr(result.bootTime), "boot-time"}, FF_ARG(age.years, "years"), FF_ARG(age.daysOfYear, "days-of-year"), FF_ARG(age.yearsFraction, "years-fraction"), FF_ARG(buffer, "formatted")})); } return true; } -void ffParseUptimeJsonObject(FFUptimeOptions* options, yyjson_val* module) -{ +void ffParseUptimeJsonObject(FFUptimeOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_UPTIME_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateUptimeJsonConfig(FFUptimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateUptimeJsonConfig(FFUptimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateUptimeJsonResult(FF_MAYBE_UNUSED FFUptimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateUptimeJsonResult(FF_MAYBE_UNUSED FFUptimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFUptimeResult result; const char* error = ffDetectUptime(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -94,13 +74,11 @@ bool ffGenerateUptimeJsonResult(FF_MAYBE_UNUSED FFUptimeOptions* options, yyjson return true; } -void ffInitUptimeOptions(FFUptimeOptions* options) -{ +void ffInitUptimeOptions(FFUptimeOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyUptimeOptions(FFUptimeOptions* options) -{ +void ffDestroyUptimeOptions(FFUptimeOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -124,5 +102,4 @@ FFModuleBaseInfo ffUptimeModuleInfo = { {"Days of year after boot", "days-of-year"}, {"Years fraction after boot", "years-fraction"}, {"Formatted uptime", "formatted"}, - })) -}; + }))}; diff --git a/src/modules/users/option.h b/src/modules/users/option.h index 16ea5e88f..6863d49f9 100644 --- a/src/modules/users/option.h +++ b/src/modules/users/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFUsersOptions -{ +typedef struct FFUsersOptions { FFModuleArgs moduleArgs; bool compact; diff --git a/src/modules/users/users.c b/src/modules/users/users.c index 56c6cda66..51a471085 100644 --- a/src/modules/users/users.c +++ b/src/modules/users/users.c @@ -7,64 +7,55 @@ #pragma GCC diagnostic ignored "-Wformat" // warning: unknown conversion type character 'F' in format -bool ffPrintUsers(FFUsersOptions* options) -{ +bool ffPrintUsers(FFUsersOptions* options) { FF_LIST_AUTO_DESTROY users = ffListCreate(sizeof(FFUserResult)); const char* error = ffDetectUsers(options, &users); - if(error) - { + if (error) { ffPrintError(FF_USERS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(users.length == 0) - { + if (users.length == 0) { ffPrintError(FF_USERS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", "Unable to detect any users"); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { - if(options->compact) - { + if (options->moduleArgs.outputFormat.length == 0) { + if (options->compact) { ffPrintLogoAndKey(FF_USERS_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); - for(uint32_t i = 0; i < users.length; ++i) - { - if(i > 0) + for (uint32_t i = 0; i < users.length; ++i) { + if (i > 0) { ffStrbufAppendS(&result, ", "); + } FFUserResult* user = FF_LIST_GET(FFUserResult, users, i); ffStrbufAppend(&result, &user->name); } ffStrbufPutTo(&result, stdout); - } - else - { - for(uint32_t i = 0; i < users.length; ++i) - { + } else { + for (uint32_t i = 0; i < users.length; ++i) { FFUserResult* user = FF_LIST_GET(FFUserResult, users, i); ffPrintLogoAndKey(FF_USERS_MODULE_NAME, users.length == 1 ? 0 : (uint8_t) (i + 1), &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY result = ffStrbufCreateCopy(&user->name); - if(user->hostName.length) + if (user->hostName.length) { ffStrbufAppendF(&result, "@%s", user->hostName.chars); + } - if(user->loginTime) + if (user->loginTime) { ffStrbufAppendF(&result, " - login time %s", ffTimeToShortStr(user->loginTime)); + } ffStrbufPutTo(&result, stdout); } } - } - else - { + } else { uint64_t now = ffTimeGetNow(); - for(uint32_t i = 0; i < users.length; ++i) - { + for (uint32_t i = 0; i < users.length; ++i) { FFUserResult* user = FF_LIST_GET(FFUserResult, users, i); uint64_t duration = now - user->loginTime; @@ -80,26 +71,25 @@ bool ffPrintUsers(FFUsersOptions* options) FFTimeGetAgeResult age = ffTimeGetAge(user->loginTime, ffTimeGetNow()); - FF_PRINT_FORMAT_CHECKED(FF_USERS_MODULE_NAME, users.length == 1 ? 0 : (uint8_t) (i + 1), &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(user->name, "name"), - FF_ARG(user->hostName, "host-name"), - FF_ARG(user->sessionName, "session-name"), - FF_ARG(user->clientIp, "client-ip"), - {FF_ARG_TYPE_STRING, ffTimeToShortStr(user->loginTime), "login-time"}, - FF_ARG(days, "days"), - FF_ARG(hours, "hours"), - FF_ARG(minutes, "minutes"), - FF_ARG(seconds, "seconds"), - FF_ARG(milliseconds, "milliseconds"), - FF_ARG(age.years, "years"), - FF_ARG(age.daysOfYear, "days-of-year"), - FF_ARG(age.yearsFraction, "years-fraction"), - })); + FF_PRINT_FORMAT_CHECKED(FF_USERS_MODULE_NAME, users.length == 1 ? 0 : (uint8_t) (i + 1), &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(user->name, "name"), + FF_ARG(user->hostName, "host-name"), + FF_ARG(user->sessionName, "session-name"), + FF_ARG(user->clientIp, "client-ip"), + {FF_ARG_TYPE_STRING, ffTimeToShortStr(user->loginTime), "login-time"}, + FF_ARG(days, "days"), + FF_ARG(hours, "hours"), + FF_ARG(minutes, "minutes"), + FF_ARG(seconds, "seconds"), + FF_ARG(milliseconds, "milliseconds"), + FF_ARG(age.years, "years"), + FF_ARG(age.daysOfYear, "days-of-year"), + FF_ARG(age.yearsFraction, "years-fraction"), + })); } } - FF_LIST_FOR_EACH(FFUserResult, user, users) - { + FF_LIST_FOR_EACH (FFUserResult, user, users) { ffStrbufDestroy(&user->clientIp); ffStrbufDestroy(&user->hostName); ffStrbufDestroy(&user->sessionName); @@ -109,26 +99,24 @@ bool ffPrintUsers(FFUsersOptions* options) return true; } -void ffParseUsersJsonObject(FFUsersOptions* options, yyjson_val* module) -{ +void ffParseUsersJsonObject(FFUsersOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) + yyjson_obj_foreach (module, idx, max, key, val) { + if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition")) { continue; + } - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "compact")) - { + if (unsafe_yyjson_equals_str(key, "compact")) { options->compact = yyjson_get_bool(val); continue; } - if (unsafe_yyjson_equals_str(key, "myselfOnly")) - { + if (unsafe_yyjson_equals_str(key, "myselfOnly")) { options->myselfOnly = yyjson_get_bool(val); continue; } @@ -137,8 +125,7 @@ void ffParseUsersJsonObject(FFUsersOptions* options, yyjson_val* module) } } -void ffGenerateUsersJsonConfig(FFUsersOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateUsersJsonConfig(FFUsersOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "compact", options->compact); @@ -146,35 +133,32 @@ void ffGenerateUsersJsonConfig(FFUsersOptions* options, yyjson_mut_doc* doc, yyj yyjson_mut_obj_add_bool(doc, module, "myselfOnly", options->myselfOnly); } -bool ffGenerateUsersJsonResult(FFUsersOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateUsersJsonResult(FFUsersOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFUserResult)); const char* error = ffDetectUsers(options, &results); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFUserResult, user, results) - { + FF_LIST_FOR_EACH (FFUserResult, user, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &user->name); yyjson_mut_obj_add_strbuf(doc, obj, "hostName", &user->hostName); yyjson_mut_obj_add_strbuf(doc, obj, "sessionName", &user->sessionName); yyjson_mut_obj_add_strbuf(doc, obj, "clientIp", &user->clientIp); const char* pstr = ffTimeToFullStr(user->loginTime); - if (*pstr) + if (*pstr) { yyjson_mut_obj_add_strcpy(doc, obj, "loginTime", pstr); - else + } else { yyjson_mut_obj_add_null(doc, obj, "loginTime"); + } } - FF_LIST_FOR_EACH(FFUserResult, user, results) - { + FF_LIST_FOR_EACH (FFUserResult, user, results) { ffStrbufDestroy(&user->clientIp); ffStrbufDestroy(&user->hostName); ffStrbufDestroy(&user->sessionName); @@ -184,16 +168,14 @@ bool ffGenerateUsersJsonResult(FFUsersOptions* options, yyjson_mut_doc* doc, yyj return true; } -void ffInitUsersOptions(FFUsersOptions* options) -{ +void ffInitUsersOptions(FFUsersOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); options->compact = false; options->myselfOnly = false; } -void ffDestroyUsersOptions(FFUsersOptions* options) -{ +void ffDestroyUsersOptions(FFUsersOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -220,5 +202,4 @@ FFModuleBaseInfo ffUsersModuleInfo = { {"Years integer after login", "years"}, {"Days of year after login", "days-of-year"}, {"Years fraction after login", "years-fraction"}, - })) -}; + }))}; diff --git a/src/modules/version/option.h b/src/modules/version/option.h index f3b68b4f2..8647420d9 100644 --- a/src/modules/version/option.h +++ b/src/modules/version/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFVersionOptions -{ +typedef struct FFVersionOptions { FFModuleArgs moduleArgs; } FFVersionOptions; diff --git a/src/modules/version/version.c b/src/modules/version/version.c index 84ccd5a0c..0749f05b2 100644 --- a/src/modules/version/version.c +++ b/src/modules/version/version.c @@ -5,67 +5,58 @@ #include "detection/version/version.h" #include "modules/version/version.h" -bool ffPrintVersion(FFVersionOptions* options) -{ +bool ffPrintVersion(FFVersionOptions* options) { FFVersionResult* result = &ffVersionResult; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_VERSION_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); printf("%s %s%s%s (%s)\n", result->projectName, result->version, result->versionTweak, result->debugMode ? "-debug" : "", result->architecture); - } - else - { + } else { FFLibcResult libcResult; FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (!ffDetectLibc(&libcResult)) - { + if (!ffDetectLibc(&libcResult)) { ffStrbufSetS(&buf, libcResult.name); - if (libcResult.version) - { + if (libcResult.version) { ffStrbufAppendC(&buf, ' '); ffStrbufAppendS(&buf, libcResult.version); } } const char* buildType = result->debugMode ? "debug" : "release"; - FF_PRINT_FORMAT_CHECKED(FF_VERSION_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result->projectName, "project-name"), - FF_ARG(result->version, "version"), - FF_ARG(result->versionTweak, "version-tweak"), - FF_ARG(buildType, "build-type"), - FF_ARG(result->sysName, "sysname"), - FF_ARG(result->architecture, "arch"), - FF_ARG(result->cmakeBuiltType, "cmake-built-type"), - FF_ARG(result->compileTime, "compile-time"), - FF_ARG(result->compiler, "compiler"), - FF_ARG(buf, "libc"), - })); + FF_PRINT_FORMAT_CHECKED(FF_VERSION_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result->projectName, "project-name"), + FF_ARG(result->version, "version"), + FF_ARG(result->versionTweak, "version-tweak"), + FF_ARG(buildType, "build-type"), + FF_ARG(result->sysName, "sysname"), + FF_ARG(result->architecture, "arch"), + FF_ARG(result->cmakeBuiltType, "cmake-built-type"), + FF_ARG(result->compileTime, "compile-time"), + FF_ARG(result->compiler, "compiler"), + FF_ARG(buf, "libc"), + })); } return true; } -void ffParseVersionJsonObject(FFVersionOptions* options, yyjson_val* module) -{ +void ffParseVersionJsonObject(FFVersionOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_VERSION_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateVersionJsonConfig(FFVersionOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateVersionJsonConfig(FFVersionOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateVersionJsonResult(FF_MAYBE_UNUSED FFVersionOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateVersionJsonResult(FF_MAYBE_UNUSED FFVersionOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFVersionResult* result = &ffVersionResult; yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); @@ -80,15 +71,11 @@ bool ffGenerateVersionJsonResult(FF_MAYBE_UNUSED FFVersionOptions* options, yyjs yyjson_mut_obj_add_bool(doc, obj, "debugMode", result->debugMode); FFLibcResult libcResult; - if (ffDetectLibc(&libcResult)) - { + if (ffDetectLibc(&libcResult)) { yyjson_mut_obj_add_null(doc, obj, "libc"); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreateS(libcResult.name); - if (libcResult.version) - { + if (libcResult.version) { ffStrbufAppendC(&buf, ' '); ffStrbufAppendS(&buf, libcResult.version); } @@ -98,13 +85,11 @@ bool ffGenerateVersionJsonResult(FF_MAYBE_UNUSED FFVersionOptions* options, yyjs return true; } -void ffInitVersionOptions(FFVersionOptions* options) -{ +void ffInitVersionOptions(FFVersionOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyVersionOptions(FFVersionOptions* options) -{ +void ffDestroyVersionOptions(FFVersionOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -128,5 +113,4 @@ FFModuleBaseInfo ffVersionModuleInfo = { {"Date time when compiling", "compile-time"}, {"Compiler used when compiling", "compiler"}, {"Libc used when compiling", "libc"}, - })) -}; + }))}; diff --git a/src/modules/vulkan/option.h b/src/modules/vulkan/option.h index 38ec20c99..2ab42c5f7 100644 --- a/src/modules/vulkan/option.h +++ b/src/modules/vulkan/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFVulkanOptions -{ +typedef struct FFVulkanOptions { FFModuleArgs moduleArgs; } FFVulkanOptions; diff --git a/src/modules/vulkan/vulkan.c b/src/modules/vulkan/vulkan.c index 159d3d743..b1125a2c0 100644 --- a/src/modules/vulkan/vulkan.c +++ b/src/modules/vulkan/vulkan.c @@ -5,78 +5,67 @@ #include "detection/vulkan/vulkan.h" #include "modules/vulkan/vulkan.h" -bool ffPrintVulkan(FFVulkanOptions* options) -{ +bool ffPrintVulkan(FFVulkanOptions* options) { const FFVulkanResult* vulkan = ffDetectVulkan(); - if(vulkan->error) - { + if (vulkan->error) { ffPrintError(FF_VULKAN_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", vulkan->error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_VULKAN_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); - if (vulkan->apiVersion.length == 0 && vulkan->driver.length == 0) - { + if (vulkan->apiVersion.length == 0 && vulkan->driver.length == 0) { ffStrbufWriteTo(&vulkan->instanceVersion, stdout); puts(" [Software only]"); - } - else - { - if(vulkan->apiVersion.length > 0) - { + } else { + if (vulkan->apiVersion.length > 0) { ffStrbufWriteTo(&vulkan->apiVersion, stdout); - if(vulkan->driver.length > 0) + if (vulkan->driver.length > 0) { fputs(" - ", stdout); + } } - if(vulkan->driver.length > 0) + if (vulkan->driver.length > 0) { ffStrbufWriteTo(&vulkan->driver, stdout); + } putchar('\n'); } - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_VULKAN_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(vulkan->driver, "driver"), - FF_ARG(vulkan->apiVersion, "api-version"), - FF_ARG(vulkan->conformanceVersion, "conformance-version"), - FF_ARG(vulkan->instanceVersion, "instance-version"), - })); + FF_ARG(vulkan->driver, "driver"), + FF_ARG(vulkan->apiVersion, "api-version"), + FF_ARG(vulkan->conformanceVersion, "conformance-version"), + FF_ARG(vulkan->instanceVersion, "instance-version"), + })); } return true; } -void ffParseVulkanJsonObject(FFVulkanOptions* options, yyjson_val* module) -{ +void ffParseVulkanJsonObject(FFVulkanOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_VULKAN_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateVulkanJsonConfig(FFVulkanOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateVulkanJsonConfig(FFVulkanOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateVulkanJsonResult(FF_MAYBE_UNUSED FFVulkanOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateVulkanJsonResult(FF_MAYBE_UNUSED FFVulkanOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFVulkanResult* result = ffDetectVulkan(); - if(result->error) - { + if (result->error) { yyjson_mut_obj_add_str(doc, module, "error", result->error); return false; } @@ -86,10 +75,10 @@ bool ffGenerateVulkanJsonResult(FF_MAYBE_UNUSED FFVulkanOptions* options, yyjson yyjson_mut_obj_add_strbuf(doc, obj, "conformanceVersion", &result->conformanceVersion); yyjson_mut_obj_add_strbuf(doc, obj, "driver", &result->driver); yyjson_mut_val* gpus = yyjson_mut_obj_add_arr(doc, obj, "gpus"); - FF_LIST_FOR_EACH(FFGPUResult, vulkanGpu, result->gpus) - { + FF_LIST_FOR_EACH (FFGPUResult, vulkanGpu, result->gpus) { yyjson_mut_val* gpuObj = yyjson_mut_arr_add_obj(doc, gpus); - yyjson_mut_obj_add_str(doc, gpuObj, "type", vulkanGpu->type == FF_GPU_TYPE_UNKNOWN ? "Unknown" : vulkanGpu->type == FF_GPU_TYPE_INTEGRATED ? "Integrated" : "Discrete"); + yyjson_mut_obj_add_str(doc, gpuObj, "type", vulkanGpu->type == FF_GPU_TYPE_UNKNOWN ? "Unknown" : vulkanGpu->type == FF_GPU_TYPE_INTEGRATED ? "Integrated" + : "Discrete"); yyjson_mut_obj_add_strbuf(doc, gpuObj, "vendor", &vulkanGpu->vendor); yyjson_mut_obj_add_strbuf(doc, gpuObj, "name", &vulkanGpu->name); yyjson_mut_obj_add_strbuf(doc, gpuObj, "driver", &vulkanGpu->driver); @@ -100,28 +89,32 @@ bool ffGenerateVulkanJsonResult(FF_MAYBE_UNUSED FFVulkanOptions* options, yyjson { yyjson_mut_val* dedicatedMemory = yyjson_mut_obj_add_obj(doc, memoryObj, "dedicated"); - if (vulkanGpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) + if (vulkanGpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, dedicatedMemory, "total", vulkanGpu->dedicated.total); - else + } else { yyjson_mut_obj_add_null(doc, dedicatedMemory, "total"); + } - if (vulkanGpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) + if (vulkanGpu->dedicated.used != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, dedicatedMemory, "used", vulkanGpu->dedicated.total); - else + } else { yyjson_mut_obj_add_null(doc, dedicatedMemory, "used"); + } } { yyjson_mut_val* sharedMemory = yyjson_mut_obj_add_obj(doc, memoryObj, "shared"); - if (vulkanGpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) + if (vulkanGpu->shared.total != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, sharedMemory, "total", vulkanGpu->shared.total); - else + } else { yyjson_mut_obj_add_null(doc, sharedMemory, "total"); + } - if (vulkanGpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) + if (vulkanGpu->shared.used != FF_GPU_VMEM_SIZE_UNSET) { yyjson_mut_obj_add_uint(doc, sharedMemory, "used", vulkanGpu->shared.used); - else + } else { yyjson_mut_obj_add_null(doc, sharedMemory, "used"); + } } yyjson_mut_obj_add_uint(doc, gpuObj, "deviceId", vulkanGpu->deviceId); @@ -130,13 +123,11 @@ bool ffGenerateVulkanJsonResult(FF_MAYBE_UNUSED FFVulkanOptions* options, yyjson return true; } -void ffInitVulkanOptions(FFVulkanOptions* options) -{ +void ffInitVulkanOptions(FFVulkanOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); } -void ffDestroyVulkanOptions(FFVulkanOptions* options) -{ +void ffDestroyVulkanOptions(FFVulkanOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -154,5 +145,4 @@ FFModuleBaseInfo ffVulkanModuleInfo = { {"API version", "api-version"}, {"Conformance version", "conformance-version"}, {"Instance version", "instance-version"}, - })) -}; + }))}; diff --git a/src/modules/wallpaper/option.h b/src/modules/wallpaper/option.h index 621699fa3..8f7008dbc 100644 --- a/src/modules/wallpaper/option.h +++ b/src/modules/wallpaper/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFWallpaperOptions -{ +typedef struct FFWallpaperOptions { FFModuleArgs moduleArgs; } FFWallpaperOptions; diff --git a/src/modules/wallpaper/wallpaper.c b/src/modules/wallpaper/wallpaper.c index c997a2591..f0795d06b 100644 --- a/src/modules/wallpaper/wallpaper.c +++ b/src/modules/wallpaper/wallpaper.c @@ -4,68 +4,60 @@ #include "detection/wallpaper/wallpaper.h" #include "modules/wallpaper/wallpaper.h" -bool ffPrintWallpaper(FFWallpaperOptions* options) -{ +bool ffPrintWallpaper(FFWallpaperOptions* options) { FF_STRBUF_AUTO_DESTROY fullpath = ffStrbufCreate(); const char* error = ffDetectWallpaper(&fullpath); const uint32_t index = ffStrbufLastIndexC(&fullpath, - #ifndef _WIN32 - '/' - #else - '\\' - #endif - ) + 1; +#ifndef _WIN32 + '/' +#else + '\\' +#endif + ) + + 1; const char* filename = index >= fullpath.length ? fullpath.chars : fullpath.chars + index; - if(error) - { + if (error) { ffPrintError(FF_WALLPAPER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_WALLPAPER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); puts(filename); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_WALLPAPER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(filename, "file-name"), - FF_ARG(fullpath, "full-path"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_WALLPAPER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(filename, "file-name"), + FF_ARG(fullpath, "full-path"), + })); } return true; } -void ffParseWallpaperJsonObject(FFWallpaperOptions* options, yyjson_val* module) -{ +void ffParseWallpaperJsonObject(FFWallpaperOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_WALLPAPER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateWallpaperJsonConfig(FFWallpaperOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateWallpaperJsonConfig(FFWallpaperOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateWallpaperJsonResult(FF_MAYBE_UNUSED FFWallpaperOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateWallpaperJsonResult(FF_MAYBE_UNUSED FFWallpaperOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY fullpath = ffStrbufCreate(); const char* error = ffDetectWallpaper(&fullpath); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -74,13 +66,11 @@ bool ffGenerateWallpaperJsonResult(FF_MAYBE_UNUSED FFWallpaperOptions* options, return true; } -void ffInitWallpaperOptions(FFWallpaperOptions* options) -{ +void ffInitWallpaperOptions(FFWallpaperOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰸉"); } -void ffDestroyWallpaperOptions(FFWallpaperOptions* options) -{ +void ffDestroyWallpaperOptions(FFWallpaperOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -96,5 +86,4 @@ FFModuleBaseInfo ffWallpaperModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"File name", "file-name"}, {"Full path", "full-path"}, - })) -}; + }))}; diff --git a/src/modules/weather/option.h b/src/modules/weather/option.h index 76c3df11b..136277fcf 100644 --- a/src/modules/weather/option.h +++ b/src/modules/weather/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFWeatherOptions -{ +typedef struct FFWeatherOptions { FFModuleArgs moduleArgs; FFstrbuf location; diff --git a/src/modules/weather/weather.c b/src/modules/weather/weather.c index 2717d6979..8a1d7a22f 100644 --- a/src/modules/weather/weather.c +++ b/src/modules/weather/weather.c @@ -4,55 +4,46 @@ #include "detection/weather/weather.h" #include "modules/weather/weather.h" -bool ffPrintWeather(FFWeatherOptions* options) -{ +bool ffPrintWeather(FFWeatherOptions* options) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); const char* error = ffDetectWeather(options, &result); - if(error) - { + if (error) { ffPrintError(FF_WEATHER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_WEATHER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufPutTo(&result, stdout); - } - else - { + } else { FF_PRINT_FORMAT_CHECKED(FF_WEATHER_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { - FF_ARG(result, "result"), - })); + FF_ARG(result, "result"), + })); } return true; } -void ffParseWeatherJsonObject(FFWeatherOptions* options, yyjson_val* module) -{ +void ffParseWeatherJsonObject(FFWeatherOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "location")) - { + if (unsafe_yyjson_equals_str(key, "location")) { ffStrbufSetJsonVal(&options->location, val); continue; } - if (unsafe_yyjson_equals_str(key, "outputFormat")) - { + if (unsafe_yyjson_equals_str(key, "outputFormat")) { ffStrbufSetJsonVal(&options->outputFormat, val); continue; } - if (unsafe_yyjson_equals_str(key, "timeout")) - { + if (unsafe_yyjson_equals_str(key, "timeout")) { options->timeout = (uint32_t) yyjson_get_uint(val); continue; } @@ -61,8 +52,7 @@ void ffParseWeatherJsonObject(FFWeatherOptions* options, yyjson_val* module) } } -void ffGenerateWeatherJsonConfig(FFWeatherOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateWeatherJsonConfig(FFWeatherOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_strbuf(doc, module, "location", &options->location); @@ -72,13 +62,11 @@ void ffGenerateWeatherJsonConfig(FFWeatherOptions* options, yyjson_mut_doc* doc, yyjson_mut_obj_add_uint(doc, module, "timeout", options->timeout); } -bool ffGenerateWeatherJsonResult(FFWeatherOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateWeatherJsonResult(FFWeatherOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); const char* error = ffDetectWeather(options, &result); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } @@ -88,8 +76,7 @@ bool ffGenerateWeatherJsonResult(FFWeatherOptions* options, yyjson_mut_doc* doc, return true; } -void ffInitWeatherOptions(FFWeatherOptions* options) -{ +void ffInitWeatherOptions(FFWeatherOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰖙"); ffStrbufInit(&options->location); @@ -97,8 +84,7 @@ void ffInitWeatherOptions(FFWeatherOptions* options) options->timeout = 0; } -void ffDestroyWeatherOptions(FFWeatherOptions* options) -{ +void ffDestroyWeatherOptions(FFWeatherOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); ffStrbufDestroy(&options->outputFormat); @@ -115,5 +101,4 @@ FFModuleBaseInfo ffWeatherModuleInfo = { .generateJsonConfig = (void*) ffGenerateWeatherJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"Weather result", "result"}, - })) -}; + }))}; diff --git a/src/modules/wifi/option.h b/src/modules/wifi/option.h index f74579267..45ff9668d 100644 --- a/src/modules/wifi/option.h +++ b/src/modules/wifi/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFWifiOptions -{ +typedef struct FFWifiOptions { FFModuleArgs moduleArgs; FFPercentageModuleConfig percent; diff --git a/src/modules/wifi/wifi.c b/src/modules/wifi/wifi.c index 9efabafad..7713a0481 100644 --- a/src/modules/wifi/wifi.c +++ b/src/modules/wifi/wifi.c @@ -4,131 +4,117 @@ #include "detection/wifi/wifi.h" #include "modules/wifi/wifi.h" -bool ffPrintWifi(FFWifiOptions* options) -{ +bool ffPrintWifi(FFWifiOptions* options) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFWifiResult)); const char* error = ffDetectWifi(&result); - if(error) - { + if (error) { ffPrintError(FF_WIFI_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(!result.length) - { + if (!result.length) { ffPrintError(FF_WIFI_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No Wifi interfaces found"); return false; } FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - for(uint32_t index = 0; index < result.length; ++index) - { + for (uint32_t index = 0; index < result.length; ++index) { FFWifiResult* item = FF_LIST_GET(FFWifiResult, result, index); - uint8_t moduleIndex = result.length == 1 ? 0 : (uint8_t)(index + 1); + uint8_t moduleIndex = result.length == 1 ? 0 : (uint8_t) (index + 1); // https://en.wikipedia.org/wiki/List_of_WLAN_channels char bandStr[8]; - if (item->conn.frequency > 58000) + if (item->conn.frequency > 58000) { strcpy(bandStr, "60"); - if (item->conn.frequency > 40000) + } + if (item->conn.frequency > 40000) { strcpy(bandStr, "45"); - else if (item->conn.frequency > 5900) + } else if (item->conn.frequency > 5900) { strcpy(bandStr, "6"); - else if (item->conn.frequency > 5100) + } else if (item->conn.frequency > 5100) { strcpy(bandStr, "5"); - else if (item->conn.frequency > 4900) + } else if (item->conn.frequency > 4900) { strcpy(bandStr, "4.9"); - else if (item->conn.frequency > 3600) + } else if (item->conn.frequency > 3600) { strcpy(bandStr, "3.65"); - else if (item->conn.frequency > 2000) + } else if (item->conn.frequency > 2000) { strcpy(bandStr, "2.4"); - else if (item->conn.frequency > 800) + } else if (item->conn.frequency > 800) { strcpy(bandStr, "0.9"); - else + } else { bandStr[0] = '\0'; + } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_WIFI_MODULE_NAME, moduleIndex, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if(item->conn.ssid.length) - { - if(item->conn.signalQuality != -DBL_MAX) - { - if(percentType & FF_PERCENTAGE_TYPE_BAR_BIT) - { + if (item->conn.ssid.length) { + if (item->conn.signalQuality != -DBL_MAX) { + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&buffer, item->conn.signalQuality, options->percent, &options->moduleArgs); ffStrbufAppendC(&buffer, ' '); } } - if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) - { + if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) { ffStrbufAppend(&buffer, &item->conn.ssid); - if(item->conn.protocol.length) - { + if (item->conn.protocol.length) { ffStrbufAppendS(&buffer, " - "); ffStrbufAppend(&buffer, &item->conn.protocol); } - if (bandStr[0]) - { - ffStrbufAppendF(&buffer, " - %s%sGHz", bandStr, - instance.config.display.freqSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " "); + if (bandStr[0]) { + ffStrbufAppendF(&buffer, " - %s%sGHz", bandStr, instance.config.display.freqSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " "); } - if(item->conn.security.length) - { + if (item->conn.security.length) { ffStrbufAppendS(&buffer, " - "); ffStrbufAppend(&buffer, &item->conn.security); } ffStrbufAppendC(&buffer, ' '); } - if(item->conn.signalQuality != -DBL_MAX) - { - if(percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (item->conn.signalQuality != -DBL_MAX) { + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&buffer, item->conn.signalQuality, options->percent, buffer.length > 0, &options->moduleArgs); + } } ffStrbufTrimRight(&buffer, ' '); - } - else - { + } else { ffStrbufAppend(&buffer, &item->inf.status); } ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY percentNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&percentNum, item->conn.signalQuality, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY percentBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&percentBar, item->conn.signalQuality, options->percent, &options->moduleArgs); + } - FF_PRINT_FORMAT_CHECKED(FF_WIFI_MODULE_NAME, moduleIndex, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(item->inf.description, "inf-desc"), - FF_ARG(item->inf.status, "inf-status"), - FF_ARG(item->conn.status, "status"), - FF_ARG(item->conn.ssid, "ssid"), - FF_ARG(item->conn.bssid, "bssid"), - FF_ARG(item->conn.protocol, "protocol"), - FF_ARG(percentNum, "signal-quality"), - FF_ARG(item->conn.rxRate, "rx-rate"), - FF_ARG(item->conn.txRate, "tx-rate"), - FF_ARG(item->conn.security, "security"), - FF_ARG(percentBar, "signal-quality-bar"), - FF_ARG(item->conn.channel, "channel"), - FF_ARG(bandStr, "band"), - })); + FF_PRINT_FORMAT_CHECKED(FF_WIFI_MODULE_NAME, moduleIndex, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(item->inf.description, "inf-desc"), + FF_ARG(item->inf.status, "inf-status"), + FF_ARG(item->conn.status, "status"), + FF_ARG(item->conn.ssid, "ssid"), + FF_ARG(item->conn.bssid, "bssid"), + FF_ARG(item->conn.protocol, "protocol"), + FF_ARG(percentNum, "signal-quality"), + FF_ARG(item->conn.rxRate, "rx-rate"), + FF_ARG(item->conn.txRate, "tx-rate"), + FF_ARG(item->conn.security, "security"), + FF_ARG(percentBar, "signal-quality-bar"), + FF_ARG(item->conn.channel, "channel"), + FF_ARG(bandStr, "band"), + })); } } - FF_LIST_FOR_EACH(FFWifiResult, item, result) - { + FF_LIST_FOR_EACH (FFWifiResult, item, result) { ffStrbufDestroy(&item->inf.description); ffStrbufDestroy(&item->inf.status); ffStrbufDestroy(&item->conn.status); @@ -141,42 +127,38 @@ bool ffPrintWifi(FFWifiOptions* options) return true; } -void ffParseWifiJsonObject(FFWifiOptions* options, yyjson_val* module) -{ +void ffParseWifiJsonObject(FFWifiOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_WIFI_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateWifiJsonConfig(FFWifiOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateWifiJsonConfig(FFWifiOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateWifiJsonResult(FF_MAYBE_UNUSED FFWifiOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateWifiJsonResult(FF_MAYBE_UNUSED FFWifiOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(sizeof(FFWifiResult)); const char* error = ffDetectWifi(&result); - if(error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFWifiResult, wifi, result) - { + FF_LIST_FOR_EACH (FFWifiResult, wifi, result) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_val* inf = yyjson_mut_obj_add_obj(doc, obj, "inf"); @@ -189,24 +171,26 @@ bool ffGenerateWifiJsonResult(FF_MAYBE_UNUSED FFWifiOptions* options, yyjson_mut yyjson_mut_obj_add_strbuf(doc, conn, "bssid", &wifi->conn.bssid); yyjson_mut_obj_add_strbuf(doc, conn, "protocol", &wifi->conn.protocol); yyjson_mut_obj_add_strbuf(doc, conn, "security", &wifi->conn.security); - if (wifi->conn.signalQuality != -DBL_MAX) + if (wifi->conn.signalQuality != -DBL_MAX) { yyjson_mut_obj_add_real(doc, conn, "signalQuality", wifi->conn.signalQuality); - else + } else { yyjson_mut_obj_add_null(doc, conn, "signalQuality"); - if (wifi->conn.rxRate != -DBL_MAX) + } + if (wifi->conn.rxRate != -DBL_MAX) { yyjson_mut_obj_add_real(doc, conn, "rxRate", wifi->conn.rxRate); - else + } else { yyjson_mut_obj_add_null(doc, conn, "rxRate"); - if (wifi->conn.txRate != -DBL_MAX) + } + if (wifi->conn.txRate != -DBL_MAX) { yyjson_mut_obj_add_real(doc, conn, "txRate", wifi->conn.txRate); - else + } else { yyjson_mut_obj_add_null(doc, conn, "txRate"); + } yyjson_mut_obj_add_uint(doc, conn, "channel", wifi->conn.channel); yyjson_mut_obj_add_uint(doc, conn, "frequency", wifi->conn.frequency); } - FF_LIST_FOR_EACH(FFWifiResult, item, result) - { + FF_LIST_FOR_EACH (FFWifiResult, item, result) { ffStrbufDestroy(&item->inf.description); ffStrbufDestroy(&item->inf.status); ffStrbufDestroy(&item->conn.status); @@ -219,15 +203,13 @@ bool ffGenerateWifiJsonResult(FF_MAYBE_UNUSED FFWifiOptions* options, yyjson_mut return true; } -void ffInitWifiOptions(FFWifiOptions* options) -{ +void ffInitWifiOptions(FFWifiOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); - options->percent = (FFPercentageModuleConfig) { 75, 50, 0 }; + options->percent = (FFPercentageModuleConfig) {75, 50, 0}; } -void ffDestroyWifiOptions(FFWifiOptions* options) -{ +void ffDestroyWifiOptions(FFWifiOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -254,5 +236,4 @@ FFModuleBaseInfo ffWifiModuleInfo = { {"Connection signal quality (percentage bar)", "signal-quality-bar"}, {"Connection channel number", "channel"}, {"Connection channel band in GHz", "band"}, - })) -}; + }))}; diff --git a/src/modules/wm/option.h b/src/modules/wm/option.h index d213c9c3a..7d343c9c3 100644 --- a/src/modules/wm/option.h +++ b/src/modules/wm/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFWMOptions -{ +typedef struct FFWMOptions { FFModuleArgs moduleArgs; bool detectPlugin; diff --git a/src/modules/wm/wm.c b/src/modules/wm/wm.c index 2c2efd2d1..526de6fc7 100644 --- a/src/modules/wm/wm.c +++ b/src/modules/wm/wm.c @@ -5,77 +5,69 @@ #include "detection/wm/wm.h" #include "modules/wm/wm.h" -bool ffPrintWM(FFWMOptions* options) -{ +bool ffPrintWM(FFWMOptions* options) { const FFDisplayServerResult* result = ffConnectDisplayServer(); - if(result->wmPrettyName.length == 0) - { + if (result->wmPrettyName.length == 0) { ffPrintError(FF_WM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No WM found"); return false; } FF_STRBUF_AUTO_DESTROY pluginName = ffStrbufCreate(); - if(options->detectPlugin) + if (options->detectPlugin) { ffDetectWMPlugin(&pluginName); + } FF_STRBUF_AUTO_DESTROY version = ffStrbufCreate(); - if (instance.config.general.detectVersion) + if (instance.config.general.detectVersion) { ffDetectWMVersion(&result->wmProcessName, &version, options); + } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_WM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); ffStrbufWriteTo(&result->wmPrettyName, stdout); - if(version.length > 0) - { + if (version.length > 0) { putchar(' '); ffStrbufWriteTo(&version, stdout); } - if(result->wmProtocolName.length > 0) - { + if (result->wmProtocolName.length > 0) { fputs(" (", stdout); ffStrbufWriteTo(&result->wmProtocolName, stdout); putchar(')'); } - if(pluginName.length > 0) - { + if (pluginName.length > 0) { fputs(" (with ", stdout); ffStrbufWriteTo(&pluginName, stdout); putchar(')'); } putchar('\n'); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_WM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(result->wmProcessName, "process-name"), - FF_ARG(result->wmPrettyName, "pretty-name"), - FF_ARG(result->wmProtocolName, "protocol-name"), - FF_ARG(pluginName, "plugin-name"), - FF_ARG(version, "version"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_WM_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(result->wmProcessName, "process-name"), + FF_ARG(result->wmPrettyName, "pretty-name"), + FF_ARG(result->wmProtocolName, "protocol-name"), + FF_ARG(pluginName, "plugin-name"), + FF_ARG(version, "version"), + })); } return true; } -void ffParseWMJsonObject(FFWMOptions* options, yyjson_val* module) -{ +void ffParseWMJsonObject(FFWMOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (unsafe_yyjson_equals_str(key, "detectPlugin")) - { + if (unsafe_yyjson_equals_str(key, "detectPlugin")) { options->detectPlugin = yyjson_get_bool(val); continue; } @@ -84,30 +76,29 @@ void ffParseWMJsonObject(FFWMOptions* options, yyjson_val* module) } } -void ffGenerateWMJsonConfig(FFWMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateWMJsonConfig(FFWMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); yyjson_mut_obj_add_bool(doc, module, "detectPlugin", options->detectPlugin); } -bool ffGenerateWMJsonResult(FF_MAYBE_UNUSED FFWMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateWMJsonResult(FF_MAYBE_UNUSED FFWMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFDisplayServerResult* result = ffConnectDisplayServer(); - if(result->wmPrettyName.length == 0) - { + if (result->wmPrettyName.length == 0) { yyjson_mut_obj_add_str(doc, module, "error", "No WM found"); return false; } FF_STRBUF_AUTO_DESTROY pluginName = ffStrbufCreate(); - if(options->detectPlugin) + if (options->detectPlugin) { ffDetectWMPlugin(&pluginName); + } FF_STRBUF_AUTO_DESTROY version = ffStrbufCreate(); - if (instance.config.general.detectVersion) + if (instance.config.general.detectVersion) { ffDetectWMVersion(&result->wmProcessName, &version, options); + } yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); yyjson_mut_obj_add_strbuf(doc, obj, "processName", &result->wmProcessName); @@ -119,14 +110,12 @@ bool ffGenerateWMJsonResult(FF_MAYBE_UNUSED FFWMOptions* options, yyjson_mut_doc return true; } -void ffInitWMOptions(FFWMOptions* options) -{ +void ffInitWMOptions(FFWMOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, ""); options->detectPlugin = true; } -void ffDestroyWMOptions(FFWMOptions* options) -{ +void ffDestroyWMOptions(FFWMOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -145,5 +134,4 @@ FFModuleBaseInfo ffWMModuleInfo = { {"WM protocol name", "protocol-name"}, {"WM plugin name", "plugin-name"}, {"WM version", "version"}, - })) -}; + }))}; diff --git a/src/modules/wmtheme/option.h b/src/modules/wmtheme/option.h index b12f9f8b3..5b0af0739 100644 --- a/src/modules/wmtheme/option.h +++ b/src/modules/wmtheme/option.h @@ -2,8 +2,7 @@ #include "common/option.h" -typedef struct FFWMThemeOptions -{ +typedef struct FFWMThemeOptions { FFModuleArgs moduleArgs; } FFWMThemeOptions; diff --git a/src/modules/wmtheme/wmtheme.c b/src/modules/wmtheme/wmtheme.c index a7de721f9..36cea8cb2 100644 --- a/src/modules/wmtheme/wmtheme.c +++ b/src/modules/wmtheme/wmtheme.c @@ -6,53 +6,44 @@ #define FF_WMTHEME_DISPLAY_NAME "WM Theme" -bool ffPrintWMTheme(FFWMThemeOptions* options) -{ +bool ffPrintWMTheme(FFWMThemeOptions* options) { FF_STRBUF_AUTO_DESTROY themeOrError = ffStrbufCreate(); - if(!ffDetectWmTheme(&themeOrError)) - { + if (!ffDetectWmTheme(&themeOrError)) { ffPrintError(FF_WMTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", themeOrError.chars); return false; } - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(FF_WMTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT); puts(themeOrError.chars); - } - else - { - FF_PRINT_FORMAT_CHECKED(FF_WMTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]){ - FF_ARG(themeOrError, "result"), - })); + } else { + FF_PRINT_FORMAT_CHECKED(FF_WMTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) { + FF_ARG(themeOrError, "result"), + })); } return true; } -void ffParseWMThemeJsonObject(FFWMThemeOptions* options, yyjson_val* module) -{ +void ffParseWMThemeJsonObject(FFWMThemeOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } ffPrintError(FF_WMTHEME_DISPLAY_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateWMThemeJsonConfig(FFWMThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateWMThemeJsonConfig(FFWMThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateWMThemeJsonResult(FF_MAYBE_UNUSED FFWMThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateWMThemeJsonResult(FF_MAYBE_UNUSED FFWMThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY themeOrError = ffStrbufCreate(); - if(!ffDetectWmTheme(&themeOrError)) - { + if (!ffDetectWmTheme(&themeOrError)) { yyjson_mut_obj_add_strbuf(doc, module, "error", &themeOrError); return false; } @@ -61,13 +52,11 @@ bool ffGenerateWMThemeJsonResult(FF_MAYBE_UNUSED FFWMThemeOptions* options, yyjs return true; } -void ffInitWMThemeOptions(FFWMThemeOptions* options) -{ +void ffInitWMThemeOptions(FFWMThemeOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󰓸"); } -void ffDestroyWMThemeOptions(FFWMThemeOptions* options) -{ +void ffDestroyWMThemeOptions(FFWMThemeOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -82,5 +71,4 @@ FFModuleBaseInfo ffWMThemeModuleInfo = { .generateJsonConfig = (void*) ffGenerateWMThemeJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { {"WM theme", "result"}, - })) -}; + }))}; diff --git a/src/modules/zpool/option.h b/src/modules/zpool/option.h index 49522b3be..e4efdcb8d 100644 --- a/src/modules/zpool/option.h +++ b/src/modules/zpool/option.h @@ -3,8 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef struct FFZpoolOptions -{ +typedef struct FFZpoolOptions { FFModuleArgs moduleArgs; FFPercentageModuleConfig percent; diff --git a/src/modules/zpool/zpool.c b/src/modules/zpool/zpool.c index 0a9ede81b..b82963310 100644 --- a/src/modules/zpool/zpool.c +++ b/src/modules/zpool/zpool.c @@ -7,25 +7,22 @@ #include "detection/zpool/zpool.h" #include "modules/zpool/zpool.h" -static void printZpool(FFZpoolOptions* options, FFZpoolResult* result, uint8_t index) -{ +static void printZpool(FFZpoolOptions* options, FFZpoolResult* result, uint8_t index) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (options->moduleArgs.key.length == 0) - { - if (result->name.length > 0) + if (options->moduleArgs.key.length == 0) { + if (result->name.length > 0) { ffStrbufSetF(&buffer, "%s (%s)", FF_ZPOOL_MODULE_NAME, result->name.chars); - else + } else { ffStrbufSetS(&buffer, FF_ZPOOL_MODULE_NAME); - } - else - { + } + } else { ffStrbufClear(&buffer); FF_PARSE_FORMAT_STRING_CHECKED(&buffer, &options->moduleArgs.key, ((FFformatarg[]) { - FF_ARG(index, "index"), - FF_ARG(result->name, "name"), - FF_ARG(result->guid, "guid"), - FF_ARG(options->moduleArgs.keyIcon, "icon"), - })); + FF_ARG(index, "index"), + FF_ARG(result->name, "name"), + FF_ARG(result->guid, "guid"), + FF_ARG(options->moduleArgs.keyIcon, "icon"), + })); } FF_STRBUF_AUTO_DESTROY usedPretty = ffStrbufCreate(); @@ -41,8 +38,7 @@ static void printZpool(FFZpoolOptions* options, FFZpoolResult* result, uint8_t i double allocatedPercentage = result->total > 0 ? (double) result->allocated / (double) result->total * 100.0 : 0; FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type; - if(options->moduleArgs.outputFormat.length == 0) - { + if (options->moduleArgs.outputFormat.length == 0) { ffPrintLogoAndKey(buffer.chars, index, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY); ffStrbufClear(&buffer); @@ -53,121 +49,117 @@ static void printZpool(FFZpoolOptions* options, FFZpoolResult* result, uint8_t i ffStrbufAppendS(&buffer, " allocated, "); ffPercentAppendNum(&buffer, result->fragmentation, options->percent, false, &options->moduleArgs); ffStrbufAppendF(&buffer, " frag) - %s", result->state.chars); - if (result->readOnly) + if (result->readOnly) { ffStrbufAppendS(&buffer, " [Read-only]"); + } ffStrbufPutTo(&buffer, stdout); - } - else - { + } else { FF_STRBUF_AUTO_DESTROY usedPercentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&usedPercentageNum, usedPercentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY usedPercentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&usedPercentageBar, usedPercentage, options->percent, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY allocatedPercentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&allocatedPercentageNum, allocatedPercentage, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY allocatedPercentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&allocatedPercentageBar, allocatedPercentage, options->percent, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY fragPercentageNum = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { ffPercentAppendNum(&fragPercentageNum, result->fragmentation, options->percent, false, &options->moduleArgs); + } FF_STRBUF_AUTO_DESTROY fragPercentageBar = ffStrbufCreate(); - if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { ffPercentAppendBar(&fragPercentageBar, result->fragmentation, options->percent, &options->moduleArgs); + } FF_PRINT_FORMAT_CHECKED(buffer.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { - FF_ARG(result->name, "name"), - FF_ARG(result->guid, "guid"), - FF_ARG(result->state, "state"), - FF_ARG(usedPretty, "size-used"), - FF_ARG(allocatedPretty, "size-allocated"), - FF_ARG(totalPretty, "size-total"), - FF_ARG(usedPercentageNum, "used-percentage"), - FF_ARG(allocatedPercentageNum, "allocated-percentage"), - FF_ARG(fragPercentageNum, "frag-percentage"), - FF_ARG(usedPercentageBar, "used-percentage-bar"), - FF_ARG(allocatedPercentageBar, "allocated-percentage-bar"), - FF_ARG(fragPercentageBar, "frag-percentage-bar"), - FF_ARG(result->readOnly, "is-readonly"), - })); + FF_ARG(result->name, "name"), + FF_ARG(result->guid, "guid"), + FF_ARG(result->state, "state"), + FF_ARG(usedPretty, "size-used"), + FF_ARG(allocatedPretty, "size-allocated"), + FF_ARG(totalPretty, "size-total"), + FF_ARG(usedPercentageNum, "used-percentage"), + FF_ARG(allocatedPercentageNum, "allocated-percentage"), + FF_ARG(fragPercentageNum, "frag-percentage"), + FF_ARG(usedPercentageBar, "used-percentage-bar"), + FF_ARG(allocatedPercentageBar, "allocated-percentage-bar"), + FF_ARG(fragPercentageBar, "frag-percentage-bar"), + FF_ARG(result->readOnly, "is-readonly"), + })); } } -bool ffPrintZpool(FFZpoolOptions* options) -{ +bool ffPrintZpool(FFZpoolOptions* options) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFZpoolResult)); const char* error = ffDetectZpool(&results); - if (error) - { + if (error) { ffPrintError(FF_ZPOOL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error); return false; } - if(results.length == 0) - { + if (results.length == 0) { ffPrintError(FF_ZPOOL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", "No zpool found"); return false; } - for(uint32_t i = 0; i < results.length; i++) - { + for (uint32_t i = 0; i < results.length; i++) { FFZpoolResult* result = FF_LIST_GET(FFZpoolResult, results, i); uint8_t index = results.length == 1 ? 0 : (uint8_t) (i + 1); printZpool(options, result, index); } - FF_LIST_FOR_EACH(FFZpoolResult, result, results) - { + FF_LIST_FOR_EACH (FFZpoolResult, result, results) { ffStrbufDestroy(&result->name); ffStrbufDestroy(&result->state); } return true; } -void ffParseZpoolJsonObject(FFZpoolOptions* options, yyjson_val* module) -{ +void ffParseZpoolJsonObject(FFZpoolOptions* options, yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(module, idx, max, key, val) - { - if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) + yyjson_obj_foreach (module, idx, max, key, val) { + if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) { continue; + } - if (ffPercentParseJsonObject(key, val, &options->percent)) + if (ffPercentParseJsonObject(key, val, &options->percent)) { continue; + } ffPrintError(FF_ZPOOL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffGenerateZpoolJsonConfig(FFZpoolOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +void ffGenerateZpoolJsonConfig(FFZpoolOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateZpoolJsonResult(FF_MAYBE_UNUSED FFZpoolOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) -{ +bool ffGenerateZpoolJsonResult(FF_MAYBE_UNUSED FFZpoolOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(sizeof(FFZpoolResult)); const char* error = ffDetectZpool(&results); - if (error) - { + if (error) { yyjson_mut_obj_add_str(doc, module, "error", error); return false; } yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result"); - FF_LIST_FOR_EACH(FFZpoolResult, zpool, results) - { + FF_LIST_FOR_EACH (FFZpoolResult, zpool, results) { yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr); yyjson_mut_obj_add_strbuf(doc, obj, "name", &zpool->name); yyjson_mut_obj_add_strbuf(doc, obj, "state", &zpool->state); @@ -175,29 +167,27 @@ bool ffGenerateZpoolJsonResult(FF_MAYBE_UNUSED FFZpoolOptions* options, yyjson_m yyjson_mut_obj_add_uint(doc, obj, "used", zpool->used); yyjson_mut_obj_add_uint(doc, obj, "allocated", zpool->allocated); yyjson_mut_obj_add_uint(doc, obj, "total", zpool->total); - if (zpool->fragmentation != -DBL_MAX) + if (zpool->fragmentation != -DBL_MAX) { yyjson_mut_obj_add_real(doc, obj, "fragmentation", zpool->fragmentation); - else + } else { yyjson_mut_obj_add_null(doc, obj, "fragmentation"); + } yyjson_mut_obj_add_bool(doc, obj, "readOnly", zpool->readOnly); } - FF_LIST_FOR_EACH(FFZpoolResult, zpool, results) - { + FF_LIST_FOR_EACH (FFZpoolResult, zpool, results) { ffStrbufDestroy(&zpool->name); ffStrbufDestroy(&zpool->state); } return true; } -void ffInitZpoolOptions(FFZpoolOptions* options) -{ +void ffInitZpoolOptions(FFZpoolOptions* options) { ffOptionInitModuleArg(&options->moduleArgs, "󱑛"); - options->percent = (FFPercentageModuleConfig) { 50, 80, 0 }; + options->percent = (FFPercentageModuleConfig) {50, 80, 0}; } -void ffDestroyZpoolOptions(FFZpoolOptions* options) -{ +void ffDestroyZpoolOptions(FFZpoolOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); } @@ -224,5 +214,4 @@ FFModuleBaseInfo ffZpoolModuleInfo = { {"Size allocated percentage bar", "allocated-percentage-bar"}, {"Fragmentation percentage bar", "fragmentation-percentage-bar"}, {"Is read-only", "is-readonly"}, - })) -}; + }))}; diff --git a/src/options/display.c b/src/options/display.c index fa70f13e2..baff1264c 100644 --- a/src/options/display.c +++ b/src/options/display.c @@ -7,828 +7,750 @@ #include -const char* ffOptionsParseDisplayJsonConfig(FFOptionsDisplay* options, yyjson_val* root) -{ +const char* ffOptionsParseDisplayJsonConfig(FFOptionsDisplay* options, yyjson_val* root) { yyjson_val* object = yyjson_obj_get(root, "display"); - if (!object) return NULL; - if (!yyjson_is_obj(object)) return "Property 'display' must be an object"; + if (!object) { + return NULL; + } + if (!yyjson_is_obj(object)) { + return "Property 'display' must be an object"; + } yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(object, idx, max, key, val) - { - if (unsafe_yyjson_equals_str(key, "stat")) - { - if (yyjson_is_bool(val)) - { - if (yyjson_get_bool(val)) - { + yyjson_obj_foreach (object, idx, max, key, val) { + if (unsafe_yyjson_equals_str(key, "stat")) { + if (yyjson_is_bool(val)) { + if (yyjson_get_bool(val)) { options->stat = 0; options->showErrors = true; - } - else + } else { options->stat = -1; - } - else if (yyjson_is_uint(val)) - { + } + } else if (yyjson_is_uint(val)) { options->stat = (int) yyjson_get_uint(val); options->showErrors = true; - } - else + } else { return "display.stat must be a boolean or a positive integer"; - } - else if (unsafe_yyjson_equals_str(key, "pipe")) + } + } else if (unsafe_yyjson_equals_str(key, "pipe")) { options->pipe = yyjson_get_bool(val); - else if (unsafe_yyjson_equals_str(key, "showErrors")) + } else if (unsafe_yyjson_equals_str(key, "showErrors")) { options->showErrors = yyjson_get_bool(val); - else if (unsafe_yyjson_equals_str(key, "disableLinewrap")) + } else if (unsafe_yyjson_equals_str(key, "disableLinewrap")) { options->disableLinewrap = yyjson_get_bool(val); - else if (unsafe_yyjson_equals_str(key, "hideCursor")) + } else if (unsafe_yyjson_equals_str(key, "hideCursor")) { options->hideCursor = yyjson_get_bool(val); - else if (unsafe_yyjson_equals_str(key, "separator")) + } else if (unsafe_yyjson_equals_str(key, "separator")) { ffStrbufSetJsonVal(&options->keyValueSeparator, val); - else if (unsafe_yyjson_equals_str(key, "color")) - { - if (yyjson_is_str(val)) - { + } else if (unsafe_yyjson_equals_str(key, "color")) { + if (yyjson_is_str(val)) { ffOptionParseColor(unsafe_yyjson_get_str(val), &options->colorKeys); ffStrbufSet(&options->colorTitle, &options->colorKeys); - } - else if (yyjson_is_obj(val)) - { + } else if (yyjson_is_obj(val)) { yyjson_val* colorKeys = yyjson_obj_get(val, "keys"); - if (colorKeys) + if (colorKeys) { ffOptionParseColor(yyjson_get_str(colorKeys), &options->colorKeys); + } yyjson_val* colorTitle = yyjson_obj_get(val, "title"); - if (colorTitle) + if (colorTitle) { ffOptionParseColor(yyjson_get_str(colorTitle), &options->colorTitle); + } yyjson_val* colorOutput = yyjson_obj_get(val, "output"); - if (colorOutput) + if (colorOutput) { ffOptionParseColor(yyjson_get_str(colorOutput), &options->colorOutput); + } yyjson_val* colorSeparator = yyjson_obj_get(val, "separator"); - if (colorSeparator) + if (colorSeparator) { ffOptionParseColor(yyjson_get_str(colorSeparator), &options->colorSeparator); - } - else + } + } else { return "display.color must be either a string or an object"; - } - else if (unsafe_yyjson_equals_str(key, "brightColor")) + } + } else if (unsafe_yyjson_equals_str(key, "brightColor")) { options->brightColor = yyjson_get_bool(val); - else if (unsafe_yyjson_equals_str(key, "duration")) - { - if (!yyjson_is_obj(val)) + } else if (unsafe_yyjson_equals_str(key, "duration")) { + if (!yyjson_is_obj(val)) { return "display.duration must be an object"; + } yyjson_val* abbreviation = yyjson_obj_get(val, "abbreviation"); - if (abbreviation) options->durationAbbreviation = yyjson_get_bool(abbreviation); + if (abbreviation) { + options->durationAbbreviation = yyjson_get_bool(abbreviation); + } yyjson_val* spaceBeforeUnit = yyjson_obj_get(val, "spaceBeforeUnit"); - if (spaceBeforeUnit) - { + if (spaceBeforeUnit) { int value; const char* error = ffJsonConfigParseEnum(spaceBeforeUnit, &value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - if (error) return error; + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + if (error) { + return error; + } options->durationSpaceBeforeUnit = (FFSpaceBeforeUnitType) value; } - } - else if (unsafe_yyjson_equals_str(key, "size")) - { - if (!yyjson_is_obj(val)) + } else if (unsafe_yyjson_equals_str(key, "size")) { + if (!yyjson_is_obj(val)) { return "display.size must be an object"; + } yyjson_val* maxPrefix = yyjson_obj_get(val, "maxPrefix"); - if (maxPrefix) - { + if (maxPrefix) { int value; - const char* error = ffJsonConfigParseEnum(maxPrefix, &value, (FFKeyValuePair[]) { - { "B", 0 }, - { "kB", 1 }, - { "MB", 2 }, - { "GB", 3 }, - { "TB", 4 }, - { "PB", 5 }, - { "EB", 6 }, - { "ZB", 7 }, - { "YB", 8 }, - {} - }); - if (error) return error; + const char* error = ffJsonConfigParseEnum(maxPrefix, &value, (FFKeyValuePair[]) {{"B", 0}, {"kB", 1}, {"MB", 2}, {"GB", 3}, {"TB", 4}, {"PB", 5}, {"EB", 6}, {"ZB", 7}, {"YB", 8}, {}}); + if (error) { + return error; + } options->sizeMaxPrefix = (uint8_t) value; } yyjson_val* binaryPrefix = yyjson_obj_get(val, "binaryPrefix"); - if (binaryPrefix) - { + if (binaryPrefix) { int value; const char* error = ffJsonConfigParseEnum(binaryPrefix, &value, (FFKeyValuePair[]) { - { "iec", FF_SIZE_BINARY_PREFIX_TYPE_IEC }, - { "si", FF_SIZE_BINARY_PREFIX_TYPE_SI }, - { "jedec", FF_SIZE_BINARY_PREFIX_TYPE_JEDEC }, - {}, - }); - if (error) return error; + {"iec", FF_SIZE_BINARY_PREFIX_TYPE_IEC}, + {"si", FF_SIZE_BINARY_PREFIX_TYPE_SI}, + {"jedec", FF_SIZE_BINARY_PREFIX_TYPE_JEDEC}, + {}, + }); + if (error) { + return error; + } options->sizeBinaryPrefix = (FFSizeBinaryPrefixType) value; } yyjson_val* ndigits = yyjson_obj_get(val, "ndigits"); - if (ndigits) - { - if (!yyjson_is_uint(ndigits)) + if (ndigits) { + if (!yyjson_is_uint(ndigits)) { return "display.size.ndigits must be an unsigned integer"; + } uint64_t val = yyjson_get_uint(ndigits); - if (val > 9) + if (val > 9) { return "display.size.ndigits must be between 0 and 9"; + } options->sizeNdigits = (uint8_t) val; } yyjson_val* spaceBeforeUnit = yyjson_obj_get(val, "spaceBeforeUnit"); - if (spaceBeforeUnit) - { + if (spaceBeforeUnit) { int value; const char* error = ffJsonConfigParseEnum(spaceBeforeUnit, &value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - if (error) return error; + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + if (error) { + return error; + } options->sizeSpaceBeforeUnit = (FFSpaceBeforeUnitType) value; } - } - else if (unsafe_yyjson_equals_str(key, "temp")) - { - if (!yyjson_is_obj(val)) + } else if (unsafe_yyjson_equals_str(key, "temp")) { + if (!yyjson_is_obj(val)) { return "display.temp must be an object"; + } yyjson_val* unit = yyjson_obj_get(val, "unit"); - if (unit) - { + if (unit) { int value; const char* error = ffJsonConfigParseEnum(unit, &value, (FFKeyValuePair[]) { - { "DEFAULT", FF_TEMPERATURE_UNIT_DEFAULT }, - { "D", FF_TEMPERATURE_UNIT_DEFAULT }, - { "CELSIUS", FF_TEMPERATURE_UNIT_CELSIUS }, - { "C", FF_TEMPERATURE_UNIT_CELSIUS }, - { "FAHRENHEIT", FF_TEMPERATURE_UNIT_FAHRENHEIT }, - { "F", FF_TEMPERATURE_UNIT_FAHRENHEIT }, - { "KELVIN", FF_TEMPERATURE_UNIT_KELVIN }, - { "K", FF_TEMPERATURE_UNIT_KELVIN }, - {}, - }); - if (error) return error; + {"DEFAULT", FF_TEMPERATURE_UNIT_DEFAULT}, + {"D", FF_TEMPERATURE_UNIT_DEFAULT}, + {"CELSIUS", FF_TEMPERATURE_UNIT_CELSIUS}, + {"C", FF_TEMPERATURE_UNIT_CELSIUS}, + {"FAHRENHEIT", FF_TEMPERATURE_UNIT_FAHRENHEIT}, + {"F", FF_TEMPERATURE_UNIT_FAHRENHEIT}, + {"KELVIN", FF_TEMPERATURE_UNIT_KELVIN}, + {"K", FF_TEMPERATURE_UNIT_KELVIN}, + {}, + }); + if (error) { + return error; + } options->tempUnit = (FFTemperatureUnit) value; } yyjson_val* ndigits = yyjson_obj_get(val, "ndigits"); - if (ndigits) - { - if (!yyjson_is_uint(ndigits)) + if (ndigits) { + if (!yyjson_is_uint(ndigits)) { return "display.temperature.ndigits must be an unsigned integer"; + } uint64_t val = yyjson_get_uint(ndigits); - if (val > 9) + if (val > 9) { return "display.temperature.ndigits must be between 0 and 9"; + } options->tempNdigits = (uint8_t) val; } yyjson_val* color = yyjson_obj_get(val, "color"); - if (color) - { - if (!yyjson_is_obj(color)) + if (color) { + if (!yyjson_is_obj(color)) { return "display.temperature.color must be an object"; + } yyjson_val* green = yyjson_obj_get(color, "green"); - if (green) ffOptionParseColor(yyjson_get_str(green), &options->tempColorGreen); + if (green) { + ffOptionParseColor(yyjson_get_str(green), &options->tempColorGreen); + } yyjson_val* yellow = yyjson_obj_get(color, "yellow"); - if (yellow) ffOptionParseColor(yyjson_get_str(yellow), &options->tempColorYellow); + if (yellow) { + ffOptionParseColor(yyjson_get_str(yellow), &options->tempColorYellow); + } yyjson_val* red = yyjson_obj_get(color, "red"); - if (red) ffOptionParseColor(yyjson_get_str(red), &options->tempColorRed); + if (red) { + ffOptionParseColor(yyjson_get_str(red), &options->tempColorRed); + } } yyjson_val* spaceBeforeUnit = yyjson_obj_get(val, "spaceBeforeUnit"); - if (spaceBeforeUnit) - { + if (spaceBeforeUnit) { int value; const char* error = ffJsonConfigParseEnum(spaceBeforeUnit, &value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - if (error) return error; + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + if (error) { + return error; + } options->tempSpaceBeforeUnit = (FFSpaceBeforeUnitType) value; } - } - else if (unsafe_yyjson_equals_str(key, "percent")) - { - if (!yyjson_is_obj(val)) + } else if (unsafe_yyjson_equals_str(key, "percent")) { + if (!yyjson_is_obj(val)) { return "display.percent must be an object"; + } yyjson_val* type = yyjson_obj_get(val, "type"); - if (type) - { + if (type) { const char* error = ffPercentParseTypeJsonConfig(type, &options->percentType); - if (error) return error; + if (error) { + return error; + } } yyjson_val* ndigits = yyjson_obj_get(val, "ndigits"); - if (ndigits) - { - if (!yyjson_is_uint(ndigits)) + if (ndigits) { + if (!yyjson_is_uint(ndigits)) { return "display.percent.ndigits must be an unsigned integer"; + } uint64_t val = yyjson_get_uint(ndigits); - if (val > 9) + if (val > 9) { return "display.percent.ndigits must be between 0 and 9"; + } options->percentNdigits = (uint8_t) val; } yyjson_val* color = yyjson_obj_get(val, "color"); - if (color) - { - if (!yyjson_is_obj(color)) + if (color) { + if (!yyjson_is_obj(color)) { return "display.percent.color must be an object"; + } yyjson_val* green = yyjson_obj_get(color, "green"); - if (green) ffOptionParseColor(yyjson_get_str(green), &options->percentColorGreen); + if (green) { + ffOptionParseColor(yyjson_get_str(green), &options->percentColorGreen); + } yyjson_val* yellow = yyjson_obj_get(color, "yellow"); - if (yellow) ffOptionParseColor(yyjson_get_str(yellow), &options->percentColorYellow); + if (yellow) { + ffOptionParseColor(yyjson_get_str(yellow), &options->percentColorYellow); + } yyjson_val* red = yyjson_obj_get(color, "red"); - if (red) ffOptionParseColor(yyjson_get_str(red), &options->percentColorRed); + if (red) { + ffOptionParseColor(yyjson_get_str(red), &options->percentColorRed); + } } yyjson_val* spaceBeforeUnit = yyjson_obj_get(val, "spaceBeforeUnit"); - if (spaceBeforeUnit) - { + if (spaceBeforeUnit) { int value; const char* error = ffJsonConfigParseEnum(spaceBeforeUnit, &value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - if (error) return error; + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + if (error) { + return error; + } options->percentSpaceBeforeUnit = (FFSpaceBeforeUnitType) value; } yyjson_val* width = yyjson_obj_get(val, "width"); - if (width) options->percentWidth = (uint8_t) yyjson_get_uint(width); - } - else if (unsafe_yyjson_equals_str(key, "bar")) - { - if (yyjson_is_obj(val)) - { + if (width) { + options->percentWidth = (uint8_t) yyjson_get_uint(width); + } + } else if (unsafe_yyjson_equals_str(key, "bar")) { + if (yyjson_is_obj(val)) { yyjson_val* char_ = yyjson_obj_get(val, "char"); - if (char_) - { - if (!yyjson_is_obj(char_)) return "display.bar.char must be an object"; + if (char_) { + if (!yyjson_is_obj(char_)) { + return "display.bar.char must be an object"; + } yyjson_val* charElapsed = yyjson_obj_get(char_, "elapsed"); - if (charElapsed) + if (charElapsed) { ffStrbufSetJsonVal(&options->barCharElapsed, charElapsed); + } yyjson_val* charTotal = yyjson_obj_get(char_, "total"); - if (charTotal) + if (charTotal) { ffStrbufSetJsonVal(&options->barCharTotal, charTotal); - } - else - { + } + } else { yyjson_val* charElapsed = yyjson_obj_get(val, "charElapsed"); - if (charElapsed) + if (charElapsed) { return "display.bar.charElapsed has been renamed to display.bar.char.elapsed."; + } yyjson_val* charTotal = yyjson_obj_get(val, "charTotal"); - if (charTotal) + if (charTotal) { return "display.bar.charTotal has been renamed to display.bar.char.total."; + } } yyjson_val* border = yyjson_obj_get(val, "border"); - if (border) - { - if (yyjson_is_null(border)) - { + if (border) { + if (yyjson_is_null(border)) { ffStrbufClear(&options->barBorderLeft); ffStrbufClear(&options->barBorderRight); ffStrbufClear(&options->barBorderLeftElapsed); ffStrbufClear(&options->barBorderRightElapsed); - } - else - { - if (!yyjson_is_obj(border)) return "display.bar.border must be an object"; + } else { + if (!yyjson_is_obj(border)) { + return "display.bar.border must be an object"; + } yyjson_val* borderLeft = yyjson_obj_get(border, "left"); - if (borderLeft) + if (borderLeft) { ffStrbufSetJsonVal(&options->barBorderLeft, borderLeft); + } yyjson_val* borderRight = yyjson_obj_get(border, "right"); - if (borderRight) + if (borderRight) { ffStrbufSetJsonVal(&options->barBorderRight, borderRight); + } yyjson_val* borderLeftElapsed = yyjson_obj_get(border, "leftElapsed"); - if (borderLeftElapsed) + if (borderLeftElapsed) { ffStrbufSetJsonVal(&options->barBorderLeftElapsed, borderLeftElapsed); + } yyjson_val* borderRightElapsed = yyjson_obj_get(border, "rightElapsed"); - if (borderRightElapsed) + if (borderRightElapsed) { ffStrbufSetJsonVal(&options->barBorderRightElapsed, borderRightElapsed); + } } - } - else - { + } else { yyjson_val* borderLeft = yyjson_obj_get(val, "borderLeft"); - if (borderLeft) + if (borderLeft) { return "display.bar.borderLeft has been renamed to display.bar.border.left."; + } yyjson_val* borderRight = yyjson_obj_get(val, "borderRight"); - if (borderRight) + if (borderRight) { return "display.bar.borderRight has been renamed to display.bar.border.right."; + } } yyjson_val* color = yyjson_obj_get(val, "color"); - if (color) - { - if (yyjson_is_null(color)) - { + if (color) { + if (yyjson_is_null(color)) { ffStrbufClear(&options->barColorElapsed); ffStrbufClear(&options->barColorTotal); ffStrbufClear(&options->barColorBorder); - } - else - { - if (!yyjson_is_obj(color)) return "display.bar.color must be an object"; + } else { + if (!yyjson_is_obj(color)) { + return "display.bar.color must be an object"; + } yyjson_val* colorElapsed = yyjson_obj_get(color, "elapsed"); - if (colorElapsed) - { + if (colorElapsed) { const char* value = yyjson_get_str(colorElapsed); - if (!value) + if (!value) { ffStrbufClear(&options->barColorElapsed); - else if (ffStrEqualsIgnCase(value, "auto")) + } else if (ffStrEqualsIgnCase(value, "auto")) { ffStrbufSetStatic(&options->barColorElapsed, "auto"); - else + } else { ffOptionParseColor(value, &options->barColorElapsed); + } } yyjson_val* colorTotal = yyjson_obj_get(color, "total"); - if (colorTotal) ffOptionParseColor(yyjson_get_str(colorTotal), &options->barColorTotal); + if (colorTotal) { + ffOptionParseColor(yyjson_get_str(colorTotal), &options->barColorTotal); + } yyjson_val* colorBorder = yyjson_obj_get(color, "border"); - if (colorBorder) ffOptionParseColor(yyjson_get_str(colorBorder), &options->barColorBorder); + if (colorBorder) { + ffOptionParseColor(yyjson_get_str(colorBorder), &options->barColorBorder); + } } } yyjson_val* width = yyjson_obj_get(val, "width"); - if (width) + if (width) { options->barWidth = (uint8_t) yyjson_get_uint(width); - } - else + } + } else { return "display.bar must be an object"; - } - else if (unsafe_yyjson_equals_str(key, "fraction")) - { - if (yyjson_is_obj(val)) - { + } + } else if (unsafe_yyjson_equals_str(key, "fraction")) { + if (yyjson_is_obj(val)) { yyjson_val* ndigits = yyjson_obj_get(val, "ndigits"); - if (ndigits) - { - if (yyjson_is_null(ndigits)) + if (ndigits) { + if (yyjson_is_null(ndigits)) { options->fractionNdigits = -1; - else - { - if (!yyjson_is_int(ndigits)) + } else { + if (!yyjson_is_int(ndigits)) { return "display.fraction.ndigits must be an integer"; + } int64_t val = yyjson_get_int(ndigits); - if (val < -1 || val > 9) + if (val < -1 || val > 9) { return "display.fraction.ndigits must be between -1 and 9"; + } options->fractionNdigits = (int8_t) val; } } yyjson_val* trailingZeros = yyjson_obj_get(val, "trailingZeros"); - if (trailingZeros) - { - if (yyjson_is_null(trailingZeros)) + if (trailingZeros) { + if (yyjson_is_null(trailingZeros)) { options->fractionTrailingZeros = FF_FRACTION_TRAILING_ZEROS_TYPE_DEFAULT; - else - { + } else { int value; const char* error = ffJsonConfigParseEnum(trailingZeros, &value, (FFKeyValuePair[]) { - { "default", FF_FRACTION_TRAILING_ZEROS_TYPE_DEFAULT }, - { "always", FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS }, - { "never", FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER }, - {}, - }); - if (error) return error; + {"default", FF_FRACTION_TRAILING_ZEROS_TYPE_DEFAULT}, + {"always", FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS}, + {"never", FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER}, + {}, + }); + if (error) { + return error; + } options->fractionTrailingZeros = (FFFractionTrailingZerosType) value; } } - } - else + } else { return "display.fraction must be an object"; - } - else if (unsafe_yyjson_equals_str(key, "noBuffer")) + } + } else if (unsafe_yyjson_equals_str(key, "noBuffer")) { options->noBuffer = yyjson_get_bool(val); - else if (unsafe_yyjson_equals_str(key, "key")) - { - if (yyjson_is_obj(val)) - { + } else if (unsafe_yyjson_equals_str(key, "key")) { + if (yyjson_is_obj(val)) { yyjson_val* width = yyjson_obj_get(val, "width"); - if (width) + if (width) { options->keyWidth = (uint16_t) yyjson_get_uint(width); + } yyjson_val* type = yyjson_obj_get(val, "type"); - if (type) - { + if (type) { int value; - const char* error = ffJsonConfigParseEnum(type, &value, (FFKeyValuePair[]) { - { "none", FF_MODULE_KEY_TYPE_NONE }, - { "string", FF_MODULE_KEY_TYPE_STRING }, - { "icon", FF_MODULE_KEY_TYPE_ICON }, - { "both", FF_MODULE_KEY_TYPE_BOTH }, - { "both-0", FF_MODULE_KEY_TYPE_BOTH_0 }, - { "both-1", FF_MODULE_KEY_TYPE_BOTH_1 }, - { "both-2", FF_MODULE_KEY_TYPE_BOTH_2 }, - { "both-3", FF_MODULE_KEY_TYPE_BOTH_3 }, - { "both-4", FF_MODULE_KEY_TYPE_BOTH_4 }, - {} - }); - if (error) return error; + const char* error = ffJsonConfigParseEnum(type, &value, (FFKeyValuePair[]) {{"none", FF_MODULE_KEY_TYPE_NONE}, {"string", FF_MODULE_KEY_TYPE_STRING}, {"icon", FF_MODULE_KEY_TYPE_ICON}, {"both", FF_MODULE_KEY_TYPE_BOTH}, {"both-0", FF_MODULE_KEY_TYPE_BOTH_0}, {"both-1", FF_MODULE_KEY_TYPE_BOTH_1}, {"both-2", FF_MODULE_KEY_TYPE_BOTH_2}, {"both-3", FF_MODULE_KEY_TYPE_BOTH_3}, {"both-4", FF_MODULE_KEY_TYPE_BOTH_4}, {}}); + if (error) { + return error; + } options->keyType = (uint8_t) value; } yyjson_val* paddingLeft = yyjson_obj_get(val, "paddingLeft"); - if (paddingLeft) + if (paddingLeft) { options->keyPaddingLeft = (uint16_t) yyjson_get_uint(paddingLeft); - } - else + } + } else { return "display.key must be an object"; - } - else if (unsafe_yyjson_equals_str(key, "constants")) - { - if (!yyjson_is_arr(val)) + } + } else if (unsafe_yyjson_equals_str(key, "constants")) { + if (!yyjson_is_arr(val)) { return "display.constants must be an array"; + } yyjson_val* item; size_t idx, max; - yyjson_arr_foreach(val, idx, max, item) + yyjson_arr_foreach (val, idx, max, item) { ffStrbufInitJsonVal(ffListAdd(&options->constants), item); - } - else if (unsafe_yyjson_equals_str(key, "freq")) - { - if (!yyjson_is_obj(val)) + } + } else if (unsafe_yyjson_equals_str(key, "freq")) { + if (!yyjson_is_obj(val)) { return "display.freq must be an object"; + } yyjson_val* ndigits = yyjson_obj_get(val, "ndigits"); - if (ndigits) - { - if (yyjson_is_null(ndigits)) + if (ndigits) { + if (yyjson_is_null(ndigits)) { options->freqNdigits = -1; - else - { - if (!yyjson_is_int(ndigits)) + } else { + if (!yyjson_is_int(ndigits)) { return "display.freq.ndigits must be an integer"; + } int64_t val = yyjson_get_int(ndigits); - if (val < -1 || val > 9) + if (val < -1 || val > 9) { return "display.freq.ndigits must be between -1 and 9"; + } options->freqNdigits = (int8_t) val; } } yyjson_val* spaceBeforeUnit = yyjson_obj_get(val, "spaceBeforeUnit"); - if (spaceBeforeUnit) - { + if (spaceBeforeUnit) { int value; const char* error = ffJsonConfigParseEnum(spaceBeforeUnit, &value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - if (error) return error; + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + if (error) { + return error; + } options->freqSpaceBeforeUnit = (FFSpaceBeforeUnitType) value; } - } - else + } else { return "Unknown display property"; + } } return NULL; } -static inline void optionCheckString(const char* key, const char* value, FFstrbuf* buffer) -{ - if(value == NULL) - { +static inline void optionCheckString(const char* key, const char* value, FFstrbuf* buffer) { + if (value == NULL) { fprintf(stderr, "Error: usage: %s \n", key); exit(477); } - ffStrbufEnsureFree(buffer, 63); //This is not needed, as ffStrbufSetS will resize capacity if needed, but giving a higher start should improve performance + ffStrbufEnsureFree(buffer, 63); // This is not needed, as ffStrbufSetS will resize capacity if needed, but giving a higher start should improve performance } -bool ffOptionsParseDisplayCommandLine(FFOptionsDisplay* options, const char* key, const char* value) -{ - if(ffStrEqualsIgnCase(key, "--stat")) - { - if(ffOptionParseBoolean(value)) - { +bool ffOptionsParseDisplayCommandLine(FFOptionsDisplay* options, const char* key, const char* value) { + if (ffStrEqualsIgnCase(key, "--stat")) { + if (ffOptionParseBoolean(value)) { options->stat = 0; options->showErrors = true; - } - else if (value) - { + } else if (value) { char* end; uint32_t num = (uint32_t) strtoul(value, &end, 10); - if (*end == '\0') - { + if (*end == '\0') { options->stat = (int32_t) num; options->showErrors = true; - } - else + } else { options->stat = -1; - } - else + } + } else { options->stat = -1; - } - else if(ffStrEqualsIgnCase(key, "--pipe")) + } + } else if (ffStrEqualsIgnCase(key, "--pipe")) { options->pipe = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(key, "--show-errors")) + } else if (ffStrEqualsIgnCase(key, "--show-errors")) { options->showErrors = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(key, "--debug")) - #ifndef NDEBUG + } else if (ffStrEqualsIgnCase(key, "--debug")) +#ifndef NDEBUG options->debugMode = ffOptionParseBoolean(value); - #else +#else { fprintf(stderr, "--debug is only available in debug builds\n"); exit(477); } - #endif - else if(ffStrEqualsIgnCase(key, "--disable-linewrap")) +#endif + else if (ffStrEqualsIgnCase(key, "--disable-linewrap")) { options->disableLinewrap = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(key, "--hide-cursor")) + } else if (ffStrEqualsIgnCase(key, "--hide-cursor")) { options->hideCursor = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(key, "--separator")) + } else if (ffStrEqualsIgnCase(key, "--separator")) { ffOptionParseString(key, value, &options->keyValueSeparator); - else if(ffStrEqualsIgnCase(key, "--color")) - { + } else if (ffStrEqualsIgnCase(key, "--color")) { optionCheckString(key, value, &options->colorKeys); ffOptionParseColor(value, &options->colorKeys); ffStrbufSet(&options->colorTitle, &options->colorKeys); - } - else if(ffStrStartsWithIgnCase(key, "--color-")) - { + } else if (ffStrStartsWithIgnCase(key, "--color-")) { const char* subkey = key + strlen("--color-"); - if(ffStrEqualsIgnCase(subkey, "keys")) - { + if (ffStrEqualsIgnCase(subkey, "keys")) { optionCheckString(key, value, &options->colorKeys); ffOptionParseColor(value, &options->colorKeys); - } - else if(ffStrEqualsIgnCase(subkey, "title")) - { + } else if (ffStrEqualsIgnCase(subkey, "title")) { optionCheckString(key, value, &options->colorTitle); ffOptionParseColor(value, &options->colorTitle); - } - else if(ffStrEqualsIgnCase(subkey, "output")) - { + } else if (ffStrEqualsIgnCase(subkey, "output")) { optionCheckString(key, value, &options->colorOutput); ffOptionParseColor(value, &options->colorOutput); - } - else if(ffStrEqualsIgnCase(subkey, "separator")) - { + } else if (ffStrEqualsIgnCase(subkey, "separator")) { optionCheckString(key, value, &options->colorSeparator); ffOptionParseColor(value, &options->colorSeparator); - } - else + } else { return false; - } - else if(ffStrStartsWithIgnCase(key, "--key-")) - { + } + } else if (ffStrStartsWithIgnCase(key, "--key-")) { const char* subkey = key + strlen("--key-"); - if(ffStrEqualsIgnCase(subkey, "width")) + if (ffStrEqualsIgnCase(subkey, "width")) { options->keyWidth = (uint16_t) ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subkey, "type")) - { - options->keyType = (FFModuleKeyType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "none", FF_MODULE_KEY_TYPE_NONE }, - { "string", FF_MODULE_KEY_TYPE_STRING }, - { "icon", FF_MODULE_KEY_TYPE_ICON }, - { "both", FF_MODULE_KEY_TYPE_BOTH }, - { "both-0", FF_MODULE_KEY_TYPE_BOTH_0 }, - { "both-1", FF_MODULE_KEY_TYPE_BOTH_1 }, - { "both-2", FF_MODULE_KEY_TYPE_BOTH_2 }, - { "both-3", FF_MODULE_KEY_TYPE_BOTH_3 }, - { "both-4", FF_MODULE_KEY_TYPE_BOTH_4 }, - {} - }); - } - else if(ffStrEqualsIgnCase(subkey, "padding-left")) + } else if (ffStrEqualsIgnCase(subkey, "type")) { + options->keyType = (FFModuleKeyType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) {{"none", FF_MODULE_KEY_TYPE_NONE}, {"string", FF_MODULE_KEY_TYPE_STRING}, {"icon", FF_MODULE_KEY_TYPE_ICON}, {"both", FF_MODULE_KEY_TYPE_BOTH}, {"both-0", FF_MODULE_KEY_TYPE_BOTH_0}, {"both-1", FF_MODULE_KEY_TYPE_BOTH_1}, {"both-2", FF_MODULE_KEY_TYPE_BOTH_2}, {"both-3", FF_MODULE_KEY_TYPE_BOTH_3}, {"both-4", FF_MODULE_KEY_TYPE_BOTH_4}, {}}); + } else if (ffStrEqualsIgnCase(subkey, "padding-left")) { options->keyPaddingLeft = (uint16_t) ffOptionParseUInt32(key, value); - else + } else { return false; - } - else if(ffStrEqualsIgnCase(key, "--bright-color")) + } + } else if (ffStrEqualsIgnCase(key, "--bright-color")) { options->brightColor = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(key, "--binary-prefix")) - { + } else if (ffStrEqualsIgnCase(key, "--binary-prefix")) { fprintf(stderr, "--binary-prefix has been renamed to --size-binary-prefix\n"); exit(477); - } - else if(ffStrStartsWithIgnCase(key, "--duration-")) - { + } else if (ffStrStartsWithIgnCase(key, "--duration-")) { const char* subkey = key + strlen("--duration-"); - if(ffStrEqualsIgnCase(subkey, "abbreviation")) + if (ffStrEqualsIgnCase(subkey, "abbreviation")) { options->durationAbbreviation = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(subkey, "space-before-unit")) - { + } else if (ffStrEqualsIgnCase(subkey, "space-before-unit")) { options->durationSpaceBeforeUnit = (FFSpaceBeforeUnitType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - } - else + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + } else { return false; - } - else if(ffStrStartsWithIgnCase(key, "--size-")) - { + } + } else if (ffStrStartsWithIgnCase(key, "--size-")) { const char* subkey = key + strlen("--size-"); - if (ffStrEqualsIgnCase(subkey, "binary-prefix")) - { - options->sizeBinaryPrefix = (FFSizeBinaryPrefixType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "iec", FF_SIZE_BINARY_PREFIX_TYPE_IEC }, - { "si", FF_SIZE_BINARY_PREFIX_TYPE_SI }, - { "jedec", FF_SIZE_BINARY_PREFIX_TYPE_JEDEC }, - {} - }); - } - else if (ffStrEqualsIgnCase(subkey, "ndigits")) + if (ffStrEqualsIgnCase(subkey, "binary-prefix")) { + options->sizeBinaryPrefix = (FFSizeBinaryPrefixType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) {{"iec", FF_SIZE_BINARY_PREFIX_TYPE_IEC}, {"si", FF_SIZE_BINARY_PREFIX_TYPE_SI}, {"jedec", FF_SIZE_BINARY_PREFIX_TYPE_JEDEC}, {}}); + } else if (ffStrEqualsIgnCase(subkey, "ndigits")) { options->sizeNdigits = (uint8_t) ffOptionParseUInt32(key, value); - else if (ffStrEqualsIgnCase(subkey, "max-prefix")) - { - options->sizeMaxPrefix = (uint8_t) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "B", 0 }, - { "kB", 1 }, - { "MB", 2 }, - { "GB", 3 }, - { "TB", 4 }, - { "PB", 5 }, - { "EB", 6 }, - { "ZB", 7 }, - { "YB", 8 }, - {} - }); - } - else if(ffStrEqualsIgnCase(subkey, "space-before-unit")) - { + } else if (ffStrEqualsIgnCase(subkey, "max-prefix")) { + options->sizeMaxPrefix = (uint8_t) ffOptionParseEnum(key, value, (FFKeyValuePair[]) {{"B", 0}, {"kB", 1}, {"MB", 2}, {"GB", 3}, {"TB", 4}, {"PB", 5}, {"EB", 6}, {"ZB", 7}, {"YB", 8}, {}}); + } else if (ffStrEqualsIgnCase(subkey, "space-before-unit")) { options->sizeSpaceBeforeUnit = (FFSpaceBeforeUnitType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - } - else + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + } else { return false; - } - else if(ffStrStartsWithIgnCase(key, "--temp-")) - { + } + } else if (ffStrStartsWithIgnCase(key, "--temp-")) { const char* subkey = key + strlen("--temp-"); - if(ffStrEqualsIgnCase(subkey, "unit")) - { + if (ffStrEqualsIgnCase(subkey, "unit")) { options->tempUnit = (FFTemperatureUnit) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "DEFAULT", FF_TEMPERATURE_UNIT_DEFAULT }, - { "D", FF_TEMPERATURE_UNIT_DEFAULT }, - { "CELSIUS", FF_TEMPERATURE_UNIT_CELSIUS }, - { "C", FF_TEMPERATURE_UNIT_CELSIUS }, - { "FAHRENHEIT", FF_TEMPERATURE_UNIT_FAHRENHEIT }, - { "F", FF_TEMPERATURE_UNIT_FAHRENHEIT }, - { "KELVIN", FF_TEMPERATURE_UNIT_KELVIN }, - { "K", FF_TEMPERATURE_UNIT_KELVIN }, - {}, - }); - } - else if (ffStrEqualsIgnCase(subkey, "ndigits")) + {"DEFAULT", FF_TEMPERATURE_UNIT_DEFAULT}, + {"D", FF_TEMPERATURE_UNIT_DEFAULT}, + {"CELSIUS", FF_TEMPERATURE_UNIT_CELSIUS}, + {"C", FF_TEMPERATURE_UNIT_CELSIUS}, + {"FAHRENHEIT", FF_TEMPERATURE_UNIT_FAHRENHEIT}, + {"F", FF_TEMPERATURE_UNIT_FAHRENHEIT}, + {"KELVIN", FF_TEMPERATURE_UNIT_KELVIN}, + {"K", FF_TEMPERATURE_UNIT_KELVIN}, + {}, + }); + } else if (ffStrEqualsIgnCase(subkey, "ndigits")) { options->tempNdigits = (uint8_t) ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subkey, "color-green")) + } else if (ffStrEqualsIgnCase(subkey, "color-green")) { ffOptionParseColor(value, &options->tempColorGreen); - else if(ffStrEqualsIgnCase(subkey, "color-yellow")) + } else if (ffStrEqualsIgnCase(subkey, "color-yellow")) { ffOptionParseColor(value, &options->tempColorYellow); - else if(ffStrEqualsIgnCase(subkey, "color-red")) + } else if (ffStrEqualsIgnCase(subkey, "color-red")) { ffOptionParseColor(value, &options->tempColorRed); - else if(ffStrEqualsIgnCase(subkey, "space-before-unit")) - { + } else if (ffStrEqualsIgnCase(subkey, "space-before-unit")) { options->tempSpaceBeforeUnit = (FFSpaceBeforeUnitType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - } - else + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + } else { return false; - } - else if(ffStrStartsWithIgnCase(key, "--percent-")) - { + } + } else if (ffStrStartsWithIgnCase(key, "--percent-")) { const char* subkey = key + strlen("--percent-"); - if(ffStrEqualsIgnCase(subkey, "type")) + if (ffStrEqualsIgnCase(subkey, "type")) { options->percentType = (uint8_t) ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subkey, "ndigits")) + } else if (ffStrEqualsIgnCase(subkey, "ndigits")) { options->percentNdigits = (uint8_t) ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subkey, "color-green")) + } else if (ffStrEqualsIgnCase(subkey, "color-green")) { ffOptionParseColor(value, &options->percentColorGreen); - else if(ffStrEqualsIgnCase(subkey, "color-yellow")) + } else if (ffStrEqualsIgnCase(subkey, "color-yellow")) { ffOptionParseColor(value, &options->percentColorYellow); - else if(ffStrEqualsIgnCase(subkey, "color-red")) + } else if (ffStrEqualsIgnCase(subkey, "color-red")) { ffOptionParseColor(value, &options->percentColorRed); - else if(ffStrEqualsIgnCase(subkey, "space-before-unit")) - { + } else if (ffStrEqualsIgnCase(subkey, "space-before-unit")) { options->percentSpaceBeforeUnit = (FFSpaceBeforeUnitType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); - } - else if(ffStrEqualsIgnCase(subkey, "width")) + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + } else if (ffStrEqualsIgnCase(subkey, "width")) { options->percentWidth = (uint8_t) ffOptionParseUInt32(key, value); - else + } else { return false; - } - else if(ffStrEqualsIgnCase(key, "--fraction-ndigits")) + } + } else if (ffStrEqualsIgnCase(key, "--fraction-ndigits")) { options->fractionNdigits = (int8_t) ffOptionParseInt32(key, value); - else if(ffStrEqualsIgnCase(key, "--fraction-trailing-zeros")) - { + } else if (ffStrEqualsIgnCase(key, "--fraction-trailing-zeros")) { options->fractionTrailingZeros = (FFFractionTrailingZerosType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "default", FF_FRACTION_TRAILING_ZEROS_TYPE_DEFAULT }, - { "always", FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS }, - { "never", FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER }, - {}, - }); - } - else if(ffStrEqualsIgnCase(key, "--no-buffer")) + {"default", FF_FRACTION_TRAILING_ZEROS_TYPE_DEFAULT}, + {"always", FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS}, + {"never", FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER}, + {}, + }); + } else if (ffStrEqualsIgnCase(key, "--no-buffer")) { options->noBuffer = ffOptionParseBoolean(value); - else if(ffStrStartsWithIgnCase(key, "--bar-")) - { + } else if (ffStrStartsWithIgnCase(key, "--bar-")) { const char* subkey = key + strlen("--bar-"); - if(ffStrEqualsIgnCase(subkey, "char-elapsed")) + if (ffStrEqualsIgnCase(subkey, "char-elapsed")) { ffOptionParseString(key, value, &options->barCharElapsed); - else if(ffStrEqualsIgnCase(subkey, "char-total")) + } else if (ffStrEqualsIgnCase(subkey, "char-total")) { ffOptionParseString(key, value, &options->barCharTotal); - else if(ffStrEqualsIgnCase(subkey, "width")) + } else if (ffStrEqualsIgnCase(subkey, "width")) { options->barWidth = (uint8_t) ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subkey, "border-left")) + } else if (ffStrEqualsIgnCase(subkey, "border-left")) { ffOptionParseString(key, value, &options->barBorderLeft); - else if(ffStrEqualsIgnCase(subkey, "border-right")) + } else if (ffStrEqualsIgnCase(subkey, "border-right")) { ffOptionParseString(key, value, &options->barBorderRight); - else if(ffStrEqualsIgnCase(subkey, "border-left-elapsed")) + } else if (ffStrEqualsIgnCase(subkey, "border-left-elapsed")) { ffOptionParseString(key, value, &options->barBorderLeftElapsed); - else if(ffStrEqualsIgnCase(subkey, "border-right-elapsed")) + } else if (ffStrEqualsIgnCase(subkey, "border-right-elapsed")) { ffOptionParseString(key, value, &options->barBorderRightElapsed); - else if(ffStrEqualsIgnCase(subkey, "color-elapsed")) - { - if (!value) + } else if (ffStrEqualsIgnCase(subkey, "color-elapsed")) { + if (!value) { ffStrbufClear(&options->barColorElapsed); - else if (ffStrEqualsIgnCase(value, "auto")) + } else if (ffStrEqualsIgnCase(value, "auto")) { ffStrbufSetStatic(&options->barColorElapsed, "auto"); - else + } else { ffOptionParseColor(value, &options->barColorElapsed); - } - else if(ffStrEqualsIgnCase(subkey, "color-total")) + } + } else if (ffStrEqualsIgnCase(subkey, "color-total")) { ffOptionParseColor(value, &options->barColorTotal); - else if(ffStrEqualsIgnCase(subkey, "color-border")) + } else if (ffStrEqualsIgnCase(subkey, "color-border")) { ffOptionParseColor(value, &options->barColorBorder); - else + } else { return false; - } - else if(ffStrStartsWithIgnCase(key, "--freq-")) - { - const char* subkey = key + strlen("--freq-"); - if(ffStrEqualsIgnCase(subkey, "ndigits")) - options->freqNdigits = (int8_t) ffOptionParseInt32(key, value); - else if(ffStrEqualsIgnCase(subkey, "space-before-unit")) - { - options->freqSpaceBeforeUnit = (FFSpaceBeforeUnitType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "default", FF_SPACE_BEFORE_UNIT_DEFAULT }, - { "always", FF_SPACE_BEFORE_UNIT_ALWAYS }, - { "never", FF_SPACE_BEFORE_UNIT_NEVER }, - {}, - }); } - else + } else if (ffStrStartsWithIgnCase(key, "--freq-")) { + const char* subkey = key + strlen("--freq-"); + if (ffStrEqualsIgnCase(subkey, "ndigits")) { + options->freqNdigits = (int8_t) ffOptionParseInt32(key, value); + } else if (ffStrEqualsIgnCase(subkey, "space-before-unit")) { + options->freqSpaceBeforeUnit = (FFSpaceBeforeUnitType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { + {"default", FF_SPACE_BEFORE_UNIT_DEFAULT}, + {"always", FF_SPACE_BEFORE_UNIT_ALWAYS}, + {"never", FF_SPACE_BEFORE_UNIT_NEVER}, + {}, + }); + } else { return false; - } - else + } + } else { return false; + } return true; } -void ffOptionsInitDisplay(FFOptionsDisplay* options) -{ +void ffOptionsInitDisplay(FFOptionsDisplay* options) { ffStrbufInit(&options->colorKeys); ffStrbufInit(&options->colorTitle); ffStrbufInit(&options->colorOutput); @@ -839,12 +761,12 @@ void ffOptionsInitDisplay(FFOptionsDisplay* options) options->showErrors = false; options->pipe = !isatty(STDOUT_FILENO) || !!getenv("NO_COLOR"); - #ifdef NDEBUG +#ifdef NDEBUG options->disableLinewrap = !options->pipe; - #else +#else options->disableLinewrap = false; options->debugMode = !!getenv("FF_DEBUG"); - #endif +#endif options->durationSpaceBeforeUnit = FF_SPACE_BEFORE_UNIT_DEFAULT; options->hideCursor = false; @@ -895,8 +817,7 @@ void ffOptionsInitDisplay(FFOptionsDisplay* options) ffListInit(&options->constants, sizeof(FFstrbuf)); } -void ffOptionsDestroyDisplay(FFOptionsDisplay* options) -{ +void ffOptionsDestroyDisplay(FFOptionsDisplay* options) { ffStrbufDestroy(&options->colorKeys); ffStrbufDestroy(&options->colorTitle); ffStrbufDestroy(&options->colorOutput); @@ -904,20 +825,21 @@ void ffOptionsDestroyDisplay(FFOptionsDisplay* options) ffStrbufDestroy(&options->keyValueSeparator); ffStrbufDestroy(&options->barCharElapsed); ffStrbufDestroy(&options->barCharTotal); - FF_LIST_FOR_EACH(FFstrbuf, item, options->constants) + FF_LIST_FOR_EACH (FFstrbuf, item, options->constants) { ffStrbufDestroy(item); + } ffListDestroy(&options->constants); } -void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) -{ +void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_doc* doc = data->resultDoc; yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, doc->root, "display"); - if (options->stat <= 0) + if (options->stat <= 0) { yyjson_mut_obj_add_bool(doc, obj, "stat", options->stat == 0); - else + } else { yyjson_mut_obj_add_int(doc, obj, "stat", options->stat); + } yyjson_mut_obj_add_bool(doc, obj, "pipe", options->pipe); @@ -942,8 +864,7 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_val* duration = yyjson_mut_obj_add_obj(doc, obj, "duration"); yyjson_mut_obj_add_bool(doc, duration, "abbreviation", options->durationAbbreviation); - switch (options->durationSpaceBeforeUnit) - { + switch (options->durationSpaceBeforeUnit) { case FF_SPACE_BEFORE_UNIT_DEFAULT: yyjson_mut_obj_add_str(doc, duration, "spaceBeforeUnit", "default"); break; @@ -958,19 +879,18 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_val* size = yyjson_mut_obj_add_obj(doc, obj, "size"); - yyjson_mut_obj_add_str(doc, size, "maxPrefix", ((const char* []) { - "B", - "kB", - "MB", - "GB", - "TB", - "PB", - "EB", - "ZB", - "YB", - })[options->sizeMaxPrefix]); - switch (options->sizeBinaryPrefix) - { + yyjson_mut_obj_add_str(doc, size, "maxPrefix", ((const char*[]) { + "B", + "kB", + "MB", + "GB", + "TB", + "PB", + "EB", + "ZB", + "YB", + })[options->sizeMaxPrefix]); + switch (options->sizeBinaryPrefix) { case FF_SIZE_BINARY_PREFIX_TYPE_IEC: yyjson_mut_obj_add_str(doc, size, "binaryPrefix", "iec"); break; @@ -982,8 +902,7 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) break; } yyjson_mut_obj_add_uint(doc, size, "ndigits", options->sizeNdigits); - switch (options->sizeSpaceBeforeUnit) - { + switch (options->sizeSpaceBeforeUnit) { case FF_SPACE_BEFORE_UNIT_DEFAULT: yyjson_mut_obj_add_str(doc, size, "spaceBeforeUnit", "default"); break; @@ -998,8 +917,7 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_val* temperature = yyjson_mut_obj_add_obj(doc, obj, "temp"); - switch (options->tempUnit) - { + switch (options->tempUnit) { case FF_TEMPERATURE_UNIT_DEFAULT: yyjson_mut_obj_add_str(doc, temperature, "unit", "D"); break; @@ -1020,8 +938,7 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) yyjson_mut_obj_add_strbuf(doc, color, "yellow", &options->tempColorYellow); yyjson_mut_obj_add_strbuf(doc, color, "red", &options->tempColorRed); } - switch (options->tempSpaceBeforeUnit) - { + switch (options->tempSpaceBeforeUnit) { case FF_SPACE_BEFORE_UNIT_DEFAULT: yyjson_mut_obj_add_str(doc, temperature, "spaceBeforeUnit", "default"); break; @@ -1038,16 +955,21 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) yyjson_mut_val* percent = yyjson_mut_obj_add_obj(doc, obj, "percent"); { yyjson_mut_val* type = yyjson_mut_obj_add_arr(doc, percent, "type"); - if (options->percentType & FF_PERCENTAGE_TYPE_NUM_BIT) + if (options->percentType & FF_PERCENTAGE_TYPE_NUM_BIT) { yyjson_mut_arr_add_str(doc, type, "num"); - if (options->percentType & FF_PERCENTAGE_TYPE_BAR_BIT) + } + if (options->percentType & FF_PERCENTAGE_TYPE_BAR_BIT) { yyjson_mut_arr_add_str(doc, type, "var"); - if (options->percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT) + } + if (options->percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT) { yyjson_mut_arr_add_str(doc, type, "hide-others"); - if (options->percentType & FF_PERCENTAGE_TYPE_NUM_COLOR_BIT) + } + if (options->percentType & FF_PERCENTAGE_TYPE_NUM_COLOR_BIT) { yyjson_mut_arr_add_str(doc, type, "num-color"); - if (options->percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) + } + if (options->percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) { yyjson_mut_arr_add_str(doc, type, "bar-monochrome"); + } } yyjson_mut_obj_add_uint(doc, percent, "ndigits", options->percentNdigits); { @@ -1056,8 +978,7 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) yyjson_mut_obj_add_strbuf(doc, color, "yellow", &options->percentColorYellow); yyjson_mut_obj_add_strbuf(doc, color, "red", &options->percentColorRed); } - switch (options->percentSpaceBeforeUnit) - { + switch (options->percentSpaceBeforeUnit) { case FF_SPACE_BEFORE_UNIT_DEFAULT: yyjson_mut_obj_add_str(doc, percent, "spaceBeforeUnit", "default"); break; @@ -1095,10 +1016,11 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_val* fraction = yyjson_mut_obj_add_obj(doc, obj, "fraction"); - if (options->fractionNdigits < 0) + if (options->fractionNdigits < 0) { yyjson_mut_obj_add_null(doc, fraction, "ndigits"); - else + } else { yyjson_mut_obj_add_uint(doc, fraction, "ndigits", (uint8_t) options->fractionNdigits); + } } yyjson_mut_obj_add_bool(doc, obj, "noBuffer", options->noBuffer); @@ -1106,8 +1028,7 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_val* key = yyjson_mut_obj_add_obj(doc, obj, "key"); yyjson_mut_obj_add_uint(doc, key, "width", options->keyWidth); - switch ((uint8_t) options->keyType) - { + switch ((uint8_t) options->keyType) { case FF_MODULE_KEY_TYPE_NONE: yyjson_mut_obj_add_str(doc, key, "type", "none"); break; @@ -1128,8 +1049,7 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_val* freq = yyjson_mut_obj_add_obj(doc, obj, "freq"); yyjson_mut_obj_add_int(doc, freq, "ndigits", options->freqNdigits); - switch (options->percentSpaceBeforeUnit) - { + switch (options->percentSpaceBeforeUnit) { case FF_SPACE_BEFORE_UNIT_DEFAULT: yyjson_mut_obj_add_str(doc, freq, "spaceBeforeUnit", "default"); break; @@ -1144,7 +1064,8 @@ void ffOptionsGenerateDisplayJsonConfig(FFdata* data, FFOptionsDisplay* options) { yyjson_mut_val* constants = yyjson_mut_obj_add_arr(doc, obj, "constants"); - FF_LIST_FOR_EACH(FFstrbuf, item, options->constants) + FF_LIST_FOR_EACH (FFstrbuf, item, options->constants) { yyjson_mut_arr_add_strbuf(doc, constants, item); + } } } diff --git a/src/options/display.h b/src/options/display.h index c9f798134..a1e729a44 100644 --- a/src/options/display.h +++ b/src/options/display.h @@ -5,38 +5,33 @@ #include "common/FFstrbuf.h" #include "common/FFlist.h" -typedef enum __attribute__((__packed__)) FFSizeBinaryPrefixType -{ +typedef enum __attribute__((__packed__)) FFSizeBinaryPrefixType { FF_SIZE_BINARY_PREFIX_TYPE_IEC, // 1024 Bytes = 1 KiB, 1024 KiB = 1 MiB, ... (standard) FF_SIZE_BINARY_PREFIX_TYPE_SI, // 1000 Bytes = 1 kB, 1000 kB = 1 MB, ... FF_SIZE_BINARY_PREFIX_TYPE_JEDEC, // 1024 Bytes = 1 KB, 1024 KB = 1 MB, ... } FFSizeBinaryPrefixType; -typedef enum __attribute__((__packed__)) FFTemperatureUnit -{ +typedef enum __attribute__((__packed__)) FFTemperatureUnit { FF_TEMPERATURE_UNIT_DEFAULT, FF_TEMPERATURE_UNIT_CELSIUS, FF_TEMPERATURE_UNIT_FAHRENHEIT, FF_TEMPERATURE_UNIT_KELVIN, } FFTemperatureUnit; -typedef enum __attribute__((__packed__)) FFSpaceBeforeUnitType -{ +typedef enum __attribute__((__packed__)) FFSpaceBeforeUnitType { FF_SPACE_BEFORE_UNIT_DEFAULT, FF_SPACE_BEFORE_UNIT_ALWAYS, FF_SPACE_BEFORE_UNIT_NEVER, } FFSpaceBeforeUnitType; -typedef enum __attribute__((__packed__)) FFFractionTrailingZerosType -{ +typedef enum __attribute__((__packed__)) FFFractionTrailingZerosType { FF_FRACTION_TRAILING_ZEROS_TYPE_DEFAULT, FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS, FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER, } FFFractionTrailingZerosType; -typedef struct FFOptionsDisplay -{ - //If one of those is empty, ffLogoPrint will set them +typedef struct FFOptionsDisplay { + // If one of those is empty, ffLogoPrint will set them FFstrbuf colorKeys; FFstrbuf colorTitle; FFstrbuf colorOutput; @@ -47,11 +42,11 @@ typedef struct FFOptionsDisplay FFstrbuf keyValueSeparator; int32_t stat; // <0: disable stat; 0: no threshold; >0: threshold in ms - bool pipe; //disables all escape sequences + bool pipe; // disables all escape sequences bool showErrors; - #ifndef NDEBUG +#ifndef NDEBUG bool debugMode; - #endif +#endif bool disableLinewrap; bool durationAbbreviation; FFSpaceBeforeUnitType durationSpaceBeforeUnit; @@ -73,8 +68,8 @@ typedef struct FFOptionsDisplay FFstrbuf barBorderLeftElapsed; FFstrbuf barBorderRightElapsed; FFstrbuf barColorElapsed; // "auto" for auto selection from percent config; empty for no custom color (inherits) - FFstrbuf barColorTotal; // empty for no custom color (inherits) - FFstrbuf barColorBorder; // empty for no custom color (inherits) + FFstrbuf barColorTotal; // empty for no custom color (inherits) + FFstrbuf barColorBorder; // empty for no custom color (inherits) uint8_t barWidth; FFPercentageTypeFlags percentType; uint8_t percentNdigits; diff --git a/src/options/general.c b/src/options/general.c index 77deb64fc..9ebb74daa 100644 --- a/src/options/general.c +++ b/src/options/general.c @@ -6,119 +6,120 @@ #include -const char* ffOptionsParseGeneralJsonConfig(FFOptionsGeneral* options, yyjson_val* root) -{ +const char* ffOptionsParseGeneralJsonConfig(FFOptionsGeneral* options, yyjson_val* root) { yyjson_val* object = yyjson_obj_get(root, "general"); - if (!object) return NULL; - if (!yyjson_is_obj(object)) return "Property 'general' must be an object"; + if (!object) { + return NULL; + } + if (!yyjson_is_obj(object)) { + return "Property 'general' must be an object"; + } yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(object, idx, max, key, val) - { - if (unsafe_yyjson_equals_str(key, "thread")) + yyjson_obj_foreach (object, idx, max, key, val) { + if (unsafe_yyjson_equals_str(key, "thread")) { options->multithreading = yyjson_get_bool(val); - else if (unsafe_yyjson_equals_str(key, "processingTimeout")) + } else if (unsafe_yyjson_equals_str(key, "processingTimeout")) { options->processingTimeout = (int32_t) yyjson_get_int(val); - else if (unsafe_yyjson_equals_str(key, "preRun")) - { - if (!yyjson_is_str(val)) + } else if (unsafe_yyjson_equals_str(key, "preRun")) { + if (!yyjson_is_str(val)) { return "general.preRun must be a string"; - if (system(unsafe_yyjson_get_str(val)) < 0) + } + if (system(unsafe_yyjson_get_str(val)) < 0) { return "Failed to execute preRun command"; - } - else if (unsafe_yyjson_equals_str(key, "detectVersion")) + } + } else if (unsafe_yyjson_equals_str(key, "detectVersion")) { options->detectVersion = yyjson_get_bool(val); - - #if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) - else if (unsafe_yyjson_equals_str(key, "playerName")) + } +#if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) + else if (unsafe_yyjson_equals_str(key, "playerName")) { ffStrbufSetJsonVal(&options->playerName, val); - else if (unsafe_yyjson_equals_str(key, "dsForceDrm")) - { - if (yyjson_is_str(val)) - { + } else if (unsafe_yyjson_equals_str(key, "dsForceDrm")) { + if (yyjson_is_str(val)) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "sysfs-only", FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY }, - { "false", FF_DS_FORCE_DRM_TYPE_FALSE }, - { "true", FF_DS_FORCE_DRM_TYPE_TRUE }, - {}, - }); - if (error) + {"sysfs-only", FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY}, + {"false", FF_DS_FORCE_DRM_TYPE_FALSE}, + {"true", FF_DS_FORCE_DRM_TYPE_TRUE}, + {}, + }); + if (error) { return "Invalid enum value of `dsForceDrm`"; - else + } else { options->dsForceDrm = (FFDsForceDrmType) value; - } - else + } + } else { options->dsForceDrm = yyjson_get_bool(val) ? FF_DS_FORCE_DRM_TYPE_TRUE : FF_DS_FORCE_DRM_TYPE_FALSE; + } } - #elif defined(_WIN32) - else if (unsafe_yyjson_equals_str(key, "wmiTimeout")) +#elif defined(_WIN32) + else if (unsafe_yyjson_equals_str(key, "wmiTimeout")) { options->wmiTimeout = (int32_t) yyjson_get_int(val); - #endif + } +#endif - else + else { return "Unknown general property"; + } } return NULL; } -bool ffOptionsParseGeneralCommandLine(FFOptionsGeneral* options, const char* key, const char* value) -{ - if(ffStrEqualsIgnCase(key, "--thread") || ffStrEqualsIgnCase(key, "--multithreading")) +bool ffOptionsParseGeneralCommandLine(FFOptionsGeneral* options, const char* key, const char* value) { + if (ffStrEqualsIgnCase(key, "--thread") || ffStrEqualsIgnCase(key, "--multithreading")) { options->multithreading = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(key, "--processing-timeout")) + } else if (ffStrEqualsIgnCase(key, "--processing-timeout")) { options->processingTimeout = ffOptionParseInt32(key, value); - else if(ffStrEqualsIgnCase(key, "--detect-version")) + } else if (ffStrEqualsIgnCase(key, "--detect-version")) { options->detectVersion = ffOptionParseBoolean(value); - - #if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) - else if(ffStrEqualsIgnCase(key, "--player-name")) - ffOptionParseString(key, value, &options->playerName); - else if(ffStrEqualsIgnCase(key, "--ds-force-drm")) - { - if (ffOptionParseBoolean(value)) - options->dsForceDrm = FF_DS_FORCE_DRM_TYPE_TRUE; - else if (ffStrEqualsIgnCase(value, "sysfs-only")) - options->dsForceDrm = FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY; - else - options->dsForceDrm = FF_DS_FORCE_DRM_TYPE_FALSE; } - #elif defined(_WIN32) - else if (ffStrEqualsIgnCase(key, "--wmi-timeout")) +#if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) + else if (ffStrEqualsIgnCase(key, "--player-name")) { + ffOptionParseString(key, value, &options->playerName); + } else if (ffStrEqualsIgnCase(key, "--ds-force-drm")) { + if (ffOptionParseBoolean(value)) { + options->dsForceDrm = FF_DS_FORCE_DRM_TYPE_TRUE; + } else if (ffStrEqualsIgnCase(value, "sysfs-only")) { + options->dsForceDrm = FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY; + } else { + options->dsForceDrm = FF_DS_FORCE_DRM_TYPE_FALSE; + } + } +#elif defined(_WIN32) + else if (ffStrEqualsIgnCase(key, "--wmi-timeout")) { options->wmiTimeout = ffOptionParseInt32(key, value); - #endif + } +#endif - else + else { return false; + } return true; } -void ffOptionsInitGeneral(FFOptionsGeneral* options) -{ +void ffOptionsInitGeneral(FFOptionsGeneral* options) { options->processingTimeout = 5000; options->multithreading = true; options->detectVersion = true; - #if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) +#if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) ffStrbufInit(&options->playerName); options->dsForceDrm = FF_DS_FORCE_DRM_TYPE_FALSE; - #elif defined(_WIN32) +#elif defined(_WIN32) options->wmiTimeout = 5000; - #endif +#endif } -void ffOptionsDestroyGeneral(FF_MAYBE_UNUSED FFOptionsGeneral* options) -{ - #if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) +void ffOptionsDestroyGeneral(FF_MAYBE_UNUSED FFOptionsGeneral* options) { +#if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) ffStrbufDestroy(&options->playerName); - #endif +#endif } -void ffOptionsGenerateGeneralJsonConfig(FFdata* data, FFOptionsGeneral* options) -{ +void ffOptionsGenerateGeneralJsonConfig(FFdata* data, FFOptionsGeneral* options) { yyjson_mut_doc* doc = data->resultDoc; yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, doc->root, "general"); @@ -128,12 +129,11 @@ void ffOptionsGenerateGeneralJsonConfig(FFdata* data, FFOptionsGeneral* options) yyjson_mut_obj_add_bool(doc, obj, "detectVersion", options->detectVersion); - #if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) +#if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) yyjson_mut_obj_add_strbuf(doc, obj, "playerName", &options->playerName); - switch (options->dsForceDrm) - { + switch (options->dsForceDrm) { case FF_DS_FORCE_DRM_TYPE_FALSE: yyjson_mut_obj_add_bool(doc, obj, "dsForceDrm", false); break; @@ -145,9 +145,9 @@ void ffOptionsGenerateGeneralJsonConfig(FFdata* data, FFOptionsGeneral* options) break; } - #elif defined(_WIN32) +#elif defined(_WIN32) yyjson_mut_obj_add_int(doc, obj, "wmiTimeout", options->wmiTimeout); - #endif +#endif } diff --git a/src/options/general.h b/src/options/general.h index 22482011d..f74c12091 100644 --- a/src/options/general.h +++ b/src/options/general.h @@ -2,26 +2,24 @@ #include "common/ffdata.h" -typedef enum __attribute__((__packed__)) FFDsForceDrmType -{ - FF_DS_FORCE_DRM_TYPE_FALSE = 0, // Disable - FF_DS_FORCE_DRM_TYPE_TRUE = 1, // Try `libdrm`, then `sysfs` if libdrm failed +typedef enum __attribute__((__packed__)) FFDsForceDrmType { + FF_DS_FORCE_DRM_TYPE_FALSE = 0, // Disable + FF_DS_FORCE_DRM_TYPE_TRUE = 1, // Try `libdrm`, then `sysfs` if libdrm failed FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY, // Use `/sys/class/drm` only } FFDsForceDrmType; -typedef struct FFOptionsGeneral -{ +typedef struct FFOptionsGeneral { bool multithreading; int32_t processingTimeout; bool detectVersion; - // Module options that cannot be put in module option structure - #if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) +// Module options that cannot be put in module option structure +#if defined(__linux__) || defined(__FreeBSD__) || defined(__sun) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__) FFstrbuf playerName; FFDsForceDrmType dsForceDrm; - #elif defined(_WIN32) +#elif defined(_WIN32) int32_t wmiTimeout; - #endif +#endif } FFOptionsGeneral; const char* ffOptionsParseGeneralJsonConfig(FFOptionsGeneral* options, yyjson_val* root); diff --git a/src/options/logo.c b/src/options/logo.c index 4542eae8e..d6b671601 100644 --- a/src/options/logo.c +++ b/src/options/logo.c @@ -3,14 +3,14 @@ #include "common/jsonconfig.h" #include "common/stringUtils.h" -void ffOptionsInitLogo(FFOptionsLogo* options) -{ +void ffOptionsInitLogo(FFOptionsLogo* options) { ffStrbufInit(&options->source); options->type = FF_LOGO_TYPE_AUTO; - for(uint8_t i = 0; i < (uint8_t) FASTFETCH_LOGO_MAX_COLORS; ++i) + for (uint8_t i = 0; i < (uint8_t) FASTFETCH_LOGO_MAX_COLORS; ++i) { ffStrbufInit(&options->colors[i]); + } options->width = 0; - options->height = 0; //preserve aspect ratio + options->height = 0; // preserve aspect ratio options->paddingTop = 0; options->paddingLeft = 0; options->paddingRight = 4; @@ -26,234 +26,190 @@ void ffOptionsInitLogo(FFOptionsLogo* options) options->chafaDitherMode = UINT32_MAX; } -bool ffOptionsParseLogoCommandLine(FFOptionsLogo* options, const char* key, const char* value) -{ - if (ffStrEqualsIgnCase(key, "-l")) +bool ffOptionsParseLogoCommandLine(FFOptionsLogo* options, const char* key, const char* value) { + if (ffStrEqualsIgnCase(key, "-l")) { goto logoType; + } const char* subKey = ffOptionTestPrefix(key, "logo"); - if(subKey) - { - if (subKey[0] == '\0') - { -logoType: - if(value == NULL) - { + if (subKey) { + if (subKey[0] == '\0') { + logoType: + if (value == NULL) { fprintf(stderr, "Error: usage: %s \n", key); exit(477); } - //this is usually wanted when disabling logo - if(ffStrEqualsIgnCase(value, "none")) + // this is usually wanted when disabling logo + if (ffStrEqualsIgnCase(value, "none")) { options->type = FF_LOGO_TYPE_NONE; - else if(ffStrEqualsIgnCase(value, "small")) + } else if (ffStrEqualsIgnCase(value, "small")) { options->type = FF_LOGO_TYPE_SMALL; - else + } else { ffOptionParseString(key, value, &options->source); - } - else if(ffStrEqualsIgnCase(subKey, "type")) - { + } + } else if (ffStrEqualsIgnCase(subKey, "type")) { options->type = (FFLogoType) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "auto", FF_LOGO_TYPE_AUTO }, - { "builtin", FF_LOGO_TYPE_BUILTIN }, - { "small", FF_LOGO_TYPE_SMALL }, - { "file", FF_LOGO_TYPE_FILE }, - { "file-raw", FF_LOGO_TYPE_FILE_RAW }, - { "data", FF_LOGO_TYPE_DATA }, - { "data-raw", FF_LOGO_TYPE_DATA_RAW }, - { "command-raw", FF_LOGO_TYPE_COMMAND_RAW }, - { "sixel", FF_LOGO_TYPE_IMAGE_SIXEL }, - { "kitty", FF_LOGO_TYPE_IMAGE_KITTY }, - { "kitty-direct", FF_LOGO_TYPE_IMAGE_KITTY_DIRECT }, - { "kitty-icat", FF_LOGO_TYPE_IMAGE_KITTY_ICAT }, - { "iterm", FF_LOGO_TYPE_IMAGE_ITERM }, - { "chafa", FF_LOGO_TYPE_IMAGE_CHAFA }, - { "raw", FF_LOGO_TYPE_IMAGE_RAW }, - { "none", FF_LOGO_TYPE_NONE }, - {}, - }); - } - else if(ffStrStartsWithIgnCase(subKey, "color-") && subKey[6] != '\0' && subKey[7] == '\0') // matches "--logo-color-*" + {"auto", FF_LOGO_TYPE_AUTO}, + {"builtin", FF_LOGO_TYPE_BUILTIN}, + {"small", FF_LOGO_TYPE_SMALL}, + {"file", FF_LOGO_TYPE_FILE}, + {"file-raw", FF_LOGO_TYPE_FILE_RAW}, + {"data", FF_LOGO_TYPE_DATA}, + {"data-raw", FF_LOGO_TYPE_DATA_RAW}, + {"command-raw", FF_LOGO_TYPE_COMMAND_RAW}, + {"sixel", FF_LOGO_TYPE_IMAGE_SIXEL}, + {"kitty", FF_LOGO_TYPE_IMAGE_KITTY}, + {"kitty-direct", FF_LOGO_TYPE_IMAGE_KITTY_DIRECT}, + {"kitty-icat", FF_LOGO_TYPE_IMAGE_KITTY_ICAT}, + {"iterm", FF_LOGO_TYPE_IMAGE_ITERM}, + {"chafa", FF_LOGO_TYPE_IMAGE_CHAFA}, + {"raw", FF_LOGO_TYPE_IMAGE_RAW}, + {"none", FF_LOGO_TYPE_NONE}, + {}, + }); + } else if (ffStrStartsWithIgnCase(subKey, "color-") && subKey[6] != '\0' && subKey[7] == '\0') // matches "--logo-color-*" { - //Map the number to an array index, so that '1' -> 0, '2' -> 1, etc. - int index = (int)subKey[6] - '0' - 1; + // Map the number to an array index, so that '1' -> 0, '2' -> 1, etc. + int index = (int) subKey[6] - '0' - 1; - //Match only --logo-color-[1-9] - if(index < 0 || index >= FASTFETCH_LOGO_MAX_COLORS) - { + // Match only --logo-color-[1-9] + if (index < 0 || index >= FASTFETCH_LOGO_MAX_COLORS) { fprintf(stderr, "Error: invalid --color-[1-9] index: %c\n", key[13]); exit(472); } - if(value == NULL) - { + if (value == NULL) { fprintf(stderr, "Error: usage: %s \n", key); exit(477); } ffOptionParseColor(value, &options->colors[index]); - } - else if(ffStrEqualsIgnCase(subKey, "width")) + } else if (ffStrEqualsIgnCase(subKey, "width")) { options->width = ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subKey, "height")) + } else if (ffStrEqualsIgnCase(subKey, "height")) { options->height = ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subKey, "padding")) - { + } else if (ffStrEqualsIgnCase(subKey, "padding")) { uint32_t padding = ffOptionParseUInt32(key, value); options->paddingLeft = padding; options->paddingRight = padding; - } - else if(ffStrEqualsIgnCase(subKey, "padding-top")) + } else if (ffStrEqualsIgnCase(subKey, "padding-top")) { options->paddingTop = ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subKey, "padding-left")) + } else if (ffStrEqualsIgnCase(subKey, "padding-left")) { options->paddingLeft = ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subKey, "padding-right")) + } else if (ffStrEqualsIgnCase(subKey, "padding-right")) { options->paddingRight = ffOptionParseUInt32(key, value); - else if(ffStrEqualsIgnCase(subKey, "print-remaining")) + } else if (ffStrEqualsIgnCase(subKey, "print-remaining")) { options->printRemaining = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(subKey, "preserve-aspect-ratio")) + } else if (ffStrEqualsIgnCase(subKey, "preserve-aspect-ratio")) { options->preserveAspectRatio = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(subKey, "recache")) + } else if (ffStrEqualsIgnCase(subKey, "recache")) { options->recache = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(subKey, "separate")) - { + } else if (ffStrEqualsIgnCase(subKey, "separate")) { fputs("--logo-separate has been renamed to --logo-position\n", stderr); exit(477); - } - else if(ffStrEqualsIgnCase(subKey, "position")) - { + } else if (ffStrEqualsIgnCase(subKey, "position")) { options->position = (FFLogoPosition) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "left", FF_LOGO_POSITION_LEFT }, - { "right", FF_LOGO_POSITION_RIGHT }, - { "top", FF_LOGO_POSITION_TOP }, - {}, - }); - } - else + {"left", FF_LOGO_POSITION_LEFT}, + {"right", FF_LOGO_POSITION_RIGHT}, + {"top", FF_LOGO_POSITION_TOP}, + {}, + }); + } else { return false; - } - else if((subKey = ffOptionTestPrefix(key, "file"))) - { - if(subKey[0] == '\0') - { + } + } else if ((subKey = ffOptionTestPrefix(key, "file"))) { + if (subKey[0] == '\0') { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_FILE; - } - else if(ffStrEqualsIgnCase(subKey, "raw")) - { + } else if (ffStrEqualsIgnCase(subKey, "raw")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_FILE_RAW; - } - else + } else { return false; - } - else if((subKey = ffOptionTestPrefix(key, "data"))) - { - if(subKey[0] == '\0') - { + } + } else if ((subKey = ffOptionTestPrefix(key, "data"))) { + if (subKey[0] == '\0') { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_DATA; - } - else if(ffStrEqualsIgnCase(subKey, "raw")) - { + } else if (ffStrEqualsIgnCase(subKey, "raw")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_DATA_RAW; - } - else + } else { return false; - } - else if(ffStrEqualsIgnCase(key, "--sixel")) - { + } + } else if (ffStrEqualsIgnCase(key, "--sixel")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_IMAGE_SIXEL; - } - else if(ffStrEqualsIgnCase(key, "--kitty")) - { + } else if (ffStrEqualsIgnCase(key, "--kitty")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_IMAGE_KITTY; - } - else if(ffStrEqualsIgnCase(key, "--kitty-direct")) - { + } else if (ffStrEqualsIgnCase(key, "--kitty-direct")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_IMAGE_KITTY_DIRECT; - } - else if(ffStrEqualsIgnCase(key, "--kitty-icat")) - { + } else if (ffStrEqualsIgnCase(key, "--kitty-icat")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_IMAGE_KITTY_ICAT; - } - else if(ffStrEqualsIgnCase(key, "--iterm")) - { + } else if (ffStrEqualsIgnCase(key, "--iterm")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_IMAGE_ITERM; - } - else if(ffStrEqualsIgnCase(key, "--raw")) - { + } else if (ffStrEqualsIgnCase(key, "--raw")) { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_IMAGE_RAW; - } - else if((subKey = ffOptionTestPrefix(key, "chafa"))) - { - if(subKey[0] == '\0') - { + } else if ((subKey = ffOptionTestPrefix(key, "chafa"))) { + if (subKey[0] == '\0') { ffOptionParseString(key, value, &options->source); options->type = FF_LOGO_TYPE_IMAGE_CHAFA; - } - else if(ffStrEqualsIgnCase(subKey, "fg-only")) + } else if (ffStrEqualsIgnCase(subKey, "fg-only")) { options->chafaFgOnly = ffOptionParseBoolean(value); - else if(ffStrEqualsIgnCase(subKey, "symbols")) + } else if (ffStrEqualsIgnCase(subKey, "symbols")) { ffOptionParseString(key, value, &options->chafaSymbols); - else if(ffStrEqualsIgnCase(subKey, "canvas-mode")) - { + } else if (ffStrEqualsIgnCase(subKey, "canvas-mode")) { options->chafaCanvasMode = (uint32_t) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "TRUECOLOR", 0 }, - { "INDEXED_256", 1 }, - { "INDEXED_240", 2 }, - { "INDEXED_16", 3 }, - { "FGBG_BGFG", 4 }, - { "FGBG", 5 }, - { "INDEXED_8", 6 }, - { "INDEXED_16_8", 7 }, - {}, - }); - } - else if(ffStrEqualsIgnCase(subKey, "color-space")) - { + {"TRUECOLOR", 0}, + {"INDEXED_256", 1}, + {"INDEXED_240", 2}, + {"INDEXED_16", 3}, + {"FGBG_BGFG", 4}, + {"FGBG", 5}, + {"INDEXED_8", 6}, + {"INDEXED_16_8", 7}, + {}, + }); + } else if (ffStrEqualsIgnCase(subKey, "color-space")) { options->chafaColorSpace = (uint32_t) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "RGB", 0 }, - { "DIN99D", 1 }, - {}, - }); - } - else if(ffStrEqualsIgnCase(subKey, "dither-mode")) - { + {"RGB", 0}, + {"DIN99D", 1}, + {}, + }); + } else if (ffStrEqualsIgnCase(subKey, "dither-mode")) { options->chafaDitherMode = (uint32_t) ffOptionParseEnum(key, value, (FFKeyValuePair[]) { - { "NONE", 0 }, - { "ORDERED", 1 }, - { "DIFFUSION", 2 }, - {}, - }); - } - else + {"NONE", 0}, + {"ORDERED", 1}, + {"DIFFUSION", 2}, + {}, + }); + } else { return false; - } - else + } + } else { return false; + } return true; } -void ffOptionsDestroyLogo(FFOptionsLogo* options) -{ +void ffOptionsDestroyLogo(FFOptionsLogo* options) { ffStrbufDestroy(&options->source); ffStrbufDestroy(&options->chafaSymbols); - for(uint8_t i = 0; i < (uint8_t) FASTFETCH_LOGO_MAX_COLORS; ++i) + for (uint8_t i = 0; i < (uint8_t) FASTFETCH_LOGO_MAX_COLORS; ++i) { ffStrbufDestroy(&options->colors[i]); + } } -const char* ffOptionsParseLogoJsonConfig(FFOptionsLogo* options, yyjson_val* root) -{ +const char* ffOptionsParseLogoJsonConfig(FFOptionsLogo* options, yyjson_val* root) { yyjson_val* object = yyjson_obj_get(root, "logo"); - if (!object) return NULL; - if (yyjson_is_null(object)) - { + if (!object) { + return NULL; + } + if (yyjson_is_null(object)) { options->type = FF_LOGO_TYPE_NONE; options->paddingTop = 0; options->paddingRight = 0; @@ -261,218 +217,206 @@ const char* ffOptionsParseLogoJsonConfig(FFOptionsLogo* options, yyjson_val* roo return NULL; } - if (yyjson_is_str(object)) - { + if (yyjson_is_str(object)) { ffStrbufSetJsonVal(&options->source, object); return NULL; } - if (!yyjson_is_obj(object)) return "Property 'logo' must be an object"; + if (!yyjson_is_obj(object)) { + return "Property 'logo' must be an object"; + } yyjson_val *key, *val; size_t idx, max; - yyjson_obj_foreach(object, idx, max, key, val) - { - if (unsafe_yyjson_equals_str(key, "type")) - { + yyjson_obj_foreach (object, idx, max, key, val) { + if (unsafe_yyjson_equals_str(key, "type")) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "auto", FF_LOGO_TYPE_AUTO }, - { "builtin", FF_LOGO_TYPE_BUILTIN }, - { "small", FF_LOGO_TYPE_SMALL }, - { "file", FF_LOGO_TYPE_FILE }, - { "file-raw", FF_LOGO_TYPE_FILE_RAW }, - { "data", FF_LOGO_TYPE_DATA }, - { "data-raw", FF_LOGO_TYPE_DATA_RAW }, - { "command-raw", FF_LOGO_TYPE_COMMAND_RAW }, - { "sixel", FF_LOGO_TYPE_IMAGE_SIXEL }, - { "kitty", FF_LOGO_TYPE_IMAGE_KITTY }, - { "kitty-direct", FF_LOGO_TYPE_IMAGE_KITTY_DIRECT }, - { "kitty-icat", FF_LOGO_TYPE_IMAGE_KITTY_ICAT }, - { "iterm", FF_LOGO_TYPE_IMAGE_ITERM }, - { "chafa", FF_LOGO_TYPE_IMAGE_CHAFA }, - { "raw", FF_LOGO_TYPE_IMAGE_RAW }, - { "none", FF_LOGO_TYPE_NONE }, - {}, - }); + {"auto", FF_LOGO_TYPE_AUTO}, + {"builtin", FF_LOGO_TYPE_BUILTIN}, + {"small", FF_LOGO_TYPE_SMALL}, + {"file", FF_LOGO_TYPE_FILE}, + {"file-raw", FF_LOGO_TYPE_FILE_RAW}, + {"data", FF_LOGO_TYPE_DATA}, + {"data-raw", FF_LOGO_TYPE_DATA_RAW}, + {"command-raw", FF_LOGO_TYPE_COMMAND_RAW}, + {"sixel", FF_LOGO_TYPE_IMAGE_SIXEL}, + {"kitty", FF_LOGO_TYPE_IMAGE_KITTY}, + {"kitty-direct", FF_LOGO_TYPE_IMAGE_KITTY_DIRECT}, + {"kitty-icat", FF_LOGO_TYPE_IMAGE_KITTY_ICAT}, + {"iterm", FF_LOGO_TYPE_IMAGE_ITERM}, + {"chafa", FF_LOGO_TYPE_IMAGE_CHAFA}, + {"raw", FF_LOGO_TYPE_IMAGE_RAW}, + {"none", FF_LOGO_TYPE_NONE}, + {}, + }); - if (error) return error; + if (error) { + return error; + } options->type = (FFLogoType) value; continue; - } - else if (unsafe_yyjson_equals_str(key, "source")) - { + } else if (unsafe_yyjson_equals_str(key, "source")) { ffStrbufSetJsonVal(&options->source, val); continue; - } - else if (unsafe_yyjson_equals_str(key, "color")) - { - if (!yyjson_is_obj(val)) + } else if (unsafe_yyjson_equals_str(key, "color")) { + if (!yyjson_is_obj(val)) { return "Property 'color' must be an object"; + } yyjson_val *keyc, *valc; size_t idxc, maxc; - yyjson_obj_foreach(val, idxc, maxc, keyc, valc) - { + yyjson_obj_foreach (val, idxc, maxc, keyc, valc) { uint32_t index = (uint32_t) strtoul(unsafe_yyjson_get_str(keyc), NULL, 10); - if (index < 1 || index > FASTFETCH_LOGO_MAX_COLORS) + if (index < 1 || index > FASTFETCH_LOGO_MAX_COLORS) { return "Keys of property 'color' must be a number between 1 to 9"; + } ffOptionParseColor(yyjson_get_str(valc), &options->colors[index - 1]); } continue; - } - else if (unsafe_yyjson_equals_str(key, "width")) - { - if (yyjson_is_null(val)) + } else if (unsafe_yyjson_equals_str(key, "width")) { + if (yyjson_is_null(val)) { options->width = 0; - else - { + } else { uint32_t value = (uint32_t) yyjson_get_uint(val); - if (value == 0) + if (value == 0) { return "Logo width must be a positive integer"; + } options->width = value; } continue; - } - else if (unsafe_yyjson_equals_str(key, "height")) - { - if (yyjson_is_null(val)) + } else if (unsafe_yyjson_equals_str(key, "height")) { + if (yyjson_is_null(val)) { options->height = 0; - else - { + } else { uint32_t value = (uint32_t) yyjson_get_uint(val); - if (value == 0) + if (value == 0) { return "Logo height must be a positive integer"; + } options->height = value; } continue; - } - else if (unsafe_yyjson_equals_str(key, "padding")) - { - if (!yyjson_is_obj(val)) + } else if (unsafe_yyjson_equals_str(key, "padding")) { + if (!yyjson_is_obj(val)) { return "Logo padding must be an object"; + } - #define FF_PARSE_PADDING_POSITON(pos, paddingPos) \ - yyjson_val* pos = yyjson_obj_get(val, #pos); \ - if (pos) \ - { \ - if (!yyjson_is_uint(pos)) \ - return "Logo padding values must be positive integers"; \ - options->paddingPos = (uint32_t) yyjson_get_uint(pos); \ - } +#define FF_PARSE_PADDING_POSITON(pos, paddingPos) \ + yyjson_val* pos = yyjson_obj_get(val, #pos); \ + if (pos) { \ + if (!yyjson_is_uint(pos)) \ + return "Logo padding values must be positive integers"; \ + options->paddingPos = (uint32_t) yyjson_get_uint(pos); \ + } FF_PARSE_PADDING_POSITON(left, paddingLeft); FF_PARSE_PADDING_POSITON(top, paddingTop); FF_PARSE_PADDING_POSITON(right, paddingRight); - #undef FF_PARSE_PADDING_POSITON +#undef FF_PARSE_PADDING_POSITON continue; - } - else if (unsafe_yyjson_equals_str(key, "printRemaining")) - { + } else if (unsafe_yyjson_equals_str(key, "printRemaining")) { options->printRemaining = yyjson_get_bool(val); continue; - } - else if (unsafe_yyjson_equals_str(key, "preserveAspectRatio")) - { + } else if (unsafe_yyjson_equals_str(key, "preserveAspectRatio")) { options->preserveAspectRatio = yyjson_get_bool(val); continue; - } - else if (unsafe_yyjson_equals_str(key, "recache")) - { + } else if (unsafe_yyjson_equals_str(key, "recache")) { options->recache = yyjson_get_bool(val); continue; - } - else if (unsafe_yyjson_equals_str(key, "position")) - { + } else if (unsafe_yyjson_equals_str(key, "position")) { int value; const char* error = ffJsonConfigParseEnum(val, &value, (FFKeyValuePair[]) { - { "left", FF_LOGO_POSITION_LEFT }, - { "top", FF_LOGO_POSITION_TOP }, - { "right", FF_LOGO_POSITION_RIGHT }, - {}, - }); + {"left", FF_LOGO_POSITION_LEFT}, + {"top", FF_LOGO_POSITION_TOP}, + {"right", FF_LOGO_POSITION_RIGHT}, + {}, + }); - if (error) return error; + if (error) { + return error; + } options->position = (FFLogoPosition) value; continue; - } - else if (unsafe_yyjson_equals_str(key, "chafa")) - { - if (!yyjson_is_obj(val)) + } else if (unsafe_yyjson_equals_str(key, "chafa")) { + if (!yyjson_is_obj(val)) { return "Chafa config must be an object"; + } yyjson_val* fgOnly = yyjson_obj_get(val, "fgOnly"); - if (fgOnly) + if (fgOnly) { options->chafaFgOnly = yyjson_get_bool(fgOnly); + } yyjson_val* symbols = yyjson_obj_get(val, "symbols"); - if (symbols) + if (symbols) { ffStrbufSetJsonVal(&options->chafaSymbols, symbols); + } yyjson_val* canvasMode = yyjson_obj_get(val, "canvasMode"); - if (canvasMode) - { + if (canvasMode) { int value; const char* error = ffJsonConfigParseEnum(canvasMode, &value, (FFKeyValuePair[]) { - { "TRUECOLOR", 0 }, - { "INDEXED_256", 1 }, - { "INDEXED_240", 2 }, - { "INDEXED_16", 3 }, - { "FGBG_BGFG", 4 }, - { "FGBG", 5 }, - { "INDEXED_8", 6 }, - { "INDEXED_16_8", 7 }, - {}, - }); + {"TRUECOLOR", 0}, + {"INDEXED_256", 1}, + {"INDEXED_240", 2}, + {"INDEXED_16", 3}, + {"FGBG_BGFG", 4}, + {"FGBG", 5}, + {"INDEXED_8", 6}, + {"INDEXED_16_8", 7}, + {}, + }); - if (error) return error; + if (error) { + return error; + } options->chafaCanvasMode = (uint32_t) value; } yyjson_val* colorSpace = yyjson_obj_get(val, "colorSpace"); - if (colorSpace) - { + if (colorSpace) { int value; const char* error = ffJsonConfigParseEnum(colorSpace, &value, (FFKeyValuePair[]) { - { "RGB", 0 }, - { "DIN99D", 1 }, - {}, - }); + {"RGB", 0}, + {"DIN99D", 1}, + {}, + }); - if (error) return error; + if (error) { + return error; + } options->chafaColorSpace = (uint32_t) value; } yyjson_val* ditherMode = yyjson_obj_get(val, "ditherMode"); - if (ditherMode) - { + if (ditherMode) { int value; const char* error = ffJsonConfigParseEnum(ditherMode, &value, (FFKeyValuePair[]) { - { "NONE", 0 }, - { "ORDERED", 1 }, - { "DIFFUSION", 2 }, - {}, - }); + {"NONE", 0}, + {"ORDERED", 1}, + {"DIFFUSION", 2}, + {}, + }); - if (error) return error; + if (error) { + return error; + } options->chafaDitherMode = (uint32_t) value; } continue; - } - else + } else { return "Unknown logo key"; + } } return NULL; } -void ffOptionsGenerateLogoJsonConfig(FFdata* data, FFOptionsLogo* options) -{ +void ffOptionsGenerateLogoJsonConfig(FFdata* data, FFOptionsLogo* options) { yyjson_mut_doc* doc = data->resultDoc; yyjson_mut_val* obj = yyjson_mut_obj(doc); - switch (options->type) - { + switch (options->type) { case FF_LOGO_TYPE_NONE: yyjson_mut_obj_add_null(doc, doc->root, "logo"); return; @@ -527,23 +471,24 @@ void ffOptionsGenerateLogoJsonConfig(FFdata* data, FFOptionsLogo* options) { yyjson_mut_val* color = yyjson_mut_obj(doc); - for (int i = 0; i < FASTFETCH_LOGO_MAX_COLORS; i++) - { - char c = (char)('1' + i); + for (int i = 0; i < FASTFETCH_LOGO_MAX_COLORS; i++) { + char c = (char) ('1' + i); yyjson_mut_obj_add(color, yyjson_mut_strncpy(doc, &c, 1), yyjson_mut_strbuf(doc, &options->colors[i])); } yyjson_mut_obj_add_val(doc, obj, "color", color); } - if (options->width == 0) + if (options->width == 0) { yyjson_mut_obj_add_null(doc, obj, "width"); - else + } else { yyjson_mut_obj_add_uint(doc, obj, "width", options->width); + } - if (options->height == 0) + if (options->height == 0) { yyjson_mut_obj_add_null(doc, obj, "height"); - else + } else { yyjson_mut_obj_add_uint(doc, obj, "height", options->height); + } { yyjson_mut_val* padding = yyjson_mut_obj_add_obj(doc, obj, "padding"); @@ -558,43 +503,40 @@ void ffOptionsGenerateLogoJsonConfig(FFdata* data, FFOptionsLogo* options) yyjson_mut_obj_add_bool(doc, obj, "recache", options->recache); - yyjson_mut_obj_add_str(doc, obj, "position", ((const char* []) { - "left", - "top", - "right", - })[options->position]); + yyjson_mut_obj_add_str(doc, obj, "position", ((const char*[]) { + "left", + "top", + "right", + })[options->position]); { yyjson_mut_val* chafa = yyjson_mut_obj(doc); yyjson_mut_obj_add_bool(doc, chafa, "fgOnly", options->chafaFgOnly); yyjson_mut_obj_add_strbuf(doc, chafa, "symbols", &options->chafaSymbols); - if (options->chafaCanvasMode <= 7) - { - yyjson_mut_obj_add_str(doc, chafa, "canvasMode", ((const char* []) { - "TRUECOLOR", - "INDEXED_256", - "INDEXED_240", - "INDEXED_16", - "FGBG_BGFG", - "FGBG", - "INDEXED_8", - "INDEXED_16_8", - })[options->chafaCanvasMode]); + if (options->chafaCanvasMode <= 7) { + yyjson_mut_obj_add_str(doc, chafa, "canvasMode", ((const char*[]) { + "TRUECOLOR", + "INDEXED_256", + "INDEXED_240", + "INDEXED_16", + "FGBG_BGFG", + "FGBG", + "INDEXED_8", + "INDEXED_16_8", + })[options->chafaCanvasMode]); } - if (options->chafaColorSpace <= 1) - { - yyjson_mut_obj_add_str(doc, chafa, "colorSpace", ((const char* []) { - "RGB", - "DIN99D", - })[options->chafaColorSpace]); + if (options->chafaColorSpace <= 1) { + yyjson_mut_obj_add_str(doc, chafa, "colorSpace", ((const char*[]) { + "RGB", + "DIN99D", + })[options->chafaColorSpace]); } - if (options->chafaDitherMode <= 2) - { - yyjson_mut_obj_add_str(doc, chafa, "ditherMode", ((const char* []) { - "NONE", - "ORDERED", - "DIFFUSION", - })[options->chafaDitherMode]); + if (options->chafaDitherMode <= 2) { + yyjson_mut_obj_add_str(doc, chafa, "ditherMode", ((const char*[]) { + "NONE", + "ORDERED", + "DIFFUSION", + })[options->chafaDitherMode]); } yyjson_mut_obj_add_val(doc, obj, "chafa", chafa); diff --git a/src/options/logo.h b/src/options/logo.h index dc2d84705..83e2d7860 100644 --- a/src/options/logo.h +++ b/src/options/logo.h @@ -5,8 +5,7 @@ #define FASTFETCH_LOGO_MAX_NAMES 9 #define FASTFETCH_LOGO_MAX_COLORS 9 // two digits would make parsing much more complicated (index 1 - 9) -typedef enum __attribute__((__packed__)) FFLogoType -{ +typedef enum __attribute__((__packed__)) FFLogoType { FF_LOGO_TYPE_AUTO, // if something is given, first try builtin, then file. Otherwise detect logo FF_LOGO_TYPE_BUILTIN, // builtin ascii art FF_LOGO_TYPE_SMALL, // builtin ascii art, small version @@ -25,15 +24,13 @@ typedef enum __attribute__((__packed__)) FFLogoType FF_LOGO_TYPE_NONE, // `--logo none`, but still applies colors to the system information output (unless `--pipe` is set) } FFLogoType; -typedef enum __attribute__((__packed__)) FFLogoPosition -{ +typedef enum __attribute__((__packed__)) FFLogoPosition { FF_LOGO_POSITION_LEFT, FF_LOGO_POSITION_TOP, FF_LOGO_POSITION_RIGHT, } FFLogoPosition; -typedef struct FFOptionsLogo -{ +typedef struct FFOptionsLogo { FFstrbuf source; FFLogoType type; FFLogoPosition position; diff --git a/tests/color.c b/tests/color.c index 45cdd51a0..90121d606 100644 --- a/tests/color.c +++ b/tests/color.c @@ -4,12 +4,10 @@ #include -static void verify(const char* color, const char* expected, int lineNo) -{ +static void verify(const char* color, const char* expected, int lineNo) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); ffOptionParseColorNoClear(color, &result); - if (!ffStrbufEqualS(&result, expected)) - { + if (!ffStrbufEqualS(&result, expected)) { fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "[%d] %s: expected \"%s\", got \"%s\"\n" FASTFETCH_TEXT_MODIFIER_RESET, lineNo, color, expected, result.chars); exit(1); } @@ -17,11 +15,10 @@ static void verify(const char* color, const char* expected, int lineNo) #define VERIFY(color, expected) verify((color), (expected), __LINE__) -int main(void) -{ +int main(void) { instance.config.display.pipe = true; // Initialize dummy config colors for property tests - ffStrbufInitS(&instance.config.display.colorKeys, "94"); // light_blue + ffStrbufInitS(&instance.config.display.colorKeys, "94"); // light_blue ffStrbufInitS(&instance.config.display.colorTitle, "95"); // light_magenta { @@ -39,8 +36,8 @@ int main(void) VERIFY("italic_underline_green", "3;4;32"); VERIFY("reset_blue", "0;34"); // Reset followed by color - VERIFY("#ff0000", "38;2;255;0;0"); // RRGGBB - VERIFY("#0f0", "38;2;0;255;0"); // RGB + VERIFY("#ff0000", "38;2;255;0;0"); // RRGGBB + VERIFY("#0f0", "38;2;0;255;0"); // RGB VERIFY("#123456", "38;2;18;52;86"); VERIFY("#abc", "38;2;170;187;204"); @@ -52,7 +49,7 @@ int main(void) VERIFY("bold_#ff00ff", "1;38;2;255;0;255"); VERIFY("underline_#123", "4;38;2;17;34;51"); - VERIFY("\e[32m", "32"); // Direct ANSI code + VERIFY("\e[32m", "32"); // Direct ANSI code VERIFY("\e[1;94m", "1;94"); // Direct ANSI code with mode // Property colors (ensure dummy config colors are set) @@ -65,6 +62,6 @@ int main(void) ffStrbufDestroy(&instance.config.display.colorKeys); ffStrbufDestroy(&instance.config.display.colorTitle); - //Success + // Success puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET); } diff --git a/tests/duration.c b/tests/duration.c index a8f2aacea..9d28ce1e1 100644 --- a/tests/duration.c +++ b/tests/duration.c @@ -4,12 +4,10 @@ #include -static void verify(uint64_t totalSeconds, const char* expected, int lineNo) -{ +static void verify(uint64_t totalSeconds, const char* expected, int lineNo) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); ffDurationAppendNum(totalSeconds, &result); - if (!ffStrbufEqualS(&result, expected)) - { + if (!ffStrbufEqualS(&result, expected)) { fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "[%d] %llu: expected \"%s\", got \"%s\"\n" FASTFETCH_TEXT_MODIFIER_RESET, lineNo, (unsigned long long) totalSeconds, expected, result.chars); exit(1); } @@ -17,8 +15,7 @@ static void verify(uint64_t totalSeconds, const char* expected, int lineNo) #define VERIFY(color, expected) verify((color), (expected), __LINE__) -int main(void) -{ +int main(void) { // Test seconds less than 60 VERIFY(0, "0 seconds"); VERIFY(1, "1 second"); @@ -115,6 +112,6 @@ int main(void) VERIFY(60 * 60 * 24 * 100, "100d"); VERIFY(60 * 60 * 24 * 200, "200d"); - //Success + // Success puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET); } diff --git a/tests/format.c b/tests/format.c index cecce2498..984666dc3 100644 --- a/tests/format.c +++ b/tests/format.c @@ -4,16 +4,12 @@ #include -static void verify(const char* format, const char* arg, const char* expected, int lineNo) -{ +static void verify(const char* format, const char* arg, const char* expected, int lineNo) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY formatter = ffStrbufCreateStatic(format); - const FFformatarg arguments[] = { - { .type = FF_ARG_TYPE_STRING, arg } - }; + const FFformatarg arguments[] = { {.type = FF_ARG_TYPE_STRING, arg}}; ffParseFormatString(&result, &formatter, 1, arguments); - if (!ffStrbufEqualS(&result, expected)) - { + if (!ffStrbufEqualS(&result, expected)) { fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "[%d] %s: expected \"%s\", got \"%s\"\n" FASTFETCH_TEXT_MODIFIER_RESET, lineNo, format, expected, result.chars); exit(1); } @@ -21,101 +17,100 @@ static void verify(const char* format, const char* arg, const char* expected, in #define VERIFY(format, argument, expected) verify((format), (argument), (expected), __LINE__) -int main(void) -{ +int main(void) { instance.config.display.pipe = true; { - VERIFY("output({})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1})", "12345 67890", "output(12345 67890)"); - VERIFY("output({})", "", "output()"); - VERIFY("output({1})", "", "output()"); + VERIFY("output({})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1})", "12345 67890", "output(12345 67890)"); + VERIFY("output({})", "", "output()"); + VERIFY("output({1})", "", "output()"); } { - VERIFY("output({1:20})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1:11})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1:-11})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1:6})", "12345 67890", "output(12345)"); - VERIFY("output({:6})", "12345 67890", "output(12345)"); - VERIFY("output({:-6})", "12345 67890", "output(12345…)"); - VERIFY("output({:0})", "12345 67890", "output()"); - VERIFY("output({:})", "12345 67890", "output()"); + VERIFY("output({1:20})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1:11})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1:-11})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1:6})", "12345 67890", "output(12345)"); + VERIFY("output({:6})", "12345 67890", "output(12345)"); + VERIFY("output({:-6})", "12345 67890", "output(12345…)"); + VERIFY("output({:0})", "12345 67890", "output()"); + VERIFY("output({:})", "12345 67890", "output()"); } { - VERIFY("output({1<20})", "12345 67890", "output(12345 67890 )"); - VERIFY("output({1<-20})", "12345 67890", "output(12345 67890 )"); - VERIFY("output({1<11})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1<-11})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1<6})", "12345 67890", "output(12345 )"); - VERIFY("output({<6})", "12345 67890", "output(12345 )"); - VERIFY("output({<-6})", "12345 67890", "output(12345…)"); - VERIFY("output({<0})", "12345 67890", "output()"); - VERIFY("output({<})", "12345 67890", "output()"); + VERIFY("output({1<20})", "12345 67890", "output(12345 67890 )"); + VERIFY("output({1<-20})", "12345 67890", "output(12345 67890 )"); + VERIFY("output({1<11})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1<-11})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1<6})", "12345 67890", "output(12345 )"); + VERIFY("output({<6})", "12345 67890", "output(12345 )"); + VERIFY("output({<-6})", "12345 67890", "output(12345…)"); + VERIFY("output({<0})", "12345 67890", "output()"); + VERIFY("output({<})", "12345 67890", "output()"); } { - VERIFY("output({1>20})", "12345 67890", "output( 12345 67890)"); - VERIFY("output({1>-20})", "12345 67890", "output( 12345 67890)"); - VERIFY("output({1>11})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1>-11})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1>6})", "12345 67890", "output(12345 )"); - VERIFY("output({>6})", "12345 67890", "output(12345 )"); - VERIFY("output({>-6})", "12345 67890", "output(12345…)"); - VERIFY("output({>0})", "12345 67890", "output()"); - VERIFY("output({>})", "12345 67890", "output()"); + VERIFY("output({1>20})", "12345 67890", "output( 12345 67890)"); + VERIFY("output({1>-20})", "12345 67890", "output( 12345 67890)"); + VERIFY("output({1>11})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1>-11})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1>6})", "12345 67890", "output(12345 )"); + VERIFY("output({>6})", "12345 67890", "output(12345 )"); + VERIFY("output({>-6})", "12345 67890", "output(12345…)"); + VERIFY("output({>0})", "12345 67890", "output()"); + VERIFY("output({>})", "12345 67890", "output()"); } { - VERIFY("output({1n>20})", "12345 67890", "output({1n>20})"); - VERIFY("output({120})", "12345 67890", "output({120})"); - VERIFY("output({1:11})", "", "output()"); - VERIFY("output({2:2})", "", "output({2:2})"); + VERIFY("output({1n>20})", "12345 67890", "output({1n>20})"); + VERIFY("output({120})", "12345 67890", "output({120})"); + VERIFY("output({1:11})", "", "output()"); + VERIFY("output({2:2})", "", "output({2:2})"); } { - VERIFY("output({1~0})", "12345 67890", "output(12345 67890)"); - VERIFY("output({1~1})", "12345 67890", "output(2345 67890)"); - VERIFY("output({1~10})", "12345 67890", "output(0)"); - VERIFY("output({1~20})", "12345 67890", "output()"); - VERIFY("output({1~-5})", "12345 67890", "output(67890)"); - VERIFY("output({1~-50})", "12345 67890", "output()"); - VERIFY("output({1~0,1})", "12345 67890", "output(1)"); - VERIFY("output({1~0,6})", "12345 67890", "output(12345 )"); - VERIFY("output({1~0,10})", "12345 67890", "output(12345 6789)"); - VERIFY("output({1~5,10})", "12345 67890", "output( 6789)"); - VERIFY("output({1~5,100})", "12345 67890", "output( 67890)"); - VERIFY("output({1~10,10})", "12345 67890", "output()"); - VERIFY("output({1~10,5})", "12345 67890", "output()"); - VERIFY("output({1~3,-3})", "12345 67890", "output(45 67)"); - VERIFY("output({1~-5,-3})", "12345 67890", "output(67)"); - VERIFY("output({1~-0,10})", "12345 67890", "output(12345 6789)"); - VERIFY("output({1~-3,-5})", "12345 67890", "output()"); - VERIFY("output({1~})", "12345 67890", "output(12345 67890)"); // Same as {1~0} - VERIFY("output({1~-0})", "12345 67890", "output(12345 67890)"); // Same as {1~0} - VERIFY("output({1~,-1})", "12345 67890", "output(12345 6789)"); // Same as {1~0,-1} - VERIFY("output({1~,})", "12345 67890", "output()"); // Same as {1~0,0} + VERIFY("output({1~0})", "12345 67890", "output(12345 67890)"); + VERIFY("output({1~1})", "12345 67890", "output(2345 67890)"); + VERIFY("output({1~10})", "12345 67890", "output(0)"); + VERIFY("output({1~20})", "12345 67890", "output()"); + VERIFY("output({1~-5})", "12345 67890", "output(67890)"); + VERIFY("output({1~-50})", "12345 67890", "output()"); + VERIFY("output({1~0,1})", "12345 67890", "output(1)"); + VERIFY("output({1~0,6})", "12345 67890", "output(12345 )"); + VERIFY("output({1~0,10})", "12345 67890", "output(12345 6789)"); + VERIFY("output({1~5,10})", "12345 67890", "output( 6789)"); + VERIFY("output({1~5,100})", "12345 67890", "output( 67890)"); + VERIFY("output({1~10,10})", "12345 67890", "output()"); + VERIFY("output({1~10,5})", "12345 67890", "output()"); + VERIFY("output({1~3,-3})", "12345 67890", "output(45 67)"); + VERIFY("output({1~-5,-3})", "12345 67890", "output(67)"); + VERIFY("output({1~-0,10})", "12345 67890", "output(12345 6789)"); + VERIFY("output({1~-3,-5})", "12345 67890", "output()"); + VERIFY("output({1~})", "12345 67890", "output(12345 67890)"); // Same as {1~0} + VERIFY("output({1~-0})", "12345 67890", "output(12345 67890)"); // Same as {1~0} + VERIFY("output({1~,-1})", "12345 67890", "output(12345 6789)"); // Same as {1~0,-1} + VERIFY("output({1~,})", "12345 67890", "output()"); // Same as {1~0,0} } { - VERIFY("output({1n~0})", "12345 67890", "output({1n~0})"); - VERIFY("output({1~<0})", "12345 67890", "output({1~<0})"); - VERIFY("output({1~-})", "12345 67890", "output({1~-})"); - VERIFY("output({1~-,1})", "12345 67890", "output({1~-,1})"); - VERIFY("output({1~0,,1})", "12345 67890", "output({1~0,,1})"); - VERIFY("output({1~0,1,})", "12345 67890", "output({1~0,1,})"); - VERIFY("output({1~,0,1})", "12345 67890", "output({1~,0,1})"); - VERIFY("output({2,0})", "12345 67890", "output({2,0})"); + VERIFY("output({1n~0})", "12345 67890", "output({1n~0})"); + VERIFY("output({1~<0})", "12345 67890", "output({1~<0})"); + VERIFY("output({1~-})", "12345 67890", "output({1~-})"); + VERIFY("output({1~-,1})", "12345 67890", "output({1~-,1})"); + VERIFY("output({1~0,,1})", "12345 67890", "output({1~0,,1})"); + VERIFY("output({1~0,1,})", "12345 67890", "output({1~0,1,})"); + VERIFY("output({1~,0,1})", "12345 67890", "output({1~,0,1})"); + VERIFY("output({2,0})", "12345 67890", "output({2,0})"); } { - VERIFY("output({1:20}{1<20}{1>20})", "12345 67890", "output(12345 6789012345 67890 12345 67890)"); - VERIFY("output({?1}OK{?}{/1}NOT OK{/})", "12345 67890", "output(OK)"); - VERIFY("output({?1}OK{?}{/1}NOT OK{/})", "", "output(NOT OK)"); + VERIFY("output({1:20}{1<20}{1>20})", "12345 67890", "output(12345 6789012345 67890 12345 67890)"); + VERIFY("output({?1}OK{?}{/1}NOT OK{/})", "12345 67890", "output(OK)"); + VERIFY("output({?1}OK{?}{/1}NOT OK{/})", "", "output(NOT OK)"); } - #ifndef _WIN32 // Windows doesn't have setenv +#ifndef _WIN32 // Windows doesn't have setenv { ffListInit(&instance.config.display.constants, sizeof(FFstrbuf)); ffStrbufInitStatic(ffListAdd(&instance.config.display.constants), "CONST1"); @@ -133,8 +128,8 @@ int main(void) VERIFY("output({$1NO})", "", "output({$1NO})"); ffListDestroy(&instance.config.display.constants); } - #endif +#endif - //Success + // Success puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET); } diff --git a/tests/list.c b/tests/list.c index 70a5739b2..e43b88cac 100644 --- a/tests/list.c +++ b/tests/list.c @@ -6,14 +6,11 @@ #include #include -__attribute__((__noreturn__)) -static void testFailed(const FFlist* list, const char* expression, int lineNo) -{ +__attribute__((__noreturn__)) static void testFailed(const FFlist* list, const char* expression, int lineNo) { fputs(FASTFETCH_TEXT_MODIFIER_ERROR, stderr); fprintf(stderr, "[%d] %s, list:", lineNo, expression); - for (uint32_t i = 0; i < list->length; ++i) - { - fprintf(stderr, "%u ", *(uint32_t*)ffListGet(list, i)); + for (uint32_t i = 0; i < list->length; ++i) { + fprintf(stderr, "%u ", *(uint32_t*) ffListGet(list, i)); } fputc('\n', stderr); fputs(FASTFETCH_TEXT_MODIFIER_RESET, stderr); @@ -21,19 +18,18 @@ static void testFailed(const FFlist* list, const char* expression, int lineNo) exit(1); } -static bool numEqualsAdapter(const void* first, const void* second) -{ - return *(uint32_t*)first == *(uint32_t*)second; +static bool numEqualsAdapter(const void* first, const void* second) { + return *(uint32_t*) first == *(uint32_t*) second; } -#define VERIFY(expression) if(!(expression)) testFailed(&list, #expression, __LINE__) +#define VERIFY(expression) \ + if (!(expression)) testFailed(&list, #expression, __LINE__) -int main(void) -{ +int main(void) { FFlist list; uint32_t n = 0; - //initA + // initA ffListInit(&list, sizeof(uint32_t)); @@ -41,44 +37,42 @@ int main(void) VERIFY(list.capacity == 0); VERIFY(list.length == 0); - //forEach - FF_LIST_FOR_EACH(uint32_t, item, list) + // forEach + FF_LIST_FOR_EACH (uint32_t, item, list) { VERIFY(false); + } - //shift + // shift VERIFY(!ffListShift(&list, &n)); VERIFY(list.length == 0); - //pop + // pop VERIFY(!ffListPop(&list, &n)); VERIFY(list.length == 0); - //add - for (uint32_t i = 1; i <= FF_LIST_DEFAULT_ALLOC + 1; ++i) - { - *(uint32_t*)ffListAdd(&list) = i; + // add + for (uint32_t i = 1; i <= FF_LIST_DEFAULT_ALLOC + 1; ++i) { + *(uint32_t*) ffListAdd(&list) = i; VERIFY(list.elementSize == sizeof(uint32_t)); VERIFY(list.length == i); - if(i <= FF_LIST_DEFAULT_ALLOC) - { + if (i <= FF_LIST_DEFAULT_ALLOC) { VERIFY(list.capacity == FF_LIST_DEFAULT_ALLOC); - } - else - { + } else { VERIFY(list.capacity == FF_LIST_DEFAULT_ALLOC * 2); } - VERIFY(*(uint32_t*)ffListGet(&list, 0) == 1); - VERIFY(*(uint32_t*)ffListGet(&list, i - 1) == i); + VERIFY(*(uint32_t*) ffListGet(&list, 0) == 1); + VERIFY(*(uint32_t*) ffListGet(&list, i - 1) == i); } VERIFY(list.length == FF_LIST_DEFAULT_ALLOC + 1); uint32_t sum = 0; - //forEach - FF_LIST_FOR_EACH(uint32_t, item, list) + // forEach + FF_LIST_FOR_EACH (uint32_t, item, list) { sum += *item; + } VERIFY(sum == (1 + FF_LIST_DEFAULT_ALLOC + 1) * (FF_LIST_DEFAULT_ALLOC + 1) / 2); // ffListFirstIndexComp @@ -93,21 +87,21 @@ int main(void) n = 999; VERIFY(!ffListContains(&list, &n, numEqualsAdapter)); - //shift + // shift VERIFY(ffListShift(&list, &n)); VERIFY(n == 1); VERIFY(list.length == FF_LIST_DEFAULT_ALLOC); VERIFY(*(uint32_t*) ffListGet(&list, 0) == 2); VERIFY(*(uint32_t*) ffListGet(&list, list.length - 1) == FF_LIST_DEFAULT_ALLOC + 1); - //pop + // pop VERIFY(ffListPop(&list, &n)); VERIFY(n == FF_LIST_DEFAULT_ALLOC + 1); VERIFY(list.length == FF_LIST_DEFAULT_ALLOC - 1); VERIFY(*(uint32_t*) ffListGet(&list, 0) == 2); VERIFY(*(uint32_t*) ffListGet(&list, list.length - 1) == FF_LIST_DEFAULT_ALLOC); - //Destroy + // Destroy ffListDestroy(&list); VERIFY(list.elementSize == sizeof(uint32_t)); @@ -121,6 +115,6 @@ int main(void) VERIFY(test.length == 0); } - //Success - puts("\033[32mAll tests passed!"FASTFETCH_TEXT_MODIFIER_RESET); + // Success + puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET); } diff --git a/tests/strbuf.c b/tests/strbuf.c index 69f4ce1c7..9e63cfdd7 100644 --- a/tests/strbuf.c +++ b/tests/strbuf.c @@ -5,9 +5,7 @@ #include #include -__attribute__((__noreturn__)) -static void testFailed(const FFstrbuf* strbuf, const char* expression, int lineNo) -{ +__attribute__((__noreturn__)) static void testFailed(const FFstrbuf* strbuf, const char* expression, int lineNo) { fputs(FASTFETCH_TEXT_MODIFIER_ERROR, stderr); fprintf(stderr, "[%d] %s, strbuf:", lineNo, expression); ffStrbufWriteTo(strbuf, stderr); @@ -16,22 +14,22 @@ static void testFailed(const FFstrbuf* strbuf, const char* expression, int lineN exit(1); } -#define VERIFY(expression) if(!(expression)) testFailed(&strbuf, #expression, __LINE__) +#define VERIFY(expression) \ + if (!(expression)) testFailed(&strbuf, #expression, __LINE__) int shouldNotBeCalled(int c) { - (void)c; + (void) c; exit(1); } -int main(void) -{ +int main(void) { FFstrbuf strbuf; - //destroy 0 + // destroy 0 ffStrbufInit(&strbuf); ffStrbufDestroy(&strbuf); - //initA + // initA ffStrbufInit(&strbuf); @@ -45,7 +43,7 @@ int main(void) VERIFY(!ffStrbufEndsWithS(&strbuf, "0")); VERIFY(ffStrbufCountC(&strbuf, '0') == 0); - //Ensure following functions work with non-allocated string + // Ensure following functions work with non-allocated string ffStrbufAppendS(&strbuf, ""); ffStrbufAppendF(&strbuf, "%s", ""); ffStrbufAppendTransformS(&strbuf, "", shouldNotBeCalled); @@ -56,7 +54,7 @@ int main(void) VERIFY(strbuf.allocated == 0); VERIFY(strbuf.length == 0); - //append(N)C + // append(N)C ffStrbufAppendC(&strbuf, '1'); VERIFY(ffStrbufEqualS(&strbuf, "1")); @@ -66,7 +64,7 @@ int main(void) VERIFY(strbuf.allocated >= 6); ffStrbufClear(&strbuf); - //appendS + // appendS ffStrbufAppendS(&strbuf, "12345"); ffStrbufAppendS(&strbuf, NULL); @@ -75,7 +73,7 @@ int main(void) VERIFY(strbuf.allocated >= 6); VERIFY(ffStrbufEqualS(&strbuf, "12345")); - //appendNS + // appendNS ffStrbufAppendNS(&strbuf, 4, "67890"); ffStrbufAppendNS(&strbuf, 0, NULL); @@ -84,14 +82,14 @@ int main(void) VERIFY(strbuf.allocated >= 10); VERIFY(ffStrbufEqualS(&strbuf, "123456789")); - //appendS long + // appendS long ffStrbufAppendS(&strbuf, "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); VERIFY(strbuf.length == 109); VERIFY(strbuf.allocated >= 110); VERIFY(strbuf.chars[strbuf.length] == 0); - //substr + // substr VERIFY(ffStrbufSubstrBefore(&strbuf, 9)); VERIFY(strbuf.length == 9); @@ -113,52 +111,52 @@ int main(void) ffStrbufSetS(&strbuf, "123456789"); - //startsWithC + // startsWithC VERIFY(ffStrbufStartsWithC(&strbuf, '1')); VERIFY(!ffStrbufStartsWithC(&strbuf, '2')); - //startsWithS + // startsWithS VERIFY(ffStrbufStartsWithS(&strbuf, "123")); VERIFY(ffStrbufStartsWithS(&strbuf, "123456789")); VERIFY(!ffStrbufStartsWithS(&strbuf, "1234567890123")); - //endsWithC + // endsWithC VERIFY(ffStrbufEndsWithC(&strbuf, '9')); VERIFY(!ffStrbufEndsWithC(&strbuf, '1')); - //endsWithS + // endsWithS VERIFY(ffStrbufEndsWithS(&strbuf, "789")); VERIFY(ffStrbufEndsWithS(&strbuf, "123456789")); VERIFY(!ffStrbufEndsWithS(&strbuf, "1234567890123")); - //toNumber + // toNumber VERIFY(ffStrbufToDouble(&strbuf, -DBL_MAX) == 123456789.0); VERIFY(ffStrbufToUInt(&strbuf, 999) == 123456789); - //countC + // countC VERIFY(ffStrbufCountC(&strbuf, '1') == 1); VERIFY(ffStrbufCountC(&strbuf, '0') == 0); - //removeS + // removeS ffStrbufRemoveS(&strbuf, "78"); VERIFY(strbuf.length == 7); VERIFY(strcmp(strbuf.chars, "1234569") == 0); - //removeStrings + // removeStrings - ffStrbufRemoveStrings(&strbuf, 3, (const char*[]) { "23", "45", "9" }); + ffStrbufRemoveStrings(&strbuf, 3, (const char*[]) {"23", "45", "9"}); VERIFY(strbuf.length == 2); VERIFY(strcmp(strbuf.chars, "16") == 0); - //PrependS + // PrependS ffStrbufPrependS(&strbuf, "123"); ffStrbufPrependS(&strbuf, NULL); @@ -166,7 +164,7 @@ int main(void) VERIFY(strbuf.length == 5); VERIFY(strcmp(strbuf.chars, "12316") == 0); - //indexC + // indexC VERIFY(ffStrbufFirstIndexC(&strbuf, '1') == 0); VERIFY(ffStrbufNextIndexC(&strbuf, 1, '1') == 3); VERIFY(ffStrbufNextIndexC(&strbuf, 4, '1') == 5); @@ -175,12 +173,12 @@ int main(void) VERIFY(ffStrbufPreviousIndexC(&strbuf, 0, '1') == 0); VERIFY(ffStrbufPreviousIndexC(&strbuf, 0, '2') == 5); - //indexS + // indexS VERIFY(ffStrbufFirstIndexS(&strbuf, "12316") == 0); VERIFY(ffStrbufNextIndexS(&strbuf, 1, "1") == 3); VERIFY(ffStrbufNextIndexS(&strbuf, 4, "1") == 5); - //ignCase + // ignCase ffStrbufSetS(&strbuf, "AbCdEfG"); VERIFY(ffStrbufIgnCaseCompS(&strbuf, "aBcDeFg") == 0); @@ -189,25 +187,25 @@ int main(void) VERIFY(!ffStrbufStartsWithIgnCaseS(&strbuf, "aBcDeFgH")); VERIFY(!ffStrbufEndsWithIgnCaseS(&strbuf, "0aBcDeFg")); - //ensure + // ensure ffStrbufEnsureEndsWithC(&strbuf, '$'); VERIFY(ffStrbufEqualS(&strbuf, "AbCdEfG$")); ffStrbufEnsureEndsWithC(&strbuf, '$'); VERIFY(ffStrbufEqualS(&strbuf, "AbCdEfG$")); - //trimRight + // trimRight ffStrbufTrimRight(&strbuf, '$'); VERIFY(ffStrbufEqualS(&strbuf, "AbCdEfG")); ffStrbufTrimRight(&strbuf, '$'); VERIFY(ffStrbufEqualS(&strbuf, "AbCdEfG")); - //clear + // clear ffStrbufClear(&strbuf); VERIFY(strbuf.allocated > 0); VERIFY(strbuf.length == 0); VERIFY(strbuf.chars && strbuf.chars[0] == 0); - //Destroy + // Destroy ffStrbufDestroy(&strbuf); @@ -215,21 +213,21 @@ int main(void) VERIFY(strbuf.length == 0); VERIFY(strbuf.chars && strbuf.chars[0] == 0); - //initA + // initA ffStrbufInitA(&strbuf, 32); VERIFY(strbuf.allocated == 32); VERIFY(strbuf.length == 0); VERIFY(strbuf.chars && strbuf.chars[0] == 0); - //appendF + // appendF ffStrbufAppendF(&strbuf, "%s", "1234567890123456789012345678901"); VERIFY(strbuf.allocated == 32); VERIFY(ffStrbufEqualS(&strbuf, "1234567890123456789012345678901")); ffStrbufDestroy(&strbuf); - //initMoveS + // initMoveS { char* heapStr = strdup("1234567890"); ffStrbufInitMoveS(&strbuf, heapStr); @@ -238,34 +236,34 @@ int main(void) ffStrbufDestroy(&strbuf); } - //initF + // initF ffStrbufInitF(&strbuf, "%s", "1234567890123456789012345678901"); VERIFY(strbuf.allocated >= 32); VERIFY(ffStrbufEqualS(&strbuf, "1234567890123456789012345678901")); - //containC + // containC VERIFY(ffStrbufContainC(&strbuf, '1')); VERIFY(!ffStrbufContainC(&strbuf, '-')); - //replaceAllC + // replaceAllC ffStrbufReplaceAllC(&strbuf, '1', '-'); VERIFY(ffStrbufEqualS(&strbuf, "-234567890-234567890-234567890-")); ffStrbufReplaceAllC(&strbuf, '1', '-'); VERIFY(ffStrbufEqualS(&strbuf, "-234567890-234567890-234567890-")); - //trim + // trim ffStrbufTrim(&strbuf, '-'); VERIFY(ffStrbufEqualS(&strbuf, "234567890-234567890-234567890")); ffStrbufDestroy(&strbuf); - //ffStrbufCreateS + // ffStrbufCreateS { FF_STRBUF_AUTO_DESTROY testCreate = ffStrbufCreateS("TEST"); VERIFY(ffStrbufEqualS(&testCreate, "TEST")); } - //ffStrbufCreateStatic + // ffStrbufCreateStatic ffStrbufInitStatic(&strbuf, "TEST"); VERIFY(ffStrbufEqualS(&strbuf, "TEST")); VERIFY(strbuf.length == 4); @@ -275,14 +273,14 @@ int main(void) VERIFY(strbuf.length == 0); VERIFY(strbuf.allocated == 0); - //ffStrbufCreateStatic / Allocate + // ffStrbufCreateStatic / Allocate ffStrbufInitStatic(&strbuf, "TEST"); ffStrbufEnsureFree(&strbuf, 0); VERIFY(ffStrbufEqualS(&strbuf, "TEST")); VERIFY(strbuf.length == 4); VERIFY(strbuf.allocated > 0); - //ffStrbufCreateStatic / Append + // ffStrbufCreateStatic / Append ffStrbufInitStatic(&strbuf, "TEST"); ffStrbufAppendS(&strbuf, "_TEST"); VERIFY(ffStrbufEqualS(&strbuf, "TEST_TEST")); @@ -294,7 +292,7 @@ int main(void) VERIFY(strbuf.length == 0); VERIFY(strbuf.allocated == 0); - //ffStrbufCreateStatic / Prepend + // ffStrbufCreateStatic / Prepend ffStrbufInitStatic(&strbuf, "TEST"); ffStrbufPrependS(&strbuf, "TEST_"); VERIFY(ffStrbufEqualS(&strbuf, "TEST_TEST")); @@ -306,14 +304,14 @@ int main(void) VERIFY(strbuf.length == 0); VERIFY(strbuf.allocated == 0); - //ffStrbufCreateStatic / Clear + // ffStrbufCreateStatic / Clear ffStrbufInitStatic(&strbuf, "TEST"); ffStrbufClear(&strbuf); VERIFY(strbuf.length == 0); VERIFY(strbuf.allocated == 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / Set + // ffStrbufCreateStatic / Set ffStrbufInitStatic(&strbuf, "TEST"); // static ffStrbufSetStatic(&strbuf, "test"); VERIFY(ffStrbufEqualS(&strbuf, "test")); @@ -321,7 +319,7 @@ int main(void) VERIFY(strbuf.allocated == 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / Set + // ffStrbufCreateStatic / Set ffStrbufInitS(&strbuf, "TEST"); // allocated ffStrbufSetStatic(&strbuf, "test"); VERIFY(ffStrbufEqualS(&strbuf, "test")); @@ -329,7 +327,7 @@ int main(void) VERIFY(strbuf.allocated == 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / TrimL + // ffStrbufCreateStatic / TrimL ffStrbufInitStatic(&strbuf, "_TEST_"); ffStrbufTrimLeft(&strbuf, '_'); VERIFY(ffStrbufEqualS(&strbuf, "TEST_")); @@ -337,7 +335,7 @@ int main(void) VERIFY(strbuf.allocated == 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / TrimR + // ffStrbufCreateStatic / TrimR ffStrbufInitStatic(&strbuf, "_TEST_"); ffStrbufTrimRight(&strbuf, ' '); VERIFY(strbuf.allocated == 0); @@ -348,7 +346,7 @@ int main(void) VERIFY(strbuf.allocated > 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / Substr + // ffStrbufCreateStatic / Substr ffStrbufInitStatic(&strbuf, "__TEST__"); VERIFY(ffStrbufRemoveSubstr(&strbuf, 0, 6)); VERIFY(ffStrbufEqualS(&strbuf, "__")); @@ -356,7 +354,7 @@ int main(void) VERIFY(strbuf.allocated > 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / Substr + // ffStrbufCreateStatic / Substr ffStrbufInitStatic(&strbuf, "__TEST__"); VERIFY(ffStrbufRemoveSubstr(&strbuf, 2, 8)); VERIFY(ffStrbufEqualS(&strbuf, "__")); @@ -364,7 +362,7 @@ int main(void) VERIFY(strbuf.allocated > 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / Substr + // ffStrbufCreateStatic / Substr ffStrbufInitStatic(&strbuf, "__TEST__"); VERIFY(ffStrbufRemoveSubstr(&strbuf, 2, 6)); VERIFY(ffStrbufEqualS(&strbuf, "____")); @@ -372,7 +370,7 @@ int main(void) VERIFY(strbuf.allocated > 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / ReplaceAllC + // ffStrbufCreateStatic / ReplaceAllC ffStrbufInitStatic(&strbuf, "__TEST__"); ffStrbufReplaceAllC(&strbuf, '_', '-'); VERIFY(ffStrbufEqualS(&strbuf, "--TEST--")); @@ -380,7 +378,7 @@ int main(void) VERIFY(strbuf.allocated > 0); ffStrbufDestroy(&strbuf); - //ffStrbufCreateStatic / TrimSpace + // ffStrbufCreateStatic / TrimSpace ffStrbufInitStatic(&strbuf, "\n TEST\n "); ffStrbufTrimSpace(&strbuf); VERIFY(strbuf.length == 4); @@ -388,7 +386,7 @@ int main(void) VERIFY(ffStrbufEqualS(&strbuf, "TEST")); ffStrbufDestroy(&strbuf); - //ffStrbufCreate / TrimSpace + // ffStrbufCreate / TrimSpace ffStrbufInitS(&strbuf, "\n TEST\n "); ffStrbufTrimSpace(&strbuf); VERIFY(strbuf.length == 4); @@ -396,7 +394,7 @@ int main(void) VERIFY(ffStrbufEqualS(&strbuf, "TEST")); ffStrbufDestroy(&strbuf); - //ffStrbufEnsureFixedLengthFree / empty buffer + // ffStrbufEnsureFixedLengthFree / empty buffer ffStrbufInit(&strbuf); ffStrbufEnsureFixedLengthFree(&strbuf, 10); VERIFY(strbuf.length == 0); @@ -411,14 +409,14 @@ int main(void) VERIFY(strbuf.allocated == 13); ffStrbufDestroy(&strbuf); - //ffStrbufEnsureFixedLengthFree / empty buffer with zero free length + // ffStrbufEnsureFixedLengthFree / empty buffer with zero free length ffStrbufInit(&strbuf); ffStrbufEnsureFixedLengthFree(&strbuf, 0); VERIFY(strbuf.length == 0); VERIFY(strbuf.allocated == 0); ffStrbufDestroy(&strbuf); - //ffStrbufEnsureFixedLengthFree / empty buffer but oldFree >= newFree + // ffStrbufEnsureFixedLengthFree / empty buffer but oldFree >= newFree ffStrbufInitA(&strbuf, 11); ffStrbufEnsureFixedLengthFree(&strbuf, 10); VERIFY(strbuf.length == 0); @@ -430,7 +428,7 @@ int main(void) VERIFY(strbuf.allocated == 12); ffStrbufDestroy(&strbuf); - //ffStrbufEnsureFixedLengthFree / non empty buffer + // ffStrbufEnsureFixedLengthFree / non empty buffer ffStrbufAppendF(&strbuf, "%s", "1234567890"); VERIFY(strbuf.length == 10); VERIFY(strbuf.allocated == 32); @@ -448,7 +446,7 @@ int main(void) VERIFY(strbuf.allocated == 33); ffStrbufDestroy(&strbuf); - //ffStrbufEnsureFixedLengthFree / static buffer + // ffStrbufEnsureFixedLengthFree / static buffer ffStrbufInitStatic(&strbuf, "__TEST__"); VERIFY(strbuf.length > 0); VERIFY(strbuf.allocated == 0); @@ -458,7 +456,7 @@ int main(void) VERIFY(ffStrbufEqualS(&strbuf, "__TEST__")); ffStrbufDestroy(&strbuf); - //ffStrbufInsertNC + // ffStrbufInsertNC ffStrbufInitStatic(&strbuf, "123456"); ffStrbufInsertNC(&strbuf, 0, 2, 'A'); VERIFY(ffStrbufEqualS(&strbuf, "AA123456")); @@ -490,11 +488,9 @@ int main(void) const char* text = "Processor\t: ARMv7\nprocessor\t: 0\nBogoMIPS\t: 38.00\n\nprocessor\t: 1\nBogoMIPS\t: 38.00"; ffStrbufSetS(&strbuf, text); - while (ffStrbufGetline(&lineptr, &n, &strbuf)) - { + while (ffStrbufGetline(&lineptr, &n, &strbuf)) { ++i; - switch (i) - { + switch (i) { case 1: VERIFY(strcmp(lineptr, "Processor\t: ARMv7") == 0); VERIFY(n == strlen("Processor\t: ARMv7")); @@ -533,11 +529,9 @@ int main(void) i = 0; text = "\n"; ffStrbufSetS(&strbuf, text); - while (ffStrbufGetline(&lineptr, &n, &strbuf)) - { + while (ffStrbufGetline(&lineptr, &n, &strbuf)) { ++i; - switch (i) - { + switch (i) { case 1: VERIFY(strcmp(lineptr, "") == 0); VERIFY(n == 0); @@ -556,11 +550,9 @@ int main(void) i = 0; text = "abcd"; ffStrbufSetS(&strbuf, text); - while (ffStrbufGetline(&lineptr, &n, &strbuf)) - { + while (ffStrbufGetline(&lineptr, &n, &strbuf)) { ++i; - switch (i) - { + switch (i) { case 1: VERIFY(strcmp(lineptr, "abcd") == 0); VERIFY(n == strlen("abcd")); @@ -579,8 +571,7 @@ int main(void) i = 0; text = ""; ffStrbufSetS(&strbuf, text); - while (ffStrbufGetline(&lineptr, &n, &strbuf)) - { + while (ffStrbufGetline(&lineptr, &n, &strbuf)) { ++i; VERIFY(false); } @@ -1058,7 +1049,7 @@ int main(void) VERIFY(ffStrbufEqualS(&strbuf, "abc\\x2G")); } - //setS + // setS ffStrbufInitStatic(&strbuf, "STATIC"); ffStrbufSetS(&strbuf, "DYNAMIC"); VERIFY(ffStrbufEqualS(&strbuf, "DYNAMIC")); @@ -1101,7 +1092,7 @@ int main(void) VERIFY(strbuf.allocated == 0); ffStrbufDestroy(&strbuf); - //set + // set ffStrbufInitStatic(&strbuf, "STATIC"); { FF_STRBUF_AUTO_DESTROY other = ffStrbufCreateS("DYNAMIC"); @@ -1147,6 +1138,6 @@ int main(void) VERIFY(strbuf.allocated == 0); ffStrbufDestroy(&strbuf); - //Success + // Success puts("\e[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET); }