My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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