summaryrefslogtreecommitdiff
path: root/wallpapers.c
blob: 53ea10217cebd03363574b848b1b443ed7a8bf3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include <Imlib2.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <glib/gprintf.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

#include "wallpapers.h"

void add_dir_recursive(const char *path, sqlite_uint64 parent) {
	int pathlen = strlen(path);
	GDir *dir;
	const char *filename;
	sqlite_uint64 dir_temp;
	sqlite_uint64 dirid;
	char *filepath;
	struct stat st;
	GdkPixbuf *pixbuf;
	GError *error;
	
	dirid = db_get_directory(path);
	if(dirid == 0) {
		dirid = db_add_directory(path, parent);
		if(dirid == 0)
			return;
	}

	dir = g_dir_open(path, 0, NULL);
	if(!dir)
		return;

	while((filename = g_dir_read_name(dir)) != NULL) {
		filepath = g_strdup_printf("%s/%s", path, filename);

		if(db_get_wallpaper(filepath) != 0) {
			continue;
		}

		if(g_access(filepath, R_OK) == -1) {
			fprintf(stderr, "Can't read %s: \n", filepath, strerror(errno));
			g_free(filepath);
			continue;
		}

		if(g_stat(filepath, &st) == -1) {
			fprintf(stderr, "Failed to stat file %s\n", filepath);
			g_free(filepath);
			continue;
		}

		switch(st.st_mode & S_IFMT) {
			case S_IFDIR:
				if(strcmp(filepath, ".") == 0 || strcmp(filepath, "..") == 0) {
					g_free(filepath);
					continue;
				}
				printf("Directory: %s\n", filepath);
				add_dir_recursive(filepath, dirid);
				g_free(filepath);
				continue;
			case S_IFLNK:
			case S_IFREG:
				break;
			default:
				printf("Skipping %s\n", filepath);
				g_free(filepath);
				continue;
		}

		pixbuf = gdk_pixbuf_new_from_file(filepath, &error);
		if(!pixbuf) {
			g_warning("%s", error->message);
			continue;
		}
		printf("%s loaded: %dx%d\n", filepath, gdk_pixbuf_get_width(pixbuf), gdk_pixbuf_get_height(pixbuf));
		if(db_add_wallpaper(filepath, dirid, st.st_size, gdk_pixbuf_get_width(pixbuf), gdk_pixbuf_get_height(pixbuf)))
			printf("added\n");
		else
			printf("failed to add\n");
		g_object_unref(pixbuf);
		g_free(filepath);
	}
	g_dir_close(dir);
}