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

4304 lignes
96 KiB

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