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.
 
 
 
 
 
 

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