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

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