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

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