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.
 
 
 
 
 
 

4023 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. regerror(r, regex, g_buf, len);
  954. printmsg(g_buf);
  955. }
  956. return r;
  957. }
  958. static int visible_re(regex_t *regex, char *fname, char *fltr)
  959. {
  960. return regexec(regex, fname, 0, NULL, 0) == 0;
  961. }
  962. static int visible_str(regex_t *regex, char *fname, char *fltr)
  963. {
  964. return strcasestr(fname, fltr) != NULL;
  965. }
  966. static int (*filterfn)(regex_t *regex, char *fname, char *fltr) = &visible_re;
  967. static int entrycmp(const void *va, const void *vb)
  968. {
  969. static pEntry pa, pb;
  970. pa = (pEntry)va;
  971. pb = (pEntry)vb;
  972. /* Sort directories first */
  973. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  974. return 1;
  975. if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  976. return -1;
  977. /* Do the actual sorting */
  978. if (cfg.mtimeorder)
  979. return pb->t - pa->t;
  980. if (cfg.sizeorder) {
  981. if (pb->size > pa->size)
  982. return 1;
  983. if (pb->size < pa->size)
  984. return -1;
  985. }
  986. if (cfg.blkorder) {
  987. if (pb->blocks > pa->blocks)
  988. return 1;
  989. if (pb->blocks < pa->blocks)
  990. return -1;
  991. }
  992. return xstricmp(pa->name, pb->name);
  993. }
  994. /*
  995. * Returns SEL_* if key is bound and 0 otherwise.
  996. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  997. * The next keyboard input can be simulated by presel.
  998. */
  999. static int nextsel(int *presel)
  1000. {
  1001. static int c;
  1002. static uint i;
  1003. static const uint len = LEN(bindings);
  1004. #ifdef LINUX_INOTIFY
  1005. static char inotify_buf[EVENT_BUF_LEN];
  1006. #elif defined(BSD_KQUEUE)
  1007. static struct kevent event_data[NUM_EVENT_SLOTS];
  1008. #endif
  1009. c = *presel;
  1010. if (c == 0) {
  1011. c = getch();
  1012. DPRINTF_D(c);
  1013. } else {
  1014. /* Unwatch dir if we are still in a filtered view */
  1015. #ifdef LINUX_INOTIFY
  1016. if (*presel == FILTER && inotify_wd >= 0) {
  1017. inotify_rm_watch(inotify_fd, inotify_wd);
  1018. inotify_wd = -1;
  1019. }
  1020. #elif defined(BSD_KQUEUE)
  1021. if (*presel == FILTER && event_fd >= 0) {
  1022. close(event_fd);
  1023. event_fd = -1;
  1024. }
  1025. #endif
  1026. *presel = 0;
  1027. }
  1028. if (c == -1) {
  1029. ++idle;
  1030. /*
  1031. * Do not check for directory changes in du mode.
  1032. * A redraw forces du calculation.
  1033. * Check for changes every odd second.
  1034. */
  1035. #ifdef LINUX_INOTIFY
  1036. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1
  1037. && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  1038. #elif defined(BSD_KQUEUE)
  1039. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  1040. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
  1041. event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  1042. #endif
  1043. c = CONTROL('L');
  1044. } else
  1045. idle = 0;
  1046. for (i = 0; i < len; ++i)
  1047. if (c == bindings[i].sym)
  1048. return bindings[i].act;
  1049. return 0;
  1050. }
  1051. /*
  1052. * Move non-matching entries to the end
  1053. */
  1054. static int fill(char* fltr, regex_t *re)
  1055. {
  1056. static int count;
  1057. static struct entry _dent, *pdent1, *pdent2;
  1058. for (count = 0; count < ndents; ++count) {
  1059. if (filterfn(re, dents[count].name, fltr) == 0) {
  1060. if (count != --ndents) {
  1061. pdent1 = &dents[count];
  1062. pdent2 = &dents[ndents];
  1063. *(&_dent) = *pdent1;
  1064. *pdent1 = *pdent2;
  1065. *pdent2 = *(&_dent);
  1066. --count;
  1067. }
  1068. continue;
  1069. }
  1070. }
  1071. return ndents;
  1072. }
  1073. static int matches(char *fltr)
  1074. {
  1075. static regex_t re;
  1076. /* Search filter */
  1077. if (cfg.filter_re && setfilter(&re, fltr) != 0)
  1078. return -1;
  1079. ndents = fill(fltr, &re);
  1080. if (cfg.filter_re)
  1081. regfree(&re);
  1082. if (!ndents)
  1083. return 0;
  1084. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1085. return 0;
  1086. }
  1087. static int filterentries(char *path)
  1088. {
  1089. static char ln[REGEX_MAX] __attribute__ ((aligned));
  1090. static wchar_t wln[REGEX_MAX] __attribute__ ((aligned));
  1091. static wint_t ch[2] = {0};
  1092. int r, total = ndents, oldcur = cur, len = 1;
  1093. char *pln = ln + 1;
  1094. ln[0] = wln[0] = FILTER;
  1095. ln[1] = wln[1] = '\0';
  1096. cur = 0;
  1097. cleartimeout();
  1098. curs_set(TRUE);
  1099. printprompt(ln);
  1100. while ((r = get_wch(ch)) != ERR) {
  1101. switch (*ch) {
  1102. case KEY_DC: // fallthrough
  1103. case KEY_BACKSPACE: // fallthrough
  1104. case '\b': // fallthrough
  1105. case CONTROL('L'): // fallthrough
  1106. case 127: /* handle DEL */
  1107. if (len == 1 && *ch != CONTROL('L')) {
  1108. cur = oldcur;
  1109. *ch = CONTROL('L');
  1110. goto end;
  1111. }
  1112. if (*ch == CONTROL('L'))
  1113. while (len > 1)
  1114. wln[--len] = '\0';
  1115. else
  1116. wln[--len] = '\0';
  1117. if (len == 1)
  1118. cur = oldcur;
  1119. wcstombs(ln, wln, REGEX_MAX);
  1120. ndents = total;
  1121. if (matches(pln) != -1)
  1122. redraw(path);
  1123. printprompt(ln);
  1124. continue;
  1125. case 27: /* Exit filter mode on Escape */
  1126. if (len == 1)
  1127. cur = oldcur;
  1128. *ch = CONTROL('L');
  1129. goto end;
  1130. }
  1131. if (r == OK) {
  1132. /* Handle all control chars in main loop */
  1133. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^') {
  1134. if (len == 1)
  1135. cur = oldcur;
  1136. goto end;
  1137. }
  1138. switch (*ch) {
  1139. case '\r': // with nonl(), this is ENTER key value
  1140. if (len == 1) {
  1141. cur = oldcur;
  1142. goto end;
  1143. }
  1144. if (matches(pln) == -1)
  1145. goto end;
  1146. redraw(path);
  1147. goto end;
  1148. case '?': // '?' is an invalid regex, show help instead
  1149. if (len == 1) {
  1150. cur = oldcur;
  1151. goto end;
  1152. } // fallthrough
  1153. default:
  1154. /* Reset cur in case it's a repeat search */
  1155. if (len == 1)
  1156. cur = 0;
  1157. if (len == REGEX_MAX - 1)
  1158. break;
  1159. wln[len] = (wchar_t)*ch;
  1160. wln[++len] = '\0';
  1161. wcstombs(ln, wln, REGEX_MAX);
  1162. /* Forward-filtering optimization:
  1163. * - new matches can only be a subset of current matches.
  1164. */
  1165. /* ndents = total; */
  1166. if (matches(pln) == -1)
  1167. continue;
  1168. /* If the only match is a dir, auto-select and cd into it */
  1169. if (ndents == 1 && cfg.filtermode
  1170. && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  1171. *ch = KEY_ENTER;
  1172. cur = 0;
  1173. goto end;
  1174. }
  1175. /*
  1176. * redraw() should be above the auto-select optimization, for
  1177. * the case where there's an issue with dir auto-select, say,
  1178. * due to a permission problem. The transition is _jumpy_ in
  1179. * case of such an error. However, we optimize for successful
  1180. * cases where the dir has permissions. This skips a redraw().
  1181. */
  1182. redraw(path);
  1183. printprompt(ln);
  1184. }
  1185. } else {
  1186. if (len == 1)
  1187. cur = oldcur;
  1188. goto end;
  1189. }
  1190. }
  1191. end:
  1192. curs_set(FALSE);
  1193. settimeout();
  1194. /* Return keys for navigation etc. */
  1195. return *ch;
  1196. }
  1197. /* Show a prompt with input string and return the changes */
  1198. static char *xreadline(char *prefill, char *prompt)
  1199. {
  1200. size_t len, pos;
  1201. int x, y, r;
  1202. wint_t ch[2] = {0};
  1203. static wchar_t * const buf = (wchar_t *)g_buf;
  1204. cleartimeout();
  1205. printprompt(prompt);
  1206. if (prefill) {
  1207. DPRINTF_S(prefill);
  1208. len = pos = mbstowcs(buf, prefill, NAME_MAX);
  1209. } else
  1210. len = (size_t)-1;
  1211. if (len == (size_t)-1) {
  1212. buf[0] = '\0';
  1213. len = pos = 0;
  1214. }
  1215. getyx(stdscr, y, x);
  1216. curs_set(TRUE);
  1217. while (1) {
  1218. buf[len] = ' ';
  1219. mvaddnwstr(y, x, buf, len + 1);
  1220. move(y, x + wcswidth(buf, pos));
  1221. r = get_wch(ch);
  1222. if (r != ERR) {
  1223. if (r == OK) {
  1224. switch (*ch) {
  1225. case KEY_ENTER: // fallthrough
  1226. case '\n': // fallthrough
  1227. case '\r':
  1228. goto END;
  1229. case 127: /* Handle DEL */ // fallthrough
  1230. case '\b': /* rhel25 sends '\b' for backspace */
  1231. if (pos > 0) {
  1232. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1233. --len, --pos;
  1234. } // fallthrough
  1235. case '\t': /* TAB breaks cursor position, ignore it */
  1236. continue;
  1237. case CONTROL('L'):
  1238. clearprompt();
  1239. printprompt(prompt);
  1240. len = pos = 0;
  1241. continue;
  1242. case CONTROL('A'):
  1243. pos = 0;
  1244. continue;
  1245. case CONTROL('E'):
  1246. pos = len;
  1247. continue;
  1248. case CONTROL('U'):
  1249. clearprompt();
  1250. printprompt(prompt);
  1251. memmove(buf, buf + pos, (len - pos) << 2);
  1252. len -= pos;
  1253. pos = 0;
  1254. continue;
  1255. case 27: /* Exit prompt on Escape */
  1256. len = 0;
  1257. goto END;
  1258. }
  1259. /* Filter out all other control chars */
  1260. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
  1261. continue;
  1262. if (pos < NAME_MAX - 1) {
  1263. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1264. buf[pos] = *ch;
  1265. ++len, ++pos;
  1266. continue;
  1267. }
  1268. } else {
  1269. switch (*ch) {
  1270. case KEY_LEFT:
  1271. if (pos > 0)
  1272. --pos;
  1273. break;
  1274. case KEY_RIGHT:
  1275. if (pos < len)
  1276. ++pos;
  1277. break;
  1278. case KEY_BACKSPACE:
  1279. if (pos > 0) {
  1280. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1281. --len, --pos;
  1282. }
  1283. break;
  1284. case KEY_DC:
  1285. if (pos < len) {
  1286. memmove(buf + pos, buf + pos + 1,
  1287. (len - pos - 1) << 2);
  1288. --len;
  1289. }
  1290. break;
  1291. default:
  1292. break;
  1293. }
  1294. }
  1295. }
  1296. }
  1297. END:
  1298. curs_set(FALSE);
  1299. settimeout();
  1300. clearprompt();
  1301. buf[len] = '\0';
  1302. wcstombs(g_buf + ((NAME_MAX + 1) << 2), buf, NAME_MAX);
  1303. return g_buf + ((NAME_MAX + 1) << 2);
  1304. }
  1305. /*
  1306. * Updates out with "dir/name or "/name"
  1307. * Returns the number of bytes copied including the terminating NULL byte
  1308. */
  1309. static size_t mkpath(char *dir, char *name, char *out)
  1310. {
  1311. static size_t len;
  1312. /* Handle absolute path */
  1313. if (name[0] == '/')
  1314. return xstrlcpy(out, name, PATH_MAX);
  1315. /* Handle root case */
  1316. if (istopdir(dir))
  1317. len = 1;
  1318. else
  1319. len = xstrlcpy(out, dir, PATH_MAX);
  1320. out[len - 1] = '/';
  1321. return (xstrlcpy(out + len, name, PATH_MAX - len) + len);
  1322. }
  1323. /*
  1324. * Create symbolic/hard link(s) to file(s) in selection list
  1325. * Returns the number of links created
  1326. */
  1327. static int xlink(char *suffix, char *path, char *buf, int type)
  1328. {
  1329. int count = 0;
  1330. char *pbuf = pcopybuf, *fname;
  1331. ssize_t pos = 0, len, r;
  1332. int (*link_fn)(const char *, const char *) = NULL;
  1333. /* Check if selection is empty */
  1334. if (!copybufpos)
  1335. return 0;
  1336. if (type == 's') /* symbolic link */
  1337. link_fn = &symlink;
  1338. else if (type == 'h') /* hard link */
  1339. link_fn = &link;
  1340. else
  1341. return -1;
  1342. while (pos < copybufpos) {
  1343. len = strlen(pbuf);
  1344. fname = xbasename(pbuf);
  1345. r = mkpath(path, fname, buf);
  1346. xstrlcpy(buf + r - 1, suffix, PATH_MAX - r - 1);
  1347. if (!link_fn(pbuf, buf))
  1348. ++count;
  1349. pos += len + 1;
  1350. pbuf += len + 1;
  1351. }
  1352. return count;
  1353. }
  1354. static bool parsebmstr()
  1355. {
  1356. int i = 0;
  1357. char *bms = getenv(env_cfg[NNN_BMS]);
  1358. if (!bms)
  1359. return TRUE;
  1360. while (*bms && i < BM_MAX) {
  1361. bookmark[i].key = *bms;
  1362. if (!*++bms) {
  1363. bookmark[i].key = '\0';
  1364. break;
  1365. }
  1366. if (*bms != ':')
  1367. return FALSE; /* We support single char keys only */
  1368. bookmark[i].loc = ++bms;
  1369. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1370. bookmark[i].key = '\0';
  1371. break;
  1372. }
  1373. while (*bms && *bms != ';')
  1374. ++bms;
  1375. if (*bms)
  1376. *bms = '\0';
  1377. else
  1378. break;
  1379. ++bms;
  1380. ++i;
  1381. }
  1382. return TRUE;
  1383. }
  1384. /*
  1385. * Get the real path to a bookmark
  1386. *
  1387. * NULL is returned in case of no match, path resolution failure etc.
  1388. * buf would be modified, so check return value before access
  1389. */
  1390. static char *get_bm_loc(int key, char *buf)
  1391. {
  1392. int r;
  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. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1402. } else
  1403. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1404. return buf;
  1405. }
  1406. }
  1407. DPRINTF_S("Invalid key");
  1408. return NULL;
  1409. }
  1410. static void resetdircolor(mode_t mode)
  1411. {
  1412. if (cfg.dircolor && !S_ISDIR(mode)) {
  1413. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  1414. cfg.dircolor = 0;
  1415. }
  1416. }
  1417. /*
  1418. * Replace escape characters in a string with '?'
  1419. * Adjust string length to maxcols if > 0;
  1420. *
  1421. * Interestingly, note that unescape() uses g_buf. What happens if
  1422. * str also points to g_buf? In this case we assume that the caller
  1423. * acknowledges that it's OK to lose the data in g_buf after this
  1424. * call to unescape().
  1425. * The API, on its part, first converts str to multibyte (after which
  1426. * it doesn't touch str anymore). Only after that it starts modifying
  1427. * g_buf. This is a phased operation.
  1428. */
  1429. static char *unescape(const char *str, uint maxcols)
  1430. {
  1431. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1432. static wchar_t *buf;
  1433. static size_t len;
  1434. /* Convert multi-byte to wide char */
  1435. len = mbstowcs(wbuf, str, PATH_MAX);
  1436. g_buf[0] = '\0';
  1437. buf = wbuf;
  1438. if (maxcols && len > maxcols) {
  1439. len = wcswidth(wbuf, len);
  1440. if (len > maxcols)
  1441. wbuf[maxcols] = 0;
  1442. }
  1443. while (*buf) {
  1444. if (*buf <= '\x1f' || *buf == '\x7f')
  1445. *buf = '\?';
  1446. ++buf;
  1447. }
  1448. /* Convert wide char to multi-byte */
  1449. wcstombs(g_buf, wbuf, PATH_MAX);
  1450. return g_buf;
  1451. }
  1452. static char *coolsize(off_t size)
  1453. {
  1454. static const char * const U = "BKMGTPEZY";
  1455. static char size_buf[12]; /* Buffer to hold human readable size */
  1456. static off_t rem;
  1457. static int i;
  1458. i = 0;
  1459. rem = 0;
  1460. while (size > 1024) {
  1461. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1462. size >>= 10;
  1463. ++i;
  1464. }
  1465. if (i == 1) {
  1466. rem = (rem * 1000) >> 10;
  1467. rem /= 10;
  1468. if (rem % 10 >= 5) {
  1469. rem = (rem / 10) + 1;
  1470. if (rem == 10) {
  1471. ++size;
  1472. rem = 0;
  1473. }
  1474. } else
  1475. rem /= 10;
  1476. } else if (i == 2) {
  1477. rem = (rem * 1000) >> 10;
  1478. if (rem % 10 >= 5) {
  1479. rem = (rem / 10) + 1;
  1480. if (rem == 100) {
  1481. ++size;
  1482. rem = 0;
  1483. }
  1484. } else
  1485. rem /= 10;
  1486. } else if (i > 0) {
  1487. rem = (rem * 10000) >> 10;
  1488. if (rem % 10 >= 5) {
  1489. rem = (rem / 10) + 1;
  1490. if (rem == 1000) {
  1491. ++size;
  1492. rem = 0;
  1493. }
  1494. } else
  1495. rem /= 10;
  1496. }
  1497. if (i > 0 && i < 6)
  1498. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1499. else
  1500. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1501. return size_buf;
  1502. }
  1503. static char *get_file_sym(mode_t mode)
  1504. {
  1505. static char ind[2] = "\0\0";
  1506. switch (mode & S_IFMT) {
  1507. case S_IFREG:
  1508. if (mode & 0100)
  1509. ind[0] = '*';
  1510. break;
  1511. case S_IFDIR:
  1512. ind[0] = '/';
  1513. break;
  1514. case S_IFLNK:
  1515. ind[0] = '@';
  1516. break;
  1517. case S_IFSOCK:
  1518. ind[0] = '=';
  1519. break;
  1520. case S_IFIFO:
  1521. ind[0] = '|';
  1522. break;
  1523. case S_IFBLK: // fallthrough
  1524. case S_IFCHR:
  1525. break;
  1526. default:
  1527. ind[0] = '?';
  1528. break;
  1529. }
  1530. return ind;
  1531. }
  1532. static void printent(struct entry *ent, int sel, uint namecols)
  1533. {
  1534. static char *pname;
  1535. pname = unescape(ent->name, namecols);
  1536. /* Directories are always shown on top */
  1537. resetdircolor(ent->mode);
  1538. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1539. }
  1540. static void printent_long(struct entry *ent, int sel, uint namecols)
  1541. {
  1542. static char buf[18], *pname;
  1543. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1544. pname = unescape(ent->name, namecols);
  1545. /* Directories are always shown on top */
  1546. resetdircolor(ent->mode);
  1547. if (sel)
  1548. attron(A_REVERSE);
  1549. switch (ent->mode & S_IFMT) {
  1550. case S_IFREG:
  1551. if (ent->mode & 0100)
  1552. printw(" %-16.16s %8.8s* %s*\n", buf,
  1553. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1554. else
  1555. printw(" %-16.16s %8.8s %s\n", buf,
  1556. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1557. break;
  1558. case S_IFDIR:
  1559. if (cfg.blkorder)
  1560. printw(" %-16.16s %8.8s/ %s/\n",
  1561. buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1562. else
  1563. printw(" %-16.16s / %s/\n", buf, pname);
  1564. break;
  1565. case S_IFLNK:
  1566. if (ent->flags & SYMLINK_TO_DIR)
  1567. printw(" %-16.16s @/ %s@\n", buf, pname);
  1568. else
  1569. printw(" %-16.16s @ %s@\n", buf, pname);
  1570. break;
  1571. case S_IFSOCK:
  1572. printw(" %-16.16s = %s=\n", buf, pname);
  1573. break;
  1574. case S_IFIFO:
  1575. printw(" %-16.16s | %s|\n", buf, pname);
  1576. break;
  1577. case S_IFBLK:
  1578. printw(" %-16.16s b %s\n", buf, pname);
  1579. break;
  1580. case S_IFCHR:
  1581. printw(" %-16.16s c %s\n", buf, pname);
  1582. break;
  1583. default:
  1584. printw(" %-16.16s %8.8s? %s?\n", buf,
  1585. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  1586. break;
  1587. }
  1588. if (sel)
  1589. attroff(A_REVERSE);
  1590. }
  1591. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1592. static char get_fileind(mode_t mode, char *desc)
  1593. {
  1594. static char c;
  1595. switch (mode & S_IFMT) {
  1596. case S_IFREG:
  1597. c = '-';
  1598. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1599. if (mode & 0100)
  1600. /* Length of string "regular file" is 12 */
  1601. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12);
  1602. break;
  1603. case S_IFDIR:
  1604. c = 'd';
  1605. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1606. break;
  1607. case S_IFLNK:
  1608. c = 'l';
  1609. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1610. break;
  1611. case S_IFSOCK:
  1612. c = 's';
  1613. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1614. break;
  1615. case S_IFIFO:
  1616. c = 'p';
  1617. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1618. break;
  1619. case S_IFBLK:
  1620. c = 'b';
  1621. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1622. break;
  1623. case S_IFCHR:
  1624. c = 'c';
  1625. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1626. break;
  1627. default:
  1628. /* Unknown type -- possibly a regular file? */
  1629. c = '?';
  1630. desc[0] = '\0';
  1631. break;
  1632. }
  1633. return c;
  1634. }
  1635. /* Convert a mode field into "ls -l" type perms field. */
  1636. static char *get_lsperms(mode_t mode, char *desc)
  1637. {
  1638. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1639. static char bits[11] = {'\0'};
  1640. bits[0] = get_fileind(mode, desc);
  1641. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1642. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1643. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1644. if (mode & S_ISUID)
  1645. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1646. if (mode & S_ISGID)
  1647. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1648. if (mode & S_ISVTX)
  1649. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1650. return bits;
  1651. }
  1652. /*
  1653. * Gets only a single line (that's what we need
  1654. * for now) or shows full command output in pager.
  1655. *
  1656. * If page is valid, returns NULL
  1657. */
  1658. static char *get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, bool page)
  1659. {
  1660. pid_t pid;
  1661. int pipefd[2];
  1662. FILE *pf;
  1663. int tmp, flags;
  1664. char *ret = NULL;
  1665. if (pipe(pipefd) == -1)
  1666. errexit();
  1667. for (tmp = 0; tmp < 2; ++tmp) {
  1668. /* Get previous flags */
  1669. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1670. /* Set bit for non-blocking flag */
  1671. flags |= O_NONBLOCK;
  1672. /* Change flags on fd */
  1673. fcntl(pipefd[tmp], F_SETFL, flags);
  1674. }
  1675. pid = fork();
  1676. if (pid == 0) {
  1677. /* In child */
  1678. close(pipefd[0]);
  1679. dup2(pipefd[1], STDOUT_FILENO);
  1680. dup2(pipefd[1], STDERR_FILENO);
  1681. close(pipefd[1]);
  1682. execlp(file, file, arg1, arg2, NULL);
  1683. _exit(1);
  1684. }
  1685. /* In parent */
  1686. waitpid(pid, &tmp, 0);
  1687. close(pipefd[1]);
  1688. if (!page) {
  1689. pf = fdopen(pipefd[0], "r");
  1690. if (pf) {
  1691. ret = fgets(buf, bytes, pf);
  1692. close(pipefd[0]);
  1693. }
  1694. return ret;
  1695. }
  1696. pid = fork();
  1697. if (pid == 0) {
  1698. /* Show in pager in child */
  1699. dup2(pipefd[0], STDIN_FILENO);
  1700. close(pipefd[0]);
  1701. execlp(pager, pager, NULL);
  1702. _exit(1);
  1703. }
  1704. /* In parent */
  1705. waitpid(pid, &tmp, 0);
  1706. close(pipefd[0]);
  1707. return NULL;
  1708. }
  1709. static bool getutil(char *util) {
  1710. if (!get_output(g_buf, CMD_LEN_MAX, "which", util, NULL, FALSE))
  1711. return FALSE;
  1712. return TRUE;
  1713. }
  1714. static char *xgetpwuid(uid_t uid)
  1715. {
  1716. struct passwd *pwd = getpwuid(uid);
  1717. if (!pwd)
  1718. return utils[UNKNOWN];
  1719. return pwd->pw_name;
  1720. }
  1721. static char *xgetgrgid(gid_t gid)
  1722. {
  1723. struct group *grp = getgrgid(gid);
  1724. if (!grp)
  1725. return utils[UNKNOWN];
  1726. return grp->gr_name;
  1727. }
  1728. /*
  1729. * Follows the stat(1) output closely
  1730. */
  1731. static bool show_stats(char *fpath, char *fname, struct stat *sb)
  1732. {
  1733. char desc[DESCRIPTOR_LEN];
  1734. char *perms = get_lsperms(sb->st_mode, desc);
  1735. char *p, *begin = g_buf;
  1736. if (g_tmpfpath[0])
  1737. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE],
  1738. HOME_LEN_MAX - g_tmpfplen);
  1739. else {
  1740. printmsg(messages[STR_NOHOME_ID]);
  1741. return FALSE;
  1742. }
  1743. int fd = mkstemp(g_tmpfpath);
  1744. if (fd == -1)
  1745. return FALSE;
  1746. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1747. /* Show file name or 'symlink' -> 'target' */
  1748. if (perms[0] == 'l') {
  1749. /* Note that CMD_LEN_MAX > PATH_MAX */
  1750. ssize_t len = readlink(fpath, g_buf, CMD_LEN_MAX);
  1751. if (len != -1) {
  1752. struct stat tgtsb;
  1753. if (!stat(fpath, &tgtsb) && S_ISDIR(tgtsb.st_mode))
  1754. g_buf[len++] = '/';
  1755. g_buf[len] = '\0';
  1756. /*
  1757. * We pass g_buf but unescape() operates on g_buf too!
  1758. * Read the API notes for information on how this works.
  1759. */
  1760. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1761. }
  1762. }
  1763. /* Show size, blocks, file type */
  1764. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1765. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1766. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1767. #else
  1768. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1769. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1770. #endif
  1771. /* Show containing device, inode, hardlink count */
  1772. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1773. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1774. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1775. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1776. #else
  1777. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1778. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1779. #endif
  1780. /* Show major, minor number for block or char device */
  1781. if (perms[0] == 'b' || perms[0] == 'c')
  1782. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1783. /* Show permissions, owner, group */
  1784. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1785. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1786. sb->st_mode & 7, perms, sb->st_uid, xgetpwuid(sb->st_uid),
  1787. sb->st_gid, xgetgrgid(sb->st_gid));
  1788. /* Show last access time */
  1789. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1790. dprintf(fd, "\n\n Access: %s", g_buf);
  1791. /* Show last modification time */
  1792. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1793. dprintf(fd, "\n Modify: %s", g_buf);
  1794. /* Show last status change time */
  1795. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1796. dprintf(fd, "\n Change: %s", g_buf);
  1797. if (S_ISREG(sb->st_mode)) {
  1798. /* Show file(1) output */
  1799. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  1800. if (p) {
  1801. dprintf(fd, "\n\n ");
  1802. while (*p) {
  1803. if (*p == ',') {
  1804. *p = '\0';
  1805. dprintf(fd, " %s\n", begin);
  1806. begin = p + 1;
  1807. }
  1808. ++p;
  1809. }
  1810. dprintf(fd, " %s", begin);
  1811. }
  1812. dprintf(fd, "\n\n");
  1813. } else
  1814. dprintf(fd, "\n\n\n");
  1815. close(fd);
  1816. spawn(pager, pager_arg, g_tmpfpath, NULL, F_NORMAL);
  1817. unlink(g_tmpfpath);
  1818. return TRUE;
  1819. }
  1820. static size_t get_fs_info(const char *path, bool type)
  1821. {
  1822. static struct statvfs svb;
  1823. if (statvfs(path, &svb) == -1)
  1824. return 0;
  1825. if (type == CAPACITY)
  1826. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1827. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1828. }
  1829. static bool show_mediainfo(char *fpath, char *arg)
  1830. {
  1831. if (!getutil(utils[cfg.metaviewer]))
  1832. return FALSE;
  1833. exitcurses();
  1834. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, TRUE);
  1835. refresh();
  1836. return TRUE;
  1837. }
  1838. static bool handle_archive(char *fpath, char *arg, char *dir)
  1839. {
  1840. if (!getutil(utils[ATOOL]))
  1841. return FALSE;
  1842. if (arg[1] == 'x')
  1843. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1844. else {
  1845. exitcurses();
  1846. get_output(NULL, 0, utils[ATOOL], arg, fpath, TRUE);
  1847. refresh();
  1848. }
  1849. return TRUE;
  1850. }
  1851. /*
  1852. * The help string tokens (each line) start with a HEX value
  1853. * which indicates the number of spaces to print before the
  1854. * particular token. This method was chosen instead of a flat
  1855. * string because the number of bytes in help was increasing
  1856. * the binary size by around a hundred bytes. This would only
  1857. * have increased as we keep adding new options.
  1858. */
  1859. static bool show_help(char *path)
  1860. {
  1861. if (g_tmpfpath[0])
  1862. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE],
  1863. HOME_LEN_MAX - g_tmpfplen);
  1864. else {
  1865. printmsg(messages[STR_NOHOME_ID]);
  1866. return FALSE;
  1867. }
  1868. int i = 0, fd = mkstemp(g_tmpfpath);
  1869. char *start, *end;
  1870. static char helpstr[] = {
  1871. "0\n"
  1872. "1NAVIGATION\n"
  1873. "5↑, k, ^P Up PgUp, ^U Scroll up\n"
  1874. "5↓, j, ^N Down PgDn, ^D Scroll down\n"
  1875. "5←, h, ^H Parent dir ~ Go HOME\n"
  1876. "2↵, →, l, ^M Open file/dir & Start dir\n"
  1877. "2Home, g, ^A First entry - Last visited dir\n"
  1878. "3End, G, ^E Last entry . Toggle show hidden\n"
  1879. "c/ Filter Ins, ^T Toggle nav-as-you-type\n"
  1880. "cb Pin current dir ^W Go to pinned dir\n"
  1881. "6Tab, ^I Next context d Toggle detail view\n"
  1882. "8`, ^/ Leader key N, LeadN Go to/create context N\n"
  1883. "aEsc Exit prompt ^L Redraw/clear prompt\n"
  1884. "b^G Quit and cd q Quit context\n"
  1885. "8Q, ^Q Quit ? Help, config\n"
  1886. "1FILES\n"
  1887. "b^O Open with... n Create new/link\n"
  1888. "cD File details ^R Rename entry\n"
  1889. "8⎵, ^K Copy entry path r Open dir in vidir\n"
  1890. "8Y, ^Y Toggle selection y List selection\n"
  1891. "cP Copy selection X Delete selection\n"
  1892. "cV Move selection ^X Delete entry\n"
  1893. "cf Archive entry F List archive\n"
  1894. "b^F Extract archive m, M Brief/full media info\n"
  1895. "ce Edit in EDITOR p Open in PAGER\n"
  1896. "1ORDER TOGGLES\n"
  1897. "b^J Disk usage S Apparent du\n"
  1898. "ct Modification time s Size\n"
  1899. "1MISC\n"
  1900. "8!, ^] Spawn SHELL in dir C Execute entry\n"
  1901. "8R, ^V Run custom script L Lock terminal\n"
  1902. "b^S Run a command N Take note\n"};
  1903. if (fd == -1)
  1904. return FALSE;
  1905. start = end = helpstr;
  1906. while (*end) {
  1907. while (*end != '\n')
  1908. ++end;
  1909. if (start == end) {
  1910. ++end;
  1911. continue;
  1912. }
  1913. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1914. start = ++end;
  1915. }
  1916. dprintf(fd, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  1917. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  1918. if (getenv(env_cfg[NNN_BMS])) {
  1919. dprintf(fd, "BOOKMARKS\n");
  1920. for (; i < BM_MAX; ++i)
  1921. if (bookmark[i].key)
  1922. dprintf(fd, " %c: %s\n", (char)bookmark[i].key, bookmark[i].loc);
  1923. else
  1924. break;
  1925. dprintf(fd, "\n");
  1926. }
  1927. for (i = NNN_OPENER; i <= NNN_TMPFILE; ++i) {
  1928. start = getenv(env_cfg[i]);
  1929. if (start)
  1930. dprintf(fd, "%s: %s\n", env_cfg[i], start);
  1931. }
  1932. if (g_cppath[0])
  1933. dprintf(fd, "COPY FILE: %s\n", g_cppath);
  1934. for (i = NNN_USE_EDITOR; i <= NNN_PLAIN_FILTER; ++i) {
  1935. if (getenv(env_cfg[i]))
  1936. dprintf(fd, "%s: 1\n", env_cfg[i]);
  1937. }
  1938. dprintf(fd, "\n");
  1939. start = getenv(envs[PWD]);
  1940. if (start)
  1941. dprintf(fd, "%s: %s\n", envs[PWD], start);
  1942. if (getenv(envs[SHELL]))
  1943. dprintf(fd, "%s: %s %s\n", envs[SHELL], shell, shell_arg);
  1944. start = getenv(envs[SHLVL]);
  1945. if (start)
  1946. dprintf(fd, "%s: %s\n", envs[SHLVL], start);
  1947. if (getenv(envs[VISUAL]))
  1948. dprintf(fd, "%s: %s\n", envs[VISUAL], editor);
  1949. else if (getenv(envs[EDITOR]))
  1950. dprintf(fd, "%s: %s\n", envs[EDITOR], editor);
  1951. if (getenv(envs[PAGER]))
  1952. dprintf(fd, "%s: %s %s\n", envs[PAGER], pager, pager_arg);
  1953. dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  1954. close(fd);
  1955. spawn(pager, pager_arg, g_tmpfpath, NULL, F_NORMAL);
  1956. unlink(g_tmpfpath);
  1957. return TRUE;
  1958. }
  1959. static int sum_bsizes(const char *fpath, const struct stat *sb,
  1960. int typeflag, struct FTW *ftwbuf)
  1961. {
  1962. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1963. ent_blocks += sb->st_blocks;
  1964. ++num_files;
  1965. return 0;
  1966. }
  1967. static int sum_sizes(const char *fpath, const struct stat *sb,
  1968. int typeflag, struct FTW *ftwbuf)
  1969. {
  1970. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  1971. ent_blocks += sb->st_size;
  1972. ++num_files;
  1973. return 0;
  1974. }
  1975. static void dentfree(struct entry *dents)
  1976. {
  1977. free(pnamebuf);
  1978. free(dents);
  1979. }
  1980. static int dentfill(char *path, struct entry **dents)
  1981. {
  1982. static DIR *dirp;
  1983. static struct dirent *dp;
  1984. static char *namep, *pnb;
  1985. static struct entry *dentp;
  1986. static size_t off, namebuflen = NAMEBUF_INCR;
  1987. static ulong num_saved;
  1988. static int fd, n, count;
  1989. static struct stat sb_path, sb;
  1990. off = 0;
  1991. dirp = opendir(path);
  1992. if (dirp == NULL)
  1993. return 0;
  1994. fd = dirfd(dirp);
  1995. n = 0;
  1996. if (cfg.blkorder) {
  1997. num_files = 0;
  1998. dir_blocks = 0;
  1999. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  2000. printwarn();
  2001. return 0;
  2002. }
  2003. }
  2004. while ((dp = readdir(dirp)) != NULL) {
  2005. namep = dp->d_name;
  2006. /* Skip self and parent */
  2007. if ((namep[0] == '.' && (namep[1] == '\0' ||
  2008. (namep[1] == '.' && namep[2] == '\0'))))
  2009. continue;
  2010. if (!cfg.showhidden && namep[0] == '.') {
  2011. if (!cfg.blkorder)
  2012. continue;
  2013. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  2014. continue;
  2015. if (S_ISDIR(sb.st_mode)) {
  2016. if (sb_path.st_dev == sb.st_dev) {
  2017. ent_blocks = 0;
  2018. mkpath(path, namep, g_buf);
  2019. if (nftw(g_buf, nftw_fn, open_max,
  2020. FTW_MOUNT | FTW_PHYS) == -1) {
  2021. printmsg(messages[STR_NFTWFAIL_ID]);
  2022. dir_blocks += (cfg.apparentsz
  2023. ? sb.st_size
  2024. : sb.st_blocks);
  2025. } else
  2026. dir_blocks += ent_blocks;
  2027. }
  2028. } else {
  2029. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2030. ++num_files;
  2031. }
  2032. continue;
  2033. }
  2034. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  2035. DPRINTF_S(namep);
  2036. continue;
  2037. }
  2038. if (n == total_dents) {
  2039. total_dents += ENTRY_INCR;
  2040. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  2041. if (*dents == NULL) {
  2042. free(pnamebuf);
  2043. errexit();
  2044. }
  2045. DPRINTF_P(*dents);
  2046. }
  2047. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  2048. if (namebuflen - off < NAME_MAX + 1) {
  2049. namebuflen += NAMEBUF_INCR;
  2050. pnb = pnamebuf;
  2051. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  2052. if (pnamebuf == NULL) {
  2053. free(*dents);
  2054. errexit();
  2055. }
  2056. DPRINTF_P(pnamebuf);
  2057. /* realloc() may result in memory move, we must re-adjust if that happens */
  2058. if (pnb != pnamebuf) {
  2059. dentp = *dents;
  2060. dentp->name = pnamebuf;
  2061. for (count = 1; count < n; ++dentp, ++count)
  2062. /* Current filename starts at last filename start + length */
  2063. (dentp + 1)->name = (char *)((size_t)dentp->name
  2064. + dentp->nlen);
  2065. }
  2066. }
  2067. dentp = *dents + n;
  2068. /* Copy file name */
  2069. dentp->name = (char *)((size_t)pnamebuf + off);
  2070. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  2071. off += dentp->nlen;
  2072. /* Copy other fields */
  2073. dentp->mode = sb.st_mode;
  2074. dentp->t = sb.st_mtime;
  2075. dentp->size = sb.st_size;
  2076. if (cfg.blkorder) {
  2077. if (S_ISDIR(sb.st_mode)) {
  2078. ent_blocks = 0;
  2079. num_saved = num_files + 1;
  2080. mkpath(path, namep, g_buf);
  2081. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  2082. printmsg(messages[STR_NFTWFAIL_ID]);
  2083. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2084. } else
  2085. dentp->blocks = ent_blocks;
  2086. if (sb_path.st_dev == sb.st_dev)
  2087. dir_blocks += dentp->blocks;
  2088. else
  2089. num_files = num_saved;
  2090. } else {
  2091. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2092. dir_blocks += dentp->blocks;
  2093. ++num_files;
  2094. }
  2095. }
  2096. /* Flag if this is a symlink to a dir */
  2097. if (S_ISLNK(sb.st_mode))
  2098. if (!fstatat(fd, namep, &sb, 0)) {
  2099. if (S_ISDIR(sb.st_mode))
  2100. dentp->flags |= SYMLINK_TO_DIR;
  2101. else
  2102. dentp->flags &= ~SYMLINK_TO_DIR;
  2103. }
  2104. ++n;
  2105. }
  2106. /* Should never be null */
  2107. if (closedir(dirp) == -1) {
  2108. dentfree(*dents);
  2109. errexit();
  2110. }
  2111. return n;
  2112. }
  2113. /*
  2114. * Return the position of the matching entry or 0 otherwise
  2115. * Note there's no NULL check for fname
  2116. */
  2117. static int dentfind(const char *fname, int n)
  2118. {
  2119. static int i;
  2120. DPRINTF_S(fname);
  2121. for (i = 0; i < n; ++i)
  2122. if (xstrcmp(fname, dents[i].name) == 0)
  2123. return i;
  2124. return 0;
  2125. }
  2126. static void populate(char *path, char *lastname)
  2127. {
  2128. if (cfg.blkorder) {
  2129. printmsg("calculating...");
  2130. refresh();
  2131. }
  2132. #ifdef DEBUGMODE
  2133. struct timespec ts1, ts2;
  2134. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  2135. #endif
  2136. ndents = dentfill(path, &dents);
  2137. if (!ndents)
  2138. return;
  2139. qsort(dents, ndents, sizeof(*dents), entrycmp);
  2140. #ifdef DEBUGMODE
  2141. clock_gettime(CLOCK_REALTIME, &ts2);
  2142. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  2143. #endif
  2144. /* Find cur from history */
  2145. /* No NULL check for lastname, always points to an array */
  2146. if (!*lastname)
  2147. cur = 0;
  2148. else
  2149. dentfind(lastname, ndents);
  2150. }
  2151. static void redraw(char *path)
  2152. {
  2153. static char buf[NAME_MAX + 65] __attribute__ ((aligned));
  2154. static size_t ncols;
  2155. static int nlines, i, attrs;
  2156. static bool mode_changed;
  2157. mode_changed = FALSE;
  2158. nlines = MIN(LINES - 4, ndents);
  2159. /* Clear screen */
  2160. erase();
  2161. #ifdef DIR_LIMITED_COPY
  2162. if (cfg.copymode)
  2163. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  2164. cfg.copymode = 0;
  2165. DPRINTF_S("selection off");
  2166. }
  2167. #endif
  2168. /* Fail redraw if < than 11 columns, context info prints 10 chars */
  2169. if (COLS < 11) {
  2170. printmsg("too few columns!");
  2171. return;
  2172. }
  2173. /* Strip trailing slashes */
  2174. for (i = strlen(path) - 1; i > 0; --i)
  2175. if (path[i] == '/')
  2176. path[i] = '\0';
  2177. else
  2178. break;
  2179. DPRINTF_D(cur);
  2180. DPRINTF_S(path);
  2181. if (!realpath(path, g_buf)) {
  2182. printwarn();
  2183. return;
  2184. }
  2185. ncols = COLS;
  2186. if (ncols > PATH_MAX)
  2187. ncols = PATH_MAX;
  2188. printw("[");
  2189. for (i = 0; i < CTX_MAX; ++i) {
  2190. /* Print current context in reverse */
  2191. if (cfg.curctx == i) {
  2192. if (cfg.showcolor)
  2193. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_REVERSE;
  2194. else
  2195. attrs = A_REVERSE;
  2196. attron(attrs);
  2197. printw("%d", i + 1);
  2198. attroff(attrs);
  2199. printw(" ");
  2200. } else if (g_ctx[i].c_cfg.ctxactive) {
  2201. if (cfg.showcolor)
  2202. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_UNDERLINE;
  2203. else
  2204. attrs = A_UNDERLINE;
  2205. attron(attrs);
  2206. printw("%d", i + 1);
  2207. attroff(attrs);
  2208. printw(" ");
  2209. } else
  2210. printw("%d ", i + 1);
  2211. }
  2212. printw("\b] "); /* 10 chars printed in total for contexts - "[1 2 3 4] " */
  2213. attron(A_UNDERLINE);
  2214. /* No text wrapping in cwd line */
  2215. g_buf[ncols - 11] = '\0';
  2216. printw("%s\n\n", g_buf);
  2217. attroff(A_UNDERLINE);
  2218. /* Fallback to light mode if less than 35 columns */
  2219. if (ncols < 35 && cfg.showdetail) {
  2220. cfg.showdetail ^= 1;
  2221. printptr = &printent;
  2222. mode_changed = TRUE;
  2223. }
  2224. /* Calculate the number of cols available to print entry name */
  2225. if (cfg.showdetail)
  2226. ncols -= 32;
  2227. else
  2228. ncols -= 5;
  2229. if (cfg.showcolor) {
  2230. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2231. cfg.dircolor = 1;
  2232. }
  2233. /* Print listing */
  2234. if (cur < (nlines >> 1)) {
  2235. for (i = 0; i < nlines; ++i)
  2236. printptr(&dents[i], i == cur, ncols);
  2237. } else if (cur >= ndents - (nlines >> 1)) {
  2238. for (i = ndents - nlines; i < ndents; ++i)
  2239. printptr(&dents[i], i == cur, ncols);
  2240. } else {
  2241. static int odd;
  2242. odd = ISODD(nlines);
  2243. nlines >>= 1;
  2244. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  2245. printptr(&dents[i], i == cur, ncols);
  2246. }
  2247. /* Must reset e.g. no files in dir */
  2248. if (cfg.dircolor) {
  2249. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2250. cfg.dircolor = 0;
  2251. }
  2252. if (cfg.showdetail) {
  2253. if (ndents) {
  2254. static char sort[9];
  2255. if (cfg.mtimeorder)
  2256. xstrlcpy(sort, "by time ", 9);
  2257. else if (cfg.sizeorder)
  2258. xstrlcpy(sort, "by size ", 9);
  2259. else
  2260. sort[0] = '\0';
  2261. /* We need to show filename as it may be truncated in directory listing */
  2262. if (!cfg.blkorder)
  2263. snprintf(buf, NAME_MAX + 65, "%d/%d %s[%s%s]",
  2264. cur + 1, ndents, sort, unescape(dents[cur].name, NAME_MAX),
  2265. get_file_sym(dents[cur].mode));
  2266. else {
  2267. i = snprintf(buf, 64, "%d/%d ", cur + 1, ndents);
  2268. if (cfg.apparentsz)
  2269. buf[i++] = 'a';
  2270. else
  2271. buf[i++] = 'd';
  2272. i += snprintf(buf + i, 64, "u: %s (%lu files) ",
  2273. coolsize(dir_blocks << BLK_SHIFT), num_files);
  2274. snprintf(buf + i, NAME_MAX, "vol: %s free [%s%s]",
  2275. coolsize(get_fs_info(path, FREE)),
  2276. unescape(dents[cur].name, NAME_MAX),
  2277. get_file_sym(dents[cur].mode));
  2278. }
  2279. printmsg(buf);
  2280. } else
  2281. printmsg("0 items");
  2282. }
  2283. if (mode_changed) {
  2284. cfg.showdetail ^= 1;
  2285. printptr = &printent_long;
  2286. }
  2287. }
  2288. static void browse(char *ipath)
  2289. {
  2290. char newpath[PATH_MAX] __attribute__ ((aligned));
  2291. char mark[PATH_MAX] __attribute__ ((aligned));
  2292. char rundir[PATH_MAX] __attribute__ ((aligned));
  2293. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  2294. char *path, *lastdir, *lastname;
  2295. char *dir, *tmp;
  2296. struct stat sb;
  2297. int r = -1, fd, presel, ncp = 0, copystartid = 0, copyendid = 0;
  2298. enum action sel;
  2299. bool dir_changed = FALSE;
  2300. /* setup first context */
  2301. xstrlcpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  2302. path = g_ctx[0].c_path;
  2303. xstrlcpy(g_ctx[0].c_init, ipath, PATH_MAX); /* start directory */
  2304. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = newpath[0] = mark[0] = '\0';
  2305. rundir[0] = runfile[0] = '\0';
  2306. lastdir = g_ctx[0].c_last; /* last visited directory */
  2307. lastname = g_ctx[0].c_name; /* last visited filename */
  2308. g_ctx[0].c_cfg = cfg; /* current configuration */
  2309. if (cfg.filtermode)
  2310. presel = FILTER;
  2311. else
  2312. presel = 0;
  2313. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2314. if (dents == NULL)
  2315. errexit();
  2316. DPRINTF_P(dents);
  2317. /* Allocate buffer to hold names */
  2318. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2319. if (pnamebuf == NULL) {
  2320. free(dents);
  2321. errexit();
  2322. }
  2323. DPRINTF_P(pnamebuf);
  2324. begin:
  2325. #ifdef LINUX_INOTIFY
  2326. if ((presel == FILTER || dir_changed) && inotify_wd >= 0) {
  2327. inotify_rm_watch(inotify_fd, inotify_wd);
  2328. inotify_wd = -1;
  2329. dir_changed = FALSE;
  2330. }
  2331. #elif defined(BSD_KQUEUE)
  2332. if ((presel == FILTER || dir_changed) && event_fd >= 0) {
  2333. close(event_fd);
  2334. event_fd = -1;
  2335. dir_changed = FALSE;
  2336. }
  2337. #endif
  2338. /* Can fail when permissions change while browsing.
  2339. * It's assumed that path IS a directory when we are here.
  2340. */
  2341. if (access(path, R_OK) == -1) {
  2342. printwarn();
  2343. goto nochange;
  2344. }
  2345. populate(path, lastname);
  2346. #ifdef LINUX_INOTIFY
  2347. if (inotify_wd == -1)
  2348. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2349. #elif defined(BSD_KQUEUE)
  2350. if (event_fd == -1) {
  2351. #if defined(O_EVTONLY)
  2352. event_fd = open(path, O_EVTONLY);
  2353. #else
  2354. event_fd = open(path, O_RDONLY);
  2355. #endif
  2356. if (event_fd >= 0)
  2357. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  2358. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2359. }
  2360. #endif
  2361. while (1) {
  2362. redraw(path);
  2363. nochange:
  2364. /* Exit if parent has exited */
  2365. if (getppid() == 1)
  2366. _exit(0);
  2367. sel = nextsel(&presel);
  2368. switch (sel) {
  2369. case SEL_BACK:
  2370. /* There is no going back */
  2371. if (istopdir(path)) {
  2372. /* Continue in navigate-as-you-type mode, if enabled */
  2373. if (cfg.filtermode)
  2374. presel = FILTER;
  2375. goto nochange;
  2376. }
  2377. dir = xdirname(path);
  2378. if (access(dir, R_OK) == -1) {
  2379. printwarn();
  2380. goto nochange;
  2381. }
  2382. /* Save history */
  2383. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  2384. /* Save last working directory */
  2385. xstrlcpy(lastdir, path, PATH_MAX);
  2386. xstrlcpy(path, dir, PATH_MAX);
  2387. setdirwatch();
  2388. goto begin;
  2389. case SEL_NAV_IN: // fallthrough
  2390. case SEL_GOIN:
  2391. /* Cannot descend in empty directories */
  2392. if (!ndents)
  2393. goto begin;
  2394. mkpath(path, dents[cur].name, newpath);
  2395. DPRINTF_S(newpath);
  2396. /* Cannot use stale data in entry, file may be missing by now */
  2397. if (stat(newpath, &sb) == -1) {
  2398. printwarn();
  2399. goto nochange;
  2400. }
  2401. DPRINTF_U(sb.st_mode);
  2402. switch (sb.st_mode & S_IFMT) {
  2403. case S_IFDIR:
  2404. if (access(newpath, R_OK) == -1) {
  2405. printwarn();
  2406. goto nochange;
  2407. }
  2408. /* Save last working directory */
  2409. xstrlcpy(lastdir, path, PATH_MAX);
  2410. xstrlcpy(path, newpath, PATH_MAX);
  2411. lastname[0] = '\0';
  2412. setdirwatch();
  2413. goto begin;
  2414. case S_IFREG:
  2415. {
  2416. /* If opened as vim plugin and Enter/^M pressed, pick */
  2417. if (cfg.picker && sel == SEL_GOIN) {
  2418. r = mkpath(path, dents[cur].name, newpath);
  2419. appendfpath(newpath, r);
  2420. writecp(pcopybuf, copybufpos - 1);
  2421. dentfree(dents);
  2422. return;
  2423. }
  2424. /* If open file is disabled on right arrow or `l`, return */
  2425. if (cfg.nonavopen && sel == SEL_NAV_IN)
  2426. continue;
  2427. /* Handle script selection mode */
  2428. if (cfg.runscript) {
  2429. if (cfg.runctx != cfg.curctx)
  2430. continue;
  2431. /* Must be in script directory to select script */
  2432. if (strcmp(path, scriptpath) != 0)
  2433. continue;
  2434. mkpath(path, dents[cur].name, newpath);
  2435. xstrlcpy(path, rundir, PATH_MAX);
  2436. if (runfile[0]) {
  2437. xstrlcpy(lastname, runfile, NAME_MAX);
  2438. spawn(shell, newpath, lastname, path,
  2439. F_NORMAL | F_SIGINT);
  2440. runfile[0] = '\0';
  2441. } else
  2442. spawn(shell, newpath, NULL, path, F_NORMAL | F_SIGINT);
  2443. rundir[0] = '\0';
  2444. cfg.runscript = 0;
  2445. setdirwatch();
  2446. goto begin;
  2447. }
  2448. /* If NNN_USE_EDITOR is set, open text in EDITOR */
  2449. if (cfg.useeditor &&
  2450. get_output(g_buf, CMD_LEN_MAX, "file", FILE_OPTS, newpath, FALSE)
  2451. && g_buf[0] == 't' && g_buf[1] == 'e' && g_buf[2] == 'x'
  2452. && g_buf[3] == g_buf[0] && g_buf[4] == '/') {
  2453. if (!quote_run_sh_cmd(editor, newpath, path))
  2454. goto nochange;
  2455. continue;
  2456. }
  2457. if (!sb.st_size && cfg.restrict0b) {
  2458. printmsg("empty: use edit or open with");
  2459. goto nochange;
  2460. }
  2461. /* Invoke desktop opener as last resort */
  2462. spawn(opener, newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2463. continue;
  2464. }
  2465. default:
  2466. printmsg("unsupported file");
  2467. goto nochange;
  2468. }
  2469. case SEL_NEXT: // fallthrough
  2470. case SEL_PREV: // fallthrough
  2471. case SEL_PGDN: // fallthrough
  2472. case SEL_PGUP: // fallthrough
  2473. case SEL_HOME: // fallthrough
  2474. case SEL_END:
  2475. switch (sel) {
  2476. case SEL_NEXT:
  2477. if (cur < ndents - 1)
  2478. ++cur;
  2479. else if (ndents)
  2480. /* Roll over, set cursor to first entry */
  2481. cur = 0;
  2482. break;
  2483. case SEL_PREV:
  2484. if (cur > 0)
  2485. --cur;
  2486. else if (ndents)
  2487. /* Roll over, set cursor to last entry */
  2488. cur = ndents - 1;
  2489. break;
  2490. case SEL_PGDN:
  2491. if (cur < ndents - 1)
  2492. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2493. break;
  2494. case SEL_PGUP:
  2495. if (cur > 0)
  2496. cur -= MIN((LINES - 4) / 2, cur);
  2497. break;
  2498. case SEL_HOME:
  2499. cur = 0;
  2500. break;
  2501. default: /* case SEL_END */
  2502. cur = ndents - 1;
  2503. break;
  2504. }
  2505. break;
  2506. case SEL_CDHOME: // fallthrough
  2507. case SEL_CDBEGIN: // fallthrough
  2508. case SEL_CDLAST: // fallthrough
  2509. case SEL_VISIT:
  2510. switch (sel) {
  2511. case SEL_CDHOME:
  2512. dir = xgetenv("HOME", path);
  2513. break;
  2514. case SEL_CDBEGIN:
  2515. dir = ipath;
  2516. break;
  2517. case SEL_CDLAST:
  2518. dir = lastdir;
  2519. break;
  2520. default: /* case SEL_VISIT */
  2521. dir = mark;
  2522. break;
  2523. }
  2524. if (dir[0] == '\0') {
  2525. printmsg("not set");
  2526. goto nochange;
  2527. }
  2528. if (!xdiraccess(dir))
  2529. goto nochange;
  2530. if (strcmp(path, dir) == 0)
  2531. break;
  2532. /* SEL_CDLAST: dir pointing to lastdir */
  2533. xstrlcpy(newpath, dir, PATH_MAX);
  2534. /* Save last working directory */
  2535. xstrlcpy(lastdir, path, PATH_MAX);
  2536. xstrlcpy(path, newpath, PATH_MAX);
  2537. lastname[0] = '\0';
  2538. DPRINTF_S(path);
  2539. setdirwatch();
  2540. goto begin;
  2541. case SEL_LEADER: // fallthrough
  2542. case SEL_CYCLE: // fallthrough
  2543. case SEL_CTX1: // fallthrough
  2544. case SEL_CTX2: // fallthrough
  2545. case SEL_CTX3: // fallthrough
  2546. case SEL_CTX4:
  2547. if (sel == SEL_CYCLE)
  2548. fd = '>';
  2549. else if (sel >= SEL_CTX1 && sel <= SEL_CTX4)
  2550. fd = sel - SEL_CTX1 + '1';
  2551. else
  2552. fd = get_input(NULL);
  2553. switch (fd) {
  2554. case 'q': // fallthrough
  2555. case '~': // fallthrough
  2556. case '-': // fallthrough
  2557. case '&':
  2558. presel = fd;
  2559. goto nochange;
  2560. case '>': // fallthrough
  2561. case '.': // fallthrough
  2562. case '<': // fallthrough
  2563. case ',':
  2564. r = cfg.curctx;
  2565. if (fd == '>' || fd == '.')
  2566. do
  2567. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  2568. while (!g_ctx[r].c_cfg.ctxactive);
  2569. else
  2570. do
  2571. (r == 0) ? (r = CTX_MAX - 1) : --r;
  2572. while (!g_ctx[r].c_cfg.ctxactive); // fallthrough
  2573. fd = '1' + r; // fallthrough
  2574. case '1': // fallthrough
  2575. case '2': // fallthrough
  2576. case '3': // fallthrough
  2577. case '4':
  2578. r = fd - '1'; /* Save the next context id */
  2579. if (cfg.curctx == r) {
  2580. if (sel == SEL_CYCLE) {
  2581. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  2582. snprintf(newpath, PATH_MAX, "Create context %d? ('Enter' confirms)", r + 1);
  2583. fd = get_input(newpath);
  2584. if (fd != '\r')
  2585. continue;
  2586. } else
  2587. continue;
  2588. }
  2589. #ifdef DIR_LIMITED_COPY
  2590. g_crc = 0;
  2591. #endif
  2592. /* Save current context */
  2593. xstrlcpy(g_ctx[cfg.curctx].c_name, dents[cur].name, NAME_MAX + 1);
  2594. g_ctx[cfg.curctx].c_cfg = cfg;
  2595. if (g_ctx[r].c_cfg.ctxactive) /* Switch to saved context */
  2596. cfg = g_ctx[r].c_cfg;
  2597. else { /* Setup a new context from current context */
  2598. g_ctx[r].c_cfg.ctxactive = 1;
  2599. xstrlcpy(g_ctx[r].c_path, path, PATH_MAX);
  2600. xstrlcpy(g_ctx[r].c_init, path, PATH_MAX);
  2601. g_ctx[r].c_last[0] = '\0';
  2602. xstrlcpy(g_ctx[r].c_name, dents[cur].name, NAME_MAX + 1);
  2603. g_ctx[r].c_cfg = cfg;
  2604. g_ctx[r].c_cfg.runscript = 0;
  2605. }
  2606. /* Reset the pointers */
  2607. path = g_ctx[r].c_path;
  2608. ipath = g_ctx[r].c_init;
  2609. lastdir = g_ctx[r].c_last;
  2610. lastname = g_ctx[r].c_name;
  2611. cfg.curctx = r;
  2612. setdirwatch();
  2613. goto begin;
  2614. }
  2615. if (get_bm_loc(fd, newpath) == NULL) {
  2616. printmsg(messages[STR_INVBM_KEY]);
  2617. goto nochange;
  2618. }
  2619. if (!xdiraccess(newpath))
  2620. goto nochange;
  2621. if (strcmp(path, newpath) == 0)
  2622. break;
  2623. lastname[0] = '\0';
  2624. /* Save last working directory */
  2625. xstrlcpy(lastdir, path, PATH_MAX);
  2626. /* Save the newly opted dir in path */
  2627. xstrlcpy(path, newpath, PATH_MAX);
  2628. DPRINTF_S(path);
  2629. setdirwatch();
  2630. goto begin;
  2631. case SEL_PIN:
  2632. xstrlcpy(mark, path, PATH_MAX);
  2633. printmsg(mark);
  2634. goto nochange;
  2635. case SEL_FLTR:
  2636. presel = filterentries(path);
  2637. /* Save current */
  2638. if (ndents)
  2639. copycurname();
  2640. goto nochange;
  2641. case SEL_MFLTR: // fallthrough
  2642. case SEL_TOGGLEDOT: // fallthrough
  2643. case SEL_DETAIL: // fallthrough
  2644. case SEL_FSIZE: // fallthrough
  2645. case SEL_BSIZE: // fallthrough
  2646. case SEL_MTIME:
  2647. switch (sel) {
  2648. case SEL_MFLTR:
  2649. cfg.filtermode ^= 1;
  2650. if (cfg.filtermode) {
  2651. presel = FILTER;
  2652. goto nochange;
  2653. }
  2654. /* Start watching the directory */
  2655. dir_changed = TRUE;
  2656. break;
  2657. case SEL_TOGGLEDOT:
  2658. cfg.showhidden ^= 1;
  2659. break;
  2660. case SEL_DETAIL:
  2661. cfg.showdetail ^= 1;
  2662. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2663. break;
  2664. case SEL_FSIZE:
  2665. cfg.sizeorder ^= 1;
  2666. cfg.mtimeorder = 0;
  2667. cfg.apparentsz = 0;
  2668. cfg.blkorder = 0;
  2669. cfg.copymode = 0;
  2670. break;
  2671. case SEL_BSIZE:
  2672. if (sel == SEL_BSIZE) {
  2673. if (!cfg.apparentsz)
  2674. cfg.blkorder ^= 1;
  2675. nftw_fn = &sum_bsizes;
  2676. cfg.apparentsz = 0;
  2677. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  2678. }
  2679. if (cfg.blkorder) {
  2680. cfg.showdetail = 1;
  2681. printptr = &printent_long;
  2682. }
  2683. cfg.mtimeorder = 0;
  2684. cfg.sizeorder = 0;
  2685. cfg.copymode = 0;
  2686. break;
  2687. default: /* SEL_MTIME */
  2688. cfg.mtimeorder ^= 1;
  2689. cfg.sizeorder = 0;
  2690. cfg.apparentsz = 0;
  2691. cfg.blkorder = 0;
  2692. cfg.copymode = 0;
  2693. break;
  2694. }
  2695. /* Save current */
  2696. if (ndents)
  2697. copycurname();
  2698. goto begin;
  2699. case SEL_STATS:
  2700. if (!ndents)
  2701. break;
  2702. mkpath(path, dents[cur].name, newpath);
  2703. if (lstat(newpath, &sb) == -1 || !show_stats(newpath, dents[cur].name, &sb)) {
  2704. printwarn();
  2705. goto nochange;
  2706. }
  2707. break;
  2708. case SEL_MEDIA: // fallthrough
  2709. case SEL_FMEDIA: // fallthrough
  2710. case SEL_ARCHIVELS: // fallthrough
  2711. case SEL_EXTRACT: // fallthrough
  2712. case SEL_RENAMEALL: // fallthrough
  2713. case SEL_RUNEDIT: // fallthrough
  2714. case SEL_RUNPAGE:
  2715. if (!ndents)
  2716. break; // fallthrough
  2717. case SEL_REDRAW: // fallthrough
  2718. case SEL_HELP: // fallthrough
  2719. case SEL_NOTE: // fallthrough
  2720. case SEL_LOCK:
  2721. {
  2722. if (ndents)
  2723. mkpath(path, dents[cur].name, newpath);
  2724. switch (sel) {
  2725. case SEL_MEDIA:
  2726. r = show_mediainfo(newpath, NULL);
  2727. break;
  2728. case SEL_FMEDIA:
  2729. r = show_mediainfo(newpath, "-f");
  2730. break;
  2731. case SEL_ARCHIVELS:
  2732. r = handle_archive(newpath, "-l", path);
  2733. break;
  2734. case SEL_EXTRACT:
  2735. r = handle_archive(newpath, "-x", path);
  2736. break;
  2737. case SEL_REDRAW:
  2738. if (ndents)
  2739. copycurname();
  2740. goto begin;
  2741. case SEL_RENAMEALL:
  2742. if ((r = getutil(utils[VIDIR])))
  2743. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2744. break;
  2745. case SEL_HELP:
  2746. r = show_help(path);
  2747. break;
  2748. case SEL_RUNEDIT:
  2749. if (!quote_run_sh_cmd(editor, dents[cur].name, path))
  2750. goto nochange;
  2751. r = TRUE;
  2752. break;
  2753. case SEL_RUNPAGE:
  2754. r = TRUE;
  2755. spawn(pager, pager_arg, dents[cur].name, path, F_NORMAL);
  2756. break;
  2757. case SEL_NOTE:
  2758. tmp = getenv(env_cfg[NNN_NOTE]);
  2759. if (!tmp) {
  2760. printmsg("set NNN_NOTE");
  2761. goto nochange;
  2762. }
  2763. if (!quote_run_sh_cmd(editor, tmp, NULL))
  2764. goto nochange;
  2765. r = TRUE;
  2766. break;
  2767. default: /* SEL_LOCK */
  2768. r = TRUE;
  2769. spawn(utils[LOCKER], NULL, NULL, NULL, F_NORMAL | F_SIGINT);
  2770. break;
  2771. }
  2772. if (!r) {
  2773. printmsg("required utility missing");
  2774. goto nochange;
  2775. }
  2776. /* In case of successful operation, reload contents */
  2777. /* Continue in navigate-as-you-type mode, if enabled */
  2778. if (cfg.filtermode)
  2779. presel = FILTER;
  2780. /* Save current */
  2781. if (ndents)
  2782. copycurname();
  2783. /* Repopulate as directory content may have changed */
  2784. goto begin;
  2785. }
  2786. case SEL_ASIZE:
  2787. cfg.apparentsz ^= 1;
  2788. if (cfg.apparentsz) {
  2789. nftw_fn = &sum_sizes;
  2790. cfg.blkorder = 1;
  2791. BLK_SHIFT = 0;
  2792. } else
  2793. cfg.blkorder = 0; // fallthrough
  2794. case SEL_COPY:
  2795. if (!ndents)
  2796. goto nochange;
  2797. if (cfg.copymode) {
  2798. /*
  2799. * Clear the tmp copy path file on first copy.
  2800. *
  2801. * This ensures that when the first file path is
  2802. * copied into memory (but not written to tmp file
  2803. * yet to save on writes), the tmp file is cleared.
  2804. * The user may be in the middle of selection mode op
  2805. * and issue a cp, mv of multi-rm assuming the files
  2806. * in the copy list would be affected. However, these
  2807. * ops read the source file paths from the tmp file.
  2808. */
  2809. if (!ncp)
  2810. writecp(NULL, 0);
  2811. r = mkpath(path, dents[cur].name, newpath);
  2812. if (!appendfpath(newpath, r))
  2813. goto nochange;
  2814. ++ncp;
  2815. } else {
  2816. r = mkpath(path, dents[cur].name, newpath);
  2817. /* Keep the copy buf in sync */
  2818. copybufpos = 0;
  2819. appendfpath(newpath, r);
  2820. writecp(newpath, r - 1); /* Truncate NULL from end */
  2821. if (copier)
  2822. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  2823. }
  2824. printmsg(newpath);
  2825. goto nochange;
  2826. case SEL_COPYMUL:
  2827. cfg.copymode ^= 1;
  2828. if (cfg.copymode) {
  2829. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2830. copystartid = cur;
  2831. copybufpos = 0;
  2832. ncp = 0;
  2833. printmsg("selection on");
  2834. DPRINTF_S("selection on");
  2835. goto nochange;
  2836. }
  2837. if (!ncp) { /* Handle range selection */
  2838. #ifndef DIR_LIMITED_COPY
  2839. if (g_crc != crc8fast((uchar *)dents,
  2840. ndents * sizeof(struct entry))) {
  2841. cfg.copymode = 0;
  2842. printmsg("range error: dir/content changed");
  2843. DPRINTF_S("range error: dir/content changed");
  2844. goto nochange;
  2845. }
  2846. #endif
  2847. if (cur < copystartid) {
  2848. copyendid = copystartid;
  2849. copystartid = cur;
  2850. } else
  2851. copyendid = cur;
  2852. if (copystartid < copyendid) {
  2853. for (r = copystartid; r <= copyendid; ++r)
  2854. if (!appendfpath(newpath, mkpath(path,
  2855. dents[r].name, newpath)))
  2856. goto nochange;
  2857. snprintf(newpath, PATH_MAX, "%d files copied",
  2858. copyendid - copystartid + 1);
  2859. printmsg(newpath);
  2860. }
  2861. }
  2862. if (copybufpos) { /* File path(s) written to the buffer */
  2863. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2864. if (copier)
  2865. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  2866. if (ncp) { /* Some files cherry picked */
  2867. snprintf(newpath, PATH_MAX, "%d files copied", ncp);
  2868. printmsg(newpath);
  2869. }
  2870. } else
  2871. printmsg("selection off");
  2872. goto nochange;
  2873. case SEL_COPYLIST:
  2874. if (copybufpos)
  2875. showcplist();
  2876. else
  2877. printmsg("none selected");
  2878. goto nochange;
  2879. case SEL_CP:
  2880. case SEL_MV:
  2881. case SEL_RMMUL:
  2882. {
  2883. /* Fail if copy file path not generated */
  2884. if (!g_cppath[0]) {
  2885. printmsg("copy file not found");
  2886. goto nochange;
  2887. }
  2888. /* Warn if selection not completed */
  2889. if (cfg.copymode) {
  2890. printmsg("finish selection first");
  2891. goto nochange;
  2892. }
  2893. /* Fail if copy file path isn't accessible */
  2894. if (access(g_cppath, R_OK) == -1) {
  2895. printmsg("empty selection list");
  2896. goto nochange;
  2897. }
  2898. if (sel == SEL_CP) {
  2899. snprintf(g_buf, CMD_LEN_MAX,
  2900. #ifdef __linux__
  2901. "xargs -0 -a %s -%c src cp -iRp src .",
  2902. #else
  2903. "cat %s | xargs -0 -o -%c src cp -iRp src .",
  2904. #endif
  2905. g_cppath, REPLACE_STR);
  2906. } else if (sel == SEL_MV) {
  2907. snprintf(g_buf, CMD_LEN_MAX,
  2908. #ifdef __linux__
  2909. "xargs -0 -a %s -%c src mv -i src .",
  2910. #else
  2911. "cat %s | xargs -0 -o -%c src mv -i src .",
  2912. #endif
  2913. g_cppath, REPLACE_STR);
  2914. } else { /* SEL_RMMUL */
  2915. snprintf(g_buf, CMD_LEN_MAX,
  2916. #ifdef __linux__
  2917. "xargs -0 -a %s rm -%cr",
  2918. #else
  2919. "cat %s | xargs -0 -o rm -%cr",
  2920. #endif
  2921. g_cppath, confirm_force());
  2922. }
  2923. spawn("sh", "-c", g_buf, path, F_NORMAL | F_SIGINT);
  2924. if (ndents)
  2925. copycurname();
  2926. if (cfg.filtermode)
  2927. presel = FILTER;
  2928. goto begin;
  2929. }
  2930. case SEL_RM:
  2931. {
  2932. if (!ndents)
  2933. break;
  2934. char rm_opts[] = "-ir";
  2935. rm_opts[1] = confirm_force();
  2936. mkpath(path, dents[cur].name, newpath);
  2937. spawn("rm", rm_opts, newpath, NULL, F_NORMAL | F_SIGINT);
  2938. if (cur && access(newpath, F_OK) == -1)
  2939. --cur;
  2940. copycurname();
  2941. if (cfg.filtermode)
  2942. presel = FILTER;
  2943. goto begin;
  2944. }
  2945. case SEL_ARCHIVE: // fallthrough
  2946. case SEL_OPENWITH: // fallthrough
  2947. case SEL_RENAME:
  2948. if (!ndents)
  2949. break; // fallthrough
  2950. case SEL_NEW:
  2951. {
  2952. switch (sel) {
  2953. case SEL_ARCHIVE:
  2954. tmp = xreadline(dents[cur].name, "name: ");
  2955. break;
  2956. case SEL_OPENWITH:
  2957. tmp = xreadline(NULL, "open with: ");
  2958. break;
  2959. case SEL_NEW:
  2960. tmp = xreadline(NULL, "name/link suffix [@ for none]: ");
  2961. break;
  2962. default: /* SEL_RENAME */
  2963. tmp = xreadline(dents[cur].name, "");
  2964. break;
  2965. }
  2966. if (tmp == NULL || tmp[0] == '\0')
  2967. break;
  2968. /* Allow only relative, same dir paths */
  2969. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2970. printmsg(messages[STR_INPUT_ID]);
  2971. goto nochange;
  2972. }
  2973. /* Confirm if app is CLI or GUI */
  2974. if (sel == SEL_OPENWITH) {
  2975. r = get_input("press 'c' for cli mode");
  2976. (r == 'c') ? (r = F_NORMAL) : (r = F_NOWAIT | F_NOTRACE);
  2977. }
  2978. switch (sel) {
  2979. case SEL_ARCHIVE:
  2980. /* newpath is used as temporary buffer */
  2981. if (!getutil(utils[APACK])) {
  2982. printmsg("utility missing");
  2983. continue;
  2984. }
  2985. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  2986. break;
  2987. case SEL_OPENWITH:
  2988. dir = NULL;
  2989. getprogarg(tmp, &dir); /* dir used as tmp var */
  2990. mkpath(path, dents[cur].name, newpath);
  2991. spawn(tmp, dir, newpath, path, r);
  2992. break;
  2993. case SEL_RENAME:
  2994. /* Skip renaming to same name */
  2995. if (strcmp(tmp, dents[cur].name) == 0)
  2996. goto nochange;
  2997. break;
  2998. default:
  2999. break;
  3000. }
  3001. /* Complete OPEN, LAUNCH, ARCHIVE operations */
  3002. if (sel != SEL_NEW && sel != SEL_RENAME) {
  3003. /* Continue in navigate-as-you-type mode, if enabled */
  3004. if (cfg.filtermode)
  3005. presel = FILTER;
  3006. /* Save current */
  3007. copycurname();
  3008. /* Repopulate as directory content may have changed */
  3009. goto begin;
  3010. }
  3011. /* Open the descriptor to currently open directory */
  3012. fd = open(path, O_RDONLY | O_DIRECTORY);
  3013. if (fd == -1) {
  3014. printwarn();
  3015. goto nochange;
  3016. }
  3017. /* Check if another file with same name exists */
  3018. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  3019. if (sel == SEL_RENAME) {
  3020. /* Overwrite file with same name? */
  3021. if (get_input("press 'y' to overwrite") != 'y') {
  3022. close(fd);
  3023. break;
  3024. }
  3025. } else {
  3026. /* Do nothing in case of NEW */
  3027. close(fd);
  3028. printmsg("entry exists");
  3029. goto nochange;
  3030. }
  3031. }
  3032. if (sel == SEL_RENAME) {
  3033. /* Rename the file */
  3034. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  3035. close(fd);
  3036. printwarn();
  3037. goto nochange;
  3038. }
  3039. } else {
  3040. /* Check if it's a dir or file */
  3041. r = get_input("create 'f'(ile) / 'd'(ir) / 's'(ym) / 'h'(ard)?");
  3042. if (r == 'f') {
  3043. r = openat(fd, tmp, O_CREAT, 0666);
  3044. close(r);
  3045. } else if (r == 'd') {
  3046. r = mkdirat(fd, tmp, 0777);
  3047. } else if (r == 's' || r == 'h') {
  3048. if (tmp[0] == '@' && tmp[1] == '\0')
  3049. tmp[0] = '\0';
  3050. r = xlink(tmp, path, newpath, r);
  3051. close(fd);
  3052. if (r <= 0) {
  3053. printmsg("none created");
  3054. goto nochange;
  3055. }
  3056. if (cfg.filtermode)
  3057. presel = FILTER;
  3058. if (ndents)
  3059. copycurname();
  3060. goto begin;
  3061. } else {
  3062. close(fd);
  3063. break;
  3064. }
  3065. /* Check if file creation failed */
  3066. if (r == -1) {
  3067. close(fd);
  3068. printwarn();
  3069. goto nochange;
  3070. }
  3071. }
  3072. close(fd);
  3073. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  3074. goto begin;
  3075. }
  3076. case SEL_EXEC: // fallthrough
  3077. case SEL_SHELL: // fallthrough
  3078. case SEL_SCRIPT: // fallthrough
  3079. case SEL_RUNCMD:
  3080. switch (sel) {
  3081. case SEL_EXEC:
  3082. if (!ndents)
  3083. goto nochange;
  3084. /* Check if this is a directory */
  3085. if (!S_ISREG(dents[cur].mode)) {
  3086. printmsg("not regular file");
  3087. goto nochange;
  3088. }
  3089. /* Check if file is executable */
  3090. if (!(dents[cur].mode & 0100)) {
  3091. printmsg("permission denied");
  3092. goto nochange;
  3093. }
  3094. mkpath(path, dents[cur].name, newpath);
  3095. DPRINTF_S(newpath);
  3096. spawn(newpath, NULL, NULL, path, F_NORMAL | F_SIGINT);
  3097. break;
  3098. case SEL_SHELL:
  3099. spawn(shell, shell_arg, NULL, path, F_NORMAL | F_MARKER);
  3100. break;
  3101. case SEL_SCRIPT:
  3102. if (!scriptpath) {
  3103. printmsg("set NNN_SCRIPT");
  3104. goto nochange;
  3105. }
  3106. if (stat(scriptpath, &sb) == -1) {
  3107. printwarn();
  3108. goto nochange;
  3109. }
  3110. if (S_ISDIR(sb.st_mode)) {
  3111. cfg.runscript ^= 1;
  3112. if (!cfg.runscript && rundir[0]) {
  3113. /* If toggled, and still in the script dir,
  3114. switch to original directory */
  3115. if (strcmp(path, scriptpath) == 0) {
  3116. xstrlcpy(path, rundir, PATH_MAX);
  3117. xstrlcpy(lastname, runfile, NAME_MAX);
  3118. rundir[0] = runfile[0] = '\0';
  3119. setdirwatch();
  3120. goto begin;
  3121. }
  3122. break;
  3123. }
  3124. /* Check if directory is accessible */
  3125. if (!xdiraccess(scriptpath))
  3126. goto nochange;
  3127. xstrlcpy(rundir, path, PATH_MAX);
  3128. xstrlcpy(path, scriptpath, PATH_MAX);
  3129. if (ndents)
  3130. xstrlcpy(runfile, dents[cur].name, NAME_MAX);
  3131. cfg.runctx = cfg.curctx;
  3132. lastname[0] = '\0';
  3133. setdirwatch();
  3134. goto begin;
  3135. }
  3136. if (S_ISREG(sb.st_mode)) {
  3137. if (ndents)
  3138. tmp = dents[cur].name;
  3139. else
  3140. tmp = NULL;
  3141. spawn(shell, scriptpath, tmp, path, F_NORMAL | F_SIGINT);
  3142. }
  3143. break;
  3144. default: /* SEL_RUNCMD */
  3145. tmp = xreadline(NULL, "> ");
  3146. if (tmp && tmp[0])
  3147. spawn(shell, "-c", tmp, path, F_NORMAL | F_SIGINT);
  3148. }
  3149. /* Continue in navigate-as-you-type mode, if enabled */
  3150. if (cfg.filtermode)
  3151. presel = FILTER;
  3152. /* Save current */
  3153. if (ndents)
  3154. copycurname();
  3155. /* Repopulate as directory content may have changed */
  3156. goto begin;
  3157. case SEL_QUITCD: // fallthrough
  3158. case SEL_QUIT:
  3159. for (r = 0; r < CTX_MAX; ++r)
  3160. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  3161. r = get_input("Quit all contexts? ('Enter' confirms)");
  3162. break;
  3163. }
  3164. if (!(r == CTX_MAX || r == '\r'))
  3165. break;
  3166. if (sel == SEL_QUITCD) {
  3167. /* In vim picker mode, clear selection and exit */
  3168. if (cfg.picker) {
  3169. if (copybufpos) {
  3170. if (cfg.pickraw) /* Reset for for raw pick */
  3171. copybufpos = 0;
  3172. else /* Clear the picker file */
  3173. writecp(NULL, 0);
  3174. }
  3175. dentfree(dents);
  3176. return;
  3177. }
  3178. tmp = getenv(env_cfg[NNN_TMPFILE]);
  3179. if (!tmp) {
  3180. printmsg("set NNN_TMPFILE");
  3181. goto nochange;
  3182. }
  3183. FILE *fp = fopen(tmp, "w");
  3184. if (fp) {
  3185. fprintf(fp, "cd \"%s\"", path);
  3186. fclose(fp);
  3187. }
  3188. } // fallthrough
  3189. case SEL_QUITCTX:
  3190. if (sel == SEL_QUITCTX) {
  3191. uint iter = 1;
  3192. r = cfg.curctx;
  3193. while (iter < CTX_MAX) {
  3194. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3195. if (g_ctx[r].c_cfg.ctxactive) {
  3196. g_ctx[cfg.curctx].c_cfg.ctxactive = 0;
  3197. /* Switch to next active context */
  3198. path = g_ctx[r].c_path;
  3199. ipath = g_ctx[r].c_init;
  3200. lastdir = g_ctx[r].c_last;
  3201. lastname = g_ctx[r].c_name;
  3202. cfg = g_ctx[r].c_cfg;
  3203. cfg.curctx = r;
  3204. setdirwatch();
  3205. goto begin;
  3206. }
  3207. ++iter;
  3208. }
  3209. }
  3210. dentfree(dents);
  3211. return;
  3212. } /* switch (sel) */
  3213. /* Locker */
  3214. if (idletimeout != 0 && idle == idletimeout) {
  3215. idle = 0;
  3216. spawn(utils[LOCKER], NULL, NULL, NULL, F_NORMAL | F_SIGINT);
  3217. }
  3218. }
  3219. }
  3220. static void usage(void)
  3221. {
  3222. fprintf(stdout,
  3223. "usage: nnn [-b key] [-C] [-e] [-i] [-l]\n"
  3224. " [-p file] [-S] [-v] [-h] [PATH]\n\n"
  3225. "The missing terminal file manager for X.\n\n"
  3226. "positional args:\n"
  3227. " PATH start dir [default: current dir]\n\n"
  3228. "optional args:\n"
  3229. " -b key open bookmark key\n"
  3230. " -C disable directory color\n"
  3231. " -e use exiftool for media info\n"
  3232. " -i nav-as-you-type mode\n"
  3233. " -l light mode\n"
  3234. " -p file selection file (stdout if '-')\n"
  3235. " -S disk usage mode\n"
  3236. " -v show version\n"
  3237. " -h show help\n\n"
  3238. "v%s\n%s\n", VERSION, GENERAL_INFO);
  3239. }
  3240. int main(int argc, char *argv[])
  3241. {
  3242. char cwd[PATH_MAX] __attribute__ ((aligned));
  3243. char *ipath = NULL;
  3244. int opt;
  3245. while ((opt = getopt(argc, argv, "Slib:Cep:vh")) != -1) {
  3246. switch (opt) {
  3247. case 'S':
  3248. cfg.blkorder = 1;
  3249. nftw_fn = sum_bsizes;
  3250. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  3251. break;
  3252. case 'l':
  3253. cfg.showdetail = 0;
  3254. printptr = &printent;
  3255. break;
  3256. case 'i':
  3257. cfg.filtermode = 1;
  3258. break;
  3259. case 'b':
  3260. ipath = optarg;
  3261. break;
  3262. case 'C':
  3263. cfg.showcolor = 0;
  3264. break;
  3265. case 'e':
  3266. cfg.metaviewer = EXIFTOOL;
  3267. break;
  3268. case 'p':
  3269. cfg.picker = 1;
  3270. if (optarg[0] == '-' && optarg[1] == '\0')
  3271. cfg.pickraw = 1;
  3272. else {
  3273. /* copier used as tmp var */
  3274. copier = realpath(optarg, g_cppath);
  3275. if (!g_cppath[0]) {
  3276. fprintf(stderr, "%s\n", strerror(errno));
  3277. return 1;
  3278. }
  3279. }
  3280. break;
  3281. case 'v':
  3282. fprintf(stdout, "%s\n", VERSION);
  3283. return 0;
  3284. case 'h':
  3285. usage();
  3286. return 0;
  3287. default:
  3288. usage();
  3289. return 1;
  3290. }
  3291. }
  3292. /* Confirm we are in a terminal */
  3293. if (!cfg.picker && !(isatty(0) && isatty(1))) {
  3294. fprintf(stderr, "stdin/stdout !tty\n");
  3295. return 1;
  3296. }
  3297. /* Get the context colors; copier used as tmp var */
  3298. if (cfg.showcolor) {
  3299. copier = xgetenv(env_cfg[NNN_CONTEXT_COLORS], "4444");
  3300. opt = 0;
  3301. while (*copier && opt < CTX_MAX) {
  3302. if (*copier < '0' || *copier > '7') {
  3303. fprintf(stderr, "invalid color code\n");
  3304. return 1;
  3305. }
  3306. g_ctx[opt].color = *copier - '0';
  3307. ++copier;
  3308. ++opt;
  3309. }
  3310. while (opt != CTX_MAX) {
  3311. g_ctx[opt].color = 4;
  3312. ++opt;
  3313. }
  3314. }
  3315. /* Parse bookmarks string */
  3316. if (!parsebmstr()) {
  3317. fprintf(stderr, "%s: 1 char per key\n", env_cfg[NNN_BMS]);
  3318. return 1;
  3319. }
  3320. if (ipath) { /* Open a bookmark directly */
  3321. if (ipath[1] || get_bm_loc(*ipath, cwd) == NULL) {
  3322. fprintf(stderr, "%s\n", messages[STR_INVBM_KEY]);
  3323. return 1;
  3324. }
  3325. ipath = cwd;
  3326. } else if (argc == optind) {
  3327. /* Start in the current directory */
  3328. ipath = getcwd(cwd, PATH_MAX);
  3329. if (ipath == NULL)
  3330. ipath = "/";
  3331. } else {
  3332. ipath = realpath(argv[optind], cwd);
  3333. if (!ipath) {
  3334. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  3335. return 1;
  3336. }
  3337. }
  3338. /* Increase current open file descriptor limit */
  3339. open_max = max_openfds();
  3340. if (getuid() == 0 || getenv(env_cfg[NNN_SHOW_HIDDEN]))
  3341. cfg.showhidden = 1;
  3342. /* Edit text in EDITOR, if opted */
  3343. if (getenv(env_cfg[NNN_USE_EDITOR]))
  3344. cfg.useeditor = 1;
  3345. /* Get VISUAL/EDITOR */
  3346. editor = xgetenv(envs[VISUAL], xgetenv(envs[EDITOR], "vi"));
  3347. /* Get PAGER */
  3348. pager = xgetenv(envs[PAGER], "less");
  3349. getprogarg(pager, &pager_arg);
  3350. /* Get SHELL */
  3351. shell = xgetenv(envs[SHELL], "sh");
  3352. getprogarg(shell, &shell_arg);
  3353. /* Setup script execution */
  3354. scriptpath = getenv(env_cfg[NNN_SCRIPT]);
  3355. #ifdef LINUX_INOTIFY
  3356. /* Initialize inotify */
  3357. inotify_fd = inotify_init1(IN_NONBLOCK);
  3358. if (inotify_fd < 0) {
  3359. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  3360. return 1;
  3361. }
  3362. #elif defined(BSD_KQUEUE)
  3363. kq = kqueue();
  3364. if (kq < 0) {
  3365. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  3366. return 1;
  3367. }
  3368. #endif
  3369. /* Get custom opener, if set */
  3370. opener = xgetenv(env_cfg[NNN_OPENER], utils[OPENER]);
  3371. /* Get locker wait time, if set; copier used as tmp var */
  3372. copier = getenv(env_cfg[NNN_IDLE_TIMEOUT]);
  3373. if (copier) {
  3374. opt = atoi(copier);
  3375. idletimeout = opt * ((opt > 0) - (opt < 0));
  3376. }
  3377. /* Get the clipboard copier, if set */
  3378. copier = getenv(env_cfg[NNN_COPIER]);
  3379. if (getenv("HOME"))
  3380. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("HOME"), HOME_LEN_MAX);
  3381. else if (getenv("TMPDIR"))
  3382. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("TMPDIR"), HOME_LEN_MAX);
  3383. else if (xdiraccess("/tmp"))
  3384. g_tmpfplen = xstrlcpy(g_tmpfpath, "/tmp", HOME_LEN_MAX);
  3385. if (!cfg.picker && g_tmpfplen) {
  3386. xstrlcpy(g_cppath, g_tmpfpath, HOME_LEN_MAX);
  3387. xstrlcpy(g_cppath + g_tmpfplen - 1, "/.nnncp", HOME_LEN_MAX - g_tmpfplen);
  3388. }
  3389. /* Disable auto-select if opted */
  3390. if (getenv(env_cfg[NNN_NO_AUTOSELECT]))
  3391. cfg.autoselect = 0;
  3392. /* Disable opening files on right arrow and `l` */
  3393. if (getenv(env_cfg[NNN_RESTRICT_NAV_OPEN]))
  3394. cfg.nonavopen = 1;
  3395. /* Restrict opening of 0-byte files */
  3396. if (getenv(env_cfg[NNN_RESTRICT_0B]))
  3397. cfg.restrict0b = 1;
  3398. /* Use string-comparison in filter mode */
  3399. if (getenv(env_cfg[NNN_PLAIN_FILTER])) {
  3400. cfg.filter_re = 0;
  3401. filterfn = &visible_str;
  3402. }
  3403. signal(SIGINT, SIG_IGN);
  3404. signal(SIGQUIT, SIG_IGN);
  3405. /* Test initial path */
  3406. if (!xdiraccess(ipath)) {
  3407. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  3408. return 1;
  3409. }
  3410. /* Set locale */
  3411. setlocale(LC_ALL, "");
  3412. crc8init();
  3413. #ifdef DEBUGMODE
  3414. enabledbg();
  3415. #endif
  3416. if (!initcurses())
  3417. return 1;
  3418. browse(ipath);
  3419. exitcurses();
  3420. if (cfg.pickraw) {
  3421. if (copybufpos) {
  3422. opt = selectiontofd(1);
  3423. if (opt != (int)(copybufpos))
  3424. fprintf(stderr, "%s\n", strerror(errno));
  3425. }
  3426. } else if (!cfg.picker && g_cppath[0])
  3427. unlink(g_cppath);
  3428. /* Free the copy buffer */
  3429. free(pcopybuf);
  3430. #ifdef LINUX_INOTIFY
  3431. /* Shutdown inotify */
  3432. if (inotify_wd >= 0)
  3433. inotify_rm_watch(inotify_fd, inotify_wd);
  3434. close(inotify_fd);
  3435. #elif defined(BSD_KQUEUE)
  3436. if (event_fd >= 0)
  3437. close(event_fd);
  3438. close(kq);
  3439. #endif
  3440. #ifdef DEBUGMODE
  3441. disabledbg();
  3442. #endif
  3443. return 0;
  3444. }