dmenu for lunch applications in dwm
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.1 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #include <dirent.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <sys/stat.h>
  8. #define CACHE ".dmenu_cache"
  9. static int qstrcmp(const void *a, const void *b);
  10. static void die(const char *s);
  11. static void scan(void);
  12. static int uptodate(void);
  13. static char **items = NULL;
  14. static const char *Home, *Path;
  15. static size_t count = 0;
  16. int
  17. main(void) {
  18. if(!(Home = getenv("HOME")))
  19. die("no $HOME");
  20. if(!(Path = getenv("PATH")))
  21. die("no $PATH");
  22. if(chdir(Home) < 0)
  23. die("chdir failed");
  24. if(uptodate()) {
  25. execlp("cat", "cat", CACHE, NULL);
  26. die("exec failed");
  27. }
  28. scan();
  29. return EXIT_SUCCESS;
  30. }
  31. void
  32. die(const char *s) {
  33. fprintf(stderr, "dmenu_path: %s\n", s);
  34. exit(EXIT_FAILURE);
  35. }
  36. int
  37. qstrcmp(const void *a, const void *b) {
  38. return strcmp(*(const char **)a, *(const char **)b);
  39. }
  40. void
  41. scan(void) {
  42. char buf[PATH_MAX];
  43. char *dir, *path;
  44. size_t i;
  45. struct dirent *ent;
  46. DIR *dp;
  47. FILE *cache;
  48. if(!(path = strdup(Path)))
  49. die("strdup failed");
  50. for(dir = strtok(path, ":"); dir; dir = strtok(NULL, ":")) {
  51. if(!(dp = opendir(dir)))
  52. continue;
  53. while((ent = readdir(dp))) {
  54. snprintf(buf, sizeof buf, "%s/%s", dir, ent->d_name);
  55. if(ent->d_name[0] == '.' || access(buf, X_OK) < 0)
  56. continue;
  57. if(!(items = realloc(items, ++count * sizeof *items)))
  58. die("malloc failed");
  59. if(!(items[count-1] = strdup(ent->d_name)))
  60. die("strdup failed");
  61. }
  62. closedir(dp);
  63. }
  64. qsort(items, count, sizeof *items, qstrcmp);
  65. if(!(cache = fopen(CACHE, "w")))
  66. die("open failed");
  67. for(i = 0; i < count; i++) {
  68. if(i > 0 && !strcmp(items[i], items[i-1]))
  69. continue;
  70. fprintf(cache, "%s\n", items[i]);
  71. fprintf(stdout, "%s\n", items[i]);
  72. }
  73. fclose(cache);
  74. free(path);
  75. }
  76. int
  77. uptodate(void) {
  78. char *dir, *path;
  79. time_t mtime;
  80. struct stat st;
  81. if(stat(CACHE, &st) < 0)
  82. return 0;
  83. mtime = st.st_mtime;
  84. if(!(path = strdup(Path)))
  85. die("strdup failed");
  86. for(dir = strtok(path, ":"); dir; dir = strtok(NULL, ":"))
  87. if(!stat(dir, &st) && st.st_mtime > mtime)
  88. return 0;
  89. free(path);
  90. return 1;
  91. }