summaryrefslogtreecommitdiff
path: root/src/drun.c
blob: 851fdd1d238cf2773f894101f6b849222326ee5d (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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fts.h>
#include <glib.h>
#include <gio/gdesktopappinfo.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "drun.h"
#include "history.h"
#include "log.h"
#include "mkdirp.h"
#include "string_vec.h"
#include "xmalloc.h"

static const char *default_data_dir = ".local/share/";
static const char *default_cache_dir = ".cache/";
static const char *cache_basename = "tofi-drun";

[[nodiscard("memory leaked")]]
static char *get_cache_path() {
	char *cache_name = NULL;
	const char *state_path = getenv("XDG_CACHE_HOME");
	if (state_path == NULL) {
		const char *home = getenv("HOME");
		if (home == NULL) {
			log_error("Couldn't retrieve HOME from environment.\n");
			return NULL;
		}
		size_t len = strlen(home) + 1
			+ strlen(default_cache_dir) + 1
			+ strlen(cache_basename) + 1;
		cache_name = xmalloc(len);
		snprintf(
			cache_name,
			len,
			"%s/%s/%s",
			home,
			default_cache_dir,
			cache_basename);
	} else {
		size_t len = strlen(state_path) + 1
			+ strlen(cache_basename) + 1;
		cache_name = xmalloc(len);
		snprintf(
			cache_name,
			len,
			"%s/%s",
			state_path,
			cache_basename);
	}
	return cache_name;
}

[[nodiscard("memory leaked")]]
static struct string_vec get_application_paths() {
	char *base_paths = NULL;
	const char *xdg_data_dirs = getenv("XDG_DATA_DIRS");
	if (xdg_data_dirs == NULL) {
		xdg_data_dirs = "/usr/local/share/:/usr/share/";
	}
	const char *xdg_data_home = getenv("XDG_DATA_HOME");
	if (xdg_data_home == NULL) {
		const char *home = getenv("HOME");
		if (home == NULL) {
			log_error("Couldn't retrieve HOME from environment.\n");
			exit(EXIT_FAILURE);
		}
		size_t len = strlen(home) + 1
			+ strlen(default_data_dir) + 1
			+ strlen(xdg_data_dirs) + 1;
		base_paths = xmalloc(len);
		snprintf(
			base_paths,
			len,
			"%s/%s:%s",
			home,
			default_data_dir,
			xdg_data_dirs);
	} else {
		size_t len = strlen(xdg_data_home) + 1
			+ strlen(xdg_data_dirs) + 1;
		base_paths = xmalloc(len);
		snprintf(
			base_paths,
			len,
			"%s:%s",
			xdg_data_home,
			xdg_data_dirs);
	}


	/* Append /applications/ to each entry. */
	struct string_vec paths = string_vec_create();
	char *saveptr = NULL;
	char *path_entry = strtok_r(base_paths, ":", &saveptr);
	while (path_entry != NULL) {
		const char *subdir = "applications/";
		size_t len = strlen(path_entry) + 1 + strlen(subdir) + 1;
		char *apps = xmalloc(len);
		snprintf(apps, len, "%s/%s", path_entry, subdir);
		string_vec_add(&paths, apps);
		free(apps);
		path_entry = strtok_r(NULL, ":", &saveptr);
	}
	free(base_paths);

	return paths;
}

static void parse_desktop_file(gpointer key, gpointer value, void *data)
{
	const char *id = key;
	const char *path = value;
	struct desktop_vec *apps = data;

	desktop_vec_add_file(apps, id, path);
}

struct desktop_vec drun_generate(void)
{
	/*
	 * Note for the future: this custom logic could be replaced with
	 * g_app_info_get_all(), but that's slower. Worth remembering
	 * though if this runs into issues.
	 */
	log_debug("Retrieving application dirs.\n");
	struct string_vec paths = get_application_paths();
 	struct string_vec desktop_files = string_vec_create();
 	log_debug("Scanning for .desktop files.\n");
 	for (size_t i = 0; i < paths.count; i++) {
		const char *path_entry = paths.buf[i].string;
 		DIR *dir = opendir(path_entry);
 		if (dir != NULL) {
 			struct dirent *d;
 			while ((d = readdir(dir)) != NULL) {
				const char *extension = strrchr(d->d_name, '.');
				if (extension == NULL) {
					continue;
				}
				if (strcmp(extension, ".desktop")) {
					continue;
				}
 				string_vec_add(&desktop_files, d->d_name);
 			}
 			closedir(dir);
 		}
 	}
	log_debug("Found %zu files.\n", desktop_files.count);


 	log_debug("Parsing .desktop files.\n");
	/*
	 * The Desktop Entry Specification says that only the highest
	 * precedence application file with a given ID should be used, so store
	 * the id / path pairs into a hash table to enforce uniqueness.
	 */
	GHashTable *id_hash = g_hash_table_new_full(g_str_hash, g_str_equal, free, free);
	struct desktop_vec apps = desktop_vec_create();
 	for (size_t i = 0; i < paths.count; i++) {
		char *path_entry = paths.buf[i].string;
		char *tree[2] = { path_entry, NULL };
		size_t prefix_len = strlen(path_entry);
		FTS *fts = fts_open(tree, FTS_LOGICAL, NULL);
		FTSENT *entry = fts_read(fts);
		for (; entry != NULL; entry = fts_read(fts)) {
			const char *extension = strrchr(entry->fts_name, '.');
			if (extension == NULL) {
				continue;
			}
			if (strcmp(extension, ".desktop")) {
				continue;
			}
			char *id = xstrdup(&entry->fts_path[prefix_len]);
			char *slash = strchr(id, '/');
			while (slash != NULL) {
				*slash = '-';
				slash = strchr(slash, '/');
			}
			/*
			 * We're iterating from highest to lowest precedence,
			 * so only the first file with a given ID should be
			 * stored.
			 */
			if (!g_hash_table_contains(id_hash, id)) {
				char *path = xstrdup(entry->fts_path);
				g_hash_table_insert(id_hash, id, path);
			} else {
				free(id);
			}

		}
		fts_close(fts);
 	}

	/* Parse the remaining files into our desktop_vec. */
	g_hash_table_foreach(id_hash, parse_desktop_file, &apps);
	g_hash_table_unref(id_hash);

	log_debug("Found %zu apps.\n", apps.count);

	/*
	 * It's now safe to sort the desktop file vector, as the rules about
	 * file precedence have been taken care of.
	 */
	log_debug("Sorting results.\n");
	desktop_vec_sort(&apps);

	string_vec_destroy(&desktop_files);
	string_vec_destroy(&paths);
	return apps;
}

struct desktop_vec drun_generate_cached()
{
	log_debug("Retrieving cache location.\n");
	char *cache_path = get_cache_path();

	struct stat sb;
	if (cache_path == NULL) {
		return drun_generate();
	}

	/* If the cache doesn't exist, create it and return */
	errno = 0;
	if (stat(cache_path, &sb) == -1) {
		if (errno == ENOENT) {
			struct desktop_vec apps = drun_generate();
			if (!mkdirp(cache_path)) {
				free(cache_path);
				return apps;
			}
			errno = 0;
			FILE *cache = fopen(cache_path, "wb");
			if (cache == NULL) {
				log_error("Error creating drun cache: %s.\n", strerror(errno));
				free(cache_path);
				return apps;
			}
			desktop_vec_save(&apps, cache);
			fclose(cache);
			free(cache_path);
			return apps;
		}
		free(cache_path);
		return drun_generate();
	}

	log_debug("Retrieving application dirs.\n");
	struct string_vec application_path = get_application_paths();;

	/* The cache exists, so check if it's still in date */
	bool out_of_date = false;
	for (size_t i = 0; i < application_path.count; i++) {
		struct stat path_sb;
		if (stat(application_path.buf[i].string, &path_sb) == 0) {
			if (path_sb.st_mtim.tv_sec > sb.st_mtim.tv_sec) {
				out_of_date = true;
				break;
			}
		}
	}
	string_vec_destroy(&application_path);

	struct desktop_vec apps;
	if (out_of_date) {
		log_debug("Cache out of date, updating.\n");
		log_indent();
		apps = drun_generate();
		log_unindent();
		errno = 0;
		FILE *cache = fopen(cache_path, "wb");
		if (cache == NULL) {
			log_error("Failed to update cache: %s.\n", strerror(errno));
		} else {
			desktop_vec_save(&apps, cache);
			fclose(cache);
		}
	} else {
		log_debug("Cache up to date, loading.\n");
		errno = 0;
		FILE *cache = fopen(cache_path, "rb");
		if (cache == NULL) {
			log_error("Failed to load cache: %s.\n", strerror(errno));
			log_indent();
			apps = drun_generate();
			log_unindent();
		} else {
			apps = desktop_vec_load(cache);
			fclose(cache);
		}
	}
	free(cache_path);
	return apps;
}

void drun_print(const char *filename, const char *terminal_command)
{
	GKeyFile *file = g_key_file_new();
	if (!g_key_file_load_from_file(file, filename, G_KEY_FILE_NONE, NULL)) {
		log_error("Failed to open %s.\n", filename);
		return;
	}
	const char *group = "Desktop Entry";

	char *exec = g_key_file_get_string(file, group, "Exec", NULL);
	if (exec == NULL) {
		log_error("Failed to get Exec key from %s.\n", filename);
		g_key_file_unref(file);
		return;
	}

	/*
	 * Build a string vector from the command line, replacing % field codes
	 * with the appropriate values.
	 */
	struct string_vec pieces = string_vec_create();
	char *search = exec;
	char *last = search;
	while ((search = strchr(search, '%')) != NULL) {
		/* Add the string up to here to our vector. */
		search[0] = '\0';
		string_vec_add(&pieces, last);

		switch (search[1]) {
			case 'i':
				if (g_key_file_has_key(file, group, "Icon", NULL)) {
					string_vec_add(&pieces, "--icon ");
					string_vec_add(&pieces, g_key_file_get_string(file, group, "Icon", NULL));
				}
				break;
			case 'c':
				string_vec_add(&pieces, g_key_file_get_locale_string(file, group, "Name", NULL, NULL));
				break;
			case 'k':
				string_vec_add(&pieces, filename);
				break;
		}

		search += 2;
		last = search;
	}
	string_vec_add(&pieces, last);

        /*
         * If this is a terminal application, the command line needs to be
         * preceded by the terminal command.
         */
	bool terminal = g_key_file_get_boolean(file, group, "Terminal", NULL);
	if (terminal) {
		if (terminal_command[0] == '\0') {
			log_warning("Terminal application launched, but no terminal is set.\n");
			log_warning("This probably isn't what you want.\n");
			log_warning("See the --terminal option documentation in the man page.\n");
		} else {
			fputs(terminal_command, stdout);
			fputc(' ', stdout);
		}
	}

        /* Build the command line from our vector. */
        for (size_t i = 0; i < pieces.count; i++) {
		fputs(pieces.buf[i].string, stdout);
	}
	fputc('\n', stdout);

	string_vec_destroy(&pieces);
	free(exec);
	g_key_file_unref(file);
}

void drun_launch(const char *filename)
{
	GDesktopAppInfo *info = g_desktop_app_info_new_from_filename(filename);
	GAppLaunchContext *context = g_app_launch_context_new();
	GError *err = NULL;

	if (!g_app_info_launch((GAppInfo *)info, NULL, context, &err)) {
		log_error("Failed to launch %s.\n", filename);
		log_error("%s.\n", err->message);
		log_error(
				"If this is a terminal issue, you can use `--drun-launch=false`,\n"
				"         and pass your preferred terminal command to `--terminal`.\n"
				"         For more information, see https://gitlab.gnome.org/GNOME/glib/-/issues/338\n"
				"         and https://github.com/philj56/tofi/issues/46.\n");
	}

	g_clear_error(&err);
	g_object_unref(context);
	g_object_unref(info);
}

static int cmpscorep(const void *restrict a, const void *restrict b)
{
	struct desktop_entry *restrict app1 = (struct desktop_entry *)a;
	struct desktop_entry *restrict app2 = (struct desktop_entry *)b;
	return app2->history_score - app1->history_score;
}

void drun_history_sort(struct desktop_vec *apps, struct history *history)
{
	log_debug("Moving already known apps to the front.\n");
	for (size_t i = 0; i < history->count; i++) {
		struct desktop_entry *res = desktop_vec_find_sorted(apps, history->buf[i].name);
		if (res == NULL) {
			continue;
		}
		res->history_score = history->buf[i].run_count;
	}
	qsort(apps->buf, apps->count, sizeof(apps->buf[0]), cmpscorep);
}