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.
 
 
 
 
 
 

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