[hackers] [slstatus][PATCH] suggestion: add user defined format callback

From: Tobias Tschinkowitz <he4d_AT_posteo.de>
Date: Thu, 17 May 2018 20:48:54 +0200

Hi!

This is just a suggestion, so not really something to commit right away.
What do you think about a callback function where the user could define
more precisely how formatting is done (like adding symbols for
percentages etc.)

I just prepared a little patch to show what i mean.

Greetings,
Tobias

---
 config.def.h | 16 +++++++++++++---
 slstatus.c   | 15 ++++++++++++---
 2 files changed, 25 insertions(+), 6 deletions(-)
diff --git a/config.def.h b/config.def.h
index 9dcd5d6..b92fbac 100644
--- a/config.def.h
+++ b/config.def.h
_AT_@ -6,6 +6,15 @@ static const unsigned int interval = 1000;
 /* text to show if no value can be retrieved */
 static const char unknown_str[] = "n/a";
 
+/* example callback function for custom formatting */
+void
+wifi_perc_cb(const char *raw_val, char *res, int res_len)
+{
+	char *s[] = { "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█", "█" };
+	int perc = atoi(raw_val);
+	snprintf(res, res_len, "%s %s ", raw_val, s[((8 * perc) / 100)]);
+}
+
 /* maximum output string length */
 #define MAXLEN 2048
 
_AT_@ -54,6 +63,7 @@ static const char unknown_str[] = "n/a";
  * wifi_essid           WiFi ESSID                      interface name (wlan0)
  */
 static const struct arg args[] = {
-	/* function format          argument */
-	{ datetime, "%s",           "%F %T" },
-};
+	/* function	format	format_cb	argument */
+	{ wifi_perc,	NULL,	wifi_perc_cb,	"iwn0"  },
+	{ datetime, 	"%s",	NULL,           "%F %T" },
+};
diff --git a/slstatus.c b/slstatus.c
index e8d367b..614d703 100644
--- a/slstatus.c
+++ b/slstatus.c
_AT_@ -14,6 +14,7 @@
 struct arg {
 	const char *(*func)();
 	const char *fmt;
+	void (*fmt_cb)(const char *, char *, int);
 	const char *args;
 };
 
_AT_@ -88,9 +89,17 @@ main(int argc, char *argv[])
 		for (i = len = 0; i < LEN(args); i++) {
 			const char * res = args[i].func(args[i].args);
 			res = (res == NULL) ? unknown_str : res;
-			len += snprintf(status + len, sizeof(status) - len,
-			                args[i].fmt, res);
-
+			if (args[i].fmt_cb) {
+				char cb_res[64];
+				args[i].fmt_cb(res, cb_res, 64);
+				strlcat(status + len, cb_res,
+					sizeof(status) - len);
+				len += strlen(cb_res);
+			} else {
+				len += snprintf(status + len,
+					sizeof(status) - len,
+					args[i].fmt, res);
+			}
 			if (len >= sizeof(status)) {
 				status[sizeof(status) - 1] = '\0';
 			}
-- 
2.16.2
Received on Thu May 17 2018 - 20:48:54 CEST

This archive was generated by hypermail 2.3.0 : Thu May 17 2018 - 21:00:26 CEST