My build of nnn with minor changes
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

2979 lines
62 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. /*
  3. * Visual layout:
  4. * .---------
  5. * | cwd: /mnt/path
  6. * |
  7. * | file0
  8. * | file1
  9. * | > file2
  10. * | file3
  11. * | file4
  12. * ...
  13. * | filen
  14. * |
  15. * | Permission denied
  16. * '------
  17. */
  18. #ifdef __linux__
  19. #ifdef __i386__
  20. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit Linux */
  21. #endif
  22. #include <sys/inotify.h>
  23. #define LINUX_INOTIFY
  24. #if !defined(__GLIBC__)
  25. #include <sys/types.h>
  26. #endif
  27. #endif
  28. #include <sys/resource.h>
  29. #include <sys/stat.h>
  30. #include <sys/statvfs.h>
  31. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  32. #include <sys/types.h>
  33. #include <sys/event.h>
  34. #include <sys/time.h>
  35. #define BSD_KQUEUE
  36. #else
  37. #include <sys/sysmacros.h>
  38. #endif
  39. #include <sys/wait.h>
  40. #include <ctype.h>
  41. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  42. #ifndef NCURSES_WIDECHAR
  43. #define NCURSES_WIDECHAR 1
  44. #endif
  45. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  46. #ifndef _XOPEN_SOURCE_EXTENDED
  47. #define _XOPEN_SOURCE_EXTENDED
  48. #endif
  49. #endif
  50. #ifndef __USE_XOPEN /* Fix failure due to wcswidth(), ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  51. #define __USE_XOPEN
  52. #endif
  53. #include <curses.h>
  54. #include <dirent.h>
  55. #include <errno.h>
  56. #include <fcntl.h>
  57. #include <grp.h>
  58. #include <libgen.h>
  59. #include <limits.h>
  60. #ifdef __gnu_hurd__
  61. #define PATH_MAX 4096
  62. #endif
  63. #include <locale.h>
  64. #include <pwd.h>
  65. #include <regex.h>
  66. #include <signal.h>
  67. #include <stdarg.h>
  68. #include <stdio.h>
  69. #include <stdlib.h>
  70. #include <string.h>
  71. #include <time.h>
  72. #include <unistd.h>
  73. #include <readline/history.h>
  74. #include <readline/readline.h>
  75. #ifndef __USE_XOPEN_EXTENDED
  76. #define __USE_XOPEN_EXTENDED 1
  77. #endif
  78. #include <ftw.h>
  79. #include <wchar.h>
  80. #include "nnn.h"
  81. #ifdef DEBUGMODE
  82. static int DEBUG_FD;
  83. static int
  84. xprintf(int fd, const char *fmt, ...)
  85. {
  86. char buf[BUFSIZ];
  87. int r;
  88. va_list ap;
  89. va_start(ap, fmt);
  90. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  91. if (r > 0)
  92. r = write(fd, buf, r);
  93. va_end(ap);
  94. return r;
  95. }
  96. static int
  97. enabledbg()
  98. {
  99. FILE *fp = fopen("/tmp/nnn_debug", "w");
  100. if (!fp) {
  101. fprintf(stderr, "Cannot open debug file\n");
  102. return -1;
  103. }
  104. DEBUG_FD = fileno(fp);
  105. if (DEBUG_FD == -1) {
  106. fprintf(stderr, "Cannot open debug file descriptor\n");
  107. return -1;
  108. }
  109. return 0;
  110. }
  111. static void
  112. disabledbg()
  113. {
  114. close(DEBUG_FD);
  115. }
  116. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  117. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  118. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  119. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
  120. #else
  121. #define DPRINTF_D(x)
  122. #define DPRINTF_U(x)
  123. #define DPRINTF_S(x)
  124. #define DPRINTF_P(x)
  125. #endif /* DEBUGMODE */
  126. /* Macro definitions */
  127. #define VERSION "1.5"
  128. #define GENERAL_INFO "License: BSD 2-Clause\nWebpage: https://github.com/jarun/nnn"
  129. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  130. #undef MIN
  131. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  132. #define ISODD(x) ((x) & 1)
  133. #define TOUPPER(ch) \
  134. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  135. #define MAX_CMD_LEN 5120
  136. #define CWD "cwd: "
  137. #define CURSR " > "
  138. #define EMPTY " "
  139. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  140. #define FILTER '/'
  141. #define REGEX_MAX 128
  142. #define BM_MAX 10
  143. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  144. #define NAMEBUF_INCR 0x1000 /* 64 dir entries at a time, avg. 64 chars per filename = 64*64B = 4KB */
  145. /* Macros to define process spawn behaviour as flags */
  146. #define F_NONE 0x00 /* no flag set */
  147. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  148. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  149. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  150. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  151. #define F_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  152. #define exitcurses() endwin()
  153. #define clearprompt() printmsg("")
  154. #define printwarn() printmsg(strerror(errno))
  155. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  156. #define settimeout() timeout(1000)
  157. #define cleartimeout() timeout(-1)
  158. #define errexit() printerr(__LINE__)
  159. #ifdef LINUX_INOTIFY
  160. #define EVENT_SIZE (sizeof(struct inotify_event))
  161. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  162. #elif defined(BSD_KQUEUE)
  163. #define NUM_EVENT_SLOTS 1
  164. #define NUM_EVENT_FDS 1
  165. #endif
  166. /* TYPE DEFINITIONS */
  167. typedef unsigned long ulong;
  168. typedef unsigned int uint;
  169. typedef unsigned char uchar;
  170. /* STRUCTURES */
  171. /* Directory entry */
  172. typedef struct entry {
  173. char *name;
  174. time_t t;
  175. off_t size;
  176. blkcnt_t blocks; /* number of 512B blocks allocated */
  177. mode_t mode;
  178. uchar nlen; /* Length of file name */
  179. } *pEntry;
  180. /* Bookmark */
  181. typedef struct {
  182. char *key;
  183. char *loc;
  184. } bm;
  185. /* Settings */
  186. typedef struct {
  187. ushort filtermode : 1; /* Set to enter filter mode */
  188. ushort mtimeorder : 1; /* Set to sort by time modified */
  189. ushort sizeorder : 1; /* Set to sort by file size */
  190. ushort blkorder : 1; /* Set to sort by blocks used (disk usage) */
  191. ushort showhidden : 1; /* Set to show hidden files */
  192. ushort showdetail : 1; /* Clear to show fewer file info */
  193. ushort showcolor : 1; /* Set to show dirs in blue */
  194. ushort dircolor : 1; /* Current status of dir color */
  195. ushort metaviewer : 1; /* Index of metadata viewer in utils[] */
  196. ushort color : 3; /* Color code for directories */
  197. } settings;
  198. /* GLOBALS */
  199. /* Configuration */
  200. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0, 0, 4};
  201. static struct entry *dents;
  202. static char *pnamebuf;
  203. static int ndents, cur, total_dents;
  204. static uint idle;
  205. static uint idletimeout;
  206. static char *player;
  207. static char *copier;
  208. static char *editor;
  209. static char *desktop_manager;
  210. static char nowait = F_NOTRACE;
  211. static blkcnt_t ent_blocks;
  212. static blkcnt_t dir_blocks;
  213. static ulong num_files;
  214. static uint open_max;
  215. static bm bookmark[BM_MAX];
  216. #ifdef LINUX_INOTIFY
  217. static int inotify_fd, inotify_wd = -1;
  218. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  219. #elif defined(BSD_KQUEUE)
  220. static int kq, event_fd = -1;
  221. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  222. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  223. static struct timespec gtimeout;
  224. #endif
  225. /* Utilities to open files, run actions */
  226. static char * const utils[] = {
  227. "mediainfo",
  228. "exiftool",
  229. #ifdef __APPLE__
  230. "/usr/bin/open",
  231. #else
  232. "/usr/bin/xdg-open",
  233. #endif
  234. "nlay",
  235. "atool"
  236. };
  237. /* Common message strings */
  238. static char *STR_NFTWFAIL = "nftw(3) failed";
  239. static char *STR_ATROOT = "You are at /";
  240. static char *STR_NOHOME = "HOME not set";
  241. static char *STR_INPUT = "No traversal delimiter allowed";
  242. /* For use in functions which are isolated and don't return the buffer */
  243. static char g_buf[MAX_CMD_LEN];
  244. /* Forward declarations */
  245. static void redraw(char *path);
  246. /* Functions */
  247. /* Messages show up at the bottom */
  248. static void
  249. printmsg(char *msg)
  250. {
  251. mvprintw(LINES - 1, 0, "%s\n", msg);
  252. }
  253. /* Kill curses and display error before exiting */
  254. static void
  255. printerr(int linenum)
  256. {
  257. exitcurses();
  258. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  259. exit(1);
  260. }
  261. /* Print prompt on the last line */
  262. static void
  263. printprompt(char *str)
  264. {
  265. clearprompt();
  266. printw(str);
  267. }
  268. /* Increase the limit on open file descriptors, if possible */
  269. static rlim_t
  270. max_openfds()
  271. {
  272. struct rlimit rl;
  273. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  274. if (limit != 0)
  275. return 32;
  276. limit = rl.rlim_cur;
  277. rl.rlim_cur = rl.rlim_max;
  278. /* Return ~75% of max possible */
  279. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  280. limit = rl.rlim_max - (rl.rlim_max >> 2);
  281. /*
  282. * 20K is arbitrary> If the limit is set to max possible
  283. * value, the memory usage increases to more than double.
  284. */
  285. return limit > 20480 ? 20480 : limit;
  286. }
  287. return limit;
  288. }
  289. /*
  290. * Custom xstrlen()
  291. */
  292. static size_t
  293. xstrlen(const char *s)
  294. {
  295. static size_t len;
  296. if (!s)
  297. return 0;
  298. len = 0;
  299. while (*s)
  300. ++len, ++s;
  301. return len;
  302. }
  303. /*
  304. * Just a safe strncpy(3)
  305. * Always null ('\0') terminates if both src and dest are valid pointers.
  306. * Returns the number of bytes copied including terminating null byte.
  307. */
  308. static size_t
  309. xstrlcpy(char *dest, const char *src, size_t n)
  310. {
  311. static size_t len, blocks, lsize = sizeof(ulong);
  312. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  313. if (!src || !dest)
  314. return 0;
  315. len = xstrlen(src) + 1;
  316. if (n > len)
  317. n = len;
  318. else if (len > n)
  319. /* Save total number of bytes to copy in len */
  320. len = n;
  321. if (n >= lsize) {
  322. blocks = n >> _WSHIFT;
  323. n -= (blocks << _WSHIFT);
  324. } else
  325. blocks = 0;
  326. if (blocks) {
  327. static ulong *s, *d;
  328. s = (ulong *)src;
  329. d = (ulong *)dest;
  330. while (blocks) {
  331. *d = *s;
  332. ++d, ++s;
  333. --blocks;
  334. }
  335. if (!n) {
  336. dest = (char *)d;
  337. *--dest = '\0';
  338. return len;
  339. }
  340. src = (char *)s;
  341. dest = (char *)d;
  342. }
  343. while (--n && (*dest = *src))
  344. ++dest, ++src;
  345. if (!n)
  346. *dest = '\0';
  347. return len;
  348. }
  349. /*
  350. * Custom strcmp(), just what we need.
  351. * Returns 0 if same, -ve if s1 < s2, +ve if s1 > s2.
  352. */
  353. static int
  354. xstrcmp(const char *s1, const char *s2)
  355. {
  356. if (!s1 || !s2)
  357. return -1;
  358. while (*s1 && *s1 == *s2)
  359. ++s1, ++s2;
  360. return *s1 - *s2;
  361. }
  362. /*
  363. * The poor man's implementation of memrchr(3).
  364. * We are only looking for '/' in this program.
  365. * Ideally 0 < n <= strlen(s).
  366. */
  367. static void *
  368. xmemrchr(uchar *s, uchar ch, size_t n)
  369. {
  370. if (!s || !n)
  371. return NULL;
  372. s = s + n - 1;
  373. while (n) {
  374. if (*s == ch)
  375. return s;
  376. --n, --s;
  377. }
  378. return NULL;
  379. }
  380. /*
  381. * The following dirname(3) implementation does not
  382. * modify the input. We use a copy of the original.
  383. *
  384. * Modified from the glibc (GNU LGPL) version.
  385. */
  386. static char *
  387. xdirname(const char *path)
  388. {
  389. static char *buf = g_buf, *last_slash, *runp;
  390. xstrlcpy(buf, path, PATH_MAX);
  391. /* Find last '/'. */
  392. last_slash = xmemrchr((uchar *)buf, '/', xstrlen(buf));
  393. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  394. /* Determine whether all remaining characters are slashes. */
  395. for (runp = last_slash; runp != buf; --runp)
  396. if (runp[-1] != '/')
  397. break;
  398. /* The '/' is the last character, we have to look further. */
  399. if (runp != buf)
  400. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  401. }
  402. if (last_slash != NULL) {
  403. /* Determine whether all remaining characters are slashes. */
  404. for (runp = last_slash; runp != buf; --runp)
  405. if (runp[-1] != '/')
  406. break;
  407. /* Terminate the buffer. */
  408. if (runp == buf) {
  409. /* The last slash is the first character in the string.
  410. * We have to return "/". As a special case we have to
  411. * return "//" if there are exactly two slashes at the
  412. * beginning of the string. See XBD 4.10 Path Name
  413. * Resolution for more information.
  414. */
  415. if (last_slash == buf + 1)
  416. ++last_slash;
  417. else
  418. last_slash = buf + 1;
  419. } else
  420. last_slash = runp;
  421. last_slash[0] = '\0';
  422. } else {
  423. /* This assignment is ill-designed but the XPG specs require to
  424. * return a string containing "." in any case no directory part
  425. * is found and so a static and constant string is required.
  426. */
  427. buf[0] = '.';
  428. buf[1] = '\0';
  429. }
  430. return buf;
  431. }
  432. /*
  433. * Return number of dots if all chars in a string are dots, else 0
  434. */
  435. static int
  436. all_dots(const char *path)
  437. {
  438. int count = 0;
  439. if (!path)
  440. return FALSE;
  441. while (*path == '.')
  442. ++count, ++path;
  443. if (*path)
  444. return 0;
  445. return count;
  446. }
  447. /* Initialize curses mode */
  448. static void
  449. initcurses(void)
  450. {
  451. if (initscr() == NULL) {
  452. char *term = getenv("TERM");
  453. if (term != NULL)
  454. fprintf(stderr, "error opening TERM: %s\n", term);
  455. else
  456. fprintf(stderr, "initscr() failed\n");
  457. exit(1);
  458. }
  459. cbreak();
  460. noecho();
  461. nonl();
  462. intrflush(stdscr, FALSE);
  463. keypad(stdscr, TRUE);
  464. curs_set(FALSE); /* Hide cursor */
  465. start_color();
  466. use_default_colors();
  467. if (cfg.showcolor)
  468. init_pair(1, cfg.color, -1);
  469. settimeout(); /* One second */
  470. }
  471. /*
  472. * Spawns a child process. Behaviour can be controlled using flag.
  473. * Limited to 2 arguments to a program, flag works on bit set.
  474. */
  475. static void
  476. spawn(char *file, char *arg1, char *arg2, char *dir, uchar flag)
  477. {
  478. static char *shlvl;
  479. static pid_t pid;
  480. static int status;
  481. if (flag & F_NORMAL)
  482. exitcurses();
  483. pid = fork();
  484. if (pid == 0) {
  485. if (dir != NULL)
  486. status = chdir(dir);
  487. shlvl = getenv("SHLVL");
  488. /* Show a marker (to indicate nnn spawned shell) */
  489. if (flag & F_MARKER && shlvl != NULL) {
  490. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  491. printf("Spawned shell level: %d\n", atoi(shlvl) + 1);
  492. }
  493. /* Suppress stdout and stderr */
  494. if (flag & F_NOTRACE) {
  495. int fd = open("/dev/null", O_WRONLY, 0200);
  496. dup2(fd, 1);
  497. dup2(fd, 2);
  498. close(fd);
  499. }
  500. if (flag & F_SIGINT)
  501. signal(SIGINT, SIG_DFL);
  502. execlp(file, file, arg1, arg2, NULL);
  503. _exit(1);
  504. } else {
  505. if (!(flag & F_NOWAIT))
  506. /* Ignore interruptions */
  507. while (waitpid(pid, &status, 0) == -1)
  508. DPRINTF_D(status);
  509. DPRINTF_D(pid);
  510. if (flag & F_NORMAL)
  511. initcurses();
  512. }
  513. }
  514. /* Get program name from env var, else return fallback program */
  515. static char *
  516. xgetenv(char *name, char *fallback)
  517. {
  518. static char *value;
  519. if (name == NULL)
  520. return fallback;
  521. value = getenv(name);
  522. return value && value[0] ? value : fallback;
  523. }
  524. /* Check if a dir exists, IS a dir and is readable */
  525. static bool
  526. xdiraccess(char *path)
  527. {
  528. static DIR *dirp;
  529. dirp = opendir(path);
  530. if (dirp == NULL) {
  531. printwarn();
  532. return FALSE;
  533. }
  534. closedir(dirp);
  535. return TRUE;
  536. }
  537. /*
  538. * We assume none of the strings are NULL.
  539. *
  540. * Let's have the logic to sort numeric names in numeric order.
  541. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  542. *
  543. * If the absolute numeric values are same, we fallback to alphasort.
  544. */
  545. static int
  546. xstricmp(char *s1, char *s2)
  547. {
  548. static char *c1, *c2;
  549. c1 = s1;
  550. while (isspace(*c1))
  551. ++c1;
  552. c2 = s2;
  553. while (isspace(*c2))
  554. ++c2;
  555. if (*c1 == '-' || *c1 == '+')
  556. ++c1;
  557. if (*c2 == '-' || *c2 == '+')
  558. ++c2;
  559. if (isdigit(*c1) && isdigit(*c2)) {
  560. while (*c1 >= '0' && *c1 <= '9')
  561. ++c1;
  562. while (isspace(*c1))
  563. ++c1;
  564. while (*c2 >= '0' && *c2 <= '9')
  565. ++c2;
  566. while (isspace(*c2))
  567. ++c2;
  568. }
  569. if (!*c1 && !*c2) {
  570. static long long num1, num2;
  571. num1 = strtoll(s1, NULL, 10);
  572. num2 = strtoll(s2, NULL, 10);
  573. if (num1 != num2) {
  574. if (num1 > num2)
  575. return 1;
  576. else
  577. return -1;
  578. }
  579. }
  580. return strcoll(s1, s2);
  581. }
  582. /* Return the integer value of a char representing HEX */
  583. static char
  584. xchartohex(char c)
  585. {
  586. if (c >= '0' && c <= '9')
  587. return c - '0';
  588. c = TOUPPER(c);
  589. if (c >= 'A' && c <= 'F')
  590. return c - 'A' + 10;
  591. return c;
  592. }
  593. /* Trim all whitespace from both ends, / from end */
  594. static char *
  595. strstrip(char *s)
  596. {
  597. if (!s || !*s)
  598. return s;
  599. size_t len = xstrlen(s) - 1;
  600. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  601. --len;
  602. s[len + 1] = '\0';
  603. while (*s && isspace(*s))
  604. ++s;
  605. return s;
  606. }
  607. static char *
  608. getmime(char *file)
  609. {
  610. static regex_t regex;
  611. static uint i;
  612. static uint len = LEN(assocs);
  613. for (i = 0; i < len; ++i) {
  614. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  615. continue;
  616. if (regexec(&regex, file, 0, NULL, 0) == 0)
  617. return assocs[i].mime;
  618. }
  619. return NULL;
  620. }
  621. static int
  622. setfilter(regex_t *regex, char *filter)
  623. {
  624. static size_t len;
  625. static int r;
  626. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  627. if (r != 0 && filter && filter[0] != '\0') {
  628. len = COLS;
  629. if (len > LINE_MAX)
  630. len = LINE_MAX;
  631. regerror(r, regex, g_buf, len);
  632. printmsg(g_buf);
  633. }
  634. return r;
  635. }
  636. static void
  637. initfilter(int dot, char **ifilter)
  638. {
  639. *ifilter = dot ? "." : "^[^.]";
  640. }
  641. static int
  642. visible(regex_t *regex, char *file)
  643. {
  644. return regexec(regex, file, 0, NULL, 0) == 0;
  645. }
  646. static int
  647. entrycmp(const void *va, const void *vb)
  648. {
  649. static pEntry pa, pb;
  650. pa = (pEntry)va;
  651. pb = (pEntry)vb;
  652. /* Sort directories first */
  653. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  654. return 1;
  655. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  656. return -1;
  657. /* Do the actual sorting */
  658. if (cfg.mtimeorder)
  659. return pb->t - pa->t;
  660. if (cfg.sizeorder) {
  661. if (pb->size > pa->size)
  662. return 1;
  663. else if (pb->size < pa->size)
  664. return -1;
  665. }
  666. if (cfg.blkorder) {
  667. if (pb->blocks > pa->blocks)
  668. return 1;
  669. else if (pb->blocks < pa->blocks)
  670. return -1;
  671. }
  672. return xstricmp(pa->name, pb->name);
  673. }
  674. /*
  675. * Returns SEL_* if key is bound and 0 otherwise.
  676. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  677. * The next keyboard input can be simulated by presel.
  678. */
  679. static int
  680. nextsel(char **run, char **env, int *presel)
  681. {
  682. static int c;
  683. static uchar i;
  684. static uint len = LEN(bindings);
  685. #ifdef LINUX_INOTIFY
  686. static char inotify_buf[EVENT_BUF_LEN];
  687. #elif defined(BSD_KQUEUE)
  688. static struct kevent event_data[NUM_EVENT_SLOTS];
  689. #endif
  690. c = *presel;
  691. if (c == 0)
  692. c = getch();
  693. else {
  694. *presel = 0;
  695. /* Unwatch dir if we are still in a filtered view */
  696. #ifdef LINUX_INOTIFY
  697. if (inotify_wd >= 0) {
  698. inotify_rm_watch(inotify_fd, inotify_wd);
  699. inotify_wd = -1;
  700. }
  701. #elif defined(BSD_KQUEUE)
  702. if (event_fd >= 0) {
  703. close(event_fd);
  704. event_fd = -1;
  705. }
  706. #endif
  707. }
  708. if (c == -1) {
  709. ++idle;
  710. /* Do not check for directory changes in du
  711. * mode. A redraw forces du calculation.
  712. * Check for changes every odd second.
  713. */
  714. #ifdef LINUX_INOTIFY
  715. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  716. #elif defined(BSD_KQUEUE)
  717. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  718. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  719. #endif
  720. c = CONTROL('L');
  721. } else
  722. idle = 0;
  723. for (i = 0; i < len; ++i)
  724. if (c == bindings[i].sym) {
  725. *run = bindings[i].run;
  726. *env = bindings[i].env;
  727. return bindings[i].act;
  728. }
  729. return 0;
  730. }
  731. /*
  732. * Move non-matching entries to the end
  733. */
  734. static void
  735. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  736. {
  737. static int count;
  738. static struct entry _dent, *dentp1, *dentp2;
  739. for (count = 0; count < ndents; ++count) {
  740. if (filter(re, (*dents)[count].name) == 0) {
  741. if (count != --ndents) {
  742. dentp1 = &(*dents)[count];
  743. dentp2 = &(*dents)[ndents];
  744. memcpy(&_dent, dentp1, sizeof(struct entry));
  745. memcpy(dentp1, dentp2, sizeof(struct entry));
  746. memcpy(dentp2, &_dent, sizeof(struct entry));
  747. --count;
  748. }
  749. continue;
  750. }
  751. }
  752. }
  753. static int
  754. matches(char *fltr)
  755. {
  756. static regex_t re;
  757. /* Search filter */
  758. if (setfilter(&re, fltr) != 0)
  759. return -1;
  760. fill(&dents, visible, &re);
  761. qsort(dents, ndents, sizeof(*dents), entrycmp);
  762. return 0;
  763. }
  764. static int
  765. filterentries(char *path)
  766. {
  767. static char ln[REGEX_MAX];
  768. static wchar_t wln[REGEX_MAX];
  769. static wint_t ch[2] = {0};
  770. int r, total = ndents, oldcur = cur, len = 1;
  771. char *pln = ln + 1;
  772. ln[0] = wln[0] = FILTER;
  773. ln[1] = wln[1] = '\0';
  774. cur = 0;
  775. cleartimeout();
  776. echo();
  777. curs_set(TRUE);
  778. printprompt(ln);
  779. while ((r = get_wch(ch)) != ERR) {
  780. if (*ch == 127 /* handle DEL */ || *ch == KEY_DC || *ch == KEY_BACKSPACE) {
  781. if (len == 1) {
  782. cur = oldcur;
  783. *ch = CONTROL('L');
  784. goto end;
  785. }
  786. wln[--len] = '\0';
  787. if (len == 1)
  788. cur = oldcur;
  789. wcstombs(ln, wln, REGEX_MAX);
  790. ndents = total;
  791. if (matches(pln) == -1)
  792. continue;
  793. redraw(path);
  794. printprompt(ln);
  795. continue;
  796. }
  797. if (r == OK) {
  798. switch (*ch) {
  799. case '\r': // with nonl(), this is ENTER key value
  800. if (len == 1) {
  801. cur = oldcur;
  802. goto end;
  803. }
  804. if (matches(pln) == -1)
  805. goto end;
  806. redraw(path);
  807. goto end;
  808. case CONTROL('L'):
  809. if (len == 1)
  810. cur = oldcur; // fallthrough
  811. case CONTROL('Q'):
  812. goto end;
  813. default:
  814. /* Reset cur in case it's a repeat search */
  815. if (len == 1)
  816. cur = 0;
  817. if (len == REGEX_MAX - 1)
  818. break;
  819. wln[len] = (wchar_t)*ch;
  820. wln[++len] = '\0';
  821. wcstombs(ln, wln, REGEX_MAX);
  822. ndents = total;
  823. if (matches(pln) == -1)
  824. continue;
  825. redraw(path);
  826. printprompt(ln);
  827. }
  828. } else {
  829. if (len == 1)
  830. cur = oldcur;
  831. goto end;
  832. }
  833. }
  834. end:
  835. noecho();
  836. curs_set(FALSE);
  837. settimeout();
  838. /* Return keys for navigation etc. */
  839. return *ch;
  840. }
  841. /* Show a prompt with input string and return the changes */
  842. static char *
  843. xreadline(char *fname)
  844. {
  845. int old_curs = curs_set(1);
  846. size_t len, pos;
  847. int x, y, r;
  848. wint_t ch[2] = {0};
  849. wchar_t *buf = (wchar_t *)g_buf;
  850. size_t buflen = NAME_MAX - 1;
  851. if (fname) {
  852. DPRINTF_S(fname);
  853. len = pos = mbstowcs(buf, fname, NAME_MAX);
  854. } else
  855. len = (size_t)-1;
  856. if (len == (size_t)-1) {
  857. buf[0] = '\0';
  858. len = pos = 0;
  859. }
  860. getyx(stdscr, y, x);
  861. cleartimeout();
  862. while (1) {
  863. buf[len] = ' ';
  864. mvaddnwstr(y, x, buf, len + 1);
  865. move(y, x + wcswidth(buf, pos));
  866. if ((r = get_wch(ch)) != ERR) {
  867. if (r == OK) {
  868. if (*ch == KEY_ENTER || *ch == '\n' || *ch == '\r')
  869. break;
  870. if (*ch == CONTROL('L')) {
  871. clearprompt();
  872. len = pos = 0;
  873. continue;
  874. }
  875. /* TAB breaks cursor position, ignore it */
  876. if (*ch == TAB || *ch == '\t')
  877. continue;
  878. if (pos < buflen) {
  879. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  880. buf[pos] = *ch;
  881. ++len, ++pos;
  882. continue;
  883. }
  884. } else {
  885. switch (*ch) {
  886. case KEY_LEFT:
  887. if (pos > 0)
  888. --pos;
  889. break;
  890. case KEY_RIGHT:
  891. if (pos < len)
  892. ++pos;
  893. break;
  894. case KEY_BACKSPACE:
  895. if (pos > 0) {
  896. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  897. --len, --pos;
  898. }
  899. break;
  900. case KEY_DC:
  901. if (pos < len) {
  902. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  903. --len;
  904. }
  905. break;
  906. default:
  907. break;
  908. }
  909. }
  910. }
  911. }
  912. buf[len] = '\0';
  913. if (old_curs != ERR) curs_set(old_curs);
  914. settimeout();
  915. DPRINTF_S(buf);
  916. wcstombs(g_buf, buf, NAME_MAX);
  917. return g_buf;
  918. }
  919. static char *
  920. readinput(void)
  921. {
  922. cleartimeout();
  923. echo();
  924. curs_set(TRUE);
  925. memset(g_buf, 0, LINE_MAX);
  926. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  927. noecho();
  928. curs_set(FALSE);
  929. settimeout();
  930. return g_buf[0] ? g_buf : NULL;
  931. }
  932. /*
  933. * Returns "dir/name or "/name"
  934. */
  935. static char *
  936. mkpath(char *dir, char *name, char *out, size_t n)
  937. {
  938. /* Handle absolute path */
  939. if (name[0] == '/')
  940. xstrlcpy(out, name, n);
  941. else {
  942. /* Handle root case */
  943. if (istopdir(dir))
  944. snprintf(out, n, "/%s", name);
  945. else
  946. snprintf(out, n, "%s/%s", dir, name);
  947. }
  948. return out;
  949. }
  950. static void
  951. parsebmstr(char *bms)
  952. {
  953. int i = 0;
  954. while (*bms && i < BM_MAX) {
  955. bookmark[i].key = bms;
  956. ++bms;
  957. while (*bms && *bms != ':')
  958. ++bms;
  959. if (!*bms) {
  960. bookmark[i].key = NULL;
  961. break;
  962. }
  963. *bms = '\0';
  964. bookmark[i].loc = ++bms;
  965. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  966. bookmark[i].key = NULL;
  967. break;
  968. }
  969. while (*bms && *bms != ';')
  970. ++bms;
  971. if (*bms)
  972. *bms = '\0';
  973. else
  974. break;
  975. ++bms;
  976. ++i;
  977. }
  978. }
  979. static void
  980. resetdircolor(mode_t mode)
  981. {
  982. if (cfg.dircolor && !S_ISDIR(mode)) {
  983. attroff(COLOR_PAIR(1) | A_BOLD);
  984. cfg.dircolor = 0;
  985. }
  986. }
  987. /*
  988. * Replace escape characters in a string with '?'
  989. * Adjust string length to maxcols if > 0;
  990. *
  991. * Interestingly, note that buffer points to g_buf. What happens if
  992. * str also points to g_buf? In this case we assume that the caller
  993. * acknowledges that it's OK to lose the data in g_buf after this
  994. * call to unescape().
  995. * The API, on its part, first converts str to multibyte (after which
  996. * it doesn't touch str anymore). Only after that it starts modifying
  997. * buffer. This works like a phased operation.
  998. */
  999. static char *
  1000. unescape(const char *str, uint maxcols)
  1001. {
  1002. static wchar_t wbuf[PATH_MAX];
  1003. static char *buffer;
  1004. static wchar_t *buf;
  1005. static size_t len;
  1006. /* Convert multi-byte to wide char */
  1007. len = mbstowcs(wbuf, str, PATH_MAX);
  1008. buffer = g_buf;
  1009. buffer[0] = '\0';
  1010. buf = wbuf;
  1011. if (maxcols && len > maxcols) {
  1012. len = wcswidth(wbuf, len);
  1013. if (len > maxcols)
  1014. wbuf[maxcols] = 0;
  1015. }
  1016. while (*buf) {
  1017. if (*buf <= '\x1f' || *buf == '\x7f')
  1018. *buf = '\?';
  1019. ++buf;
  1020. }
  1021. /* Convert wide char to multi-byte */
  1022. wcstombs(buffer, wbuf, PATH_MAX);
  1023. return buffer;
  1024. }
  1025. static char *
  1026. coolsize(off_t size)
  1027. {
  1028. static const char * const U = "BKMGTPEZY";
  1029. static char size_buf[12]; /* Buffer to hold human readable size */
  1030. static int i;
  1031. static off_t tmp;
  1032. static long double rem;
  1033. static const double div_2_pow_10 = 1.0 / 1024.0;
  1034. i = 0;
  1035. rem = 0;
  1036. while (size > 1024) {
  1037. tmp = size;
  1038. size >>= 10;
  1039. rem = tmp - (size << 10);
  1040. ++i;
  1041. }
  1042. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  1043. return size_buf;
  1044. }
  1045. static void
  1046. printent(struct entry *ent, int sel, uint namecols)
  1047. {
  1048. static char *pname;
  1049. pname = unescape(ent->name, namecols);
  1050. /* Directories are always shown on top */
  1051. resetdircolor(ent->mode);
  1052. if (S_ISDIR(ent->mode))
  1053. printw("%s%s/\n", CURSYM(sel), pname);
  1054. else if (S_ISLNK(ent->mode))
  1055. printw("%s%s@\n", CURSYM(sel), pname);
  1056. else if (S_ISSOCK(ent->mode))
  1057. printw("%s%s=\n", CURSYM(sel), pname);
  1058. else if (S_ISFIFO(ent->mode))
  1059. printw("%s%s|\n", CURSYM(sel), pname);
  1060. else if (ent->mode & 0100)
  1061. printw("%s%s*\n", CURSYM(sel), pname);
  1062. else
  1063. printw("%s%s\n", CURSYM(sel), pname);
  1064. }
  1065. static void
  1066. printent_long(struct entry *ent, int sel, uint namecols)
  1067. {
  1068. static char buf[18], *pname;
  1069. strftime(buf, 18, "%d-%m-%Y %H:%M", localtime(&ent->t));
  1070. pname = unescape(ent->name, namecols);
  1071. /* Directories are always shown on top */
  1072. resetdircolor(ent->mode);
  1073. if (sel)
  1074. attron(A_REVERSE);
  1075. if (!cfg.blkorder) {
  1076. if (S_ISDIR(ent->mode))
  1077. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1078. else if (S_ISLNK(ent->mode))
  1079. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1080. else if (S_ISSOCK(ent->mode))
  1081. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1082. else if (S_ISFIFO(ent->mode))
  1083. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1084. else if (S_ISBLK(ent->mode))
  1085. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1086. else if (S_ISCHR(ent->mode))
  1087. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1088. else if (ent->mode & 0100)
  1089. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1090. else
  1091. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1092. } else {
  1093. if (S_ISDIR(ent->mode))
  1094. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1095. else if (S_ISLNK(ent->mode))
  1096. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1097. else if (S_ISSOCK(ent->mode))
  1098. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1099. else if (S_ISFIFO(ent->mode))
  1100. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1101. else if (S_ISBLK(ent->mode))
  1102. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1103. else if (S_ISCHR(ent->mode))
  1104. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1105. else if (ent->mode & 0100)
  1106. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1107. else
  1108. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1109. }
  1110. if (sel)
  1111. attroff(A_REVERSE);
  1112. }
  1113. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1114. static char
  1115. get_fileind(mode_t mode, char *desc)
  1116. {
  1117. static char c;
  1118. if (S_ISREG(mode)) {
  1119. c = '-';
  1120. sprintf(desc, "%s", "regular file");
  1121. if (mode & 0100)
  1122. strcat(desc, ", executable");
  1123. } else if (S_ISDIR(mode)) {
  1124. c = 'd';
  1125. sprintf(desc, "%s", "directory");
  1126. } else if (S_ISBLK(mode)) {
  1127. c = 'b';
  1128. sprintf(desc, "%s", "block special device");
  1129. } else if (S_ISCHR(mode)) {
  1130. c = 'c';
  1131. sprintf(desc, "%s", "character special device");
  1132. #ifdef S_ISFIFO
  1133. } else if (S_ISFIFO(mode)) {
  1134. c = 'p';
  1135. sprintf(desc, "%s", "FIFO");
  1136. #endif /* S_ISFIFO */
  1137. #ifdef S_ISLNK
  1138. } else if (S_ISLNK(mode)) {
  1139. c = 'l';
  1140. sprintf(desc, "%s", "symbolic link");
  1141. #endif /* S_ISLNK */
  1142. #ifdef S_ISSOCK
  1143. } else if (S_ISSOCK(mode)) {
  1144. c = 's';
  1145. sprintf(desc, "%s", "socket");
  1146. #endif /* S_ISSOCK */
  1147. #ifdef S_ISDOOR
  1148. /* Solaris 2.6, etc. */
  1149. } else if (S_ISDOOR(mode)) {
  1150. c = 'D';
  1151. desc[0] = '\0';
  1152. #endif /* S_ISDOOR */
  1153. } else {
  1154. /* Unknown type -- possibly a regular file? */
  1155. c = '?';
  1156. desc[0] = '\0';
  1157. }
  1158. return c;
  1159. }
  1160. /* Convert a mode field into "ls -l" type perms field. */
  1161. static char *
  1162. get_lsperms(mode_t mode, char *desc)
  1163. {
  1164. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1165. static char bits[11] = {'\0'};
  1166. bits[0] = get_fileind(mode, desc);
  1167. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1168. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1169. strcpy(&bits[7], rwx[(mode & 7)]);
  1170. if (mode & S_ISUID)
  1171. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1172. if (mode & S_ISGID)
  1173. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1174. if (mode & S_ISVTX)
  1175. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1176. return bits;
  1177. }
  1178. /*
  1179. * Gets only a single line (that's what we need
  1180. * for now) or shows full command output in pager.
  1181. *
  1182. * If pager is valid, returns NULL
  1183. */
  1184. static char *
  1185. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1186. {
  1187. pid_t pid;
  1188. int pipefd[2];
  1189. FILE *pf;
  1190. int tmp, flags;
  1191. char *ret = NULL;
  1192. if (pipe(pipefd) == -1)
  1193. errexit();
  1194. for (tmp = 0; tmp < 2; ++tmp) {
  1195. /* Get previous flags */
  1196. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1197. /* Set bit for non-blocking flag */
  1198. flags |= O_NONBLOCK;
  1199. /* Change flags on fd */
  1200. fcntl(pipefd[tmp], F_SETFL, flags);
  1201. }
  1202. pid = fork();
  1203. if (pid == 0) {
  1204. /* In child */
  1205. close(pipefd[0]);
  1206. dup2(pipefd[1], STDOUT_FILENO);
  1207. dup2(pipefd[1], STDERR_FILENO);
  1208. close(pipefd[1]);
  1209. execlp(file, file, arg1, arg2, NULL);
  1210. _exit(1);
  1211. }
  1212. /* In parent */
  1213. waitpid(pid, &tmp, 0);
  1214. close(pipefd[1]);
  1215. if (!pager) {
  1216. pf = fdopen(pipefd[0], "r");
  1217. if (pf) {
  1218. ret = fgets(buf, bytes, pf);
  1219. close(pipefd[0]);
  1220. }
  1221. return ret;
  1222. }
  1223. pid = fork();
  1224. if (pid == 0) {
  1225. /* Show in pager in child */
  1226. dup2(pipefd[0], STDIN_FILENO);
  1227. close(pipefd[0]);
  1228. execlp("less", "less", NULL);
  1229. _exit(1);
  1230. }
  1231. /* In parent */
  1232. waitpid(pid, &tmp, 0);
  1233. close(pipefd[0]);
  1234. return NULL;
  1235. }
  1236. /*
  1237. * Follows the stat(1) output closely
  1238. */
  1239. static int
  1240. show_stats(char *fpath, char *fname, struct stat *sb)
  1241. {
  1242. char desc[32];
  1243. char *perms = get_lsperms(sb->st_mode, desc);
  1244. char *p, *begin = g_buf;
  1245. char tmp[] = "/tmp/nnnXXXXXX";
  1246. int fd = mkstemp(tmp);
  1247. if (fd == -1)
  1248. return -1;
  1249. /* Show file name or 'symlink' -> 'target' */
  1250. if (perms[0] == 'l') {
  1251. /* Note that MAX_CMD_LEN > PATH_MAX */
  1252. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1253. if (len != -1) {
  1254. g_buf[len] = '\0';
  1255. dprintf(fd, " File: '%s' -> ", unescape(fname, 0));
  1256. /*
  1257. * We pass g_buf but unescape() operates on g_buf too!
  1258. * Read the API notes for information on how this works.
  1259. */
  1260. dprintf(fd, "'%s'", unescape(g_buf, 0));
  1261. }
  1262. } else
  1263. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1264. /* Show size, blocks, file type */
  1265. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1266. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1267. #else
  1268. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1269. #endif
  1270. sb->st_size, sb->st_blocks, sb->st_blksize, desc);
  1271. /* Show containing device, inode, hardlink count */
  1272. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1273. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1274. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1275. #else
  1276. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1277. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1278. #endif
  1279. g_buf, sb->st_ino, sb->st_nlink);
  1280. /* Show major, minor number for block or char device */
  1281. if (perms[0] == 'b' || perms[0] == 'c')
  1282. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1283. /* Show permissions, owner, group */
  1284. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)", (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1285. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1286. /* Show last access time */
  1287. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1288. dprintf(fd, "\n\n Access: %s", g_buf);
  1289. /* Show last modification time */
  1290. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1291. dprintf(fd, "\n Modify: %s", g_buf);
  1292. /* Show last status change time */
  1293. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1294. dprintf(fd, "\n Change: %s", g_buf);
  1295. if (S_ISREG(sb->st_mode)) {
  1296. /* Show file(1) output */
  1297. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1298. if (p) {
  1299. dprintf(fd, "\n\n ");
  1300. while (*p) {
  1301. if (*p == ',') {
  1302. *p = '\0';
  1303. dprintf(fd, " %s\n", begin);
  1304. begin = p + 1;
  1305. }
  1306. ++p;
  1307. }
  1308. dprintf(fd, " %s", begin);
  1309. }
  1310. dprintf(fd, "\n\n");
  1311. } else
  1312. dprintf(fd, "\n\n\n");
  1313. close(fd);
  1314. exitcurses();
  1315. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1316. unlink(tmp);
  1317. initcurses();
  1318. return 0;
  1319. }
  1320. /*
  1321. * Get the order of 2 for this size
  1322. * In brief - return the number of trailing zeroes
  1323. */
  1324. static int
  1325. getorder(size_t size)
  1326. {
  1327. static int count, mask;
  1328. for (mask = 1, count = 0; count < 32; mask <<= 1, ++count)
  1329. if ((size & mask) != 0)
  1330. return count;
  1331. return 32;
  1332. }
  1333. static size_t
  1334. get_fs_free(char *path)
  1335. {
  1336. static struct statvfs svb;
  1337. if (statvfs(path, &svb) == -1)
  1338. return 0;
  1339. else
  1340. return svb.f_bavail << getorder(svb.f_frsize);
  1341. }
  1342. static size_t
  1343. get_fs_capacity(char *path)
  1344. {
  1345. struct statvfs svb;
  1346. if (statvfs(path, &svb) == -1)
  1347. return 0;
  1348. else
  1349. return svb.f_blocks << getorder(svb.f_bsize);
  1350. }
  1351. static int
  1352. show_mediainfo(char *fpath, char *arg)
  1353. {
  1354. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1355. return -1;
  1356. exitcurses();
  1357. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1358. initcurses();
  1359. return 0;
  1360. }
  1361. static int
  1362. handle_archive(char *fpath, char *arg, char *dir)
  1363. {
  1364. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[4], NULL, 0))
  1365. return -1;
  1366. if (arg[1] == 'x')
  1367. spawn(utils[4], arg, fpath, dir, F_NORMAL);
  1368. else {
  1369. exitcurses();
  1370. get_output(NULL, 0, utils[4], arg, fpath, 1);
  1371. initcurses();
  1372. }
  1373. return 0;
  1374. }
  1375. /*
  1376. * The help string tokens (each line) start with a HEX value
  1377. * which indicates the number of spaces to print before the
  1378. * particular token. This method was chosen instead of a flat
  1379. * string because the number of bytes in help was increasing
  1380. * the binary size by around a hundred bytes. This would only
  1381. * have increased as we keep adding new options.
  1382. */
  1383. static int
  1384. show_help(char *path)
  1385. {
  1386. char tmp[] = "/tmp/nnnXXXXXX";
  1387. int i = 0, fd = mkstemp(tmp);
  1388. char *start, *end;
  1389. static char helpstr[] = (
  1390. "cKey | Function\n"
  1391. "e- + -\n"
  1392. "7↑, k, ^P | Previous entry\n"
  1393. "7↓, j, ^N | Next entry\n"
  1394. "7PgUp, ^U | Scroll half page up\n"
  1395. "7PgDn, ^D | Scroll half page down\n"
  1396. "1Home, g, ^, ^A | Jump to first entry\n"
  1397. "2End, G, $, ^E | Jump to last entry\n"
  1398. "4→, ↵, l, ^M | Open file or enter dir\n"
  1399. "1←, Bksp, h, ^H | Go to parent dir\n"
  1400. "9Insert | Toggle navigate-as-you-type\n"
  1401. "e~ | Go HOME\n"
  1402. "e& | Go to initial dir\n"
  1403. "e- | Go to last visited dir\n"
  1404. "e/ | Filter dir contents\n"
  1405. "d^/ | Open desktop search tool\n"
  1406. "e. | Toggle hide . files\n"
  1407. "eb | Bookmark prompt\n"
  1408. "d^B | Pin current dir\n"
  1409. "d^V | Go to pinned dir\n"
  1410. "ec | Change dir prompt\n"
  1411. "ed | Toggle detail view\n"
  1412. "eD | File details\n"
  1413. "em | Brief media info\n"
  1414. "eM | Full media info\n"
  1415. "en | Create new\n"
  1416. "d^R | Rename selected entry\n"
  1417. "es | Toggle sort by size\n"
  1418. "eS | Toggle disk usage mode\n"
  1419. "et | Toggle sort by mtime\n"
  1420. "e! | Spawn SHELL in dir\n"
  1421. "ee | Edit entry in EDITOR\n"
  1422. "eo | Open dir in file manager\n"
  1423. "ep | Open entry in PAGER\n"
  1424. "eF | List archive\n"
  1425. "d^X | Extract archive\n"
  1426. "d^K | Invoke file path copier\n"
  1427. "d^L | Redraw, clear prompt\n"
  1428. "e? | Help, settings\n"
  1429. "eQ | Quit and change dir\n"
  1430. "aq, ^Q | Quit\n\n");
  1431. if (fd == -1)
  1432. return -1;
  1433. start = end = helpstr;
  1434. while (*end) {
  1435. while (*end != '\n')
  1436. ++end;
  1437. if (start == end) {
  1438. ++end;
  1439. continue;
  1440. }
  1441. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1442. start = ++end;
  1443. }
  1444. dprintf(fd, "\n");
  1445. if (getenv("NNN_BMS")) {
  1446. dprintf(fd, "BOOKMARKS\n");
  1447. for (; i < BM_MAX; ++i)
  1448. if (bookmark[i].key)
  1449. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1450. else
  1451. break;
  1452. dprintf(fd, "\n");
  1453. }
  1454. if (editor)
  1455. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1456. if (desktop_manager)
  1457. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1458. if (idletimeout)
  1459. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1460. if (copier)
  1461. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1462. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_free(path)));
  1463. dprintf(fd, "%s free\n", coolsize(get_fs_capacity(path)));
  1464. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1465. close(fd);
  1466. exitcurses();
  1467. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1468. unlink(tmp);
  1469. initcurses();
  1470. return 0;
  1471. }
  1472. static int
  1473. sum_bsizes(const char *fpath, const struct stat *sb,
  1474. int typeflag, struct FTW *ftwbuf)
  1475. {
  1476. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1477. ent_blocks += sb->st_blocks;
  1478. ++num_files;
  1479. return 0;
  1480. }
  1481. static int
  1482. dentfill(char *path, struct entry **dents,
  1483. int (*filter)(regex_t *, char *), regex_t *re)
  1484. {
  1485. static DIR *dirp;
  1486. static struct dirent *dp;
  1487. static char *namep, *pnb;
  1488. static struct entry *dentp;
  1489. static size_t off, namebuflen = NAMEBUF_INCR;
  1490. static ulong num_saved;
  1491. static int fd, n, count;
  1492. static struct stat sb_path, sb;
  1493. off = 0;
  1494. dirp = opendir(path);
  1495. if (dirp == NULL)
  1496. return 0;
  1497. fd = dirfd(dirp);
  1498. n = 0;
  1499. if (cfg.blkorder) {
  1500. num_files = 0;
  1501. dir_blocks = 0;
  1502. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1503. printwarn();
  1504. return 0;
  1505. }
  1506. }
  1507. while ((dp = readdir(dirp)) != NULL) {
  1508. namep = dp->d_name;
  1509. if (filter(re, namep) == 0) {
  1510. if (!cfg.blkorder)
  1511. continue;
  1512. /* Skip self and parent */
  1513. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1514. continue;
  1515. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1516. continue;
  1517. if (S_ISDIR(sb.st_mode)) {
  1518. if (sb_path.st_dev == sb.st_dev) {
  1519. ent_blocks = 0;
  1520. mkpath(path, namep, g_buf, PATH_MAX);
  1521. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1522. printmsg(STR_NFTWFAIL);
  1523. dir_blocks += sb.st_blocks;
  1524. } else
  1525. dir_blocks += ent_blocks;
  1526. }
  1527. } else {
  1528. if (sb.st_blocks)
  1529. dir_blocks += sb.st_blocks;
  1530. ++num_files;
  1531. }
  1532. continue;
  1533. }
  1534. /* Skip self and parent */
  1535. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1536. (namep[1] == '.' && namep[2] == '\0'))))
  1537. continue;
  1538. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1539. DPRINTF_S(namep);
  1540. continue;
  1541. }
  1542. if (n == total_dents) {
  1543. total_dents += ENTRY_INCR;
  1544. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1545. if (*dents == NULL) {
  1546. if (pnamebuf)
  1547. free(pnamebuf);
  1548. errexit();
  1549. }
  1550. }
  1551. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1552. if (namebuflen - off < NAME_MAX + 1) {
  1553. namebuflen += NAMEBUF_INCR;
  1554. pnb = pnamebuf;
  1555. pnamebuf = (char *)realloc(pnamebuf, namebuflen);
  1556. DPRINTF_P(pnamebuf);
  1557. if (pnamebuf == NULL) {
  1558. free(*dents);
  1559. errexit();
  1560. }
  1561. /* realloc() may result in memory move, we must re-adjust if that happens */
  1562. if (pnb != pnamebuf) {
  1563. dentp = *dents;
  1564. dentp->name = pnamebuf;
  1565. for (count = 1; count < n; ++dentp, ++count)
  1566. /* Current filename starts at last filename start + length */
  1567. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1568. }
  1569. }
  1570. dentp = *dents + n;
  1571. /* Copy file name */
  1572. dentp->name = (char *)((size_t)pnamebuf + off);
  1573. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1574. off += dentp->nlen;
  1575. /* Copy other fields */
  1576. dentp->mode = sb.st_mode;
  1577. dentp->t = sb.st_mtime;
  1578. dentp->size = sb.st_size;
  1579. if (cfg.blkorder) {
  1580. if (S_ISDIR(sb.st_mode)) {
  1581. ent_blocks = 0;
  1582. num_saved = num_files + 1;
  1583. mkpath(path, namep, g_buf, PATH_MAX);
  1584. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1585. printmsg(STR_NFTWFAIL);
  1586. dentp->blocks = sb.st_blocks;
  1587. } else
  1588. dentp->blocks = ent_blocks;
  1589. if (sb_path.st_dev == sb.st_dev)
  1590. dir_blocks += dentp->blocks;
  1591. else
  1592. num_files = num_saved;
  1593. } else {
  1594. dentp->blocks = sb.st_blocks;
  1595. dir_blocks += dentp->blocks;
  1596. ++num_files;
  1597. }
  1598. }
  1599. ++n;
  1600. }
  1601. /* Should never be null */
  1602. if (closedir(dirp) == -1) {
  1603. if (*dents) {
  1604. free(pnamebuf);
  1605. free(*dents);
  1606. }
  1607. errexit();
  1608. }
  1609. return n;
  1610. }
  1611. static void
  1612. dentfree(struct entry *dents)
  1613. {
  1614. free(pnamebuf);
  1615. free(dents);
  1616. }
  1617. /* Return the position of the matching entry or 0 otherwise */
  1618. static int
  1619. dentfind(struct entry *dents, int n, char *path)
  1620. {
  1621. if (!path)
  1622. return 0;
  1623. static int i;
  1624. static char *p;
  1625. p = basename(path);
  1626. DPRINTF_S(p);
  1627. for (i = 0; i < n; ++i)
  1628. if (xstrcmp(p, dents[i].name) == 0)
  1629. return i;
  1630. return 0;
  1631. }
  1632. static int
  1633. populate(char *path, char *oldpath, char *fltr)
  1634. {
  1635. static regex_t re;
  1636. /* Can fail when permissions change while browsing.
  1637. * It's assumed that path IS a directory when we are here.
  1638. */
  1639. if (access(path, R_OK) == -1)
  1640. return -1;
  1641. /* Search filter */
  1642. if (setfilter(&re, fltr) != 0)
  1643. return -1;
  1644. if (cfg.blkorder) {
  1645. printmsg("Calculating...");
  1646. refresh();
  1647. }
  1648. #ifdef DEBUGMODE
  1649. struct timespec ts1, ts2;
  1650. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1651. #endif
  1652. ndents = dentfill(path, &dents, visible, &re);
  1653. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1654. #ifdef DEBUGMODE
  1655. clock_gettime(CLOCK_REALTIME, &ts2);
  1656. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1657. #endif
  1658. /* Find cur from history */
  1659. cur = dentfind(dents, ndents, oldpath);
  1660. return 0;
  1661. }
  1662. static void
  1663. redraw(char *path)
  1664. {
  1665. static char buf[(NAME_MAX + 1) << 1];
  1666. static size_t ncols;
  1667. static int nlines, i;
  1668. static bool mode_changed;
  1669. mode_changed = FALSE;
  1670. nlines = MIN(LINES - 4, ndents);
  1671. /* Clean screen */
  1672. erase();
  1673. /* Fail redraw if < than 10 columns */
  1674. if (COLS < 10) {
  1675. printmsg("Too few columns!");
  1676. return;
  1677. }
  1678. /* Strip trailing slashes */
  1679. for (i = xstrlen(path) - 1; i > 0; --i)
  1680. if (path[i] == '/')
  1681. path[i] = '\0';
  1682. else
  1683. break;
  1684. DPRINTF_D(cur);
  1685. DPRINTF_S(path);
  1686. if (!realpath(path, g_buf)) {
  1687. printwarn();
  1688. return;
  1689. }
  1690. ncols = COLS;
  1691. if (ncols > PATH_MAX)
  1692. ncols = PATH_MAX;
  1693. /* No text wrapping in cwd line */
  1694. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1695. g_buf[ncols - 6] = '\0';
  1696. printw(CWD "%s\n\n", g_buf);
  1697. /* Fallback to light mode if less than 35 columns */
  1698. if (ncols < 35 && cfg.showdetail) {
  1699. cfg.showdetail ^= 1;
  1700. printptr = &printent;
  1701. mode_changed = TRUE;
  1702. }
  1703. /* Calculate the number of cols available to print entry name */
  1704. if (cfg.showdetail)
  1705. ncols -= 32;
  1706. else
  1707. ncols -= 5;
  1708. if (cfg.showcolor) {
  1709. attron(COLOR_PAIR(1) | A_BOLD);
  1710. cfg.dircolor = 1;
  1711. }
  1712. /* Print listing */
  1713. if (cur < (nlines >> 1)) {
  1714. for (i = 0; i < nlines; ++i)
  1715. printptr(&dents[i], i == cur, ncols);
  1716. } else if (cur >= ndents - (nlines >> 1)) {
  1717. for (i = ndents - nlines; i < ndents; ++i)
  1718. printptr(&dents[i], i == cur, ncols);
  1719. } else {
  1720. static int odd;
  1721. odd = ISODD(nlines);
  1722. nlines >>= 1;
  1723. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1724. printptr(&dents[i], i == cur, ncols);
  1725. }
  1726. /* Must reset e.g. no files in dir */
  1727. if (cfg.dircolor) {
  1728. attroff(COLOR_PAIR(1) | A_BOLD);
  1729. cfg.dircolor = 0;
  1730. }
  1731. if (cfg.showdetail) {
  1732. if (ndents) {
  1733. static char ind[2] = "\0\0";
  1734. static char sort[9];
  1735. if (cfg.mtimeorder)
  1736. sprintf(sort, "by time ");
  1737. else if (cfg.sizeorder)
  1738. sprintf(sort, "by size ");
  1739. else
  1740. sort[0] = '\0';
  1741. if (S_ISDIR(dents[cur].mode))
  1742. ind[0] = '/';
  1743. else if (S_ISLNK(dents[cur].mode))
  1744. ind[0] = '@';
  1745. else if (S_ISSOCK(dents[cur].mode))
  1746. ind[0] = '=';
  1747. else if (S_ISFIFO(dents[cur].mode))
  1748. ind[0] = '|';
  1749. else if (dents[cur].mode & 0100)
  1750. ind[0] = '*';
  1751. else
  1752. ind[0] = '\0';
  1753. /* We need to show filename as it may be truncated in directory listing */
  1754. if (!cfg.blkorder)
  1755. sprintf(buf, "%d/%d %s[%s%s]", cur + 1, ndents, sort, unescape(dents[cur].name, 0), ind);
  1756. else {
  1757. i = sprintf(buf, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  1758. sprintf(buf + i, "vol: %s free [%s%s]", coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), ind);
  1759. }
  1760. printmsg(buf);
  1761. } else
  1762. printmsg("0 items");
  1763. }
  1764. if (mode_changed) {
  1765. cfg.showdetail ^= 1;
  1766. printptr = &printent_long;
  1767. }
  1768. }
  1769. static void
  1770. browse(char *ipath, char *ifilter)
  1771. {
  1772. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX], lastdir[PATH_MAX], mark[PATH_MAX];
  1773. static char fltr[LINE_MAX];
  1774. char *dir, *tmp, *run = NULL, *env = NULL;
  1775. struct stat sb;
  1776. int r, fd, presel;
  1777. enum action sel = SEL_RUNARG + 1;
  1778. bool dir_changed = FALSE;
  1779. xstrlcpy(path, ipath, PATH_MAX);
  1780. xstrlcpy(fltr, ifilter, LINE_MAX);
  1781. oldpath[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1782. if (cfg.filtermode)
  1783. presel = FILTER;
  1784. else
  1785. presel = 0;
  1786. /* Allocate buffer to hold names */
  1787. pnamebuf = (char *)malloc(NAMEBUF_INCR);
  1788. if (pnamebuf == NULL)
  1789. errexit();
  1790. begin:
  1791. #ifdef LINUX_INOTIFY
  1792. if (dir_changed && inotify_wd >= 0) {
  1793. inotify_rm_watch(inotify_fd, inotify_wd);
  1794. inotify_wd = -1;
  1795. dir_changed = FALSE;
  1796. }
  1797. #elif defined(BSD_KQUEUE)
  1798. if (dir_changed && event_fd >= 0) {
  1799. close(event_fd);
  1800. event_fd = -1;
  1801. dir_changed = FALSE;
  1802. }
  1803. #endif
  1804. if (populate(path, oldpath, fltr) == -1) {
  1805. printwarn();
  1806. goto nochange;
  1807. }
  1808. #ifdef LINUX_INOTIFY
  1809. if (inotify_wd == -1)
  1810. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1811. #elif defined(BSD_KQUEUE)
  1812. if (event_fd == -1) {
  1813. #if defined(O_EVTONLY)
  1814. event_fd = open(path, O_EVTONLY);
  1815. #else
  1816. event_fd = open(path, O_RDONLY);
  1817. #endif
  1818. if (event_fd >= 0)
  1819. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  1820. }
  1821. #endif
  1822. for (;;) {
  1823. redraw(path);
  1824. nochange:
  1825. /* Exit if parent has exited */
  1826. if (getppid() == 1)
  1827. _exit(0);
  1828. sel = nextsel(&run, &env, &presel);
  1829. switch (sel) {
  1830. case SEL_BACK:
  1831. /* There is no going back */
  1832. if (istopdir(path)) {
  1833. printmsg(STR_ATROOT);
  1834. goto nochange;
  1835. }
  1836. dir = xdirname(path);
  1837. if (access(dir, R_OK) == -1) {
  1838. printwarn();
  1839. goto nochange;
  1840. }
  1841. /* Save history */
  1842. xstrlcpy(oldpath, path, PATH_MAX);
  1843. /* Save last working directory */
  1844. xstrlcpy(lastdir, path, PATH_MAX);
  1845. dir_changed = TRUE;
  1846. xstrlcpy(path, dir, PATH_MAX);
  1847. /* Reset filter */
  1848. xstrlcpy(fltr, ifilter, LINE_MAX);
  1849. if (cfg.filtermode)
  1850. presel = FILTER;
  1851. goto begin;
  1852. case SEL_GOIN:
  1853. /* Cannot descend in empty directories */
  1854. if (ndents == 0)
  1855. goto begin;
  1856. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1857. DPRINTF_S(newpath);
  1858. /* Get path info */
  1859. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1860. if (fd == -1) {
  1861. printwarn();
  1862. goto nochange;
  1863. }
  1864. if (fstat(fd, &sb) == -1) {
  1865. printwarn();
  1866. close(fd);
  1867. goto nochange;
  1868. }
  1869. close(fd);
  1870. DPRINTF_U(sb.st_mode);
  1871. switch (sb.st_mode & S_IFMT) {
  1872. case S_IFDIR:
  1873. if (access(newpath, R_OK) == -1) {
  1874. printwarn();
  1875. goto nochange;
  1876. }
  1877. /* Save last working directory */
  1878. xstrlcpy(lastdir, path, PATH_MAX);
  1879. dir_changed = TRUE;
  1880. xstrlcpy(path, newpath, PATH_MAX);
  1881. oldpath[0] = '\0';
  1882. /* Reset filter */
  1883. xstrlcpy(fltr, ifilter, LINE_MAX);
  1884. if (cfg.filtermode)
  1885. presel = FILTER;
  1886. goto begin;
  1887. case S_IFREG:
  1888. {
  1889. /* If NNN_USE_EDITOR is set,
  1890. * open text in EDITOR
  1891. */
  1892. if (editor) {
  1893. if (getmime(dents[cur].name)) {
  1894. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1895. continue;
  1896. }
  1897. /* Recognize and open plain
  1898. * text files with vi
  1899. */
  1900. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  1901. continue;
  1902. if (strstr(g_buf, "text/") == g_buf) {
  1903. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1904. continue;
  1905. }
  1906. }
  1907. /* Invoke desktop opener as last resort */
  1908. spawn(utils[2], newpath, NULL, NULL, nowait);
  1909. continue;
  1910. }
  1911. default:
  1912. printmsg("Unsupported file");
  1913. goto nochange;
  1914. }
  1915. case SEL_NEXT:
  1916. if (cur < ndents - 1)
  1917. ++cur;
  1918. else if (ndents)
  1919. /* Roll over, set cursor to first entry */
  1920. cur = 0;
  1921. break;
  1922. case SEL_PREV:
  1923. if (cur > 0)
  1924. --cur;
  1925. else if (ndents)
  1926. /* Roll over, set cursor to last entry */
  1927. cur = ndents - 1;
  1928. break;
  1929. case SEL_PGDN:
  1930. if (cur < ndents - 1)
  1931. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1932. break;
  1933. case SEL_PGUP:
  1934. if (cur > 0)
  1935. cur -= MIN((LINES - 4) / 2, cur);
  1936. break;
  1937. case SEL_HOME:
  1938. cur = 0;
  1939. break;
  1940. case SEL_END:
  1941. cur = ndents - 1;
  1942. break;
  1943. case SEL_CD:
  1944. {
  1945. char *input;
  1946. int truecd;
  1947. /* Save the program start dir */
  1948. tmp = getcwd(newpath, PATH_MAX);
  1949. if (tmp == NULL) {
  1950. printwarn();
  1951. goto nochange;
  1952. }
  1953. /* Switch to current path for readline(3) */
  1954. if (chdir(path) == -1) {
  1955. printwarn();
  1956. goto nochange;
  1957. }
  1958. exitcurses();
  1959. tmp = readline("chdir: ");
  1960. initcurses();
  1961. /* Change back to program start dir */
  1962. if (chdir(newpath) == -1)
  1963. printwarn();
  1964. if (tmp[0] == '\0')
  1965. break;
  1966. /* Add to readline(3) history */
  1967. add_history(tmp);
  1968. input = tmp;
  1969. tmp = strstrip(tmp);
  1970. if (tmp[0] == '\0') {
  1971. free(input);
  1972. break;
  1973. }
  1974. truecd = 0;
  1975. if (tmp[0] == '~') {
  1976. /* Expand ~ to HOME absolute path */
  1977. char *home = getenv("HOME");
  1978. if (home)
  1979. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1980. else {
  1981. free(input);
  1982. printmsg(STR_NOHOME);
  1983. goto nochange;
  1984. }
  1985. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1986. if (lastdir[0] == '\0') {
  1987. free(input);
  1988. break;
  1989. }
  1990. /* Switch to last visited dir */
  1991. xstrlcpy(newpath, lastdir, PATH_MAX);
  1992. truecd = 1;
  1993. } else if ((r = all_dots(tmp))) {
  1994. if (r == 1) {
  1995. /* Always in the current dir */
  1996. free(input);
  1997. break;
  1998. }
  1999. /* Show a message if already at / */
  2000. if (istopdir(path)) {
  2001. printmsg(STR_ATROOT);
  2002. free(input);
  2003. goto nochange;
  2004. }
  2005. --r; /* One . for the current dir */
  2006. dir = path;
  2007. /* Note: fd is used as a tmp variable here */
  2008. for (fd = 0; fd < r; ++fd) {
  2009. /* Reached / ? */
  2010. if (istopdir(path)) {
  2011. /* Can't cd beyond / */
  2012. break;
  2013. }
  2014. dir = xdirname(dir);
  2015. if (access(dir, R_OK) == -1) {
  2016. printwarn();
  2017. free(input);
  2018. goto nochange;
  2019. }
  2020. }
  2021. truecd = 1;
  2022. /* Save the path in case of cd ..
  2023. * We mark the current dir in parent dir
  2024. */
  2025. if (r == 1) {
  2026. xstrlcpy(oldpath, path, PATH_MAX);
  2027. truecd = 2;
  2028. }
  2029. xstrlcpy(newpath, dir, PATH_MAX);
  2030. } else
  2031. mkpath(path, tmp, newpath, PATH_MAX);
  2032. free(input);
  2033. if (!xdiraccess(newpath))
  2034. goto nochange;
  2035. if (truecd == 0) {
  2036. /* Probable change in dir */
  2037. /* No-op if it's the same directory */
  2038. if (xstrcmp(path, newpath) == 0)
  2039. break;
  2040. oldpath[0] = '\0';
  2041. } else if (truecd == 1)
  2042. /* Sure change in dir */
  2043. oldpath[0] = '\0';
  2044. /* Save last working directory */
  2045. xstrlcpy(lastdir, path, PATH_MAX);
  2046. dir_changed = TRUE;
  2047. /* Save the newly opted dir in path */
  2048. xstrlcpy(path, newpath, PATH_MAX);
  2049. /* Reset filter */
  2050. xstrlcpy(fltr, ifilter, LINE_MAX);
  2051. DPRINTF_S(path);
  2052. if (cfg.filtermode)
  2053. presel = FILTER;
  2054. goto begin;
  2055. }
  2056. case SEL_CDHOME:
  2057. dir = getenv("HOME");
  2058. if (dir == NULL) {
  2059. clearprompt();
  2060. goto nochange;
  2061. } // fallthrough
  2062. case SEL_CDBEGIN:
  2063. if (sel == SEL_CDBEGIN)
  2064. dir = ipath;
  2065. if (!xdiraccess(dir)) {
  2066. goto nochange;
  2067. }
  2068. if (xstrcmp(path, dir) == 0) {
  2069. break;
  2070. }
  2071. /* Save last working directory */
  2072. xstrlcpy(lastdir, path, PATH_MAX);
  2073. dir_changed = TRUE;
  2074. xstrlcpy(path, dir, PATH_MAX);
  2075. oldpath[0] = '\0';
  2076. /* Reset filter */
  2077. xstrlcpy(fltr, ifilter, LINE_MAX);
  2078. DPRINTF_S(path);
  2079. if (cfg.filtermode)
  2080. presel = FILTER;
  2081. goto begin;
  2082. case SEL_CDLAST: // fallthrough
  2083. case SEL_VISIT:
  2084. if (sel == SEL_VISIT) {
  2085. if (xstrcmp(mark, path) == 0)
  2086. break;
  2087. tmp = mark;
  2088. } else
  2089. tmp = lastdir;
  2090. if (tmp[0] == '\0') {
  2091. printmsg("Not set...");
  2092. goto nochange;
  2093. }
  2094. if (!xdiraccess(tmp))
  2095. goto nochange;
  2096. xstrlcpy(newpath, tmp, PATH_MAX);
  2097. xstrlcpy(lastdir, path, PATH_MAX);
  2098. dir_changed = TRUE;
  2099. xstrlcpy(path, newpath, PATH_MAX);
  2100. oldpath[0] = '\0';
  2101. /* Reset filter */
  2102. xstrlcpy(fltr, ifilter, LINE_MAX);
  2103. DPRINTF_S(path);
  2104. if (cfg.filtermode)
  2105. presel = FILTER;
  2106. goto begin;
  2107. case SEL_CDBM:
  2108. printprompt("key: ");
  2109. tmp = readinput();
  2110. clearprompt();
  2111. if (tmp == NULL)
  2112. break;
  2113. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  2114. if (xstrcmp(bookmark[r].key, tmp) != 0)
  2115. continue;
  2116. if (bookmark[r].loc[0] == '~') {
  2117. /* Expand ~ to HOME */
  2118. char *home = getenv("HOME");
  2119. if (home)
  2120. snprintf(newpath, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  2121. else {
  2122. printmsg(STR_NOHOME);
  2123. goto nochange;
  2124. }
  2125. } else
  2126. mkpath(path, bookmark[r].loc, newpath, PATH_MAX);
  2127. if (!xdiraccess(newpath))
  2128. goto nochange;
  2129. if (xstrcmp(path, newpath) == 0)
  2130. break;
  2131. oldpath[0] = '\0';
  2132. break;
  2133. }
  2134. if (!bookmark[r].key) {
  2135. printmsg("No matching bookmark");
  2136. goto nochange;
  2137. }
  2138. /* Save last working directory */
  2139. xstrlcpy(lastdir, path, PATH_MAX);
  2140. dir_changed = TRUE;
  2141. /* Save the newly opted dir in path */
  2142. xstrlcpy(path, newpath, PATH_MAX);
  2143. /* Reset filter */
  2144. xstrlcpy(fltr, ifilter, LINE_MAX);
  2145. DPRINTF_S(path);
  2146. if (cfg.filtermode)
  2147. presel = FILTER;
  2148. goto begin;
  2149. case SEL_PIN:
  2150. xstrlcpy(mark, path, PATH_MAX);
  2151. printmsg(mark);
  2152. goto nochange;
  2153. case SEL_FLTR:
  2154. presel = filterentries(path);
  2155. xstrlcpy(fltr, ifilter, LINE_MAX);
  2156. DPRINTF_S(fltr);
  2157. /* Save current */
  2158. if (ndents > 0)
  2159. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2160. goto nochange;
  2161. case SEL_MFLTR:
  2162. cfg.filtermode ^= 1;
  2163. if (cfg.filtermode)
  2164. presel = FILTER;
  2165. else
  2166. printmsg("navigate-as-you-type off");
  2167. goto nochange;
  2168. case SEL_SEARCH:
  2169. spawn(player, path, "search", NULL, F_NORMAL);
  2170. break;
  2171. case SEL_TOGGLEDOT:
  2172. cfg.showhidden ^= 1;
  2173. initfilter(cfg.showhidden, &ifilter);
  2174. xstrlcpy(fltr, ifilter, LINE_MAX);
  2175. goto begin;
  2176. case SEL_DETAIL:
  2177. cfg.showdetail ^= 1;
  2178. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2179. /* Save current */
  2180. if (ndents > 0)
  2181. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2182. goto begin;
  2183. case SEL_STATS:
  2184. if (ndents > 0) {
  2185. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2186. if (lstat(oldpath, &sb) == -1) {
  2187. if (dents)
  2188. dentfree(dents);
  2189. errexit();
  2190. } else {
  2191. if (show_stats(oldpath, dents[cur].name, &sb) < 0) {
  2192. printwarn();
  2193. goto nochange;
  2194. }
  2195. }
  2196. }
  2197. break;
  2198. case SEL_LIST: // fallthrough
  2199. case SEL_EXTRACT: // fallthrough
  2200. case SEL_MEDIA: // fallthrough
  2201. case SEL_FMEDIA:
  2202. if (ndents > 0) {
  2203. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2204. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2205. r = show_mediainfo(oldpath, run);
  2206. else
  2207. r = handle_archive(oldpath, run, path);
  2208. if (r == -1) {
  2209. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2210. sprintf(g_buf, "%s missing", utils[cfg.metaviewer]);
  2211. else
  2212. sprintf(g_buf, "%s missing", utils[4]);
  2213. printmsg(g_buf);
  2214. goto nochange;
  2215. }
  2216. }
  2217. break;
  2218. case SEL_DFB:
  2219. if (!desktop_manager) {
  2220. printmsg("NNN_DE_FILE_MANAGER not set");
  2221. goto nochange;
  2222. }
  2223. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2224. break;
  2225. case SEL_FSIZE:
  2226. cfg.sizeorder ^= 1;
  2227. cfg.mtimeorder = 0;
  2228. cfg.blkorder = 0;
  2229. /* Save current */
  2230. if (ndents > 0)
  2231. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2232. goto begin;
  2233. case SEL_BSIZE:
  2234. cfg.blkorder ^= 1;
  2235. if (cfg.blkorder) {
  2236. cfg.showdetail = 1;
  2237. printptr = &printent_long;
  2238. }
  2239. cfg.mtimeorder = 0;
  2240. cfg.sizeorder = 0;
  2241. /* Save current */
  2242. if (ndents > 0)
  2243. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2244. goto begin;
  2245. case SEL_MTIME:
  2246. cfg.mtimeorder ^= 1;
  2247. cfg.sizeorder = 0;
  2248. cfg.blkorder = 0;
  2249. /* Save current */
  2250. if (ndents > 0)
  2251. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2252. goto begin;
  2253. case SEL_REDRAW:
  2254. /* Save current */
  2255. if (ndents > 0)
  2256. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2257. goto begin;
  2258. case SEL_COPY:
  2259. if (copier && ndents) {
  2260. if (istopdir(path))
  2261. snprintf(newpath, PATH_MAX, "/%s", dents[cur].name);
  2262. else
  2263. snprintf(newpath, PATH_MAX, "%s/%s", path, dents[cur].name);
  2264. spawn(copier, newpath, NULL, NULL, F_NONE);
  2265. printmsg(newpath);
  2266. } else if (!copier)
  2267. printmsg("NNN_COPIER is not set");
  2268. goto nochange;
  2269. case SEL_NEW:
  2270. printprompt("name: ");
  2271. tmp = xreadline(NULL);
  2272. clearprompt();
  2273. if (tmp == NULL || tmp[0] == '\0')
  2274. break;
  2275. /* Allow only relative, same dir paths */
  2276. if (tmp[0] == '/' || xstrcmp(basename(tmp), tmp) != 0) {
  2277. printmsg(STR_INPUT);
  2278. goto nochange;
  2279. }
  2280. /* Open the descriptor to currently open directory */
  2281. fd = open(path, O_RDONLY | O_DIRECTORY);
  2282. if (fd == -1) {
  2283. printwarn();
  2284. goto nochange;
  2285. }
  2286. /* Check if another file with same name exists */
  2287. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2288. printmsg("Entry exists");
  2289. goto nochange;
  2290. }
  2291. /* Check if it's a dir or file */
  2292. printprompt("Press 'f' for file or 'd' for dir");
  2293. cleartimeout();
  2294. r = getch();
  2295. settimeout();
  2296. if (r == 'f') {
  2297. r = openat(fd, tmp, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
  2298. close(r);
  2299. } else if (r == 'd')
  2300. r = mkdirat(fd, tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2301. else {
  2302. close(fd);
  2303. break;
  2304. }
  2305. if (r == -1) {
  2306. printwarn();
  2307. close(fd);
  2308. goto nochange;
  2309. }
  2310. close(fd);
  2311. mkpath(path, tmp, oldpath, PATH_MAX);
  2312. goto begin;
  2313. case SEL_RENAME:
  2314. if (ndents <= 0)
  2315. break;
  2316. printprompt("");
  2317. tmp = xreadline(dents[cur].name);
  2318. clearprompt();
  2319. if (tmp == NULL || tmp[0] == '\0')
  2320. break;
  2321. /* Allow only relative, same dir paths */
  2322. if (tmp[0] == '/' || xstrcmp(basename(tmp), tmp) != 0) {
  2323. printmsg(STR_INPUT);
  2324. goto nochange;
  2325. }
  2326. /* Skip renaming to same name */
  2327. if (xstrcmp(tmp, dents[cur].name) == 0)
  2328. break;
  2329. /* Open the descriptor to currently open directory */
  2330. fd = open(path, O_RDONLY | O_DIRECTORY);
  2331. if (fd == -1) {
  2332. printwarn();
  2333. goto nochange;
  2334. }
  2335. /* Check if another file with same name exists */
  2336. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2337. /* File with the same name exists */
  2338. printprompt("Press 'y' to overwrite");
  2339. cleartimeout();
  2340. r = getch();
  2341. settimeout();
  2342. if (r != 'y') {
  2343. close(fd);
  2344. break;
  2345. }
  2346. }
  2347. /* Rename the file */
  2348. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2349. printwarn();
  2350. close(fd);
  2351. goto nochange;
  2352. }
  2353. close(fd);
  2354. mkpath(path, tmp, oldpath, PATH_MAX);
  2355. goto begin;
  2356. case SEL_HELP:
  2357. show_help(path);
  2358. break;
  2359. case SEL_RUN:
  2360. run = xgetenv(env, run);
  2361. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2362. /* Repopulate as directory content may have changed */
  2363. goto begin;
  2364. case SEL_RUNARG:
  2365. run = xgetenv(env, run);
  2366. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2367. break;
  2368. case SEL_CDQUIT:
  2369. {
  2370. char *tmpfile = "/tmp/nnn";
  2371. tmp = getenv("NNN_TMPFILE");
  2372. if (tmp)
  2373. tmpfile = tmp;
  2374. FILE *fp = fopen(tmpfile, "w");
  2375. if (fp) {
  2376. fprintf(fp, "cd \"%s\"", path);
  2377. fclose(fp);
  2378. }
  2379. /* Fall through to exit */
  2380. } // fallthrough
  2381. case SEL_QUIT:
  2382. dentfree(dents);
  2383. return;
  2384. }
  2385. /* Screensaver */
  2386. if (idletimeout != 0 && idle == idletimeout) {
  2387. idle = 0;
  2388. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2389. }
  2390. }
  2391. }
  2392. static void
  2393. usage(void)
  2394. {
  2395. printf("usage: nnn [-c N] [-e] [-i] [-l] [-p nlay] [-S]\n\
  2396. [-v] [-h] [PATH]\n\n\
  2397. The missing terminal file browser for X.\n\n\
  2398. positional arguments:\n\
  2399. PATH directory to open [default: current dir]\n\n\
  2400. optional arguments:\n\
  2401. -c N specify dir color, disables if N>7\n\
  2402. -e use exiftool instead of mediainfo\n\
  2403. -i start in navigate-as-you-type mode\n\
  2404. -l start in light mode (fewer details)\n\
  2405. -p nlay path to custom nlay\n\
  2406. -S start in disk usage analyzer mode\n\
  2407. -v show program version and exit\n\
  2408. -h show this help and exit\n\n\
  2409. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2410. exit(0);
  2411. }
  2412. int
  2413. main(int argc, char *argv[])
  2414. {
  2415. static char cwd[PATH_MAX];
  2416. char *ipath, *ifilter, *bmstr;
  2417. int opt;
  2418. /* Confirm we are in a terminal */
  2419. if (!isatty(0) || !isatty(1)) {
  2420. fprintf(stderr, "stdin or stdout is not a tty\n");
  2421. exit(1);
  2422. }
  2423. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2424. switch (opt) {
  2425. case 'S':
  2426. cfg.blkorder = 1;
  2427. break;
  2428. case 'l':
  2429. cfg.showdetail = 0;
  2430. printptr = &printent;
  2431. break;
  2432. case 'i':
  2433. cfg.filtermode = 1;
  2434. break;
  2435. case 'c':
  2436. if (atoi(optarg) > 7)
  2437. cfg.showcolor = 0;
  2438. else
  2439. cfg.color = (uchar)atoi(optarg);
  2440. break;
  2441. case 'e':
  2442. cfg.metaviewer = 1;
  2443. break;
  2444. case 'p':
  2445. player = optarg;
  2446. break;
  2447. case 'v':
  2448. printf("%s\n", VERSION);
  2449. return 0;
  2450. case 'h': // fallthrough
  2451. default:
  2452. usage();
  2453. }
  2454. }
  2455. if (argc == optind) {
  2456. /* Start in the current directory */
  2457. ipath = getcwd(cwd, PATH_MAX);
  2458. if (ipath == NULL)
  2459. ipath = "/";
  2460. } else {
  2461. ipath = realpath(argv[optind], cwd);
  2462. if (!ipath) {
  2463. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2464. exit(1);
  2465. }
  2466. }
  2467. /* Increase current open file descriptor limit */
  2468. open_max = max_openfds();
  2469. if (getuid() == 0)
  2470. cfg.showhidden = 1;
  2471. initfilter(cfg.showhidden, &ifilter);
  2472. #ifdef LINUX_INOTIFY
  2473. /* Initialize inotify */
  2474. inotify_fd = inotify_init1(IN_NONBLOCK);
  2475. if (inotify_fd < 0) {
  2476. fprintf(stderr, "Cannot initialize inotify: %s\n", strerror(errno));
  2477. exit(1);
  2478. }
  2479. #elif defined(BSD_KQUEUE)
  2480. kq = kqueue();
  2481. if (kq < 0) {
  2482. fprintf(stderr, "Cannot initialize kqueue: %s\n", strerror(errno));
  2483. exit(1);
  2484. }
  2485. gtimeout.tv_sec = 0;
  2486. gtimeout.tv_nsec = 0;
  2487. #endif
  2488. /* Parse bookmarks string, if available */
  2489. bmstr = getenv("NNN_BMS");
  2490. if (bmstr)
  2491. parsebmstr(bmstr);
  2492. /* Edit text in EDITOR, if opted */
  2493. if (getenv("NNN_USE_EDITOR"))
  2494. editor = xgetenv("EDITOR", "vi");
  2495. /* Set player if not set already */
  2496. if (!player)
  2497. player = utils[3];
  2498. /* Get the desktop file browser, if set */
  2499. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2500. /* Get screensaver wait time, if set; copier used as tmp var */
  2501. copier = getenv("NNN_IDLE_TIMEOUT");
  2502. if (copier)
  2503. idletimeout = abs(atoi(copier));
  2504. /* Get the default copier, if set */
  2505. copier = getenv("NNN_COPIER");
  2506. /* Get nowait flag */
  2507. nowait |= getenv("NNN_NOWAIT") ? F_NOWAIT : 0;
  2508. signal(SIGINT, SIG_IGN);
  2509. /* Test initial path */
  2510. if (!xdiraccess(ipath)) {
  2511. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2512. exit(1);
  2513. }
  2514. /* Set locale */
  2515. setlocale(LC_ALL, "");
  2516. #ifdef DEBUGMODE
  2517. enabledbg();
  2518. #endif
  2519. initcurses();
  2520. browse(ipath, ifilter);
  2521. exitcurses();
  2522. #ifdef LINUX_INOTIFY
  2523. /* Shutdown inotify */
  2524. if (inotify_wd >= 0)
  2525. inotify_rm_watch(inotify_fd, inotify_wd);
  2526. close(inotify_fd);
  2527. #elif defined(BSD_KQUEUE)
  2528. if (event_fd >= 0)
  2529. close(event_fd);
  2530. close(kq);
  2531. #endif
  2532. #ifdef DEBUGMODE
  2533. disabledbg();
  2534. #endif
  2535. exit(0);
  2536. }