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.
 
 
 
 
 
 

4244 lines
93 KiB

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