My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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