My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

4292 lines
96 KiB

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