My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

4238 lines
94 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-2019, 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. #ifndef _GNU_SOURCE
  32. #define _GNU_SOURCE
  33. #endif
  34. #if defined(__arm__) || defined(__i386__)
  35. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
  36. #endif
  37. #include <sys/inotify.h>
  38. #define LINUX_INOTIFY
  39. #if !defined(__GLIBC__)
  40. #include <sys/types.h>
  41. #endif
  42. #endif
  43. #include <sys/resource.h>
  44. #include <sys/stat.h>
  45. #include <sys/statvfs.h>
  46. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  47. #include <sys/types.h>
  48. #include <sys/event.h>
  49. #include <sys/time.h>
  50. #define BSD_KQUEUE
  51. #else
  52. #include <sys/sysmacros.h>
  53. #endif
  54. #include <sys/wait.h>
  55. #include <ctype.h>
  56. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  57. #ifndef NCURSES_WIDECHAR
  58. #define NCURSES_WIDECHAR 1
  59. #endif
  60. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  61. #ifndef _XOPEN_SOURCE_EXTENDED
  62. #define _XOPEN_SOURCE_EXTENDED
  63. #endif
  64. #endif
  65. #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  66. #define __USE_XOPEN
  67. #endif
  68. #include <dirent.h>
  69. #include <errno.h>
  70. #include <fcntl.h>
  71. #include <grp.h>
  72. #include <libgen.h>
  73. #include <limits.h>
  74. #ifdef __gnu_hurd__
  75. #define PATH_MAX 4096
  76. #endif
  77. #include <locale.h>
  78. #include <pwd.h>
  79. #include <stdio.h>
  80. #include <readline/history.h>
  81. #include <readline/readline.h>
  82. #include <regex.h>
  83. #include <signal.h>
  84. #include <stdarg.h>
  85. #include <stdlib.h>
  86. #include <string.h>
  87. #include <strings.h>
  88. #include <time.h>
  89. #include <unistd.h>
  90. #ifndef __USE_XOPEN_EXTENDED
  91. #define __USE_XOPEN_EXTENDED 1
  92. #endif
  93. #include <ftw.h>
  94. #include <wchar.h>
  95. #ifndef S_BLKSIZE
  96. #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
  97. #endif
  98. #include "nnn.h"
  99. #ifdef DEBUGMODE
  100. static int DEBUG_FD;
  101. static int
  102. xprintf(int fd, const char *fmt, ...)
  103. {
  104. char buf[BUFSIZ];
  105. int r;
  106. va_list ap;
  107. va_start(ap, fmt);
  108. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  109. if (r > 0)
  110. r = write(fd, buf, r);
  111. va_end(ap);
  112. return r;
  113. }
  114. static int
  115. enabledbg()
  116. {
  117. FILE *fp = fopen("/tmp/nnn_debug", "w");
  118. if (!fp) {
  119. fprintf(stderr, "debug: open failed! (1)\n");
  120. fp = fopen("./nnn_debug", "w");
  121. if (!fp) {
  122. fprintf(stderr, "debug: open failed! (2)\n");
  123. return -1;
  124. }
  125. }
  126. DEBUG_FD = fileno(fp);
  127. if (DEBUG_FD == -1) {
  128. fprintf(stderr, "debug: open fd failed!\n");
  129. return -1;
  130. }
  131. return 0;
  132. }
  133. static void
  134. disabledbg()
  135. {
  136. close(DEBUG_FD);
  137. }
  138. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  139. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  140. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  141. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
  142. #else
  143. #define DPRINTF_D(x)
  144. #define DPRINTF_U(x)
  145. #define DPRINTF_S(x)
  146. #define DPRINTF_P(x)
  147. #endif /* DEBUGMODE */
  148. /* Macro definitions */
  149. #define VERSION "2.2"
  150. #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
  151. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  152. #undef MIN
  153. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  154. #define ISODD(x) ((x) & 1)
  155. #define TOUPPER(ch) \
  156. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  157. #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
  158. #define CURSR " > "
  159. #define EMPTY " "
  160. #define CURSYM(flag) ((flag) ? CURSR : EMPTY)
  161. #define FILTER '/'
  162. #define REGEX_MAX 128
  163. #define BM_MAX 10
  164. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  165. #define NAMEBUF_INCR 0x1000 /* 64 dir entries at once, avg. 64 chars per filename = 64*64B = 4KB */
  166. #define DESCRIPTOR_LEN 32
  167. #define _ALIGNMENT 0x10 /* 16-byte alignment */
  168. #define _ALIGNMENT_MASK 0xF
  169. #define DIR_OR_LINK_TO_DIR 0x1
  170. #define HOME_LEN_MAX 64
  171. #define CTX_MAX 4
  172. #define DOT_FILTER_LEN 7
  173. #define ASCII_MAX 128
  174. /* Macros to define process spawn behaviour as flags */
  175. #define F_NONE 0x00 /* no flag set */
  176. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  177. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  178. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  179. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  180. #define F_NORMAL 0x80 /* spawn child process in non-curses regular CLI mode */
  181. /* CRC8 macros */
  182. #define WIDTH (sizeof(unsigned char) << 3)
  183. #define TOPBIT (1 << (WIDTH - 1))
  184. #define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
  185. #define CRC8_TABLE_LEN 256
  186. /* Version compare macros */
  187. /* states: S_N: normal, S_I: comparing integral part, S_F: comparing
  188. fractionnal parts, S_Z: idem but with leading Zeroes only */
  189. #define S_N 0x0
  190. #define S_I 0x3
  191. #define S_F 0x6
  192. #define S_Z 0x9
  193. /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
  194. #define VCMP 2
  195. #define VLEN 3
  196. /* Volume info */
  197. #define FREE 0
  198. #define CAPACITY 1
  199. /* Function macros */
  200. #define exitcurses() endwin()
  201. #define clearprompt() printmsg("")
  202. #define printwarn() printmsg(strerror(errno))
  203. #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
  204. #define copycurname() xstrlcpy(lastname, dents[cur].name, NAME_MAX + 1)
  205. #define settimeout() timeout(1000)
  206. #define cleartimeout() timeout(-1)
  207. #define errexit() printerr(__LINE__)
  208. #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (dir_changed = TRUE))
  209. /* We don't care about the return value from strcmp() */
  210. #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
  211. /* A faster version of xisdigit */
  212. #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
  213. #ifdef LINUX_INOTIFY
  214. #define EVENT_SIZE (sizeof(struct inotify_event))
  215. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  216. #elif defined(BSD_KQUEUE)
  217. #define NUM_EVENT_SLOTS 1
  218. #define NUM_EVENT_FDS 1
  219. #endif
  220. /* TYPE DEFINITIONS */
  221. typedef unsigned long ulong;
  222. typedef unsigned int uint;
  223. typedef unsigned char uchar;
  224. typedef unsigned short ushort;
  225. /* STRUCTURES */
  226. /* Directory entry */
  227. typedef struct entry {
  228. char *name;
  229. time_t t;
  230. off_t size;
  231. blkcnt_t blocks; /* number of 512B blocks allocated */
  232. mode_t mode;
  233. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  234. uchar flags; /* Flags specific to the file */
  235. } __attribute__ ((packed, aligned(_ALIGNMENT))) *pEntry;
  236. /* Bookmark */
  237. typedef struct {
  238. int key;
  239. char *loc;
  240. } bm;
  241. /* Settings */
  242. typedef struct {
  243. uint filtermode : 1; /* Set to enter filter mode */
  244. uint mtimeorder : 1; /* Set to sort by time modified */
  245. uint sizeorder : 1; /* Set to sort by file size */
  246. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  247. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  248. uint showhidden : 1; /* Set to show hidden files */
  249. uint copymode : 1; /* Set when copying files */
  250. uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
  251. uint showdetail : 1; /* Clear to show fewer file info */
  252. uint showcolor : 1; /* Set to show dirs in blue */
  253. uint dircolor : 1; /* Current status of dir color */
  254. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  255. uint ctxactive : 1; /* Context active or not */
  256. uint reserved : 8;
  257. /* The following settings are global */
  258. uint curctx : 2; /* Current context number */
  259. uint picker : 1; /* Write selection to user-specified file */
  260. uint pickraw : 1; /* Write selection to sdtout before exit */
  261. uint nonavopen : 1; /* Open file on right arrow or `l` */
  262. uint useeditor : 1; /* Use VISUAL to open text files */
  263. uint runscript : 1; /* Choose script to run mode */
  264. uint runctx : 2; /* The context in which script is to be run */
  265. uint restrict0b : 1; /* Restrict 0-byte file opening */
  266. uint filter_re : 1; /* Use regex filters */
  267. } settings;
  268. /* Contexts or workspaces */
  269. typedef struct {
  270. char c_path[PATH_MAX]; /* Current dir */
  271. char c_init[PATH_MAX]; /* Initial dir */
  272. char c_last[PATH_MAX]; /* Last visited dir */
  273. char c_name[NAME_MAX + 1]; /* Current file name */
  274. settings c_cfg; /* Current configuration */
  275. uint color; /* Color code for directories */
  276. } context;
  277. /* GLOBALS */
  278. /* Configuration, contexts */
  279. static settings cfg = {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
  280. static context g_ctx[CTX_MAX] __attribute__ ((aligned));
  281. static struct entry *dents;
  282. static char *pnamebuf, *pcopybuf;
  283. static int ndents, cur, total_dents = ENTRY_INCR;
  284. static uint idle;
  285. static uint idletimeout, copybufpos, copybuflen;
  286. static char *opener;
  287. static char *copier;
  288. static char *editor;
  289. static char *pager, *pager_arg;
  290. static char *shell, *shell_arg;
  291. static char *scriptpath;
  292. static char *home;
  293. static blkcnt_t ent_blocks;
  294. static blkcnt_t dir_blocks;
  295. static ulong num_files;
  296. static uint open_max;
  297. static bm bookmark[BM_MAX];
  298. static size_t g_tmpfplen; /* path to tmp files for copy without X, keybind help and file stats */
  299. static uchar g_crc;
  300. static uchar BLK_SHIFT = 9;
  301. /* CRC data */
  302. static uchar crc8table[CRC8_TABLE_LEN] __attribute__ ((aligned));
  303. /* For use in functions which are isolated and don't return the buffer */
  304. static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
  305. /* Buffer for file path copy file */
  306. static char g_cppath[PATH_MAX] __attribute__ ((aligned));
  307. /* Buffer to store tmp file path */
  308. static char g_tmpfpath[HOME_LEN_MAX] __attribute__ ((aligned));
  309. #ifdef LINUX_INOTIFY
  310. static int inotify_fd, inotify_wd = -1;
  311. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  312. #elif defined(BSD_KQUEUE)
  313. static int kq, event_fd = -1;
  314. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  315. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  316. static struct timespec gtimeout;
  317. #endif
  318. /* Replace-str for xargs on different platforms */
  319. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  320. #define REPLACE_STR 'J'
  321. #elif defined(__linux__) || defined(__CYGWIN__)
  322. #define REPLACE_STR 'I'
  323. #else
  324. #define REPLACE_STR 'I'
  325. #endif
  326. /* Options to identify file mime */
  327. #ifdef __APPLE__
  328. #define FILE_OPTS "-bI"
  329. #else
  330. #define FILE_OPTS "-bi"
  331. #endif
  332. /* Macros for utilities */
  333. #define MEDIAINFO 0
  334. #define EXIFTOOL 1
  335. #define OPENER 2
  336. #define ATOOL 3
  337. #define APACK 4
  338. #define VIDIR 5
  339. #define LOCKER 6
  340. #define UNKNOWN 7
  341. /* Utilities to open files, run actions */
  342. static char * const utils[] = {
  343. "mediainfo",
  344. "exiftool",
  345. #ifdef __APPLE__
  346. "/usr/bin/open",
  347. #elif defined __CYGWIN__
  348. "cygstart",
  349. #else
  350. "xdg-open",
  351. #endif
  352. "atool",
  353. "apack",
  354. "vidir",
  355. #ifdef __APPLE__
  356. "bashlock",
  357. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  358. "lock",
  359. #else
  360. "vlock",
  361. #endif
  362. "UNKNOWN"
  363. };
  364. /* Common strings */
  365. #define STR_NFTWFAIL_ID 0
  366. #define STR_NOHOME_ID 1
  367. #define STR_INPUT_ID 2
  368. #define STR_INVBM_KEY 3
  369. #define STR_DATE_ID 4
  370. #define STR_UNSAFE 5
  371. #define STR_TMPFILE 6
  372. static const char * const messages[] = {
  373. "nftw failed",
  374. "HOME not set",
  375. "no traversal",
  376. "invalid key",
  377. "%F %T %z",
  378. "unsafe cmd",
  379. "/.nnnXXXXXX",
  380. };
  381. /* Supported config env vars */
  382. #define NNN_BMS 0
  383. #define NNN_OPENER 1
  384. #define NNN_CONTEXT_COLORS 2
  385. #define NNN_IDLE_TIMEOUT 3
  386. #define NNN_COPIER 4
  387. #define NNN_SCRIPT 5
  388. #define NNN_NOTE 6
  389. #define NNN_TMPFILE 7
  390. #define NNN_USE_EDITOR 8
  391. #define NNN_SHOW_HIDDEN 9
  392. #define NNN_NO_AUTOSELECT 10
  393. #define NNN_RESTRICT_NAV_OPEN 11
  394. #define NNN_RESTRICT_0B 12
  395. #define NNN_PLAIN_FILTER 13
  396. static const char * const env_cfg[] = {
  397. "NNN_BMS",
  398. "NNN_OPENER",
  399. "NNN_CONTEXT_COLORS",
  400. "NNN_IDLE_TIMEOUT",
  401. "NNN_COPIER",
  402. "NNN_SCRIPT",
  403. "NNN_NOTE",
  404. "NNN_TMPFILE",
  405. "NNN_USE_EDITOR",
  406. "NNN_SHOW_HIDDEN",
  407. "NNN_NO_AUTOSELECT",
  408. "NNN_RESTRICT_NAV_OPEN",
  409. "NNN_RESTRICT_0B",
  410. "NNN_PLAIN_FILTER",
  411. };
  412. /* Required env vars */
  413. #define SHELL 0
  414. #define SHLVL 1
  415. #define VISUAL 2
  416. #define EDITOR 3
  417. #define PAGER 4
  418. static const char * const envs[] = {
  419. "SHELL",
  420. "SHLVL",
  421. "VISUAL",
  422. "EDITOR",
  423. "PAGER",
  424. };
  425. /* Forward declarations */
  426. static void redraw(char *path);
  427. static void spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag);
  428. static int (*nftw_fn) (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  429. /* Functions */
  430. /*
  431. * CRC8 source:
  432. * https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
  433. */
  434. static void crc8init()
  435. {
  436. uchar remainder, bit;
  437. uint dividend;
  438. /* Compute the remainder of each possible dividend */
  439. for (dividend = 0; dividend < CRC8_TABLE_LEN; ++dividend) {
  440. /* Start with the dividend followed by zeros */
  441. remainder = dividend << (WIDTH - 8);
  442. /* Perform modulo-2 division, a bit at a time */
  443. for (bit = 8; bit > 0; --bit) {
  444. /* Try to divide the current data bit */
  445. if (remainder & TOPBIT)
  446. remainder = (remainder << 1) ^ POLYNOMIAL;
  447. else
  448. remainder = (remainder << 1);
  449. }
  450. /* Store the result into the table */
  451. crc8table[dividend] = remainder;
  452. }
  453. }
  454. static uchar crc8fast(uchar const message[], size_t n)
  455. {
  456. static uchar data, remainder;
  457. static size_t byte;
  458. /* Divide the message by the polynomial, a byte at a time */
  459. for (remainder = byte = 0; byte < n; ++byte) {
  460. data = message[byte] ^ (remainder >> (WIDTH - 8));
  461. remainder = crc8table[data] ^ (remainder << 8);
  462. }
  463. /* The final remainder is the CRC */
  464. return remainder;
  465. }
  466. /* Messages show up at the bottom */
  467. static void printmsg(const char *msg)
  468. {
  469. mvprintw(LINES - 1, 0, "%s\n", msg);
  470. }
  471. /* Kill curses and display error before exiting */
  472. static void printerr(int linenum)
  473. {
  474. exitcurses();
  475. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  476. if (!cfg.picker && g_cppath[0])
  477. unlink(g_cppath);
  478. free(pcopybuf);
  479. exit(1);
  480. }
  481. /* Print prompt on the last line */
  482. static void printprompt(const char *str)
  483. {
  484. clearprompt();
  485. printw(str);
  486. }
  487. static int get_input(const char *prompt)
  488. {
  489. if (prompt)
  490. printprompt(prompt);
  491. cleartimeout();
  492. int r = getch();
  493. settimeout();
  494. return r;
  495. }
  496. static char confirm_force()
  497. {
  498. int r = get_input("use force? [y/Y]");
  499. if (r == 'y' || r == 'Y')
  500. return 'f'; /* forceful */
  501. return 'i'; /* interactive */
  502. }
  503. /* Increase the limit on open file descriptors, if possible */
  504. static rlim_t max_openfds()
  505. {
  506. struct rlimit rl;
  507. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  508. if (limit != 0)
  509. return 32;
  510. limit = rl.rlim_cur;
  511. rl.rlim_cur = rl.rlim_max;
  512. /* Return ~75% of max possible */
  513. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  514. limit = rl.rlim_max - (rl.rlim_max >> 2);
  515. /*
  516. * 20K is arbitrary. If the limit is set to max possible
  517. * value, the memory usage increases to more than double.
  518. */
  519. return limit > 20480 ? 20480 : limit;
  520. }
  521. return limit;
  522. }
  523. /*
  524. * Wrapper to realloc()
  525. * Frees current memory if realloc() fails and returns NULL.
  526. *
  527. * As per the docs, the *alloc() family is supposed to be memory aligned:
  528. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  529. * macOS: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  530. */
  531. static void *xrealloc(void *pcur, size_t len)
  532. {
  533. static void *pmem;
  534. pmem = realloc(pcur, len);
  535. if (!pmem)
  536. free(pcur);
  537. return pmem;
  538. }
  539. /*
  540. * Just a safe strncpy(3)
  541. * Always null ('\0') terminates if both src and dest are valid pointers.
  542. * Returns the number of bytes copied including terminating null byte.
  543. */
  544. static size_t xstrlcpy(char *dest, const char *src, size_t n)
  545. {
  546. static ulong *s, *d;
  547. static size_t len, blocks;
  548. static const uint lsize = sizeof(ulong);
  549. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  550. if (!src || !dest || !n)
  551. return 0;
  552. len = strlen(src) + 1;
  553. if (n > len)
  554. n = len;
  555. else if (len > n)
  556. /* Save total number of bytes to copy in len */
  557. len = n;
  558. /*
  559. * To enable -O3 ensure src and dest are 16-byte aligned
  560. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  561. */
  562. if ((n >= lsize) && (((ulong)src & _ALIGNMENT_MASK) == 0 &&
  563. ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  564. s = (ulong *)src;
  565. d = (ulong *)dest;
  566. blocks = n >> _WSHIFT;
  567. n &= lsize - 1;
  568. while (blocks) {
  569. *d = *s;
  570. ++d, ++s;
  571. --blocks;
  572. }
  573. if (!n) {
  574. dest = (char *)d;
  575. *--dest = '\0';
  576. return len;
  577. }
  578. src = (char *)s;
  579. dest = (char *)d;
  580. }
  581. while (--n && (*dest = *src))
  582. ++dest, ++src;
  583. if (!n)
  584. *dest = '\0';
  585. return len;
  586. }
  587. /*
  588. * The poor man's implementation of memrchr(3).
  589. * We are only looking for '/' in this program.
  590. * And we are NOT expecting a '/' at the end.
  591. * Ideally 0 < n <= strlen(s).
  592. */
  593. static void *xmemrchr(uchar *s, uchar ch, size_t n)
  594. {
  595. static uchar *ptr;
  596. if (!s || !n)
  597. return NULL;
  598. ptr = s + n;
  599. do {
  600. --ptr;
  601. if (*ptr == ch)
  602. return ptr;
  603. } while (s != ptr);
  604. return NULL;
  605. }
  606. /*
  607. * The following dirname(3) implementation does not
  608. * modify the input. We use a copy of the original.
  609. *
  610. * Modified from the glibc (GNU LGPL) version.
  611. */
  612. static char *xdirname(const char *path)
  613. {
  614. static char * const buf = g_buf, *last_slash, *runp;
  615. xstrlcpy(buf, path, PATH_MAX);
  616. /* Find last '/'. */
  617. last_slash = xmemrchr((uchar *)buf, '/', strlen(buf));
  618. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  619. /* Determine whether all remaining characters are slashes. */
  620. for (runp = last_slash; runp != buf; --runp)
  621. if (runp[-1] != '/')
  622. break;
  623. /* The '/' is the last character, we have to look further. */
  624. if (runp != buf)
  625. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  626. }
  627. if (last_slash != NULL) {
  628. /* Determine whether all remaining characters are slashes. */
  629. for (runp = last_slash; runp != buf; --runp)
  630. if (runp[-1] != '/')
  631. break;
  632. /* Terminate the buffer. */
  633. if (runp == buf) {
  634. /* The last slash is the first character in the string.
  635. * We have to return "/". As a special case we have to
  636. * return "//" if there are exactly two slashes at the
  637. * beginning of the string. See XBD 4.10 Path Name
  638. * Resolution for more information.
  639. */
  640. if (last_slash == buf + 1)
  641. ++last_slash;
  642. else
  643. last_slash = buf + 1;
  644. } else
  645. last_slash = runp;
  646. last_slash[0] = '\0';
  647. } else {
  648. /* This assignment is ill-designed but the XPG specs require to
  649. * return a string containing "." in any case no directory part
  650. * is found and so a static and constant string is required.
  651. */
  652. buf[0] = '.';
  653. buf[1] = '\0';
  654. }
  655. return buf;
  656. }
  657. static char *xbasename(char *path)
  658. {
  659. static char *base;
  660. base = xmemrchr((uchar *)path, '/', strlen(path));
  661. return base ? base + 1 : path;
  662. }
  663. static uint xatoi(const char *str)
  664. {
  665. int val = 0;
  666. if (!str)
  667. return 0;
  668. while (xisdigit(*str))
  669. {
  670. val = val * 10 + (*str - '0');
  671. ++str;
  672. }
  673. return val;
  674. }
  675. /* Writes buflen char(s) from buf to a file */
  676. static void writecp(const char *buf, const size_t buflen)
  677. {
  678. static FILE *fp;
  679. if (cfg.pickraw)
  680. return;
  681. if (!g_cppath[0])
  682. return;
  683. fp = fopen(g_cppath, "w");
  684. if (fp) {
  685. fwrite(buf, 1, buflen, fp);
  686. fclose(fp);
  687. } else
  688. printwarn();
  689. }
  690. static bool appendfpath(const char *path, const size_t len)
  691. {
  692. if ((copybufpos >= copybuflen) || ((len + 3) > (copybuflen - copybufpos))) {
  693. copybuflen += PATH_MAX;
  694. pcopybuf = xrealloc(pcopybuf, copybuflen);
  695. if (!pcopybuf) {
  696. printmsg("no memory!");
  697. return FALSE;
  698. }
  699. }
  700. /* Enabling the following will miss files with newlines */
  701. /* if (copybufpos)
  702. pcopybuf[copybufpos - 1] = '\n'; */
  703. copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
  704. return TRUE;
  705. }
  706. /* Write selected file paths to fd, linefeed separated */
  707. static ssize_t selectiontofd(int fd)
  708. {
  709. uint lastpos = copybufpos - 1;
  710. char *pbuf = pcopybuf;
  711. ssize_t pos = 0, len, r;
  712. while (pos <= lastpos) {
  713. len = strlen(pbuf);
  714. pos += len;
  715. r = write(fd, pbuf, len);
  716. if (r != len)
  717. return pos;
  718. if (pos <= lastpos) {
  719. if (write(fd, "\n", 1) != 1)
  720. return pos;
  721. pbuf += len + 1;
  722. }
  723. ++pos;
  724. }
  725. return pos;
  726. }
  727. static bool showcplist()
  728. {
  729. int fd;
  730. ssize_t pos;
  731. if (!copybufpos)
  732. return FALSE;
  733. if (g_tmpfpath[0])
  734. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE],
  735. HOME_LEN_MAX - g_tmpfplen);
  736. else {
  737. printmsg(messages[STR_NOHOME_ID]);
  738. return -1;
  739. }
  740. fd = mkstemp(g_tmpfpath);
  741. if (fd == -1)
  742. return FALSE;
  743. pos = selectiontofd(fd);
  744. close(fd);
  745. if (pos && pos == copybufpos)
  746. spawn(pager, pager_arg, g_tmpfpath, NULL, F_NORMAL);
  747. unlink(g_tmpfpath);
  748. return TRUE;
  749. }
  750. static bool cpsafe()
  751. {
  752. /* Fail if copy file path not generated */
  753. if (!g_cppath[0]) {
  754. printmsg("copy file not found");
  755. return FALSE;
  756. }
  757. /* Warn if selection not completed */
  758. if (cfg.copymode) {
  759. printmsg("finish selection first");
  760. return FALSE;
  761. }
  762. /* Fail if copy file path isn't accessible */
  763. if (access(g_cppath, R_OK) == -1) {
  764. printmsg("empty selection list");
  765. return FALSE;
  766. }
  767. return TRUE;
  768. }
  769. /* Initialize curses mode */
  770. static bool initcurses(void)
  771. {
  772. if (cfg.picker) {
  773. if (!newterm(NULL, stderr, stdin)) {
  774. fprintf(stderr, "newterm!\n");
  775. return FALSE;
  776. }
  777. } else if (!initscr()) {
  778. char *term = getenv("TERM");
  779. if (term != NULL)
  780. fprintf(stderr, "error opening TERM: %s\n", term);
  781. else
  782. fprintf(stderr, "initscr!\n");
  783. return FALSE;
  784. }
  785. cbreak();
  786. noecho();
  787. nonl();
  788. intrflush(stdscr, FALSE);
  789. keypad(stdscr, TRUE);
  790. curs_set(FALSE); /* Hide cursor */
  791. start_color();
  792. use_default_colors();
  793. if (cfg.showcolor) {
  794. init_pair(1, g_ctx[0].color, -1);
  795. init_pair(2, g_ctx[1].color, -1);
  796. init_pair(3, g_ctx[2].color, -1);
  797. init_pair(4, g_ctx[3].color, -1);
  798. }
  799. settimeout(); /* One second */
  800. set_escdelay(25);
  801. return TRUE;
  802. }
  803. /*
  804. * Spawns a child process. Behaviour can be controlled using flag.
  805. * Limited to 2 arguments to a program, flag works on bit set.
  806. */
  807. static void spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
  808. {
  809. static const char *shlvl;
  810. static pid_t pid;
  811. static int status;
  812. /* Swap args if the first arg is NULL and second isn't */
  813. if (!arg1 && arg2) {
  814. shlvl = arg1;
  815. arg1 = arg2;
  816. arg2 = shlvl;
  817. }
  818. if (flag & F_NORMAL)
  819. exitcurses();
  820. pid = fork();
  821. if (pid == 0) {
  822. if (dir != NULL)
  823. status = chdir(dir);
  824. shlvl = getenv(envs[SHLVL]);
  825. /* Show a marker (to indicate nnn spawned shell) */
  826. if (flag & F_MARKER && shlvl != NULL) {
  827. fprintf(stdout, "\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  828. fprintf(stdout, "Next shell level: %d\n", xatoi(shlvl) + 1);
  829. }
  830. /* Suppress stdout and stderr */
  831. if (flag & F_NOTRACE) {
  832. int fd = open("/dev/null", O_WRONLY, 0200);
  833. dup2(fd, 1);
  834. dup2(fd, 2);
  835. close(fd);
  836. }
  837. if (flag & F_NOWAIT) {
  838. signal(SIGHUP, SIG_IGN);
  839. signal(SIGPIPE, SIG_IGN);
  840. setsid();
  841. }
  842. if (flag & F_SIGINT)
  843. signal(SIGINT, SIG_DFL);
  844. execlp(file, file, arg1, arg2, NULL);
  845. _exit(1);
  846. } else {
  847. if (!(flag & F_NOWAIT))
  848. /* Ignore interruptions */
  849. while (waitpid(pid, &status, 0) == -1)
  850. DPRINTF_D(status);
  851. DPRINTF_D(pid);
  852. if (flag & F_NORMAL)
  853. refresh();
  854. }
  855. }
  856. /*
  857. * Quotes argument and spawns a shell command
  858. * Uses g_buf
  859. */
  860. static bool quote_run_sh_cmd(const char *cmd, const char *arg, const char *path)
  861. {
  862. const char *ptr;
  863. size_t r;
  864. if (!cmd)
  865. return FALSE;
  866. r = xstrlcpy(g_buf, cmd, CMD_LEN_MAX);
  867. if (arg) {
  868. if (r >= CMD_LEN_MAX - 4) { /* space for at least 4 chars - space'c' */
  869. printmsg(messages[STR_UNSAFE]);
  870. return FALSE;
  871. }
  872. for (ptr = arg; *ptr; ++ptr)
  873. if (*ptr == '\'') {
  874. printmsg(messages[STR_UNSAFE]);
  875. return FALSE;
  876. }
  877. g_buf[r - 1] = ' ';
  878. g_buf[r] = '\'';
  879. r += xstrlcpy(g_buf + r + 1, arg, CMD_LEN_MAX - 1 - r);
  880. if (r >= CMD_LEN_MAX - 1) {
  881. printmsg(messages[STR_UNSAFE]);
  882. return FALSE;
  883. }
  884. g_buf[r] = '\'';
  885. g_buf[r + 1] = '\0';
  886. }
  887. DPRINTF_S(g_buf);
  888. spawn("sh", "-c", g_buf, path, F_NORMAL);
  889. return TRUE;
  890. }
  891. /* Get program name from env var, else return fallback program */
  892. static char *xgetenv(const char *name, char *fallback)
  893. {
  894. static char *value;
  895. if (name == NULL)
  896. return fallback;
  897. value = getenv(name);
  898. return value && value[0] ? value : fallback;
  899. }
  900. /*
  901. * Parse a string to get program and argument
  902. * NOTE: original string may be modified
  903. */
  904. static void getprogarg(char *prog, char **arg)
  905. {
  906. char *argptr;
  907. while (*prog && !isblank(*prog))
  908. ++prog;
  909. if (*prog) {
  910. *prog = '\0';
  911. *arg = ++prog;
  912. argptr = *arg;
  913. /* Make sure there are no more args */
  914. while (*argptr) {
  915. if (isblank(*argptr)) {
  916. fprintf(stderr, "Too many args [%s]\n", prog);
  917. exit(1);
  918. }
  919. ++argptr;
  920. }
  921. }
  922. }
  923. /* Check if a dir exists, IS a dir and is readable */
  924. static bool xdiraccess(const char *path)
  925. {
  926. static DIR *dirp;
  927. dirp = opendir(path);
  928. if (dirp == NULL) {
  929. printwarn();
  930. return FALSE;
  931. }
  932. closedir(dirp);
  933. return TRUE;
  934. }
  935. static int digit_compare(const char *a, const char *b)
  936. {
  937. while (*a && *b && *a == *b)
  938. ++a, ++b;
  939. return *a - *b;
  940. }
  941. /*
  942. * We assume none of the strings are NULL.
  943. *
  944. * Let's have the logic to sort numeric names in numeric order.
  945. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  946. *
  947. * If the absolute numeric values are same, we fallback to alphasort.
  948. */
  949. static int xstricmp(const char * const s1, const char * const s2)
  950. {
  951. static const char *c1, *c2, *m1, *m2;
  952. static int count1, count2, bias;
  953. static char sign[2];
  954. count1 = 0;
  955. count2 = 0;
  956. sign[0] = '+';
  957. sign[1] = '+';
  958. c1 = s1;
  959. while (isspace(*c1))
  960. ++c1;
  961. c2 = s2;
  962. while (isspace(*c2))
  963. ++c2;
  964. if (*c1 == '-' || *c1 == '+') {
  965. if (*c1 == '-')
  966. sign[0] = '-';
  967. ++c1;
  968. }
  969. if (*c2 == '-' || *c2 == '+') {
  970. if (*c2 == '-')
  971. sign[1] = '-';
  972. ++c2;
  973. }
  974. if (xisdigit(*c1) && xisdigit(*c2)) {
  975. while (*c1 == '0')
  976. ++c1;
  977. m1 = c1;
  978. while (*c2 == '0')
  979. ++c2;
  980. m2 = c2;
  981. while (xisdigit(*c1)) {
  982. ++count1;
  983. ++c1;
  984. }
  985. while (isspace(*c1))
  986. ++c1;
  987. while (xisdigit(*c2)) {
  988. ++count2;
  989. ++c2;
  990. }
  991. while (isspace(*c2))
  992. ++c2;
  993. if (*c1 && !*c2)
  994. return 1;
  995. if (!*c1 && *c2)
  996. return -1;
  997. if (!*c1 && !*c2) {
  998. if (sign[0] != sign[1])
  999. return ((sign[0] == '+') ? 1 : -1);
  1000. if (count1 > count2)
  1001. return 1;
  1002. if (count1 < count2)
  1003. return -1;
  1004. bias = digit_compare(m1, m2);
  1005. if (bias)
  1006. return bias;
  1007. }
  1008. }
  1009. return strcoll(s1, s2);
  1010. }
  1011. /*
  1012. * Version comparison
  1013. *
  1014. * The code for version compare is a modified version of the GLIBC
  1015. * and uClibc implementation of strverscmp(). The source is here:
  1016. * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
  1017. */
  1018. /*
  1019. * Compare S1 and S2 as strings holding indices/version numbers,
  1020. * returning less than, equal to or greater than zero if S1 is less than,
  1021. * equal to or greater than S2 (for more info, see the texinfo doc).
  1022. */
  1023. static int xstrverscmp(const char * const s1, const char * const s2)
  1024. {
  1025. static const uchar *p1;
  1026. static const uchar *p2;
  1027. static uchar c1, c2;
  1028. static int state, diff;
  1029. p1 = (const uchar *)s1;
  1030. p2 = (const uchar *)s2;
  1031. /* Symbol(s) 0 [1-9] others
  1032. Transition (10) 0 (01) d (00) x */
  1033. static const uint8_t next_state[] =
  1034. {
  1035. /* state x d 0 */
  1036. /* S_N */ S_N, S_I, S_Z,
  1037. /* S_I */ S_N, S_I, S_I,
  1038. /* S_F */ S_N, S_F, S_F,
  1039. /* S_Z */ S_N, S_F, S_Z
  1040. };
  1041. static const int8_t result_type[] =
  1042. {
  1043. /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
  1044. /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
  1045. /* S_I */ VCMP, -1, -1, +1, VLEN, VLEN, +1, VLEN, VLEN,
  1046. /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
  1047. /* S_Z */ VCMP, +1, +1, -1, VCMP, VCMP, -1, VCMP, VCMP
  1048. };
  1049. if (p1 == p2)
  1050. return 0;
  1051. c1 = *p1++;
  1052. c2 = *p2++;
  1053. /* Hint: '0' is a digit too. */
  1054. state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
  1055. while ((diff = c1 - c2) == 0) {
  1056. if (c1 == '\0')
  1057. return diff;
  1058. state = next_state[state];
  1059. c1 = *p1++;
  1060. c2 = *p2++;
  1061. state += (c1 == '0') + (xisdigit(c1) != 0);
  1062. }
  1063. state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))];
  1064. switch (state) {
  1065. case VCMP:
  1066. return diff;
  1067. case VLEN:
  1068. while (xisdigit (*p1++))
  1069. if (!xisdigit (*p2++))
  1070. return 1;
  1071. return xisdigit (*p2) ? -1 : diff;
  1072. default:
  1073. return state;
  1074. }
  1075. }
  1076. static int (*cmpfn)(const char * const s1, const char * const s2) = &xstricmp;
  1077. /* Return the integer value of a char representing HEX */
  1078. static char xchartohex(char c)
  1079. {
  1080. if (xisdigit(c))
  1081. return c - '0';
  1082. c = TOUPPER(c);
  1083. if (c >= 'A' && c <= 'F')
  1084. return c - 'A' + 10;
  1085. return c;
  1086. }
  1087. static int setfilter(regex_t *regex, char *filter)
  1088. {
  1089. static size_t len;
  1090. static int r;
  1091. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  1092. if (r != 0 && filter && filter[0] != '\0') {
  1093. len = COLS;
  1094. if (len > NAME_MAX)
  1095. len = NAME_MAX;
  1096. mvprintw(LINES - 1, 0, "regex error: %d\n", r);
  1097. }
  1098. return r;
  1099. }
  1100. static int visible_re(regex_t *regex, char *fname, char *fltr)
  1101. {
  1102. return regexec(regex, fname, 0, NULL, 0) == 0;
  1103. }
  1104. static int visible_str(regex_t *regex, char *fname, char *fltr)
  1105. {
  1106. return strcasestr(fname, fltr) != NULL;
  1107. }
  1108. static int (*filterfn)(regex_t *regex, char *fname, char *fltr) = &visible_re;
  1109. static int entrycmp(const void *va, const void *vb)
  1110. {
  1111. static pEntry pa, pb;
  1112. pa = (pEntry)va;
  1113. pb = (pEntry)vb;
  1114. if ((pb->flags & DIR_OR_LINK_TO_DIR) != (pa->flags & DIR_OR_LINK_TO_DIR)) {
  1115. if (pb->flags & DIR_OR_LINK_TO_DIR)
  1116. return 1;
  1117. return -1;
  1118. }
  1119. /* Do the actual sorting */
  1120. if (cfg.mtimeorder)
  1121. return pb->t - pa->t;
  1122. if (cfg.sizeorder) {
  1123. if (pb->size > pa->size)
  1124. return 1;
  1125. if (pb->size < pa->size)
  1126. return -1;
  1127. }
  1128. if (cfg.blkorder) {
  1129. if (pb->blocks > pa->blocks)
  1130. return 1;
  1131. if (pb->blocks < pa->blocks)
  1132. return -1;
  1133. }
  1134. return cmpfn(pa->name, pb->name);
  1135. }
  1136. /*
  1137. * Returns SEL_* if key is bound and 0 otherwise.
  1138. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  1139. * The next keyboard input can be simulated by presel.
  1140. */
  1141. static int nextsel(int *presel)
  1142. {
  1143. static int c;
  1144. static uint i;
  1145. static const uint len = LEN(bindings);
  1146. #ifdef LINUX_INOTIFY
  1147. static char inotify_buf[EVENT_BUF_LEN];
  1148. #elif defined(BSD_KQUEUE)
  1149. static struct kevent event_data[NUM_EVENT_SLOTS];
  1150. #endif
  1151. c = *presel;
  1152. if (c == 0) {
  1153. c = getch();
  1154. DPRINTF_D(c);
  1155. } else
  1156. *presel = 0;
  1157. if (c == -1) {
  1158. ++idle;
  1159. /*
  1160. * Do not check for directory changes in du mode.
  1161. * A redraw forces du calculation.
  1162. * Check for changes every odd second.
  1163. */
  1164. #ifdef LINUX_INOTIFY
  1165. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1
  1166. && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  1167. #elif defined(BSD_KQUEUE)
  1168. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  1169. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
  1170. event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  1171. #endif
  1172. c = CONTROL('L');
  1173. } else
  1174. idle = 0;
  1175. for (i = 0; i < len; ++i)
  1176. if (c == bindings[i].sym)
  1177. return bindings[i].act;
  1178. return 0;
  1179. }
  1180. /*
  1181. * Move non-matching entries to the end
  1182. */
  1183. static int fill(char* fltr, regex_t *re)
  1184. {
  1185. static int count;
  1186. static struct entry _dent, *pdent1, *pdent2;
  1187. for (count = 0; count < ndents; ++count) {
  1188. if (filterfn(re, dents[count].name, fltr) == 0) {
  1189. if (count != --ndents) {
  1190. pdent1 = &dents[count];
  1191. pdent2 = &dents[ndents];
  1192. *(&_dent) = *pdent1;
  1193. *pdent1 = *pdent2;
  1194. *pdent2 = *(&_dent);
  1195. --count;
  1196. }
  1197. continue;
  1198. }
  1199. }
  1200. return ndents;
  1201. }
  1202. static int matches(char *fltr)
  1203. {
  1204. static regex_t re;
  1205. /* Search filter */
  1206. if (cfg.filter_re && setfilter(&re, fltr) != 0)
  1207. return -1;
  1208. ndents = fill(fltr, &re);
  1209. if (cfg.filter_re)
  1210. regfree(&re);
  1211. if (!ndents)
  1212. return 0;
  1213. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1214. return 0;
  1215. }
  1216. static int filterentries(char *path)
  1217. {
  1218. static char ln[REGEX_MAX] __attribute__ ((aligned));
  1219. static wchar_t wln[REGEX_MAX] __attribute__ ((aligned));
  1220. static wint_t ch[2] = {0};
  1221. int r, total = ndents, oldcur = cur, len = 1;
  1222. char *pln = ln + 1;
  1223. ln[0] = wln[0] = FILTER;
  1224. ln[1] = wln[1] = '\0';
  1225. cur = 0;
  1226. cleartimeout();
  1227. curs_set(TRUE);
  1228. printprompt(ln);
  1229. while ((r = get_wch(ch)) != ERR) {
  1230. switch (*ch) {
  1231. case KEY_DC: // fallthrough
  1232. case KEY_BACKSPACE: // fallthrough
  1233. case '\b': // fallthrough
  1234. case CONTROL('L'): // fallthrough
  1235. case 127: /* handle DEL */
  1236. if (len == 1 && *ch != CONTROL('L')) {
  1237. cur = oldcur;
  1238. *ch = CONTROL('L');
  1239. goto end;
  1240. }
  1241. if (*ch == CONTROL('L'))
  1242. while (len > 1)
  1243. wln[--len] = '\0';
  1244. else
  1245. wln[--len] = '\0';
  1246. if (len == 1)
  1247. cur = oldcur;
  1248. wcstombs(ln, wln, REGEX_MAX);
  1249. ndents = total;
  1250. if (matches(pln) != -1)
  1251. redraw(path);
  1252. printprompt(ln);
  1253. continue;
  1254. case 27: /* Exit filter mode on Escape */
  1255. if (len == 1)
  1256. cur = oldcur;
  1257. *ch = CONTROL('L');
  1258. goto end;
  1259. }
  1260. if (r == OK) {
  1261. /* Handle all control chars in main loop */
  1262. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^') {
  1263. if (len == 1)
  1264. cur = oldcur;
  1265. goto end;
  1266. }
  1267. switch (*ch) {
  1268. case '\r': // with nonl(), this is ENTER key value
  1269. if (len == 1) {
  1270. cur = oldcur;
  1271. goto end;
  1272. }
  1273. if (matches(pln) == -1)
  1274. goto end;
  1275. redraw(path);
  1276. goto end;
  1277. case '?': // '?' is an invalid regex, show help instead
  1278. if (len == 1) {
  1279. cur = oldcur;
  1280. goto end;
  1281. } // fallthrough
  1282. default:
  1283. /* Reset cur in case it's a repeat search */
  1284. if (len == 1)
  1285. cur = 0;
  1286. if (len == REGEX_MAX - 1)
  1287. break;
  1288. wln[len] = (wchar_t)*ch;
  1289. wln[++len] = '\0';
  1290. wcstombs(ln, wln, REGEX_MAX);
  1291. /* Forward-filtering optimization:
  1292. * - new matches can only be a subset of current matches.
  1293. */
  1294. /* ndents = total; */
  1295. if (matches(pln) == -1)
  1296. continue;
  1297. /* If the only match is a dir, auto-select and cd into it */
  1298. if (ndents == 1 && cfg.filtermode
  1299. && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  1300. *ch = KEY_ENTER;
  1301. cur = 0;
  1302. goto end;
  1303. }
  1304. /*
  1305. * redraw() should be above the auto-select optimization, for
  1306. * the case where there's an issue with dir auto-select, say,
  1307. * due to a permission problem. The transition is _jumpy_ in
  1308. * case of such an error. However, we optimize for successful
  1309. * cases where the dir has permissions. This skips a redraw().
  1310. */
  1311. redraw(path);
  1312. printprompt(ln);
  1313. }
  1314. } else {
  1315. if (len == 1)
  1316. cur = oldcur;
  1317. goto end;
  1318. }
  1319. }
  1320. end:
  1321. curs_set(FALSE);
  1322. settimeout();
  1323. /* Return keys for navigation etc. */
  1324. return *ch;
  1325. }
  1326. /* Show a prompt with input string and return the changes */
  1327. static char *xreadline(char *prefill, char *prompt)
  1328. {
  1329. size_t len, pos;
  1330. int x, y, r;
  1331. wint_t ch[2] = {0};
  1332. static wchar_t * const buf = (wchar_t *)g_buf;
  1333. cleartimeout();
  1334. printprompt(prompt);
  1335. if (prefill) {
  1336. DPRINTF_S(prefill);
  1337. len = pos = mbstowcs(buf, prefill, NAME_MAX);
  1338. } else
  1339. len = (size_t)-1;
  1340. if (len == (size_t)-1) {
  1341. buf[0] = '\0';
  1342. len = pos = 0;
  1343. }
  1344. getyx(stdscr, y, x);
  1345. curs_set(TRUE);
  1346. while (1) {
  1347. buf[len] = ' ';
  1348. mvaddnwstr(y, x, buf, len + 1);
  1349. move(y, x + wcswidth(buf, pos));
  1350. r = get_wch(ch);
  1351. if (r != ERR) {
  1352. if (r == OK) {
  1353. switch (*ch) {
  1354. case KEY_ENTER: // fallthrough
  1355. case '\n': // fallthrough
  1356. case '\r':
  1357. goto END;
  1358. case 127: /* Handle DEL */ // fallthrough
  1359. case '\b': /* rhel25 sends '\b' for backspace */
  1360. if (pos > 0) {
  1361. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1362. --len, --pos;
  1363. } // fallthrough
  1364. case '\t': /* TAB breaks cursor position, ignore it */
  1365. continue;
  1366. case CONTROL('L'):
  1367. printprompt(prompt);
  1368. len = pos = 0;
  1369. continue;
  1370. case CONTROL('A'):
  1371. pos = 0;
  1372. continue;
  1373. case CONTROL('E'):
  1374. pos = len;
  1375. continue;
  1376. case CONTROL('U'):
  1377. printprompt(prompt);
  1378. memmove(buf, buf + pos, (len - pos) << 2);
  1379. len -= pos;
  1380. pos = 0;
  1381. continue;
  1382. case 27: /* Exit prompt on Escape */
  1383. len = 0;
  1384. goto END;
  1385. }
  1386. /* Filter out all other control chars */
  1387. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
  1388. continue;
  1389. if (pos < NAME_MAX - 1) {
  1390. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1391. buf[pos] = *ch;
  1392. ++len, ++pos;
  1393. continue;
  1394. }
  1395. } else {
  1396. switch (*ch) {
  1397. case KEY_LEFT:
  1398. if (pos > 0)
  1399. --pos;
  1400. break;
  1401. case KEY_RIGHT:
  1402. if (pos < len)
  1403. ++pos;
  1404. break;
  1405. case KEY_BACKSPACE:
  1406. if (pos > 0) {
  1407. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1408. --len, --pos;
  1409. }
  1410. break;
  1411. case KEY_DC:
  1412. if (pos < len) {
  1413. memmove(buf + pos, buf + pos + 1,
  1414. (len - pos - 1) << 2);
  1415. --len;
  1416. }
  1417. break;
  1418. default:
  1419. break;
  1420. }
  1421. }
  1422. }
  1423. }
  1424. END:
  1425. curs_set(FALSE);
  1426. settimeout();
  1427. clearprompt();
  1428. buf[len] = '\0';
  1429. wcstombs(g_buf + ((NAME_MAX + 1) << 2), buf, NAME_MAX);
  1430. return g_buf + ((NAME_MAX + 1) << 2);
  1431. }
  1432. /*
  1433. * Updates out with "dir/name or "/name"
  1434. * Returns the number of bytes copied including the terminating NULL byte
  1435. */
  1436. static size_t mkpath(char *dir, char *name, char *out)
  1437. {
  1438. static size_t len;
  1439. /* Handle absolute path */
  1440. if (name[0] == '/')
  1441. return xstrlcpy(out, name, PATH_MAX);
  1442. /* Handle root case */
  1443. if (istopdir(dir))
  1444. len = 1;
  1445. else
  1446. len = xstrlcpy(out, dir, PATH_MAX);
  1447. out[len - 1] = '/';
  1448. return (xstrlcpy(out + len, name, PATH_MAX - len) + len);
  1449. }
  1450. /*
  1451. * Create symbolic/hard link(s) to file(s) in selection list
  1452. * Returns the number of links created
  1453. */
  1454. static int xlink(char *suffix, char *path, char *buf, int type)
  1455. {
  1456. int count = 0;
  1457. char *pbuf = pcopybuf, *fname;
  1458. ssize_t pos = 0, len, r;
  1459. int (*link_fn)(const char *, const char *) = NULL;
  1460. /* Check if selection is empty */
  1461. if (!copybufpos)
  1462. return 0;
  1463. if (type == 's') /* symbolic link */
  1464. link_fn = &symlink;
  1465. else if (type == 'h') /* hard link */
  1466. link_fn = &link;
  1467. else
  1468. return -1;
  1469. while (pos < copybufpos) {
  1470. len = strlen(pbuf);
  1471. fname = xbasename(pbuf);
  1472. r = mkpath(path, fname, buf);
  1473. xstrlcpy(buf + r - 1, suffix, PATH_MAX - r - 1);
  1474. if (!link_fn(pbuf, buf))
  1475. ++count;
  1476. pos += len + 1;
  1477. pbuf += len + 1;
  1478. }
  1479. return count;
  1480. }
  1481. static bool parsebmstr()
  1482. {
  1483. int i = 0;
  1484. char *bms = getenv(env_cfg[NNN_BMS]);
  1485. char *nextkey = bms;
  1486. if (!bms || !*bms)
  1487. return TRUE;
  1488. while (*bms && i < BM_MAX) {
  1489. if (bms == nextkey) {
  1490. bookmark[i].key = *bms;
  1491. if (*++bms != ':')
  1492. return FALSE;
  1493. if (*++bms == '\0')
  1494. return FALSE;
  1495. bookmark[i].loc = bms;
  1496. ++i;
  1497. }
  1498. if (*bms == ';') {
  1499. *bms = '\0';
  1500. nextkey = bms + 1;
  1501. }
  1502. ++bms;
  1503. }
  1504. if (i < BM_MAX) {
  1505. if (*bookmark[i - 1].loc == '\0')
  1506. return FALSE;
  1507. bookmark[i].key = '\0';
  1508. }
  1509. return TRUE;
  1510. }
  1511. /*
  1512. * Get the real path to a bookmark
  1513. *
  1514. * NULL is returned in case of no match, path resolution failure etc.
  1515. * buf would be modified, so check return value before access
  1516. */
  1517. static char *get_bm_loc(int key, char *buf)
  1518. {
  1519. int r;
  1520. ssize_t count;
  1521. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1522. if (bookmark[r].key == key) {
  1523. if (bookmark[r].loc[0] == '~') {
  1524. if (!home) {
  1525. DPRINTF_S(messages[STR_NOHOME_ID]);
  1526. return NULL;
  1527. }
  1528. count = xstrlcpy(buf, home, PATH_MAX);
  1529. xstrlcpy(buf + count - 1, bookmark[r].loc + 1, PATH_MAX - count - 1);
  1530. } else
  1531. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1532. return buf;
  1533. }
  1534. }
  1535. DPRINTF_S("Invalid key");
  1536. return NULL;
  1537. }
  1538. static void resetdircolor(int flags)
  1539. {
  1540. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  1541. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  1542. cfg.dircolor = 0;
  1543. }
  1544. }
  1545. /*
  1546. * Replace escape characters in a string with '?'
  1547. * Adjust string length to maxcols if > 0;
  1548. *
  1549. * Interestingly, note that unescape() uses g_buf. What happens if
  1550. * str also points to g_buf? In this case we assume that the caller
  1551. * acknowledges that it's OK to lose the data in g_buf after this
  1552. * call to unescape().
  1553. * The API, on its part, first converts str to multibyte (after which
  1554. * it doesn't touch str anymore). Only after that it starts modifying
  1555. * g_buf. This is a phased operation.
  1556. */
  1557. static char *unescape(const char *str, uint maxcols)
  1558. {
  1559. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1560. static wchar_t *buf;
  1561. static size_t len;
  1562. /* Convert multi-byte to wide char */
  1563. len = mbstowcs(wbuf, str, PATH_MAX);
  1564. g_buf[0] = '\0';
  1565. buf = wbuf;
  1566. if (maxcols && len > maxcols) {
  1567. len = wcswidth(wbuf, len);
  1568. if (len > maxcols)
  1569. wbuf[maxcols] = 0;
  1570. }
  1571. while (*buf) {
  1572. if (*buf <= '\x1f' || *buf == '\x7f')
  1573. *buf = '\?';
  1574. ++buf;
  1575. }
  1576. /* Convert wide char to multi-byte */
  1577. wcstombs(g_buf, wbuf, PATH_MAX);
  1578. return g_buf;
  1579. }
  1580. static char *coolsize(off_t size)
  1581. {
  1582. static const char * const U = "BKMGTPEZY";
  1583. static char size_buf[12]; /* Buffer to hold human readable size */
  1584. static off_t rem;
  1585. static int i;
  1586. i = 0;
  1587. rem = 0;
  1588. while (size > 1024) {
  1589. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1590. size >>= 10;
  1591. ++i;
  1592. }
  1593. if (i == 1) {
  1594. rem = (rem * 1000) >> 10;
  1595. rem /= 10;
  1596. if (rem % 10 >= 5) {
  1597. rem = (rem / 10) + 1;
  1598. if (rem == 10) {
  1599. ++size;
  1600. rem = 0;
  1601. }
  1602. } else
  1603. rem /= 10;
  1604. } else if (i == 2) {
  1605. rem = (rem * 1000) >> 10;
  1606. if (rem % 10 >= 5) {
  1607. rem = (rem / 10) + 1;
  1608. if (rem == 100) {
  1609. ++size;
  1610. rem = 0;
  1611. }
  1612. } else
  1613. rem /= 10;
  1614. } else if (i > 0) {
  1615. rem = (rem * 10000) >> 10;
  1616. if (rem % 10 >= 5) {
  1617. rem = (rem / 10) + 1;
  1618. if (rem == 1000) {
  1619. ++size;
  1620. rem = 0;
  1621. }
  1622. } else
  1623. rem /= 10;
  1624. }
  1625. if (i > 0 && i < 6)
  1626. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1627. else
  1628. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1629. return size_buf;
  1630. }
  1631. static char *get_file_sym(mode_t mode)
  1632. {
  1633. static char ind[2] = "\0\0";
  1634. switch (mode & S_IFMT) {
  1635. case S_IFREG:
  1636. if (mode & 0100)
  1637. ind[0] = '*';
  1638. break;
  1639. case S_IFDIR:
  1640. ind[0] = '/';
  1641. break;
  1642. case S_IFLNK:
  1643. ind[0] = '@';
  1644. break;
  1645. case S_IFSOCK:
  1646. ind[0] = '=';
  1647. break;
  1648. case S_IFIFO:
  1649. ind[0] = '|';
  1650. break;
  1651. case S_IFBLK: // fallthrough
  1652. case S_IFCHR:
  1653. break;
  1654. default:
  1655. ind[0] = '?';
  1656. break;
  1657. }
  1658. return ind;
  1659. }
  1660. static void printent(struct entry *ent, int sel, uint namecols)
  1661. {
  1662. static char *pname;
  1663. pname = unescape(ent->name, namecols);
  1664. /* Directories are always shown on top */
  1665. resetdircolor(ent->flags);
  1666. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1667. }
  1668. static void printent_long(struct entry *ent, int sel, uint namecols)
  1669. {
  1670. static char buf[18], *pname;
  1671. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1672. pname = unescape(ent->name, namecols);
  1673. /* Directories are always shown on top */
  1674. resetdircolor(ent->flags);
  1675. if (sel)
  1676. attron(A_REVERSE);
  1677. switch (ent->mode & S_IFMT) {
  1678. case S_IFREG:
  1679. if (ent->mode & 0100)
  1680. printw(" %-16.16s %8.8s* %s*\n", buf,
  1681. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1682. else
  1683. printw(" %-16.16s %8.8s %s\n", buf,
  1684. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1685. break;
  1686. case S_IFDIR:
  1687. if (cfg.blkorder)
  1688. printw(" %-16.16s %8.8s/ %s/\n",
  1689. buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1690. else
  1691. printw(" %-16.16s / %s/\n", buf, pname);
  1692. break;
  1693. case S_IFLNK:
  1694. if (ent->flags & DIR_OR_LINK_TO_DIR)
  1695. printw(" %-16.16s @/ %s@\n", buf, pname);
  1696. else
  1697. printw(" %-16.16s @ %s@\n", buf, pname);
  1698. break;
  1699. case S_IFSOCK:
  1700. printw(" %-16.16s = %s=\n", buf, pname);
  1701. break;
  1702. case S_IFIFO:
  1703. printw(" %-16.16s | %s|\n", buf, pname);
  1704. break;
  1705. case S_IFBLK:
  1706. printw(" %-16.16s b %s\n", buf, pname);
  1707. break;
  1708. case S_IFCHR:
  1709. printw(" %-16.16s c %s\n", buf, pname);
  1710. break;
  1711. default:
  1712. printw(" %-16.16s %8.8s? %s?\n", buf,
  1713. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1714. break;
  1715. }
  1716. if (sel)
  1717. attroff(A_REVERSE);
  1718. }
  1719. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1720. static char get_fileind(mode_t mode, char *desc)
  1721. {
  1722. static char c;
  1723. switch (mode & S_IFMT) {
  1724. case S_IFREG:
  1725. c = '-';
  1726. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1727. if (mode & 0100)
  1728. /* Length of string "regular file" is 12 */
  1729. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12);
  1730. break;
  1731. case S_IFDIR:
  1732. c = 'd';
  1733. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1734. break;
  1735. case S_IFLNK:
  1736. c = 'l';
  1737. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1738. break;
  1739. case S_IFSOCK:
  1740. c = 's';
  1741. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1742. break;
  1743. case S_IFIFO:
  1744. c = 'p';
  1745. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1746. break;
  1747. case S_IFBLK:
  1748. c = 'b';
  1749. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1750. break;
  1751. case S_IFCHR:
  1752. c = 'c';
  1753. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1754. break;
  1755. default:
  1756. /* Unknown type -- possibly a regular file? */
  1757. c = '?';
  1758. desc[0] = '\0';
  1759. break;
  1760. }
  1761. return c;
  1762. }
  1763. /* Convert a mode field into "ls -l" type perms field. */
  1764. static char *get_lsperms(mode_t mode, char *desc)
  1765. {
  1766. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1767. static char bits[11] = {'\0'};
  1768. bits[0] = get_fileind(mode, desc);
  1769. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1770. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1771. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1772. if (mode & S_ISUID)
  1773. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1774. if (mode & S_ISGID)
  1775. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1776. if (mode & S_ISVTX)
  1777. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1778. return bits;
  1779. }
  1780. /*
  1781. * Gets only a single line (that's what we need
  1782. * for now) or shows full command output in pager.
  1783. *
  1784. * If page is valid, returns NULL
  1785. */
  1786. static char *get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, bool page)
  1787. {
  1788. pid_t pid;
  1789. int pipefd[2];
  1790. FILE *pf;
  1791. int tmp, flags;
  1792. char *ret = NULL;
  1793. if (pipe(pipefd) == -1)
  1794. errexit();
  1795. for (tmp = 0; tmp < 2; ++tmp) {
  1796. /* Get previous flags */
  1797. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1798. /* Set bit for non-blocking flag */
  1799. flags |= O_NONBLOCK;
  1800. /* Change flags on fd */
  1801. fcntl(pipefd[tmp], F_SETFL, flags);
  1802. }
  1803. pid = fork();
  1804. if (pid == 0) {
  1805. /* In child */
  1806. close(pipefd[0]);
  1807. dup2(pipefd[1], STDOUT_FILENO);
  1808. dup2(pipefd[1], STDERR_FILENO);
  1809. close(pipefd[1]);
  1810. execlp(file, file, arg1, arg2, NULL);
  1811. _exit(1);
  1812. }
  1813. /* In parent */
  1814. waitpid(pid, &tmp, 0);
  1815. close(pipefd[1]);
  1816. if (!page) {
  1817. pf = fdopen(pipefd[0], "r");
  1818. if (pf) {
  1819. ret = fgets(buf, bytes, pf);
  1820. close(pipefd[0]);
  1821. }
  1822. return ret;
  1823. }
  1824. pid = fork();
  1825. if (pid == 0) {
  1826. /* Show in pager in child */
  1827. dup2(pipefd[0], STDIN_FILENO);
  1828. close(pipefd[0]);
  1829. execlp(pager, pager, NULL);
  1830. _exit(1);
  1831. }
  1832. /* In parent */
  1833. waitpid(pid, &tmp, 0);
  1834. close(pipefd[0]);
  1835. return NULL;
  1836. }
  1837. static bool getutil(char *util) {
  1838. if (!get_output(g_buf, CMD_LEN_MAX, "which", util, NULL, FALSE))
  1839. return FALSE;
  1840. return TRUE;
  1841. }
  1842. static char *xgetpwuid(uid_t uid)
  1843. {
  1844. struct passwd *pwd = getpwuid(uid);
  1845. if (!pwd)
  1846. return utils[UNKNOWN];
  1847. return pwd->pw_name;
  1848. }
  1849. static char *xgetgrgid(gid_t gid)
  1850. {
  1851. struct group *grp = getgrgid(gid);
  1852. if (!grp)
  1853. return utils[UNKNOWN];
  1854. return grp->gr_name;
  1855. }
  1856. /*
  1857. * Follows the stat(1) output closely
  1858. */
  1859. static bool show_stats(char *fpath, char *fname, struct stat *sb)
  1860. {
  1861. char desc[DESCRIPTOR_LEN];
  1862. char *perms = get_lsperms(sb->st_mode, desc);
  1863. char *p, *begin = g_buf;
  1864. if (g_tmpfpath[0])
  1865. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE],
  1866. HOME_LEN_MAX - g_tmpfplen);
  1867. else {
  1868. printmsg(messages[STR_NOHOME_ID]);
  1869. return FALSE;
  1870. }
  1871. int fd = mkstemp(g_tmpfpath);
  1872. if (fd == -1)
  1873. return FALSE;
  1874. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1875. /* Show file name or 'symlink' -> 'target' */
  1876. if (perms[0] == 'l') {
  1877. /* Note that CMD_LEN_MAX > PATH_MAX */
  1878. ssize_t len = readlink(fpath, g_buf, CMD_LEN_MAX);
  1879. if (len != -1) {
  1880. struct stat tgtsb;
  1881. if (!stat(fpath, &tgtsb) && S_ISDIR(tgtsb.st_mode))
  1882. g_buf[len++] = '/';
  1883. g_buf[len] = '\0';
  1884. /*
  1885. * We pass g_buf but unescape() operates on g_buf too!
  1886. * Read the API notes for information on how this works.
  1887. */
  1888. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1889. }
  1890. }
  1891. /* Show size, blocks, file type */
  1892. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1893. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1894. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1895. #else
  1896. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1897. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1898. #endif
  1899. /* Show containing device, inode, hardlink count */
  1900. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1901. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1902. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1903. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1904. #else
  1905. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1906. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1907. #endif
  1908. /* Show major, minor number for block or char device */
  1909. if (perms[0] == 'b' || perms[0] == 'c')
  1910. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1911. /* Show permissions, owner, group */
  1912. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1913. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1914. sb->st_mode & 7, perms, sb->st_uid, xgetpwuid(sb->st_uid),
  1915. sb->st_gid, xgetgrgid(sb->st_gid));
  1916. /* Show last access time */
  1917. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1918. dprintf(fd, "\n\n Access: %s", g_buf);
  1919. /* Show last modification time */
  1920. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1921. dprintf(fd, "\n Modify: %s", g_buf);
  1922. /* Show last status change time */
  1923. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1924. dprintf(fd, "\n Change: %s", g_buf);
  1925. if (S_ISREG(sb->st_mode)) {
  1926. /* Show file(1) output */
  1927. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  1928. if (p) {
  1929. dprintf(fd, "\n\n ");
  1930. while (*p) {
  1931. if (*p == ',') {
  1932. *p = '\0';
  1933. dprintf(fd, " %s\n", begin);
  1934. begin = p + 1;
  1935. }
  1936. ++p;
  1937. }
  1938. dprintf(fd, " %s", begin);
  1939. }
  1940. dprintf(fd, "\n\n");
  1941. } else
  1942. dprintf(fd, "\n\n\n");
  1943. close(fd);
  1944. spawn(pager, pager_arg, g_tmpfpath, NULL, F_NORMAL);
  1945. unlink(g_tmpfpath);
  1946. return TRUE;
  1947. }
  1948. static size_t get_fs_info(const char *path, bool type)
  1949. {
  1950. static struct statvfs svb;
  1951. if (statvfs(path, &svb) == -1)
  1952. return 0;
  1953. if (type == CAPACITY)
  1954. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1955. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1956. }
  1957. static bool show_mediainfo(char *fpath, char *arg)
  1958. {
  1959. if (!getutil(utils[cfg.metaviewer]))
  1960. return FALSE;
  1961. exitcurses();
  1962. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, TRUE);
  1963. refresh();
  1964. return TRUE;
  1965. }
  1966. static bool handle_archive(char *fpath, char *arg, char *dir)
  1967. {
  1968. if (!getutil(utils[ATOOL]))
  1969. return FALSE;
  1970. if (arg[1] == 'x')
  1971. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1972. else {
  1973. exitcurses();
  1974. get_output(NULL, 0, utils[ATOOL], arg, fpath, TRUE);
  1975. refresh();
  1976. }
  1977. return TRUE;
  1978. }
  1979. /*
  1980. * The help string tokens (each line) start with a HEX value
  1981. * which indicates the number of spaces to print before the
  1982. * particular token. This method was chosen instead of a flat
  1983. * string because the number of bytes in help was increasing
  1984. * the binary size by around a hundred bytes. This would only
  1985. * have increased as we keep adding new options.
  1986. */
  1987. static bool show_help(char *path)
  1988. {
  1989. int i = 0, fd;
  1990. char *start, *end;
  1991. if (g_tmpfpath[0])
  1992. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE],
  1993. HOME_LEN_MAX - g_tmpfplen);
  1994. else {
  1995. printmsg(messages[STR_NOHOME_ID]);
  1996. return FALSE;
  1997. }
  1998. fd = mkstemp(g_tmpfpath);
  1999. static char helpstr[] = {
  2000. "0\n"
  2001. "1NAVIGATION\n"
  2002. "a↑ k Up PgUp ^U Scroll up\n"
  2003. "a↓ j Down PgDn ^D Scroll down\n"
  2004. "a← h Parent dir ~ Go HOME\n"
  2005. "8↵ → l Open file/dir & Start dir\n"
  2006. "4Home g ^A First entry - Last visited dir\n"
  2007. "5End G ^E Last entry . Toggle show hidden\n"
  2008. "c/ Filter Ins ^T Toggle nav-as-you-type\n"
  2009. "cb Pin current dir ^B Go to pinned dir\n"
  2010. "7Tab ^I Next context d Toggle detail view\n"
  2011. "9, ^/ Leader key N LeadN Go to/create context N\n"
  2012. "aEsc Exit prompt ^L Redraw/clear prompt\n"
  2013. "b^G Quit and cd q Quit context\n"
  2014. "9Q ^Q Quit ? Help, config\n"
  2015. "1FILES\n"
  2016. "b^O Open with... n Create new/link\n"
  2017. "cD File details ^R Rename entry\n"
  2018. "9⎵ ^K Copy entry path r Open dir in vidir\n"
  2019. "b^Y Toggle selection y List selection\n"
  2020. "cY Select all\n"
  2021. "cP Copy selection X Delete selection\n"
  2022. "cV Move selection ^X Delete entry\n"
  2023. "cf Archive files m M Brief/full media info\n"
  2024. "b^F Extract archive F List archive\n"
  2025. "ce Edit in EDITOR p Open in PAGER\n"
  2026. "1ORDER TOGGLES\n"
  2027. "b^J Disk usage S Apparent du\n"
  2028. "ct Time modified s Size\n"
  2029. "1MISC\n"
  2030. "9! ^] Spawn SHELL C Execute entry\n"
  2031. "9R ^V Run/pick script L Lock terminal\n"
  2032. "b^P Command prompt ^N Take note\n"};
  2033. if (fd == -1)
  2034. return FALSE;
  2035. start = end = helpstr;
  2036. while (*end) {
  2037. if (*end == '\n') {
  2038. dprintf(fd, "%*c%.*s",
  2039. xchartohex(*start), ' ', (int)(end - start), start + 1);
  2040. start = end + 1;
  2041. }
  2042. ++end;
  2043. }
  2044. dprintf(fd, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  2045. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  2046. if (bookmark[0].loc) {
  2047. dprintf(fd, "BOOKMARKS\n");
  2048. for (; i < BM_MAX; ++i)
  2049. if (bookmark[i].key)
  2050. dprintf(fd, " %c: %s\n", (char)bookmark[i].key, bookmark[i].loc);
  2051. else
  2052. break;
  2053. dprintf(fd, "\n");
  2054. }
  2055. for (i = NNN_OPENER; i <= NNN_PLAIN_FILTER; ++i) {
  2056. start = getenv(env_cfg[i]);
  2057. if (start) {
  2058. if (i < NNN_USE_EDITOR)
  2059. dprintf(fd, "%s: %s\n", env_cfg[i], start);
  2060. else
  2061. dprintf(fd, "%s: 1\n", env_cfg[i]);
  2062. }
  2063. }
  2064. if (g_cppath[0])
  2065. dprintf(fd, "COPY FILE: %s\n", g_cppath);
  2066. dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  2067. close(fd);
  2068. spawn(pager, pager_arg, g_tmpfpath, NULL, F_NORMAL);
  2069. unlink(g_tmpfpath);
  2070. return TRUE;
  2071. }
  2072. static int sum_bsizes(const char *fpath, const struct stat *sb,
  2073. int typeflag, struct FTW *ftwbuf)
  2074. {
  2075. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  2076. ent_blocks += sb->st_blocks;
  2077. ++num_files;
  2078. return 0;
  2079. }
  2080. static int sum_sizes(const char *fpath, const struct stat *sb,
  2081. int typeflag, struct FTW *ftwbuf)
  2082. {
  2083. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  2084. ent_blocks += sb->st_size;
  2085. ++num_files;
  2086. return 0;
  2087. }
  2088. static void dentfree(struct entry *dents)
  2089. {
  2090. free(pnamebuf);
  2091. free(dents);
  2092. }
  2093. static int dentfill(char *path, struct entry **dents)
  2094. {
  2095. static DIR *dirp;
  2096. static struct dirent *dp;
  2097. static char *namep, *pnb;
  2098. static struct entry *dentp;
  2099. static size_t off, namebuflen = NAMEBUF_INCR;
  2100. static ulong num_saved;
  2101. static int fd, n, count;
  2102. static struct stat sb_path, sb;
  2103. off = 0;
  2104. dirp = opendir(path);
  2105. if (dirp == NULL)
  2106. return 0;
  2107. fd = dirfd(dirp);
  2108. n = 0;
  2109. if (cfg.blkorder) {
  2110. num_files = 0;
  2111. dir_blocks = 0;
  2112. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  2113. printwarn();
  2114. return 0;
  2115. }
  2116. }
  2117. while ((dp = readdir(dirp)) != NULL) {
  2118. namep = dp->d_name;
  2119. /* Skip self and parent */
  2120. if ((namep[0] == '.' && (namep[1] == '\0' ||
  2121. (namep[1] == '.' && namep[2] == '\0'))))
  2122. continue;
  2123. if (!cfg.showhidden && namep[0] == '.') {
  2124. if (!cfg.blkorder)
  2125. continue;
  2126. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  2127. continue;
  2128. if (S_ISDIR(sb.st_mode)) {
  2129. if (sb_path.st_dev == sb.st_dev) {
  2130. ent_blocks = 0;
  2131. mkpath(path, namep, g_buf);
  2132. if (nftw(g_buf, nftw_fn, open_max,
  2133. FTW_MOUNT | FTW_PHYS) == -1) {
  2134. printmsg(messages[STR_NFTWFAIL_ID]);
  2135. dir_blocks += (cfg.apparentsz
  2136. ? sb.st_size
  2137. : sb.st_blocks);
  2138. } else
  2139. dir_blocks += ent_blocks;
  2140. }
  2141. } else {
  2142. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2143. ++num_files;
  2144. }
  2145. continue;
  2146. }
  2147. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  2148. DPRINTF_S(namep);
  2149. continue;
  2150. }
  2151. if (n == total_dents) {
  2152. total_dents += ENTRY_INCR;
  2153. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  2154. if (*dents == NULL) {
  2155. free(pnamebuf);
  2156. errexit();
  2157. }
  2158. DPRINTF_P(*dents);
  2159. }
  2160. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  2161. if (namebuflen - off < NAME_MAX + 1) {
  2162. namebuflen += NAMEBUF_INCR;
  2163. pnb = pnamebuf;
  2164. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  2165. if (pnamebuf == NULL) {
  2166. free(*dents);
  2167. errexit();
  2168. }
  2169. DPRINTF_P(pnamebuf);
  2170. /* realloc() may result in memory move, we must re-adjust if that happens */
  2171. if (pnb != pnamebuf) {
  2172. dentp = *dents;
  2173. dentp->name = pnamebuf;
  2174. for (count = 1; count < n; ++dentp, ++count)
  2175. /* Current filename starts at last filename start + length */
  2176. (dentp + 1)->name = (char *)((size_t)dentp->name
  2177. + dentp->nlen);
  2178. }
  2179. }
  2180. dentp = *dents + n;
  2181. /* Copy file name */
  2182. dentp->name = (char *)((size_t)pnamebuf + off);
  2183. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  2184. off += dentp->nlen;
  2185. /* Copy other fields */
  2186. dentp->mode = sb.st_mode;
  2187. dentp->t = sb.st_mtime;
  2188. dentp->size = sb.st_size;
  2189. if (cfg.blkorder) {
  2190. if (S_ISDIR(sb.st_mode)) {
  2191. ent_blocks = 0;
  2192. num_saved = num_files + 1;
  2193. mkpath(path, namep, g_buf);
  2194. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  2195. printmsg(messages[STR_NFTWFAIL_ID]);
  2196. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2197. } else
  2198. dentp->blocks = ent_blocks;
  2199. if (sb_path.st_dev == sb.st_dev)
  2200. dir_blocks += dentp->blocks;
  2201. else
  2202. num_files = num_saved;
  2203. } else {
  2204. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2205. dir_blocks += dentp->blocks;
  2206. ++num_files;
  2207. }
  2208. }
  2209. /* Flag if this is a dir or symlink to a dir */
  2210. if (S_ISDIR(sb.st_mode))
  2211. dentp->flags |= DIR_OR_LINK_TO_DIR;
  2212. else if (!S_ISLNK(sb.st_mode)) {
  2213. if (dentp->flags & DIR_OR_LINK_TO_DIR)
  2214. dentp->flags &= ~DIR_OR_LINK_TO_DIR;
  2215. } else {
  2216. if (!fstatat(fd, namep, &sb, 0)) {
  2217. if (S_ISDIR(sb.st_mode))
  2218. dentp->flags |= DIR_OR_LINK_TO_DIR;
  2219. else
  2220. dentp->flags &= ~DIR_OR_LINK_TO_DIR;
  2221. }
  2222. }
  2223. ++n;
  2224. }
  2225. /* Should never be null */
  2226. if (closedir(dirp) == -1) {
  2227. dentfree(*dents);
  2228. errexit();
  2229. }
  2230. return n;
  2231. }
  2232. /*
  2233. * Return the position of the matching entry or 0 otherwise
  2234. * Note there's no NULL check for fname
  2235. */
  2236. static int dentfind(const char *fname, int n)
  2237. {
  2238. static int i;
  2239. DPRINTF_S(fname);
  2240. for (i = 0; i < n; ++i)
  2241. if (xstrcmp(fname, dents[i].name) == 0)
  2242. return i;
  2243. return 0;
  2244. }
  2245. static void populate(char *path, char *lastname)
  2246. {
  2247. if (cfg.blkorder) {
  2248. printmsg("calculating...");
  2249. refresh();
  2250. }
  2251. #ifdef DEBUGMODE
  2252. struct timespec ts1, ts2;
  2253. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  2254. #endif
  2255. ndents = dentfill(path, &dents);
  2256. if (!ndents)
  2257. return;
  2258. qsort(dents, ndents, sizeof(*dents), entrycmp);
  2259. #ifdef DEBUGMODE
  2260. clock_gettime(CLOCK_REALTIME, &ts2);
  2261. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  2262. #endif
  2263. /* Find cur from history */
  2264. /* No NULL check for lastname, always points to an array */
  2265. if (!*lastname)
  2266. cur = 0;
  2267. else
  2268. cur = dentfind(lastname, ndents);
  2269. }
  2270. static void redraw(char *path)
  2271. {
  2272. static char c;
  2273. static char buf[12];
  2274. static size_t ncols;
  2275. static int nlines, i, attrs;
  2276. static bool mode_changed;
  2277. mode_changed = FALSE;
  2278. nlines = MIN(LINES - 4, ndents);
  2279. /* Clear screen */
  2280. erase();
  2281. #ifdef DIR_LIMITED_COPY
  2282. if (cfg.copymode)
  2283. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  2284. cfg.copymode = 0;
  2285. DPRINTF_S("selection off");
  2286. }
  2287. #endif
  2288. /* Fail redraw if < than 11 columns, context info prints 10 chars */
  2289. if (COLS < 11) {
  2290. printmsg("too few columns!");
  2291. return;
  2292. }
  2293. /* Strip trailing slashes */
  2294. for (i = strlen(path) - 1; i > 0; --i)
  2295. if (path[i] == '/')
  2296. path[i] = '\0';
  2297. else
  2298. break;
  2299. DPRINTF_D(cur);
  2300. DPRINTF_S(path);
  2301. if (!realpath(path, g_buf)) {
  2302. printwarn();
  2303. return;
  2304. }
  2305. ncols = COLS;
  2306. if (ncols > PATH_MAX)
  2307. ncols = PATH_MAX;
  2308. printw("[");
  2309. for (i = 0; i < CTX_MAX; ++i) {
  2310. if (!g_ctx[i].c_cfg.ctxactive)
  2311. printw("%d ", i + 1);
  2312. else if (cfg.curctx != i) {
  2313. if (cfg.showcolor)
  2314. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_UNDERLINE;
  2315. else
  2316. attrs = A_UNDERLINE;
  2317. attron(attrs);
  2318. printw("%d", i + 1);
  2319. attroff(attrs);
  2320. printw(" ");
  2321. } else {
  2322. /* Print current context in reverse */
  2323. if (cfg.showcolor)
  2324. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_REVERSE;
  2325. else
  2326. attrs = A_REVERSE;
  2327. attron(attrs);
  2328. printw("%d", i + 1);
  2329. attroff(attrs);
  2330. printw(" ");
  2331. }
  2332. }
  2333. printw("\b] "); /* 10 chars printed in total for contexts - "[1 2 3 4] " */
  2334. attron(A_UNDERLINE);
  2335. /* No text wrapping in cwd line */
  2336. g_buf[ncols - 11] = '\0';
  2337. printw("%s\n\n", g_buf);
  2338. attroff(A_UNDERLINE);
  2339. /* Fallback to light mode if less than 35 columns */
  2340. if (ncols < 35 && cfg.showdetail) {
  2341. cfg.showdetail ^= 1;
  2342. printptr = &printent;
  2343. mode_changed = TRUE;
  2344. }
  2345. /* Calculate the number of cols available to print entry name */
  2346. if (cfg.showdetail)
  2347. ncols -= 32;
  2348. else
  2349. ncols -= 5;
  2350. if (cfg.showcolor) {
  2351. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2352. cfg.dircolor = 1;
  2353. }
  2354. /* Print listing */
  2355. if (cur < (nlines >> 1)) {
  2356. for (i = 0; i < nlines; ++i)
  2357. printptr(&dents[i], i == cur, ncols);
  2358. } else if (cur >= ndents - (nlines >> 1)) {
  2359. for (i = ndents - nlines; i < ndents; ++i)
  2360. printptr(&dents[i], i == cur, ncols);
  2361. } else {
  2362. static int odd;
  2363. odd = ISODD(nlines);
  2364. nlines >>= 1;
  2365. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  2366. printptr(&dents[i], i == cur, ncols);
  2367. }
  2368. /* Must reset e.g. no files in dir */
  2369. if (cfg.dircolor) {
  2370. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2371. cfg.dircolor = 0;
  2372. }
  2373. if (cfg.showdetail) {
  2374. if (ndents) {
  2375. static char sort[9];
  2376. if (cfg.mtimeorder)
  2377. xstrlcpy(sort, "by time ", 9);
  2378. else if (cfg.sizeorder)
  2379. xstrlcpy(sort, "by size ", 9);
  2380. else
  2381. sort[0] = '\0';
  2382. /* We need to show filename as it may be truncated in directory listing */
  2383. if (!cfg.blkorder)
  2384. mvprintw(LINES - 1, 0, "%d/%d %s[%s]\n", cur + 1, ndents, sort,
  2385. unescape(dents[cur].name, NAME_MAX));
  2386. else {
  2387. xstrlcpy(buf, coolsize(dir_blocks << BLK_SHIFT), 12);
  2388. if (cfg.apparentsz)
  2389. c = 'a';
  2390. else
  2391. c = 'd';
  2392. mvprintw(LINES - 1, 0,
  2393. "%d/%d %cu: %s (%lu files) vol: %s free [%s]\n",
  2394. cur + 1, ndents, c, buf, num_files,
  2395. coolsize(get_fs_info(path, FREE)),
  2396. unescape(dents[cur].name, NAME_MAX));
  2397. }
  2398. } else
  2399. printmsg("0/0");
  2400. }
  2401. if (mode_changed) {
  2402. cfg.showdetail ^= 1;
  2403. printptr = &printent_long;
  2404. }
  2405. }
  2406. static void browse(char *ipath)
  2407. {
  2408. char newpath[PATH_MAX] __attribute__ ((aligned));
  2409. char mark[PATH_MAX] __attribute__ ((aligned));
  2410. char rundir[PATH_MAX] __attribute__ ((aligned));
  2411. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  2412. char *path, *lastdir, *lastname;
  2413. char *dir, *tmp;
  2414. struct stat sb;
  2415. int r = -1, fd, presel, ncp = 0, copystartid = 0, copyendid = 0;
  2416. enum action sel;
  2417. bool dir_changed = FALSE;
  2418. /* setup first context */
  2419. xstrlcpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  2420. path = g_ctx[0].c_path;
  2421. xstrlcpy(g_ctx[0].c_init, ipath, PATH_MAX); /* start directory */
  2422. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = newpath[0] = mark[0] = '\0';
  2423. rundir[0] = runfile[0] = '\0';
  2424. lastdir = g_ctx[0].c_last; /* last visited directory */
  2425. lastname = g_ctx[0].c_name; /* last visited filename */
  2426. g_ctx[0].c_cfg = cfg; /* current configuration */
  2427. if (cfg.filtermode)
  2428. presel = FILTER;
  2429. else
  2430. presel = 0;
  2431. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2432. if (dents == NULL)
  2433. errexit();
  2434. DPRINTF_P(dents);
  2435. /* Allocate buffer to hold names */
  2436. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2437. if (pnamebuf == NULL) {
  2438. free(dents);
  2439. errexit();
  2440. }
  2441. DPRINTF_P(pnamebuf);
  2442. begin:
  2443. #ifdef LINUX_INOTIFY
  2444. if ((presel == FILTER || dir_changed) && inotify_wd >= 0) {
  2445. inotify_rm_watch(inotify_fd, inotify_wd);
  2446. inotify_wd = -1;
  2447. dir_changed = FALSE;
  2448. }
  2449. #elif defined(BSD_KQUEUE)
  2450. if ((presel == FILTER || dir_changed) && event_fd >= 0) {
  2451. close(event_fd);
  2452. event_fd = -1;
  2453. dir_changed = FALSE;
  2454. }
  2455. #endif
  2456. /* Can fail when permissions change while browsing.
  2457. * It's assumed that path IS a directory when we are here.
  2458. */
  2459. if (access(path, R_OK) == -1) {
  2460. printwarn();
  2461. goto nochange;
  2462. }
  2463. populate(path, lastname);
  2464. #ifdef LINUX_INOTIFY
  2465. if (presel != FILTER && inotify_wd == -1) {
  2466. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2467. }
  2468. #elif defined(BSD_KQUEUE)
  2469. if (presel != FILTER && event_fd == -1) {
  2470. #if defined(O_EVTONLY)
  2471. event_fd = open(path, O_EVTONLY);
  2472. #else
  2473. event_fd = open(path, O_RDONLY);
  2474. #endif
  2475. if (event_fd >= 0)
  2476. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  2477. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2478. }
  2479. #endif
  2480. while (1) {
  2481. redraw(path);
  2482. nochange:
  2483. /* Exit if parent has exited */
  2484. if (getppid() == 1)
  2485. _exit(0);
  2486. sel = nextsel(&presel);
  2487. switch (sel) {
  2488. case SEL_BACK:
  2489. /* There is no going back */
  2490. if (istopdir(path)) {
  2491. /* Continue in navigate-as-you-type mode, if enabled */
  2492. if (cfg.filtermode)
  2493. presel = FILTER;
  2494. goto nochange;
  2495. }
  2496. dir = xdirname(path);
  2497. if (access(dir, R_OK) == -1) {
  2498. printwarn();
  2499. goto nochange;
  2500. }
  2501. /* Save history */
  2502. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  2503. /* Save last working directory */
  2504. xstrlcpy(lastdir, path, PATH_MAX);
  2505. xstrlcpy(path, dir, PATH_MAX);
  2506. setdirwatch();
  2507. goto begin;
  2508. case SEL_NAV_IN: // fallthrough
  2509. case SEL_GOIN:
  2510. /* Cannot descend in empty directories */
  2511. if (!ndents)
  2512. goto begin;
  2513. mkpath(path, dents[cur].name, newpath);
  2514. DPRINTF_S(newpath);
  2515. /* Cannot use stale data in entry, file may be missing by now */
  2516. if (stat(newpath, &sb) == -1) {
  2517. printwarn();
  2518. goto nochange;
  2519. }
  2520. DPRINTF_U(sb.st_mode);
  2521. switch (sb.st_mode & S_IFMT) {
  2522. case S_IFDIR:
  2523. if (access(newpath, R_OK) == -1) {
  2524. printwarn();
  2525. goto nochange;
  2526. }
  2527. /* Save last working directory */
  2528. xstrlcpy(lastdir, path, PATH_MAX);
  2529. xstrlcpy(path, newpath, PATH_MAX);
  2530. lastname[0] = '\0';
  2531. setdirwatch();
  2532. goto begin;
  2533. case S_IFREG:
  2534. {
  2535. /* If opened as vim plugin and Enter/^M pressed, pick */
  2536. if (cfg.picker && sel == SEL_GOIN) {
  2537. r = mkpath(path, dents[cur].name, newpath);
  2538. appendfpath(newpath, r);
  2539. writecp(pcopybuf, copybufpos - 1);
  2540. dentfree(dents);
  2541. return;
  2542. }
  2543. /* If open file is disabled on right arrow or `l`, return */
  2544. if (cfg.nonavopen && sel == SEL_NAV_IN)
  2545. continue;
  2546. /* Handle script selection mode */
  2547. if (cfg.runscript) {
  2548. if (cfg.runctx != cfg.curctx)
  2549. continue;
  2550. /* Must be in script directory to select script */
  2551. if (strcmp(path, scriptpath) != 0)
  2552. continue;
  2553. mkpath(path, dents[cur].name, newpath);
  2554. xstrlcpy(path, rundir, PATH_MAX);
  2555. if (runfile[0]) {
  2556. xstrlcpy(lastname, runfile, NAME_MAX);
  2557. spawn(shell, newpath, lastname, path,
  2558. F_NORMAL | F_SIGINT);
  2559. runfile[0] = '\0';
  2560. } else
  2561. spawn(shell, newpath, NULL, path, F_NORMAL | F_SIGINT);
  2562. rundir[0] = '\0';
  2563. cfg.runscript = 0;
  2564. setdirwatch();
  2565. goto begin;
  2566. }
  2567. /* If NNN_USE_EDITOR is set, open text in EDITOR */
  2568. if (cfg.useeditor &&
  2569. get_output(g_buf, CMD_LEN_MAX, "file", FILE_OPTS, newpath, FALSE)
  2570. && g_buf[0] == 't' && g_buf[1] == 'e' && g_buf[2] == 'x'
  2571. && g_buf[3] == g_buf[0] && g_buf[4] == '/') {
  2572. if (!quote_run_sh_cmd(editor, newpath, path))
  2573. goto nochange;
  2574. continue;
  2575. }
  2576. if (!sb.st_size && cfg.restrict0b) {
  2577. printmsg("empty: use edit or open with");
  2578. goto nochange;
  2579. }
  2580. /* Invoke desktop opener as last resort */
  2581. spawn(opener, newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2582. continue;
  2583. }
  2584. default:
  2585. printmsg("unsupported file");
  2586. goto nochange;
  2587. }
  2588. case SEL_NEXT: // fallthrough
  2589. case SEL_PREV: // fallthrough
  2590. case SEL_PGDN: // fallthrough
  2591. case SEL_PGUP: // fallthrough
  2592. case SEL_HOME: // fallthrough
  2593. case SEL_END:
  2594. switch (sel) {
  2595. case SEL_NEXT:
  2596. if (cur < ndents - 1)
  2597. ++cur;
  2598. else if (ndents)
  2599. /* Roll over, set cursor to first entry */
  2600. cur = 0;
  2601. break;
  2602. case SEL_PREV:
  2603. if (cur > 0)
  2604. --cur;
  2605. else if (ndents)
  2606. /* Roll over, set cursor to last entry */
  2607. cur = ndents - 1;
  2608. break;
  2609. case SEL_PGDN:
  2610. if (cur < ndents - 1)
  2611. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2612. break;
  2613. case SEL_PGUP:
  2614. if (cur > 0)
  2615. cur -= MIN((LINES - 4) / 2, cur);
  2616. break;
  2617. case SEL_HOME:
  2618. cur = 0;
  2619. break;
  2620. default: /* case SEL_END */
  2621. cur = ndents - 1;
  2622. break;
  2623. }
  2624. break;
  2625. case SEL_CDHOME: // fallthrough
  2626. case SEL_CDBEGIN: // fallthrough
  2627. case SEL_CDLAST: // fallthrough
  2628. case SEL_VISIT:
  2629. switch (sel) {
  2630. case SEL_CDHOME:
  2631. if (home)
  2632. dir = home;
  2633. else
  2634. dir = path;
  2635. break;
  2636. case SEL_CDBEGIN:
  2637. dir = ipath;
  2638. break;
  2639. case SEL_CDLAST:
  2640. dir = lastdir;
  2641. break;
  2642. default: /* case SEL_VISIT */
  2643. dir = mark;
  2644. break;
  2645. }
  2646. if (dir[0] == '\0') {
  2647. printmsg("not set");
  2648. goto nochange;
  2649. }
  2650. if (!xdiraccess(dir))
  2651. goto nochange;
  2652. if (strcmp(path, dir) == 0)
  2653. break;
  2654. /* SEL_CDLAST: dir pointing to lastdir */
  2655. xstrlcpy(newpath, dir, PATH_MAX);
  2656. /* Save last working directory */
  2657. xstrlcpy(lastdir, path, PATH_MAX);
  2658. xstrlcpy(path, newpath, PATH_MAX);
  2659. lastname[0] = '\0';
  2660. DPRINTF_S(path);
  2661. setdirwatch();
  2662. goto begin;
  2663. case SEL_LEADER: // fallthrough
  2664. case SEL_CYCLE: // fallthrough
  2665. case SEL_CTX1: // fallthrough
  2666. case SEL_CTX2: // fallthrough
  2667. case SEL_CTX3: // fallthrough
  2668. case SEL_CTX4:
  2669. if (sel == SEL_CYCLE)
  2670. fd = '>';
  2671. else if (sel >= SEL_CTX1 && sel <= SEL_CTX4)
  2672. fd = sel - SEL_CTX1 + '1';
  2673. else
  2674. fd = get_input(NULL);
  2675. switch (fd) {
  2676. case 'q': // fallthrough
  2677. case '~': // fallthrough
  2678. case '-': // fallthrough
  2679. case '&':
  2680. presel = fd;
  2681. goto nochange;
  2682. case '>': // fallthrough
  2683. case '.': // fallthrough
  2684. case '<': // fallthrough
  2685. case ',':
  2686. r = cfg.curctx;
  2687. if (fd == '>' || fd == '.')
  2688. do
  2689. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  2690. while (!g_ctx[r].c_cfg.ctxactive);
  2691. else
  2692. do
  2693. (r == 0) ? (r = CTX_MAX - 1) : --r;
  2694. while (!g_ctx[r].c_cfg.ctxactive); // fallthrough
  2695. fd = '1' + r; // fallthrough
  2696. case '1': // fallthrough
  2697. case '2': // fallthrough
  2698. case '3': // fallthrough
  2699. case '4':
  2700. r = fd - '1'; /* Save the next context id */
  2701. if (cfg.curctx == r) {
  2702. if (sel == SEL_CYCLE) {
  2703. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  2704. snprintf(newpath, PATH_MAX,
  2705. "Create context %d? [Enter]", r + 1);
  2706. fd = get_input(newpath);
  2707. if (fd != '\r')
  2708. continue;
  2709. } else
  2710. continue;
  2711. }
  2712. #ifdef DIR_LIMITED_COPY
  2713. g_crc = 0;
  2714. #endif
  2715. /* Save current context */
  2716. xstrlcpy(g_ctx[cfg.curctx].c_name, dents[cur].name, NAME_MAX + 1);
  2717. g_ctx[cfg.curctx].c_cfg = cfg;
  2718. if (g_ctx[r].c_cfg.ctxactive) /* Switch to saved context */
  2719. cfg = g_ctx[r].c_cfg;
  2720. else { /* Setup a new context from current context */
  2721. g_ctx[r].c_cfg.ctxactive = 1;
  2722. xstrlcpy(g_ctx[r].c_path, path, PATH_MAX);
  2723. xstrlcpy(g_ctx[r].c_init, path, PATH_MAX);
  2724. g_ctx[r].c_last[0] = '\0';
  2725. xstrlcpy(g_ctx[r].c_name, dents[cur].name, NAME_MAX + 1);
  2726. g_ctx[r].c_cfg = cfg;
  2727. g_ctx[r].c_cfg.runscript = 0;
  2728. }
  2729. /* Reset the pointers */
  2730. path = g_ctx[r].c_path;
  2731. ipath = g_ctx[r].c_init;
  2732. lastdir = g_ctx[r].c_last;
  2733. lastname = g_ctx[r].c_name;
  2734. cfg.curctx = r;
  2735. setdirwatch();
  2736. goto begin;
  2737. }
  2738. if (get_bm_loc(fd, newpath) == NULL) {
  2739. printmsg(messages[STR_INVBM_KEY]);
  2740. goto nochange;
  2741. }
  2742. if (!xdiraccess(newpath))
  2743. goto nochange;
  2744. if (strcmp(path, newpath) == 0)
  2745. break;
  2746. lastname[0] = '\0';
  2747. /* Save last working directory */
  2748. xstrlcpy(lastdir, path, PATH_MAX);
  2749. /* Save the newly opted dir in path */
  2750. xstrlcpy(path, newpath, PATH_MAX);
  2751. DPRINTF_S(path);
  2752. setdirwatch();
  2753. goto begin;
  2754. case SEL_PIN:
  2755. xstrlcpy(mark, path, PATH_MAX);
  2756. printmsg(mark);
  2757. goto nochange;
  2758. case SEL_FLTR:
  2759. /* Unwatch dir if we are still in a filtered view */
  2760. #ifdef LINUX_INOTIFY
  2761. if (inotify_wd >= 0) {
  2762. inotify_rm_watch(inotify_fd, inotify_wd);
  2763. inotify_wd = -1;
  2764. }
  2765. #elif defined(BSD_KQUEUE)
  2766. if (event_fd >= 0) {
  2767. close(event_fd);
  2768. event_fd = -1;
  2769. }
  2770. #endif
  2771. presel = filterentries(path);
  2772. /* Save current */
  2773. if (ndents)
  2774. copycurname();
  2775. goto nochange;
  2776. case SEL_MFLTR: // fallthrough
  2777. case SEL_TOGGLEDOT: // fallthrough
  2778. case SEL_DETAIL: // fallthrough
  2779. case SEL_FSIZE: // fallthrough
  2780. case SEL_ASIZE: // fallthrough
  2781. case SEL_BSIZE: // fallthrough
  2782. case SEL_MTIME:
  2783. switch (sel) {
  2784. case SEL_MFLTR:
  2785. cfg.filtermode ^= 1;
  2786. if (cfg.filtermode) {
  2787. presel = FILTER;
  2788. goto nochange;
  2789. }
  2790. /* Start watching the directory */
  2791. dir_changed = TRUE;
  2792. break;
  2793. case SEL_TOGGLEDOT:
  2794. cfg.showhidden ^= 1;
  2795. break;
  2796. case SEL_DETAIL:
  2797. cfg.showdetail ^= 1;
  2798. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2799. break;
  2800. case SEL_FSIZE:
  2801. cfg.sizeorder ^= 1;
  2802. cfg.mtimeorder = 0;
  2803. cfg.apparentsz = 0;
  2804. cfg.blkorder = 0;
  2805. cfg.copymode = 0;
  2806. break;
  2807. case SEL_ASIZE:
  2808. cfg.apparentsz ^= 1;
  2809. if (cfg.apparentsz) {
  2810. nftw_fn = &sum_sizes;
  2811. cfg.blkorder = 1;
  2812. BLK_SHIFT = 0;
  2813. } else
  2814. cfg.blkorder = 0;
  2815. break;
  2816. case SEL_BSIZE:
  2817. if (sel == SEL_BSIZE) {
  2818. if (!cfg.apparentsz)
  2819. cfg.blkorder ^= 1;
  2820. nftw_fn = &sum_bsizes;
  2821. cfg.apparentsz = 0;
  2822. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  2823. }
  2824. if (cfg.blkorder) {
  2825. cfg.showdetail = 1;
  2826. printptr = &printent_long;
  2827. }
  2828. cfg.mtimeorder = 0;
  2829. cfg.sizeorder = 0;
  2830. cfg.copymode = 0;
  2831. break;
  2832. default: /* SEL_MTIME */
  2833. cfg.mtimeorder ^= 1;
  2834. cfg.sizeorder = 0;
  2835. cfg.apparentsz = 0;
  2836. cfg.blkorder = 0;
  2837. cfg.copymode = 0;
  2838. break;
  2839. }
  2840. /* Save current */
  2841. if (ndents)
  2842. copycurname();
  2843. goto begin;
  2844. case SEL_STATS:
  2845. if (!ndents)
  2846. break;
  2847. mkpath(path, dents[cur].name, newpath);
  2848. if (lstat(newpath, &sb) == -1 || !show_stats(newpath, dents[cur].name, &sb)) {
  2849. printwarn();
  2850. goto nochange;
  2851. }
  2852. break;
  2853. case SEL_MEDIA: // fallthrough
  2854. case SEL_FMEDIA: // fallthrough
  2855. case SEL_ARCHIVELS: // fallthrough
  2856. case SEL_EXTRACT: // fallthrough
  2857. case SEL_RENAMEALL: // fallthrough
  2858. case SEL_RUNEDIT: // fallthrough
  2859. case SEL_RUNPAGE:
  2860. if (!ndents)
  2861. break; // fallthrough
  2862. case SEL_REDRAW: // fallthrough
  2863. case SEL_HELP: // fallthrough
  2864. case SEL_NOTE: // fallthrough
  2865. case SEL_LOCK:
  2866. {
  2867. if (ndents)
  2868. mkpath(path, dents[cur].name, newpath);
  2869. switch (sel) {
  2870. case SEL_MEDIA:
  2871. r = show_mediainfo(newpath, NULL);
  2872. break;
  2873. case SEL_FMEDIA:
  2874. r = show_mediainfo(newpath, "-f");
  2875. break;
  2876. case SEL_ARCHIVELS:
  2877. r = handle_archive(newpath, "-l", path);
  2878. break;
  2879. case SEL_EXTRACT:
  2880. r = handle_archive(newpath, "-x", path);
  2881. break;
  2882. case SEL_REDRAW:
  2883. if (ndents)
  2884. copycurname();
  2885. goto begin;
  2886. case SEL_RENAMEALL:
  2887. if ((r = getutil(utils[VIDIR])))
  2888. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2889. break;
  2890. case SEL_HELP:
  2891. r = show_help(path);
  2892. break;
  2893. case SEL_RUNEDIT:
  2894. if (!quote_run_sh_cmd(editor, dents[cur].name, path))
  2895. goto nochange;
  2896. r = TRUE;
  2897. break;
  2898. case SEL_RUNPAGE:
  2899. r = TRUE;
  2900. spawn(pager, pager_arg, dents[cur].name, path, F_NORMAL);
  2901. break;
  2902. case SEL_NOTE:
  2903. tmp = getenv(env_cfg[NNN_NOTE]);
  2904. if (!tmp) {
  2905. printmsg("set NNN_NOTE");
  2906. goto nochange;
  2907. }
  2908. if (!quote_run_sh_cmd(editor, tmp, NULL))
  2909. goto nochange;
  2910. r = TRUE;
  2911. break;
  2912. default: /* SEL_LOCK */
  2913. r = TRUE;
  2914. spawn(utils[LOCKER], NULL, NULL, NULL, F_NORMAL | F_SIGINT);
  2915. break;
  2916. }
  2917. if (!r) {
  2918. printmsg("required utility missing");
  2919. goto nochange;
  2920. }
  2921. /* In case of successful operation, reload contents */
  2922. /* Continue in navigate-as-you-type mode, if enabled */
  2923. if (cfg.filtermode)
  2924. presel = FILTER;
  2925. /* Save current */
  2926. if (ndents)
  2927. copycurname();
  2928. /* Repopulate as directory content may have changed */
  2929. goto begin;
  2930. }
  2931. case SEL_COPY:
  2932. if (!ndents)
  2933. goto nochange;
  2934. if (cfg.copymode) {
  2935. /*
  2936. * Clear the tmp copy path file on first copy.
  2937. *
  2938. * This ensures that when the first file path is
  2939. * copied into memory (but not written to tmp file
  2940. * yet to save on writes), the tmp file is cleared.
  2941. * The user may be in the middle of selection mode op
  2942. * and issue a cp, mv of multi-rm assuming the files
  2943. * in the copy list would be affected. However, these
  2944. * ops read the source file paths from the tmp file.
  2945. */
  2946. if (!ncp)
  2947. writecp(NULL, 0);
  2948. r = mkpath(path, dents[cur].name, newpath);
  2949. if (!appendfpath(newpath, r))
  2950. goto nochange;
  2951. ++ncp;
  2952. } else {
  2953. r = mkpath(path, dents[cur].name, newpath);
  2954. /* Keep the copy buf in sync */
  2955. copybufpos = 0;
  2956. appendfpath(newpath, r);
  2957. writecp(newpath, r - 1); /* Truncate NULL from end */
  2958. if (copier)
  2959. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  2960. }
  2961. printmsg(newpath);
  2962. goto nochange;
  2963. case SEL_COPYMUL:
  2964. cfg.copymode ^= 1;
  2965. if (cfg.copymode) {
  2966. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2967. copystartid = cur;
  2968. copybufpos = 0;
  2969. ncp = 0;
  2970. printmsg("selection on");
  2971. DPRINTF_S("selection on");
  2972. goto nochange;
  2973. } // fallthrough
  2974. case SEL_COPYALL:
  2975. if (sel == SEL_COPYALL) {
  2976. if (!ndents) {
  2977. printmsg("0 entries");
  2978. goto nochange;
  2979. }
  2980. cfg.copymode = 0;
  2981. copybufpos = 0;
  2982. ncp = 0;
  2983. copystartid = 0;
  2984. copyendid = ndents - 1;
  2985. }
  2986. if (!ncp) { /* Handle range selection */
  2987. #ifndef DIR_LIMITED_COPY
  2988. if ((sel != SEL_COPYALL) && g_crc != crc8fast((uchar *)dents,
  2989. ndents * sizeof(struct entry))) {
  2990. cfg.copymode = 0;
  2991. printmsg("range error: dir/content changed");
  2992. DPRINTF_S("range error: dir/content changed");
  2993. goto nochange;
  2994. }
  2995. #endif
  2996. if (sel != SEL_COPYALL) {
  2997. if (cur < copystartid) {
  2998. copyendid = copystartid;
  2999. copystartid = cur;
  3000. } else
  3001. copyendid = cur;
  3002. }
  3003. if (copystartid < copyendid || sel == SEL_COPYALL) {
  3004. for (r = copystartid; r <= copyendid; ++r)
  3005. if (!appendfpath(newpath, mkpath(path,
  3006. dents[r].name, newpath)))
  3007. goto nochange;
  3008. mvprintw(LINES - 1, 0, "%d files copied\n",
  3009. copyendid - copystartid + 1);
  3010. }
  3011. }
  3012. if (copybufpos) { /* File path(s) written to the buffer */
  3013. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  3014. if (copier)
  3015. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  3016. if (ncp) /* Some files cherry picked */
  3017. mvprintw(LINES - 1, 0, "%d files copied\n", ncp);
  3018. } else
  3019. printmsg("selection off");
  3020. goto nochange;
  3021. case SEL_COPYLIST:
  3022. if (copybufpos)
  3023. showcplist();
  3024. else
  3025. printmsg("none selected");
  3026. goto nochange;
  3027. case SEL_CP:
  3028. case SEL_MV:
  3029. case SEL_RMMUL:
  3030. {
  3031. if (!cpsafe())
  3032. goto nochange;
  3033. if (sel == SEL_CP) {
  3034. snprintf(g_buf, CMD_LEN_MAX,
  3035. #ifdef __linux__
  3036. "xargs -0 -a %s -%c src cp -iRp src .",
  3037. #else
  3038. "cat %s | xargs -0 -o -%c src cp -iRp src .",
  3039. #endif
  3040. g_cppath, REPLACE_STR);
  3041. } else if (sel == SEL_MV) {
  3042. snprintf(g_buf, CMD_LEN_MAX,
  3043. #ifdef __linux__
  3044. "xargs -0 -a %s -%c src mv -i src .",
  3045. #else
  3046. "cat %s | xargs -0 -o -%c src mv -i src .",
  3047. #endif
  3048. g_cppath, REPLACE_STR);
  3049. } else { /* SEL_RMMUL */
  3050. snprintf(g_buf, CMD_LEN_MAX,
  3051. #ifdef __linux__
  3052. "xargs -0 -a %s rm -%cr",
  3053. #else
  3054. "cat %s | xargs -0 -o rm -%cr",
  3055. #endif
  3056. g_cppath, confirm_force());
  3057. }
  3058. spawn("sh", "-c", g_buf, path, F_NORMAL | F_SIGINT);
  3059. if (ndents)
  3060. copycurname();
  3061. if (cfg.filtermode)
  3062. presel = FILTER;
  3063. goto begin;
  3064. }
  3065. case SEL_RM:
  3066. {
  3067. if (!ndents)
  3068. break;
  3069. char rm_opts[] = "-ir";
  3070. rm_opts[1] = confirm_force();
  3071. mkpath(path, dents[cur].name, newpath);
  3072. spawn("rm", rm_opts, newpath, NULL, F_NORMAL | F_SIGINT);
  3073. /* Don't optimize cur if filtering is on */
  3074. if (!cfg.filtermode && cur && access(newpath, F_OK) == -1)
  3075. --cur;
  3076. copycurname();
  3077. if (cfg.filtermode)
  3078. presel = FILTER;
  3079. goto begin;
  3080. }
  3081. case SEL_ARCHIVE: // fallthrough
  3082. case SEL_OPENWITH: // fallthrough
  3083. case SEL_RENAME:
  3084. if (!ndents)
  3085. break; // fallthrough
  3086. case SEL_NEW:
  3087. {
  3088. switch (sel) {
  3089. case SEL_ARCHIVE:
  3090. tmp = xreadline(NULL, "archive name: ");
  3091. break;
  3092. case SEL_OPENWITH:
  3093. tmp = xreadline(NULL, "open with: ");
  3094. break;
  3095. case SEL_NEW:
  3096. tmp = xreadline(NULL, "name/link suffix [@ for none]: ");
  3097. break;
  3098. default: /* SEL_RENAME */
  3099. tmp = xreadline(dents[cur].name, "");
  3100. break;
  3101. }
  3102. if (tmp == NULL || tmp[0] == '\0')
  3103. break;
  3104. /* Allow only relative, same dir paths */
  3105. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  3106. printmsg(messages[STR_INPUT_ID]);
  3107. goto nochange;
  3108. }
  3109. /* Confirm if app is CLI or GUI */
  3110. if (sel == SEL_OPENWITH) {
  3111. r = get_input("cli mode? [y/Y]");
  3112. (r == 'y' || r == 'Y') ? (r = F_NORMAL) : (r = F_NOWAIT | F_NOTRACE);
  3113. }
  3114. switch (sel) {
  3115. case SEL_ARCHIVE:
  3116. /* newpath is used as temporary buffer */
  3117. if (!getutil(utils[APACK])) {
  3118. printmsg("utility missing");
  3119. goto nochange;
  3120. }
  3121. r = get_input("archive selection (else current)? [s]");
  3122. if (r == 's') {
  3123. if (!cpsafe())
  3124. goto nochange;
  3125. snprintf(g_buf, CMD_LEN_MAX,
  3126. #ifdef __linux__
  3127. "xargs -0 -a %s %s %s",
  3128. #else
  3129. "cat %s | xargs -0 -o %s %s",
  3130. #endif
  3131. g_cppath, utils[APACK], tmp);
  3132. spawn("sh", "-c", g_buf, path, F_NORMAL | F_SIGINT);
  3133. } else
  3134. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  3135. break;
  3136. case SEL_OPENWITH:
  3137. dir = NULL;
  3138. getprogarg(tmp, &dir); /* dir used as tmp var */
  3139. mkpath(path, dents[cur].name, newpath);
  3140. spawn(tmp, dir, newpath, path, r);
  3141. break;
  3142. case SEL_RENAME:
  3143. /* Skip renaming to same name */
  3144. if (strcmp(tmp, dents[cur].name) == 0)
  3145. goto nochange;
  3146. break;
  3147. default:
  3148. break;
  3149. }
  3150. /* Complete OPEN, LAUNCH, ARCHIVE operations */
  3151. if (sel != SEL_NEW && sel != SEL_RENAME) {
  3152. /* Continue in navigate-as-you-type mode, if enabled */
  3153. if (cfg.filtermode)
  3154. presel = FILTER;
  3155. /* Save current */
  3156. copycurname();
  3157. /* Repopulate as directory content may have changed */
  3158. goto begin;
  3159. }
  3160. /* Open the descriptor to currently open directory */
  3161. fd = open(path, O_RDONLY | O_DIRECTORY);
  3162. if (fd == -1) {
  3163. printwarn();
  3164. goto nochange;
  3165. }
  3166. /* Check if another file with same name exists */
  3167. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  3168. if (sel == SEL_RENAME) {
  3169. /* Overwrite file with same name? */
  3170. r = get_input("overwrite? [y/Y]");
  3171. if (r != 'y' && r != 'Y') {
  3172. close(fd);
  3173. break;
  3174. }
  3175. } else {
  3176. /* Do nothing in case of NEW */
  3177. close(fd);
  3178. printmsg("entry exists");
  3179. goto nochange;
  3180. }
  3181. }
  3182. if (sel == SEL_RENAME) {
  3183. /* Rename the file */
  3184. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  3185. close(fd);
  3186. printwarn();
  3187. goto nochange;
  3188. }
  3189. } else {
  3190. /* Check if it's a dir or file */
  3191. r = get_input("create 'f'(ile) / 'd'(ir) / 's'(ym) / 'h'(ard)?");
  3192. if (r == 'f') {
  3193. r = openat(fd, tmp, O_CREAT, 0666);
  3194. close(r);
  3195. } else if (r == 'd') {
  3196. r = mkdirat(fd, tmp, 0777);
  3197. } else if (r == 's' || r == 'h') {
  3198. if (tmp[0] == '@' && tmp[1] == '\0')
  3199. tmp[0] = '\0';
  3200. r = xlink(tmp, path, newpath, r);
  3201. close(fd);
  3202. if (r <= 0) {
  3203. printmsg("none created");
  3204. goto nochange;
  3205. }
  3206. if (cfg.filtermode)
  3207. presel = FILTER;
  3208. if (ndents)
  3209. copycurname();
  3210. goto begin;
  3211. } else {
  3212. close(fd);
  3213. break;
  3214. }
  3215. /* Check if file creation failed */
  3216. if (r == -1) {
  3217. close(fd);
  3218. printwarn();
  3219. goto nochange;
  3220. }
  3221. }
  3222. close(fd);
  3223. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  3224. goto begin;
  3225. }
  3226. case SEL_EXEC: // fallthrough
  3227. case SEL_SHELL: // fallthrough
  3228. case SEL_SCRIPT: // fallthrough
  3229. case SEL_RUNCMD:
  3230. switch (sel) {
  3231. case SEL_EXEC:
  3232. if (!ndents)
  3233. goto nochange;
  3234. /* Check if this is a directory */
  3235. if (!S_ISREG(dents[cur].mode)) {
  3236. printmsg("not regular file");
  3237. goto nochange;
  3238. }
  3239. /* Check if file is executable */
  3240. if (!(dents[cur].mode & 0100)) {
  3241. printmsg("permission denied");
  3242. goto nochange;
  3243. }
  3244. mkpath(path, dents[cur].name, newpath);
  3245. DPRINTF_S(newpath);
  3246. spawn(newpath, NULL, NULL, path, F_NORMAL | F_SIGINT);
  3247. break;
  3248. case SEL_SHELL:
  3249. spawn(shell, shell_arg, NULL, path, F_NORMAL | F_MARKER);
  3250. break;
  3251. case SEL_SCRIPT:
  3252. if (!scriptpath) {
  3253. printmsg("set NNN_SCRIPT");
  3254. goto nochange;
  3255. }
  3256. if (stat(scriptpath, &sb) == -1) {
  3257. printwarn();
  3258. goto nochange;
  3259. }
  3260. if (S_ISDIR(sb.st_mode)) {
  3261. cfg.runscript ^= 1;
  3262. if (!cfg.runscript && rundir[0]) {
  3263. /* If toggled, and still in the script dir,
  3264. switch to original directory */
  3265. if (strcmp(path, scriptpath) == 0) {
  3266. xstrlcpy(path, rundir, PATH_MAX);
  3267. xstrlcpy(lastname, runfile, NAME_MAX);
  3268. rundir[0] = runfile[0] = '\0';
  3269. setdirwatch();
  3270. goto begin;
  3271. }
  3272. break;
  3273. }
  3274. /* Check if directory is accessible */
  3275. if (!xdiraccess(scriptpath))
  3276. goto nochange;
  3277. xstrlcpy(rundir, path, PATH_MAX);
  3278. xstrlcpy(path, scriptpath, PATH_MAX);
  3279. if (ndents)
  3280. xstrlcpy(runfile, dents[cur].name, NAME_MAX);
  3281. cfg.runctx = cfg.curctx;
  3282. lastname[0] = '\0';
  3283. setdirwatch();
  3284. goto begin;
  3285. }
  3286. if (S_ISREG(sb.st_mode)) {
  3287. if (ndents)
  3288. tmp = dents[cur].name;
  3289. else
  3290. tmp = NULL;
  3291. spawn(shell, scriptpath, tmp, path, F_NORMAL | F_SIGINT);
  3292. }
  3293. break;
  3294. default: /* SEL_RUNCMD */
  3295. exitcurses();
  3296. /* Switch to current path for readline(3) */
  3297. if (chdir(path) == -1) {
  3298. printwarn();
  3299. goto nochange;
  3300. }
  3301. tmp = readline("nnn> ");
  3302. if (chdir(ipath) == -1) {
  3303. printwarn();
  3304. goto nochange;
  3305. }
  3306. refresh();
  3307. if (tmp && tmp[0]) {
  3308. spawn(shell, "-c", tmp, path, F_NORMAL | F_SIGINT);
  3309. add_history(tmp);
  3310. free(tmp);
  3311. }
  3312. }
  3313. /* Continue in navigate-as-you-type mode, if enabled */
  3314. if (cfg.filtermode)
  3315. presel = FILTER;
  3316. /* Save current */
  3317. if (ndents)
  3318. copycurname();
  3319. /* Repopulate as directory content may have changed */
  3320. goto begin;
  3321. case SEL_QUITCD: // fallthrough
  3322. case SEL_QUIT:
  3323. for (r = 0; r < CTX_MAX; ++r)
  3324. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  3325. r = get_input("Quit all contexts? [Enter]");
  3326. break;
  3327. }
  3328. if (!(r == CTX_MAX || r == '\r'))
  3329. break;
  3330. if (sel == SEL_QUITCD) {
  3331. /* In vim picker mode, clear selection and exit */
  3332. if (cfg.picker) {
  3333. if (copybufpos) {
  3334. if (cfg.pickraw) /* Reset for for raw pick */
  3335. copybufpos = 0;
  3336. else /* Clear the picker file */
  3337. writecp(NULL, 0);
  3338. }
  3339. dentfree(dents);
  3340. return;
  3341. }
  3342. tmp = getenv(env_cfg[NNN_TMPFILE]);
  3343. if (!tmp) {
  3344. printmsg("set NNN_TMPFILE");
  3345. goto nochange;
  3346. }
  3347. FILE *fp = fopen(tmp, "w");
  3348. if (fp) {
  3349. fprintf(fp, "cd \"%s\"", path);
  3350. fclose(fp);
  3351. }
  3352. } // fallthrough
  3353. case SEL_QUITCTX:
  3354. if (sel == SEL_QUITCTX) {
  3355. uint iter = 1;
  3356. r = cfg.curctx;
  3357. while (iter < CTX_MAX) {
  3358. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3359. if (g_ctx[r].c_cfg.ctxactive) {
  3360. g_ctx[cfg.curctx].c_cfg.ctxactive = 0;
  3361. /* Switch to next active context */
  3362. path = g_ctx[r].c_path;
  3363. ipath = g_ctx[r].c_init;
  3364. lastdir = g_ctx[r].c_last;
  3365. lastname = g_ctx[r].c_name;
  3366. cfg = g_ctx[r].c_cfg;
  3367. cfg.curctx = r;
  3368. setdirwatch();
  3369. goto begin;
  3370. }
  3371. ++iter;
  3372. }
  3373. }
  3374. dentfree(dents);
  3375. return;
  3376. } /* switch (sel) */
  3377. /* Locker */
  3378. if (idletimeout != 0 && idle == idletimeout) {
  3379. idle = 0;
  3380. spawn(utils[LOCKER], NULL, NULL, NULL, F_NORMAL | F_SIGINT);
  3381. }
  3382. }
  3383. }
  3384. static void usage(void)
  3385. {
  3386. fprintf(stdout,
  3387. "usage: nnn [-b key] [-C] [-e] [-i] [-l] [-n]\n"
  3388. " [-p file] [-s] [-S] [-v] [-h] [PATH]\n\n"
  3389. "The missing terminal file manager for X.\n\n"
  3390. "positional args:\n"
  3391. " PATH start dir [default: current dir]\n\n"
  3392. "optional args:\n"
  3393. " -b key open bookmark key\n"
  3394. " -C disable directory color\n"
  3395. " -e use exiftool for media info\n"
  3396. " -i nav-as-you-type mode\n"
  3397. " -l light mode\n"
  3398. " -n use version compare to sort\n"
  3399. " -p file selection file (stdout if '-')\n"
  3400. " -s string filters [default: regex]\n"
  3401. " -S disk usage mode\n"
  3402. " -v show version\n"
  3403. " -h show help\n\n"
  3404. "v%s\n%s\n", VERSION, GENERAL_INFO);
  3405. }
  3406. int main(int argc, char *argv[])
  3407. {
  3408. char cwd[PATH_MAX] __attribute__ ((aligned));
  3409. char *ipath = NULL;
  3410. int opt;
  3411. while ((opt = getopt(argc, argv, "Slib:Cenp:svh")) != -1) {
  3412. switch (opt) {
  3413. case 'S':
  3414. cfg.blkorder = 1;
  3415. nftw_fn = sum_bsizes;
  3416. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  3417. break;
  3418. case 'l':
  3419. cfg.showdetail = 0;
  3420. printptr = &printent;
  3421. break;
  3422. case 'i':
  3423. cfg.filtermode = 1;
  3424. break;
  3425. case 'b':
  3426. ipath = optarg;
  3427. break;
  3428. case 'C':
  3429. cfg.showcolor = 0;
  3430. break;
  3431. case 'e':
  3432. cfg.metaviewer = EXIFTOOL;
  3433. break;
  3434. case 'n':
  3435. cmpfn = &xstrverscmp;
  3436. break;
  3437. case 'p':
  3438. cfg.picker = 1;
  3439. if (optarg[0] == '-' && optarg[1] == '\0')
  3440. cfg.pickraw = 1;
  3441. else {
  3442. /* copier used as tmp var */
  3443. copier = realpath(optarg, g_cppath);
  3444. if (!g_cppath[0]) {
  3445. fprintf(stderr, "%s\n", strerror(errno));
  3446. return 1;
  3447. }
  3448. }
  3449. break;
  3450. case 's':
  3451. cfg.filter_re = 0;
  3452. filterfn = &visible_str;
  3453. break;
  3454. case 'v':
  3455. fprintf(stdout, "%s\n", VERSION);
  3456. return 0;
  3457. case 'h':
  3458. usage();
  3459. return 0;
  3460. default:
  3461. usage();
  3462. return 1;
  3463. }
  3464. }
  3465. /* Confirm we are in a terminal */
  3466. if (!cfg.picker && !(isatty(0) && isatty(1))) {
  3467. fprintf(stderr, "stdin/stdout !tty\n");
  3468. return 1;
  3469. }
  3470. /* Get the context colors; copier used as tmp var */
  3471. if (cfg.showcolor) {
  3472. copier = xgetenv(env_cfg[NNN_CONTEXT_COLORS], "4444");
  3473. opt = 0;
  3474. while (*copier && opt < CTX_MAX) {
  3475. if (*copier < '0' || *copier > '7') {
  3476. fprintf(stderr, "invalid color code\n");
  3477. return 1;
  3478. }
  3479. g_ctx[opt].color = *copier - '0';
  3480. ++copier;
  3481. ++opt;
  3482. }
  3483. while (opt != CTX_MAX) {
  3484. g_ctx[opt].color = 4;
  3485. ++opt;
  3486. }
  3487. }
  3488. /* Parse bookmarks string */
  3489. if (!parsebmstr()) {
  3490. fprintf(stderr, "%s: malformed\n", env_cfg[NNN_BMS]);
  3491. return 1;
  3492. }
  3493. if (ipath) { /* Open a bookmark directly */
  3494. if (ipath[1] || get_bm_loc(*ipath, cwd) == NULL) {
  3495. fprintf(stderr, "%s\n", messages[STR_INVBM_KEY]);
  3496. return 1;
  3497. }
  3498. ipath = cwd;
  3499. } else if (argc == optind) {
  3500. /* Start in the current directory */
  3501. ipath = getcwd(cwd, PATH_MAX);
  3502. if (ipath == NULL)
  3503. ipath = "/";
  3504. } else {
  3505. ipath = realpath(argv[optind], cwd);
  3506. if (!ipath) {
  3507. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  3508. return 1;
  3509. }
  3510. }
  3511. /* Increase current open file descriptor limit */
  3512. open_max = max_openfds();
  3513. if (getuid() == 0 || getenv(env_cfg[NNN_SHOW_HIDDEN]))
  3514. cfg.showhidden = 1;
  3515. /* Edit text in EDITOR, if opted */
  3516. if (getenv(env_cfg[NNN_USE_EDITOR]))
  3517. cfg.useeditor = 1;
  3518. /* Get VISUAL/EDITOR */
  3519. editor = xgetenv(envs[VISUAL], xgetenv(envs[EDITOR], "vi"));
  3520. DPRINTF_S(getenv(envs[VISUAL]));
  3521. DPRINTF_S(getenv(envs[EDITOR]));
  3522. DPRINTF_S(editor);
  3523. /* Get PAGER */
  3524. pager = xgetenv(envs[PAGER], "less");
  3525. getprogarg(pager, &pager_arg);
  3526. DPRINTF_S(pager);
  3527. DPRINTF_S(pager_arg);
  3528. /* Get SHELL */
  3529. shell = xgetenv(envs[SHELL], "sh");
  3530. getprogarg(shell, &shell_arg);
  3531. DPRINTF_S(shell);
  3532. DPRINTF_S(shell_arg);
  3533. DPRINTF_S(getenv("PWD"));
  3534. /* Setup script execution */
  3535. scriptpath = getenv(env_cfg[NNN_SCRIPT]);
  3536. #ifdef LINUX_INOTIFY
  3537. /* Initialize inotify */
  3538. inotify_fd = inotify_init1(IN_NONBLOCK);
  3539. if (inotify_fd < 0) {
  3540. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  3541. return 1;
  3542. }
  3543. #elif defined(BSD_KQUEUE)
  3544. kq = kqueue();
  3545. if (kq < 0) {
  3546. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  3547. return 1;
  3548. }
  3549. #endif
  3550. /* Get custom opener, if set */
  3551. opener = xgetenv(env_cfg[NNN_OPENER], utils[OPENER]);
  3552. /* Get locker wait time, if set */
  3553. idletimeout = xatoi(getenv(env_cfg[NNN_IDLE_TIMEOUT]));
  3554. DPRINTF_U(idletimeout);
  3555. /* Get the clipboard copier, if set */
  3556. copier = getenv(env_cfg[NNN_COPIER]);
  3557. home = getenv("HOME");
  3558. DPRINTF_S(home);
  3559. if (home)
  3560. g_tmpfplen = xstrlcpy(g_tmpfpath, home, HOME_LEN_MAX);
  3561. else if (getenv("TMPDIR"))
  3562. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("TMPDIR"), HOME_LEN_MAX);
  3563. else if (xdiraccess("/tmp"))
  3564. g_tmpfplen = xstrlcpy(g_tmpfpath, "/tmp", HOME_LEN_MAX);
  3565. if (!cfg.picker && g_tmpfplen) {
  3566. xstrlcpy(g_cppath, g_tmpfpath, HOME_LEN_MAX);
  3567. xstrlcpy(g_cppath + g_tmpfplen - 1, "/.nnncp", HOME_LEN_MAX - g_tmpfplen);
  3568. }
  3569. /* Disable auto-select if opted */
  3570. if (getenv(env_cfg[NNN_NO_AUTOSELECT]))
  3571. cfg.autoselect = 0;
  3572. /* Disable opening files on right arrow and `l` */
  3573. if (getenv(env_cfg[NNN_RESTRICT_NAV_OPEN]))
  3574. cfg.nonavopen = 1;
  3575. /* Restrict opening of 0-byte files */
  3576. if (getenv(env_cfg[NNN_RESTRICT_0B]))
  3577. cfg.restrict0b = 1;
  3578. /* Ignore certain signals */
  3579. signal(SIGINT, SIG_IGN);
  3580. signal(SIGQUIT, SIG_IGN);
  3581. /* Test initial path */
  3582. if (!xdiraccess(ipath)) {
  3583. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  3584. return 1;
  3585. }
  3586. /* Set locale */
  3587. setlocale(LC_ALL, "");
  3588. crc8init();
  3589. /* Bind TAB to cycling */
  3590. rl_variable_bind("completion-ignore-case", "on");
  3591. #ifdef __linux__
  3592. rl_bind_key('\t', rl_menu_complete);
  3593. #else
  3594. rl_bind_key('\t', rl_complete);
  3595. #endif
  3596. read_history(NULL);
  3597. #ifdef DEBUGMODE
  3598. enabledbg();
  3599. #endif
  3600. if (!initcurses())
  3601. return 1;
  3602. browse(ipath);
  3603. exitcurses();
  3604. write_history(NULL);
  3605. if (cfg.pickraw) {
  3606. if (copybufpos) {
  3607. opt = selectiontofd(1);
  3608. if (opt != (int)(copybufpos))
  3609. fprintf(stderr, "%s\n", strerror(errno));
  3610. }
  3611. } else if (!cfg.picker && g_cppath[0])
  3612. unlink(g_cppath);
  3613. /* Free the copy buffer */
  3614. free(pcopybuf);
  3615. #ifdef LINUX_INOTIFY
  3616. /* Shutdown inotify */
  3617. if (inotify_wd >= 0)
  3618. inotify_rm_watch(inotify_fd, inotify_wd);
  3619. close(inotify_fd);
  3620. #elif defined(BSD_KQUEUE)
  3621. if (event_fd >= 0)
  3622. close(event_fd);
  3623. close(kq);
  3624. #endif
  3625. #ifdef DEBUGMODE
  3626. disabledbg();
  3627. #endif
  3628. return 0;
  3629. }