aboutsummaryrefslogtreecommitdiff
path: root/src/palette.c
diff options
context:
space:
mode:
authorKrow Savcik <krow@savcik.xyz>2023-09-26 22:32:35 +0300
committerKrow Savcik <krow@savcik.xyz>2023-09-26 22:32:35 +0300
commit9e660e594f6d3a43ea1427fb872801a2fcedad93 (patch)
tree459cd0c6fc5fef0366f7ef249ae19dd67c363772 /src/palette.c
initial commit
Diffstat (limited to 'src/palette.c')
-rw-r--r--src/palette.c113
1 files changed, 113 insertions, 0 deletions
diff --git a/src/palette.c b/src/palette.c
new file mode 100644
index 0000000..3584e55
--- /dev/null
+++ b/src/palette.c
@@ -0,0 +1,113 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "palette.h"
+#include "debug.h"
+#include "types.h"
+
+Palette *
+palette_clone(const Palette *p)
+{
+ Palette *res;
+
+ /* TODO: better malloc (place list and num together) */
+ res = malloc(sizeof(Palette));
+ res->clist = malloc(p->num*sizeof(*p->clist));
+
+ res->num = p->num;
+ memcpy(res->clist, p->clist, p->num * sizeof(*p->clist));
+
+ return res;
+}
+
+static char *
+palette_intern_get_num(char *s, int *a)
+{
+ while (*s == ' ' || *s == '\t')
+ ++s;
+ if (*s == '\n')
+ *a = -1;
+ else {
+ *a = 0;
+ while (*s >= '0' && *s <= '9') {
+ *a = (*a) * 10;
+ *a += (int) (*s-'0');
+ ++s;
+ }
+ }
+
+ return s;
+}
+
+static uint8
+palette_intern_get_color(char *s, Color *c)
+{
+ int a;
+ char *st = s;
+
+ st = palette_intern_get_num(st, &a);
+ if (a < 0 || a > 255) return 1;
+ c->r = a;
+
+ st = palette_intern_get_num(st, &a);
+ if (a < 0 || a > 255) return 1;
+ c->g = a;
+
+ st = palette_intern_get_num(st, &a);
+ if (a < 0 || a > 255) return 1;
+ c->b = a;
+
+ return 0;
+}
+
+static uint
+palette_intern_get_color_number(const char *s)
+{
+ FILE *fp;
+ char line[1024];
+ size_t len = 1024;
+ uint ans = 0;
+
+ fp = fopen(s, "r");
+ while (fgets(line, len, fp)) {
+ if (line[0] >= '0' && line[0] <= '9')
+ ++ans;
+ }
+ fclose(fp);
+
+ return ans;
+}
+
+Palette *
+palette_open_gpl(const char *p)
+{
+ /* TODO: check if file exists */
+ /* TODO: better parsing */
+ /* TODO: better malloc (place list and num together) */
+ Palette *res;
+ FILE *fp;
+ Color *c;
+ char line[1024];
+ size_t len = 1024;
+
+ res = malloc(sizeof(Palette));
+ res->num = palette_intern_get_color_number(p);
+ res->clist = malloc(res->num*sizeof(*res->clist));
+ c = res->clist;
+
+ fp = fopen(p, "r");
+ while (fgets(line, len, fp)) {
+ if (line[0] >= '0' && line[0] <= '9') {
+ if (palette_intern_get_color(line, c)) {
+ free(res->clist);
+ free(res);
+ return NULL;
+ }
+ c++;
+ }
+ }
+ fclose(fp);
+
+ return res;
+}