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.
 
 
 
 
 
 

3591 lines
78 KiB

  1. /*
  2. * BSD 2-Clause License
  3. *
  4. * Copyright (c) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
  5. * Copyright (c) 2014-2016, Dimitris Papastamos <sin@2f30.org>
  6. * Copyright (c) 2016-2018, Arun Prakash Jana <engineerarun@gmail.com>
  7. * All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions are met:
  11. *
  12. * * Redistributions of source code must retain the above copyright notice, this
  13. * list of conditions and the following disclaimer.
  14. *
  15. * * Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  23. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  26. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  27. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #ifdef __linux__
  31. #ifdef __i386__
  32. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit Linux */
  33. #endif
  34. #include <sys/inotify.h>
  35. #define LINUX_INOTIFY
  36. #if !defined(__GLIBC__)
  37. #include <sys/types.h>
  38. #endif
  39. #endif
  40. #include <sys/resource.h>
  41. #include <sys/stat.h>
  42. #include <sys/statvfs.h>
  43. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  44. #include <sys/types.h>
  45. #include <sys/event.h>
  46. #include <sys/time.h>
  47. #define BSD_KQUEUE
  48. #else
  49. #include <sys/sysmacros.h>
  50. #endif
  51. #include <sys/wait.h>
  52. #include <ctype.h>
  53. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  54. #ifndef NCURSES_WIDECHAR
  55. #define NCURSES_WIDECHAR 1
  56. #endif
  57. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  58. #ifndef _XOPEN_SOURCE_EXTENDED
  59. #define _XOPEN_SOURCE_EXTENDED
  60. #endif
  61. #endif
  62. #ifndef __USE_XOPEN /* Fix failure due to wcswidth(), ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  63. #define __USE_XOPEN
  64. #endif
  65. #include <curses.h>
  66. #include <dirent.h>
  67. #include <errno.h>
  68. #include <fcntl.h>
  69. #include <grp.h>
  70. #include <libgen.h>
  71. #include <limits.h>
  72. #ifdef __gnu_hurd__
  73. #define PATH_MAX 4096
  74. #endif
  75. #include <locale.h>
  76. #include <pwd.h>
  77. #include <regex.h>
  78. #include <signal.h>
  79. #include <stdarg.h>
  80. #include <stdio.h>
  81. #include <stdlib.h>
  82. #include <string.h>
  83. #include <strings.h>
  84. #include <time.h>
  85. #include <unistd.h>
  86. #ifndef __USE_XOPEN_EXTENDED
  87. #define __USE_XOPEN_EXTENDED 1
  88. #endif
  89. #include <ftw.h>
  90. #include <wchar.h>
  91. #include "nnn.h"
  92. #ifdef DEBUGMODE
  93. static int DEBUG_FD;
  94. static int
  95. xprintf(int fd, const char *fmt, ...)
  96. {
  97. char buf[BUFSIZ];
  98. int r;
  99. va_list ap;
  100. va_start(ap, fmt);
  101. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  102. if (r > 0)
  103. r = write(fd, buf, r);
  104. va_end(ap);
  105. return r;
  106. }
  107. static int
  108. enabledbg()
  109. {
  110. FILE *fp = fopen("/tmp/nnn_debug", "w");
  111. if (!fp) {
  112. fprintf(stderr, "debug: open failed! (1)\n");
  113. fp = fopen("./nnn_debug", "w");
  114. if (!fp) {
  115. fprintf(stderr, "debug: open failed! (2)\n");
  116. return -1;
  117. }
  118. }
  119. DEBUG_FD = fileno(fp);
  120. if (DEBUG_FD == -1) {
  121. fprintf(stderr, "debug: open fd failed!\n");
  122. return -1;
  123. }
  124. return 0;
  125. }
  126. static void
  127. disabledbg()
  128. {
  129. close(DEBUG_FD);
  130. }
  131. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  132. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  133. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  134. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
  135. #else
  136. #define DPRINTF_D(x)
  137. #define DPRINTF_U(x)
  138. #define DPRINTF_S(x)
  139. #define DPRINTF_P(x)
  140. #endif /* DEBUGMODE */
  141. /* Macro definitions */
  142. #define VERSION "2.0"
  143. #define GENERAL_INFO "License: BSD 2-Clause\nWebpage: https://github.com/jarun/nnn"
  144. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  145. #undef MIN
  146. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  147. #define ISODD(x) ((x) & 1)
  148. #define TOUPPER(ch) \
  149. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  150. #define MAX_CMD_LEN 5120
  151. #define CURSR " > "
  152. #define EMPTY " "
  153. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  154. #define FILTER '/'
  155. #define REGEX_MAX 128
  156. #define BM_MAX 10
  157. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  158. #define NAMEBUF_INCR 0x1000 /* 64 dir entries at a time, avg. 64 chars per filename = 64*64B = 4KB */
  159. #define DESCRIPTOR_LEN 32
  160. #define _ALIGNMENT 0x10
  161. #define _ALIGNMENT_MASK 0xF
  162. #define SYMLINK_TO_DIR 0x1
  163. #define MAX_HOME_LEN 64
  164. /* Macros to define process spawn behaviour as flags */
  165. #define F_NONE 0x00 /* no flag set */
  166. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  167. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  168. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  169. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  170. #define F_NORMAL 0x80 /* spawn child process in non-curses regular CLI mode */
  171. /* CRC8 macros */
  172. #define WIDTH (sizeof(unsigned char) << 3)
  173. #define TOPBIT (1 << (WIDTH - 1))
  174. #define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
  175. #define CRC8_TABLE_LEN 256
  176. /* Volume info */
  177. #define FREE 0
  178. #define CAPACITY 1
  179. /* Function macros */
  180. #define exitcurses() endwin()
  181. #define clearprompt() printmsg("")
  182. #define printwarn() printmsg(strerror(errno))
  183. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  184. #define copyfilter() xstrlcpy(fltr, ifilter, NAME_MAX)
  185. #define copycurname() xstrlcpy(oldname, dents[cur].name, NAME_MAX + 1)
  186. #define settimeout() timeout(1000)
  187. #define cleartimeout() timeout(-1)
  188. #define errexit() printerr(__LINE__)
  189. #ifdef LINUX_INOTIFY
  190. #define EVENT_SIZE (sizeof(struct inotify_event))
  191. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  192. #elif defined(BSD_KQUEUE)
  193. #define NUM_EVENT_SLOTS 1
  194. #define NUM_EVENT_FDS 1
  195. #endif
  196. /* TYPE DEFINITIONS */
  197. typedef unsigned long ulong;
  198. typedef unsigned int uint;
  199. typedef unsigned char uchar;
  200. typedef unsigned short ushort;
  201. /* STRUCTURES */
  202. /* Directory entry */
  203. typedef struct entry {
  204. char *name;
  205. time_t t;
  206. off_t size;
  207. blkcnt_t blocks; /* number of 512B blocks allocated */
  208. mode_t mode;
  209. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  210. uchar flags; /* Flags specific to the file */
  211. } __attribute__ ((packed, aligned(_ALIGNMENT))) *pEntry;
  212. /* Bookmark */
  213. typedef struct {
  214. char *key;
  215. char *loc;
  216. } bm;
  217. /* Settings */
  218. typedef struct {
  219. uint filtermode : 1; /* Set to enter filter mode */
  220. uint mtimeorder : 1; /* Set to sort by time modified */
  221. uint sizeorder : 1; /* Set to sort by file size */
  222. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  223. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  224. uint showhidden : 1; /* Set to show hidden files */
  225. uint copymode : 1; /* Set when copying files */
  226. uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
  227. uint showdetail : 1; /* Clear to show fewer file info */
  228. uint showcolor : 1; /* Set to show dirs in blue */
  229. uint dircolor : 1; /* Current status of dir color */
  230. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  231. uint quote : 1; /* Copy paths within quotes */
  232. uint noxdisplay : 1; /* X11 is not available */
  233. uint color : 3; /* Color code for directories */
  234. uint reserved : 15;
  235. } settings;
  236. /* GLOBALS */
  237. /* Configuration */
  238. static settings cfg = {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 4, 0};
  239. static struct entry *dents;
  240. static char *pnamebuf, *pcopybuf;
  241. static int ndents, cur, total_dents = ENTRY_INCR;
  242. static uint idle;
  243. static uint idletimeout, copybufpos, copybuflen;
  244. static char *player;
  245. static char *copier;
  246. static char *editor;
  247. static char *dmanager; /* desktop file manager */
  248. static blkcnt_t ent_blocks;
  249. static blkcnt_t dir_blocks;
  250. static ulong num_files;
  251. static uint open_max;
  252. static bm bookmark[BM_MAX];
  253. static size_t g_tmpfplen; /* path to tmp files for copy without X, keybind help and file stats */
  254. static uchar g_crc;
  255. static uchar BLK_SHIFT = 9;
  256. /* CRC data */
  257. static uchar crc8table[CRC8_TABLE_LEN] __attribute__ ((aligned));
  258. /* For use in functions which are isolated and don't return the buffer */
  259. static char g_buf[MAX_CMD_LEN] __attribute__ ((aligned));
  260. /* Buffer for file path copy file */
  261. static char g_cppath[MAX_HOME_LEN] __attribute__ ((aligned));
  262. /* Buffer to store tmp file path */
  263. static char g_tmpfpath[MAX_HOME_LEN] __attribute__ ((aligned));
  264. #ifdef LINUX_INOTIFY
  265. static int inotify_fd, inotify_wd = -1;
  266. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  267. #elif defined(BSD_KQUEUE)
  268. static int kq, event_fd = -1;
  269. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  270. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  271. static struct timespec gtimeout;
  272. #endif
  273. /* Macros for utilities */
  274. #define MEDIAINFO 0
  275. #define EXIFTOOL 1
  276. #define OPENER 2
  277. #define NLAY 3
  278. #define ATOOL 4
  279. #define APACK 5
  280. #define VIDIR 6
  281. #define UNKNOWN 7
  282. /* Utilities to open files, run actions */
  283. static char * const utils[] = {
  284. "mediainfo",
  285. "exiftool",
  286. #ifdef __APPLE__
  287. "/usr/bin/open",
  288. #elif defined __CYGWIN__
  289. "cygstart",
  290. #else
  291. "xdg-open",
  292. #endif
  293. "nlay",
  294. "atool",
  295. "apack",
  296. "vidir",
  297. "UNKNOWN"
  298. };
  299. /* Common strings */
  300. #define STR_NFTWFAIL_ID 0
  301. #define STR_NOHOME_ID 1
  302. #define STR_INPUT_ID 2
  303. #define STR_INVBM_ID 3
  304. #define STR_COPY_ID 4
  305. #define STR_DATE_ID 5
  306. static const char messages[][16] = {
  307. "nftw failed",
  308. "HOME not set",
  309. "no traversal",
  310. "invalid key",
  311. "copy not set",
  312. "%F %T %z",
  313. };
  314. /* Forward declarations */
  315. static void redraw(char *path);
  316. static char * get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager);
  317. /* Functions */
  318. /*
  319. * CRC8 source:
  320. * https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
  321. */
  322. static void
  323. crc8init()
  324. {
  325. uchar remainder, bit;
  326. uint dividend;
  327. /* Compute the remainder of each possible dividend */
  328. for (dividend = 0; dividend < CRC8_TABLE_LEN; ++dividend) {
  329. /* Start with the dividend followed by zeros */
  330. remainder = dividend << (WIDTH - 8);
  331. /* Perform modulo-2 division, a bit at a time */
  332. for (bit = 8; bit > 0; --bit) {
  333. /* Try to divide the current data bit */
  334. if (remainder & TOPBIT)
  335. remainder = (remainder << 1) ^ POLYNOMIAL;
  336. else
  337. remainder = (remainder << 1);
  338. }
  339. /* Store the result into the table */
  340. crc8table[dividend] = remainder;
  341. }
  342. }
  343. static uchar
  344. crc8fast(uchar const message[], size_t n)
  345. {
  346. static uchar data, remainder;
  347. static size_t byte;
  348. /* Divide the message by the polynomial, a byte at a time */
  349. for (remainder = byte = 0; byte < n; ++byte) {
  350. data = message[byte] ^ (remainder >> (WIDTH - 8));
  351. remainder = crc8table[data] ^ (remainder << 8);
  352. }
  353. /* The final remainder is the CRC */
  354. return remainder;
  355. }
  356. /* Messages show up at the bottom */
  357. static void
  358. printmsg(const char *msg)
  359. {
  360. mvprintw(LINES - 1, 0, "%s\n", msg);
  361. }
  362. /* Kill curses and display error before exiting */
  363. static void
  364. printerr(int linenum)
  365. {
  366. exitcurses();
  367. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  368. if (cfg.noxdisplay && g_cppath[0])
  369. unlink(g_cppath);
  370. exit(1);
  371. }
  372. /* Print prompt on the last line */
  373. static void
  374. printprompt(char *str)
  375. {
  376. clearprompt();
  377. printw(str);
  378. }
  379. /* Increase the limit on open file descriptors, if possible */
  380. static rlim_t
  381. max_openfds()
  382. {
  383. struct rlimit rl;
  384. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  385. if (limit != 0)
  386. return 32;
  387. limit = rl.rlim_cur;
  388. rl.rlim_cur = rl.rlim_max;
  389. /* Return ~75% of max possible */
  390. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  391. limit = rl.rlim_max - (rl.rlim_max >> 2);
  392. /*
  393. * 20K is arbitrary. If the limit is set to max possible
  394. * value, the memory usage increases to more than double.
  395. */
  396. return limit > 20480 ? 20480 : limit;
  397. }
  398. return limit;
  399. }
  400. /*
  401. * Wrapper to realloc()
  402. * Frees current memory if realloc() fails and returns NULL.
  403. *
  404. * As per the docs, the *alloc() family is supposed to be memory aligned:
  405. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  406. * OS X: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  407. */
  408. static void *
  409. xrealloc(void *pcur, size_t len)
  410. {
  411. static void *pmem;
  412. pmem = realloc(pcur, len);
  413. if (!pmem && pcur)
  414. free(pcur);
  415. return pmem;
  416. }
  417. /*
  418. * Just a safe strncpy(3)
  419. * Always null ('\0') terminates if both src and dest are valid pointers.
  420. * Returns the number of bytes copied including terminating null byte.
  421. */
  422. static size_t
  423. xstrlcpy(char *dest, const char *src, size_t n)
  424. {
  425. static ulong *s, *d;
  426. static size_t len, blocks;
  427. static const uint lsize = sizeof(ulong);
  428. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  429. if (!src || !dest || !n)
  430. return 0;
  431. len = strlen(src) + 1;
  432. if (n > len)
  433. n = len;
  434. else if (len > n)
  435. /* Save total number of bytes to copy in len */
  436. len = n;
  437. /*
  438. * To enable -O3 ensure src and dest are 16-byte aligned
  439. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  440. */
  441. if ((n >= lsize) && (((ulong)src & _ALIGNMENT_MASK) == 0 && ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  442. s = (ulong *)src;
  443. d = (ulong *)dest;
  444. blocks = n >> _WSHIFT;
  445. n &= lsize - 1;
  446. while (blocks) {
  447. *d = *s;
  448. ++d, ++s;
  449. --blocks;
  450. }
  451. if (!n) {
  452. dest = (char *)d;
  453. *--dest = '\0';
  454. return len;
  455. }
  456. src = (char *)s;
  457. dest = (char *)d;
  458. }
  459. while (--n && (*dest = *src))
  460. ++dest, ++src;
  461. if (!n)
  462. *dest = '\0';
  463. return len;
  464. }
  465. /*
  466. * The poor man's implementation of memrchr(3).
  467. * We are only looking for '/' in this program.
  468. * And we are NOT expecting a '/' at the end.
  469. * Ideally 0 < n <= strlen(s).
  470. */
  471. static void *
  472. xmemrchr(uchar *s, uchar ch, size_t n)
  473. {
  474. static uchar *ptr;
  475. if (!s || !n)
  476. return NULL;
  477. ptr = s + n;
  478. do {
  479. --ptr;
  480. if (*ptr == ch)
  481. return ptr;
  482. } while (s != ptr);
  483. return NULL;
  484. }
  485. /*
  486. * The following dirname(3) implementation does not
  487. * modify the input. We use a copy of the original.
  488. *
  489. * Modified from the glibc (GNU LGPL) version.
  490. */
  491. static char *
  492. xdirname(const char *path)
  493. {
  494. static char * const buf = g_buf, *last_slash, *runp;
  495. xstrlcpy(buf, path, PATH_MAX);
  496. /* Find last '/'. */
  497. last_slash = xmemrchr((uchar *)buf, '/', strlen(buf));
  498. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  499. /* Determine whether all remaining characters are slashes. */
  500. for (runp = last_slash; runp != buf; --runp)
  501. if (runp[-1] != '/')
  502. break;
  503. /* The '/' is the last character, we have to look further. */
  504. if (runp != buf)
  505. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  506. }
  507. if (last_slash != NULL) {
  508. /* Determine whether all remaining characters are slashes. */
  509. for (runp = last_slash; runp != buf; --runp)
  510. if (runp[-1] != '/')
  511. break;
  512. /* Terminate the buffer. */
  513. if (runp == buf) {
  514. /* The last slash is the first character in the string.
  515. * We have to return "/". As a special case we have to
  516. * return "//" if there are exactly two slashes at the
  517. * beginning of the string. See XBD 4.10 Path Name
  518. * Resolution for more information.
  519. */
  520. if (last_slash == buf + 1)
  521. ++last_slash;
  522. else
  523. last_slash = buf + 1;
  524. } else
  525. last_slash = runp;
  526. last_slash[0] = '\0';
  527. } else {
  528. /* This assignment is ill-designed but the XPG specs require to
  529. * return a string containing "." in any case no directory part
  530. * is found and so a static and constant string is required.
  531. */
  532. buf[0] = '.';
  533. buf[1] = '\0';
  534. }
  535. return buf;
  536. }
  537. static char *
  538. xbasename(char *path)
  539. {
  540. static char *base;
  541. base = xmemrchr((uchar *)path, '/', strlen(path));
  542. return base ? base + 1 : path;
  543. }
  544. /* Writes buflen char(s) from buf to a file */
  545. static void
  546. writecp(const char *buf, const size_t buflen)
  547. {
  548. if (!g_cppath[0])
  549. return;
  550. FILE *fp = fopen(g_cppath, "w");
  551. if (fp) {
  552. fwrite(buf, 1, buflen, fp);
  553. fclose(fp);
  554. } else
  555. printwarn();
  556. }
  557. static bool
  558. appendfpath(const char *path, const size_t len)
  559. {
  560. if ((copybufpos >= copybuflen) || ((len + 3) > (copybuflen - copybufpos))) {
  561. copybuflen += PATH_MAX;
  562. pcopybuf = xrealloc(pcopybuf, copybuflen);
  563. if (!pcopybuf) {
  564. printmsg("no memory!");
  565. return FALSE;
  566. }
  567. }
  568. if (copybufpos) {
  569. pcopybuf[copybufpos - 1] = '\n';
  570. if (cfg.quote) {
  571. pcopybuf[copybufpos] = '\'';
  572. ++copybufpos;
  573. }
  574. } else if (cfg.quote) {
  575. pcopybuf[copybufpos] = '\'';
  576. ++copybufpos;
  577. }
  578. copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
  579. if (cfg.quote) {
  580. pcopybuf[copybufpos - 1] = '\'';
  581. pcopybuf[copybufpos] = '\0';
  582. ++copybufpos;
  583. }
  584. return TRUE;
  585. }
  586. static bool
  587. showcplist()
  588. {
  589. ssize_t len;
  590. if (!copybufpos)
  591. return FALSE;
  592. if (g_tmpfpath[0])
  593. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  594. else {
  595. printmsg(messages[STR_NOHOME_ID]);
  596. return -1;
  597. }
  598. int fd = mkstemp(g_tmpfpath);
  599. if (fd == -1)
  600. return FALSE;
  601. len = write(fd, pcopybuf, copybufpos - 1);
  602. close(fd);
  603. exitcurses();
  604. if (len == copybufpos - 1)
  605. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  606. unlink(g_tmpfpath);
  607. refresh();
  608. return TRUE;
  609. }
  610. /*
  611. * Return number of dots if all chars in a string are dots, else 0
  612. */
  613. static int
  614. all_dots(const char *path)
  615. {
  616. int count = 0;
  617. if (!path)
  618. return FALSE;
  619. while (*path == '.')
  620. ++count, ++path;
  621. if (*path)
  622. return 0;
  623. return count;
  624. }
  625. /* Initialize curses mode */
  626. static void
  627. initcurses(void)
  628. {
  629. if (initscr() == NULL) {
  630. char *term = getenv("TERM");
  631. if (term != NULL)
  632. fprintf(stderr, "error opening TERM: %s\n", term);
  633. else
  634. fprintf(stderr, "initscr() failed\n");
  635. exit(1);
  636. }
  637. cbreak();
  638. noecho();
  639. nonl();
  640. intrflush(stdscr, FALSE);
  641. keypad(stdscr, TRUE);
  642. curs_set(FALSE); /* Hide cursor */
  643. start_color();
  644. use_default_colors();
  645. if (cfg.showcolor)
  646. init_pair(1, cfg.color, -1);
  647. settimeout(); /* One second */
  648. }
  649. /*
  650. * Spawns a child process. Behaviour can be controlled using flag.
  651. * Limited to 2 arguments to a program, flag works on bit set.
  652. */
  653. static void
  654. spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
  655. {
  656. static char *shlvl;
  657. static pid_t pid;
  658. static int status;
  659. if (flag & F_NORMAL)
  660. exitcurses();
  661. pid = fork();
  662. if (pid == 0) {
  663. if (dir != NULL)
  664. status = chdir(dir);
  665. shlvl = getenv("SHLVL");
  666. /* Show a marker (to indicate nnn spawned shell) */
  667. if (flag & F_MARKER && shlvl != NULL) {
  668. fprintf(stdout, "\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  669. fprintf(stdout, "Next shell level: %d\n", atoi(shlvl) + 1);
  670. }
  671. /* Suppress stdout and stderr */
  672. if (flag & F_NOTRACE) {
  673. int fd = open("/dev/null", O_WRONLY, 0200);
  674. dup2(fd, 1);
  675. dup2(fd, 2);
  676. close(fd);
  677. }
  678. if (flag & F_NOWAIT) {
  679. signal(SIGHUP, SIG_IGN);
  680. signal(SIGPIPE, SIG_IGN);
  681. setsid();
  682. }
  683. if (flag & F_SIGINT)
  684. signal(SIGINT, SIG_DFL);
  685. execlp(file, file, arg1, arg2, NULL);
  686. _exit(1);
  687. } else {
  688. if (!(flag & F_NOWAIT))
  689. /* Ignore interruptions */
  690. while (waitpid(pid, &status, 0) == -1)
  691. DPRINTF_D(status);
  692. DPRINTF_D(pid);
  693. if (flag & F_NORMAL)
  694. refresh();
  695. }
  696. }
  697. /* Get program name from env var, else return fallback program */
  698. static char *
  699. xgetenv(const char *name, char *fallback)
  700. {
  701. static char *value;
  702. if (name == NULL)
  703. return fallback;
  704. value = getenv(name);
  705. return value && value[0] ? value : fallback;
  706. }
  707. /* Check if a dir exists, IS a dir and is readable */
  708. static bool
  709. xdiraccess(const char *path)
  710. {
  711. static DIR *dirp;
  712. dirp = opendir(path);
  713. if (dirp == NULL) {
  714. printwarn();
  715. return FALSE;
  716. }
  717. closedir(dirp);
  718. return TRUE;
  719. }
  720. /*
  721. * We assume none of the strings are NULL.
  722. *
  723. * Let's have the logic to sort numeric names in numeric order.
  724. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  725. *
  726. * If the absolute numeric values are same, we fallback to alphasort.
  727. */
  728. static int
  729. xstricmp(const char * const s1, const char * const s2)
  730. {
  731. static const char *c1, *c2;
  732. c1 = s1;
  733. while (isspace(*c1))
  734. ++c1;
  735. c2 = s2;
  736. while (isspace(*c2))
  737. ++c2;
  738. if (*c1 == '-' || *c1 == '+')
  739. ++c1;
  740. if (*c2 == '-' || *c2 == '+')
  741. ++c2;
  742. if (isdigit(*c1) && isdigit(*c2)) {
  743. while (*c1 >= '0' && *c1 <= '9')
  744. ++c1;
  745. while (isspace(*c1))
  746. ++c1;
  747. while (*c2 >= '0' && *c2 <= '9')
  748. ++c2;
  749. while (isspace(*c2))
  750. ++c2;
  751. }
  752. if (!*c1 && !*c2) {
  753. static long long num1, num2;
  754. num1 = strtoll(s1, NULL, 10);
  755. num2 = strtoll(s2, NULL, 10);
  756. if (num1 != num2) {
  757. if (num1 > num2)
  758. return 1;
  759. else
  760. return -1;
  761. }
  762. }
  763. return strcoll(s1, s2);
  764. }
  765. /* Return the integer value of a char representing HEX */
  766. static char
  767. xchartohex(char c)
  768. {
  769. if (c >= '0' && c <= '9')
  770. return c - '0';
  771. c = TOUPPER(c);
  772. if (c >= 'A' && c <= 'F')
  773. return c - 'A' + 10;
  774. return c;
  775. }
  776. static char *
  777. getmime(const char *file)
  778. {
  779. static regex_t regex;
  780. static uint i;
  781. static const uint len = LEN(assocs);
  782. for (i = 0; i < len; ++i) {
  783. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  784. continue;
  785. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  786. regfree(&regex);
  787. return assocs[i].mime;
  788. }
  789. }
  790. regfree(&regex);
  791. return NULL;
  792. }
  793. static int
  794. setfilter(regex_t *regex, char *filter)
  795. {
  796. static size_t len;
  797. static int r;
  798. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  799. if (r != 0 && filter && filter[0] != '\0') {
  800. len = COLS;
  801. if (len > NAME_MAX)
  802. len = NAME_MAX;
  803. regerror(r, regex, g_buf, len);
  804. printmsg(g_buf);
  805. }
  806. return r;
  807. }
  808. static void
  809. initfilter(int dot, char **ifilter)
  810. {
  811. *ifilter = dot ? "." : "^[^.]";
  812. }
  813. static int
  814. visible(regex_t *regex, char *file)
  815. {
  816. return regexec(regex, file, 0, NULL, 0) == 0;
  817. }
  818. static int
  819. entrycmp(const void *va, const void *vb)
  820. {
  821. static pEntry pa, pb;
  822. pa = (pEntry)va;
  823. pb = (pEntry)vb;
  824. /* Sort directories first */
  825. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  826. return 1;
  827. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  828. return -1;
  829. /* Do the actual sorting */
  830. if (cfg.mtimeorder)
  831. return pb->t - pa->t;
  832. if (cfg.sizeorder) {
  833. if (pb->size > pa->size)
  834. return 1;
  835. else if (pb->size < pa->size)
  836. return -1;
  837. }
  838. if (cfg.blkorder) {
  839. if (pb->blocks > pa->blocks)
  840. return 1;
  841. else if (pb->blocks < pa->blocks)
  842. return -1;
  843. }
  844. return xstricmp(pa->name, pb->name);
  845. }
  846. /*
  847. * Returns SEL_* if key is bound and 0 otherwise.
  848. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  849. * The next keyboard input can be simulated by presel.
  850. */
  851. static int
  852. nextsel(char **run, char **env, int *presel)
  853. {
  854. static int c;
  855. static uint i;
  856. static const uint len = LEN(bindings);
  857. #ifdef LINUX_INOTIFY
  858. static char inotify_buf[EVENT_BUF_LEN];
  859. #elif defined(BSD_KQUEUE)
  860. static struct kevent event_data[NUM_EVENT_SLOTS];
  861. #endif
  862. c = *presel;
  863. if (c == 0)
  864. c = getch();
  865. else {
  866. *presel = 0;
  867. /* Unwatch dir if we are still in a filtered view */
  868. #ifdef LINUX_INOTIFY
  869. if (inotify_wd >= 0) {
  870. inotify_rm_watch(inotify_fd, inotify_wd);
  871. inotify_wd = -1;
  872. }
  873. #elif defined(BSD_KQUEUE)
  874. if (event_fd >= 0) {
  875. close(event_fd);
  876. event_fd = -1;
  877. }
  878. #endif
  879. }
  880. if (c == -1) {
  881. ++idle;
  882. /* Do not check for directory changes in du
  883. * mode. A redraw forces du calculation.
  884. * Check for changes every odd second.
  885. */
  886. #ifdef LINUX_INOTIFY
  887. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  888. #elif defined(BSD_KQUEUE)
  889. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  890. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  891. #endif
  892. c = CONTROL('L');
  893. } else
  894. idle = 0;
  895. for (i = 0; i < len; ++i)
  896. if (c == bindings[i].sym) {
  897. *run = bindings[i].run;
  898. *env = bindings[i].env;
  899. return bindings[i].act;
  900. }
  901. return 0;
  902. }
  903. /*
  904. * Move non-matching entries to the end
  905. */
  906. static int
  907. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  908. {
  909. static int count;
  910. static struct entry _dent, *pdent1, *pdent2;
  911. for (count = 0; count < ndents; ++count) {
  912. if (filter(re, (*dents)[count].name) == 0) {
  913. if (count != --ndents) {
  914. pdent1 = &(*dents)[count];
  915. pdent2 = &(*dents)[ndents];
  916. *(&_dent) = *pdent1;
  917. *pdent1 = *pdent2;
  918. *pdent2 = *(&_dent);
  919. --count;
  920. }
  921. continue;
  922. }
  923. }
  924. return ndents;
  925. }
  926. static int
  927. matches(char *fltr)
  928. {
  929. static regex_t re;
  930. /* Search filter */
  931. if (setfilter(&re, fltr) != 0)
  932. return -1;
  933. ndents = fill(&dents, visible, &re);
  934. regfree(&re);
  935. if (!ndents)
  936. return 0;
  937. qsort(dents, ndents, sizeof(*dents), entrycmp);
  938. return 0;
  939. }
  940. static int
  941. filterentries(char *path)
  942. {
  943. static char ln[REGEX_MAX] __attribute__ ((aligned));
  944. static wchar_t wln[REGEX_MAX] __attribute__ ((aligned));
  945. static wint_t ch[2] = {0};
  946. int r, total = ndents, oldcur = cur, len = 1;
  947. char *pln = ln + 1;
  948. ln[0] = wln[0] = FILTER;
  949. ln[1] = wln[1] = '\0';
  950. cur = 0;
  951. cleartimeout();
  952. echo();
  953. curs_set(TRUE);
  954. printprompt(ln);
  955. while ((r = get_wch(ch)) != ERR) {
  956. if (*ch == 127 /* handle DEL */ || *ch == KEY_DC || *ch == KEY_BACKSPACE || *ch == '\b') {
  957. if (len == 1) {
  958. cur = oldcur;
  959. *ch = CONTROL('L');
  960. goto end;
  961. }
  962. wln[--len] = '\0';
  963. if (len == 1)
  964. cur = oldcur;
  965. wcstombs(ln, wln, REGEX_MAX);
  966. ndents = total;
  967. if (matches(pln) != -1)
  968. redraw(path);
  969. printprompt(ln);
  970. continue;
  971. }
  972. if (r == OK) {
  973. /* Handle all control chars in main loop */
  974. if (keyname(*ch)[0] == '^') {
  975. if (len == 1)
  976. cur = oldcur;
  977. goto end;
  978. }
  979. switch (*ch) {
  980. case '\r': // with nonl(), this is ENTER key value
  981. if (len == 1) {
  982. cur = oldcur;
  983. goto end;
  984. }
  985. if (matches(pln) == -1)
  986. goto end;
  987. redraw(path);
  988. goto end;
  989. case '?': // '?' is an invalid regex, show help instead
  990. if (len == 1) {
  991. cur = oldcur;
  992. goto end;
  993. } // fallthrough
  994. default:
  995. /* Reset cur in case it's a repeat search */
  996. if (len == 1)
  997. cur = 0;
  998. if (len == REGEX_MAX - 1)
  999. break;
  1000. wln[len] = (wchar_t)*ch;
  1001. wln[++len] = '\0';
  1002. wcstombs(ln, wln, REGEX_MAX);
  1003. /* Forward-filtering optimization:
  1004. * - new matches can only be a subset of current matches.
  1005. */
  1006. /* ndents = total; */
  1007. if (matches(pln) == -1)
  1008. continue;
  1009. /* If the only match is a dir, auto-select and cd into it */
  1010. if (ndents == 1 && cfg.filtermode && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  1011. *ch = KEY_ENTER;
  1012. cur = 0;
  1013. goto end;
  1014. }
  1015. /*
  1016. * redraw() should be above the auto-select optimization, for
  1017. * the case where there's an issue with dir auto-select, say,
  1018. * due to a permission problem. The transition is jumpy in
  1019. * case of such an error. However, we optimize for successful
  1020. * cases where the dir has permissions. This skips a redraw().
  1021. */
  1022. redraw(path);
  1023. printprompt(ln);
  1024. }
  1025. } else {
  1026. if (len == 1)
  1027. cur = oldcur;
  1028. goto end;
  1029. }
  1030. }
  1031. end:
  1032. noecho();
  1033. curs_set(FALSE);
  1034. settimeout();
  1035. /* Return keys for navigation etc. */
  1036. return *ch;
  1037. }
  1038. /* Show a prompt with input string and return the changes */
  1039. static char *
  1040. xreadline(char *fname, char *prompt)
  1041. {
  1042. int old_curs = curs_set(1);
  1043. size_t len, pos;
  1044. int x, y, r;
  1045. wint_t ch[2] = {0};
  1046. static wchar_t * const buf = (wchar_t *)g_buf;
  1047. printprompt(prompt);
  1048. if (fname) {
  1049. DPRINTF_S(fname);
  1050. len = pos = mbstowcs(buf, fname, NAME_MAX);
  1051. } else
  1052. len = (size_t)-1;
  1053. if (len == (size_t)-1) {
  1054. buf[0] = '\0';
  1055. len = pos = 0;
  1056. }
  1057. getyx(stdscr, y, x);
  1058. cleartimeout();
  1059. while (1) {
  1060. buf[len] = ' ';
  1061. mvaddnwstr(y, x, buf, len + 1);
  1062. move(y, x + wcswidth(buf, pos));
  1063. r = get_wch(ch);
  1064. if (r != ERR) {
  1065. if (r == OK) {
  1066. switch (*ch) {
  1067. case KEY_ENTER: //fallthrough
  1068. case '\n': //fallthrough
  1069. case '\r':
  1070. goto END;
  1071. case '\b': /* some old curses (e.g. rhel25) still send '\b' for backspace */
  1072. if (pos > 0) {
  1073. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1074. --len, --pos;
  1075. } //fallthrough
  1076. case '\t': /* TAB breaks cursor position, ignore it */
  1077. continue;
  1078. case CONTROL('L'):
  1079. clearprompt();
  1080. printprompt(prompt);
  1081. len = pos = 0;
  1082. continue;
  1083. case CONTROL('A'):
  1084. pos = 0;
  1085. continue;
  1086. case CONTROL('E'):
  1087. pos = len;
  1088. continue;
  1089. case CONTROL('U'):
  1090. clearprompt();
  1091. printprompt(prompt);
  1092. memmove(buf, buf + pos, (len - pos) << 2);
  1093. len -= pos;
  1094. pos = 0;
  1095. continue;
  1096. }
  1097. /* Filter out all other control chars */
  1098. if (keyname(*ch)[0] == '^')
  1099. continue;
  1100. if (pos < NAME_MAX - 1) {
  1101. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1102. buf[pos] = *ch;
  1103. ++len, ++pos;
  1104. continue;
  1105. }
  1106. } else {
  1107. switch (*ch) {
  1108. case KEY_LEFT:
  1109. if (pos > 0)
  1110. --pos;
  1111. break;
  1112. case KEY_RIGHT:
  1113. if (pos < len)
  1114. ++pos;
  1115. break;
  1116. case KEY_BACKSPACE:
  1117. if (pos > 0) {
  1118. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1119. --len, --pos;
  1120. }
  1121. break;
  1122. case KEY_DC:
  1123. if (pos < len) {
  1124. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  1125. --len;
  1126. }
  1127. break;
  1128. default:
  1129. break;
  1130. }
  1131. }
  1132. }
  1133. }
  1134. END:
  1135. buf[len] = '\0';
  1136. if (old_curs != ERR)
  1137. curs_set(old_curs);
  1138. settimeout();
  1139. DPRINTF_S(buf);
  1140. wcstombs(g_buf, buf, NAME_MAX);
  1141. clearprompt();
  1142. return g_buf;
  1143. }
  1144. /*
  1145. * Updates out with "dir/name or "/name"
  1146. * Returns the number of bytes copied including the terminating NULL byte
  1147. */
  1148. static size_t
  1149. mkpath(char *dir, char *name, char *out, size_t n)
  1150. {
  1151. static size_t len;
  1152. /* Handle absolute path */
  1153. if (name[0] == '/')
  1154. return xstrlcpy(out, name, n);
  1155. /* Handle root case */
  1156. if (istopdir(dir))
  1157. len = 1;
  1158. else
  1159. len = xstrlcpy(out, dir, n);
  1160. out[len - 1] = '/';
  1161. return (xstrlcpy(out + len, name, n - len) + len);
  1162. }
  1163. static void
  1164. parsebmstr()
  1165. {
  1166. int i = 0;
  1167. char *bms = getenv("NNN_BMS");
  1168. if (!bms)
  1169. return;
  1170. while (*bms && i < BM_MAX) {
  1171. bookmark[i].key = bms;
  1172. ++bms;
  1173. while (*bms && *bms != ':')
  1174. ++bms;
  1175. if (!*bms) {
  1176. bookmark[i].key = NULL;
  1177. break;
  1178. }
  1179. *bms = '\0';
  1180. bookmark[i].loc = ++bms;
  1181. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1182. bookmark[i].key = NULL;
  1183. break;
  1184. }
  1185. while (*bms && *bms != ';')
  1186. ++bms;
  1187. if (*bms)
  1188. *bms = '\0';
  1189. else
  1190. break;
  1191. ++bms;
  1192. ++i;
  1193. }
  1194. }
  1195. /*
  1196. * Get the real path to a bookmark
  1197. *
  1198. * NULL is returned in case of no match, path resolution failure etc.
  1199. * buf would be modified, so check return value before access
  1200. */
  1201. static char *
  1202. get_bm_loc(char *key, char *buf)
  1203. {
  1204. int r;
  1205. if (!key || !key[0])
  1206. return NULL;
  1207. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1208. if (strcmp(bookmark[r].key, key) == 0) {
  1209. if (bookmark[r].loc[0] == '~') {
  1210. char *home = getenv("HOME");
  1211. if (!home) {
  1212. DPRINTF_S(messages[STR_NOHOME_ID]);
  1213. return NULL;
  1214. }
  1215. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1216. } else
  1217. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1218. return buf;
  1219. }
  1220. }
  1221. DPRINTF_S("Invalid key");
  1222. return NULL;
  1223. }
  1224. static void
  1225. resetdircolor(mode_t mode)
  1226. {
  1227. if (cfg.dircolor && !S_ISDIR(mode)) {
  1228. attroff(COLOR_PAIR(1) | A_BOLD);
  1229. cfg.dircolor = 0;
  1230. }
  1231. }
  1232. /*
  1233. * Replace escape characters in a string with '?'
  1234. * Adjust string length to maxcols if > 0;
  1235. *
  1236. * Interestingly, note that unescape() uses g_buf. What happens if
  1237. * str also points to g_buf? In this case we assume that the caller
  1238. * acknowledges that it's OK to lose the data in g_buf after this
  1239. * call to unescape().
  1240. * The API, on its part, first converts str to multibyte (after which
  1241. * it doesn't touch str anymore). Only after that it starts modifying
  1242. * g_buf. This is a phased operation.
  1243. */
  1244. static char *
  1245. unescape(const char *str, uint maxcols)
  1246. {
  1247. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1248. static wchar_t *buf;
  1249. static size_t len;
  1250. /* Convert multi-byte to wide char */
  1251. len = mbstowcs(wbuf, str, PATH_MAX);
  1252. g_buf[0] = '\0';
  1253. buf = wbuf;
  1254. if (maxcols && len > maxcols) {
  1255. len = wcswidth(wbuf, len);
  1256. if (len > maxcols)
  1257. wbuf[maxcols] = 0;
  1258. }
  1259. while (*buf) {
  1260. if (*buf <= '\x1f' || *buf == '\x7f')
  1261. *buf = '\?';
  1262. ++buf;
  1263. }
  1264. /* Convert wide char to multi-byte */
  1265. wcstombs(g_buf, wbuf, PATH_MAX);
  1266. return g_buf;
  1267. }
  1268. static char *
  1269. coolsize(off_t size)
  1270. {
  1271. static const char * const U = "BKMGTPEZY";
  1272. static char size_buf[12]; /* Buffer to hold human readable size */
  1273. static off_t rem;
  1274. static int i;
  1275. i = 0;
  1276. rem = 0;
  1277. while (size > 1024) {
  1278. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1279. size >>= 10;
  1280. ++i;
  1281. }
  1282. if (i == 1) {
  1283. rem = (rem * 1000) >> 10;
  1284. rem /= 10;
  1285. if (rem % 10 >= 5) {
  1286. rem = (rem / 10) + 1;
  1287. if (rem == 10) {
  1288. ++size;
  1289. rem = 0;
  1290. }
  1291. } else
  1292. rem /= 10;
  1293. } else if (i == 2) {
  1294. rem = (rem * 1000) >> 10;
  1295. if (rem % 10 >= 5) {
  1296. rem = (rem / 10) + 1;
  1297. if (rem == 100) {
  1298. ++size;
  1299. rem = 0;
  1300. }
  1301. } else
  1302. rem /= 10;
  1303. } else if (i > 0) {
  1304. rem = (rem * 10000) >> 10;
  1305. if (rem % 10 >= 5) {
  1306. rem = (rem / 10) + 1;
  1307. if (rem == 1000) {
  1308. ++size;
  1309. rem = 0;
  1310. }
  1311. } else
  1312. rem /= 10;
  1313. }
  1314. if (i > 0)
  1315. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1316. else
  1317. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1318. return size_buf;
  1319. }
  1320. static char *
  1321. get_file_sym(mode_t mode)
  1322. {
  1323. static char ind[2] = "\0\0";
  1324. if (S_ISDIR(mode))
  1325. ind[0] = '/';
  1326. else if (S_ISLNK(mode))
  1327. ind[0] = '@';
  1328. else if (S_ISSOCK(mode))
  1329. ind[0] = '=';
  1330. else if (S_ISFIFO(mode))
  1331. ind[0] = '|';
  1332. else if (mode & 0100)
  1333. ind[0] = '*';
  1334. else
  1335. ind[0] = '\0';
  1336. return ind;
  1337. }
  1338. static void
  1339. printent(struct entry *ent, int sel, uint namecols)
  1340. {
  1341. static char *pname;
  1342. pname = unescape(ent->name, namecols);
  1343. /* Directories are always shown on top */
  1344. resetdircolor(ent->mode);
  1345. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1346. }
  1347. static void
  1348. printent_long(struct entry *ent, int sel, uint namecols)
  1349. {
  1350. static char buf[18], *pname;
  1351. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1352. pname = unescape(ent->name, namecols);
  1353. /* Directories are always shown on top */
  1354. resetdircolor(ent->mode);
  1355. if (sel)
  1356. attron(A_REVERSE);
  1357. if (S_ISDIR(ent->mode)) {
  1358. if (cfg.blkorder)
  1359. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1360. else
  1361. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1362. } else if (S_ISLNK(ent->mode)) {
  1363. if (ent->flags & SYMLINK_TO_DIR)
  1364. printw("%s%-16.16s @/ %s@\n", CURSYM(sel), buf, pname);
  1365. else
  1366. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1367. } else if (S_ISSOCK(ent->mode))
  1368. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1369. else if (S_ISFIFO(ent->mode))
  1370. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1371. else if (S_ISBLK(ent->mode))
  1372. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1373. else if (S_ISCHR(ent->mode))
  1374. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1375. else if (ent->mode & 0100) {
  1376. if (cfg.blkorder)
  1377. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1378. else
  1379. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1380. } else {
  1381. if (cfg.blkorder)
  1382. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1383. else
  1384. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1385. }
  1386. if (sel)
  1387. attroff(A_REVERSE);
  1388. }
  1389. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1390. static char
  1391. get_fileind(mode_t mode, char *desc)
  1392. {
  1393. static char c;
  1394. if (S_ISREG(mode)) {
  1395. c = '-';
  1396. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1397. if (mode & 0100)
  1398. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1399. } else if (S_ISDIR(mode)) {
  1400. c = 'd';
  1401. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1402. } else if (S_ISBLK(mode)) {
  1403. c = 'b';
  1404. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1405. } else if (S_ISCHR(mode)) {
  1406. c = 'c';
  1407. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1408. #ifdef S_ISFIFO
  1409. } else if (S_ISFIFO(mode)) {
  1410. c = 'p';
  1411. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1412. #endif /* S_ISFIFO */
  1413. #ifdef S_ISLNK
  1414. } else if (S_ISLNK(mode)) {
  1415. c = 'l';
  1416. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1417. #endif /* S_ISLNK */
  1418. #ifdef S_ISSOCK
  1419. } else if (S_ISSOCK(mode)) {
  1420. c = 's';
  1421. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1422. #endif /* S_ISSOCK */
  1423. #ifdef S_ISDOOR
  1424. /* Solaris 2.6, etc. */
  1425. } else if (S_ISDOOR(mode)) {
  1426. c = 'D';
  1427. desc[0] = '\0';
  1428. #endif /* S_ISDOOR */
  1429. } else {
  1430. /* Unknown type -- possibly a regular file? */
  1431. c = '?';
  1432. desc[0] = '\0';
  1433. }
  1434. return c;
  1435. }
  1436. /* Convert a mode field into "ls -l" type perms field. */
  1437. static char *
  1438. get_lsperms(mode_t mode, char *desc)
  1439. {
  1440. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1441. static char bits[11] = {'\0'};
  1442. bits[0] = get_fileind(mode, desc);
  1443. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1444. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1445. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1446. if (mode & S_ISUID)
  1447. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1448. if (mode & S_ISGID)
  1449. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1450. if (mode & S_ISVTX)
  1451. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1452. return bits;
  1453. }
  1454. /*
  1455. * Gets only a single line (that's what we need
  1456. * for now) or shows full command output in pager.
  1457. *
  1458. * If pager is valid, returns NULL
  1459. */
  1460. static char *
  1461. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1462. {
  1463. pid_t pid;
  1464. int pipefd[2];
  1465. FILE *pf;
  1466. int tmp, flags;
  1467. char *ret = NULL;
  1468. if (pipe(pipefd) == -1)
  1469. errexit();
  1470. for (tmp = 0; tmp < 2; ++tmp) {
  1471. /* Get previous flags */
  1472. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1473. /* Set bit for non-blocking flag */
  1474. flags |= O_NONBLOCK;
  1475. /* Change flags on fd */
  1476. fcntl(pipefd[tmp], F_SETFL, flags);
  1477. }
  1478. pid = fork();
  1479. if (pid == 0) {
  1480. /* In child */
  1481. close(pipefd[0]);
  1482. dup2(pipefd[1], STDOUT_FILENO);
  1483. dup2(pipefd[1], STDERR_FILENO);
  1484. close(pipefd[1]);
  1485. execlp(file, file, arg1, arg2, NULL);
  1486. _exit(1);
  1487. }
  1488. /* In parent */
  1489. waitpid(pid, &tmp, 0);
  1490. close(pipefd[1]);
  1491. if (!pager) {
  1492. pf = fdopen(pipefd[0], "r");
  1493. if (pf) {
  1494. ret = fgets(buf, bytes, pf);
  1495. close(pipefd[0]);
  1496. }
  1497. return ret;
  1498. }
  1499. pid = fork();
  1500. if (pid == 0) {
  1501. /* Show in pager in child */
  1502. dup2(pipefd[0], STDIN_FILENO);
  1503. close(pipefd[0]);
  1504. execlp("less", "less", NULL);
  1505. _exit(1);
  1506. }
  1507. /* In parent */
  1508. waitpid(pid, &tmp, 0);
  1509. close(pipefd[0]);
  1510. return NULL;
  1511. }
  1512. static char *
  1513. xgetpwuid(uid_t uid)
  1514. {
  1515. struct passwd *pwd = getpwuid(uid);
  1516. if (!pwd)
  1517. return utils[UNKNOWN];
  1518. return pwd->pw_name;
  1519. }
  1520. static char *
  1521. xgetgrgid(gid_t gid)
  1522. {
  1523. struct group *grp = getgrgid(gid);
  1524. if (!grp)
  1525. return utils[UNKNOWN];
  1526. return grp->gr_name;
  1527. }
  1528. /*
  1529. * Follows the stat(1) output closely
  1530. */
  1531. static int
  1532. show_stats(char *fpath, char *fname, struct stat *sb)
  1533. {
  1534. char desc[DESCRIPTOR_LEN];
  1535. char *perms = get_lsperms(sb->st_mode, desc);
  1536. char *p, *begin = g_buf;
  1537. if (g_tmpfpath[0])
  1538. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  1539. else {
  1540. printmsg(messages[STR_NOHOME_ID]);
  1541. return -1;
  1542. }
  1543. int fd = mkstemp(g_tmpfpath);
  1544. if (fd == -1)
  1545. return -1;
  1546. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1547. /* Show file name or 'symlink' -> 'target' */
  1548. if (perms[0] == 'l') {
  1549. /* Note that MAX_CMD_LEN > PATH_MAX */
  1550. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1551. if (len != -1) {
  1552. struct stat tgtsb;
  1553. if (!stat(fpath, &tgtsb) && S_ISDIR(tgtsb.st_mode))
  1554. g_buf[len++] = '/';
  1555. g_buf[len] = '\0';
  1556. /*
  1557. * We pass g_buf but unescape() operates on g_buf too!
  1558. * Read the API notes for information on how this works.
  1559. */
  1560. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1561. }
  1562. }
  1563. /* Show size, blocks, file type */
  1564. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1565. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1566. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1567. #else
  1568. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1569. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1570. #endif
  1571. /* Show containing device, inode, hardlink count */
  1572. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1573. snprintf(g_buf, 32, "%xh/%ud", sb->st_dev, sb->st_dev);
  1574. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1575. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1576. #else
  1577. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1578. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1579. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1580. #endif
  1581. /* Show major, minor number for block or char device */
  1582. if (perms[0] == 'b' || perms[0] == 'c')
  1583. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1584. /* Show permissions, owner, group */
  1585. 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,
  1586. sb->st_mode & 7, perms, sb->st_uid, xgetpwuid(sb->st_uid), sb->st_gid, xgetgrgid(sb->st_gid));
  1587. /* Show last access time */
  1588. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1589. dprintf(fd, "\n\n Access: %s", g_buf);
  1590. /* Show last modification time */
  1591. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1592. dprintf(fd, "\n Modify: %s", g_buf);
  1593. /* Show last status change time */
  1594. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1595. dprintf(fd, "\n Change: %s", g_buf);
  1596. if (S_ISREG(sb->st_mode)) {
  1597. /* Show file(1) output */
  1598. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1599. if (p) {
  1600. dprintf(fd, "\n\n ");
  1601. while (*p) {
  1602. if (*p == ',') {
  1603. *p = '\0';
  1604. dprintf(fd, " %s\n", begin);
  1605. begin = p + 1;
  1606. }
  1607. ++p;
  1608. }
  1609. dprintf(fd, " %s", begin);
  1610. }
  1611. dprintf(fd, "\n\n");
  1612. } else
  1613. dprintf(fd, "\n\n\n");
  1614. close(fd);
  1615. exitcurses();
  1616. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  1617. unlink(g_tmpfpath);
  1618. refresh();
  1619. return 0;
  1620. }
  1621. static size_t
  1622. get_fs_info(const char *path, bool type)
  1623. {
  1624. static struct statvfs svb;
  1625. if (statvfs(path, &svb) == -1)
  1626. return 0;
  1627. if (type == CAPACITY)
  1628. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1629. else
  1630. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1631. }
  1632. static int
  1633. show_mediainfo(char *fpath, char *arg)
  1634. {
  1635. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1636. return -1;
  1637. exitcurses();
  1638. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1639. refresh();
  1640. return 0;
  1641. }
  1642. static int
  1643. handle_archive(char *fpath, char *arg, char *dir)
  1644. {
  1645. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1646. return -1;
  1647. if (arg[1] == 'x')
  1648. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1649. else {
  1650. exitcurses();
  1651. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1652. refresh();
  1653. }
  1654. return 0;
  1655. }
  1656. /*
  1657. * The help string tokens (each line) start with a HEX value
  1658. * which indicates the number of spaces to print before the
  1659. * particular token. This method was chosen instead of a flat
  1660. * string because the number of bytes in help was increasing
  1661. * the binary size by around a hundred bytes. This would only
  1662. * have increased as we keep adding new options.
  1663. */
  1664. static int
  1665. show_help(char *path)
  1666. {
  1667. if (g_tmpfpath[0])
  1668. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  1669. else {
  1670. printmsg(messages[STR_NOHOME_ID]);
  1671. return -1;
  1672. }
  1673. int i = 0, fd = mkstemp(g_tmpfpath);
  1674. char *start, *end;
  1675. static char helpstr[] = {
  1676. "cKey Desc\n"
  1677. "e----\n"
  1678. "7↑, k, ^P Prev entry\n"
  1679. "7↓, j, ^N Next entry\n"
  1680. "7PgUp, ^U Scroll half page up\n"
  1681. "7PgDn, ^D Scroll half page down\n"
  1682. "1Home, g, ^, ^A First entry\n"
  1683. "2End, G, $, ^E Last entry\n"
  1684. "4→, ↵, l, ^M Open file/enter dir\n"
  1685. "1←, Bksp, h, ^H Parent dir\n"
  1686. "d^O Open with...\n"
  1687. "5Insert, ^I Toggle nav-as-you-type\n"
  1688. "e~ Go HOME\n"
  1689. "e& Start-up dir\n"
  1690. "e- Last visited dir\n"
  1691. "e/ Filter entries\n"
  1692. "d^/ Open desktop search app\n"
  1693. "e. Toggle show . files\n"
  1694. "d^B Bookmark prompt\n"
  1695. "eb Pin current dir\n"
  1696. "d^V Go to pinned dir\n"
  1697. "ec Change dir prompt\n"
  1698. "ed Toggle detail view\n"
  1699. "eD File details\n"
  1700. "em Brief media info\n"
  1701. "eM Full media info\n"
  1702. "en Create new\n"
  1703. "d^R Rename entry\n"
  1704. "er Open dir in vidir\n"
  1705. "es Toggle sort by size\n"
  1706. "eS Toggle apparent size\n"
  1707. "d^J Toggle du mode\n"
  1708. "et Toggle sort by mtime\n"
  1709. "a!, ^] Spawn SHELL in dir\n"
  1710. "eR Run custom script\n"
  1711. "ee Edit entry in EDITOR\n"
  1712. "eo Open DE filemanager\n"
  1713. "ep Open entry in PAGER\n"
  1714. "ef Archive entry\n"
  1715. "eF List archive\n"
  1716. "d^F Extract archive\n"
  1717. "6Space, ^K Copy file path\n"
  1718. "d^Y Toggle multi-copy\n"
  1719. "ey Show copy buffer\n"
  1720. "d^T Toggle path quote\n"
  1721. "d^L Redraw, clear prompt\n"
  1722. "eL Lock terminal\n"
  1723. "e? Help, settings\n"
  1724. "aQ, ^G Quit and cd\n"
  1725. "aq, ^X Quit\n\n"};
  1726. if (fd == -1)
  1727. return -1;
  1728. start = end = helpstr;
  1729. while (*end) {
  1730. while (*end != '\n')
  1731. ++end;
  1732. if (start == end) {
  1733. ++end;
  1734. continue;
  1735. }
  1736. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1737. start = ++end;
  1738. }
  1739. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_info(path, FREE)));
  1740. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  1741. if (getenv("NNN_BMS")) {
  1742. dprintf(fd, "BOOKMARKS\n");
  1743. for (; i < BM_MAX; ++i)
  1744. if (bookmark[i].key)
  1745. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1746. else
  1747. break;
  1748. dprintf(fd, "\n");
  1749. }
  1750. if (editor)
  1751. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1752. if (dmanager)
  1753. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", dmanager);
  1754. if (idletimeout)
  1755. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1756. if (copier)
  1757. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1758. if (getenv("NNN_NO_X"))
  1759. dprintf(fd, "NNN_NO_X: %s (%s)\n", getenv("NNN_NO_X"), g_cppath);
  1760. if (getenv("NNN_SCRIPT"))
  1761. dprintf(fd, "NNN_SCRIPT: %s\n", getenv("NNN_SCRIPT"));
  1762. if (getenv("NNN_MULTISCRIPT"))
  1763. dprintf(fd, "NNN_MULTISCRIPT: %s\n", getenv("NNN_MULTISCRIPT"));
  1764. if (getenv("NNN_SHOW_HIDDEN"))
  1765. dprintf(fd, "NNN_SHOW_HIDDEN: %s\n", getenv("NNN_SHOW_HIDDEN"));
  1766. dprintf(fd, "\n");
  1767. if (getenv("PWD"))
  1768. dprintf(fd, "PWD: %s\n", getenv("PWD"));
  1769. if (getenv("SHELL"))
  1770. dprintf(fd, "SHELL: %s\n", getenv("SHELL"));
  1771. if (getenv("SHLVL"))
  1772. dprintf(fd, "SHLVL: %s\n", getenv("SHLVL"));
  1773. if (getenv("VISUAL"))
  1774. dprintf(fd, "VISUAL: %s\n", getenv("VISUAL"));
  1775. else if (getenv("EDITOR"))
  1776. dprintf(fd, "EDITOR: %s\n", getenv("EDITOR"));
  1777. if (getenv("PAGER"))
  1778. dprintf(fd, "PAGER: %s\n", getenv("PAGER"));
  1779. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1780. close(fd);
  1781. exitcurses();
  1782. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  1783. unlink(g_tmpfpath);
  1784. refresh();
  1785. return 0;
  1786. }
  1787. int (*nftw_fn) (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  1788. static int
  1789. sum_bsizes(const char *fpath, const struct stat *sb,
  1790. int typeflag, struct FTW *ftwbuf)
  1791. {
  1792. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1793. ent_blocks += sb->st_blocks;
  1794. ++num_files;
  1795. return 0;
  1796. }
  1797. static int
  1798. sum_sizes(const char *fpath, const struct stat *sb,
  1799. int typeflag, struct FTW *ftwbuf)
  1800. {
  1801. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  1802. ent_blocks += sb->st_size;
  1803. ++num_files;
  1804. return 0;
  1805. }
  1806. static int
  1807. dentfill(char *path, struct entry **dents,
  1808. int (*filter)(regex_t *, char *), regex_t *re)
  1809. {
  1810. static DIR *dirp;
  1811. static struct dirent *dp;
  1812. static char *namep, *pnb;
  1813. static struct entry *dentp;
  1814. static size_t off, namebuflen = NAMEBUF_INCR;
  1815. static ulong num_saved;
  1816. static int fd, n, count;
  1817. static struct stat sb_path, sb;
  1818. off = 0;
  1819. dirp = opendir(path);
  1820. if (dirp == NULL)
  1821. return 0;
  1822. fd = dirfd(dirp);
  1823. n = 0;
  1824. if (cfg.blkorder) {
  1825. num_files = 0;
  1826. dir_blocks = 0;
  1827. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1828. printwarn();
  1829. return 0;
  1830. }
  1831. }
  1832. while ((dp = readdir(dirp)) != NULL) {
  1833. namep = dp->d_name;
  1834. if (filter(re, namep) == 0) {
  1835. if (!cfg.blkorder)
  1836. continue;
  1837. /* Skip self and parent */
  1838. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1839. continue;
  1840. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1841. continue;
  1842. if (S_ISDIR(sb.st_mode)) {
  1843. if (sb_path.st_dev == sb.st_dev) {
  1844. ent_blocks = 0;
  1845. mkpath(path, namep, g_buf, PATH_MAX);
  1846. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1847. printmsg(messages[STR_NFTWFAIL_ID]);
  1848. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1849. } else
  1850. dir_blocks += ent_blocks;
  1851. }
  1852. } else {
  1853. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1854. ++num_files;
  1855. }
  1856. continue;
  1857. }
  1858. /* Skip self and parent */
  1859. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1860. (namep[1] == '.' && namep[2] == '\0'))))
  1861. continue;
  1862. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1863. DPRINTF_S(namep);
  1864. continue;
  1865. }
  1866. if (n == total_dents) {
  1867. total_dents += ENTRY_INCR;
  1868. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1869. if (*dents == NULL) {
  1870. if (pnamebuf)
  1871. free(pnamebuf);
  1872. errexit();
  1873. }
  1874. DPRINTF_P(*dents);
  1875. }
  1876. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1877. if (namebuflen - off < NAME_MAX + 1) {
  1878. namebuflen += NAMEBUF_INCR;
  1879. pnb = pnamebuf;
  1880. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1881. if (pnamebuf == NULL) {
  1882. free(*dents);
  1883. errexit();
  1884. }
  1885. DPRINTF_P(pnamebuf);
  1886. /* realloc() may result in memory move, we must re-adjust if that happens */
  1887. if (pnb != pnamebuf) {
  1888. dentp = *dents;
  1889. dentp->name = pnamebuf;
  1890. for (count = 1; count < n; ++dentp, ++count)
  1891. /* Current filename starts at last filename start + length */
  1892. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1893. }
  1894. }
  1895. dentp = *dents + n;
  1896. /* Copy file name */
  1897. dentp->name = (char *)((size_t)pnamebuf + off);
  1898. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1899. off += dentp->nlen;
  1900. /* Copy other fields */
  1901. dentp->mode = sb.st_mode;
  1902. dentp->t = sb.st_mtime;
  1903. dentp->size = sb.st_size;
  1904. if (cfg.blkorder) {
  1905. if (S_ISDIR(sb.st_mode)) {
  1906. ent_blocks = 0;
  1907. num_saved = num_files + 1;
  1908. mkpath(path, namep, g_buf, PATH_MAX);
  1909. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1910. printmsg(messages[STR_NFTWFAIL_ID]);
  1911. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1912. } else
  1913. dentp->blocks = ent_blocks;
  1914. if (sb_path.st_dev == sb.st_dev)
  1915. dir_blocks += dentp->blocks;
  1916. else
  1917. num_files = num_saved;
  1918. } else {
  1919. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1920. dir_blocks += dentp->blocks;
  1921. ++num_files;
  1922. }
  1923. }
  1924. /* Flag if this is a symlink to a dir */
  1925. if (S_ISLNK(sb.st_mode))
  1926. if (!fstatat(fd, namep, &sb, 0)) {
  1927. if (S_ISDIR(sb.st_mode))
  1928. dentp->flags |= SYMLINK_TO_DIR;
  1929. else
  1930. dentp->flags &= ~SYMLINK_TO_DIR;
  1931. }
  1932. ++n;
  1933. }
  1934. /* Should never be null */
  1935. if (closedir(dirp) == -1) {
  1936. if (*dents) {
  1937. free(pnamebuf);
  1938. free(*dents);
  1939. }
  1940. errexit();
  1941. }
  1942. return n;
  1943. }
  1944. static void
  1945. dentfree(struct entry *dents)
  1946. {
  1947. free(pnamebuf);
  1948. free(dents);
  1949. }
  1950. /* Return the position of the matching entry or 0 otherwise */
  1951. static int
  1952. dentfind(struct entry *dents, const char *fname, int n)
  1953. {
  1954. static int i;
  1955. if (!fname)
  1956. return 0;
  1957. DPRINTF_S(fname);
  1958. for (i = 0; i < n; ++i)
  1959. if (strcmp(fname, dents[i].name) == 0)
  1960. return i;
  1961. return 0;
  1962. }
  1963. static int
  1964. populate(char *path, char *oldname, char *fltr)
  1965. {
  1966. static regex_t re;
  1967. /* Can fail when permissions change while browsing.
  1968. * It's assumed that path IS a directory when we are here.
  1969. */
  1970. if (access(path, R_OK) == -1)
  1971. return -1;
  1972. /* Search filter */
  1973. if (setfilter(&re, fltr) != 0)
  1974. return -1;
  1975. if (cfg.blkorder) {
  1976. printmsg("calculating...");
  1977. refresh();
  1978. }
  1979. #ifdef DEBUGMODE
  1980. struct timespec ts1, ts2;
  1981. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1982. #endif
  1983. ndents = dentfill(path, &dents, visible, &re);
  1984. regfree(&re);
  1985. if (!ndents)
  1986. return 0;
  1987. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1988. #ifdef DEBUGMODE
  1989. clock_gettime(CLOCK_REALTIME, &ts2);
  1990. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1991. #endif
  1992. /* Find cur from history */
  1993. cur = dentfind(dents, oldname, ndents);
  1994. return 0;
  1995. }
  1996. static void
  1997. redraw(char *path)
  1998. {
  1999. static char buf[NAME_MAX + 65] __attribute__ ((aligned));
  2000. static size_t ncols;
  2001. static int nlines, i;
  2002. static bool mode_changed;
  2003. mode_changed = FALSE;
  2004. nlines = MIN(LINES - 4, ndents);
  2005. /* Clean screen */
  2006. erase();
  2007. if (cfg.copymode)
  2008. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  2009. cfg.copymode = 0;
  2010. DPRINTF_S("copymode off");
  2011. }
  2012. /* Fail redraw if < than 10 columns */
  2013. if (COLS < 10) {
  2014. printmsg("too few columns!");
  2015. return;
  2016. }
  2017. /* Strip trailing slashes */
  2018. for (i = strlen(path) - 1; i > 0; --i)
  2019. if (path[i] == '/')
  2020. path[i] = '\0';
  2021. else
  2022. break;
  2023. DPRINTF_D(cur);
  2024. DPRINTF_S(path);
  2025. if (!realpath(path, g_buf)) {
  2026. printwarn();
  2027. return;
  2028. }
  2029. ncols = COLS;
  2030. if (ncols > PATH_MAX)
  2031. ncols = PATH_MAX;
  2032. attron(A_UNDERLINE);
  2033. /* No text wrapping in cwd line */
  2034. g_buf[ncols - 1] = '\0';
  2035. printw("%s\n\n", g_buf);
  2036. attroff(A_UNDERLINE);
  2037. /* Fallback to light mode if less than 35 columns */
  2038. if (ncols < 35 && cfg.showdetail) {
  2039. cfg.showdetail ^= 1;
  2040. printptr = &printent;
  2041. mode_changed = TRUE;
  2042. }
  2043. /* Calculate the number of cols available to print entry name */
  2044. if (cfg.showdetail)
  2045. ncols -= 32;
  2046. else
  2047. ncols -= 5;
  2048. if (cfg.showcolor) {
  2049. attron(COLOR_PAIR(1) | A_BOLD);
  2050. cfg.dircolor = 1;
  2051. }
  2052. /* Print listing */
  2053. if (cur < (nlines >> 1)) {
  2054. for (i = 0; i < nlines; ++i)
  2055. printptr(&dents[i], i == cur, ncols);
  2056. } else if (cur >= ndents - (nlines >> 1)) {
  2057. for (i = ndents - nlines; i < ndents; ++i)
  2058. printptr(&dents[i], i == cur, ncols);
  2059. } else {
  2060. static int odd;
  2061. odd = ISODD(nlines);
  2062. nlines >>= 1;
  2063. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  2064. printptr(&dents[i], i == cur, ncols);
  2065. }
  2066. /* Must reset e.g. no files in dir */
  2067. if (cfg.dircolor) {
  2068. attroff(COLOR_PAIR(1) | A_BOLD);
  2069. cfg.dircolor = 0;
  2070. }
  2071. if (cfg.showdetail) {
  2072. if (ndents) {
  2073. static char sort[9];
  2074. if (cfg.mtimeorder)
  2075. xstrlcpy(sort, "by time ", 9);
  2076. else if (cfg.sizeorder)
  2077. xstrlcpy(sort, "by size ", 9);
  2078. else
  2079. sort[0] = '\0';
  2080. /* We need to show filename as it may be truncated in directory listing */
  2081. if (!cfg.blkorder)
  2082. snprintf(buf, NAME_MAX + 65, "%d/%d %s[%s%s]",
  2083. cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2084. else {
  2085. i = snprintf(buf, 64, "%d/%d ", cur + 1, ndents);
  2086. if (cfg.apparentsz)
  2087. buf[i++] = 'a';
  2088. else
  2089. buf[i++] = 'd';
  2090. i += snprintf(buf + i, 64, "u: %s (%lu files) ", coolsize(dir_blocks << BLK_SHIFT), num_files);
  2091. snprintf(buf + i, NAME_MAX, "vol: %s free [%s%s]",
  2092. coolsize(get_fs_info(path, FREE)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2093. }
  2094. printmsg(buf);
  2095. } else
  2096. printmsg("0 items");
  2097. }
  2098. if (mode_changed) {
  2099. cfg.showdetail ^= 1;
  2100. printptr = &printent_long;
  2101. }
  2102. }
  2103. static void
  2104. browse(char *ipath, char *ifilter)
  2105. {
  2106. static char path[PATH_MAX] __attribute__ ((aligned));
  2107. static char newpath[PATH_MAX] __attribute__ ((aligned));
  2108. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  2109. static char mark[PATH_MAX] __attribute__ ((aligned));
  2110. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  2111. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  2112. char *dir, *tmp, *run = NULL, *env = NULL;
  2113. struct stat sb;
  2114. int r, fd, truecd, presel, ncp = 0, copystartid = 0, copyendid = 0;
  2115. enum action sel = SEL_RUNARG + 1;
  2116. bool dir_changed = FALSE;
  2117. xstrlcpy(path, ipath, PATH_MAX);
  2118. copyfilter();
  2119. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  2120. if (cfg.filtermode)
  2121. presel = FILTER;
  2122. else
  2123. presel = 0;
  2124. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2125. if (dents == NULL)
  2126. errexit();
  2127. DPRINTF_P(dents);
  2128. /* Allocate buffer to hold names */
  2129. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2130. if (pnamebuf == NULL) {
  2131. free(dents);
  2132. errexit();
  2133. }
  2134. DPRINTF_P(pnamebuf);
  2135. begin:
  2136. #ifdef LINUX_INOTIFY
  2137. if (dir_changed && inotify_wd >= 0) {
  2138. inotify_rm_watch(inotify_fd, inotify_wd);
  2139. inotify_wd = -1;
  2140. dir_changed = FALSE;
  2141. }
  2142. #elif defined(BSD_KQUEUE)
  2143. if (dir_changed && event_fd >= 0) {
  2144. close(event_fd);
  2145. event_fd = -1;
  2146. dir_changed = FALSE;
  2147. }
  2148. #endif
  2149. if (populate(path, oldname, fltr) == -1) {
  2150. printwarn();
  2151. goto nochange;
  2152. }
  2153. #ifdef LINUX_INOTIFY
  2154. if (inotify_wd == -1)
  2155. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2156. #elif defined(BSD_KQUEUE)
  2157. if (event_fd == -1) {
  2158. #if defined(O_EVTONLY)
  2159. event_fd = open(path, O_EVTONLY);
  2160. #else
  2161. event_fd = open(path, O_RDONLY);
  2162. #endif
  2163. if (event_fd >= 0)
  2164. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2165. }
  2166. #endif
  2167. for (;;) {
  2168. redraw(path);
  2169. nochange:
  2170. /* Exit if parent has exited */
  2171. if (getppid() == 1)
  2172. _exit(0);
  2173. sel = nextsel(&run, &env, &presel);
  2174. switch (sel) {
  2175. case SEL_BACK:
  2176. /* There is no going back */
  2177. if (istopdir(path)) {
  2178. /* Continue in navigate-as-you-type mode, if enabled */
  2179. if (cfg.filtermode)
  2180. presel = FILTER;
  2181. goto nochange;
  2182. }
  2183. dir = xdirname(path);
  2184. if (access(dir, R_OK) == -1) {
  2185. printwarn();
  2186. goto nochange;
  2187. }
  2188. /* Save history */
  2189. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2190. /* Save last working directory */
  2191. xstrlcpy(lastdir, path, PATH_MAX);
  2192. dir_changed = TRUE;
  2193. xstrlcpy(path, dir, PATH_MAX);
  2194. /* Reset filter */
  2195. copyfilter();
  2196. if (cfg.filtermode)
  2197. presel = FILTER;
  2198. goto begin;
  2199. case SEL_GOIN:
  2200. /* Cannot descend in empty directories */
  2201. if (!ndents)
  2202. goto begin;
  2203. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2204. DPRINTF_S(newpath);
  2205. /* Get path info */
  2206. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2207. if (fd == -1) {
  2208. printwarn();
  2209. goto nochange;
  2210. }
  2211. if (fstat(fd, &sb) == -1) {
  2212. printwarn();
  2213. close(fd);
  2214. goto nochange;
  2215. }
  2216. close(fd);
  2217. DPRINTF_U(sb.st_mode);
  2218. switch (sb.st_mode & S_IFMT) {
  2219. case S_IFDIR:
  2220. if (access(newpath, R_OK) == -1) {
  2221. printwarn();
  2222. goto nochange;
  2223. }
  2224. /* Save last working directory */
  2225. xstrlcpy(lastdir, path, PATH_MAX);
  2226. dir_changed = TRUE;
  2227. xstrlcpy(path, newpath, PATH_MAX);
  2228. oldname[0] = '\0';
  2229. /* Reset filter */
  2230. copyfilter();
  2231. if (cfg.filtermode)
  2232. presel = FILTER;
  2233. goto begin;
  2234. case S_IFREG:
  2235. {
  2236. /* If NNN_USE_EDITOR is set,
  2237. * open text in EDITOR
  2238. */
  2239. if (editor) {
  2240. if (getmime(dents[cur].name)) {
  2241. spawn(editor, newpath, NULL, path, F_NORMAL);
  2242. continue;
  2243. }
  2244. /* Recognize and open plain
  2245. * text files with vi
  2246. */
  2247. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2248. continue;
  2249. if (strstr(g_buf, "text/") == g_buf) {
  2250. spawn(editor, newpath, NULL, path, F_NORMAL);
  2251. continue;
  2252. }
  2253. }
  2254. /* Invoke desktop opener as last resort */
  2255. spawn(utils[OPENER], newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2256. continue;
  2257. }
  2258. default:
  2259. printmsg("unsupported file");
  2260. goto nochange;
  2261. }
  2262. case SEL_NEXT:
  2263. if (cur < ndents - 1)
  2264. ++cur;
  2265. else if (ndents)
  2266. /* Roll over, set cursor to first entry */
  2267. cur = 0;
  2268. break;
  2269. case SEL_PREV:
  2270. if (cur > 0)
  2271. --cur;
  2272. else if (ndents)
  2273. /* Roll over, set cursor to last entry */
  2274. cur = ndents - 1;
  2275. break;
  2276. case SEL_PGDN:
  2277. if (cur < ndents - 1)
  2278. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2279. break;
  2280. case SEL_PGUP:
  2281. if (cur > 0)
  2282. cur -= MIN((LINES - 4) / 2, cur);
  2283. break;
  2284. case SEL_HOME:
  2285. cur = 0;
  2286. break;
  2287. case SEL_END:
  2288. cur = ndents - 1;
  2289. break;
  2290. case SEL_CD:
  2291. truecd = 0;
  2292. tmp = xreadline(NULL, "cd: ");
  2293. if (tmp == NULL || tmp[0] == '\0')
  2294. break;
  2295. if (tmp[0] == '~') {
  2296. /* Expand ~ to HOME absolute path */
  2297. dir = getenv("HOME");
  2298. if (dir)
  2299. snprintf(newpath, PATH_MAX, "%s%s", dir, tmp + 1);
  2300. else {
  2301. printmsg(messages[STR_NOHOME_ID]);
  2302. goto nochange;
  2303. }
  2304. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2305. if (lastdir[0] == '\0')
  2306. break;
  2307. /* Switch to last visited dir */
  2308. xstrlcpy(newpath, lastdir, PATH_MAX);
  2309. truecd = 1;
  2310. } else if ((r = all_dots(tmp))) {
  2311. if (r == 1)
  2312. /* Always in the current dir */
  2313. break;
  2314. /* Show a message if already at / */
  2315. if (istopdir(path)) {
  2316. /* Continue in navigate-as-you-type mode, if enabled */
  2317. if (cfg.filtermode)
  2318. presel = FILTER;
  2319. goto nochange;
  2320. }
  2321. --r; /* One . for the current dir */
  2322. dir = path;
  2323. /* Note: fd is used as a tmp variable here */
  2324. for (fd = 0; fd < r; ++fd) {
  2325. /* Reached / ? */
  2326. if (istopdir(path)) {
  2327. /* Can't cd beyond / */
  2328. break;
  2329. }
  2330. dir = xdirname(dir);
  2331. if (access(dir, R_OK) == -1) {
  2332. printwarn();
  2333. goto nochange;
  2334. }
  2335. }
  2336. truecd = 1;
  2337. /* Save the path in case of cd ..
  2338. * We mark the current dir in parent dir
  2339. */
  2340. if (r == 1) {
  2341. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2342. truecd = 2;
  2343. }
  2344. xstrlcpy(newpath, dir, PATH_MAX);
  2345. } else
  2346. mkpath(path, tmp, newpath, PATH_MAX);
  2347. if (!xdiraccess(newpath))
  2348. goto nochange;
  2349. if (truecd == 0) {
  2350. /* Probable change in dir */
  2351. /* No-op if it's the same directory */
  2352. if (strcmp(path, newpath) == 0)
  2353. break;
  2354. oldname[0] = '\0';
  2355. } else if (truecd == 1)
  2356. /* Sure change in dir */
  2357. oldname[0] = '\0';
  2358. /* Save last working directory */
  2359. xstrlcpy(lastdir, path, PATH_MAX);
  2360. dir_changed = TRUE;
  2361. /* Save the newly opted dir in path */
  2362. xstrlcpy(path, newpath, PATH_MAX);
  2363. /* Reset filter */
  2364. copyfilter();
  2365. DPRINTF_S(path);
  2366. if (cfg.filtermode)
  2367. presel = FILTER;
  2368. goto begin;
  2369. case SEL_CDHOME:
  2370. dir = getenv("HOME");
  2371. if (dir == NULL) {
  2372. clearprompt();
  2373. goto nochange;
  2374. } // fallthrough
  2375. case SEL_CDBEGIN:
  2376. if (sel == SEL_CDBEGIN)
  2377. dir = ipath;
  2378. if (!xdiraccess(dir))
  2379. goto nochange;
  2380. if (strcmp(path, dir) == 0)
  2381. break;
  2382. /* Save last working directory */
  2383. xstrlcpy(lastdir, path, PATH_MAX);
  2384. dir_changed = TRUE;
  2385. xstrlcpy(path, dir, PATH_MAX);
  2386. oldname[0] = '\0';
  2387. /* Reset filter */
  2388. copyfilter();
  2389. DPRINTF_S(path);
  2390. if (cfg.filtermode)
  2391. presel = FILTER;
  2392. goto begin;
  2393. case SEL_CDLAST: // fallthrough
  2394. case SEL_VISIT:
  2395. if (sel == SEL_VISIT) {
  2396. if (strcmp(mark, path) == 0)
  2397. break;
  2398. tmp = mark;
  2399. } else
  2400. tmp = lastdir;
  2401. if (tmp[0] == '\0') {
  2402. printmsg("not set...");
  2403. goto nochange;
  2404. }
  2405. if (!xdiraccess(tmp))
  2406. goto nochange;
  2407. xstrlcpy(newpath, tmp, PATH_MAX);
  2408. xstrlcpy(lastdir, path, PATH_MAX);
  2409. dir_changed = TRUE;
  2410. xstrlcpy(path, newpath, PATH_MAX);
  2411. oldname[0] = '\0';
  2412. /* Reset filter */
  2413. copyfilter();
  2414. DPRINTF_S(path);
  2415. if (cfg.filtermode)
  2416. presel = FILTER;
  2417. goto begin;
  2418. case SEL_CDBM:
  2419. tmp = xreadline(NULL, "key: ");
  2420. if (tmp == NULL || tmp[0] == '\0')
  2421. break;
  2422. /* Interpret ~, - and & keys */
  2423. if ((tmp[1] == '\0') && (tmp[0] == '~' || tmp[0] == '-' || tmp[0] == '&')) {
  2424. presel = tmp[0];
  2425. goto begin;
  2426. }
  2427. if (get_bm_loc(tmp, newpath) == NULL) {
  2428. printmsg(messages[STR_INVBM_ID]);
  2429. goto nochange;
  2430. }
  2431. if (!xdiraccess(newpath))
  2432. goto nochange;
  2433. if (strcmp(path, newpath) == 0)
  2434. break;
  2435. oldname[0] = '\0';
  2436. /* Save last working directory */
  2437. xstrlcpy(lastdir, path, PATH_MAX);
  2438. dir_changed = TRUE;
  2439. /* Save the newly opted dir in path */
  2440. xstrlcpy(path, newpath, PATH_MAX);
  2441. /* Reset filter */
  2442. copyfilter();
  2443. DPRINTF_S(path);
  2444. if (cfg.filtermode)
  2445. presel = FILTER;
  2446. goto begin;
  2447. case SEL_PIN:
  2448. xstrlcpy(mark, path, PATH_MAX);
  2449. printmsg(mark);
  2450. goto nochange;
  2451. case SEL_FLTR:
  2452. presel = filterentries(path);
  2453. copyfilter();
  2454. DPRINTF_S(fltr);
  2455. /* Save current */
  2456. if (ndents)
  2457. copycurname();
  2458. goto nochange;
  2459. case SEL_MFLTR:
  2460. cfg.filtermode ^= 1;
  2461. if (cfg.filtermode)
  2462. presel = FILTER;
  2463. else {
  2464. /* Save current */
  2465. if (ndents)
  2466. copycurname();
  2467. /* Start watching the directory */
  2468. goto begin;
  2469. }
  2470. goto nochange;
  2471. case SEL_SEARCH:
  2472. spawn(player, path, "search", NULL, F_NORMAL);
  2473. break;
  2474. case SEL_TOGGLEDOT:
  2475. cfg.showhidden ^= 1;
  2476. initfilter(cfg.showhidden, &ifilter);
  2477. copyfilter();
  2478. goto begin;
  2479. case SEL_DETAIL:
  2480. cfg.showdetail ^= 1;
  2481. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2482. /* Save current */
  2483. if (ndents)
  2484. copycurname();
  2485. goto begin;
  2486. case SEL_STATS:
  2487. if (!ndents)
  2488. break;
  2489. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2490. if (lstat(newpath, &sb) == -1) {
  2491. if (dents)
  2492. dentfree(dents);
  2493. errexit();
  2494. }
  2495. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2496. printwarn();
  2497. goto nochange;
  2498. }
  2499. break;
  2500. case SEL_LIST: // fallthrough
  2501. case SEL_EXTRACT: // fallthrough
  2502. case SEL_MEDIA: // fallthrough
  2503. case SEL_FMEDIA:
  2504. if (!ndents)
  2505. break;
  2506. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2507. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2508. r = show_mediainfo(newpath, run);
  2509. else
  2510. r = handle_archive(newpath, run, path);
  2511. if (r == -1) {
  2512. xstrlcpy(newpath, "missing ", PATH_MAX);
  2513. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2514. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2515. else
  2516. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2517. printmsg(newpath);
  2518. goto nochange;
  2519. }
  2520. /* In case of successful archive extract, reload contents */
  2521. if (sel == SEL_EXTRACT) {
  2522. /* Continue in navigate-as-you-type mode, if enabled */
  2523. if (cfg.filtermode)
  2524. presel = FILTER;
  2525. /* Save current */
  2526. copycurname();
  2527. /* Repopulate as directory content may have changed */
  2528. goto begin;
  2529. }
  2530. break;
  2531. case SEL_DFB:
  2532. if (!dmanager) {
  2533. printmsg("set NNN_DE_FILE_MANAGER");
  2534. goto nochange;
  2535. }
  2536. spawn(dmanager, path, NULL, path, F_NOWAIT | F_NOTRACE);
  2537. break;
  2538. case SEL_FSIZE:
  2539. cfg.sizeorder ^= 1;
  2540. cfg.mtimeorder = 0;
  2541. cfg.apparentsz = 0;
  2542. cfg.blkorder = 0;
  2543. cfg.copymode = 0;
  2544. /* Save current */
  2545. if (ndents)
  2546. copycurname();
  2547. goto begin;
  2548. case SEL_ASIZE:
  2549. cfg.apparentsz ^= 1;
  2550. if (cfg.apparentsz) {
  2551. nftw_fn = &sum_sizes;
  2552. cfg.blkorder = 1;
  2553. BLK_SHIFT = 0;
  2554. } else
  2555. cfg.blkorder = 0; // fallthrough
  2556. case SEL_BSIZE:
  2557. if (sel == SEL_BSIZE) {
  2558. if (!cfg.apparentsz)
  2559. cfg.blkorder ^= 1;
  2560. nftw_fn = &sum_bsizes;
  2561. cfg.apparentsz = 0;
  2562. BLK_SHIFT = 9;
  2563. }
  2564. if (cfg.blkorder) {
  2565. cfg.showdetail = 1;
  2566. printptr = &printent_long;
  2567. }
  2568. cfg.mtimeorder = 0;
  2569. cfg.sizeorder = 0;
  2570. cfg.copymode = 0;
  2571. /* Save current */
  2572. if (ndents)
  2573. copycurname();
  2574. goto begin;
  2575. case SEL_MTIME:
  2576. cfg.mtimeorder ^= 1;
  2577. cfg.sizeorder = 0;
  2578. cfg.apparentsz = 0;
  2579. cfg.blkorder = 0;
  2580. cfg.copymode = 0;
  2581. /* Save current */
  2582. if (ndents)
  2583. copycurname();
  2584. goto begin;
  2585. case SEL_REDRAW:
  2586. /* Save current */
  2587. if (ndents)
  2588. copycurname();
  2589. goto begin;
  2590. case SEL_COPY:
  2591. if (!(cfg.noxdisplay || copier)) {
  2592. printmsg(messages[STR_COPY_ID]);
  2593. goto nochange;
  2594. }
  2595. if (!ndents)
  2596. goto nochange;
  2597. if (cfg.copymode) {
  2598. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2599. if (!appendfpath(newpath, r))
  2600. goto nochange;
  2601. ++ncp;
  2602. printmsg(newpath);
  2603. } else if (cfg.quote) {
  2604. g_buf[0] = '\'';
  2605. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2606. g_buf[r] = '\'';
  2607. g_buf[r + 1] = '\0';
  2608. if (cfg.noxdisplay)
  2609. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2610. else
  2611. spawn(copier, g_buf, NULL, NULL, F_NOTRACE);
  2612. g_buf[r] = '\0';
  2613. printmsg(g_buf + 1);
  2614. } else {
  2615. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2616. if (cfg.noxdisplay)
  2617. writecp(newpath, r - 1); /* Truncate NULL from end */
  2618. else
  2619. spawn(copier, newpath, NULL, NULL, F_NOTRACE);
  2620. printmsg(newpath);
  2621. }
  2622. goto nochange;
  2623. case SEL_COPYMUL:
  2624. if (!(cfg.noxdisplay || copier)) {
  2625. printmsg(messages[STR_COPY_ID]);
  2626. goto nochange;
  2627. }
  2628. if (!ndents)
  2629. goto nochange;
  2630. cfg.copymode ^= 1;
  2631. if (cfg.copymode) {
  2632. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2633. copystartid = cur;
  2634. copybufpos = 0;
  2635. ncp = 0;
  2636. printmsg("multi-copy on");
  2637. DPRINTF_S("copymode on");
  2638. goto nochange;
  2639. }
  2640. if (!ncp) { /* Handle range selection */
  2641. if (cur < copystartid) {
  2642. copyendid = copystartid;
  2643. copystartid = cur;
  2644. } else
  2645. copyendid = cur;
  2646. if (copystartid < copyendid) {
  2647. for (r = copystartid; r <= copyendid; ++r)
  2648. if (!appendfpath(newpath, mkpath(path, dents[r].name, newpath, PATH_MAX)))
  2649. goto nochange;
  2650. snprintf(newpath, PATH_MAX, "%d files copied", copyendid - copystartid + 1);
  2651. printmsg(newpath);
  2652. }
  2653. }
  2654. if (copybufpos) { /* File path(s) written to the buffer */
  2655. if (cfg.noxdisplay)
  2656. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2657. else
  2658. spawn(copier, pcopybuf, NULL, NULL, F_NOTRACE);
  2659. if (ncp) { /* Some files cherry picked */
  2660. snprintf(newpath, PATH_MAX, "%d files copied", ncp);
  2661. printmsg(newpath);
  2662. }
  2663. } else
  2664. printmsg("multi-copy off");
  2665. goto nochange;
  2666. case SEL_COPYLIST:
  2667. if (cfg.copymode)
  2668. showcplist();
  2669. else
  2670. printmsg("multi-copy off");
  2671. goto nochange;
  2672. case SEL_QUOTE:
  2673. cfg.quote ^= 1;
  2674. DPRINTF_D(cfg.quote);
  2675. if (cfg.quote)
  2676. printmsg("quotes on");
  2677. else
  2678. printmsg("quotes off");
  2679. goto nochange;
  2680. case SEL_OPEN: // fallthrough
  2681. case SEL_ARCHIVE:
  2682. if (!ndents)
  2683. break; // fallthrough
  2684. case SEL_NEW:
  2685. if (sel == SEL_OPEN)
  2686. tmp = xreadline(NULL, "open with: ");
  2687. else if (sel == SEL_ARCHIVE)
  2688. tmp = xreadline(dents[cur].name, "name: ");
  2689. else
  2690. tmp = xreadline(NULL, "name: ");
  2691. if (tmp == NULL || tmp[0] == '\0')
  2692. break;
  2693. /* Allow only relative, same dir paths */
  2694. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2695. printmsg(messages[STR_INPUT_ID]);
  2696. goto nochange;
  2697. }
  2698. if (sel == SEL_OPEN) {
  2699. printprompt("press 'c' for cli mode");
  2700. cleartimeout();
  2701. r = getch();
  2702. settimeout();
  2703. if (r == 'c')
  2704. r = F_NORMAL;
  2705. else
  2706. r = F_NOWAIT | F_NOTRACE;
  2707. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2708. spawn(tmp, newpath, NULL, path, r);
  2709. continue;
  2710. } else if (sel == SEL_ARCHIVE) {
  2711. /* newpath is used as temporary buffer */
  2712. if (!get_output(newpath, PATH_MAX, "which", utils[APACK], NULL, 0)) {
  2713. printmsg("apack missing");
  2714. continue;
  2715. }
  2716. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  2717. /* Continue in navigate-as-you-type mode, if enabled */
  2718. if (cfg.filtermode)
  2719. presel = FILTER;
  2720. /* Save current */
  2721. copycurname();
  2722. /* Repopulate as directory content may have changed */
  2723. goto begin;
  2724. }
  2725. /* Open the descriptor to currently open directory */
  2726. fd = open(path, O_RDONLY | O_DIRECTORY);
  2727. if (fd == -1) {
  2728. printwarn();
  2729. goto nochange;
  2730. }
  2731. /* Check if another file with same name exists */
  2732. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2733. printmsg("entry exists");
  2734. goto nochange;
  2735. }
  2736. /* Check if it's a dir or file */
  2737. printprompt("press 'f'(ile) or 'd'(ir)");
  2738. cleartimeout();
  2739. r = getch();
  2740. settimeout();
  2741. if (r == 'f') {
  2742. r = openat(fd, tmp, O_CREAT, 0666);
  2743. close(r);
  2744. } else if (r == 'd')
  2745. r = mkdirat(fd, tmp, 0777);
  2746. else {
  2747. close(fd);
  2748. break;
  2749. }
  2750. if (r == -1) {
  2751. printwarn();
  2752. close(fd);
  2753. goto nochange;
  2754. }
  2755. close(fd);
  2756. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2757. goto begin;
  2758. case SEL_RENAME:
  2759. if (!ndents)
  2760. break;
  2761. tmp = xreadline(dents[cur].name, "");
  2762. if (tmp == NULL || tmp[0] == '\0')
  2763. break;
  2764. /* Allow only relative, same dir paths */
  2765. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2766. printmsg(messages[STR_INPUT_ID]);
  2767. goto nochange;
  2768. }
  2769. /* Skip renaming to same name */
  2770. if (strcmp(tmp, dents[cur].name) == 0)
  2771. break;
  2772. /* Open the descriptor to currently open directory */
  2773. fd = open(path, O_RDONLY | O_DIRECTORY);
  2774. if (fd == -1) {
  2775. printwarn();
  2776. goto nochange;
  2777. }
  2778. /* Check if another file with same name exists */
  2779. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2780. /* File with the same name exists */
  2781. printprompt("press 'y' to overwrite");
  2782. cleartimeout();
  2783. r = getch();
  2784. settimeout();
  2785. if (r != 'y') {
  2786. close(fd);
  2787. break;
  2788. }
  2789. }
  2790. /* Rename the file */
  2791. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2792. printwarn();
  2793. close(fd);
  2794. goto nochange;
  2795. }
  2796. close(fd);
  2797. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2798. goto begin;
  2799. case SEL_RENAMEALL:
  2800. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2801. printmsg("vidir missing");
  2802. goto nochange;
  2803. }
  2804. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2805. /* Save current */
  2806. if (ndents)
  2807. copycurname();
  2808. goto begin;
  2809. case SEL_HELP:
  2810. show_help(path);
  2811. /* Continue in navigate-as-you-type mode, if enabled */
  2812. if (cfg.filtermode)
  2813. presel = FILTER;
  2814. break;
  2815. case SEL_RUN: // fallthrough
  2816. case SEL_RUNSCRIPT:
  2817. run = xgetenv(env, run);
  2818. if (sel == SEL_RUNSCRIPT) {
  2819. tmp = getenv("NNN_SCRIPT");
  2820. if (tmp) {
  2821. if (getenv("NNN_MULTISCRIPT")) {
  2822. size_t _len = xstrlcpy(newpath, tmp, PATH_MAX);
  2823. tmp = xreadline(NULL, "script suffix: ");
  2824. if (tmp && tmp[0])
  2825. xstrlcpy(newpath + _len - 1, tmp, PATH_MAX - _len);
  2826. tmp = newpath;
  2827. }
  2828. char *curfile = NULL;
  2829. if (ndents)
  2830. curfile = dents[cur].name;
  2831. spawn(run, tmp, curfile, path, F_NORMAL | F_SIGINT);
  2832. } else
  2833. printmsg("set NNN_SCRIPT");
  2834. } else {
  2835. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2836. /* Continue in navigate-as-you-type mode, if enabled */
  2837. if (cfg.filtermode)
  2838. presel = FILTER;
  2839. }
  2840. /* Save current */
  2841. if (ndents)
  2842. copycurname();
  2843. /* Repopulate as directory content may have changed */
  2844. goto begin;
  2845. case SEL_RUNARG:
  2846. run = xgetenv(env, run);
  2847. if ((!run || !run[0]) && (strcmp("VISUAL", env) == 0))
  2848. run = editor ? editor : xgetenv("EDITOR", "vi");
  2849. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2850. break;
  2851. case SEL_LOCK:
  2852. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2853. break;
  2854. case SEL_CDQUIT:
  2855. {
  2856. tmp = getenv("NNN_TMPFILE");
  2857. if (!tmp) {
  2858. printmsg("set NNN_TMPFILE");
  2859. goto nochange;
  2860. }
  2861. FILE *fp = fopen(tmp, "w");
  2862. if (fp) {
  2863. fprintf(fp, "cd \"%s\"", path);
  2864. fclose(fp);
  2865. }
  2866. /* Fall through to exit */
  2867. } // fallthrough
  2868. case SEL_QUIT:
  2869. dentfree(dents);
  2870. return;
  2871. } /* switch (sel) */
  2872. /* Screensaver */
  2873. if (idletimeout != 0 && idle == idletimeout) {
  2874. idle = 0;
  2875. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2876. }
  2877. }
  2878. }
  2879. static void
  2880. usage(void)
  2881. {
  2882. fprintf(stdout,
  2883. "usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n"
  2884. " [-p nlay] [-S] [-v] [-h] [PATH]\n\n"
  2885. "The missing terminal file manager for X.\n\n"
  2886. "positional args:\n"
  2887. " PATH start dir [default: current dir]\n\n"
  2888. "optional args:\n"
  2889. " -b key bookmark key to open\n"
  2890. " -c N dir color, disables if N>7\n"
  2891. " -e use exiftool instead of mediainfo\n"
  2892. " -i start in navigate-as-you-type mode\n"
  2893. " -l start in light mode\n"
  2894. " -p nlay path to custom nlay\n"
  2895. " -S start in disk usage analyser mode\n"
  2896. " -v show program version\n"
  2897. " -h show this help\n\n"
  2898. "Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2899. exit(0);
  2900. }
  2901. int
  2902. main(int argc, char *argv[])
  2903. {
  2904. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2905. char *ipath = NULL, *ifilter;
  2906. int opt;
  2907. /* Confirm we are in a terminal */
  2908. if (!isatty(0) || !isatty(1)) {
  2909. fprintf(stderr, "stdin or stdout is not a tty\n");
  2910. exit(1);
  2911. }
  2912. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2913. switch (opt) {
  2914. case 'S':
  2915. cfg.blkorder = 1;
  2916. nftw_fn = sum_bsizes;
  2917. break;
  2918. case 'l':
  2919. cfg.showdetail = 0;
  2920. printptr = &printent;
  2921. break;
  2922. case 'i':
  2923. cfg.filtermode = 1;
  2924. break;
  2925. case 'b':
  2926. ipath = optarg;
  2927. break;
  2928. case 'c':
  2929. if (atoi(optarg) > 7)
  2930. cfg.showcolor = 0;
  2931. else
  2932. cfg.color = (uchar)atoi(optarg);
  2933. break;
  2934. case 'e':
  2935. cfg.metaviewer = EXIFTOOL;
  2936. break;
  2937. case 'p':
  2938. player = optarg;
  2939. break;
  2940. case 'v':
  2941. fprintf(stdout, "%s\n", VERSION);
  2942. return 0;
  2943. case 'h': // fallthrough
  2944. default:
  2945. usage();
  2946. }
  2947. }
  2948. /* Parse bookmarks string */
  2949. parsebmstr();
  2950. if (ipath) { /* Open a bookmark directly */
  2951. if (get_bm_loc(ipath, cwd) == NULL) {
  2952. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2953. exit(1);
  2954. }
  2955. ipath = cwd;
  2956. } else if (argc == optind) {
  2957. /* Start in the current directory */
  2958. ipath = getcwd(cwd, PATH_MAX);
  2959. if (ipath == NULL)
  2960. ipath = "/";
  2961. } else {
  2962. ipath = realpath(argv[optind], cwd);
  2963. if (!ipath) {
  2964. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2965. exit(1);
  2966. }
  2967. }
  2968. /* Increase current open file descriptor limit */
  2969. open_max = max_openfds();
  2970. if (getuid() == 0 || getenv("NNN_SHOW_HIDDEN"))
  2971. cfg.showhidden = 1;
  2972. initfilter(cfg.showhidden, &ifilter);
  2973. #ifdef LINUX_INOTIFY
  2974. /* Initialize inotify */
  2975. inotify_fd = inotify_init1(IN_NONBLOCK);
  2976. if (inotify_fd < 0) {
  2977. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2978. exit(1);
  2979. }
  2980. #elif defined(BSD_KQUEUE)
  2981. kq = kqueue();
  2982. if (kq < 0) {
  2983. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2984. exit(1);
  2985. }
  2986. #endif
  2987. /* Edit text in EDITOR, if opted */
  2988. if (getenv("NNN_USE_EDITOR")) {
  2989. editor = xgetenv("VISUAL", NULL);
  2990. if (!editor)
  2991. editor = xgetenv("EDITOR", "vi");
  2992. }
  2993. /* Set player if not set already */
  2994. if (!player)
  2995. player = utils[NLAY];
  2996. /* Get the desktop file manager, if set */
  2997. dmanager = getenv("NNN_DE_FILE_MANAGER");
  2998. /* Get screensaver wait time, if set; copier used as tmp var */
  2999. copier = getenv("NNN_IDLE_TIMEOUT");
  3000. if (copier) {
  3001. opt = atoi(copier);
  3002. idletimeout = opt * ((opt > 0) - (opt < 0));
  3003. }
  3004. /* Get the default copier, if set */
  3005. copier = getenv("NNN_COPIER");
  3006. /* Enable quotes if opted */
  3007. if (getenv("NNN_QUOTE_ON"))
  3008. cfg.quote = 1;
  3009. if (getenv("HOME"))
  3010. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("HOME"), MAX_HOME_LEN);
  3011. else if (getenv("TMPDIR"))
  3012. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("TMPDIR"), MAX_HOME_LEN);
  3013. else if (xdiraccess("/tmp"))
  3014. g_tmpfplen = xstrlcpy(g_tmpfpath, "/tmp", MAX_HOME_LEN);
  3015. /* Check if X11 is available */
  3016. if (!copier && g_tmpfplen && getenv("NNN_NO_X")) {
  3017. cfg.noxdisplay = 1;
  3018. xstrlcpy(g_cppath, g_tmpfpath, MAX_HOME_LEN);
  3019. xstrlcpy(g_cppath + g_tmpfplen - 1, "/.nnncp", MAX_HOME_LEN - g_tmpfplen);
  3020. }
  3021. /* Disable auto-select if opted */
  3022. if (getenv("NNN_NO_AUTOSELECT"))
  3023. cfg.autoselect = 0;
  3024. signal(SIGINT, SIG_IGN);
  3025. /* Test initial path */
  3026. if (!xdiraccess(ipath)) {
  3027. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  3028. exit(1);
  3029. }
  3030. /* Set locale */
  3031. setlocale(LC_ALL, "");
  3032. crc8init();
  3033. #ifdef DEBUGMODE
  3034. enabledbg();
  3035. #endif
  3036. initcurses();
  3037. browse(ipath, ifilter);
  3038. exitcurses();
  3039. if (cfg.noxdisplay && g_cppath[0])
  3040. unlink(g_cppath);
  3041. #ifdef LINUX_INOTIFY
  3042. /* Shutdown inotify */
  3043. if (inotify_wd >= 0)
  3044. inotify_rm_watch(inotify_fd, inotify_wd);
  3045. close(inotify_fd);
  3046. #elif defined(BSD_KQUEUE)
  3047. if (event_fd >= 0)
  3048. close(event_fd);
  3049. close(kq);
  3050. #endif
  3051. #ifdef DEBUGMODE
  3052. disabledbg();
  3053. #endif
  3054. exit(0);
  3055. }