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

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