My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

4289 Zeilen
96 KiB

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