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

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