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

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