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

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