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

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