My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

4267 rindas
94 KiB

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