master ohmu/fastfetch-openbsd / src / modules / gamepad / gamepad.c
ohmu  ·  2026-10-15
  1#include "common/percent.h"
  2#include "common/printing.h"
  3#include "common/jsonconfig.h"
  4#include "common/strutil.h"
  5#include "detection/gamepad/gamepad.h"
  6#include "modules/gamepad/gamepad.h"
  7
  8static void printDevice(FFGamepadOptions* options, const FFGamepadDevice* device, uint8_t index) {
  9    FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type;
 10    if (options->moduleArgs.outputFormat.length == 0) {
 11        ffPrintLogoAndKey(FF_MODULE_GET_DISPLAY_NAME(Gamepad), index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT);
 12
 13        FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
 14        bool showBatteryLevel = device->battery > 0 && device->battery <= 100;
 15
 16        if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_BAR_BIT)) {
 17            ffPercentAppendBar(&buffer, device->battery, options->percent, &options->moduleArgs);
 18            ffStrbufAppendC(&buffer, ' ');
 19        }
 20
 21        if (!(percentType & FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT)) {
 22            ffStrbufAppend(&buffer, &device->name);
 23        }
 24
 25        if (showBatteryLevel && (percentType & FF_PERCENTAGE_TYPE_NUM_BIT)) {
 26            if (buffer.length) {
 27                ffStrbufAppendC(&buffer, ' ');
 28            }
 29            ffPercentAppendNum(&buffer, device->battery, options->percent, buffer.length > 0, &options->moduleArgs);
 30        }
 31        ffStrbufPutTo(&buffer, stdout);
 32    } else {
 33        FF_STRBUF_AUTO_DESTROY percentageNum = ffStrbufCreate();
 34        if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) {
 35            ffPercentAppendNum(&percentageNum, device->battery, options->percent, false, &options->moduleArgs);
 36        }
 37        FF_STRBUF_AUTO_DESTROY percentageBar = ffStrbufCreate();
 38        if (percentType & FF_PERCENTAGE_TYPE_BAR_BIT) {
 39            ffPercentAppendBar(&percentageBar, device->battery, options->percent, &options->moduleArgs);
 40        }
 41
 42        FF_PRINT_FORMAT_CHECKED(FF_MODULE_GET_DISPLAY_NAME(Gamepad), index, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, ((FFformatarg[]) {
 43                                                                                                                FF_ARG(device->name, "name"),
 44                                                                                                                FF_ARG(device->serial, "serial"),
 45                                                                                                                FF_ARG(percentageNum, "battery-percentage"),
 46                                                                                                                FF_ARG(percentageBar, "battery-percentage-bar"),
 47                                                                                                            }));
 48    }
 49}
 50
 51bool ffPrintGamepad(FFGamepadOptions* options) {
 52    FF_LIST_AUTO_DESTROY result = ffListCreate();
 53
 54    const char* error = ffDetectGamepad(&result);
 55
 56    if (error) {
 57        ffPrintError(FF_MODULE_GET_DISPLAY_NAME(Gamepad), 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", error);
 58        return false;
 59    }
 60
 61    if (!result.length) {
 62        ffPrintError(FF_MODULE_GET_DISPLAY_NAME(Gamepad), 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "No devices detected");
 63        return false;
 64    }
 65
 66    FF_LIST_AUTO_DESTROY filtered = ffListCreate();
 67    FF_LIST_FOR_EACH (FFGamepadDevice, device, result) {
 68        bool ignored = false;
 69        FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) {
 70            if (ffStrbufStartsWithIgnCase(&device->name, ignore)) {
 71                ignored = true;
 72                break;
 73            }
 74        }
 75        if (!ignored) {
 76            FFGamepadDevice** ptr = FF_LIST_ADD(FFGamepadDevice*, filtered);
 77            *ptr = device;
 78        }
 79    }
 80
 81    bool ret = true;
 82    if (!filtered.length) {
 83        ffPrintError(FF_MODULE_GET_DISPLAY_NAME(Gamepad), 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "All devices are ignored");
 84        ret = false;
 85    } else {
 86        uint8_t index = 0;
 87        FF_LIST_FOR_EACH (FFGamepadDevice*, pdevice, filtered) {
 88            FFGamepadDevice* device = *pdevice;
 89            printDevice(options, device, filtered.length > 1 ? ++index : 0);
 90        }
 91    }
 92
 93    // `filtered` only holds borrowed pointers, so the strings of all devices — including the ignored
 94    // ones — have to be released here, not in the printing branch
 95    FF_LIST_FOR_EACH (FFGamepadDevice, device, result) {
 96        ffStrbufDestroy(&device->serial);
 97        ffStrbufDestroy(&device->name);
 98    }
 99
100    return ret;
101}
102
103void ffParseGamepadJsonObject(FFGamepadOptions* options, yyjson_val* module) {
104    yyjson_val *key, *val;
105    size_t idx, max;
106    yyjson_obj_foreach (module, idx, max, key, val) {
107        if (ffJsonConfigParseModuleArgs(key, val, &options->moduleArgs)) {
108            continue;
109        }
110
111        if (unsafe_yyjson_equals_str(key, "ignores")) {
112            yyjson_val* elem;
113            size_t eidx, emax;
114            yyjson_arr_foreach (val, eidx, emax, elem) {
115                if (yyjson_is_str(elem)) {
116                    FFstrbuf* strbuf = FF_LIST_ADD(FFstrbuf, options->ignores);
117                    ffStrbufInitJsonVal(strbuf, elem);
118                }
119            }
120            continue;
121        }
122
123        if (ffPercentParseJsonObject(key, val, &options->percent)) {
124            continue;
125        }
126
127        ffPrintError(FF_MODULE_GET_DISPLAY_NAME(Gamepad), 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key));
128    }
129}
130
131[[gnu::cold]]
132void ffGenerateGamepadJsonConfig(FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) {
133    ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs);
134
135    if (options->ignores.length > 0) {
136        yyjson_mut_val* ignores = yyjson_mut_obj_add_arr(doc, module, "ignores");
137        FF_LIST_FOR_EACH (FFstrbuf, strbuf, options->ignores) {
138            yyjson_mut_arr_append(ignores, yyjson_mut_strncpy(doc, strbuf->chars, strbuf->length));
139        }
140    }
141    ffPercentGenerateJsonConfig(doc, module, options->percent);
142}
143
144bool ffGenerateGamepadJsonResult([[maybe_unused]] FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) {
145    FF_LIST_AUTO_DESTROY result = ffListCreate();
146
147    const char* error = ffDetectGamepad(&result);
148
149    if (error) {
150        yyjson_mut_obj_add_str(doc, module, "error", error);
151        return false;
152    }
153
154    yyjson_mut_val* arr = yyjson_mut_obj_add_arr(doc, module, "result");
155    FF_LIST_FOR_EACH (FFGamepadDevice, device, result) {
156        yyjson_mut_val* obj = yyjson_mut_arr_add_obj(doc, arr);
157        yyjson_mut_obj_add_strbuf(doc, obj, "serial", &device->serial);
158        yyjson_mut_obj_add_strbuf(doc, obj, "name", &device->name);
159        // 0 means "the device does not report a battery level", not "empty battery"
160        yyjson_mut_obj_add_uint(doc, obj, "battery", device->battery);
161
162        bool ignored = false;
163        FF_LIST_FOR_EACH (FFstrbuf, ignore, options->ignores) {
164            if (ffStrbufStartsWithIgnCase(&device->name, ignore)) {
165                ignored = true;
166                break;
167            }
168        }
169        yyjson_mut_obj_add_bool(doc, obj, "ignored", ignored);
170    }
171
172    FF_LIST_FOR_EACH (FFGamepadDevice, device, result) {
173        ffStrbufDestroy(&device->serial);
174        ffStrbufDestroy(&device->name);
175    }
176
177    return true;
178}
179
180void ffInitGamepadOptions(FFGamepadOptions* options) {
181    ffOptionInitModuleArg(&options->moduleArgs, "󰺵");
182
183    ffListInit(&options->ignores);
184    options->percent = (FFPercentageModuleConfig) { 50, 20, 0 };
185}
186
187void ffDestroyGamepadOptions(FFGamepadOptions* options) {
188    ffOptionDestroyModuleArg(&options->moduleArgs);
189
190    FF_LIST_FOR_EACH (FFstrbuf, str, options->ignores) {
191        ffStrbufDestroy(str);
192    }
193    ffListDestroy(&options->ignores);
194}
195
196FFModuleBaseInfo ffGamepadModuleInfo = {
197    .name = "Gamepad",
198    .description = "List connected gamepads",
199    .displayName = {
200        .en = "Gamepad",
201        .ar = "يد التحكم",
202        .cs = "Gamepad",
203        .de = "Gamepad",
204        .es = "Gamepad",
205        .fi = "Peliohjain",
206        .fr = "Manette",
207        .gl = "Gamepad",
208        .he = "משטח משחק",
209        .id = "Gamepad",
210        .it = "Gamepad",
211        .ja = "ゲームパッド",
212        .ko = "게임패드",
213        .pl = "Gamepad",
214        .pt = "Gamepad",
215        .ru = "Геймпад",
216        .tr = "Oyun Kumandası",
217        .uk = "Геймпад",
218        .vi = "Tay cầm chơi game",
219        .zh_CN = "游戏手柄",
220        .zh_TW = "遊戲手把",
221    },
222    .initOptions = (void*) ffInitGamepadOptions,
223    .destroyOptions = (void*) ffDestroyGamepadOptions,
224    .parseJsonObject = (void*) ffParseGamepadJsonObject,
225    .printModule = (void*) ffPrintGamepad,
226    .generateJsonResult = (void*) ffGenerateGamepadJsonResult,
227    .generateJsonConfig = (void*) ffGenerateGamepadJsonConfig,
228    .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) {
229        { "Name", "name" },
230        { "Serial number", "serial" },
231        { "Battery percentage num", "battery-percentage" },
232        { "Battery percentage bar", "battery-percentage-bar" },
233    })),
234    .defaultOrder = 63,
235};