My build of nnn with minor changes
 
 
 
 
 
 

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