-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
find_desktop.c
116 lines (85 loc) · 3.02 KB
/
find_desktop.c
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
//
// Created by waff on 12/20/19.
//
#include "find_desktop.h"
char* get_user_desktop_files_directory() {
char* homedir = get_user_home();
char* local_desktop_directory = "/.local/share/applications/";
return str_concat(homedir, local_desktop_directory);
}
desktop_entry* read_desktop_file(const char* file_path, const char* gtk_launch_name) {
FILE* fp = fopen(file_path, "r");
if (!fp) return NULL;
desktop_entry* entry = de_constructor(gtk_launch_name);
char in_entry_section = 0;
char line[PATH_MAX];
while (!feof(fp)) {
fscanf(fp, "%[^\n]\n", line);
// Skip comments and empty lines
if (line[0] == '\0' || line[0] == '#') continue;
if (in_entry_section) {
// Another section occured, stop parsing
if (line[0] == '[') break;
char* key = strtok(line, "=");
char* value = strtok(NULL, "=");
// Skip malformed field
if (!value) continue;
if (!strcmp(key, "NoDisplay") && !strcmp(value, "true")) {
free(entry);
return NULL;
}
if (!strcmp(key, "Name")) {
strcpy(entry->name, value);
continue;
}
if (!strcmp(key, "Icon")) {
strcpy(entry->icon, value);
continue;
}
} else if (!strcmp(line, "[Desktop Entry]")) {
in_entry_section = 1;
}
}
fclose(fp);
return entry;
}
desktop_entry_batch* find_desktop_files(const char* directory) {
DIR* dir_handle = opendir(directory);
// Skip non-existant directory
if (dir_handle == NULL) {
return NULL;
}
struct dirent* dp;
desktop_entry_batch* batch = deb_constructor();
while ((dp = readdir(dir_handle)) != NULL) {
if (!str_ends_with(dp->d_name, ".desktop")) continue;
char* file_path = str_concat(directory, dp->d_name);
// Remove .desktop from end
// size_t len = strlen(dp->d_name) - 8;
// char gtk_launch_name[len + 1];
// strncpy(gtk_launch_name, dp->d_name, len);
// gtk_launch_name[len] = '\0';
desktop_entry* entry = read_desktop_file(file_path, dp->d_name);
// desktop_entry* entry = read_desktop_file(file_path, gtk_launch_name);
if (entry != NULL) deb_push(batch, entry);
free(file_path);
}
closedir(dir_handle);
return batch;
}
desktop_entry_batch* find_all_desktop_files() {
char* user_dir = get_user_desktop_files_directory();
char* desktop_entry_dirs[DESKTOP_ENTRY_DIRS_NUM] = {
"/usr/share/applications/",
"/usr/local/share/applications/",
user_dir
};
desktop_entry_batch* all_entries = deb_constructor();
for (size_t i = 0; i < DESKTOP_ENTRY_DIRS_NUM; ++i) {
desktop_entry_batch* entries = find_desktop_files(desktop_entry_dirs[i]);
if (entries == NULL) continue;
deb_concat(all_entries, entries);
}
free(user_dir);
return all_entries;
}