My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

7027 rindas
153 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-2020, 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. #elif defined(__HAIKU__)
  52. #include "../misc/haiku/haiku_interop.h"
  53. #define HAIKU_NM
  54. #else
  55. #include <sys/sysmacros.h>
  56. #endif
  57. #include <sys/wait.h>
  58. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  59. #ifndef NCURSES_WIDECHAR
  60. #define NCURSES_WIDECHAR 1
  61. #endif
  62. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(__sun)
  63. #ifndef _XOPEN_SOURCE_EXTENDED
  64. #define _XOPEN_SOURCE_EXTENDED
  65. #endif
  66. #endif
  67. #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  68. #define __USE_XOPEN
  69. #endif
  70. #include <dirent.h>
  71. #include <errno.h>
  72. #include <fcntl.h>
  73. #include <libgen.h>
  74. #include <limits.h>
  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. #ifdef PCRE
  84. #include <pcre.h>
  85. #else
  86. #include <regex.h>
  87. #endif
  88. #include <signal.h>
  89. #include <stdarg.h>
  90. #include <stdlib.h>
  91. #ifdef __sun
  92. #include <alloca.h>
  93. #endif
  94. #include <string.h>
  95. #include <strings.h>
  96. #include <time.h>
  97. #include <unistd.h>
  98. #ifndef __USE_XOPEN_EXTENDED
  99. #define __USE_XOPEN_EXTENDED 1
  100. #endif
  101. #include <ftw.h>
  102. #include <wchar.h>
  103. #include "nnn.h"
  104. #include "dbg.h"
  105. /* Macro definitions */
  106. #define VERSION "3.1"
  107. #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
  108. #define SESSIONS_VERSION 1
  109. #ifndef S_BLKSIZE
  110. #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
  111. #endif
  112. /*
  113. * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
  114. * flexible array on Illumos. Use somewhat accomodating fallback values.
  115. */
  116. #ifndef NAME_MAX
  117. #define NAME_MAX 255
  118. #endif
  119. #ifndef PATH_MAX
  120. #define PATH_MAX 4096
  121. #endif
  122. #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
  123. #define DOUBLECLICK_INTERVAL_NS (400000000)
  124. #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
  125. #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
  126. #undef MIN
  127. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  128. #undef MAX
  129. #define MAX(x, y) ((x) > (y) ? (x) : (y))
  130. #define ISODD(x) ((x) & 1)
  131. #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
  132. #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  133. #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
  134. #define READLINE_MAX 256
  135. #define FILTER '/'
  136. #define RFILTER '\\'
  137. #define CASE ':'
  138. #define MSGWAIT '$'
  139. #define SELECT ' '
  140. #define REGEX_MAX 48
  141. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  142. #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per filename = 64*32B = 2KB */
  143. #define DESCRIPTOR_LEN 32
  144. #define _ALIGNMENT 0x10 /* 16-byte alignment */
  145. #define _ALIGNMENT_MASK 0xF
  146. #define TMP_LEN_MAX 64
  147. #define CTX_MAX 4
  148. #define DOT_FILTER_LEN 7
  149. #define ASCII_MAX 128
  150. #define EXEC_ARGS_MAX 8
  151. #define LIST_FILES_MAX (1 << 16)
  152. #define SCROLLOFF 3
  153. #define MIN_DISPLAY_COLS 10
  154. #define LONG_SIZE sizeof(ulong)
  155. #define ARCHIVE_CMD_LEN 16
  156. #define BLK_SHIFT_512 9
  157. /* Detect hardlinks in du */
  158. #define HASH_BITS (0xFFFFFF)
  159. #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
  160. /* Program return codes */
  161. #define _SUCCESS 0
  162. #define _FAILURE !_SUCCESS
  163. /* Entry flags */
  164. #define DIR_OR_LINK_TO_DIR 0x01
  165. #define HARD_LINK 0x02
  166. #define FILE_SELECTED 0x10
  167. /* Macros to define process spawn behaviour as flags */
  168. #define F_NONE 0x00 /* no flag set */
  169. #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
  170. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  171. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  172. #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
  173. #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
  174. #define F_CLI (F_NORMAL | F_MULTI)
  175. #define F_SILENT (F_CLI | F_NOTRACE)
  176. /* Version compare macros */
  177. /*
  178. * states: S_N: normal, S_I: comparing integral part, S_F: comparing
  179. * fractional parts, S_Z: idem but with leading Zeroes only
  180. */
  181. #define S_N 0x0
  182. #define S_I 0x3
  183. #define S_F 0x6
  184. #define S_Z 0x9
  185. /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
  186. #define VCMP 2
  187. #define VLEN 3
  188. /* Volume info */
  189. #define FREE 0
  190. #define CAPACITY 1
  191. /* TYPE DEFINITIONS */
  192. typedef unsigned long ulong;
  193. typedef unsigned int uint;
  194. typedef unsigned char uchar;
  195. typedef unsigned short ushort;
  196. typedef long long ll;
  197. typedef unsigned long long ull;
  198. /* STRUCTURES */
  199. /* Directory entry */
  200. typedef struct entry {
  201. char *name;
  202. time_t t;
  203. off_t size;
  204. blkcnt_t blocks; /* number of 512B blocks allocated */
  205. mode_t mode;
  206. ushort nlen; /* Length of file name */
  207. uchar flags; /* Flags specific to the file */
  208. } *pEntry;
  209. /* Key-value pairs from env */
  210. typedef struct {
  211. int key;
  212. char *val;
  213. } kv;
  214. typedef struct {
  215. #ifdef PCRE
  216. const pcre *pcrex;
  217. #else
  218. const regex_t *regex;
  219. #endif
  220. const char *str;
  221. } fltrexp_t;
  222. /*
  223. * Settings
  224. * NOTE: update default values if changing order
  225. */
  226. typedef struct {
  227. uint filtermode : 1; /* Set to enter filter mode */
  228. uint timeorder : 1; /* Set to sort by time */
  229. uint sizeorder : 1; /* Set to sort by file size */
  230. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  231. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  232. uint extnorder : 1; /* Order by extension */
  233. uint showhidden : 1; /* Set to show hidden files */
  234. uint selmode : 1; /* Set when selecting files */
  235. uint showdetail : 1; /* Clear to show fewer file info */
  236. uint ctxactive : 1; /* Context active or not */
  237. uint reserved1 : 3;
  238. /* The following settings are global */
  239. uint curctx : 2; /* Current context number */
  240. uint dircolor : 1; /* Current status of dir color */
  241. uint picker : 1; /* Write selection to user-specified file */
  242. uint pickraw : 1; /* Write selection to sdtout before exit */
  243. uint nonavopen : 1; /* Open file on right arrow or `l` */
  244. uint autoselect : 1; /* Auto-select dir in type-to-nav mode */
  245. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  246. uint useeditor : 1; /* Use VISUAL to open text files */
  247. uint runplugin : 1; /* Choose plugin mode */
  248. uint runctx : 2; /* The context in which plugin is to be run */
  249. uint regex : 1; /* Use regex filters */
  250. uint x11 : 1; /* Copy to system clipboard and show notis */
  251. uint timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
  252. uint cliopener : 1; /* All-CLI app opener */
  253. uint waitedit : 1; /* For ops that can't be detached, used EDITOR */
  254. uint rollover : 1; /* Roll over at edges */
  255. } settings;
  256. /* Contexts or workspaces */
  257. typedef struct {
  258. char c_path[PATH_MAX]; /* Current dir */
  259. char c_last[PATH_MAX]; /* Last visited dir */
  260. char c_name[NAME_MAX + 1]; /* Current file name */
  261. char c_fltr[REGEX_MAX]; /* Current filter */
  262. settings c_cfg; /* Current configuration */
  263. uint color; /* Color code for directories */
  264. } context;
  265. typedef struct {
  266. size_t ver;
  267. size_t pathln[CTX_MAX];
  268. size_t lastln[CTX_MAX];
  269. size_t nameln[CTX_MAX];
  270. size_t fltrln[CTX_MAX];
  271. } session_header_t;
  272. /* GLOBALS */
  273. /* Configuration, contexts */
  274. static settings cfg = {
  275. 0, /* filtermode */
  276. 0, /* timeorder */
  277. 0, /* sizeorder */
  278. 0, /* apparentsz */
  279. 0, /* blkorder */
  280. 0, /* extnorder */
  281. 0, /* showhidden */
  282. 0, /* selmode */
  283. 0, /* showdetail */
  284. 1, /* ctxactive */
  285. 0, /* reserved1 */
  286. 0, /* curctx */
  287. 0, /* dircolor */
  288. 0, /* picker */
  289. 0, /* pickraw */
  290. 0, /* nonavopen */
  291. 1, /* autoselect */
  292. 0, /* metaviewer */
  293. 0, /* useeditor */
  294. 0, /* runplugin */
  295. 0, /* runctx */
  296. 0, /* regex */
  297. 0, /* x11 */
  298. 2, /* timetype (T_MOD) */
  299. 0, /* cliopener */
  300. 0, /* waitedit */
  301. 1, /* rollover */
  302. };
  303. static context g_ctx[CTX_MAX] __attribute__ ((aligned));
  304. static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR;
  305. static int nselected;
  306. static uint idletimeout, selbufpos, lastappendpos, selbuflen;
  307. static ushort xlines, xcols;
  308. static ushort idle;
  309. static uchar maxbm, maxplug;
  310. static char *bmstr;
  311. static char *pluginstr;
  312. static char *opener;
  313. static char *editor;
  314. static char *enveditor;
  315. static char *pager;
  316. static char *shell;
  317. static char *home;
  318. static char *initpath;
  319. static char *cfgdir;
  320. static char *selpath;
  321. static char *listpath;
  322. static char *prefixpath;
  323. static char *plugindir;
  324. static char *sessiondir;
  325. static char *pnamebuf, *pselbuf;
  326. static ull *ihashbmp;
  327. static struct entry *dents;
  328. static blkcnt_t ent_blocks;
  329. static blkcnt_t dir_blocks;
  330. static ulong num_files;
  331. static kv *bookmark;
  332. static kv *plug;
  333. static uchar tmpfplen;
  334. static uchar blk_shift = BLK_SHIFT_512;
  335. #ifndef NOMOUSE
  336. static int middle_click_key;
  337. #endif
  338. #ifdef PCRE
  339. static pcre *archive_pcre;
  340. #else
  341. static regex_t archive_re;
  342. #endif
  343. /* Retain old signal handlers */
  344. #ifdef __linux__
  345. static sighandler_t oldsighup; /* old value of hangup signal */
  346. static sighandler_t oldsigtstp; /* old value of SIGTSTP */
  347. #else
  348. /* note: no sig_t on Solaris-derivs */
  349. static void (*oldsighup)(int);
  350. static void (*oldsigtstp)(int);
  351. #endif
  352. /* For use in functions which are isolated and don't return the buffer */
  353. static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
  354. /* Buffer to store tmp file path to show selection, file stats and help */
  355. static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
  356. /* Buffer to store plugins control pipe location */
  357. static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
  358. /* MISC NON-PERSISTENT INTERNAL BINARY STATES */
  359. /* Plugin control initialization status */
  360. #define STATE_PLUGIN_INIT 0x1
  361. #define STATE_INTERRUPTED 0x2
  362. #define STATE_RANGESEL 0x4
  363. #define STATE_MOVE_OP 0x8
  364. #define STATE_AUTONEXT 0x10
  365. #define STATE_MSG 0x20
  366. #define STATE_TRASH 0x40
  367. #define STATE_FORCEQUIT 0x80
  368. #define STATE_FORTUNE 0x100
  369. static uint g_states;
  370. /* Options to identify file mime */
  371. #if defined(__APPLE__)
  372. #define FILE_MIME_OPTS "-bIL"
  373. #elif !defined(__sun) /* no mime option for 'file' */
  374. #define FILE_MIME_OPTS "-biL"
  375. #endif
  376. /* Macros for utilities */
  377. #define UTIL_OPENER 0
  378. #define UTIL_ATOOL 1
  379. #define UTIL_BSDTAR 2
  380. #define UTIL_UNZIP 3
  381. #define UTIL_TAR 4
  382. #define UTIL_LOCKER 5
  383. #define UTIL_LAUNCH 6
  384. #define UTIL_SH_EXEC 7
  385. #define UTIL_BASH 8
  386. #define UTIL_ARCHIVEMOUNT 9
  387. #define UTIL_SSHFS 10
  388. #define UTIL_RCLONE 11
  389. #define UTIL_VI 12
  390. #define UTIL_LESS 13
  391. #define UTIL_SH 14
  392. #define UTIL_FZF 15
  393. #define UTIL_FZY 16
  394. #define UTIL_NTFY 17
  395. #define UTIL_CBCP 18
  396. #define UTIL_NMV 19
  397. /* Utilities to open files, run actions */
  398. static char * const utils[] = {
  399. #ifdef __APPLE__
  400. "/usr/bin/open",
  401. #elif defined __CYGWIN__
  402. "cygstart",
  403. #elif defined __HAIKU__
  404. "open",
  405. #else
  406. "xdg-open",
  407. #endif
  408. "atool",
  409. "bsdtar",
  410. "unzip",
  411. "tar",
  412. #ifdef __APPLE__
  413. "bashlock",
  414. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  415. "lock",
  416. #elif defined __HAIKU__
  417. "peaclock",
  418. #else
  419. "vlock",
  420. #endif
  421. "launch",
  422. "sh -c",
  423. "bash",
  424. "archivemount",
  425. "sshfs",
  426. "rclone",
  427. "vi",
  428. "less",
  429. "sh",
  430. "fzf",
  431. "fzy",
  432. ".ntfy",
  433. ".cbcp",
  434. ".nmv",
  435. };
  436. /* Common strings */
  437. #define MSG_NO_TRAVERSAL 0
  438. #define MSG_INVALID_KEY 1
  439. #define STR_TMPFILE 2
  440. #define MSG_0_SELECTED 3
  441. #define MSG_UTIL_MISSING 4
  442. #define MSG_FAILED 5
  443. #define MSG_SSN_NAME 6
  444. #define MSG_CP_MV_AS 7
  445. #define MSG_CUR_SEL_OPTS 8
  446. #define MSG_FORCE_RM 9
  447. #define MSG_LIMIT 10
  448. #define MSG_NEW_OPTS 11
  449. #define MSG_CLI_MODE 12
  450. #define MSG_OVERWRITE 13
  451. #define MSG_SSN_OPTS 14
  452. #define MSG_QUIT_ALL 15
  453. #define MSG_HOSTNAME 16
  454. #define MSG_ARCHIVE_NAME 17
  455. #define MSG_OPEN_WITH 18
  456. #define MSG_REL_PATH 19
  457. #define MSG_LINK_PREFIX 20
  458. #define MSG_COPY_NAME 21
  459. #define MSG_CONTINUE 22
  460. #define MSG_SEL_MISSING 23
  461. #define MSG_ACCESS 24
  462. #define MSG_EMPTY_FILE 25
  463. #define MSG_UNSUPPORTED 26
  464. #define MSG_NOT_SET 27
  465. #define MSG_EXISTS 28
  466. #define MSG_FEW_COLUMNS 29
  467. #define MSG_REMOTE_OPTS 30
  468. #define MSG_RCLONE_DELAY 31
  469. #define MSG_APP_NAME 32
  470. #define MSG_ARCHIVE_OPTS 33
  471. #define MSG_PLUGIN_KEYS 34
  472. #define MSG_BOOKMARK_KEYS 35
  473. #define MSG_INVALID_REG 36
  474. #define MSG_ORDER 37
  475. #define MSG_LAZY 38
  476. #define MSG_IGNORED 39
  477. #define MSG_RM_TMP 40
  478. #define MSG_NOCHNAGE 41
  479. #define MSG_CANCEL 42
  480. #ifndef DIR_LIMITED_SELECTION
  481. #define MSG_DIR_CHANGED 43 /* Must be the last entry */
  482. #endif
  483. static const char * const messages[] = {
  484. "no traversal",
  485. "invalid key",
  486. "/.nnnXXXXXX",
  487. "0 selected",
  488. "missing util",
  489. "failed!",
  490. "session name: ",
  491. "'c'p / 'm'v as?",
  492. "'c'urrent / 's'el?",
  493. "rm -rf %s file%s?",
  494. "limit exceeded\n",
  495. "'f'ile / 'd'ir / 's'ym / 'h'ard?",
  496. "'c'li / 'g'ui?",
  497. "overwrite?",
  498. "'s'ave / 'l'oad / 'r'estore?",
  499. "Quit all contexts?",
  500. "remote name ('-' for hovered): ",
  501. "archive name: ",
  502. "open with: ",
  503. "relative path: ",
  504. "link prefix [@ for none]: ",
  505. "copy name: ",
  506. "\n'Enter' to continue",
  507. "open failed",
  508. "dir inaccessible",
  509. "empty: edit/open with",
  510. "unknown",
  511. "not set",
  512. "entry exists",
  513. "too few columns!",
  514. "'s'shfs / 'r'clone?",
  515. "refresh if slow",
  516. "app name: ",
  517. "'d'efault / e'x'tract / 'l'ist / 'm'ount?",
  518. "plugin keys:",
  519. "bookmark keys:",
  520. "invalid regex",
  521. "'a'u / 'd'u / 'e'xtn / 'r'ev / 's'ize / 't'ime / 'v'er / 'c'lear?",
  522. "unmount failed! try lazy?",
  523. "ignoring invalid paths...",
  524. "remove tmp file?",
  525. "unchanged",
  526. "cancelled",
  527. #ifndef DIR_LIMITED_SELECTION
  528. "dir changed, range sel off", /* Must be the last entry */
  529. #endif
  530. };
  531. /* Supported configuration environment variables */
  532. #define NNN_OPTS 0
  533. #define NNN_BMS 1
  534. #define NNN_PLUG 2
  535. #define NNN_OPENER 3
  536. #define NNN_COLORS 4
  537. #define NNNLVL 5
  538. #define NNN_PIPE 6
  539. #define NNN_MCLICK 7
  540. #define NNN_ARCHIVE 8 /* strings end here */
  541. #define NNN_TRASH 9 /* flags begin here */
  542. static const char * const env_cfg[] = {
  543. "NNN_OPTS",
  544. "NNN_BMS",
  545. "NNN_PLUG",
  546. "NNN_OPENER",
  547. "NNN_COLORS",
  548. "NNNLVL",
  549. "NNN_PIPE",
  550. "NNN_MCLICK",
  551. "NNN_ARCHIVE",
  552. "NNN_TRASH",
  553. };
  554. /* Required environment variables */
  555. #define ENV_SHELL 0
  556. #define ENV_VISUAL 1
  557. #define ENV_EDITOR 2
  558. #define ENV_PAGER 3
  559. #define ENV_NCUR 4
  560. static const char * const envs[] = {
  561. "SHELL",
  562. "VISUAL",
  563. "EDITOR",
  564. "PAGER",
  565. "nnn",
  566. };
  567. /* Time type used */
  568. #define T_ACCESS 0
  569. #define T_CHANGE 1
  570. #define T_MOD 2
  571. #ifdef __linux__
  572. static char cp[] = "cp -iRp";
  573. static char mv[] = "mv -i";
  574. #else
  575. static char cp[] = "cp -iRp";
  576. static char mv[] = "mv -i";
  577. #endif
  578. /* Patterns */
  579. #define P_CPMVFMT 0
  580. #define P_CPMVRNM 1
  581. #define P_ARCHIVE 2
  582. #define P_REPLACE 3
  583. static const char * const patterns[] = {
  584. "sed -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
  585. "sed 's|^\\([^#][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
  586. "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
  587. "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$",
  588. "sed -i 's|^%s\\(.*\\)$|%s\\1|' %s",
  589. };
  590. /* Event handling */
  591. #ifdef LINUX_INOTIFY
  592. #define NUM_EVENT_SLOTS 32 /* Make room for 8 events */
  593. #define EVENT_SIZE (sizeof(struct inotify_event))
  594. #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
  595. static int inotify_fd, inotify_wd = -1;
  596. static uint INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
  597. | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  598. #elif defined(BSD_KQUEUE)
  599. #define NUM_EVENT_SLOTS 1
  600. #define NUM_EVENT_FDS 1
  601. static int kq, event_fd = -1;
  602. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  603. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
  604. | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  605. static struct timespec gtimeout;
  606. #elif defined(HAIKU_NM)
  607. static bool haiku_nm_active = FALSE;
  608. static haiku_nm_h haiku_hnd;
  609. #endif
  610. /* Function macros */
  611. #define tolastln() move(xlines - 1, 0)
  612. #define exitcurses() endwin()
  613. #define printwarn(presel) printwait(strerror(errno), presel)
  614. #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
  615. #define copycurname() xstrsncpy(lastname, dents[cur].name, NAME_MAX + 1)
  616. #define settimeout() timeout(1000)
  617. #define cleartimeout() timeout(-1)
  618. #define errexit() printerr(__LINE__)
  619. #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
  620. #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
  621. /* We don't care about the return value from strcmp() */
  622. #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
  623. /* A faster version of xisdigit */
  624. #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
  625. #define xerror() perror(xitoa(__LINE__))
  626. #ifdef __GNUC__
  627. #define UNUSED(x) UNUSED_##x __attribute__((__unused__))
  628. #else
  629. #define UNUSED(x) UNUSED_##x
  630. #endif /* __GNUC__ */
  631. /* Forward declarations */
  632. static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n);
  633. static void redraw(char *path);
  634. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag);
  635. static int (*nftw_fn)(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  636. static int dentfind(const char *fname, int n);
  637. static void move_cursor(int target, int ignore_scrolloff);
  638. static inline bool getutil(char *util);
  639. static size_t mkpath(const char *dir, const char *name, char *out);
  640. static char *xgetenv(const char *name, char *fallback);
  641. static bool plugscript(const char *plugin, const char *path, uchar flags);
  642. /* Functions */
  643. static void sigint_handler(int UNUSED(sig))
  644. {
  645. g_states |= STATE_INTERRUPTED;
  646. }
  647. static char *xitoa(uint val)
  648. {
  649. static char ascbuf[32] = {0};
  650. int i = 30;
  651. uint rem;
  652. if (!val)
  653. return "0";
  654. while (val && i) {
  655. rem = val / 10;
  656. ascbuf[i] = '0' + (val - (rem * 10));
  657. val = rem;
  658. --i;
  659. }
  660. return &ascbuf[++i];
  661. }
  662. /*
  663. * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
  664. */
  665. static bool test_set_bit(uint nr)
  666. {
  667. nr &= HASH_BITS;
  668. ull *m = ((ull *)ihashbmp) + (nr >> 6);
  669. if (*m & (1 << (nr & 63)))
  670. return FALSE;
  671. *m |= 1 << (nr & 63);
  672. return TRUE;
  673. }
  674. #if 0
  675. static bool test_clear_bit(uint nr)
  676. {
  677. nr &= HASH_BITS;
  678. ull *m = ((ull *) ihashbmp) + (nr >> 6);
  679. if (!(*m & (1 << (nr & 63))))
  680. return FALSE;
  681. *m &= ~(1 << (nr & 63));
  682. return TRUE;
  683. }
  684. #endif
  685. static void clearinfoln(void)
  686. {
  687. move(xlines - 2, 0);
  688. clrtoeol();
  689. }
  690. #ifdef KEY_RESIZE
  691. /* Clear the old prompt */
  692. static void clearoldprompt(void)
  693. {
  694. clearinfoln();
  695. tolastln();
  696. addch('\n');
  697. }
  698. #endif
  699. /* Messages show up at the bottom */
  700. static inline void printmsg_nc(const char *msg)
  701. {
  702. tolastln();
  703. addstr(msg);
  704. addch('\n');
  705. }
  706. static void printmsg(const char *msg)
  707. {
  708. attron(COLOR_PAIR(cfg.curctx + 1));
  709. printmsg_nc(msg);
  710. attroff(COLOR_PAIR(cfg.curctx + 1));
  711. }
  712. static void printwait(const char *msg, int *presel)
  713. {
  714. printmsg(msg);
  715. if (presel) {
  716. *presel = MSGWAIT;
  717. if (ndents)
  718. xstrsncpy(g_ctx[cfg.curctx].c_name, dents[cur].name, NAME_MAX + 1);
  719. }
  720. }
  721. /* Kill curses and display error before exiting */
  722. static void printerr(int linenum)
  723. {
  724. exitcurses();
  725. perror(xitoa(linenum));
  726. if (!cfg.picker && selpath)
  727. unlink(selpath);
  728. free(pselbuf);
  729. exit(1);
  730. }
  731. static inline bool xconfirm(int c)
  732. {
  733. return (c == 'y' || c == 'Y');
  734. }
  735. static int get_input(const char *prompt)
  736. {
  737. int r;
  738. if (prompt)
  739. printmsg(prompt);
  740. cleartimeout();
  741. #ifdef KEY_RESIZE
  742. do {
  743. r = getch();
  744. if (r == KEY_RESIZE && prompt) {
  745. clearoldprompt();
  746. xlines = LINES;
  747. printmsg(prompt);
  748. }
  749. } while (r == KEY_RESIZE);
  750. #else
  751. r = getch();
  752. #endif
  753. settimeout();
  754. return r;
  755. }
  756. static int get_cur_or_sel(void)
  757. {
  758. if (selbufpos && ndents) {
  759. int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
  760. return ((choice == 'c' || choice == 's') ? choice : 0);
  761. }
  762. if (selbufpos)
  763. return 's';
  764. if (ndents)
  765. return 'c';
  766. return 0;
  767. }
  768. static void xdelay(useconds_t delay)
  769. {
  770. refresh();
  771. usleep(delay);
  772. }
  773. static char confirm_force(bool selection)
  774. {
  775. char str[32];
  776. snprintf(str, 32, messages[MSG_FORCE_RM],
  777. (selection ? xitoa(nselected) : "current"), (selection ? "(s)" : ""));
  778. if (xconfirm(get_input(str)))
  779. return 'f'; /* forceful */
  780. return 'i'; /* interactive */
  781. }
  782. /* Increase the limit on open file descriptors, if possible */
  783. static rlim_t max_openfds(void)
  784. {
  785. struct rlimit rl;
  786. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  787. if (!limit) {
  788. limit = rl.rlim_cur;
  789. rl.rlim_cur = rl.rlim_max;
  790. /* Return ~75% of max possible */
  791. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  792. limit = rl.rlim_max - (rl.rlim_max >> 2);
  793. /*
  794. * 20K is arbitrary. If the limit is set to max possible
  795. * value, the memory usage increases to more than double.
  796. */
  797. if (limit > 20480)
  798. limit = 20480;
  799. }
  800. } else
  801. limit = 32;
  802. return limit;
  803. }
  804. /*
  805. * Wrapper to realloc()
  806. * Frees current memory if realloc() fails and returns NULL.
  807. *
  808. * As per the docs, the *alloc() family is supposed to be memory aligned:
  809. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  810. * macOS: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  811. */
  812. static void *xrealloc(void *pcur, size_t len)
  813. {
  814. void *pmem = realloc(pcur, len);
  815. if (!pmem)
  816. free(pcur);
  817. return pmem;
  818. }
  819. /*
  820. * Just a safe strncpy(3)
  821. * Always null ('\0') terminates if both src and dest are valid pointers.
  822. * Returns the number of bytes copied including terminating null byte.
  823. */
  824. static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
  825. {
  826. char *end = memccpy(dst, src, '\0', n);
  827. if (!end) {
  828. dst[n - 1] = '\0'; // NOLINT
  829. end = dst + n;
  830. }
  831. return end - dst;
  832. }
  833. static inline size_t xstrlen(const char *s)
  834. {
  835. #if !defined(__GLIBC__)
  836. return strlen(s); // NOLINT
  837. #else
  838. return (char *)rawmemchr(s, '\0') - s; // NOLINT
  839. #endif
  840. }
  841. static char *xstrdup(const char *s)
  842. {
  843. size_t len = xstrlen(s) + 1;
  844. char *ptr = malloc(len);
  845. if (ptr)
  846. xstrsncpy(ptr, s, len);
  847. return ptr;
  848. }
  849. static bool is_suffix(const char *str, const char *suffix)
  850. {
  851. if (!str || !suffix)
  852. return FALSE;
  853. size_t lenstr = xstrlen(str);
  854. size_t lensuffix = xstrlen(suffix);
  855. if (lensuffix > lenstr)
  856. return FALSE;
  857. return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
  858. }
  859. /*
  860. * The poor man's implementation of memrchr(3).
  861. * We are only looking for '/' in this program.
  862. * And we are NOT expecting a '/' at the end.
  863. * Ideally 0 < n <= xstrlen(s).
  864. */
  865. static void *xmemrchr(uchar *s, uchar ch, size_t n)
  866. {
  867. if (!s || !n)
  868. return NULL;
  869. uchar *ptr = s + n;
  870. do
  871. if (*--ptr == ch)
  872. return ptr;
  873. while (s != ptr);
  874. return NULL;
  875. }
  876. /* Assumes both the paths passed are directories */
  877. static char *common_prefix(const char *path, char *prefix)
  878. {
  879. const char *x = path, *y = prefix;
  880. char *sep;
  881. if (!path || !*path || !prefix)
  882. return NULL;
  883. if (!*prefix) {
  884. xstrsncpy(prefix, path, PATH_MAX);
  885. return prefix;
  886. }
  887. while (*x && *y && (*x == *y))
  888. ++x, ++y;
  889. /* Strings are same */
  890. if (!*x && !*y)
  891. return prefix;
  892. /* Path is shorter */
  893. if (!*x && *y == '/') {
  894. xstrsncpy(prefix, path, y - path);
  895. return prefix;
  896. }
  897. /* Prefix is shorter */
  898. if (!*y && *x == '/')
  899. return prefix;
  900. /* Shorten prefix */
  901. prefix[y - prefix] = '\0';
  902. sep = xmemrchr((uchar *)prefix, '/', y - prefix);
  903. if (sep != prefix)
  904. *sep = '\0';
  905. else /* Just '/' */
  906. prefix[1] = '\0';
  907. return prefix;
  908. }
  909. /*
  910. * The library function realpath() resolves symlinks.
  911. * If there's a symlink in file list we want to show the symlink not what it's points to.
  912. */
  913. static char *abspath(const char *path, const char *cwd)
  914. {
  915. if (!path || !cwd)
  916. return NULL;
  917. size_t dst_size = 0, src_size = xstrlen(path), cwd_size = xstrlen(cwd);
  918. const char *src;
  919. char *dst;
  920. char *resolved_path = malloc(src_size + (*path == '/' ? 0 : cwd_size) + 1);
  921. if (!resolved_path)
  922. return NULL;
  923. /* Turn relative paths into absolute */
  924. if (path[0] != '/')
  925. dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
  926. else
  927. resolved_path[0] = '\0';
  928. src = path;
  929. dst = resolved_path + dst_size;
  930. for (const char *next = NULL; next != path + src_size;) {
  931. next = strchr(src, '/');
  932. if (!next)
  933. next = path + src_size;
  934. if (next - src == 2 && src[0] == '.' && src[1] == '.') {
  935. if (dst - resolved_path) {
  936. dst = xmemrchr((uchar *)resolved_path, '/', dst - resolved_path);
  937. *dst = '\0';
  938. }
  939. } else if (next - src == 1 && src[0] == '.') {
  940. /* NOP */
  941. } else if (next - src) {
  942. *(dst++) = '/';
  943. xstrsncpy(dst, src, next - src + 1);
  944. dst += next - src;
  945. }
  946. src = next + 1;
  947. }
  948. if (*resolved_path == '\0') {
  949. resolved_path[0] = '/';
  950. resolved_path[1] = '\0';
  951. }
  952. return resolved_path;
  953. }
  954. /* A very simplified implementation, changes path */
  955. static char *xdirname(char *path)
  956. {
  957. char *base = xmemrchr((uchar *)path, '/', xstrlen(path));
  958. if (base == path)
  959. path[1] = '\0';
  960. else
  961. *base = '\0';
  962. return path;
  963. }
  964. static char *xbasename(char *path)
  965. {
  966. char *base = xmemrchr((uchar *)path, '/', xstrlen(path)); // NOLINT
  967. return base ? base + 1 : path;
  968. }
  969. static int create_tmp_file(void)
  970. {
  971. xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
  972. int fd = mkstemp(g_tmpfpath);
  973. if (fd == -1) {
  974. DPRINTF_S(strerror(errno));
  975. }
  976. return fd;
  977. }
  978. /* Writes buflen char(s) from buf to a file */
  979. static void writesel(const char *buf, const size_t buflen)
  980. {
  981. if (cfg.pickraw || !selpath)
  982. return;
  983. FILE *fp = fopen(selpath, "w");
  984. if (fp) {
  985. if (fwrite(buf, 1, buflen, fp) != buflen)
  986. printwarn(NULL);
  987. fclose(fp);
  988. } else
  989. printwarn(NULL);
  990. }
  991. static void appendfpath(const char *path, const size_t len)
  992. {
  993. if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
  994. selbuflen += PATH_MAX;
  995. pselbuf = xrealloc(pselbuf, selbuflen);
  996. if (!pselbuf)
  997. errexit();
  998. }
  999. selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
  1000. }
  1001. /* Write selected file paths to fd, linefeed separated */
  1002. static size_t seltofile(int fd, uint *pcount)
  1003. {
  1004. uint lastpos, count = 0;
  1005. char *pbuf = pselbuf;
  1006. size_t pos = 0, len;
  1007. ssize_t r;
  1008. if (pcount)
  1009. *pcount = 0;
  1010. if (!selbufpos)
  1011. return 0;
  1012. lastpos = selbufpos - 1;
  1013. while (pos <= lastpos) {
  1014. len = xstrlen(pbuf);
  1015. pos += len;
  1016. r = write(fd, pbuf, len);
  1017. if (r != (ssize_t)len)
  1018. return pos;
  1019. if (pos <= lastpos) {
  1020. if (write(fd, "\n", 1) != 1)
  1021. return pos;
  1022. pbuf += len + 1;
  1023. }
  1024. ++pos;
  1025. ++count;
  1026. }
  1027. if (pcount)
  1028. *pcount = count;
  1029. return pos;
  1030. }
  1031. /* List selection from selection file (another instance) */
  1032. static bool listselfile(void)
  1033. {
  1034. struct stat sb;
  1035. if (stat(selpath, &sb) == -1)
  1036. return FALSE;
  1037. /* Nothing selected if file size is 0 */
  1038. if (!sb.st_size)
  1039. return FALSE;
  1040. snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
  1041. spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
  1042. return TRUE;
  1043. }
  1044. /* Reset selection indicators */
  1045. static void resetselind(void)
  1046. {
  1047. for (int r = 0; r < ndents; ++r)
  1048. if (dents[r].flags & FILE_SELECTED)
  1049. dents[r].flags &= ~FILE_SELECTED;
  1050. }
  1051. static void startselection(void)
  1052. {
  1053. if (!cfg.selmode) {
  1054. cfg.selmode = 1;
  1055. nselected = 0;
  1056. if (selbufpos) {
  1057. resetselind();
  1058. writesel(NULL, 0);
  1059. selbufpos = 0;
  1060. }
  1061. lastappendpos = 0;
  1062. }
  1063. }
  1064. static void updateselbuf(const char *path, char *newpath)
  1065. {
  1066. size_t r;
  1067. for (int i = 0; i < ndents; ++i)
  1068. if (dents[i].flags & FILE_SELECTED) {
  1069. r = mkpath(path, dents[i].name, newpath);
  1070. appendfpath(newpath, r);
  1071. }
  1072. }
  1073. /* Finish selection procedure before an operation */
  1074. static void endselection(void)
  1075. {
  1076. int fd;
  1077. ssize_t count;
  1078. char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
  1079. if (cfg.selmode)
  1080. cfg.selmode = 0;
  1081. if (!listpath || !selbufpos)
  1082. return;
  1083. fd = create_tmp_file();
  1084. if (fd == -1) {
  1085. DPRINTF_S("couldn't create tmp file");
  1086. return;
  1087. }
  1088. seltofile(fd, NULL);
  1089. if (close(fd)) {
  1090. DPRINTF_S(strerror(errno));
  1091. printwarn(NULL);
  1092. return;
  1093. }
  1094. snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, prefixpath, g_tmpfpath);
  1095. spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
  1096. fd = open(g_tmpfpath, O_RDONLY);
  1097. if (fd == -1) {
  1098. DPRINTF_S(strerror(errno));
  1099. printwarn(NULL);
  1100. if (unlink(g_tmpfpath)) {
  1101. DPRINTF_S(strerror(errno));
  1102. printwarn(NULL);
  1103. }
  1104. return;
  1105. }
  1106. count = read(fd, pselbuf, selbuflen);
  1107. if (count < 0) {
  1108. DPRINTF_S(strerror(errno));
  1109. printwarn(NULL);
  1110. if (close(fd) || unlink(g_tmpfpath)) {
  1111. DPRINTF_S(strerror(errno));
  1112. }
  1113. return;
  1114. }
  1115. if (close(fd) || unlink(g_tmpfpath)) {
  1116. DPRINTF_S(strerror(errno));
  1117. printwarn(NULL);
  1118. return;
  1119. }
  1120. selbufpos = count;
  1121. pselbuf[--count] = '\0';
  1122. for (--count; count > 0; --count)
  1123. if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
  1124. pselbuf[count] = '\0';
  1125. writesel(pselbuf, selbufpos - 1);
  1126. }
  1127. static void clearselection(void)
  1128. {
  1129. nselected = 0;
  1130. selbufpos = 0;
  1131. cfg.selmode = 0;
  1132. writesel(NULL, 0);
  1133. }
  1134. /* Returns: 1 - success, 0 - none selected, -1 - other failure */
  1135. static int editselection(void)
  1136. {
  1137. int ret = -1;
  1138. int fd, lines = 0;
  1139. ssize_t count;
  1140. struct stat sb;
  1141. time_t mtime;
  1142. if (!selbufpos)
  1143. return listselfile();
  1144. fd = create_tmp_file();
  1145. if (fd == -1) {
  1146. DPRINTF_S("couldn't create tmp file");
  1147. return -1;
  1148. }
  1149. seltofile(fd, NULL);
  1150. if (close(fd)) {
  1151. DPRINTF_S(strerror(errno));
  1152. return -1;
  1153. }
  1154. /* Save the last modification time */
  1155. if (stat(g_tmpfpath, &sb)) {
  1156. DPRINTF_S(strerror(errno));
  1157. unlink(g_tmpfpath);
  1158. return -1;
  1159. }
  1160. mtime = sb.st_mtime;
  1161. spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
  1162. fd = open(g_tmpfpath, O_RDONLY);
  1163. if (fd == -1) {
  1164. DPRINTF_S(strerror(errno));
  1165. unlink(g_tmpfpath);
  1166. return -1;
  1167. }
  1168. fstat(fd, &sb);
  1169. if (mtime == sb.st_mtime) {
  1170. DPRINTF_S("selection is not modified");
  1171. unlink(g_tmpfpath);
  1172. return 1;
  1173. }
  1174. if (sb.st_size > selbufpos) {
  1175. DPRINTF_S("edited buffer larger than previous");
  1176. unlink(g_tmpfpath);
  1177. goto emptyedit;
  1178. }
  1179. count = read(fd, pselbuf, selbuflen);
  1180. if (count < 0) {
  1181. DPRINTF_S(strerror(errno));
  1182. printwarn(NULL);
  1183. if (close(fd) || unlink(g_tmpfpath)) {
  1184. DPRINTF_S(strerror(errno));
  1185. printwarn(NULL);
  1186. }
  1187. goto emptyedit;
  1188. }
  1189. if (close(fd) || unlink(g_tmpfpath)) {
  1190. DPRINTF_S(strerror(errno));
  1191. printwarn(NULL);
  1192. goto emptyedit;
  1193. }
  1194. if (!count) {
  1195. ret = 1;
  1196. goto emptyedit;
  1197. }
  1198. resetselind();
  1199. selbufpos = count;
  1200. /* The last character should be '\n' */
  1201. pselbuf[--count] = '\0';
  1202. for (--count; count > 0; --count) {
  1203. /* Replace every '\n' that separates two paths */
  1204. if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
  1205. ++lines;
  1206. pselbuf[count] = '\0';
  1207. }
  1208. }
  1209. /* Add a line for the last file */
  1210. ++lines;
  1211. if (lines > nselected) {
  1212. DPRINTF_S("files added to selection");
  1213. goto emptyedit;
  1214. }
  1215. nselected = lines;
  1216. writesel(pselbuf, selbufpos - 1);
  1217. return 1;
  1218. emptyedit:
  1219. resetselind();
  1220. clearselection();
  1221. return ret;
  1222. }
  1223. static bool selsafe(void)
  1224. {
  1225. /* Fail if selection file path not generated */
  1226. if (!selpath) {
  1227. printmsg(messages[MSG_SEL_MISSING]);
  1228. return FALSE;
  1229. }
  1230. /* Fail if selection file path isn't accessible */
  1231. if (access(selpath, R_OK | W_OK) == -1) {
  1232. errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
  1233. return FALSE;
  1234. }
  1235. return TRUE;
  1236. }
  1237. static void export_file_list(void)
  1238. {
  1239. if (!ndents)
  1240. return;
  1241. struct entry *pdent = dents;
  1242. int fd = create_tmp_file();
  1243. if (fd == -1) {
  1244. DPRINTF_S(strerror(errno));
  1245. return;
  1246. }
  1247. for (int r = 0; r < ndents; ++pdent, ++r) {
  1248. if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
  1249. break;
  1250. if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
  1251. break;
  1252. }
  1253. if (close(fd)) {
  1254. DPRINTF_S(strerror(errno));
  1255. }
  1256. spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
  1257. if (xconfirm(get_input(messages[MSG_RM_TMP])))
  1258. unlink(g_tmpfpath);
  1259. }
  1260. /* Initialize curses mode */
  1261. static bool initcurses(void *oldmask)
  1262. {
  1263. #ifdef NOMOUSE
  1264. (void) oldmask;
  1265. #endif
  1266. if (cfg.picker) {
  1267. if (!newterm(NULL, stderr, stdin)) {
  1268. fprintf(stderr, "newterm!\n");
  1269. return FALSE;
  1270. }
  1271. } else if (!initscr()) {
  1272. fprintf(stderr, "initscr!\n");
  1273. DPRINTF_S(getenv("TERM"));
  1274. return FALSE;
  1275. }
  1276. cbreak();
  1277. noecho();
  1278. nonl();
  1279. //intrflush(stdscr, FALSE);
  1280. keypad(stdscr, TRUE);
  1281. #ifndef NOMOUSE
  1282. #if NCURSES_MOUSE_VERSION <= 1
  1283. mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
  1284. (mmask_t *)oldmask);
  1285. #else
  1286. mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED | BUTTON5_PRESSED,
  1287. (mmask_t *)oldmask);
  1288. #endif
  1289. mouseinterval(0);
  1290. #endif
  1291. curs_set(FALSE); /* Hide cursor */
  1292. char *colors = getenv(env_cfg[NNN_COLORS]);
  1293. if (colors || !getenv("NO_COLOR")) {
  1294. start_color();
  1295. use_default_colors();
  1296. /* Get and set the context colors */
  1297. for (uchar i = 0; i < CTX_MAX; ++i) {
  1298. if (colors && *colors) {
  1299. g_ctx[i].color = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
  1300. ++colors;
  1301. } else
  1302. g_ctx[i].color = 4;
  1303. init_pair(i + 1, g_ctx[i].color, -1);
  1304. }
  1305. }
  1306. settimeout(); /* One second */
  1307. set_escdelay(25);
  1308. return TRUE;
  1309. }
  1310. /* No NULL check here as spawn() guards against it */
  1311. static int parseargs(char *line, char **argv)
  1312. {
  1313. int count = 0;
  1314. argv[count++] = line;
  1315. while (*line) { // NOLINT
  1316. if (ISBLANK(*line)) {
  1317. *line++ = '\0';
  1318. if (!*line) // NOLINT
  1319. return count;
  1320. argv[count++] = line;
  1321. if (count == EXEC_ARGS_MAX)
  1322. return -1;
  1323. }
  1324. ++line;
  1325. }
  1326. return count;
  1327. }
  1328. static pid_t xfork(uchar flag)
  1329. {
  1330. int status;
  1331. pid_t p = fork();
  1332. if (p > 0) {
  1333. /* the parent ignores the interrupt, quit and hangup signals */
  1334. oldsighup = signal(SIGHUP, SIG_IGN);
  1335. oldsigtstp = signal(SIGTSTP, SIG_DFL);
  1336. } else if (p == 0) {
  1337. /* We create a grandchild to detach */
  1338. if (flag & F_NOWAIT) {
  1339. p = fork();
  1340. if (p > 0)
  1341. _exit(0);
  1342. else if (p == 0) {
  1343. signal(SIGHUP, SIG_DFL);
  1344. signal(SIGINT, SIG_DFL);
  1345. signal(SIGQUIT, SIG_DFL);
  1346. signal(SIGTSTP, SIG_DFL);
  1347. setsid();
  1348. return p;
  1349. }
  1350. perror("fork");
  1351. _exit(0);
  1352. }
  1353. /* so they can be used to stop the child */
  1354. signal(SIGHUP, SIG_DFL);
  1355. signal(SIGINT, SIG_DFL);
  1356. signal(SIGQUIT, SIG_DFL);
  1357. signal(SIGTSTP, SIG_DFL);
  1358. }
  1359. /* This is the parent waiting for the child to create grandchild*/
  1360. if (flag & F_NOWAIT)
  1361. waitpid(p, &status, 0);
  1362. if (p == -1)
  1363. perror("fork");
  1364. return p;
  1365. }
  1366. static int join(pid_t p, uchar flag)
  1367. {
  1368. int status = 0xFFFF;
  1369. if (!(flag & F_NOWAIT)) {
  1370. /* wait for the child to exit */
  1371. do {
  1372. } while (waitpid(p, &status, 0) == -1);
  1373. if (WIFEXITED(status)) {
  1374. status = WEXITSTATUS(status);
  1375. DPRINTF_D(status);
  1376. }
  1377. }
  1378. /* restore parent's signal handling */
  1379. signal(SIGHUP, oldsighup);
  1380. signal(SIGTSTP, oldsigtstp);
  1381. return status;
  1382. }
  1383. /*
  1384. * Spawns a child process. Behaviour can be controlled using flag.
  1385. * Limited to 2 arguments to a program, flag works on bit set.
  1386. */
  1387. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag)
  1388. {
  1389. pid_t pid;
  1390. int status = 0, retstatus = 0xFFFF;
  1391. char *argv[EXEC_ARGS_MAX] = {0};
  1392. char *cmd = NULL;
  1393. if (!file || !*file)
  1394. return retstatus;
  1395. /* Swap args if the first arg is NULL and second isn't */
  1396. if (!arg1 && arg2) {
  1397. arg1 = arg2;
  1398. arg2 = NULL;
  1399. }
  1400. if (flag & F_MULTI) {
  1401. size_t len = xstrlen(file) + 1;
  1402. cmd = (char *)malloc(len);
  1403. if (!cmd) {
  1404. DPRINTF_S("malloc()!");
  1405. return retstatus;
  1406. }
  1407. xstrsncpy(cmd, file, len);
  1408. status = parseargs(cmd, argv);
  1409. if (status == -1 || status > (EXEC_ARGS_MAX - 3)) { /* arg1, arg2 and last NULL */
  1410. free(cmd);
  1411. DPRINTF_S("NULL or too many args");
  1412. return retstatus;
  1413. }
  1414. } else
  1415. argv[status++] = file;
  1416. argv[status] = arg1;
  1417. argv[++status] = arg2;
  1418. if (flag & F_NORMAL)
  1419. exitcurses();
  1420. pid = xfork(flag);
  1421. if (pid == 0) {
  1422. if (dir && chdir(dir) == -1)
  1423. _exit(1);
  1424. /* Suppress stdout and stderr */
  1425. if (flag & F_NOTRACE) {
  1426. int fd = open("/dev/null", O_WRONLY, 0200);
  1427. dup2(fd, 1);
  1428. dup2(fd, 2);
  1429. close(fd);
  1430. }
  1431. execvp(*argv, argv);
  1432. _exit(1);
  1433. } else {
  1434. retstatus = join(pid, flag);
  1435. DPRINTF_D(pid);
  1436. if (flag & F_NORMAL) {
  1437. if (flag & F_CONFIRM) {
  1438. printf("%s", messages[MSG_CONTINUE]);
  1439. #ifndef NORL
  1440. fflush(stdout);
  1441. #endif
  1442. while (getchar() != '\n');
  1443. }
  1444. refresh();
  1445. }
  1446. free(cmd);
  1447. }
  1448. return retstatus;
  1449. }
  1450. static void prompt_run(char *cmd, const char *cur, const char *path)
  1451. {
  1452. setenv(envs[ENV_NCUR], cur, 1);
  1453. spawn(shell, "-c", cmd, path, F_CLI | F_CONFIRM);
  1454. }
  1455. /* Get program name from env var, else return fallback program */
  1456. static char *xgetenv(const char * const name, char *fallback)
  1457. {
  1458. char *value = getenv(name);
  1459. return value && value[0] ? value : fallback;
  1460. }
  1461. /* Checks if an env variable is set to 1 */
  1462. static bool xgetenv_set(const char *name)
  1463. {
  1464. char *value = getenv(name);
  1465. if (value && value[0] == '1' && !value[1])
  1466. return TRUE;
  1467. return FALSE;
  1468. }
  1469. /* Check if a dir exists, IS a dir and is readable */
  1470. static bool xdiraccess(const char *path)
  1471. {
  1472. DIR *dirp = opendir(path);
  1473. if (!dirp) {
  1474. printwarn(NULL);
  1475. return FALSE;
  1476. }
  1477. closedir(dirp);
  1478. return TRUE;
  1479. }
  1480. static void opstr(char *buf, char *op)
  1481. {
  1482. snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s",
  1483. op, selpath);
  1484. }
  1485. static void rmmulstr(char *buf)
  1486. {
  1487. if (g_states & STATE_TRASH)
  1488. snprintf(buf, CMD_LEN_MAX, "xargs -0 trash-put < %s", selpath);
  1489. else
  1490. snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
  1491. confirm_force(TRUE), selpath);
  1492. }
  1493. static void xrm(char *path)
  1494. {
  1495. if (g_states & STATE_TRASH)
  1496. spawn("trash-put", path, NULL, NULL, F_NORMAL);
  1497. else {
  1498. char rm_opts[] = "-ir";
  1499. rm_opts[1] = confirm_force(FALSE);
  1500. spawn("rm", rm_opts, path, NULL, F_NORMAL);
  1501. }
  1502. }
  1503. static uint lines_in_file(int fd, char *buf, size_t buflen)
  1504. {
  1505. ssize_t len;
  1506. uint count = 0;
  1507. while ((len = read(fd, buf, buflen)) > 0)
  1508. while (len)
  1509. count += (buf[--len] == '\n');
  1510. /* For all use cases 0 linecount is considered as error */
  1511. return ((len < 0) ? 0 : count);
  1512. }
  1513. static bool cpmv_rename(int choice, const char *path)
  1514. {
  1515. int fd;
  1516. uint count = 0, lines = 0;
  1517. bool ret = FALSE;
  1518. char *cmd = (choice == 'c' ? cp : mv);
  1519. char buf[sizeof(patterns[P_CPMVRNM]) + sizeof(cmd) + (PATH_MAX << 1)];
  1520. fd = create_tmp_file();
  1521. if (fd == -1)
  1522. return ret;
  1523. /* selsafe() returned TRUE for this to be called */
  1524. if (!selbufpos) {
  1525. snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
  1526. spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
  1527. count = lines_in_file(fd, buf, sizeof(buf));
  1528. if (!count)
  1529. goto finish;
  1530. } else
  1531. seltofile(fd, &count);
  1532. close(fd);
  1533. snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
  1534. spawn(utils[UTIL_SH_EXEC], buf, NULL, path, F_CLI);
  1535. spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, path, F_CLI);
  1536. fd = open(g_tmpfpath, O_RDONLY);
  1537. if (fd == -1)
  1538. goto finish;
  1539. lines = lines_in_file(fd, buf, sizeof(buf));
  1540. DPRINTF_U(count);
  1541. DPRINTF_U(lines);
  1542. if (!lines || (2 * count != lines)) {
  1543. DPRINTF_S("num mismatch");
  1544. goto finish;
  1545. }
  1546. snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
  1547. spawn(utils[UTIL_SH_EXEC], buf, NULL, path, F_CLI);
  1548. ret = TRUE;
  1549. finish:
  1550. if (fd >= 0)
  1551. close(fd);
  1552. return ret;
  1553. }
  1554. static bool cpmvrm_selection(enum action sel, char *path)
  1555. {
  1556. int r;
  1557. if (!selsafe())
  1558. return FALSE;
  1559. switch (sel) {
  1560. case SEL_CP:
  1561. opstr(g_buf, cp);
  1562. break;
  1563. case SEL_MV:
  1564. opstr(g_buf, mv);
  1565. break;
  1566. case SEL_CPMVAS:
  1567. r = get_input(messages[MSG_CP_MV_AS]);
  1568. if (r != 'c' && r != 'm') {
  1569. printmsg(messages[MSG_INVALID_KEY]);
  1570. return FALSE;
  1571. }
  1572. if (!cpmv_rename(r, path)) {
  1573. printmsg(messages[MSG_FAILED]);
  1574. return FALSE;
  1575. }
  1576. break;
  1577. default: /* SEL_RM */
  1578. rmmulstr(g_buf);
  1579. break;
  1580. }
  1581. if (sel != SEL_CPMVAS)
  1582. spawn(utils[UTIL_SH_EXEC], g_buf, NULL, path, F_CLI);
  1583. /* Clear selection on move or delete */
  1584. if (sel != SEL_CP)
  1585. clearselection();
  1586. return TRUE;
  1587. }
  1588. #ifndef NOBATCH
  1589. static bool batch_rename(const char *path)
  1590. {
  1591. int fd1, fd2;
  1592. uint count = 0, lines = 0;
  1593. bool dir = FALSE, ret = FALSE;
  1594. char foriginal[TMP_LEN_MAX] = {0};
  1595. static const char batchrenamecmd[] = "paste -d'\n' %s %s | sed 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
  1596. "tr '\n' '\\0' | xargs -0 -n2 mv 2>/dev/null";
  1597. char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
  1598. int i = get_cur_or_sel();
  1599. if (!i)
  1600. return ret;
  1601. if (i == 'c') { /* Rename entries in current dir */
  1602. selbufpos = 0;
  1603. dir = TRUE;
  1604. }
  1605. fd1 = create_tmp_file();
  1606. if (fd1 == -1)
  1607. return ret;
  1608. xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
  1609. fd2 = create_tmp_file();
  1610. if (fd2 == -1) {
  1611. unlink(foriginal);
  1612. close(fd1);
  1613. return ret;
  1614. }
  1615. if (dir)
  1616. for (i = 0; i < ndents; ++i)
  1617. appendfpath(dents[i].name, NAME_MAX);
  1618. seltofile(fd1, &count);
  1619. seltofile(fd2, NULL);
  1620. close(fd2);
  1621. if (dir) /* Don't retain dir entries in selection */
  1622. selbufpos = 0;
  1623. spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, path, F_CLI);
  1624. /* Reopen file descriptor to get updated contents */
  1625. fd2 = open(g_tmpfpath, O_RDONLY);
  1626. if (fd2 == -1)
  1627. goto finish;
  1628. lines = lines_in_file(fd2, buf, sizeof(buf));
  1629. DPRINTF_U(count);
  1630. DPRINTF_U(lines);
  1631. if (!lines || (count != lines)) {
  1632. DPRINTF_S("cannot delete files");
  1633. goto finish;
  1634. }
  1635. snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
  1636. spawn(utils[UTIL_SH_EXEC], buf, NULL, path, F_CLI);
  1637. ret = TRUE;
  1638. finish:
  1639. if (fd1 >= 0)
  1640. close(fd1);
  1641. unlink(foriginal);
  1642. if (fd2 >= 0)
  1643. close(fd2);
  1644. unlink(g_tmpfpath);
  1645. return ret;
  1646. }
  1647. #endif
  1648. static void get_archive_cmd(char *cmd, const char *archive)
  1649. {
  1650. uchar i = 3;
  1651. const char *arcmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
  1652. if (getutil(utils[UTIL_ATOOL]))
  1653. i = 0;
  1654. else if (getutil(utils[UTIL_BSDTAR]))
  1655. i = 1;
  1656. else if (is_suffix(archive, ".zip"))
  1657. i = 2;
  1658. // else tar
  1659. xstrsncpy(cmd, arcmd[i], ARCHIVE_CMD_LEN);
  1660. }
  1661. static void archive_selection(const char *cmd, const char *archive, const char *curpath)
  1662. {
  1663. /* The 70 comes from the string below */
  1664. char *buf = (char *)malloc((70 + xstrlen(cmd) + xstrlen(archive)
  1665. + xstrlen(curpath) + xstrlen(selpath)) * sizeof(char));
  1666. if (!buf) {
  1667. DPRINTF_S(strerror(errno));
  1668. printwarn(NULL);
  1669. return;
  1670. }
  1671. snprintf(buf, CMD_LEN_MAX,
  1672. #ifdef __linux__
  1673. "sed -ze 's|^%s/||' '%s' | xargs -0 %s %s", curpath, selpath, cmd, archive);
  1674. #else
  1675. "tr '\\0' '\n' < '%s' | sed -e 's|^%s/||' | tr '\n' '\\0' | xargs -0 %s %s",
  1676. selpath, curpath, cmd, archive);
  1677. #endif
  1678. spawn(utils[UTIL_SH_EXEC], buf, NULL, curpath, F_CLI);
  1679. free(buf);
  1680. }
  1681. static bool write_lastdir(const char *curpath)
  1682. {
  1683. bool ret = TRUE;
  1684. size_t len = xstrlen(cfgdir);
  1685. xstrsncpy(cfgdir + len, "/.lastd", 8);
  1686. DPRINTF_S(cfgdir);
  1687. FILE *fp = fopen(cfgdir, "w");
  1688. if (fp) {
  1689. if (fprintf(fp, "cd \"%s\"", curpath) < 0)
  1690. ret = FALSE;
  1691. fclose(fp);
  1692. } else
  1693. ret = FALSE;
  1694. return ret;
  1695. }
  1696. /*
  1697. * We assume none of the strings are NULL.
  1698. *
  1699. * Let's have the logic to sort numeric names in numeric order.
  1700. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  1701. *
  1702. * If the absolute numeric values are same, we fallback to alphasort.
  1703. */
  1704. static int xstricmp(const char * const s1, const char * const s2)
  1705. {
  1706. char *p1, *p2;
  1707. ll v1 = strtoll(s1, &p1, 10);
  1708. ll v2 = strtoll(s2, &p2, 10);
  1709. /* Check if at least 1 string is numeric */
  1710. if (s1 != p1 || s2 != p2) {
  1711. /* Handle both pure numeric */
  1712. if (s1 != p1 && s2 != p2) {
  1713. if (v2 > v1)
  1714. return -1;
  1715. if (v1 > v2)
  1716. return 1;
  1717. }
  1718. /* Only first string non-numeric */
  1719. if (s1 == p1)
  1720. return 1;
  1721. /* Only second string non-numeric */
  1722. if (s2 == p2)
  1723. return -1;
  1724. }
  1725. /* Handle 1. all non-numeric and 2. both same numeric value cases */
  1726. #ifndef NOLOCALE
  1727. return strcoll(s1, s2);
  1728. #else
  1729. return strcasecmp(s1, s2);
  1730. #endif
  1731. }
  1732. /*
  1733. * Version comparison
  1734. *
  1735. * The code for version compare is a modified version of the GLIBC
  1736. * and uClibc implementation of strverscmp(). The source is here:
  1737. * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
  1738. */
  1739. /*
  1740. * Compare S1 and S2 as strings holding indices/version numbers,
  1741. * returning less than, equal to or greater than zero if S1 is less than,
  1742. * equal to or greater than S2 (for more info, see the texinfo doc).
  1743. *
  1744. * Ignores case.
  1745. */
  1746. static int xstrverscasecmp(const char * const s1, const char * const s2)
  1747. {
  1748. const uchar *p1 = (const uchar *)s1;
  1749. const uchar *p2 = (const uchar *)s2;
  1750. int state, diff;
  1751. uchar c1, c2;
  1752. /*
  1753. * Symbol(s) 0 [1-9] others
  1754. * Transition (10) 0 (01) d (00) x
  1755. */
  1756. static const uint8_t next_state[] = {
  1757. /* state x d 0 */
  1758. /* S_N */ S_N, S_I, S_Z,
  1759. /* S_I */ S_N, S_I, S_I,
  1760. /* S_F */ S_N, S_F, S_F,
  1761. /* S_Z */ S_N, S_F, S_Z
  1762. };
  1763. static const int8_t result_type[] __attribute__ ((aligned)) = {
  1764. /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
  1765. /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
  1766. /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
  1767. /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
  1768. /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
  1769. };
  1770. if (p1 == p2)
  1771. return 0;
  1772. c1 = TOUPPER(*p1);
  1773. ++p1;
  1774. c2 = TOUPPER(*p2);
  1775. ++p2;
  1776. /* Hint: '0' is a digit too. */
  1777. state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
  1778. while ((diff = c1 - c2) == 0) {
  1779. if (c1 == '\0')
  1780. return diff;
  1781. state = next_state[state];
  1782. c1 = TOUPPER(*p1);
  1783. ++p1;
  1784. c2 = TOUPPER(*p2);
  1785. ++p2;
  1786. state += (c1 == '0') + (xisdigit(c1) != 0);
  1787. }
  1788. state = (uchar)result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))];
  1789. switch (state) {
  1790. case VCMP:
  1791. return diff;
  1792. case VLEN:
  1793. while (xisdigit(*p1++))
  1794. if (!xisdigit(*p2++))
  1795. return 1;
  1796. return xisdigit(*p2) ? -1 : diff;
  1797. default:
  1798. return state;
  1799. }
  1800. }
  1801. static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
  1802. /* Return the integer value of a char representing HEX */
  1803. static char xchartohex(char c)
  1804. {
  1805. if (xisdigit(c))
  1806. return c - '0';
  1807. if (c >= 'a' && c <= 'f')
  1808. return c - 'a' + 10;
  1809. if (c >= 'A' && c <= 'F')
  1810. return c - 'A' + 10;
  1811. return c;
  1812. }
  1813. static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
  1814. #ifdef PCRE
  1815. static const unsigned char *tables;
  1816. static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
  1817. #else
  1818. static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
  1819. #endif
  1820. #ifdef PCRE
  1821. static int setfilter(pcre **pcrex, const char *filter)
  1822. {
  1823. const char *errstr = NULL;
  1824. int erroffset = 0;
  1825. *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
  1826. return errstr ? -1 : 0;
  1827. }
  1828. #else
  1829. static int setfilter(regex_t *regex, const char *filter)
  1830. {
  1831. return regcomp(regex, filter, regflags);
  1832. }
  1833. #endif
  1834. static int visible_re(const fltrexp_t *fltrexp, const char *fname)
  1835. {
  1836. #ifdef PCRE
  1837. return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
  1838. #else
  1839. return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
  1840. #endif
  1841. }
  1842. static int visible_str(const fltrexp_t *fltrexp, const char *fname)
  1843. {
  1844. return fnstrstr(fname, fltrexp->str) != NULL;
  1845. }
  1846. static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
  1847. static void clearfilter(void)
  1848. {
  1849. char *fltr = g_ctx[cfg.curctx].c_fltr;
  1850. if (fltr[1]) {
  1851. fltr[REGEX_MAX - 1] = fltr[1];
  1852. fltr[1] = '\0';
  1853. }
  1854. }
  1855. static int entrycmp(const void *va, const void *vb)
  1856. {
  1857. const struct entry *pa = (pEntry)va;
  1858. const struct entry *pb = (pEntry)vb;
  1859. if ((pb->flags & DIR_OR_LINK_TO_DIR) != (pa->flags & DIR_OR_LINK_TO_DIR)) {
  1860. if (pb->flags & DIR_OR_LINK_TO_DIR)
  1861. return 1;
  1862. return -1;
  1863. }
  1864. /* Sort based on specified order */
  1865. if (cfg.timeorder) {
  1866. if (pb->t > pa->t)
  1867. return 1;
  1868. if (pb->t < pa->t)
  1869. return -1;
  1870. } else if (cfg.sizeorder) {
  1871. if (pb->size > pa->size)
  1872. return 1;
  1873. if (pb->size < pa->size)
  1874. return -1;
  1875. } else if (cfg.blkorder) {
  1876. if (pb->blocks > pa->blocks)
  1877. return 1;
  1878. if (pb->blocks < pa->blocks)
  1879. return -1;
  1880. } else if (cfg.extnorder && !(pb->flags & DIR_OR_LINK_TO_DIR)) {
  1881. char *extna = xmemrchr((uchar *)pa->name, '.', pa->nlen - 1);
  1882. char *extnb = xmemrchr((uchar *)pb->name, '.', pb->nlen - 1);
  1883. if (extna || extnb) {
  1884. if (!extna)
  1885. return -1;
  1886. if (!extnb)
  1887. return 1;
  1888. int ret = strcasecmp(extna, extnb);
  1889. if (ret)
  1890. return ret;
  1891. }
  1892. }
  1893. return namecmpfn(pa->name, pb->name);
  1894. }
  1895. static int reventrycmp(const void *va, const void *vb)
  1896. {
  1897. if ((((pEntry)vb)->flags & DIR_OR_LINK_TO_DIR)
  1898. != (((pEntry)va)->flags & DIR_OR_LINK_TO_DIR)) {
  1899. if (((pEntry)vb)->flags & DIR_OR_LINK_TO_DIR)
  1900. return 1;
  1901. return -1;
  1902. }
  1903. return -entrycmp(va, vb);
  1904. }
  1905. static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
  1906. /*
  1907. * Returns SEL_* if key is bound and 0 otherwise.
  1908. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  1909. * The next keyboard input can be simulated by presel.
  1910. */
  1911. static int nextsel(int presel)
  1912. {
  1913. int c = presel;
  1914. uint i;
  1915. #ifdef LINUX_INOTIFY
  1916. struct inotify_event *event;
  1917. char inotify_buf[EVENT_BUF_LEN];
  1918. memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
  1919. #elif defined(BSD_KQUEUE)
  1920. struct kevent event_data[NUM_EVENT_SLOTS];
  1921. memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
  1922. #elif defined(HAIKU_NM)
  1923. // TODO: Do some Haiku declarations
  1924. #endif
  1925. if (c == 0 || c == MSGWAIT) {
  1926. c = getch();
  1927. //DPRINTF_D(c);
  1928. //DPRINTF_S(keyname(c));
  1929. if (c == ERR && presel == MSGWAIT)
  1930. c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
  1931. else if (c == FILTER || c == CONTROL('L'))
  1932. /* Clear previous filter when manually starting */
  1933. clearfilter();
  1934. }
  1935. if (c == -1) {
  1936. ++idle;
  1937. /*
  1938. * Do not check for directory changes in du mode.
  1939. * A redraw forces du calculation.
  1940. * Check for changes every odd second.
  1941. */
  1942. #ifdef LINUX_INOTIFY
  1943. if (!cfg.selmode && !cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
  1944. i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
  1945. if (i > 0) {
  1946. for (char *ptr = inotify_buf;
  1947. ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
  1948. ptr += sizeof(struct inotify_event) + event->len) {
  1949. event = (struct inotify_event *) ptr;
  1950. DPRINTF_D(event->wd);
  1951. DPRINTF_D(event->mask);
  1952. if (!event->wd)
  1953. break;
  1954. if (event->mask & INOTIFY_MASK) {
  1955. c = CONTROL('L');
  1956. DPRINTF_S("issue refresh");
  1957. break;
  1958. }
  1959. }
  1960. DPRINTF_S("inotify read done");
  1961. }
  1962. }
  1963. #elif defined(BSD_KQUEUE)
  1964. if (!cfg.selmode && !cfg.blkorder && event_fd >= 0 && idle & 1
  1965. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
  1966. event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  1967. c = CONTROL('L');
  1968. #elif defined(HAIKU_NM)
  1969. if (!cfg.selmode && !cfg.blkorder && haiku_nm_active && idle & 1 && haiku_is_update_needed(haiku_hnd))
  1970. c = CONTROL('L');
  1971. #endif
  1972. } else
  1973. idle = 0;
  1974. for (i = 0; i < (int)ELEMENTS(bindings); ++i)
  1975. if (c == bindings[i].sym)
  1976. return bindings[i].act;
  1977. return 0;
  1978. }
  1979. static int getorderstr(char *sort)
  1980. {
  1981. int i = 0;
  1982. if (cfg.timeorder)
  1983. sort[0] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
  1984. else if (cfg.sizeorder)
  1985. sort[0] = 'S';
  1986. else if (cfg.extnorder)
  1987. sort[0] = 'E';
  1988. if (sort[i])
  1989. ++i;
  1990. if (entrycmpfn == &reventrycmp) {
  1991. sort[i] = 'R';
  1992. ++i;
  1993. }
  1994. if (namecmpfn == &xstrverscasecmp) {
  1995. sort[i] = 'V';
  1996. ++i;
  1997. }
  1998. if (i)
  1999. sort[i] = ' ';
  2000. return i;
  2001. }
  2002. static void showfilterinfo(void)
  2003. {
  2004. int i = 0;
  2005. char info[REGEX_MAX] = "\0\0\0\0";
  2006. i = getorderstr(info);
  2007. snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %s [:]",
  2008. (cfg.regex ? "regex" : "str"),
  2009. ((fnstrstr == &strcasestr) ? "ic" : "noic"));
  2010. clearinfoln();
  2011. mvaddstr(xlines - 2, xcols - xstrlen(info), info);
  2012. }
  2013. static void showfilter(char *str)
  2014. {
  2015. attron(COLOR_PAIR(cfg.curctx + 1));
  2016. showfilterinfo();
  2017. printmsg(str);
  2018. // printmsg calls attroff()
  2019. }
  2020. static inline void swap_ent(int id1, int id2)
  2021. {
  2022. struct entry _dent, *pdent1 = &dents[id1], *pdent2 = &dents[id2];
  2023. *(&_dent) = *pdent1;
  2024. *pdent1 = *pdent2;
  2025. *pdent2 = *(&_dent);
  2026. }
  2027. #ifdef PCRE
  2028. static int fill(const char *fltr, pcre *pcrex)
  2029. #else
  2030. static int fill(const char *fltr, regex_t *re)
  2031. #endif
  2032. {
  2033. #ifdef PCRE
  2034. fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
  2035. #else
  2036. fltrexp_t fltrexp = { .regex = re, .str = fltr };
  2037. #endif
  2038. for (int count = 0; count < ndents; ++count) {
  2039. if (filterfn(&fltrexp, dents[count].name) == 0) {
  2040. if (count != --ndents) {
  2041. swap_ent(count, ndents);
  2042. --count;
  2043. }
  2044. continue;
  2045. }
  2046. }
  2047. return ndents;
  2048. }
  2049. static int matches(const char *fltr)
  2050. {
  2051. #ifdef PCRE
  2052. pcre *pcrex = NULL;
  2053. /* Search filter */
  2054. if (cfg.regex && setfilter(&pcrex, fltr))
  2055. return -1;
  2056. ndents = fill(fltr, pcrex);
  2057. if (cfg.regex)
  2058. pcre_free(pcrex);
  2059. #else
  2060. regex_t re;
  2061. /* Search filter */
  2062. if (cfg.regex && setfilter(&re, fltr))
  2063. return -1;
  2064. ndents = fill(fltr, &re);
  2065. if (cfg.regex)
  2066. regfree(&re);
  2067. #endif
  2068. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  2069. return ndents;
  2070. }
  2071. static int filterentries(char *path, char *lastname)
  2072. {
  2073. wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
  2074. char *ln = g_ctx[cfg.curctx].c_fltr;
  2075. wint_t ch[2] = {0};
  2076. int r, total = ndents, len;
  2077. char *pln = g_ctx[cfg.curctx].c_fltr + 1;
  2078. DPRINTF_S(__FUNCTION__);
  2079. if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
  2080. if (matches(pln) != -1) {
  2081. move_cursor(dentfind(lastname, ndents), 0);
  2082. redraw(path);
  2083. }
  2084. if (!cfg.filtermode)
  2085. return 0;
  2086. len = mbstowcs(wln, ln, REGEX_MAX);
  2087. } else {
  2088. ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
  2089. ln[1] = wln[1] = '\0';
  2090. len = 1;
  2091. }
  2092. cleartimeout();
  2093. curs_set(TRUE);
  2094. showfilter(ln);
  2095. while ((r = get_wch(ch)) != ERR) {
  2096. //DPRINTF_D(*ch);
  2097. //DPRINTF_S(keyname(*ch));
  2098. switch (*ch) {
  2099. #ifdef KEY_RESIZE
  2100. case KEY_RESIZE:
  2101. clearoldprompt();
  2102. redraw(path);
  2103. showfilter(ln);
  2104. continue;
  2105. #endif
  2106. case KEY_DC: // fallthrough
  2107. case KEY_BACKSPACE: // fallthrough
  2108. case '\b': // fallthrough
  2109. case 127: /* handle DEL */
  2110. if (len != 1) {
  2111. wln[--len] = '\0';
  2112. wcstombs(ln, wln, REGEX_MAX);
  2113. ndents = total;
  2114. } else
  2115. continue;
  2116. // fallthrough
  2117. case CONTROL('L'):
  2118. if (*ch == CONTROL('L')) {
  2119. if (wln[1]) {
  2120. ln[REGEX_MAX - 1] = ln[1];
  2121. ln[1] = wln[1] = '\0';
  2122. len = 1;
  2123. ndents = total;
  2124. } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
  2125. ln[1] = ln[REGEX_MAX - 1];
  2126. ln[REGEX_MAX - 1] = '\0';
  2127. len = mbstowcs(wln, ln, REGEX_MAX);
  2128. }
  2129. }
  2130. /* Go to the top, we don't know if the hovered file will match the filter */
  2131. cur = 0;
  2132. if (matches(pln) != -1)
  2133. redraw(path);
  2134. showfilter(ln);
  2135. continue;
  2136. #ifndef NOMOUSE
  2137. case KEY_MOUSE: // fallthrough
  2138. #endif
  2139. case 27: /* Exit filter mode on Escape */
  2140. goto end;
  2141. }
  2142. if (r != OK) /* Handle Fn keys in main loop */
  2143. break;
  2144. /* Handle all control chars in main loop */
  2145. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
  2146. goto end;
  2147. if (len == 1) {
  2148. if (*ch == '?') /* Help and config key, '?' is an invalid regex */
  2149. goto end;
  2150. if (cfg.filtermode) {
  2151. switch (*ch) {
  2152. case '\'': // fallthrough /* Go to first non-dir file */
  2153. case '+': // fallthrough /* Toggle auto-advance */
  2154. case ',': // fallthrough /* Pin CWD */
  2155. case '-': // fallthrough /* Visit last visited dir */
  2156. case '.': // fallthrough /* Show hidden files */
  2157. case ';': // fallthrough /* Run plugin key */
  2158. case '=': // fallthrough /* Launch app */
  2159. case '>': // fallthrough /* Export file list */
  2160. case '@': // fallthrough /* Visit start dir */
  2161. case ']': // fallthorugh /* Prompt key */
  2162. case '`': // fallthrough /* Visit / */
  2163. case '~': /* Go HOME */
  2164. goto end;
  2165. }
  2166. }
  2167. /* Toggle case-sensitivity */
  2168. if (*ch == CASE) {
  2169. fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
  2170. #ifdef PCRE
  2171. pcreflags ^= PCRE_CASELESS;
  2172. #else
  2173. regflags ^= REG_ICASE;
  2174. #endif
  2175. showfilter(ln);
  2176. continue;
  2177. }
  2178. /* toggle string or regex filter */
  2179. if (*ch == FILTER) {
  2180. ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
  2181. wln[0] = (uchar)ln[0];
  2182. cfg.regex ^= 1;
  2183. filterfn = (filterfn == &visible_str) ? &visible_re : &visible_str;
  2184. showfilter(ln);
  2185. continue;
  2186. }
  2187. /* Reset cur in case it's a repeat search */
  2188. cur = 0;
  2189. } else if (len == REGEX_MAX - 1)
  2190. continue;
  2191. wln[len] = (wchar_t)*ch;
  2192. wln[++len] = '\0';
  2193. wcstombs(ln, wln, REGEX_MAX);
  2194. /* Forward-filtering optimization:
  2195. * - new matches can only be a subset of current matches.
  2196. */
  2197. /* ndents = total; */
  2198. if (matches(pln) == -1) {
  2199. showfilter(ln);
  2200. continue;
  2201. }
  2202. /* If the only match is a dir, auto-select and cd into it */
  2203. if (ndents == 1 && cfg.filtermode
  2204. && cfg.autoselect && (dents[0].flags & DIR_OR_LINK_TO_DIR)) {
  2205. *ch = KEY_ENTER;
  2206. cur = 0;
  2207. goto end;
  2208. }
  2209. /*
  2210. * redraw() should be above the auto-select optimization, for
  2211. * the case where there's an issue with dir auto-select, say,
  2212. * due to a permission problem. The transition is _jumpy_ in
  2213. * case of such an error. However, we optimize for successful
  2214. * cases where the dir has permissions. This skips a redraw().
  2215. */
  2216. redraw(path);
  2217. showfilter(ln);
  2218. }
  2219. end:
  2220. clearinfoln();
  2221. /* Save last working filter in-filter */
  2222. if (ln[1])
  2223. ln[REGEX_MAX - 1] = ln[1];
  2224. /* Save current */
  2225. if (ndents)
  2226. copycurname();
  2227. curs_set(FALSE);
  2228. settimeout();
  2229. /* Return keys for navigation etc. */
  2230. return *ch;
  2231. }
  2232. /* Show a prompt with input string and return the changes */
  2233. static char *xreadline(const char *prefill, const char *prompt)
  2234. {
  2235. size_t len, pos;
  2236. int x, r;
  2237. const int WCHAR_T_WIDTH = sizeof(wchar_t);
  2238. wint_t ch[2] = {0};
  2239. wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
  2240. if (!buf)
  2241. errexit();
  2242. cleartimeout();
  2243. printmsg(prompt);
  2244. if (prefill) {
  2245. DPRINTF_S(prefill);
  2246. len = pos = mbstowcs(buf, prefill, READLINE_MAX);
  2247. } else
  2248. len = (size_t)-1;
  2249. if (len == (size_t)-1) {
  2250. buf[0] = '\0';
  2251. len = pos = 0;
  2252. }
  2253. x = getcurx(stdscr);
  2254. curs_set(TRUE);
  2255. while (1) {
  2256. buf[len] = ' ';
  2257. attron(COLOR_PAIR(cfg.curctx + 1));
  2258. mvaddnwstr(xlines - 1, x, buf, len + 1);
  2259. move(xlines - 1, x + wcswidth(buf, pos));
  2260. attroff(COLOR_PAIR(cfg.curctx + 1));
  2261. r = get_wch(ch);
  2262. if (r == ERR)
  2263. continue;
  2264. if (r == OK) {
  2265. switch (*ch) {
  2266. case KEY_ENTER: // fallthrough
  2267. case '\n': // fallthrough
  2268. case '\r':
  2269. goto END;
  2270. case CONTROL('D'):
  2271. if (pos < len)
  2272. ++pos;
  2273. else if (!(pos || len)) { /* Exit on ^D at empty prompt */
  2274. len = 0;
  2275. goto END;
  2276. } else
  2277. continue;
  2278. // fallthrough
  2279. case 127: // fallthrough
  2280. case '\b': /* rhel25 sends '\b' for backspace */
  2281. if (pos > 0) {
  2282. memmove(buf + pos - 1, buf + pos,
  2283. (len - pos) * WCHAR_T_WIDTH);
  2284. --len, --pos;
  2285. } // fallthrough
  2286. case '\t': /* TAB breaks cursor position, ignore it */
  2287. continue;
  2288. case CONTROL('F'):
  2289. if (pos < len)
  2290. ++pos;
  2291. continue;
  2292. case CONTROL('B'):
  2293. if (pos > 0)
  2294. --pos;
  2295. continue;
  2296. case CONTROL('W'):
  2297. printmsg(prompt);
  2298. do {
  2299. if (pos == 0)
  2300. break;
  2301. memmove(buf + pos - 1, buf + pos,
  2302. (len - pos) * WCHAR_T_WIDTH);
  2303. --pos, --len;
  2304. } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
  2305. continue;
  2306. case CONTROL('K'):
  2307. printmsg(prompt);
  2308. len = pos;
  2309. continue;
  2310. case CONTROL('L'):
  2311. printmsg(prompt);
  2312. len = pos = 0;
  2313. continue;
  2314. case CONTROL('A'):
  2315. pos = 0;
  2316. continue;
  2317. case CONTROL('E'):
  2318. pos = len;
  2319. continue;
  2320. case CONTROL('U'):
  2321. printmsg(prompt);
  2322. memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
  2323. len -= pos;
  2324. pos = 0;
  2325. continue;
  2326. case 27: /* Exit prompt on Escape */
  2327. len = 0;
  2328. goto END;
  2329. }
  2330. /* Filter out all other control chars */
  2331. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
  2332. continue;
  2333. if (pos < READLINE_MAX - 1) {
  2334. memmove(buf + pos + 1, buf + pos,
  2335. (len - pos) * WCHAR_T_WIDTH);
  2336. buf[pos] = *ch;
  2337. ++len, ++pos;
  2338. continue;
  2339. }
  2340. } else {
  2341. switch (*ch) {
  2342. #ifdef KEY_RESIZE
  2343. case KEY_RESIZE:
  2344. clearoldprompt();
  2345. xlines = LINES;
  2346. printmsg(prompt);
  2347. break;
  2348. #endif
  2349. case KEY_LEFT:
  2350. if (pos > 0)
  2351. --pos;
  2352. break;
  2353. case KEY_RIGHT:
  2354. if (pos < len)
  2355. ++pos;
  2356. break;
  2357. case KEY_BACKSPACE:
  2358. if (pos > 0) {
  2359. memmove(buf + pos - 1, buf + pos,
  2360. (len - pos) * WCHAR_T_WIDTH);
  2361. --len, --pos;
  2362. }
  2363. break;
  2364. case KEY_DC:
  2365. if (pos < len) {
  2366. memmove(buf + pos, buf + pos + 1,
  2367. (len - pos - 1) * WCHAR_T_WIDTH);
  2368. --len;
  2369. }
  2370. break;
  2371. case KEY_END:
  2372. pos = len;
  2373. break;
  2374. case KEY_HOME:
  2375. pos = 0;
  2376. break;
  2377. default:
  2378. break;
  2379. }
  2380. }
  2381. }
  2382. END:
  2383. curs_set(FALSE);
  2384. settimeout();
  2385. printmsg("");
  2386. buf[len] = '\0';
  2387. pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
  2388. if (pos >= READLINE_MAX - 1)
  2389. g_buf[READLINE_MAX - 1] = '\0';
  2390. free(buf);
  2391. return g_buf;
  2392. }
  2393. #ifndef NORL
  2394. /*
  2395. * Caller should check the value of presel to confirm if it needs to wait to show warning
  2396. */
  2397. static char *getreadline(const char *prompt, char *path, char *curpath, int *presel)
  2398. {
  2399. /* Switch to current path for readline(3) */
  2400. if (chdir(path) == -1) {
  2401. printwarn(presel);
  2402. return NULL;
  2403. }
  2404. exitcurses();
  2405. char *input = readline(prompt);
  2406. refresh();
  2407. if (chdir(curpath) == -1)
  2408. printwarn(presel);
  2409. else if (input && input[0]) {
  2410. add_history(input);
  2411. xstrsncpy(g_buf, input, CMD_LEN_MAX);
  2412. free(input);
  2413. return g_buf;
  2414. }
  2415. free(input);
  2416. return NULL;
  2417. }
  2418. #endif
  2419. /*
  2420. * Updates out with "dir/name or "/name"
  2421. * Returns the number of bytes copied including the terminating NULL byte
  2422. */
  2423. static size_t mkpath(const char *dir, const char *name, char *out)
  2424. {
  2425. size_t len;
  2426. /* Handle absolute path */
  2427. if (name[0] == '/')
  2428. return xstrsncpy(out, name, PATH_MAX);
  2429. /* Handle root case */
  2430. if (istopdir(dir))
  2431. len = 1;
  2432. else
  2433. len = xstrsncpy(out, dir, PATH_MAX);
  2434. out[len - 1] = '/'; // NOLINT
  2435. return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
  2436. }
  2437. /*
  2438. * Create symbolic/hard link(s) to file(s) in selection list
  2439. * Returns the number of links created, -1 on error
  2440. */
  2441. static int xlink(char *prefix, char *path, char *curfname, char *buf, int *presel, int type)
  2442. {
  2443. int count = 0, choice;
  2444. char *psel = pselbuf, *fname;
  2445. size_t pos = 0, len, r;
  2446. int (*link_fn)(const char *, const char *) = NULL;
  2447. char lnpath[PATH_MAX];
  2448. choice = get_cur_or_sel();
  2449. if (!choice)
  2450. return -1;
  2451. if (type == 's') /* symbolic link */
  2452. link_fn = &symlink;
  2453. else /* hard link */
  2454. link_fn = &link;
  2455. if (choice == 'c') {
  2456. r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
  2457. xstrsncpy(buf + r - 1, curfname, NAME_MAX - r); /* Suffix target file name */
  2458. mkpath(path, buf, lnpath); /* Generate link path */
  2459. mkpath(path, curfname, buf); /* Generate target file path */
  2460. if (!link_fn(buf, lnpath))
  2461. return 1; /* One link created */
  2462. printwarn(presel);
  2463. return -1;
  2464. }
  2465. while (pos < selbufpos) {
  2466. len = xstrlen(psel);
  2467. fname = xbasename(psel);
  2468. r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
  2469. xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
  2470. mkpath(path, buf, lnpath); /* Generate link path */
  2471. if (!link_fn(psel, lnpath))
  2472. ++count;
  2473. pos += len + 1;
  2474. psel += len + 1;
  2475. }
  2476. return count;
  2477. }
  2478. static bool parsekvpair(kv **arr, char **envcpy, const uchar id, uchar *items)
  2479. {
  2480. const uchar INCR = 8;
  2481. uint i = 0;
  2482. char *nextkey;
  2483. kv *kvarr = NULL;
  2484. char *ptr = getenv(env_cfg[id]);
  2485. if (!ptr || !*ptr)
  2486. return TRUE;
  2487. *envcpy = xstrdup(ptr);
  2488. if (!*envcpy) {
  2489. xerror();
  2490. return FALSE;
  2491. }
  2492. ptr = *envcpy;
  2493. nextkey = ptr;
  2494. while (*ptr && i < 100) {
  2495. if (ptr == nextkey) {
  2496. if (!(i & (INCR - 1))) {
  2497. kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
  2498. *arr = kvarr;
  2499. if (!kvarr) {
  2500. xerror();
  2501. return FALSE;
  2502. }
  2503. memset(kvarr + i, 0, sizeof(kv) * INCR);
  2504. }
  2505. kvarr[i].key = (uchar)*ptr;
  2506. if (*++ptr != ':')
  2507. return FALSE;
  2508. if (*++ptr == '\0')
  2509. return FALSE;
  2510. if (*ptr == ';') /* Empty location */
  2511. return FALSE;
  2512. kvarr[i].val = ptr;
  2513. ++i;
  2514. }
  2515. if (*ptr == ';') {
  2516. *ptr = '\0';
  2517. nextkey = ptr + 1;
  2518. }
  2519. ++ptr;
  2520. }
  2521. *items = i;
  2522. return (i != 0);
  2523. }
  2524. /*
  2525. * Get the value corresponding to a key
  2526. *
  2527. * NULL is returned in case of no match, path resolution failure etc.
  2528. * buf would be modified, so check return value before access
  2529. */
  2530. static char *get_kv_val(kv *kvarr, char *buf, int key, uchar max, bool bookmark)
  2531. {
  2532. if (!kvarr)
  2533. return NULL;
  2534. for (int r = 0; kvarr[r].key && r < max; ++r) {
  2535. if (kvarr[r].key == key) {
  2536. /* Do not allocate new memory for plugin */
  2537. if (!bookmark)
  2538. return kvarr[r].val;
  2539. if (kvarr[r].val[0] == '~') {
  2540. ssize_t len = xstrlen(home);
  2541. ssize_t loclen = xstrlen(kvarr[r].val);
  2542. xstrsncpy(g_buf, home, len + 1);
  2543. xstrsncpy(g_buf + len, kvarr[r].val + 1, loclen);
  2544. }
  2545. return realpath(((kvarr[r].val[0] == '~') ? g_buf : kvarr[r].val), buf);
  2546. }
  2547. }
  2548. DPRINTF_S("Invalid key");
  2549. return NULL;
  2550. }
  2551. static void resetdircolor(int flags)
  2552. {
  2553. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  2554. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2555. cfg.dircolor = 0;
  2556. }
  2557. }
  2558. /*
  2559. * Replace escape characters in a string with '?'
  2560. * Adjust string length to maxcols if > 0;
  2561. * Max supported str length: NAME_MAX;
  2562. */
  2563. static wchar_t *unescape(const char *str, uint maxcols)
  2564. {
  2565. wchar_t * const wbuf = (wchar_t *)g_buf;
  2566. wchar_t *buf = wbuf;
  2567. size_t lencount = 0;
  2568. #ifdef NOLOCALE
  2569. memset(wbuf, 0, sizeof(NAME_MAX + 1) * sizeof(wchar_t));
  2570. #endif
  2571. /* Convert multi-byte to wide char */
  2572. size_t len = mbstowcs(wbuf, str, NAME_MAX);
  2573. len = wcswidth(wbuf, len);
  2574. /* Reduce number of wide chars to max columns */
  2575. if (len > maxcols) {
  2576. while (*buf && lencount <= maxcols) {
  2577. if (*buf <= '\x1f' || *buf == '\x7f')
  2578. *buf = '\?';
  2579. ++buf;
  2580. ++lencount;
  2581. }
  2582. lencount = maxcols + 1;
  2583. /* Reduce wide chars one by one till it fits */
  2584. do
  2585. len = wcswidth(wbuf, --lencount);
  2586. while (len > maxcols);
  2587. wbuf[lencount] = L'\0';
  2588. } else {
  2589. do /* We do not expect a NULL string */
  2590. if (*buf <= '\x1f' || *buf == '\x7f')
  2591. *buf = '\?';
  2592. while (*++buf);
  2593. }
  2594. return wbuf;
  2595. }
  2596. static char *coolsize(off_t size)
  2597. {
  2598. const char * const U = "BKMGTPEZY";
  2599. static char size_buf[12]; /* Buffer to hold human readable size */
  2600. off_t rem = 0;
  2601. size_t ret;
  2602. int i = 0;
  2603. while (size >= 1024) {
  2604. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  2605. size >>= 10;
  2606. ++i;
  2607. }
  2608. if (i == 1) {
  2609. rem = (rem * 1000) >> 10;
  2610. rem /= 10;
  2611. if (rem % 10 >= 5) {
  2612. rem = (rem / 10) + 1;
  2613. if (rem == 10) {
  2614. ++size;
  2615. rem = 0;
  2616. }
  2617. } else
  2618. rem /= 10;
  2619. } else if (i == 2) {
  2620. rem = (rem * 1000) >> 10;
  2621. if (rem % 10 >= 5) {
  2622. rem = (rem / 10) + 1;
  2623. if (rem == 100) {
  2624. ++size;
  2625. rem = 0;
  2626. }
  2627. } else
  2628. rem /= 10;
  2629. } else if (i > 0) {
  2630. rem = (rem * 10000) >> 10;
  2631. if (rem % 10 >= 5) {
  2632. rem = (rem / 10) + 1;
  2633. if (rem == 1000) {
  2634. ++size;
  2635. rem = 0;
  2636. }
  2637. } else
  2638. rem /= 10;
  2639. }
  2640. if (i > 0 && i < 6 && rem) {
  2641. ret = xstrsncpy(size_buf, xitoa(size), 12);
  2642. size_buf[ret - 1] = '.';
  2643. char *frac = xitoa(rem);
  2644. size_t toprint = i > 3 ? 3 : i;
  2645. size_t len = xstrlen(frac);
  2646. if (len < toprint) {
  2647. size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
  2648. xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
  2649. } else
  2650. xstrsncpy(size_buf + ret, frac, toprint + 1);
  2651. ret += toprint;
  2652. } else {
  2653. ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
  2654. --ret;
  2655. }
  2656. size_buf[ret] = U[i];
  2657. size_buf[ret + 1] = '\0';
  2658. return size_buf;
  2659. }
  2660. static char get_ind(mode_t mode, bool perms)
  2661. {
  2662. switch (mode & S_IFMT) {
  2663. case S_IFREG:
  2664. if (perms)
  2665. return '-';
  2666. if (mode & 0100)
  2667. return '*';
  2668. return '\0';
  2669. case S_IFDIR:
  2670. return perms ? 'd' : '/';
  2671. case S_IFLNK:
  2672. return perms ? 'l' : '@';
  2673. case S_IFSOCK:
  2674. return perms ? 's' : '=';
  2675. case S_IFIFO:
  2676. return perms ? 'p' : '|';
  2677. case S_IFBLK:
  2678. return perms ? 'b' : '\0';
  2679. case S_IFCHR:
  2680. return perms ? 'c' : '\0';
  2681. default:
  2682. return '?';
  2683. }
  2684. }
  2685. /* Convert a mode field into "ls -l" type perms field. */
  2686. static char *get_lsperms(mode_t mode)
  2687. {
  2688. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  2689. static char bits[11] = {'\0'};
  2690. bits[0] = get_ind(mode, TRUE);
  2691. xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  2692. xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  2693. xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
  2694. if (mode & S_ISUID)
  2695. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  2696. if (mode & S_ISGID)
  2697. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  2698. if (mode & S_ISVTX)
  2699. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  2700. return bits;
  2701. }
  2702. static void print_time(const time_t *timep)
  2703. {
  2704. struct tm *t = localtime(timep);
  2705. printw("%d-%02d-%02d %02d:%02d",
  2706. t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min);
  2707. }
  2708. static void printent(const struct entry *ent, uint namecols, bool sel)
  2709. {
  2710. char ind = get_ind(ent->mode, FALSE);
  2711. int attrs = ((ind == '@' || (ent->flags & HARD_LINK)) ? A_DIM : 0) | (sel ? A_REVERSE : 0);
  2712. if (ind == '@' && (ent->flags & DIR_OR_LINK_TO_DIR))
  2713. ind = '/';
  2714. if (!ind)
  2715. ++namecols;
  2716. /* Directories are always shown on top */
  2717. resetdircolor(ent->flags);
  2718. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2719. if (attrs)
  2720. attron(attrs);
  2721. addwstr(unescape(ent->name, namecols));
  2722. if (attrs)
  2723. attroff(attrs);
  2724. if (ind)
  2725. addch(ind);
  2726. addch('\n');
  2727. }
  2728. static void printent_long(const struct entry *ent, uint namecols, bool sel)
  2729. {
  2730. bool ln = FALSE;
  2731. char ind1 = '\0', ind2 = '\0';
  2732. int attrs = sel ? A_REVERSE : 0;
  2733. uint len;
  2734. char *size;
  2735. /* Directories are always shown on top */
  2736. resetdircolor(ent->flags);
  2737. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2738. if (attrs)
  2739. attron(attrs);
  2740. /* Timestamp */
  2741. print_time(&ent->t);
  2742. addstr(" ");
  2743. /* Permissions */
  2744. addch('0' + ((ent->mode >> 6) & 7));
  2745. addch('0' + ((ent->mode >> 3) & 7));
  2746. addch('0' + (ent->mode & 7));
  2747. switch (ent->mode & S_IFMT) {
  2748. case S_IFDIR:
  2749. ind2 = '/'; // fallthrough
  2750. case S_IFREG:
  2751. if (!ind2) {
  2752. if (ent->flags & HARD_LINK)
  2753. ln = TRUE;
  2754. if (ent->mode & 0100)
  2755. ind2 = '*';
  2756. if (!ind2) /* Add a column if end indicator is not needed */
  2757. ++namecols;
  2758. }
  2759. size = coolsize(cfg.blkorder ? ent->blocks << blk_shift : ent->size);
  2760. len = 10 - (uint)xstrlen(size);
  2761. while (--len)
  2762. addch(' ');
  2763. addstr(size);
  2764. break;
  2765. case S_IFLNK:
  2766. ln = TRUE;
  2767. ind1 = '@';
  2768. ind2 = (ent->flags & DIR_OR_LINK_TO_DIR) ? '/' : '@'; // fallthrough
  2769. case S_IFSOCK:
  2770. if (!ind1)
  2771. ind1 = ind2 = '='; // fallthrough
  2772. case S_IFIFO:
  2773. if (!ind1)
  2774. ind1 = ind2 = '|'; // fallthrough
  2775. case S_IFBLK:
  2776. if (!ind1)
  2777. ind1 = 'b'; // fallthrough
  2778. case S_IFCHR:
  2779. if (!ind1)
  2780. ind1 = 'c'; // fallthrough
  2781. default:
  2782. if (!ind1)
  2783. ind1 = ind2 = '?';
  2784. addstr(" ");
  2785. addch(ind1);
  2786. break;
  2787. }
  2788. addstr(" ");
  2789. if (ln) {
  2790. attron(A_DIM);
  2791. attrs |= A_DIM;
  2792. }
  2793. addwstr(unescape(ent->name, namecols));
  2794. if (attrs)
  2795. attroff(attrs);
  2796. if (ind2)
  2797. addch(ind2);
  2798. addch('\n');
  2799. }
  2800. static void (*printptr)(const struct entry *ent, uint namecols, bool sel) = &printent;
  2801. static void savecurctx(settings *curcfg, char *path, char *curname, int r /* next context num */)
  2802. {
  2803. settings cfg = *curcfg;
  2804. context *ctxr = &g_ctx[r];
  2805. bool selmode = cfg.selmode ? TRUE : FALSE;
  2806. /* Save current context */
  2807. xstrsncpy(g_ctx[cfg.curctx].c_name, curname, NAME_MAX + 1);
  2808. g_ctx[cfg.curctx].c_cfg = cfg;
  2809. if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
  2810. /* Switch light/detail mode */
  2811. if (cfg.showdetail != ctxr->c_cfg.showdetail)
  2812. /* set the reverse */
  2813. printptr = cfg.showdetail ? &printent : &printent_long;
  2814. cfg = ctxr->c_cfg;
  2815. } else { /* Setup a new context from current context */
  2816. ctxr->c_cfg.ctxactive = 1;
  2817. xstrsncpy(ctxr->c_path, path, PATH_MAX);
  2818. ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
  2819. ctxr->c_cfg = cfg;
  2820. ctxr->c_cfg.runplugin = 0;
  2821. }
  2822. /* Continue selection mode */
  2823. cfg.selmode = selmode;
  2824. cfg.curctx = r;
  2825. *curcfg = cfg;
  2826. }
  2827. static void save_session(bool last_session, int *presel)
  2828. {
  2829. char spath[PATH_MAX];
  2830. int i;
  2831. session_header_t header;
  2832. FILE *fsession;
  2833. char *sname;
  2834. bool status = FALSE;
  2835. memset(&header, 0, sizeof(session_header_t));
  2836. header.ver = SESSIONS_VERSION;
  2837. for (i = 0; i < CTX_MAX; ++i) {
  2838. if (g_ctx[i].c_cfg.ctxactive) {
  2839. if (cfg.curctx == i && ndents)
  2840. /* Update current file name, arrows don't update it */
  2841. xstrsncpy(g_ctx[i].c_name, dents[cur].name, NAME_MAX + 1);
  2842. header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
  2843. header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
  2844. header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
  2845. header.fltrln[i] = strnlen(g_ctx[i].c_fltr, REGEX_MAX) + 1;
  2846. }
  2847. }
  2848. sname = !last_session ? xreadline(NULL, messages[MSG_SSN_NAME]) : "@";
  2849. if (!sname[0])
  2850. return;
  2851. mkpath(sessiondir, sname, spath);
  2852. fsession = fopen(spath, "wb");
  2853. if (!fsession) {
  2854. printwait(messages[MSG_SEL_MISSING], presel);
  2855. return;
  2856. }
  2857. if ((fwrite(&header, sizeof(header), 1, fsession) != 1)
  2858. || (fwrite(&cfg, sizeof(cfg), 1, fsession) != 1))
  2859. goto END;
  2860. for (i = 0; i < CTX_MAX; ++i)
  2861. if ((fwrite(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2862. || (fwrite(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2863. || (header.nameln[i] > 0
  2864. && fwrite(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2865. || (header.lastln[i] > 0
  2866. && fwrite(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2867. || (header.fltrln[i] > 0
  2868. && fwrite(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2869. || (header.pathln[i] > 0
  2870. && fwrite(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2871. goto END;
  2872. status = TRUE;
  2873. END:
  2874. fclose(fsession);
  2875. if (!status)
  2876. printwait(messages[MSG_FAILED], presel);
  2877. }
  2878. static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
  2879. {
  2880. char spath[PATH_MAX];
  2881. int i = 0;
  2882. session_header_t header;
  2883. FILE *fsession;
  2884. bool has_loaded_dynamically = !(sname || restore);
  2885. bool status = FALSE;
  2886. if (!restore) {
  2887. sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
  2888. if (!sname[0])
  2889. return FALSE;
  2890. mkpath(sessiondir, sname, spath);
  2891. } else
  2892. mkpath(sessiondir, "@", spath);
  2893. if (has_loaded_dynamically)
  2894. save_session(TRUE, NULL);
  2895. fsession = fopen(spath, "rb");
  2896. if (!fsession) {
  2897. printmsg(messages[MSG_SEL_MISSING]);
  2898. xdelay(XDELAY_INTERVAL_MS);
  2899. return FALSE;
  2900. }
  2901. if ((fread(&header, sizeof(header), 1, fsession) != 1)
  2902. || (header.ver != SESSIONS_VERSION)
  2903. || (fread(&cfg, sizeof(cfg), 1, fsession) != 1))
  2904. goto END;
  2905. g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
  2906. = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  2907. for (; i < CTX_MAX; ++i)
  2908. if ((fread(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2909. || (fread(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2910. || (header.nameln[i] > 0
  2911. && fread(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2912. || (header.lastln[i] > 0
  2913. && fread(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2914. || (header.fltrln[i] > 0
  2915. && fread(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2916. || (header.pathln[i] > 0
  2917. && fread(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2918. goto END;
  2919. *path = g_ctx[cfg.curctx].c_path;
  2920. *lastdir = g_ctx[cfg.curctx].c_last;
  2921. *lastname = g_ctx[cfg.curctx].c_name;
  2922. printptr = cfg.showdetail ? &printent_long : &printent;
  2923. status = TRUE;
  2924. END:
  2925. fclose(fsession);
  2926. if (!status) {
  2927. printmsg(messages[MSG_FAILED]);
  2928. xdelay(XDELAY_INTERVAL_MS);
  2929. } else if (restore)
  2930. unlink(spath);
  2931. return status;
  2932. }
  2933. /*
  2934. * Gets only a single line (that's what we need
  2935. * for now) or shows full command output in pager.
  2936. *
  2937. * If page is valid, returns NULL
  2938. */
  2939. static char *get_output(char *buf, const size_t bytes, const char *file,
  2940. const char *arg1, const char *arg2, const bool page)
  2941. {
  2942. pid_t pid;
  2943. int pipefd[2];
  2944. FILE *pf;
  2945. int tmp, flags;
  2946. char *ret = NULL;
  2947. if (pipe(pipefd) == -1)
  2948. errexit();
  2949. for (tmp = 0; tmp < 2; ++tmp) {
  2950. /* Get previous flags */
  2951. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  2952. /* Set bit for non-blocking flag */
  2953. flags |= O_NONBLOCK;
  2954. /* Change flags on fd */
  2955. fcntl(pipefd[tmp], F_SETFL, flags);
  2956. }
  2957. pid = fork();
  2958. if (pid == 0) {
  2959. /* In child */
  2960. close(pipefd[0]);
  2961. dup2(pipefd[1], STDOUT_FILENO);
  2962. dup2(pipefd[1], STDERR_FILENO);
  2963. close(pipefd[1]);
  2964. execlp(file, file, arg1, arg2, NULL);
  2965. _exit(1);
  2966. }
  2967. /* In parent */
  2968. waitpid(pid, &tmp, 0);
  2969. close(pipefd[1]);
  2970. if (!page) {
  2971. pf = fdopen(pipefd[0], "r");
  2972. if (pf) {
  2973. ret = fgets(buf, bytes, pf);
  2974. close(pipefd[0]);
  2975. }
  2976. return ret;
  2977. }
  2978. pid = fork();
  2979. if (pid == 0) {
  2980. /* Show in pager in child */
  2981. dup2(pipefd[0], STDIN_FILENO);
  2982. close(pipefd[0]);
  2983. spawn(pager, NULL, NULL, NULL, F_CLI);
  2984. _exit(1);
  2985. }
  2986. /* In parent */
  2987. waitpid(pid, &tmp, 0);
  2988. close(pipefd[0]);
  2989. return NULL;
  2990. }
  2991. static inline bool getutil(char *util)
  2992. {
  2993. return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
  2994. }
  2995. static void pipetof(char *cmd, FILE *fout)
  2996. {
  2997. FILE *fin = popen(cmd, "r");
  2998. if (fin) {
  2999. while (fgets(g_buf, CMD_LEN_MAX - 1, fin))
  3000. fprintf(fout, "%s", g_buf);
  3001. pclose(fin);
  3002. }
  3003. }
  3004. /*
  3005. * Follows the stat(1) output closely
  3006. */
  3007. static bool show_stats(const char *fpath, const struct stat *sb)
  3008. {
  3009. int fd;
  3010. FILE *fp;
  3011. char *p, *begin = g_buf;
  3012. size_t r;
  3013. fd = create_tmp_file();
  3014. if (fd == -1)
  3015. return FALSE;
  3016. r = xstrsncpy(g_buf, "stat \"", PATH_MAX);
  3017. r += xstrsncpy(g_buf + r - 1, fpath, PATH_MAX);
  3018. g_buf[r - 2] = '\"';
  3019. g_buf[r - 1] = '\0';
  3020. DPRINTF_S(g_buf);
  3021. fp = fdopen(fd, "w");
  3022. if (!fp) {
  3023. close(fd);
  3024. return FALSE;
  3025. }
  3026. pipetof(g_buf, fp);
  3027. if (S_ISREG(sb->st_mode)) {
  3028. /* Show file(1) output */
  3029. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  3030. if (p) {
  3031. fprintf(fp, "\n\n ");
  3032. while (*p) {
  3033. if (*p == ',') {
  3034. *p = '\0';
  3035. fprintf(fp, " %s\n", begin);
  3036. begin = p + 1;
  3037. }
  3038. ++p;
  3039. }
  3040. fprintf(fp, " %s\n ", begin);
  3041. /* Show the file mime type */
  3042. get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, fpath, FALSE);
  3043. fprintf(fp, "%s", g_buf);
  3044. }
  3045. }
  3046. fprintf(fp, "\n");
  3047. fclose(fp);
  3048. close(fd);
  3049. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3050. unlink(g_tmpfpath);
  3051. return TRUE;
  3052. }
  3053. static bool xchmod(const char *fpath, mode_t mode)
  3054. {
  3055. /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
  3056. (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
  3057. return (chmod(fpath, mode) == 0);
  3058. }
  3059. static size_t get_fs_info(const char *path, bool type)
  3060. {
  3061. struct statvfs svb;
  3062. if (statvfs(path, &svb) == -1)
  3063. return 0;
  3064. if (type == CAPACITY)
  3065. return svb.f_blocks << ffs((int)(svb.f_frsize >> 1));
  3066. return svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
  3067. }
  3068. /* List or extract archive */
  3069. static void handle_archive(char *fpath, const char *dir, char op)
  3070. {
  3071. char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
  3072. char *util;
  3073. if (getutil(utils[UTIL_ATOOL])) {
  3074. util = utils[UTIL_ATOOL];
  3075. arg[1] = op;
  3076. arg[2] = '\0';
  3077. } else if (getutil(utils[UTIL_BSDTAR])) {
  3078. util = utils[UTIL_BSDTAR];
  3079. if (op == 'x')
  3080. arg[1] = op;
  3081. } else if (is_suffix(fpath, ".zip")) {
  3082. util = utils[UTIL_UNZIP];
  3083. arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
  3084. arg[2] = '\0';
  3085. } else {
  3086. util = utils[UTIL_TAR];
  3087. if (op == 'x')
  3088. arg[1] = op;
  3089. }
  3090. if (op == 'x') /* extract */
  3091. spawn(util, arg, fpath, dir, F_NORMAL);
  3092. else /* list */
  3093. get_output(NULL, 0, util, arg, fpath, TRUE);
  3094. }
  3095. static char *visit_parent(char *path, char *newpath, int *presel)
  3096. {
  3097. char *dir;
  3098. /* There is no going back */
  3099. if (istopdir(path)) {
  3100. /* Continue in type-to-nav mode, if enabled */
  3101. if (cfg.filtermode && presel)
  3102. *presel = FILTER;
  3103. return NULL;
  3104. }
  3105. /* Use a copy as xdirname() may change the string passed */
  3106. if (newpath)
  3107. xstrsncpy(newpath, path, PATH_MAX);
  3108. else
  3109. newpath = path;
  3110. dir = xdirname(newpath);
  3111. if (access(dir, R_OK) == -1) {
  3112. printwarn(presel);
  3113. return NULL;
  3114. }
  3115. return dir;
  3116. }
  3117. static void valid_parent(char *path, char *lastname)
  3118. {
  3119. /* Save history */
  3120. xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
  3121. while (!istopdir(path))
  3122. if (visit_parent(path, NULL, NULL))
  3123. break;
  3124. printwarn(NULL);
  3125. xdelay(XDELAY_INTERVAL_MS);
  3126. }
  3127. /* Create non-existent parents and a file or dir */
  3128. static bool xmktree(char *path, bool dir)
  3129. {
  3130. char *p = path;
  3131. char *slash = path;
  3132. if (!p || !*p)
  3133. return FALSE;
  3134. /* Skip the first '/' */
  3135. ++p;
  3136. while (*p != '\0') {
  3137. if (*p == '/') {
  3138. slash = p;
  3139. *p = '\0';
  3140. } else {
  3141. ++p;
  3142. continue;
  3143. }
  3144. /* Create folder from path to '\0' inserted at p */
  3145. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3146. #ifdef __HAIKU__
  3147. // XDG_CONFIG_HOME contains a directory
  3148. // that is read-only, but the full path
  3149. // is writeable.
  3150. // Try to continue and see what happens.
  3151. // TODO: Find a more robust solution.
  3152. if (errno == B_READ_ONLY_DEVICE)
  3153. goto next;
  3154. #endif
  3155. DPRINTF_S("mkdir1!");
  3156. DPRINTF_S(strerror(errno));
  3157. *slash = '/';
  3158. return FALSE;
  3159. }
  3160. #ifdef __HAIKU__
  3161. next:
  3162. #endif
  3163. /* Restore path */
  3164. *slash = '/';
  3165. ++p;
  3166. }
  3167. if (dir) {
  3168. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3169. DPRINTF_S("mkdir2!");
  3170. DPRINTF_S(strerror(errno));
  3171. return FALSE;
  3172. }
  3173. } else {
  3174. int fd = open(path, O_CREAT, 0666);
  3175. if (fd == -1 && errno != EEXIST) {
  3176. DPRINTF_S("open!");
  3177. DPRINTF_S(strerror(errno));
  3178. return FALSE;
  3179. }
  3180. close(fd);
  3181. }
  3182. return TRUE;
  3183. }
  3184. static bool archive_mount(char *path, char *newpath)
  3185. {
  3186. char *dir, *cmd = utils[UTIL_ARCHIVEMOUNT];
  3187. char *name = dents[cur].name;
  3188. size_t len = dents[cur].nlen;
  3189. if (!getutil(cmd)) {
  3190. printmsg(messages[MSG_UTIL_MISSING]);
  3191. return FALSE;
  3192. }
  3193. dir = xstrdup(name);
  3194. if (!dir) {
  3195. printmsg(messages[MSG_FAILED]);
  3196. return FALSE;
  3197. }
  3198. while (len > 1)
  3199. if (dir[--len] == '.') {
  3200. dir[len] = '\0';
  3201. break;
  3202. }
  3203. DPRINTF_S(dir);
  3204. /* Create the mount point */
  3205. mkpath(cfgdir, dir, newpath);
  3206. free(dir);
  3207. if (!xmktree(newpath, TRUE)) {
  3208. printwarn(NULL);
  3209. return FALSE;
  3210. }
  3211. /* Mount archive */
  3212. DPRINTF_S(name);
  3213. DPRINTF_S(newpath);
  3214. if (spawn(cmd, name, newpath, path, F_NORMAL)) {
  3215. printmsg(messages[MSG_FAILED]);
  3216. return FALSE;
  3217. }
  3218. return TRUE;
  3219. }
  3220. static bool remote_mount(char *newpath, char *currentpath)
  3221. {
  3222. uchar flag = F_CLI;
  3223. int opt;
  3224. char *tmp, *env;
  3225. bool r, s;
  3226. r = getutil(utils[UTIL_RCLONE]);
  3227. s = getutil(utils[UTIL_SSHFS]);
  3228. if (!(r || s)) {
  3229. printmsg(messages[MSG_UTIL_MISSING]);
  3230. return FALSE;
  3231. }
  3232. if (r && s)
  3233. opt = get_input(messages[MSG_REMOTE_OPTS]);
  3234. else
  3235. opt = (!s) ? 'r' : 's';
  3236. if (opt == 's')
  3237. env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
  3238. else if (opt == 'r') {
  3239. flag |= F_NOWAIT | F_NOTRACE;
  3240. env = xgetenv("NNN_RCLONE", "rclone mount");
  3241. } else {
  3242. printmsg(messages[MSG_INVALID_KEY]);
  3243. return FALSE;
  3244. }
  3245. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3246. if (!tmp[0]) {
  3247. printmsg(messages[MSG_CANCEL]);
  3248. return FALSE;
  3249. }
  3250. if (tmp[0] == '-' && !tmp[1]) {
  3251. if (!strcmp(cfgdir, currentpath) && ndents && (dents[cur].flags & DIR_OR_LINK_TO_DIR))
  3252. xstrsncpy(tmp, dents[cur].name, NAME_MAX + 1);
  3253. else {
  3254. printmsg(messages[MSG_FAILED]);
  3255. return FALSE;
  3256. }
  3257. }
  3258. /* Create the mount point */
  3259. mkpath(cfgdir, tmp, newpath);
  3260. if (!xmktree(newpath, TRUE)) {
  3261. printwarn(NULL);
  3262. return FALSE;
  3263. }
  3264. /* Convert "Host" to "Host:" */
  3265. size_t len = xstrlen(tmp);
  3266. if (tmp[len - 1] != ':') { /* Append ':' if missing */
  3267. tmp[len] = ':';
  3268. tmp[len + 1] = '\0';
  3269. }
  3270. /* Connect to remote */
  3271. if (opt == 's') {
  3272. if (spawn(env, tmp, newpath, NULL, flag)) {
  3273. printmsg(messages[MSG_FAILED]);
  3274. return FALSE;
  3275. }
  3276. } else {
  3277. spawn(env, tmp, newpath, NULL, flag);
  3278. printmsg(messages[MSG_RCLONE_DELAY]);
  3279. xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
  3280. }
  3281. return TRUE;
  3282. }
  3283. /*
  3284. * Unmounts if the directory represented by name is a mount point.
  3285. * Otherwise, asks for hostname
  3286. */
  3287. static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
  3288. {
  3289. #ifdef __APPLE__
  3290. static char cmd[] = "umount";
  3291. #else
  3292. static char cmd[] = "fusermount3"; /* Arch Linux utility */
  3293. static bool found = FALSE;
  3294. #endif
  3295. char *tmp = name;
  3296. struct stat sb, psb;
  3297. bool child = FALSE;
  3298. bool parent = FALSE;
  3299. #ifndef __APPLE__
  3300. /* On Ubuntu it's fusermount */
  3301. if (!found && !getutil(cmd)) {
  3302. cmd[10] = '\0';
  3303. found = TRUE;
  3304. }
  3305. #endif
  3306. if (tmp && strcmp(cfgdir, currentpath) == 0) {
  3307. mkpath(cfgdir, tmp, newpath);
  3308. child = lstat(newpath, &sb) != -1;
  3309. parent = lstat(xdirname(newpath), &psb) != -1;
  3310. if (!child && !parent) {
  3311. *presel = MSGWAIT;
  3312. return FALSE;
  3313. }
  3314. }
  3315. if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
  3316. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3317. if (!tmp[0])
  3318. return FALSE;
  3319. }
  3320. /* Create the mount point */
  3321. mkpath(cfgdir, tmp, newpath);
  3322. if (!xdiraccess(newpath)) {
  3323. *presel = MSGWAIT;
  3324. return FALSE;
  3325. }
  3326. #ifdef __APPLE__
  3327. if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
  3328. #else
  3329. if (spawn(cmd, "-u", newpath, NULL, F_NORMAL)) {
  3330. #endif
  3331. if (!xconfirm(get_input(messages[MSG_LAZY])))
  3332. return FALSE;
  3333. #ifdef __APPLE__
  3334. if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
  3335. #else
  3336. if (spawn(cmd, "-uz", newpath, NULL, F_NORMAL)) {
  3337. #endif
  3338. printwait(messages[MSG_FAILED], presel);
  3339. return FALSE;
  3340. }
  3341. }
  3342. return TRUE;
  3343. }
  3344. static void lock_terminal(void)
  3345. {
  3346. spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
  3347. }
  3348. static void printkv(kv *kvarr, FILE *fp, uchar max)
  3349. {
  3350. for (uchar i = 0; i < max && kvarr[i].key; ++i)
  3351. fprintf(fp, " %c: %s\n", (char)kvarr[i].key, kvarr[i].val);
  3352. }
  3353. static void printkeys(kv *kvarr, char *buf, uchar max)
  3354. {
  3355. uchar i = 0;
  3356. for (; i < max && kvarr[i].key; ++i) {
  3357. buf[i << 1] = ' ';
  3358. buf[(i << 1) + 1] = kvarr[i].key;
  3359. }
  3360. buf[i << 1] = '\0';
  3361. }
  3362. static size_t handle_bookmark(const char *mark, char *newpath)
  3363. {
  3364. int fd;
  3365. size_t r = xstrsncpy(g_buf, messages[MSG_BOOKMARK_KEYS], CMD_LEN_MAX);
  3366. if (mark) { /* There is a pinned directory */
  3367. g_buf[--r] = ' ';
  3368. g_buf[++r] = ',';
  3369. g_buf[++r] = '\0';
  3370. ++r;
  3371. }
  3372. printkeys(bookmark, g_buf + r - 1, maxbm);
  3373. printmsg(g_buf);
  3374. r = FALSE;
  3375. fd = get_input(NULL);
  3376. if (fd == ',') /* Visit pinned directory */
  3377. mark ? xstrsncpy(newpath, mark, PATH_MAX) : (r = MSG_NOT_SET);
  3378. else if (!get_kv_val(bookmark, newpath, fd, maxbm, TRUE))
  3379. r = MSG_INVALID_KEY;
  3380. if (!r && !xdiraccess(newpath))
  3381. r = MSG_ACCESS;
  3382. return r;
  3383. }
  3384. /*
  3385. * The help string tokens (each line) start with a HEX value
  3386. * which indicates the number of spaces to print before the
  3387. * particular token. This method was chosen instead of a flat
  3388. * string because the number of bytes in help was increasing
  3389. * the binary size by around a hundred bytes. This would only
  3390. * have increased as we keep adding new options.
  3391. */
  3392. static void show_help(const char *path)
  3393. {
  3394. int fd;
  3395. FILE *fp;
  3396. const char *start, *end;
  3397. const char helpstr[] = {
  3398. "0\n"
  3399. "1NAVIGATION\n"
  3400. "9Up k Up%-16cPgUp ^U Scroll up\n"
  3401. "9Dn j Down%-14cPgDn ^D Scroll down\n"
  3402. "9Lt h Parent%-12c~ ` @ - HOME, /, start, last\n"
  3403. "5Ret Rt l Open%-20c' First file\n"
  3404. "9g ^A Top%-18c. F5 Toggle hidden\n"
  3405. "9G ^E End%-21c0 Lock terminal\n"
  3406. "9b ^/ Bookmark key%-12c, Pin CWD\n"
  3407. "a1-4 Context 1-4%-7c(Sh)Tab Cycle context\n"
  3408. "c/ Filter%-17c^N Toggle type-to-nav\n"
  3409. "aEsc Exit prompt%-12c^L Redraw/clear prompt\n"
  3410. "c? Help, conf%-14c+ Toggle auto-advance\n"
  3411. "cq Quit context%-11c^G QuitCD\n"
  3412. "b^Q Quit%-20cQ Quit with err\n"
  3413. "1FILES\n"
  3414. "9o ^O Open with...%-12cn Create new/link\n"
  3415. "9f ^F File details%-12cd Detail mode toggle\n"
  3416. "b^R Rename/dup%-14cr Batch rename\n"
  3417. "cz Archive%-17ce Edit in EDITOR\n"
  3418. "5Space ^J (Un)select%-11cm ^K Mark range/clear\n"
  3419. "9p ^P Copy sel here%-11ca Select all\n"
  3420. "9v ^V Move sel here%-8cw ^W Cp/mv sel as\n"
  3421. "9x ^X Delete%-18cE Edit sel\n"
  3422. "c* Toggle exe%-14c> Export list\n"
  3423. "1MISC\n"
  3424. "9; ^S Select plugin%-11c= Launch app\n"
  3425. "9! ^] Shell%-19c] Cmd prompt\n"
  3426. "cc Connect remote%-10cu Unmount\n"
  3427. "9t ^T Sort toggles%-12cs Manage session\n"
  3428. "cT Set time type%-0c\n"
  3429. };
  3430. fd = create_tmp_file();
  3431. if (fd == -1)
  3432. return;
  3433. fp = fdopen(fd, "w");
  3434. if (!fp) {
  3435. close(fd);
  3436. return;
  3437. }
  3438. if ((g_states & STATE_FORTUNE) && getutil("fortune"))
  3439. pipetof("fortune -s", fp);
  3440. start = end = helpstr;
  3441. while (*end) {
  3442. if (*end == '\n') {
  3443. snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
  3444. xchartohex(*start), ' ', (int)(end - start), start + 1);
  3445. fprintf(fp, g_buf, ' ');
  3446. start = end + 1;
  3447. }
  3448. ++end;
  3449. }
  3450. fprintf(fp, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  3451. fprintf(fp, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  3452. if (bookmark) {
  3453. fprintf(fp, "BOOKMARKS\n");
  3454. printkv(bookmark, fp, maxbm);
  3455. fprintf(fp, "\n");
  3456. }
  3457. if (plug) {
  3458. fprintf(fp, "PLUGIN KEYS\n");
  3459. printkv(plug, fp, maxplug);
  3460. fprintf(fp, "\n");
  3461. }
  3462. for (uchar i = NNN_OPENER; i <= NNN_TRASH; ++i) {
  3463. start = getenv(env_cfg[i]);
  3464. if (start)
  3465. fprintf(fp, "%s: %s\n", env_cfg[i], start);
  3466. }
  3467. if (selpath)
  3468. fprintf(fp, "SELECTION FILE: %s\n", selpath);
  3469. fprintf(fp, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  3470. fclose(fp);
  3471. close(fd);
  3472. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3473. unlink(g_tmpfpath);
  3474. }
  3475. static bool run_cmd_as_plugin(const char *path, const char *file, char *runfile)
  3476. {
  3477. uchar flags = F_CLI | F_CONFIRM;
  3478. size_t len;
  3479. /* Get rid of preceding _ */
  3480. ++file;
  3481. if (!*file)
  3482. return FALSE;
  3483. /* Check if GUI flags are to be used */
  3484. if (*file == '|') {
  3485. flags = F_NOTRACE | F_NOWAIT;
  3486. ++file;
  3487. if (!*file)
  3488. return FALSE;
  3489. }
  3490. xstrsncpy(g_buf, file, PATH_MAX);
  3491. len = xstrlen(g_buf);
  3492. if (len > 1 && g_buf[len - 1] == '*') {
  3493. flags &= ~F_CONFIRM; /* Skip user confirmation */
  3494. g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
  3495. --len;
  3496. }
  3497. if (is_suffix(g_buf, " $nnn"))
  3498. g_buf[len - 5] = '\0'; /* Set `\0` to clear ' $nnn' suffix */
  3499. else
  3500. runfile = NULL;
  3501. spawn(g_buf, runfile, NULL, path, flags);
  3502. return TRUE;
  3503. }
  3504. static bool plctrl_init(void)
  3505. {
  3506. snprintf(g_buf, CMD_LEN_MAX, "nnn-pipe.%d", getpid());
  3507. /* g_tmpfpath is used to generate tmp file names */
  3508. g_tmpfpath[tmpfplen - 1] = '\0';
  3509. mkpath(g_tmpfpath, g_buf, g_pipepath);
  3510. unlink(g_pipepath);
  3511. if (mkfifo(g_pipepath, 0600) != 0)
  3512. return _FAILURE;
  3513. setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
  3514. return _SUCCESS;
  3515. }
  3516. static bool run_selected_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
  3517. {
  3518. int fd;
  3519. size_t len;
  3520. if (*file == '_')
  3521. return run_cmd_as_plugin(*path, file, runfile);
  3522. if (!(g_states & STATE_PLUGIN_INIT)) {
  3523. plctrl_init();
  3524. g_states |= STATE_PLUGIN_INIT;
  3525. }
  3526. fd = open(g_pipepath, O_RDONLY | O_NONBLOCK);
  3527. if (fd == -1)
  3528. return FALSE;
  3529. /* Generate absolute path to plugin */
  3530. mkpath(plugindir, file, g_buf);
  3531. if (runfile && runfile[0]) {
  3532. xstrsncpy(*lastname, runfile, NAME_MAX);
  3533. spawn(g_buf, *lastname, *path, *path, F_NORMAL);
  3534. } else
  3535. spawn(g_buf, NULL, *path, *path, F_NORMAL);
  3536. len = read(fd, g_buf, PATH_MAX);
  3537. g_buf[len] = '\0';
  3538. close(fd);
  3539. if (len > 1) {
  3540. int ctx = g_buf[0] - '0';
  3541. if (ctx == 0 || ctx == cfg.curctx + 1) {
  3542. xstrsncpy(*lastdir, *path, PATH_MAX);
  3543. xstrsncpy(*path, g_buf + 1, PATH_MAX);
  3544. } else if (ctx >= 1 && ctx <= CTX_MAX) {
  3545. int r = ctx - 1;
  3546. g_ctx[r].c_cfg.ctxactive = 0;
  3547. savecurctx(&cfg, g_buf + 1, dents[cur].name, r);
  3548. *path = g_ctx[r].c_path;
  3549. *lastdir = g_ctx[r].c_last;
  3550. *lastname = g_ctx[r].c_name;
  3551. }
  3552. }
  3553. return TRUE;
  3554. }
  3555. static bool plugscript(const char *plugin, const char *path, uchar flags)
  3556. {
  3557. mkpath(plugindir, plugin, g_buf);
  3558. if (!access(g_buf, X_OK)) {
  3559. spawn(g_buf, NULL, NULL, path, flags);
  3560. return TRUE;
  3561. }
  3562. return FALSE;
  3563. }
  3564. static void launch_app(const char *path, char *newpath)
  3565. {
  3566. int r = F_NORMAL;
  3567. char *tmp = newpath;
  3568. mkpath(plugindir, utils[UTIL_LAUNCH], newpath);
  3569. if (!(getutil(utils[UTIL_FZF]) || getutil(utils[UTIL_FZY])) || access(newpath, X_OK) < 0) {
  3570. tmp = xreadline(NULL, messages[MSG_APP_NAME]);
  3571. r = F_NOWAIT | F_NOTRACE | F_MULTI;
  3572. }
  3573. if (tmp && *tmp) // NOLINT
  3574. spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, path, r);
  3575. }
  3576. static int sum_bsize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3577. {
  3578. if (sb->st_blocks
  3579. && ((typeflag == FTW_F && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))
  3580. || typeflag == FTW_D))
  3581. ent_blocks += sb->st_blocks;
  3582. ++num_files;
  3583. return 0;
  3584. }
  3585. static int sum_asize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3586. {
  3587. if (sb->st_size
  3588. && ((typeflag == FTW_F && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))
  3589. || typeflag == FTW_D))
  3590. ent_blocks += sb->st_size;
  3591. ++num_files;
  3592. return 0;
  3593. }
  3594. static void dentfree(void)
  3595. {
  3596. free(pnamebuf);
  3597. free(dents);
  3598. }
  3599. static blkcnt_t dirwalk(char *path, struct stat *psb)
  3600. {
  3601. static uint open_max;
  3602. /* Increase current open file descriptor limit */
  3603. if (!open_max)
  3604. open_max = max_openfds();
  3605. ent_blocks = 0;
  3606. tolastln();
  3607. addstr(xbasename(path));
  3608. addstr(" [^C aborts]\n");
  3609. refresh();
  3610. if (nftw(path, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) < 0) {
  3611. DPRINTF_S("nftw failed");
  3612. return cfg.apparentsz ? psb->st_size : psb->st_blocks;
  3613. }
  3614. return ent_blocks;
  3615. }
  3616. /* Skip self and parent */
  3617. static bool selforparent(const char *path)
  3618. {
  3619. return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
  3620. }
  3621. static int dentfill(char *path, struct entry **dents)
  3622. {
  3623. int n = 0, flags = 0;
  3624. ulong num_saved;
  3625. struct dirent *dp;
  3626. char *namep, *pnb, *buf = NULL;
  3627. struct entry *dentp;
  3628. size_t off = 0, namebuflen = NAMEBUF_INCR;
  3629. struct stat sb_path, sb;
  3630. DIR *dirp = opendir(path);
  3631. DPRINTF_S(__FUNCTION__);
  3632. if (!dirp)
  3633. return 0;
  3634. int fd = dirfd(dirp);
  3635. if (cfg.blkorder) {
  3636. num_files = 0;
  3637. dir_blocks = 0;
  3638. buf = (char *)alloca(xstrlen(path) + NAME_MAX + 2);
  3639. if (!buf)
  3640. return 0;
  3641. if (fstatat(fd, path, &sb_path, 0) == -1)
  3642. goto exit;
  3643. if (!ihashbmp) {
  3644. ihashbmp = calloc(1, HASH_OCTETS << 3);
  3645. if (!ihashbmp)
  3646. goto exit;
  3647. } else
  3648. memset(ihashbmp, 0, HASH_OCTETS << 3);
  3649. attron(COLOR_PAIR(cfg.curctx + 1));
  3650. }
  3651. #if _POSIX_C_SOURCE >= 200112L
  3652. posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
  3653. #endif
  3654. dp = readdir(dirp);
  3655. if (!dp)
  3656. goto exit;
  3657. #if defined(__sun) || defined(__HAIKU__)
  3658. flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
  3659. #else
  3660. if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
  3661. /*
  3662. * Optimization added for filesystems which support dirent.d_type
  3663. * see readdir(3)
  3664. * Known drawbacks:
  3665. * - the symlink size is set to 0
  3666. * - the modification time of the symlink is set to that of the target file
  3667. */
  3668. flags = AT_SYMLINK_NOFOLLOW;
  3669. }
  3670. #endif
  3671. do {
  3672. namep = dp->d_name;
  3673. if (selforparent(namep))
  3674. continue;
  3675. if (!cfg.showhidden && namep[0] == '.') {
  3676. if (!cfg.blkorder)
  3677. continue;
  3678. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  3679. continue;
  3680. if (S_ISDIR(sb.st_mode)) {
  3681. if (sb_path.st_dev == sb.st_dev) { // NOLINT
  3682. mkpath(path, namep, buf);
  3683. dir_blocks += dirwalk(buf, &sb);
  3684. if (g_states & STATE_INTERRUPTED)
  3685. goto exit;
  3686. }
  3687. } else {
  3688. /* Do not recount hard links */
  3689. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3690. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3691. ++num_files;
  3692. }
  3693. continue;
  3694. }
  3695. if (fstatat(fd, namep, &sb, flags) == -1) {
  3696. /* List a symlink with target missing */
  3697. if (flags || (!flags && fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
  3698. DPRINTF_U(flags);
  3699. if (!flags) {
  3700. DPRINTF_S(namep);
  3701. DPRINTF_S(strerror(errno));
  3702. }
  3703. memset(&sb, 0, sizeof(struct stat));
  3704. }
  3705. }
  3706. if (n == total_dents) {
  3707. total_dents += ENTRY_INCR;
  3708. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  3709. if (!*dents) {
  3710. free(pnamebuf);
  3711. closedir(dirp);
  3712. errexit();
  3713. }
  3714. DPRINTF_P(*dents);
  3715. }
  3716. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  3717. if (namebuflen - off < NAME_MAX + 1) {
  3718. namebuflen += NAMEBUF_INCR;
  3719. pnb = pnamebuf;
  3720. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  3721. if (!pnamebuf) {
  3722. free(*dents);
  3723. closedir(dirp);
  3724. errexit();
  3725. }
  3726. DPRINTF_P(pnamebuf);
  3727. /* realloc() may result in memory move, we must re-adjust if that happens */
  3728. if (pnb != pnamebuf) {
  3729. dentp = *dents;
  3730. dentp->name = pnamebuf;
  3731. for (int count = 1; count < n; ++dentp, ++count)
  3732. /* Current filename starts at last filename start + length */
  3733. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  3734. }
  3735. }
  3736. dentp = *dents + n;
  3737. /* Selection file name */
  3738. dentp->name = (char *)((size_t)pnamebuf + off);
  3739. dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
  3740. off += dentp->nlen;
  3741. /* Copy other fields */
  3742. dentp->t = ((cfg.timetype == T_MOD)
  3743. ? sb.st_mtime
  3744. : ((cfg.timetype == T_ACCESS) ? sb.st_atime : sb.st_ctime));
  3745. #if !(defined(__sun) || defined(__HAIKU__))
  3746. if (!flags && dp->d_type == DT_LNK) {
  3747. /* Do not add sizes for links */
  3748. dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
  3749. dentp->size = listpath ? sb.st_size : 0;
  3750. } else {
  3751. dentp->mode = sb.st_mode;
  3752. dentp->size = sb.st_size;
  3753. }
  3754. #else
  3755. dentp->mode = sb.st_mode;
  3756. dentp->size = sb.st_size;
  3757. #endif
  3758. dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
  3759. if (cfg.blkorder) {
  3760. if (S_ISDIR(sb.st_mode)) {
  3761. num_saved = num_files + 1;
  3762. mkpath(path, namep, buf);
  3763. /* Need to show the disk usage of this dir */
  3764. dentp->blocks = dirwalk(buf, &sb);
  3765. if (sb_path.st_dev == sb.st_dev) // NOLINT
  3766. dir_blocks += dentp->blocks;
  3767. else
  3768. num_files = num_saved;
  3769. if (g_states & STATE_INTERRUPTED)
  3770. goto exit;
  3771. } else {
  3772. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3773. /* Do not recount hard links */
  3774. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3775. dir_blocks += dentp->blocks;
  3776. ++num_files;
  3777. }
  3778. }
  3779. if (flags) {
  3780. /* Flag if this is a dir or symlink to a dir */
  3781. if (S_ISLNK(sb.st_mode)) {
  3782. sb.st_mode = 0;
  3783. fstatat(fd, namep, &sb, 0);
  3784. }
  3785. if (S_ISDIR(sb.st_mode))
  3786. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3787. #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
  3788. } else if (dp->d_type == DT_DIR || (dp->d_type == DT_LNK && S_ISDIR(sb.st_mode))) {
  3789. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3790. #endif
  3791. }
  3792. ++n;
  3793. } while ((dp = readdir(dirp)));
  3794. exit:
  3795. if (cfg.blkorder)
  3796. attroff(COLOR_PAIR(cfg.curctx + 1));
  3797. /* Should never be null */
  3798. if (closedir(dirp) == -1)
  3799. errexit();
  3800. return n;
  3801. }
  3802. /*
  3803. * Return the position of the matching entry or 0 otherwise
  3804. * Note there's no NULL check for fname
  3805. */
  3806. static int dentfind(const char *fname, int n)
  3807. {
  3808. for (int i = 0; i < n; ++i)
  3809. if (xstrcmp(fname, dents[i].name) == 0)
  3810. return i;
  3811. return 0;
  3812. }
  3813. static void populate(char *path, char *lastname)
  3814. {
  3815. #ifdef DBGMODE
  3816. struct timespec ts1, ts2;
  3817. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  3818. #endif
  3819. ndents = dentfill(path, &dents);
  3820. if (!ndents)
  3821. return;
  3822. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  3823. #ifdef DBGMODE
  3824. clock_gettime(CLOCK_REALTIME, &ts2);
  3825. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  3826. #endif
  3827. /* Find cur from history */
  3828. /* No NULL check for lastname, always points to an array */
  3829. move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
  3830. // Force full redraw
  3831. last_curscroll = -1;
  3832. }
  3833. static void move_cursor(int target, int ignore_scrolloff)
  3834. {
  3835. int delta, scrolloff, onscreen = xlines - 4;
  3836. last_curscroll = curscroll;
  3837. target = MAX(0, MIN(ndents - 1, target));
  3838. delta = target - cur;
  3839. last = cur;
  3840. cur = target;
  3841. if (!ignore_scrolloff) {
  3842. scrolloff = MIN(SCROLLOFF, onscreen >> 1);
  3843. /*
  3844. * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
  3845. * margin area, but when ignore_scrolloff is 0, act like a boa
  3846. * constrictor and squeeze the cursor towards the middle region of the
  3847. * screen by allowing it to move inward and disallowing it to move
  3848. * outward (deeper into the scrolloff margin area).
  3849. */
  3850. if (((cur < (curscroll + scrolloff)) && delta < 0)
  3851. || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
  3852. curscroll += delta;
  3853. }
  3854. curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
  3855. curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
  3856. }
  3857. static void handle_screen_move(enum action sel)
  3858. {
  3859. int onscreen;
  3860. switch (sel) {
  3861. case SEL_NEXT:
  3862. if (ndents && (cfg.rollover || (cur != ndents - 1)))
  3863. move_cursor((cur + 1) % ndents, 0);
  3864. break;
  3865. case SEL_PREV:
  3866. if (ndents && (cfg.rollover || cur))
  3867. move_cursor((cur + ndents - 1) % ndents, 0);
  3868. break;
  3869. case SEL_PGDN:
  3870. onscreen = xlines - 4;
  3871. move_cursor(curscroll + (onscreen - 1), 1);
  3872. curscroll += onscreen - 1;
  3873. break;
  3874. case SEL_CTRL_D:
  3875. onscreen = xlines - 4;
  3876. move_cursor(curscroll + (onscreen - 1), 1);
  3877. curscroll += onscreen >> 1;
  3878. break;
  3879. case SEL_PGUP: // fallthrough
  3880. onscreen = xlines - 4;
  3881. move_cursor(curscroll, 1);
  3882. curscroll -= onscreen - 1;
  3883. break;
  3884. case SEL_CTRL_U:
  3885. onscreen = xlines - 4;
  3886. move_cursor(curscroll, 1);
  3887. curscroll -= onscreen >> 1;
  3888. break;
  3889. case SEL_HOME:
  3890. move_cursor(0, 1);
  3891. break;
  3892. case SEL_END:
  3893. move_cursor(ndents - 1, 1);
  3894. break;
  3895. default: /* case SEL_FIRST */
  3896. {
  3897. for (int r = 0; r < ndents; ++r) {
  3898. if (!(dents[r].flags & DIR_OR_LINK_TO_DIR)) {
  3899. move_cursor((r) % ndents, 0);
  3900. break;
  3901. }
  3902. }
  3903. break;
  3904. }
  3905. }
  3906. }
  3907. static int handle_context_switch(enum action sel)
  3908. {
  3909. int r = -1;
  3910. switch (sel) {
  3911. case SEL_CYCLE: // fallthrough
  3912. case SEL_CYCLER:
  3913. /* visit next and previous contexts */
  3914. r = cfg.curctx;
  3915. if (sel == SEL_CYCLE)
  3916. do
  3917. r = (r + 1) & ~CTX_MAX;
  3918. while (!g_ctx[r].c_cfg.ctxactive);
  3919. else
  3920. do
  3921. r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
  3922. while (!g_ctx[r].c_cfg.ctxactive);
  3923. // fallthrough
  3924. default: /* SEL_CTXN */
  3925. if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
  3926. r = sel - SEL_CTX1; /* Save the next context id */
  3927. if (cfg.curctx == r) {
  3928. if (sel == SEL_CYCLE)
  3929. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3930. else if (sel == SEL_CYCLER)
  3931. (r == 0) ? (r = CTX_MAX - 1) : --r;
  3932. else
  3933. return -1;
  3934. }
  3935. if (cfg.selmode)
  3936. lastappendpos = selbufpos;
  3937. }
  3938. return r;
  3939. }
  3940. static int set_sort_flags(int r)
  3941. {
  3942. switch (r) {
  3943. case 'a': /* Apparent du */
  3944. cfg.apparentsz ^= 1;
  3945. if (cfg.apparentsz) {
  3946. nftw_fn = &sum_asize;
  3947. cfg.blkorder = 1;
  3948. blk_shift = 0;
  3949. } else
  3950. cfg.blkorder = 0;
  3951. // fallthrough
  3952. case 'd': /* Disk usage */
  3953. if (r == 'd') {
  3954. if (!cfg.apparentsz)
  3955. cfg.blkorder ^= 1;
  3956. nftw_fn = &sum_bsize;
  3957. cfg.apparentsz = 0;
  3958. blk_shift = ffs(S_BLKSIZE) - 1;
  3959. }
  3960. if (cfg.blkorder) {
  3961. cfg.showdetail = 1;
  3962. printptr = &printent_long;
  3963. }
  3964. cfg.timeorder = 0;
  3965. cfg.sizeorder = 0;
  3966. cfg.extnorder = 0;
  3967. entrycmpfn = &entrycmp;
  3968. endselection(); /* We are going to reload dir */
  3969. break;
  3970. case 'c':
  3971. cfg.timeorder = 0;
  3972. cfg.sizeorder = 0;
  3973. cfg.apparentsz = 0;
  3974. cfg.blkorder = 0;
  3975. cfg.extnorder = 0;
  3976. entrycmpfn = &entrycmp;
  3977. namecmpfn = &xstricmp;
  3978. break;
  3979. case 'e': /* File extension */
  3980. cfg.extnorder ^= 1;
  3981. cfg.sizeorder = 0;
  3982. cfg.timeorder = 0;
  3983. cfg.apparentsz = 0;
  3984. cfg.blkorder = 0;
  3985. entrycmpfn = &entrycmp;
  3986. break;
  3987. case 'r': /* Reverse sort */
  3988. entrycmpfn = (entrycmpfn == &entrycmp) ? &reventrycmp : &entrycmp;
  3989. break;
  3990. case 's': /* File size */
  3991. cfg.sizeorder ^= 1;
  3992. cfg.timeorder = 0;
  3993. cfg.apparentsz = 0;
  3994. cfg.blkorder = 0;
  3995. cfg.extnorder = 0;
  3996. entrycmpfn = &entrycmp;
  3997. break;
  3998. case 't': /* Time */
  3999. cfg.timeorder ^= 1;
  4000. cfg.sizeorder = 0;
  4001. cfg.apparentsz = 0;
  4002. cfg.blkorder = 0;
  4003. cfg.extnorder = 0;
  4004. entrycmpfn = &entrycmp;
  4005. break;
  4006. case 'v': /* Version */
  4007. namecmpfn = (namecmpfn == &xstrverscasecmp) ? &xstricmp : &xstrverscasecmp;
  4008. cfg.timeorder = 0;
  4009. cfg.sizeorder = 0;
  4010. cfg.apparentsz = 0;
  4011. cfg.blkorder = 0;
  4012. cfg.extnorder = 0;
  4013. break;
  4014. default:
  4015. return 0;
  4016. }
  4017. return r;
  4018. }
  4019. static bool set_time_type(int *presel)
  4020. {
  4021. bool ret = FALSE;
  4022. char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
  4023. buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
  4024. int r = get_input(buf);
  4025. if (r == 'a' || r == 'c' || r == 'm') {
  4026. r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
  4027. if (cfg.timetype != r) {
  4028. cfg.timetype = r;
  4029. if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
  4030. *presel = FILTER;
  4031. ret = TRUE;
  4032. } else
  4033. r = MSG_NOCHNAGE;
  4034. } else
  4035. r = MSG_INVALID_KEY;
  4036. if (!ret)
  4037. printwait(messages[r], presel);
  4038. return ret;
  4039. }
  4040. static void statusbar(char *path)
  4041. {
  4042. int i = 0, extnlen = 0;
  4043. char *ptr;
  4044. pEntry pent = &dents[cur];
  4045. if (!ndents) {
  4046. printmsg("0/0");
  4047. return;
  4048. }
  4049. /* Get the file extension for regular files */
  4050. if (S_ISREG(pent->mode)) {
  4051. i = (int)(pent->nlen - 1);
  4052. ptr = xmemrchr((uchar *)pent->name, '.', i);
  4053. if (ptr)
  4054. extnlen = i - (ptr - pent->name);
  4055. if (!ptr || extnlen > 5 || extnlen < 2)
  4056. ptr = "\b";
  4057. } else
  4058. ptr = "\b";
  4059. tolastln();
  4060. attron(COLOR_PAIR(cfg.curctx + 1));
  4061. if (cfg.blkorder) { /* du mode */
  4062. char buf[24];
  4063. xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
  4064. printw("%d/%d [%s:%s] %cu:%s free:%s files:%lu %lldB %s\n",
  4065. cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4066. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4067. (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, FREE)),
  4068. num_files, (ll)pent->blocks << blk_shift, ptr);
  4069. } else { /* light or detail mode */
  4070. char sort[] = "\0\0\0\0";
  4071. getorderstr(sort);
  4072. printw("%d/%d [%s:%s] %s", cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4073. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4074. sort);
  4075. /* Timestamp */
  4076. print_time(&pent->t);
  4077. addch(' ');
  4078. addstr(get_lsperms(pent->mode));
  4079. addch(' ');
  4080. addstr(coolsize(pent->size));
  4081. addch(' ');
  4082. addstr(ptr);
  4083. addch('\n');
  4084. }
  4085. attroff(COLOR_PAIR(cfg.curctx + 1));
  4086. }
  4087. static int adjust_cols(int ncols)
  4088. {
  4089. /* Calculate the number of cols available to print entry name */
  4090. if (cfg.showdetail) {
  4091. /* Fallback to light mode if less than 35 columns */
  4092. if (ncols < 36) {
  4093. cfg.showdetail ^= 1;
  4094. printptr = &printent;
  4095. ncols -= 3; /* Preceding space, indicator, newline */
  4096. } else
  4097. ncols -= 35;
  4098. } else
  4099. ncols -= 3; /* Preceding space, indicator, newline */
  4100. return ncols;
  4101. }
  4102. static void draw_line(char *path, int ncols)
  4103. {
  4104. bool dir = FALSE;
  4105. ncols = adjust_cols(ncols);
  4106. if (dents[last].flags & DIR_OR_LINK_TO_DIR) {
  4107. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4108. dir = TRUE;
  4109. }
  4110. move(2 + last - curscroll, 0);
  4111. printptr(&dents[last], ncols, false);
  4112. if (dents[cur].flags & DIR_OR_LINK_TO_DIR) {
  4113. if (!dir) {/* First file is not a directory */
  4114. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4115. dir = TRUE;
  4116. }
  4117. } else if (dir) { /* Second file is not a directory */
  4118. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4119. dir = FALSE;
  4120. }
  4121. move(2 + cur - curscroll, 0);
  4122. printptr(&dents[cur], ncols, true);
  4123. /* Must reset e.g. no files in dir */
  4124. if (dir)
  4125. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4126. statusbar(path);
  4127. }
  4128. static void redraw(char *path)
  4129. {
  4130. xlines = LINES;
  4131. xcols = COLS;
  4132. DPRINTF_S(__FUNCTION__);
  4133. int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
  4134. int onscreen = xlines - 4;
  4135. int i;
  4136. char *ptr = path;
  4137. // Fast redraw
  4138. if (g_states & STATE_MOVE_OP) {
  4139. g_states &= ~STATE_MOVE_OP;
  4140. if (ndents && (last_curscroll == curscroll))
  4141. return draw_line(path, ncols);
  4142. }
  4143. /* Clear screen */
  4144. erase();
  4145. /* Enforce scroll/cursor invariants */
  4146. move_cursor(cur, 1);
  4147. /* Fail redraw if < than 10 columns, context info prints 10 chars */
  4148. if (ncols < MIN_DISPLAY_COLS) {
  4149. printmsg(messages[MSG_FEW_COLUMNS]);
  4150. return;
  4151. }
  4152. //DPRINTF_D(cur);
  4153. DPRINTF_S(path);
  4154. addch('[');
  4155. for (i = 0; i < CTX_MAX; ++i) {
  4156. if (!g_ctx[i].c_cfg.ctxactive)
  4157. addch(i + '1');
  4158. else
  4159. addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
  4160. /* active: underline, current: reverse */
  4161. | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
  4162. addch(' ');
  4163. }
  4164. addstr("\b] "); /* 10 chars printed for contexts - "[1 2 3 4] " */
  4165. attron(A_UNDERLINE);
  4166. /* Print path */
  4167. i = (int)xstrlen(path);
  4168. if ((i + MIN_DISPLAY_COLS) <= ncols)
  4169. addnstr(path, ncols - MIN_DISPLAY_COLS);
  4170. else {
  4171. char *base = xmemrchr((uchar *)path, '/', i);
  4172. i = 0;
  4173. if (base != ptr) {
  4174. while (ptr < base) {
  4175. if (*ptr == '/') {
  4176. i += 2; /* 2 characters added */
  4177. if (ncols < i + MIN_DISPLAY_COLS) {
  4178. base = NULL; /* Can't print more characters */
  4179. break;
  4180. }
  4181. addch(*ptr);
  4182. addch(*(++ptr));
  4183. }
  4184. ++ptr;
  4185. }
  4186. }
  4187. addnstr(base, ncols - (MIN_DISPLAY_COLS + i));
  4188. }
  4189. attroff(A_UNDERLINE);
  4190. /* Go to first entry */
  4191. move(2, 0);
  4192. ncols = adjust_cols(ncols);
  4193. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4194. cfg.dircolor = 1;
  4195. /* Print listing */
  4196. for (i = curscroll; i < ndents && i < curscroll + onscreen; ++i)
  4197. printptr(&dents[i], ncols, i == cur);
  4198. /* Must reset e.g. no files in dir */
  4199. if (cfg.dircolor) {
  4200. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4201. cfg.dircolor = 0;
  4202. }
  4203. statusbar(path);
  4204. }
  4205. static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
  4206. {
  4207. if (lastname)
  4208. lastname[0] = '\0';
  4209. /* Save last working directory */
  4210. xstrsncpy(lastdir, path, PATH_MAX);
  4211. /* Save the newly opted dir in path */
  4212. xstrsncpy(path, newpath, PATH_MAX);
  4213. DPRINTF_S(path);
  4214. clearfilter();
  4215. return cfg.filtermode;
  4216. }
  4217. static bool browse(char *ipath, const char *session)
  4218. {
  4219. char newpath[PATH_MAX] __attribute__ ((aligned));
  4220. char rundir[PATH_MAX] __attribute__ ((aligned));
  4221. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  4222. char *path, *lastdir, *lastname, *dir, *tmp, *mark = NULL;
  4223. enum action sel;
  4224. struct stat sb;
  4225. int r = -1, presel, selstartid = 0, selendid = 0;
  4226. const uchar opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOWAIT));
  4227. bool watch = FALSE;
  4228. #ifndef NOMOUSE
  4229. MEVENT event;
  4230. struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
  4231. bool currentmouse = 1;
  4232. bool rightclicksel = 0;
  4233. #endif
  4234. #ifndef DIR_LIMITED_SELECTION
  4235. ino_t inode = 0;
  4236. #endif
  4237. atexit(dentfree);
  4238. xlines = LINES;
  4239. xcols = COLS;
  4240. /* setup first context */
  4241. if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
  4242. xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  4243. path = g_ctx[0].c_path;
  4244. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = '\0';
  4245. lastdir = g_ctx[0].c_last; /* last visited directory */
  4246. lastname = g_ctx[0].c_name; /* last visited filename */
  4247. g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
  4248. g_ctx[0].c_cfg = cfg; /* current configuration */
  4249. }
  4250. newpath[0] = rundir[0] = runfile[0] = '\0';
  4251. presel = cfg.filtermode ? FILTER : 0;
  4252. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  4253. if (!dents)
  4254. errexit();
  4255. /* Allocate buffer to hold names */
  4256. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  4257. if (!pnamebuf)
  4258. errexit();
  4259. begin:
  4260. /* Can fail when permissions change while browsing.
  4261. * It's assumed that path IS a directory when we are here.
  4262. */
  4263. if (access(path, R_OK) == -1) {
  4264. DPRINTF_S("directory inaccessible");
  4265. valid_parent(path, lastname);
  4266. setdirwatch();
  4267. }
  4268. if (cfg.selmode && lastdir[0])
  4269. lastappendpos = selbufpos;
  4270. #ifdef LINUX_INOTIFY
  4271. if ((presel == FILTER || watch) && inotify_wd >= 0) {
  4272. inotify_rm_watch(inotify_fd, inotify_wd);
  4273. inotify_wd = -1;
  4274. watch = FALSE;
  4275. }
  4276. #elif defined(BSD_KQUEUE)
  4277. if ((presel == FILTER || watch) && event_fd >= 0) {
  4278. close(event_fd);
  4279. event_fd = -1;
  4280. watch = FALSE;
  4281. }
  4282. #elif defined(HAIKU_NM)
  4283. if ((presel == FILTER || watch) && haiku_hnd != NULL) {
  4284. haiku_stop_watch(haiku_hnd);
  4285. haiku_nm_active = FALSE;
  4286. watch = FALSE;
  4287. }
  4288. #endif
  4289. populate(path, lastname);
  4290. if (g_states & STATE_INTERRUPTED) {
  4291. g_states &= ~STATE_INTERRUPTED;
  4292. cfg.apparentsz = 0;
  4293. cfg.blkorder = 0;
  4294. blk_shift = BLK_SHIFT_512;
  4295. presel = CONTROL('L');
  4296. }
  4297. #ifdef LINUX_INOTIFY
  4298. if (presel != FILTER && inotify_wd == -1)
  4299. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  4300. #elif defined(BSD_KQUEUE)
  4301. if (presel != FILTER && event_fd == -1) {
  4302. #if defined(O_EVTONLY)
  4303. event_fd = open(path, O_EVTONLY);
  4304. #else
  4305. event_fd = open(path, O_RDONLY);
  4306. #endif
  4307. if (event_fd >= 0)
  4308. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  4309. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  4310. }
  4311. #elif defined(HAIKU_NM)
  4312. haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == _SUCCESS;
  4313. #endif
  4314. while (1) {
  4315. redraw(path);
  4316. /* Display a one-time message */
  4317. if (listpath && (g_states & STATE_MSG)) {
  4318. g_states &= ~STATE_MSG;
  4319. printwait(messages[MSG_IGNORED], &presel);
  4320. }
  4321. nochange:
  4322. /* Exit if parent has exited */
  4323. if (getppid() == 1) {
  4324. free(mark);
  4325. _exit(0);
  4326. }
  4327. /* If CWD is deleted or moved or perms changed, find an accessible parent */
  4328. if (access(path, F_OK))
  4329. goto begin;
  4330. /* If STDIN is no longer a tty (closed) we should exit */
  4331. if (!isatty(STDIN_FILENO) && !cfg.picker) {
  4332. free(mark);
  4333. return _FAILURE;
  4334. }
  4335. sel = nextsel(presel);
  4336. if (presel)
  4337. presel = 0;
  4338. switch (sel) {
  4339. #ifndef NOMOUSE
  4340. case SEL_CLICK:
  4341. if (getmouse(&event) != OK)
  4342. goto nochange;
  4343. /* Handle clicking on a context at the top */
  4344. if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
  4345. /* Get context from: "[1 2 3 4]..." */
  4346. r = event.x >> 1;
  4347. /* If clicked after contexts, go to parent */
  4348. if (r >= CTX_MAX)
  4349. sel = SEL_BACK;
  4350. else if (r >= 0 && r != cfg.curctx) {
  4351. if (cfg.selmode)
  4352. lastappendpos = selbufpos;
  4353. savecurctx(&cfg, path, dents[cur].name, r);
  4354. /* Reset the pointers */
  4355. path = g_ctx[r].c_path;
  4356. lastdir = g_ctx[r].c_last;
  4357. lastname = g_ctx[r].c_name;
  4358. setdirwatch();
  4359. goto begin;
  4360. }
  4361. }
  4362. #endif
  4363. // fallthrough
  4364. case SEL_BACK:
  4365. #ifndef NOMOUSE
  4366. if (sel == SEL_BACK) {
  4367. #endif
  4368. dir = visit_parent(path, newpath, &presel);
  4369. if (!dir)
  4370. goto nochange;
  4371. /* Save history */
  4372. xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
  4373. cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
  4374. goto begin;
  4375. #ifndef NOMOUSE
  4376. }
  4377. #endif
  4378. #ifndef NOMOUSE
  4379. /* Middle click action */
  4380. if (event.bstate == BUTTON2_PRESSED) {
  4381. presel = middle_click_key;
  4382. goto nochange;
  4383. }
  4384. #if NCURSES_MOUSE_VERSION > 1
  4385. /* Scroll up */
  4386. if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
  4387. move_cursor((cur + ndents - 1) % ndents, 0);
  4388. break;
  4389. }
  4390. /* Scroll down */
  4391. if (event.bstate == BUTTON5_PRESSED && ndents
  4392. && (cfg.rollover || (cur != ndents - 1))) {
  4393. move_cursor((cur + 1) % ndents, 0);
  4394. break;
  4395. }
  4396. #endif
  4397. /* Toggle filter mode on left click on last 2 lines */
  4398. if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
  4399. clearfilter();
  4400. cfg.filtermode ^= 1;
  4401. if (cfg.filtermode) {
  4402. presel = FILTER;
  4403. goto nochange;
  4404. }
  4405. /* Start watching the directory */
  4406. watch = TRUE;
  4407. if (ndents)
  4408. copycurname();
  4409. goto begin;
  4410. }
  4411. /* Handle clicking on a file */
  4412. if (event.y >= 2 && event.y <= ndents + 1 &&
  4413. (event.bstate == BUTTON1_PRESSED ||
  4414. event.bstate == BUTTON3_PRESSED)) {
  4415. r = curscroll + (event.y - 2);
  4416. move_cursor(r, 1);
  4417. /* Handle right click selection */
  4418. if (event.bstate == BUTTON3_PRESSED) {
  4419. rightclicksel = 1;
  4420. presel = SELECT;
  4421. goto nochange;
  4422. }
  4423. currentmouse ^= 1;
  4424. clock_gettime(
  4425. #if defined(CLOCK_MONOTONIC_RAW)
  4426. CLOCK_MONOTONIC_RAW,
  4427. #elif defined(CLOCK_MONOTONIC)
  4428. CLOCK_MONOTONIC,
  4429. #else
  4430. CLOCK_REALTIME,
  4431. #endif
  4432. &mousetimings[currentmouse]);
  4433. /*Single click just selects, double click also opens */
  4434. if (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
  4435. + (mousetimings[0].tv_nsec - mousetimings[1].tv_nsec))
  4436. > DOUBLECLICK_INTERVAL_NS)
  4437. break;
  4438. mousetimings[currentmouse].tv_sec = 0;
  4439. } else {
  4440. if (cfg.filtermode || filterset())
  4441. presel = FILTER;
  4442. if (ndents)
  4443. copycurname();
  4444. goto nochange;
  4445. }
  4446. #endif
  4447. // fallthrough
  4448. case SEL_NAV_IN: // fallthrough
  4449. case SEL_GOIN:
  4450. /* Cannot descend in empty directories */
  4451. if (!ndents)
  4452. goto begin;
  4453. mkpath(path, dents[cur].name, newpath);
  4454. DPRINTF_S(newpath);
  4455. /* Cannot use stale data in entry, file may be missing by now */
  4456. if (stat(newpath, &sb) == -1) {
  4457. printwarn(&presel);
  4458. goto nochange;
  4459. }
  4460. DPRINTF_U(sb.st_mode);
  4461. switch (sb.st_mode & S_IFMT) {
  4462. case S_IFDIR:
  4463. if (access(newpath, R_OK) == -1) {
  4464. printwarn(&presel);
  4465. goto nochange;
  4466. }
  4467. cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
  4468. goto begin;
  4469. case S_IFREG:
  4470. {
  4471. /* If opened as vim plugin and Enter/^M pressed, pick */
  4472. if (cfg.picker && sel == SEL_GOIN) {
  4473. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4474. writesel(pselbuf, selbufpos - 1);
  4475. free(mark);
  4476. return _SUCCESS;
  4477. }
  4478. /* If open file is disabled on right arrow or `l`, return */
  4479. if (cfg.nonavopen && sel == SEL_NAV_IN)
  4480. goto nochange;
  4481. /* Handle plugin selection mode */
  4482. if (cfg.runplugin) {
  4483. cfg.runplugin = 0;
  4484. /* Must be in plugin dir and same context to select plugin */
  4485. if ((cfg.runctx == cfg.curctx) && !strcmp(path, plugindir)) {
  4486. endselection();
  4487. /* Copy path so we can return back to earlier dir */
  4488. xstrsncpy(path, rundir, PATH_MAX);
  4489. rundir[0] = '\0';
  4490. if (!run_selected_plugin(&path, dents[cur].name,
  4491. runfile, &lastname, &lastdir)) {
  4492. DPRINTF_S("plugin failed!");
  4493. }
  4494. if (runfile[0])
  4495. runfile[0] = '\0';
  4496. clearfilter();
  4497. setdirwatch();
  4498. goto begin;
  4499. }
  4500. }
  4501. if (cfg.useeditor && (!sb.st_size ||
  4502. #ifdef FILE_MIME_OPTS
  4503. (get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, newpath, FALSE)
  4504. && !strncmp(g_buf, "text/", 5)))) {
  4505. #else
  4506. /* no mime option; guess from description instead */
  4507. (get_output(g_buf, CMD_LEN_MAX, "file", "-b", newpath, FALSE)
  4508. && strstr(g_buf, "text")))) {
  4509. #endif
  4510. spawn(editor, newpath, NULL, path, F_CLI);
  4511. continue;
  4512. }
  4513. if (!sb.st_size) {
  4514. printwait(messages[MSG_EMPTY_FILE], &presel);
  4515. goto nochange;
  4516. }
  4517. #ifdef PCRE
  4518. if (!pcre_exec(archive_pcre, NULL, dents[cur].name,
  4519. xstrlen(dents[cur].name), 0, 0, NULL, 0)) {
  4520. #else
  4521. if (!regexec(&archive_re, dents[cur].name, 0, NULL, 0)) {
  4522. #endif
  4523. r = get_input(messages[MSG_ARCHIVE_OPTS]);
  4524. if (r == 'l' || r == 'x') {
  4525. mkpath(path, dents[cur].name, newpath);
  4526. handle_archive(newpath, path, r);
  4527. if (r == 'l') {
  4528. statusbar(path);
  4529. goto nochange;
  4530. }
  4531. copycurname();
  4532. clearfilter();
  4533. goto begin;
  4534. }
  4535. if (r == 'm') {
  4536. if (!archive_mount(path, newpath)) {
  4537. presel = MSGWAIT;
  4538. goto nochange;
  4539. }
  4540. cdprep(lastdir, lastname, path, newpath)
  4541. ? (presel = FILTER) : (watch = TRUE);
  4542. goto begin;
  4543. }
  4544. if (r != 'd') {
  4545. printwait(messages[MSG_INVALID_KEY], &presel);
  4546. goto nochange;
  4547. }
  4548. }
  4549. /* Invoke desktop opener as last resort */
  4550. spawn(opener, newpath, NULL, NULL, opener_flags);
  4551. /* Move cursor to the next entry if not the last entry */
  4552. if ((g_states & STATE_AUTONEXT) && cur != ndents - 1)
  4553. move_cursor((cur + 1) % ndents, 0);
  4554. continue;
  4555. }
  4556. default:
  4557. printwait(messages[MSG_UNSUPPORTED], &presel);
  4558. goto nochange;
  4559. }
  4560. case SEL_NEXT: // fallthrough
  4561. case SEL_PREV: // fallthrough
  4562. case SEL_PGDN: // fallthrough
  4563. case SEL_CTRL_D: // fallthrough
  4564. case SEL_PGUP: // fallthrough
  4565. case SEL_CTRL_U: // fallthrough
  4566. case SEL_HOME: // fallthrough
  4567. case SEL_END: // fallthrough
  4568. case SEL_FIRST:
  4569. g_states |= STATE_MOVE_OP;
  4570. handle_screen_move(sel);
  4571. break;
  4572. case SEL_CDHOME: // fallthrough
  4573. case SEL_CDBEGIN: // fallthrough
  4574. case SEL_CDLAST: // fallthrough
  4575. case SEL_CDROOT:
  4576. switch (sel) {
  4577. case SEL_CDHOME:
  4578. dir = home;
  4579. break;
  4580. case SEL_CDBEGIN:
  4581. dir = ipath;
  4582. break;
  4583. case SEL_CDLAST:
  4584. dir = lastdir;
  4585. break;
  4586. default: /* SEL_CDROOT */
  4587. dir = "/";
  4588. break;
  4589. }
  4590. if (!dir || !*dir) {
  4591. printwait(messages[MSG_NOT_SET], &presel);
  4592. goto nochange;
  4593. }
  4594. if (!xdiraccess(dir)) {
  4595. presel = MSGWAIT;
  4596. goto nochange;
  4597. }
  4598. if (strcmp(path, dir) == 0) {
  4599. if (cfg.filtermode)
  4600. presel = FILTER;
  4601. goto nochange;
  4602. }
  4603. /* SEL_CDLAST: dir pointing to lastdir */
  4604. xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
  4605. case SEL_BOOKMARK:
  4606. if (sel == SEL_BOOKMARK) {
  4607. r = (int)handle_bookmark(mark, newpath);
  4608. if (r) {
  4609. printwait(messages[r], &presel);
  4610. goto nochange;
  4611. }
  4612. if (strcmp(path, newpath) == 0)
  4613. break;
  4614. } // fallthrough
  4615. case SEL_REMOTE:
  4616. if (sel == SEL_REMOTE && !remote_mount(newpath, path)) {
  4617. presel = MSGWAIT;
  4618. goto nochange;
  4619. }
  4620. cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
  4621. goto begin;
  4622. case SEL_CYCLE: // fallthrough
  4623. case SEL_CYCLER: // fallthrough
  4624. case SEL_CTX1: // fallthrough
  4625. case SEL_CTX2: // fallthrough
  4626. case SEL_CTX3: // fallthrough
  4627. case SEL_CTX4:
  4628. r = handle_context_switch(sel);
  4629. if (r < 0)
  4630. continue;
  4631. savecurctx(&cfg, path, dents[cur].name, r);
  4632. /* Reset the pointers */
  4633. path = g_ctx[r].c_path;
  4634. lastdir = g_ctx[r].c_last;
  4635. lastname = g_ctx[r].c_name;
  4636. tmp = g_ctx[r].c_fltr;
  4637. if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
  4638. presel = FILTER;
  4639. else
  4640. watch = TRUE;
  4641. goto begin;
  4642. case SEL_PIN:
  4643. free(mark);
  4644. mark = xstrdup(path);
  4645. printwait(mark, &presel);
  4646. goto nochange;
  4647. case SEL_FLTR:
  4648. /* Unwatch dir if we are still in a filtered view */
  4649. #ifdef LINUX_INOTIFY
  4650. if (inotify_wd >= 0) {
  4651. inotify_rm_watch(inotify_fd, inotify_wd);
  4652. inotify_wd = -1;
  4653. }
  4654. #elif defined(BSD_KQUEUE)
  4655. if (event_fd >= 0) {
  4656. close(event_fd);
  4657. event_fd = -1;
  4658. }
  4659. #elif defined(HAIKU_NM)
  4660. if (haiku_nm_active) {
  4661. haiku_stop_watch(haiku_hnd);
  4662. haiku_nm_active = FALSE;
  4663. }
  4664. #endif
  4665. presel = filterentries(path, lastname);
  4666. if (presel == 27) {
  4667. presel = 0;
  4668. break;
  4669. }
  4670. goto nochange;
  4671. case SEL_MFLTR: // fallthrough
  4672. case SEL_HIDDEN: // fallthrough
  4673. case SEL_DETAIL: // fallthrough
  4674. case SEL_SORT:
  4675. switch (sel) {
  4676. case SEL_MFLTR:
  4677. cfg.filtermode ^= 1;
  4678. if (cfg.filtermode) {
  4679. presel = FILTER;
  4680. clearfilter();
  4681. goto nochange;
  4682. }
  4683. watch = TRUE; // fallthrough
  4684. case SEL_HIDDEN:
  4685. if (sel == SEL_HIDDEN) {
  4686. cfg.showhidden ^= 1;
  4687. if (cfg.filtermode)
  4688. presel = FILTER;
  4689. clearfilter();
  4690. }
  4691. if (ndents)
  4692. copycurname();
  4693. goto begin;
  4694. case SEL_DETAIL:
  4695. cfg.showdetail ^= 1;
  4696. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  4697. cfg.blkorder = 0;
  4698. continue;
  4699. default: /* SEL_SORT */
  4700. r = set_sort_flags(get_input(messages[MSG_ORDER]));
  4701. if (!r) {
  4702. printwait(messages[MSG_INVALID_KEY], &presel);
  4703. goto nochange;
  4704. }
  4705. }
  4706. if (cfg.filtermode || filterset())
  4707. presel = FILTER;
  4708. if (ndents) {
  4709. copycurname();
  4710. if (r == 'd' || r == 'a')
  4711. goto begin;
  4712. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  4713. move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
  4714. }
  4715. continue;
  4716. case SEL_STATS: // fallthrough
  4717. case SEL_CHMODX:
  4718. if (ndents) {
  4719. tmp = (listpath && xstrcmp(path, listpath) == 0) ? prefixpath : path;
  4720. mkpath(tmp, dents[cur].name, newpath);
  4721. if (lstat(newpath, &sb) == -1
  4722. || (sel == SEL_STATS && !show_stats(newpath, &sb))
  4723. || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
  4724. printwarn(&presel);
  4725. goto nochange;
  4726. }
  4727. if (sel == SEL_CHMODX)
  4728. dents[cur].mode ^= 0111;
  4729. }
  4730. break;
  4731. case SEL_REDRAW: // fallthrough
  4732. case SEL_RENAMEMUL: // fallthrough
  4733. case SEL_HELP: // fallthrough
  4734. case SEL_AUTONEXT: // fallthrough
  4735. case SEL_EDIT: // fallthrough
  4736. case SEL_LOCK:
  4737. {
  4738. bool refresh = FALSE;
  4739. if (ndents)
  4740. mkpath(path, dents[cur].name, newpath);
  4741. else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
  4742. goto nochange;
  4743. switch (sel) {
  4744. case SEL_REDRAW:
  4745. refresh = TRUE;
  4746. break;
  4747. case SEL_RENAMEMUL:
  4748. endselection();
  4749. if (!(getutil(utils[UTIL_BASH])
  4750. && plugscript(utils[UTIL_NMV], path, F_CLI))
  4751. #ifndef NOBATCH
  4752. && !batch_rename(path)) {
  4753. #else
  4754. ) {
  4755. #endif
  4756. printwait(messages[MSG_FAILED], &presel);
  4757. goto nochange;
  4758. }
  4759. refresh = TRUE;
  4760. break;
  4761. case SEL_HELP:
  4762. show_help(path); // fallthrough
  4763. case SEL_AUTONEXT:
  4764. if (sel == SEL_AUTONEXT)
  4765. g_states ^= STATE_AUTONEXT;
  4766. if (cfg.filtermode)
  4767. presel = FILTER;
  4768. if (ndents)
  4769. copycurname();
  4770. goto nochange;
  4771. case SEL_EDIT:
  4772. spawn(editor, dents[cur].name, NULL, path, F_CLI);
  4773. continue;
  4774. default: /* SEL_LOCK */
  4775. lock_terminal();
  4776. break;
  4777. }
  4778. /* In case of successful operation, reload contents */
  4779. /* Continue in type-to-nav mode, if enabled */
  4780. if ((cfg.filtermode || filterset()) && !refresh)
  4781. break;
  4782. /* Save current */
  4783. if (ndents)
  4784. copycurname();
  4785. /* Repopulate as directory content may have changed */
  4786. goto begin;
  4787. }
  4788. case SEL_SEL:
  4789. if (!ndents)
  4790. goto nochange;
  4791. startselection();
  4792. if (g_states & STATE_RANGESEL)
  4793. g_states &= ~STATE_RANGESEL;
  4794. /* Toggle selection status */
  4795. dents[cur].flags ^= FILE_SELECTED;
  4796. if (dents[cur].flags & FILE_SELECTED) {
  4797. ++nselected;
  4798. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4799. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4800. } else {
  4801. selbufpos = lastappendpos;
  4802. if (--nselected) {
  4803. updateselbuf(path, newpath);
  4804. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4805. } else
  4806. writesel(NULL, 0);
  4807. }
  4808. if (cfg.x11)
  4809. plugscript(utils[UTIL_CBCP], NULL, F_NOWAIT | F_NOTRACE);
  4810. if (!nselected)
  4811. unlink(selpath);
  4812. #ifndef NOMOUSE
  4813. if (rightclicksel)
  4814. rightclicksel = 0;
  4815. else
  4816. #endif
  4817. /* move cursor to the next entry if this is not the last entry */
  4818. if (!cfg.picker && cur != ndents - 1)
  4819. move_cursor((cur + 1) % ndents, 0);
  4820. break;
  4821. case SEL_SELMUL:
  4822. if (!ndents)
  4823. goto nochange;
  4824. startselection();
  4825. g_states ^= STATE_RANGESEL;
  4826. if (stat(path, &sb) == -1) {
  4827. printwarn(&presel);
  4828. goto nochange;
  4829. }
  4830. if (g_states & STATE_RANGESEL) { /* Range selection started */
  4831. #ifndef DIR_LIMITED_SELECTION
  4832. inode = sb.st_ino;
  4833. #endif
  4834. selstartid = cur;
  4835. continue;
  4836. }
  4837. #ifndef DIR_LIMITED_SELECTION
  4838. if (inode != sb.st_ino) {
  4839. printwait(messages[MSG_DIR_CHANGED], &presel);
  4840. goto nochange;
  4841. }
  4842. #endif
  4843. if (cur < selstartid) {
  4844. selendid = selstartid;
  4845. selstartid = cur;
  4846. } else
  4847. selendid = cur;
  4848. /* Clear selection on repeat on same file */
  4849. if (selstartid == selendid) {
  4850. resetselind();
  4851. clearselection();
  4852. break;
  4853. } // fallthrough
  4854. case SEL_SELALL:
  4855. if (sel == SEL_SELALL) {
  4856. if (!ndents)
  4857. goto nochange;
  4858. startselection();
  4859. if (g_states & STATE_RANGESEL)
  4860. g_states &= ~STATE_RANGESEL;
  4861. selstartid = 0;
  4862. selendid = ndents - 1;
  4863. }
  4864. /* Remember current selection buffer position */
  4865. for (r = selstartid; r <= selendid; ++r)
  4866. if (!(dents[r].flags & FILE_SELECTED)) {
  4867. /* Write the path to selection file to avoid flush */
  4868. appendfpath(newpath, mkpath(path, dents[r].name, newpath));
  4869. dents[r].flags |= FILE_SELECTED;
  4870. ++nselected;
  4871. }
  4872. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4873. if (cfg.x11)
  4874. plugscript(utils[UTIL_CBCP], NULL, F_NOWAIT | F_NOTRACE);
  4875. continue;
  4876. case SEL_SELEDIT:
  4877. r = editselection();
  4878. if (r <= 0) {
  4879. r = !r ? MSG_0_SELECTED : MSG_FAILED;
  4880. printwait(messages[r], &presel);
  4881. } else {
  4882. if (cfg.x11)
  4883. plugscript(utils[UTIL_CBCP], NULL, F_NOWAIT | F_NOTRACE);
  4884. cfg.filtermode ? presel = FILTER : statusbar(path);
  4885. }
  4886. goto nochange;
  4887. case SEL_CP: // fallthrough
  4888. case SEL_MV: // fallthrough
  4889. case SEL_CPMVAS: // fallthrough
  4890. case SEL_RM:
  4891. {
  4892. if (sel == SEL_RM) {
  4893. r = get_cur_or_sel();
  4894. if (!r) {
  4895. statusbar(path);
  4896. goto nochange;
  4897. }
  4898. if (r == 'c') {
  4899. tmp = (listpath && xstrcmp(path, listpath) == 0)
  4900. ? prefixpath : path;
  4901. mkpath(tmp, dents[cur].name, newpath);
  4902. xrm(newpath);
  4903. if (access(newpath, F_OK) == 0) /* File not removed */
  4904. continue;
  4905. if (cur) {
  4906. cur += (cur != (ndents - 1)) ? 1 : -1;
  4907. copycurname();
  4908. } else
  4909. lastname[0] = '\0';
  4910. if (cfg.filtermode || filterset())
  4911. presel = FILTER;
  4912. goto begin;
  4913. }
  4914. }
  4915. if (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
  4916. mkpath(path, xbasename(pselbuf), newpath);
  4917. else
  4918. newpath[0] = '\0';
  4919. endselection();
  4920. if (!cpmvrm_selection(sel, path)) {
  4921. presel = MSGWAIT;
  4922. goto nochange;
  4923. }
  4924. if (cfg.filtermode)
  4925. presel = FILTER;
  4926. clearfilter();
  4927. /* Show notification on operation complete */
  4928. if (cfg.x11)
  4929. plugscript(utils[UTIL_NTFY], NULL, F_NOWAIT | F_NOTRACE);
  4930. if (newpath[0] && !access(newpath, F_OK))
  4931. xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
  4932. else if (ndents)
  4933. copycurname();
  4934. goto begin;
  4935. }
  4936. case SEL_ARCHIVE: // fallthrough
  4937. case SEL_OPENWITH: // fallthrough
  4938. case SEL_NEW: // fallthrough
  4939. case SEL_RENAME:
  4940. {
  4941. int fd, ret = 'n';
  4942. if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
  4943. break;
  4944. if (sel != SEL_OPENWITH)
  4945. endselection();
  4946. switch (sel) {
  4947. case SEL_ARCHIVE:
  4948. r = get_cur_or_sel();
  4949. if (!r) {
  4950. statusbar(path);
  4951. goto nochange;
  4952. }
  4953. if (r == 's') {
  4954. if (!selsafe()) {
  4955. presel = MSGWAIT;
  4956. goto nochange;
  4957. }
  4958. tmp = NULL;
  4959. } else
  4960. tmp = dents[cur].name;
  4961. tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
  4962. break;
  4963. case SEL_OPENWITH:
  4964. #ifdef NORL
  4965. tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
  4966. #else
  4967. presel = 0;
  4968. tmp = getreadline(messages[MSG_OPEN_WITH], path, ipath, &presel);
  4969. if (presel == MSGWAIT)
  4970. goto nochange;
  4971. #endif
  4972. break;
  4973. case SEL_NEW:
  4974. r = get_input(messages[MSG_NEW_OPTS]);
  4975. if (r == 'f' || r == 'd')
  4976. tmp = xreadline(NULL, messages[MSG_REL_PATH]);
  4977. else if (r == 's' || r == 'h')
  4978. tmp = xreadline(NULL, messages[MSG_LINK_PREFIX]);
  4979. else
  4980. tmp = NULL;
  4981. break;
  4982. default: /* SEL_RENAME */
  4983. tmp = xreadline(dents[cur].name, "");
  4984. break;
  4985. }
  4986. if (!tmp || !*tmp)
  4987. break;
  4988. /* Allow only relative, same dir paths */
  4989. if (tmp[0] == '/'
  4990. || ((r != 'f' && r != 'd') && (xstrcmp(xbasename(tmp), tmp) != 0))) {
  4991. printwait(messages[MSG_NO_TRAVERSAL], &presel);
  4992. goto nochange;
  4993. }
  4994. switch (sel) {
  4995. case SEL_ARCHIVE:
  4996. if (r == 'c' && strcmp(tmp, dents[cur].name) == 0)
  4997. goto nochange;
  4998. mkpath(path, tmp, newpath);
  4999. if (access(newpath, F_OK) == 0) {
  5000. if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
  5001. statusbar(path);
  5002. goto nochange;
  5003. }
  5004. }
  5005. get_archive_cmd(newpath, tmp);
  5006. (r == 's') ? archive_selection(newpath, tmp, path)
  5007. : spawn(newpath, tmp, dents[cur].name,
  5008. path, F_NORMAL | F_MULTI);
  5009. mkpath(path, tmp, newpath);
  5010. if (access(newpath, F_OK) == 0) { /* File created */
  5011. xstrsncpy(lastname, tmp, NAME_MAX + 1);
  5012. clearfilter(); /* Archive name may not match */
  5013. goto begin;
  5014. }
  5015. continue;
  5016. case SEL_OPENWITH:
  5017. /* Confirm if app is CLI or GUI */
  5018. r = get_input(messages[MSG_CLI_MODE]);
  5019. r = (r == 'c' ? F_CLI :
  5020. (r == 'g' ? F_NOWAIT | F_NOTRACE | F_MULTI : 0));
  5021. if (r) {
  5022. mkpath(path, dents[cur].name, newpath);
  5023. spawn(tmp, newpath, NULL, path, r);
  5024. }
  5025. cfg.filtermode ? presel = FILTER : statusbar(path);
  5026. copycurname();
  5027. goto nochange;
  5028. case SEL_RENAME:
  5029. /* Skip renaming to same name */
  5030. if (strcmp(tmp, dents[cur].name) == 0) {
  5031. tmp = xreadline(dents[cur].name, messages[MSG_COPY_NAME]);
  5032. if (!tmp || !tmp[0] || !strcmp(tmp, dents[cur].name)) {
  5033. cfg.filtermode ? presel = FILTER : statusbar(path);
  5034. copycurname();
  5035. goto nochange;
  5036. }
  5037. ret = 'd';
  5038. }
  5039. break;
  5040. default: /* SEL_NEW */
  5041. break;
  5042. }
  5043. /* Open the descriptor to currently open directory */
  5044. #ifdef O_DIRECTORY
  5045. fd = open(path, O_RDONLY | O_DIRECTORY);
  5046. #else
  5047. fd = open(path, O_RDONLY);
  5048. #endif
  5049. if (fd == -1) {
  5050. printwarn(&presel);
  5051. goto nochange;
  5052. }
  5053. /* Check if another file with same name exists */
  5054. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  5055. if (sel == SEL_RENAME) {
  5056. /* Overwrite file with same name? */
  5057. if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
  5058. close(fd);
  5059. break;
  5060. }
  5061. } else {
  5062. /* Do nothing in case of NEW */
  5063. close(fd);
  5064. printwait(messages[MSG_EXISTS], &presel);
  5065. goto nochange;
  5066. }
  5067. }
  5068. if (sel == SEL_RENAME) {
  5069. /* Rename the file */
  5070. if (ret == 'd')
  5071. spawn("cp -rp", dents[cur].name, tmp, path, F_SILENT);
  5072. else if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  5073. close(fd);
  5074. printwarn(&presel);
  5075. goto nochange;
  5076. }
  5077. close(fd);
  5078. xstrsncpy(lastname, tmp, NAME_MAX + 1);
  5079. } else { /* SEL_NEW */
  5080. close(fd);
  5081. presel = 0;
  5082. /* Check if it's a dir or file */
  5083. if (r == 'f') {
  5084. mkpath(path, tmp, newpath);
  5085. ret = xmktree(newpath, FALSE);
  5086. } else if (r == 'd') {
  5087. mkpath(path, tmp, newpath);
  5088. ret = xmktree(newpath, TRUE);
  5089. } else if (r == 's' || r == 'h') {
  5090. if (tmp[0] == '@' && tmp[1] == '\0')
  5091. tmp[0] = '\0';
  5092. ret = xlink(tmp, path, (ndents ? dents[cur].name : NULL),
  5093. newpath, &presel, r);
  5094. }
  5095. if (!ret)
  5096. printwait(messages[MSG_FAILED], &presel);
  5097. if (ret <= 0)
  5098. goto nochange;
  5099. if (r == 'f' || r == 'd')
  5100. xstrsncpy(lastname, tmp, NAME_MAX + 1);
  5101. else if (ndents) {
  5102. if (cfg.filtermode)
  5103. presel = FILTER;
  5104. copycurname();
  5105. }
  5106. clearfilter();
  5107. }
  5108. goto begin;
  5109. }
  5110. case SEL_PLUGIN:
  5111. /* Check if directory is accessible */
  5112. if (!xdiraccess(plugindir)) {
  5113. printwarn(&presel);
  5114. goto nochange;
  5115. }
  5116. r = xstrsncpy(g_buf, messages[MSG_PLUGIN_KEYS], CMD_LEN_MAX);
  5117. printkeys(plug, g_buf + r - 1, maxplug);
  5118. printmsg(g_buf);
  5119. r = get_input(NULL);
  5120. if (r != '\r') {
  5121. endselection();
  5122. tmp = get_kv_val(plug, NULL, r, maxplug, FALSE);
  5123. if (!tmp) {
  5124. printwait(messages[MSG_INVALID_KEY], &presel);
  5125. goto nochange;
  5126. }
  5127. if (tmp[0] == '-' && tmp[1]) {
  5128. ++tmp;
  5129. r = FALSE; /* Do not refresh dir after completion */
  5130. } else
  5131. r = TRUE;
  5132. if (!run_selected_plugin(&path, tmp, (ndents ? dents[cur].name : NULL),
  5133. &lastname, &lastdir)) {
  5134. printwait(messages[MSG_FAILED], &presel);
  5135. goto nochange;
  5136. }
  5137. if (ndents)
  5138. copycurname();
  5139. if (!r) {
  5140. cfg.filtermode ? presel = FILTER : statusbar(path);
  5141. goto nochange;
  5142. }
  5143. } else { /* 'Return/Enter' enters the plugin directory */
  5144. cfg.runplugin ^= 1;
  5145. if (!cfg.runplugin && rundir[0]) {
  5146. /*
  5147. * If toggled, and still in the plugin dir,
  5148. * switch to original directory
  5149. */
  5150. if (strcmp(path, plugindir) == 0) {
  5151. xstrsncpy(path, rundir, PATH_MAX);
  5152. xstrsncpy(lastname, runfile, NAME_MAX);
  5153. rundir[0] = runfile[0] = '\0';
  5154. setdirwatch();
  5155. goto begin;
  5156. }
  5157. /* Otherwise, initiate choosing plugin again */
  5158. cfg.runplugin = 1;
  5159. }
  5160. xstrsncpy(rundir, path, PATH_MAX);
  5161. xstrsncpy(path, plugindir, PATH_MAX);
  5162. if (ndents)
  5163. xstrsncpy(runfile, dents[cur].name, NAME_MAX);
  5164. cfg.runctx = cfg.curctx;
  5165. lastname[0] = '\0';
  5166. }
  5167. setdirwatch();
  5168. clearfilter();
  5169. goto begin;
  5170. case SEL_SHELL: // fallthrough
  5171. case SEL_LAUNCH: // fallthrough
  5172. case SEL_RUNCMD:
  5173. endselection();
  5174. switch (sel) {
  5175. case SEL_SHELL:
  5176. /* Set nnn nesting level */
  5177. tmp = getenv(env_cfg[NNNLVL]);
  5178. setenv(env_cfg[NNNLVL], xitoa((tmp ? atoi(tmp) : 0) + 1), 1);
  5179. setenv(envs[ENV_NCUR], (ndents ? dents[cur].name : ""), 1);
  5180. spawn(shell, NULL, NULL, path, F_CLI);
  5181. setenv(env_cfg[NNNLVL], xitoa(tmp ? atoi(tmp) : 0), 1);
  5182. r = TRUE;
  5183. break;
  5184. case SEL_LAUNCH:
  5185. launch_app(path, newpath);
  5186. r = FALSE;
  5187. break;
  5188. default: /* SEL_RUNCMD */
  5189. r = TRUE;
  5190. #ifndef NORL
  5191. if (cfg.picker) {
  5192. #endif
  5193. tmp = xreadline(NULL, ">>> ");
  5194. #ifndef NORL
  5195. } else {
  5196. presel = 0;
  5197. tmp = getreadline("\n>>> ", path, ipath, &presel);
  5198. if (presel == MSGWAIT)
  5199. goto nochange;
  5200. }
  5201. #endif
  5202. if (tmp && *tmp) // NOLINT
  5203. prompt_run(tmp, (ndents ? dents[cur].name : ""), path);
  5204. else
  5205. r = FALSE;
  5206. }
  5207. /* Continue in type-to-nav mode, if enabled */
  5208. if (cfg.filtermode)
  5209. presel = FILTER;
  5210. /* Save current */
  5211. if (ndents)
  5212. copycurname();
  5213. if (!r)
  5214. goto nochange;
  5215. /* Repopulate as directory content may have changed */
  5216. goto begin;
  5217. case SEL_UMOUNT:
  5218. tmp = ndents ? dents[cur].name : NULL;
  5219. unmount(tmp, newpath, &presel, path);
  5220. goto nochange;
  5221. case SEL_SESSIONS:
  5222. r = get_input(messages[MSG_SSN_OPTS]);
  5223. if (r == 's')
  5224. save_session(FALSE, &presel);
  5225. else if (r == 'l' || r == 'r') {
  5226. if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
  5227. setdirwatch();
  5228. goto begin;
  5229. }
  5230. }
  5231. statusbar(path);
  5232. goto nochange;
  5233. case SEL_EXPORT:
  5234. export_file_list();
  5235. cfg.filtermode ? presel = FILTER : statusbar(path);
  5236. goto nochange;
  5237. case SEL_TIMETYPE:
  5238. if (!set_time_type(&presel))
  5239. goto nochange;
  5240. goto begin;
  5241. case SEL_QUITCTX: // fallthrough
  5242. case SEL_QUITCD: // fallthrough
  5243. case SEL_QUIT:
  5244. case SEL_QUITFAIL:
  5245. if (sel == SEL_QUITCTX) {
  5246. int ctx = cfg.curctx;
  5247. for (r = (ctx + 1) & ~CTX_MAX;
  5248. (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
  5249. r = ((r + 1) & ~CTX_MAX)) {
  5250. };
  5251. if (r != ctx) {
  5252. bool selmode = cfg.selmode ? TRUE : FALSE;
  5253. g_ctx[ctx].c_cfg.ctxactive = 0;
  5254. /* Switch to next active context */
  5255. path = g_ctx[r].c_path;
  5256. lastdir = g_ctx[r].c_last;
  5257. lastname = g_ctx[r].c_name;
  5258. /* Switch light/detail mode */
  5259. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  5260. /* Set the reverse */
  5261. printptr = cfg.showdetail ?
  5262. &printent : &printent_long;
  5263. cfg = g_ctx[r].c_cfg;
  5264. /* Continue selection mode */
  5265. cfg.selmode = selmode;
  5266. cfg.curctx = r;
  5267. setdirwatch();
  5268. goto begin;
  5269. }
  5270. } else if (!(g_states & STATE_FORCEQUIT)) {
  5271. for (r = 0; r < CTX_MAX; ++r)
  5272. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  5273. r = get_input(messages[MSG_QUIT_ALL]);
  5274. break;
  5275. }
  5276. if (!(r == CTX_MAX || xconfirm(r)))
  5277. break; // fallthrough
  5278. }
  5279. /* CD on Quit */
  5280. /* In vim picker mode, clear selection and exit */
  5281. /* Picker mode: reset buffer or clear file */
  5282. if (sel == SEL_QUITCD || getenv("NNN_TMPFILE"))
  5283. cfg.picker ? selbufpos = 0 : write_lastdir(path);
  5284. free(mark);
  5285. return sel == SEL_QUITFAIL ? _FAILURE : _SUCCESS;
  5286. default:
  5287. r = FALSE;
  5288. if (xlines != LINES || xcols != COLS) {
  5289. setdirwatch(); /* Terminal resized */
  5290. r = TRUE;
  5291. } else if (idletimeout && idle == idletimeout)
  5292. lock_terminal(); /* Locker */
  5293. idle = 0;
  5294. if (ndents)
  5295. copycurname();
  5296. if (r)
  5297. continue;
  5298. goto nochange;
  5299. } /* switch (sel) */
  5300. }
  5301. }
  5302. static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
  5303. {
  5304. /* tmpdir holds the full path */
  5305. /* tmp holds the path without the tmp dir prefix */
  5306. int err, ignore = 0;
  5307. struct stat sb;
  5308. char *slash, *tmp;
  5309. ssize_t len = xstrlen(prefix);
  5310. char *tmpdir = malloc(sizeof(char) * (PATH_MAX + TMP_LEN_MAX));
  5311. if (!tmpdir) {
  5312. DPRINTF_S(strerror(errno));
  5313. return NULL;
  5314. }
  5315. tmp = tmpdir + tmpfplen - 1;
  5316. xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
  5317. xstrsncpy(tmp, "/nnnXXXXXX", 11);
  5318. /* Points right after the base tmp dir */
  5319. tmp += 10;
  5320. if (!mkdtemp(tmpdir)) {
  5321. free(tmpdir);
  5322. DPRINTF_S(strerror(errno));
  5323. return NULL;
  5324. }
  5325. listpath = tmpdir;
  5326. for (ssize_t i = 0; i < entries; ++i) {
  5327. if (!paths[i])
  5328. continue;
  5329. err = stat(paths[i], &sb);
  5330. if (err && errno == ENOENT) {
  5331. ignore = 1;
  5332. continue;
  5333. }
  5334. /* Don't copy the common prefix */
  5335. xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
  5336. /* Get the dir containing the path */
  5337. slash = xmemrchr((uchar *)tmp, '/', xstrlen(paths[i]) - len);
  5338. if (slash)
  5339. *slash = '\0';
  5340. xmktree(tmpdir, TRUE);
  5341. if (slash)
  5342. *slash = '/';
  5343. if (symlink(paths[i], tmpdir)) {
  5344. DPRINTF_S(paths[i]);
  5345. DPRINTF_S(strerror(errno));
  5346. }
  5347. }
  5348. if (ignore)
  5349. g_states |= STATE_MSG;
  5350. /* Get the dir in which to start */
  5351. *tmp = '\0';
  5352. return tmpdir;
  5353. }
  5354. static char *load_input()
  5355. {
  5356. /* 512 KiB chunk size */
  5357. ssize_t i, chunk_count = 1, chunk = 512 * 1024, entries = 0;
  5358. char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
  5359. char cwd[PATH_MAX], *next, *tmp;
  5360. size_t offsets[LIST_FILES_MAX];
  5361. char **paths = NULL;
  5362. ssize_t input_read, total_read = 0, off = 0;
  5363. if (!input) {
  5364. DPRINTF_S(strerror(errno));
  5365. return NULL;
  5366. }
  5367. if (!getcwd(cwd, PATH_MAX)) {
  5368. free(input);
  5369. return NULL;
  5370. }
  5371. while (chunk_count < 512) {
  5372. input_read = read(STDIN_FILENO, input + total_read, chunk);
  5373. if (input_read < 0) {
  5374. DPRINTF_S(strerror(errno));
  5375. goto malloc_1;
  5376. }
  5377. if (input_read == 0)
  5378. break;
  5379. total_read += input_read;
  5380. ++chunk_count;
  5381. while (off < total_read) {
  5382. next = memchr(input + off, '\0', total_read - off) + 1;
  5383. if (next == (void *)1)
  5384. break;
  5385. if (next - input == off + 1) {
  5386. off = next - input;
  5387. continue;
  5388. }
  5389. if (entries == LIST_FILES_MAX) {
  5390. fprintf(stderr, messages[MSG_LIMIT], NULL);
  5391. goto malloc_1;
  5392. }
  5393. offsets[entries++] = off;
  5394. off = next - input;
  5395. }
  5396. if (chunk_count == 512) {
  5397. fprintf(stderr, messages[MSG_LIMIT], NULL);
  5398. goto malloc_1;
  5399. }
  5400. /* We don't need to allocate another chunk */
  5401. if (chunk_count == (total_read - input_read) / chunk)
  5402. continue;
  5403. chunk_count = total_read / chunk;
  5404. if (total_read % chunk)
  5405. ++chunk_count;
  5406. if (!(input = xrealloc(input, (chunk_count + 1) * chunk)))
  5407. return NULL;
  5408. }
  5409. if (off != total_read) {
  5410. if (entries == LIST_FILES_MAX) {
  5411. fprintf(stderr, messages[MSG_LIMIT], NULL);
  5412. goto malloc_1;
  5413. }
  5414. offsets[entries++] = off;
  5415. }
  5416. DPRINTF_D(entries);
  5417. DPRINTF_D(total_read);
  5418. DPRINTF_D(chunk_count);
  5419. if (!entries)
  5420. goto malloc_1;
  5421. input[total_read] = '\0';
  5422. paths = malloc(entries * sizeof(char *));
  5423. if (!paths)
  5424. goto malloc_1;
  5425. for (i = 0; i < entries; ++i)
  5426. paths[i] = input + offsets[i];
  5427. prefixpath = malloc(sizeof(char) * PATH_MAX);
  5428. if (!prefixpath)
  5429. goto malloc_1;
  5430. prefixpath[0] = '\0';
  5431. DPRINTF_S(paths[0]);
  5432. for (i = 0; i < entries; ++i) {
  5433. if (paths[i][0] == '\n' || selforparent(paths[i])) {
  5434. paths[i] = NULL;
  5435. continue;
  5436. }
  5437. if (!(paths[i] = abspath(paths[i], cwd))) {
  5438. entries = i; // free from the previous entry
  5439. goto malloc_2;
  5440. }
  5441. DPRINTF_S(paths[i]);
  5442. xstrsncpy(g_buf, paths[i], PATH_MAX);
  5443. if (!common_prefix(xdirname(g_buf), prefixpath)) {
  5444. entries = i + 1; // free from the current entry
  5445. goto malloc_2;
  5446. }
  5447. DPRINTF_S(prefixpath);
  5448. }
  5449. DPRINTF_S(prefixpath);
  5450. if (prefixpath[0]) {
  5451. if (entries == 1) {
  5452. tmp = xmemrchr((uchar *)prefixpath, '/', xstrlen(prefixpath));
  5453. if (!tmp)
  5454. goto malloc_2;
  5455. *(tmp != prefixpath ? tmp : tmp + 1) = '\0';
  5456. }
  5457. tmpdir = make_tmp_tree(paths, entries, prefixpath);
  5458. }
  5459. malloc_2:
  5460. for (i = entries - 1; i >= 0; --i)
  5461. free(paths[i]);
  5462. malloc_1:
  5463. free(input);
  5464. free(paths);
  5465. return tmpdir;
  5466. }
  5467. static void check_key_collision(void)
  5468. {
  5469. int key;
  5470. bool bitmap[KEY_MAX] = {FALSE};
  5471. for (ulong i = 0; i < sizeof(bindings) / sizeof(struct key); ++i) {
  5472. key = bindings[i].sym;
  5473. if (bitmap[key])
  5474. fprintf(stdout, "key collision! [%s]\n", keyname(key));
  5475. else
  5476. bitmap[key] = TRUE;
  5477. }
  5478. }
  5479. static void usage(void)
  5480. {
  5481. fprintf(stdout,
  5482. "%s: nnn [OPTIONS] [PATH]\n\n"
  5483. "The missing terminal file manager for X.\n\n"
  5484. "positional args:\n"
  5485. " PATH start dir [default: .]\n\n"
  5486. "optional args:\n"
  5487. " -A no dir auto-select\n"
  5488. " -b key open bookmark key\n"
  5489. " -c cli-only opener (overrides -e)\n"
  5490. " -d detail mode\n"
  5491. " -e text in $VISUAL/$EDITOR/vi\n"
  5492. " -E use EDITOR for undetached edits\n"
  5493. #ifndef NORL
  5494. " -f use readline history file\n"
  5495. #endif
  5496. " -F show fortune\n"
  5497. " -g regex filters [default: string]\n"
  5498. " -H show hidden files\n"
  5499. " -K detect key collision\n"
  5500. " -n type-to-nav mode\n"
  5501. " -o open files only on Enter\n"
  5502. " -p file selection file [stdout if '-']\n"
  5503. " -Q no quit confirmation\n"
  5504. " -r use advcpmv patched cp, mv\n"
  5505. " -R no rollover at edges\n"
  5506. " -s name load session by name\n"
  5507. " -S du mode\n"
  5508. " -t secs timeout to lock\n"
  5509. " -T key sort order [a/d/e/r/s/t/v]\n"
  5510. " -V show version\n"
  5511. " -x notis, sel to system clipboard\n"
  5512. " -h show help\n\n"
  5513. "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
  5514. }
  5515. static bool setup_config(void)
  5516. {
  5517. size_t r, len;
  5518. char *xdgcfg = getenv("XDG_CONFIG_HOME");
  5519. bool xdg = FALSE;
  5520. /* Set up configuration file paths */
  5521. if (xdgcfg && xdgcfg[0]) {
  5522. DPRINTF_S(xdgcfg);
  5523. if (xdgcfg[0] == '~') {
  5524. r = xstrsncpy(g_buf, home, PATH_MAX);
  5525. xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
  5526. xdgcfg = g_buf;
  5527. DPRINTF_S(xdgcfg);
  5528. }
  5529. if (!xdiraccess(xdgcfg)) {
  5530. xerror();
  5531. return FALSE;
  5532. }
  5533. len = xstrlen(xdgcfg) + 1 + 13; /* add length of "/nnn/sessions" */
  5534. xdg = TRUE;
  5535. }
  5536. if (!xdg)
  5537. len = xstrlen(home) + 1 + 21; /* add length of "/.config/nnn/sessions" */
  5538. cfgdir = (char *)malloc(len);
  5539. plugindir = (char *)malloc(len);
  5540. sessiondir = (char *)malloc(len);
  5541. if (!cfgdir || !plugindir || !sessiondir) {
  5542. xerror();
  5543. return FALSE;
  5544. }
  5545. if (xdg) {
  5546. xstrsncpy(cfgdir, xdgcfg, len);
  5547. r = len - 13; /* subtract length of "/nnn/sessions" */
  5548. } else {
  5549. r = xstrsncpy(cfgdir, home, len);
  5550. /* Create ~/.config */
  5551. xstrsncpy(cfgdir + r - 1, "/.config", len - r);
  5552. DPRINTF_S(cfgdir);
  5553. r += 8; /* length of "/.config" */
  5554. }
  5555. /* Create ~/.config/nnn */
  5556. xstrsncpy(cfgdir + r - 1, "/nnn", len - r);
  5557. DPRINTF_S(cfgdir);
  5558. /* Create ~/.config/nnn/plugins */
  5559. xstrsncpy(plugindir, cfgdir, PATH_MAX);
  5560. xstrsncpy(plugindir + r + 4 - 1, "/plugins", 9); /* subtract length of "/nnn" (4) */
  5561. DPRINTF_S(plugindir);
  5562. if (access(plugindir, F_OK) && !xmktree(plugindir, TRUE)) {
  5563. xerror();
  5564. return FALSE;
  5565. }
  5566. /* Create ~/.config/nnn/sessions */
  5567. xstrsncpy(sessiondir, cfgdir, PATH_MAX);
  5568. xstrsncpy(sessiondir + r + 4 - 1, "/sessions", 10); /* subtract length of "/nnn" (4) */
  5569. DPRINTF_S(sessiondir);
  5570. if (access(sessiondir, F_OK) && !xmktree(sessiondir, TRUE)) {
  5571. xerror();
  5572. return FALSE;
  5573. }
  5574. /* Set selection file path */
  5575. if (!cfg.picker) {
  5576. /* Length of "/.config/nnn/.selection" */
  5577. selpath = (char *)malloc(len + 3);
  5578. if (!selpath) {
  5579. xerror();
  5580. return FALSE;
  5581. }
  5582. r = xstrsncpy(selpath, cfgdir, len + 3);
  5583. xstrsncpy(selpath + r - 1, "/.selection", 12);
  5584. DPRINTF_S(selpath);
  5585. }
  5586. return TRUE;
  5587. }
  5588. static bool set_tmp_path(void)
  5589. {
  5590. char *tmp = "/tmp";
  5591. char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
  5592. if (!path) {
  5593. fprintf(stderr, "set TMPDIR\n");
  5594. return FALSE;
  5595. }
  5596. tmpfplen = (uchar)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
  5597. return TRUE;
  5598. }
  5599. static void cleanup(void)
  5600. {
  5601. free(selpath);
  5602. free(plugindir);
  5603. free(sessiondir);
  5604. free(cfgdir);
  5605. free(initpath);
  5606. free(bmstr);
  5607. free(pluginstr);
  5608. free(prefixpath);
  5609. free(ihashbmp);
  5610. free(bookmark);
  5611. free(plug);
  5612. unlink(g_pipepath);
  5613. #ifdef DBGMODE
  5614. disabledbg();
  5615. #endif
  5616. }
  5617. int main(int argc, char *argv[])
  5618. {
  5619. char *arg = NULL;
  5620. char *session = NULL;
  5621. int opt, sort = 0;
  5622. #ifndef NOMOUSE
  5623. mmask_t mask;
  5624. char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
  5625. if (middle_click_env[0] == '^' && middle_click_env[1])
  5626. middle_click_key = CONTROL(middle_click_env[1]);
  5627. else
  5628. middle_click_key = (uchar)middle_click_env[0];
  5629. #endif
  5630. const char* const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
  5631. int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
  5632. #ifndef NORL
  5633. bool rlhist = FALSE;
  5634. #endif
  5635. while ((opt = (env_opts_id > 0
  5636. ? env_opts[--env_opts_id]
  5637. : getopt(argc, argv, "Ab:cdeEfFgHKnop:QrRs:St:T:Vxh"))) != -1) {
  5638. switch (opt) {
  5639. case 'A':
  5640. cfg.autoselect = 0;
  5641. break;
  5642. case 'b':
  5643. arg = optarg;
  5644. break;
  5645. case 'c':
  5646. cfg.cliopener = 1;
  5647. break;
  5648. case 'S':
  5649. cfg.blkorder = 1;
  5650. nftw_fn = sum_bsize;
  5651. blk_shift = ffs(S_BLKSIZE) - 1; // fallthrough
  5652. case 'd':
  5653. cfg.showdetail = 1;
  5654. printptr = &printent_long;
  5655. break;
  5656. case 'e':
  5657. cfg.useeditor = 1;
  5658. break;
  5659. case 'E':
  5660. cfg.waitedit = 1;
  5661. break;
  5662. case 'f':
  5663. #ifndef NORL
  5664. rlhist = TRUE;
  5665. #endif
  5666. break;
  5667. case 'F':
  5668. g_states |= STATE_FORTUNE;
  5669. break;
  5670. case 'g':
  5671. cfg.regex = 1;
  5672. filterfn = &visible_re;
  5673. break;
  5674. case 'H':
  5675. cfg.showhidden = 1;
  5676. break;
  5677. case 'K':
  5678. check_key_collision();
  5679. return _SUCCESS;
  5680. case 'n':
  5681. cfg.filtermode = 1;
  5682. break;
  5683. case 'o':
  5684. cfg.nonavopen = 1;
  5685. break;
  5686. case 'p':
  5687. if (env_opts_id >= 0)
  5688. break;
  5689. cfg.picker = 1;
  5690. if (optarg[0] == '-' && optarg[1] == '\0')
  5691. cfg.pickraw = 1;
  5692. else {
  5693. int fd = open(optarg, O_WRONLY | O_CREAT, 0600);
  5694. if (fd == -1) {
  5695. xerror();
  5696. return _FAILURE;
  5697. }
  5698. close(fd);
  5699. selpath = realpath(optarg, NULL);
  5700. unlink(selpath);
  5701. }
  5702. break;
  5703. case 'Q':
  5704. g_states |= STATE_FORCEQUIT;
  5705. break;
  5706. case 'r':
  5707. #ifdef __linux__
  5708. cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
  5709. cp[4] = mv[4] = '-';
  5710. #endif
  5711. break;
  5712. case 'R':
  5713. cfg.rollover = 0;
  5714. break;
  5715. case 's':
  5716. if (env_opts_id < 0)
  5717. session = optarg;
  5718. break;
  5719. case 't':
  5720. if (env_opts_id < 0)
  5721. idletimeout = atoi(optarg);
  5722. break;
  5723. case 'T':
  5724. if (env_opts_id < 0)
  5725. sort = (uchar)optarg[0];
  5726. break;
  5727. case 'V':
  5728. fprintf(stdout, "%s\n", VERSION);
  5729. return _SUCCESS;
  5730. case 'x':
  5731. cfg.x11 = 1;
  5732. break;
  5733. case 'h':
  5734. usage();
  5735. return _SUCCESS;
  5736. default:
  5737. usage();
  5738. return _FAILURE;
  5739. }
  5740. }
  5741. #ifdef DBGMODE
  5742. enabledbg();
  5743. DPRINTF_S(VERSION);
  5744. #endif
  5745. /* Prefix for temporary files */
  5746. if (!set_tmp_path())
  5747. return _FAILURE;
  5748. atexit(cleanup);
  5749. if (!cfg.picker) {
  5750. /* Confirm we are in a terminal */
  5751. if (!isatty(STDOUT_FILENO))
  5752. exit(1);
  5753. /* Now we are in path list mode */
  5754. if (!isatty(STDIN_FILENO)) {
  5755. /* This is the same as listpath */
  5756. initpath = load_input();
  5757. if (!initpath)
  5758. exit(1);
  5759. /* We return to tty */
  5760. dup2(STDOUT_FILENO, STDIN_FILENO);
  5761. }
  5762. }
  5763. home = getenv("HOME");
  5764. if (!home) {
  5765. fprintf(stderr, "set HOME\n");
  5766. return _FAILURE;
  5767. }
  5768. DPRINTF_S(home);
  5769. if (!setup_config())
  5770. return _FAILURE;
  5771. /* Get custom opener, if set */
  5772. opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
  5773. DPRINTF_S(opener);
  5774. /* Parse bookmarks string */
  5775. if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
  5776. fprintf(stderr, "%s\n", env_cfg[NNN_BMS]);
  5777. return _FAILURE;
  5778. }
  5779. /* Parse plugins string */
  5780. if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
  5781. fprintf(stderr, "%s\n", env_cfg[NNN_PLUG]);
  5782. return _FAILURE;
  5783. }
  5784. if (!initpath) {
  5785. if (arg) { /* Open a bookmark directly */
  5786. if (!arg[1]) /* Bookmarks keys are single char */
  5787. initpath = get_kv_val(bookmark, NULL, *arg, maxbm, TRUE);
  5788. if (!initpath) {
  5789. fprintf(stderr, "%s\n", messages[MSG_INVALID_KEY]);
  5790. return _FAILURE;
  5791. }
  5792. } else if (argc == optind) {
  5793. /* Start in the current directory */
  5794. initpath = getcwd(NULL, PATH_MAX);
  5795. if (!initpath)
  5796. initpath = "/";
  5797. } else {
  5798. arg = argv[optind];
  5799. DPRINTF_S(arg);
  5800. if (xstrlen(arg) > 7 && !strncmp(arg, "file://", 7))
  5801. arg = arg + 7;
  5802. initpath = realpath(arg, NULL);
  5803. DPRINTF_S(initpath);
  5804. if (!initpath) {
  5805. xerror();
  5806. return _FAILURE;
  5807. }
  5808. /*
  5809. * If nnn is set as the file manager, applications may try to open
  5810. * files by invoking nnn. In that case pass the file path to the
  5811. * desktop opener and exit.
  5812. */
  5813. struct stat sb;
  5814. if (stat(initpath, &sb) == -1) {
  5815. xerror();
  5816. return _FAILURE;
  5817. }
  5818. if (S_ISREG(sb.st_mode)) {
  5819. spawn(opener, arg, NULL, NULL, cfg.cliopener ? F_CLI : F_NOTRACE | F_NOWAIT);
  5820. return _SUCCESS;
  5821. }
  5822. }
  5823. }
  5824. /* Set archive handling (enveditor used as tmp var) */
  5825. enveditor = getenv(env_cfg[NNN_ARCHIVE]);
  5826. #ifdef PCRE
  5827. if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5828. #else
  5829. if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5830. #endif
  5831. fprintf(stderr, "%s\n", messages[MSG_INVALID_REG]);
  5832. return _FAILURE;
  5833. }
  5834. /* An all-CLI opener overrides option -e) */
  5835. if (cfg.cliopener)
  5836. cfg.useeditor = 0;
  5837. /* Get VISUAL/EDITOR */
  5838. enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
  5839. editor = xgetenv(envs[ENV_VISUAL], enveditor);
  5840. DPRINTF_S(getenv(envs[ENV_VISUAL]));
  5841. DPRINTF_S(getenv(envs[ENV_EDITOR]));
  5842. DPRINTF_S(editor);
  5843. /* Get PAGER */
  5844. pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
  5845. DPRINTF_S(pager);
  5846. /* Get SHELL */
  5847. shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
  5848. DPRINTF_S(shell);
  5849. DPRINTF_S(getenv("PWD"));
  5850. #ifdef LINUX_INOTIFY
  5851. /* Initialize inotify */
  5852. inotify_fd = inotify_init1(IN_NONBLOCK);
  5853. if (inotify_fd < 0) {
  5854. xerror();
  5855. return _FAILURE;
  5856. }
  5857. #elif defined(BSD_KQUEUE)
  5858. kq = kqueue();
  5859. if (kq < 0) {
  5860. xerror();
  5861. return _FAILURE;
  5862. }
  5863. #elif defined(HAIKU_NM)
  5864. haiku_hnd = haiku_init_nm();
  5865. if (!haiku_hnd) {
  5866. xerror();
  5867. return _FAILURE;
  5868. }
  5869. #endif
  5870. /* Configure trash preference */
  5871. if (xgetenv_set(env_cfg[NNN_TRASH]))
  5872. g_states |= STATE_TRASH;
  5873. /* Ignore/handle certain signals */
  5874. struct sigaction act = {.sa_handler = sigint_handler};
  5875. if (sigaction(SIGINT, &act, NULL) < 0) {
  5876. xerror();
  5877. return _FAILURE;
  5878. }
  5879. signal(SIGQUIT, SIG_IGN);
  5880. #ifndef NOLOCALE
  5881. /* Set locale */
  5882. setlocale(LC_ALL, "");
  5883. #ifdef PCRE
  5884. tables = pcre_maketables();
  5885. #endif
  5886. #endif
  5887. #ifndef NORL
  5888. #if RL_READLINE_VERSION >= 0x0603
  5889. /* readline would overwrite the WINCH signal hook */
  5890. rl_change_environment = 0;
  5891. #endif
  5892. /* Bind TAB to cycling */
  5893. rl_variable_bind("completion-ignore-case", "on");
  5894. #ifdef __linux__
  5895. rl_bind_key('\t', rl_menu_complete);
  5896. #else
  5897. rl_bind_key('\t', rl_complete);
  5898. #endif
  5899. if (rlhist) {
  5900. mkpath(cfgdir, ".history", g_buf);
  5901. read_history(g_buf);
  5902. }
  5903. #endif
  5904. #ifndef NOMOUSE
  5905. if (!initcurses(&mask))
  5906. #else
  5907. if (!initcurses(NULL))
  5908. #endif
  5909. return _FAILURE;
  5910. if (sort)
  5911. set_sort_flags(sort);
  5912. opt = browse(initpath, session);
  5913. #ifndef NOMOUSE
  5914. mousemask(mask, NULL);
  5915. #endif
  5916. if (listpath)
  5917. spawn("rm -rf", initpath, NULL, NULL, F_SILENT);
  5918. exitcurses();
  5919. #ifndef NORL
  5920. if (rlhist) {
  5921. mkpath(cfgdir, ".history", g_buf);
  5922. write_history(g_buf);
  5923. }
  5924. #endif
  5925. if (cfg.pickraw) {
  5926. if (selbufpos && (seltofile(1, NULL) != (size_t)(selbufpos)))
  5927. xerror();
  5928. } else if (cfg.picker) {
  5929. if (selbufpos)
  5930. writesel(pselbuf, selbufpos - 1);
  5931. } else if (selpath)
  5932. unlink(selpath);
  5933. /* Free the regex */
  5934. #ifdef PCRE
  5935. pcre_free(archive_pcre);
  5936. #else
  5937. regfree(&archive_re);
  5938. #endif
  5939. /* Free the selection buffer */
  5940. free(pselbuf);
  5941. #ifdef LINUX_INOTIFY
  5942. /* Shutdown inotify */
  5943. if (inotify_wd >= 0)
  5944. inotify_rm_watch(inotify_fd, inotify_wd);
  5945. close(inotify_fd);
  5946. #elif defined(BSD_KQUEUE)
  5947. if (event_fd >= 0)
  5948. close(event_fd);
  5949. close(kq);
  5950. #elif defined(HAIKU_NM)
  5951. haiku_close_nm(haiku_hnd);
  5952. #endif
  5953. return opt;
  5954. }