My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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