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

4020 lines
90 KiB

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