My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

7040 líneas
153 KiB

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