My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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