Files
lotherkandClaude Sonnet 5.5 d53ea094e7 licence: CNCL for what Makronix wrote itself
LICENSE at the root; the 103 files new in ext/src/mcde (none was in the CDE
import) carry the CNCL line instead of the LGPL notice.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 11:48:02 +00:00

102 lines
2.1 KiB
C

/*
* items.c -- dtbar: the lists behind Favourites and Recent Items (items.h)
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <string.h>
#include "items.h"
static char *
Trim(char *s)
{
char *e;
while (*s == ' ' || *s == '\t')
s++;
e = s + strlen(s);
while (e > s && (e[-1] == '\n' || e[-1] == '\r' || e[-1] == ' ' ||
e[-1] == '\t'))
*--e = '\0';
return s;
}
int
ItemsRead(const char *file, Item *items, int max)
{
char line[1024], *s, *tab;
FILE *fp = fopen(file, "r");
int n = 0;
if (fp == NULL)
return 0;
while (n < max && fgets(line, sizeof line, fp) != NULL) {
/* split at the tab first: trimming would eat a leading one */
tab = strchr(line, '\t');
if (tab != NULL)
*tab = '\0';
s = Trim(line);
if (tab == NULL && (*s == '\0' || *s == '#'))
continue;
if (*s == '#')
continue;
memset(&items[n], 0, sizeof items[n]);
if (tab != NULL) {
snprintf(items[n].label, sizeof items[n].label, "%s", s);
snprintf(items[n].command, sizeof items[n].command, "%s",
Trim(tab + 1));
} else {
snprintf(items[n].label, sizeof items[n].label, "%s", s);
snprintf(items[n].command, sizeof items[n].command, "%s",
s);
}
if (items[n].label[0] != '\0' && items[n].command[0] != '\0')
n++;
}
fclose(fp);
return n;
}
int
ItemsWrite(const char *file, const Item *items, int n)
{
char tmp[1024];
FILE *fp;
int i;
if ((size_t) snprintf(tmp, sizeof tmp, "%s.new", file) >= sizeof tmp ||
(fp = fopen(tmp, "w")) == NULL)
return -1;
for (i = 0; i < n; i++)
fprintf(fp, "%s\t%s\n", items[i].label, items[i].command);
if (fclose(fp) != 0 || rename(tmp, file) != 0) {
remove(tmp);
return -1;
}
return 0;
}
int
ItemsPush(Item *items, int n, int max, const Item *item)
{
Item keep = *item;
int i;
for (i = 0; i < n; i++)
if (strcmp(items[i].command, item->command) == 0) {
memmove(&items[i], &items[i + 1],
(size_t) (n - i - 1) * sizeof *items);
n--;
break;
}
if (n >= max)
n = max - 1;
memmove(&items[1], &items[0], (size_t) n * sizeof *items);
items[0] = keep;
return n + 1;
}