My build of nnn with minor changes
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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