My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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