My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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