My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

5326 lines
115 KiB

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