[PATCH 4/6] clients: image: pick random image when no arguments are passed

Tiago Vignatti vignatti at freedesktop.org
Wed Dec 21 09:34:12 PST 2011


From: Tiago Vignatti <tiago.vignatti at intel.com>

Signed-off-by: Tiago Vignatti <tiago.vignatti at intel.com>
---
 clients/image.c |   52 ++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 50 insertions(+), 2 deletions(-)

diff --git a/clients/image.c b/clients/image.c
index 13115d2..b12a360 100644
--- a/clients/image.c
+++ b/clients/image.c
@@ -27,6 +27,8 @@
 #include <string.h>
 #include <fcntl.h>
 #include <unistd.h>
+#include <dirent.h>
+#include <sys/time.h>
 #include <math.h>
 #include <time.h>
 #include <cairo.h>
@@ -233,6 +235,48 @@ image_create(struct display *display, uint32_t key, const char *filename)
 	return image;
 }
 
+static int
+filter(const struct dirent *entry)
+{
+	if ((strcmp(entry->d_name, ".") == 0) ||
+	    (strcmp(entry->d_name, "..") == 0))
+		return 0;
+
+	if ((strstr(entry->d_name, ".jpg") == NULL) &&
+	   (strstr(entry->d_name, ".png") == NULL))
+		return 0;
+
+	return 1;
+}
+
+#define IMAGES_DIR "/usr/share/backgrounds/"
+
+static char *
+get_image_random(void)
+{
+	struct dirent **namelist;
+	struct timeval tv;
+	int n, seed, index;
+	char *str;
+
+	n = scandir(IMAGES_DIR, &namelist, filter, alphasort);
+	if (n < 0) {
+		fprintf (stderr, "Couldn't open the directory\n");
+		return NULL;
+	}
+
+	gettimeofday(&tv, NULL);
+	seed = tv.tv_usec;
+	srandom(seed);
+	index = random() % n;
+
+	str = malloc (sizeof (namelist[index]->d_name) + 24);
+	strcpy(str, IMAGES_DIR);
+	strcat(str, namelist[index]->d_name);
+
+	return str;
+}
+
 static const GOptionEntry option_entries[] = {
 	{ NULL }
 };
@@ -249,8 +293,12 @@ main(int argc, char *argv[])
 		return -1;
 	}
 
-	for (i = 1; i < argc; i++)
-		image_create (d, i, argv[i]);
+	/* if not enough args, pick a random image from the system */
+	if (argc == 1)
+		image_create (d, 1, get_image_random());
+	else
+		for (i = 1; i < argc; i++)
+			image_create (d, i, argv[i]);
 
 	display_run(d);
 
-- 
1.7.5.4



More information about the wayland-devel mailing list