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.
 
 
 
 
 
 

4316 lignes
96 KiB

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