My build of nnn with minor changes
 
 
 
 
 
 

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