My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

4261 行
93 KiB

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