My build of nnn with minor changes
 
 
 
 
 
 

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