My build of nnn with minor changes
 
 
 
 
 
 

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