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.
 
 
 
 
 
 

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