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

7060 rindas
154 KiB

  1. /*
  2. * BSD 2-Clause License
  3. *
  4. * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
  5. * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
  6. * Copyright (C) 2016-2020, Arun Prakash Jana <engineerarun@gmail.com>
  7. * All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions are met:
  11. *
  12. * * Redistributions of source code must retain the above copyright notice, this
  13. * list of conditions and the following disclaimer.
  14. *
  15. * * Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  23. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  26. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  27. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #ifdef __linux__
  31. #ifndef _GNU_SOURCE
  32. #define _GNU_SOURCE
  33. #endif
  34. #if defined(__arm__) || defined(__i386__)
  35. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
  36. #endif
  37. #include <sys/inotify.h>
  38. #define LINUX_INOTIFY
  39. #if !defined(__GLIBC__)
  40. #include <sys/types.h>
  41. #endif
  42. #endif
  43. #include <sys/resource.h>
  44. #include <sys/stat.h>
  45. #include <sys/statvfs.h>
  46. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  47. #include <sys/types.h>
  48. #include <sys/event.h>
  49. #include <sys/time.h>
  50. #define BSD_KQUEUE
  51. #elif defined(__HAIKU__)
  52. #include "../misc/haiku/haiku_interop.h"
  53. #define HAIKU_NM
  54. #else
  55. #include <sys/sysmacros.h>
  56. #endif
  57. #include <sys/wait.h>
  58. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  59. #ifndef NCURSES_WIDECHAR
  60. #define NCURSES_WIDECHAR 1
  61. #endif
  62. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(__sun)
  63. #ifndef _XOPEN_SOURCE_EXTENDED
  64. #define _XOPEN_SOURCE_EXTENDED
  65. #endif
  66. #endif
  67. #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  68. #define __USE_XOPEN
  69. #endif
  70. #include <dirent.h>
  71. #include <errno.h>
  72. #include <fcntl.h>
  73. #include <libgen.h>
  74. #include <limits.h>
  75. #ifndef NOLOCALE
  76. #include <locale.h>
  77. #endif
  78. #include <stdio.h>
  79. #ifndef NORL
  80. #include <readline/history.h>
  81. #include <readline/readline.h>
  82. #endif
  83. #ifdef PCRE
  84. #include <pcre.h>
  85. #else
  86. #include <regex.h>
  87. #endif
  88. #include <signal.h>
  89. #include <stdarg.h>
  90. #include <stdlib.h>
  91. #ifdef __sun
  92. #include <alloca.h>
  93. #endif
  94. #include <string.h>
  95. #include <strings.h>
  96. #include <time.h>
  97. #include <unistd.h>
  98. #ifndef __USE_XOPEN_EXTENDED
  99. #define __USE_XOPEN_EXTENDED 1
  100. #endif
  101. #include <ftw.h>
  102. #include <wchar.h>
  103. #include "nnn.h"
  104. #include "dbg.h"
  105. /* Macro definitions */
  106. #define VERSION "3.1"
  107. #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
  108. #define SESSIONS_VERSION 1
  109. #ifndef S_BLKSIZE
  110. #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
  111. #endif
  112. /*
  113. * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
  114. * flexible array on Illumos. Use somewhat accomodating fallback values.
  115. */
  116. #ifndef NAME_MAX
  117. #define NAME_MAX 255
  118. #endif
  119. #ifndef PATH_MAX
  120. #define PATH_MAX 4096
  121. #endif
  122. #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
  123. #define DOUBLECLICK_INTERVAL_NS (400000000)
  124. #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
  125. #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
  126. #undef MIN
  127. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  128. #undef MAX
  129. #define MAX(x, y) ((x) > (y) ? (x) : (y))
  130. #define ISODD(x) ((x) & 1)
  131. #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
  132. #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  133. #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
  134. #define READLINE_MAX 256
  135. #define FILTER '/'
  136. #define RFILTER '\\'
  137. #define CASE ':'
  138. #define MSGWAIT '$'
  139. #define SELECT ' '
  140. #define REGEX_MAX 48
  141. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  142. #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per filename = 64*32B = 2KB */
  143. #define DESCRIPTOR_LEN 32
  144. #define _ALIGNMENT 0x10 /* 16-byte alignment */
  145. #define _ALIGNMENT_MASK 0xF
  146. #define TMP_LEN_MAX 64
  147. #define CTX_MAX 4
  148. #define DOT_FILTER_LEN 7
  149. #define ASCII_MAX 128
  150. #define EXEC_ARGS_MAX 8
  151. #define LIST_FILES_MAX (1 << 16)
  152. #define SCROLLOFF 3
  153. #define MIN_DISPLAY_COLS 10
  154. #define LONG_SIZE sizeof(ulong)
  155. #define ARCHIVE_CMD_LEN 16
  156. #define BLK_SHIFT_512 9
  157. /* Detect hardlinks in du */
  158. #define HASH_BITS (0xFFFFFF)
  159. #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
  160. /* Program return codes */
  161. #define _SUCCESS 0
  162. #define _FAILURE !_SUCCESS
  163. /* Entry flags */
  164. #define DIR_OR_LINK_TO_DIR 0x01
  165. #define HARD_LINK 0x02
  166. #define FILE_SELECTED 0x10
  167. /* Macros to define process spawn behaviour as flags */
  168. #define F_NONE 0x00 /* no flag set */
  169. #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
  170. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  171. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  172. #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
  173. #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
  174. #define F_CLI (F_NORMAL | F_MULTI)
  175. #define F_SILENT (F_CLI | F_NOTRACE)
  176. /* Version compare macros */
  177. /*
  178. * states: S_N: normal, S_I: comparing integral part, S_F: comparing
  179. * fractional parts, S_Z: idem but with leading Zeroes only
  180. */
  181. #define S_N 0x0
  182. #define S_I 0x3
  183. #define S_F 0x6
  184. #define S_Z 0x9
  185. /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
  186. #define VCMP 2
  187. #define VLEN 3
  188. /* Volume info */
  189. #define FREE 0
  190. #define CAPACITY 1
  191. /* TYPE DEFINITIONS */
  192. typedef unsigned long ulong;
  193. typedef unsigned int uint;
  194. typedef unsigned char uchar;
  195. typedef unsigned short ushort;
  196. typedef long long ll;
  197. typedef unsigned long long ull;
  198. /* STRUCTURES */
  199. /* Directory entry */
  200. typedef struct entry {
  201. char *name;
  202. time_t t;
  203. off_t size;
  204. blkcnt_t blocks; /* number of 512B blocks allocated */
  205. mode_t mode;
  206. ushort nlen; /* Length of file name */
  207. uchar flags; /* Flags specific to the file */
  208. } *pEntry;
  209. /* Key-value pairs from env */
  210. typedef struct {
  211. int key;
  212. char *val;
  213. } kv;
  214. typedef struct {
  215. #ifdef PCRE
  216. const pcre *pcrex;
  217. #else
  218. const regex_t *regex;
  219. #endif
  220. const char *str;
  221. } fltrexp_t;
  222. /*
  223. * Settings
  224. * NOTE: update default values if changing order
  225. */
  226. typedef struct {
  227. uint filtermode : 1; /* Set to enter filter mode */
  228. uint timeorder : 1; /* Set to sort by time */
  229. uint sizeorder : 1; /* Set to sort by file size */
  230. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  231. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  232. uint extnorder : 1; /* Order by extension */
  233. uint showhidden : 1; /* Set to show hidden files */
  234. uint selmode : 1; /* Set when selecting files */
  235. uint showdetail : 1; /* Clear to show fewer file info */
  236. uint ctxactive : 1; /* Context active or not */
  237. uint reserved1 : 3;
  238. /* The following settings are global */
  239. uint curctx : 2; /* Current context number */
  240. uint dircolor : 1; /* Current status of dir color */
  241. uint picker : 1; /* Write selection to user-specified file */
  242. uint pickraw : 1; /* Write selection to sdtout before exit */
  243. uint nonavopen : 1; /* Open file on right arrow or `l` */
  244. uint autoselect : 1; /* Auto-select dir in type-to-nav mode */
  245. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  246. uint useeditor : 1; /* Use VISUAL to open text files */
  247. uint runplugin : 1; /* Choose plugin mode */
  248. uint runctx : 2; /* The context in which plugin is to be run */
  249. uint regex : 1; /* Use regex filters */
  250. uint x11 : 1; /* Copy to system clipboard and show notis */
  251. uint timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
  252. uint cliopener : 1; /* All-CLI app opener */
  253. uint waitedit : 1; /* For ops that can't be detached, used EDITOR */
  254. uint rollover : 1; /* Roll over at edges */
  255. } settings;
  256. /* Contexts or workspaces */
  257. typedef struct {
  258. char c_path[PATH_MAX]; /* Current dir */
  259. char c_last[PATH_MAX]; /* Last visited dir */
  260. char c_name[NAME_MAX + 1]; /* Current file name */
  261. char c_fltr[REGEX_MAX]; /* Current filter */
  262. settings c_cfg; /* Current configuration */
  263. uint color; /* Color code for directories */
  264. } context;
  265. typedef struct {
  266. size_t ver;
  267. size_t pathln[CTX_MAX];
  268. size_t lastln[CTX_MAX];
  269. size_t nameln[CTX_MAX];
  270. size_t fltrln[CTX_MAX];
  271. } session_header_t;
  272. /* GLOBALS */
  273. /* Configuration, contexts */
  274. static settings cfg = {
  275. 0, /* filtermode */
  276. 0, /* timeorder */
  277. 0, /* sizeorder */
  278. 0, /* apparentsz */
  279. 0, /* blkorder */
  280. 0, /* extnorder */
  281. 0, /* showhidden */
  282. 0, /* selmode */
  283. 0, /* showdetail */
  284. 1, /* ctxactive */
  285. 0, /* reserved1 */
  286. 0, /* curctx */
  287. 0, /* dircolor */
  288. 0, /* picker */
  289. 0, /* pickraw */
  290. 0, /* nonavopen */
  291. 1, /* autoselect */
  292. 0, /* metaviewer */
  293. 0, /* useeditor */
  294. 0, /* runplugin */
  295. 0, /* runctx */
  296. 0, /* regex */
  297. 0, /* x11 */
  298. 2, /* timetype (T_MOD) */
  299. 0, /* cliopener */
  300. 0, /* waitedit */
  301. 1, /* rollover */
  302. };
  303. static context g_ctx[CTX_MAX] __attribute__ ((aligned));
  304. static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR;
  305. static int nselected;
  306. static uint idletimeout, selbufpos, lastappendpos, selbuflen;
  307. static ushort xlines, xcols;
  308. static ushort idle;
  309. static uchar maxbm, maxplug;
  310. static char *bmstr;
  311. static char *pluginstr;
  312. static char *opener;
  313. static char *editor;
  314. static char *enveditor;
  315. static char *pager;
  316. static char *shell;
  317. static char *home;
  318. static char *initpath;
  319. static char *cfgdir;
  320. static char *selpath;
  321. static char *listpath;
  322. static char *prefixpath;
  323. static char *plugindir;
  324. static char *sessiondir;
  325. static char *pnamebuf, *pselbuf;
  326. static ull *ihashbmp;
  327. static struct entry *dents;
  328. static blkcnt_t ent_blocks;
  329. static blkcnt_t dir_blocks;
  330. static ulong num_files;
  331. static kv *bookmark;
  332. static kv *plug;
  333. static uchar tmpfplen;
  334. static uchar blk_shift = BLK_SHIFT_512;
  335. #ifndef NOMOUSE
  336. static int middle_click_key;
  337. #endif
  338. #ifdef PCRE
  339. static pcre *archive_pcre;
  340. #else
  341. static regex_t archive_re;
  342. #endif
  343. /* Retain old signal handlers */
  344. #ifdef __linux__
  345. static sighandler_t oldsighup; /* old value of hangup signal */
  346. static sighandler_t oldsigtstp; /* old value of SIGTSTP */
  347. #else
  348. /* note: no sig_t on Solaris-derivs */
  349. static void (*oldsighup)(int);
  350. static void (*oldsigtstp)(int);
  351. #endif
  352. /* For use in functions which are isolated and don't return the buffer */
  353. static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
  354. /* Buffer to store tmp file path to show selection, file stats and help */
  355. static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
  356. /* Buffer to store plugins control pipe location */
  357. static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
  358. /* MISC NON-PERSISTENT INTERNAL BINARY STATES */
  359. /* Plugin control initialization status */
  360. #define STATE_PLUGIN_INIT 0x1
  361. #define STATE_INTERRUPTED 0x2
  362. #define STATE_RANGESEL 0x4
  363. #define STATE_MOVE_OP 0x8
  364. #define STATE_AUTONEXT 0x10
  365. #define STATE_MSG 0x20
  366. #define STATE_TRASH 0x40
  367. #define STATE_FORCEQUIT 0x80
  368. #define STATE_FORTUNE 0x100
  369. static uint g_states;
  370. /* Options to identify file mime */
  371. #if defined(__APPLE__)
  372. #define FILE_MIME_OPTS "-bIL"
  373. #elif !defined(__sun) /* no mime option for 'file' */
  374. #define FILE_MIME_OPTS "-biL"
  375. #endif
  376. /* Macros for utilities */
  377. #define UTIL_OPENER 0
  378. #define UTIL_ATOOL 1
  379. #define UTIL_BSDTAR 2
  380. #define UTIL_UNZIP 3
  381. #define UTIL_TAR 4
  382. #define UTIL_LOCKER 5
  383. #define UTIL_CMATRIX 6
  384. #define UTIL_LAUNCH 7
  385. #define UTIL_SH_EXEC 8
  386. #define UTIL_ARCHIVEMOUNT 9
  387. #define UTIL_SSHFS 10
  388. #define UTIL_RCLONE 11
  389. #define UTIL_VI 12
  390. #define UTIL_LESS 13
  391. #define UTIL_SH 14
  392. #define UTIL_FZF 15
  393. #define UTIL_FZY 16
  394. #define UTIL_NTFY 17
  395. #define UTIL_CBCP 18
  396. #define UTIL_BASH 19
  397. #define UTIL_NMV 20
  398. /* Utilities to open files, run actions */
  399. static char * const utils[] = {
  400. #ifdef __APPLE__
  401. "/usr/bin/open",
  402. #elif defined __CYGWIN__
  403. "cygstart",
  404. #elif defined __HAIKU__
  405. "open",
  406. #else
  407. "xdg-open",
  408. #endif
  409. "atool",
  410. "bsdtar",
  411. "unzip",
  412. "tar",
  413. #ifdef __APPLE__
  414. "bashlock",
  415. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  416. "lock",
  417. #elif defined __HAIKU__
  418. "peaclock",
  419. #else
  420. "vlock",
  421. #endif
  422. "cmatrix",
  423. "launch",
  424. "sh -c",
  425. "archivemount",
  426. "sshfs",
  427. "rclone",
  428. "vi",
  429. "less",
  430. "sh",
  431. "fzf",
  432. "fzy",
  433. ".ntfy",
  434. ".cbcp",
  435. "bash",
  436. ".nmv",
  437. };
  438. /* Common strings */
  439. #define MSG_NO_TRAVERSAL 0
  440. #define MSG_INVALID_KEY 1
  441. #define STR_TMPFILE 2
  442. #define MSG_0_SELECTED 3
  443. #define MSG_UTIL_MISSING 4
  444. #define MSG_FAILED 5
  445. #define MSG_SSN_NAME 6
  446. #define MSG_CP_MV_AS 7
  447. #define MSG_CUR_SEL_OPTS 8
  448. #define MSG_FORCE_RM 9
  449. #define MSG_LIMIT 10
  450. #define MSG_NEW_OPTS 11
  451. #define MSG_CLI_MODE 12
  452. #define MSG_OVERWRITE 13
  453. #define MSG_SSN_OPTS 14
  454. #define MSG_QUIT_ALL 15
  455. #define MSG_HOSTNAME 16
  456. #define MSG_ARCHIVE_NAME 17
  457. #define MSG_OPEN_WITH 18
  458. #define MSG_REL_PATH 19
  459. #define MSG_LINK_PREFIX 20
  460. #define MSG_COPY_NAME 21
  461. #define MSG_CONTINUE 22
  462. #define MSG_SEL_MISSING 23
  463. #define MSG_ACCESS 24
  464. #define MSG_EMPTY_FILE 25
  465. #define MSG_UNSUPPORTED 26
  466. #define MSG_NOT_SET 27
  467. #define MSG_EXISTS 28
  468. #define MSG_FEW_COLUMNS 29
  469. #define MSG_REMOTE_OPTS 30
  470. #define MSG_RCLONE_DELAY 31
  471. #define MSG_APP_NAME 32
  472. #define MSG_ARCHIVE_OPTS 33
  473. #define MSG_PLUGIN_KEYS 34
  474. #define MSG_BOOKMARK_KEYS 35
  475. #define MSG_INVALID_REG 36
  476. #define MSG_ORDER 37
  477. #define MSG_LAZY 38
  478. #define MSG_IGNORED 39
  479. #define MSG_RM_TMP 40
  480. #define MSG_NOCHNAGE 41
  481. #define MSG_CANCEL 42
  482. #ifndef DIR_LIMITED_SELECTION
  483. #define MSG_DIR_CHANGED 43 /* Must be the last entry */
  484. #endif
  485. static const char * const messages[] = {
  486. "no traversal",
  487. "invalid key",
  488. "/.nnnXXXXXX",
  489. "0 selected",
  490. "missing util",
  491. "failed!",
  492. "session name: ",
  493. "'c'p / 'm'v as?",
  494. "'c'urrent / 's'el?",
  495. "rm -rf %s file%s?",
  496. "limit exceeded\n",
  497. "'f'ile / 'd'ir / 's'ym / 'h'ard?",
  498. "'c'li / 'g'ui?",
  499. "overwrite?",
  500. "'s'ave / 'l'oad / 'r'estore?",
  501. "Quit all contexts?",
  502. "remote name ('-' for hovered): ",
  503. "archive name: ",
  504. "open with: ",
  505. "relative path: ",
  506. "link prefix [@ for none]: ",
  507. "copy name: ",
  508. "\n'Enter' to continue",
  509. "open failed",
  510. "dir inaccessible",
  511. "empty: edit/open with",
  512. "unknown",
  513. "not set",
  514. "entry exists",
  515. "too few columns!",
  516. "'s'shfs / 'r'clone?",
  517. "refresh if slow",
  518. "app name: ",
  519. "'d'efault / e'x'tract / 'l'ist / 'm'ount?",
  520. "plugin keys:",
  521. "bookmark keys:",
  522. "invalid regex",
  523. "'a'u / 'd'u / 'e'xtn / 'r'ev / 's'ize / 't'ime / 'v'er / 'c'lear?",
  524. "unmount failed! try lazy?",
  525. "ignoring invalid paths...",
  526. "remove tmp file?",
  527. "unchanged",
  528. "cancelled",
  529. #ifndef DIR_LIMITED_SELECTION
  530. "dir changed, range sel off", /* Must be the last entry */
  531. #endif
  532. };
  533. /* Supported configuration environment variables */
  534. #define NNN_OPTS 0
  535. #define NNN_BMS 1
  536. #define NNN_PLUG 2
  537. #define NNN_OPENER 3
  538. #define NNN_COLORS 4
  539. #define NNNLVL 5
  540. #define NNN_PIPE 6
  541. #define NNN_MCLICK 7
  542. #define NNN_ARCHIVE 8 /* strings end here */
  543. #define NNN_TRASH 9 /* flags begin here */
  544. static const char * const env_cfg[] = {
  545. "NNN_OPTS",
  546. "NNN_BMS",
  547. "NNN_PLUG",
  548. "NNN_OPENER",
  549. "NNN_COLORS",
  550. "NNNLVL",
  551. "NNN_PIPE",
  552. "NNN_MCLICK",
  553. "NNN_ARCHIVE",
  554. "NNN_TRASH",
  555. };
  556. /* Required environment variables */
  557. #define ENV_SHELL 0
  558. #define ENV_VISUAL 1
  559. #define ENV_EDITOR 2
  560. #define ENV_PAGER 3
  561. #define ENV_NCUR 4
  562. static const char * const envs[] = {
  563. "SHELL",
  564. "VISUAL",
  565. "EDITOR",
  566. "PAGER",
  567. "nnn",
  568. };
  569. /* Time type used */
  570. #define T_ACCESS 0
  571. #define T_CHANGE 1
  572. #define T_MOD 2
  573. #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. uint maxitems = 0, i = 0;
  2483. char *nextkey;
  2484. char *ptr = getenv(env_cfg[id]);
  2485. kv *kvarr;
  2486. if (!ptr || !*ptr)
  2487. return TRUE;
  2488. nextkey = ptr;
  2489. while (*nextkey)
  2490. if (*nextkey++ == ':')
  2491. ++maxitems;
  2492. if (!maxitems || maxitems > 100)
  2493. return FALSE;
  2494. *arr = calloc(maxitems, sizeof(kv));
  2495. if (!arr) {
  2496. xerror();
  2497. return FALSE;
  2498. }
  2499. kvarr = *arr;
  2500. *envcpy = xstrdup(ptr);
  2501. if (!*envcpy) {
  2502. xerror();
  2503. return FALSE;
  2504. }
  2505. /* Clear trailing ;s */
  2506. if (*--nextkey == ';')
  2507. *(*envcpy + (nextkey - ptr)) = '\0';
  2508. ptr = *envcpy;
  2509. nextkey = ptr;
  2510. while (*ptr && i < maxitems) {
  2511. if (ptr == nextkey) {
  2512. kvarr[i].key = (uchar)*ptr;
  2513. if (*++ptr != ':')
  2514. return FALSE;
  2515. if (*++ptr == '\0')
  2516. return FALSE;
  2517. if (*ptr == ';') /* Empty location */
  2518. return FALSE;
  2519. kvarr[i].val = ptr;
  2520. ++i;
  2521. }
  2522. if (*ptr == ';') {
  2523. *ptr = '\0';
  2524. nextkey = ptr + 1;
  2525. }
  2526. ++ptr;
  2527. }
  2528. maxitems = i;
  2529. if (kvarr[i - 1].val && *kvarr[i - 1].val == '\0')
  2530. return FALSE;
  2531. /* Redundant check so far, all paths will get evaluated and fail */
  2532. //for (i = 0; i < maxitems && kvarr[i].key; ++i)
  2533. // if (xstrlen(kvarr[i].val) >= PATH_MAX)
  2534. // return FALSE;
  2535. *items = maxitems;
  2536. return TRUE;
  2537. }
  2538. /*
  2539. * Get the value corresponding to a key
  2540. *
  2541. * NULL is returned in case of no match, path resolution failure etc.
  2542. * buf would be modified, so check return value before access
  2543. */
  2544. static char *get_kv_val(kv *kvarr, char *buf, int key, uchar max, bool bookmark)
  2545. {
  2546. if (!kvarr)
  2547. return NULL;
  2548. for (int r = 0; kvarr[r].key && r < max; ++r) {
  2549. if (kvarr[r].key == key) {
  2550. /* Do not allocate new memory for plugin */
  2551. if (!bookmark)
  2552. return kvarr[r].val;
  2553. if (kvarr[r].val[0] == '~') {
  2554. ssize_t len = xstrlen(home);
  2555. ssize_t loclen = xstrlen(kvarr[r].val);
  2556. xstrsncpy(g_buf, home, len + 1);
  2557. xstrsncpy(g_buf + len, kvarr[r].val + 1, loclen);
  2558. }
  2559. return realpath(((kvarr[r].val[0] == '~') ? g_buf : kvarr[r].val), buf);
  2560. }
  2561. }
  2562. DPRINTF_S("Invalid key");
  2563. return NULL;
  2564. }
  2565. static void resetdircolor(int flags)
  2566. {
  2567. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  2568. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2569. cfg.dircolor = 0;
  2570. }
  2571. }
  2572. /*
  2573. * Replace escape characters in a string with '?'
  2574. * Adjust string length to maxcols if > 0;
  2575. * Max supported str length: NAME_MAX;
  2576. */
  2577. static wchar_t *unescape(const char *str, uint maxcols)
  2578. {
  2579. wchar_t * const wbuf = (wchar_t *)g_buf;
  2580. wchar_t *buf = wbuf;
  2581. size_t lencount = 0;
  2582. #ifdef NOLOCALE
  2583. memset(wbuf, 0, sizeof(NAME_MAX + 1) * sizeof(wchar_t));
  2584. #endif
  2585. /* Convert multi-byte to wide char */
  2586. size_t len = mbstowcs(wbuf, str, NAME_MAX);
  2587. len = wcswidth(wbuf, len);
  2588. /* Reduce number of wide chars to max columns */
  2589. if (len > maxcols) {
  2590. while (*buf && lencount <= maxcols) {
  2591. if (*buf <= '\x1f' || *buf == '\x7f')
  2592. *buf = '\?';
  2593. ++buf;
  2594. ++lencount;
  2595. }
  2596. lencount = maxcols + 1;
  2597. /* Reduce wide chars one by one till it fits */
  2598. do
  2599. len = wcswidth(wbuf, --lencount);
  2600. while (len > maxcols);
  2601. wbuf[lencount] = L'\0';
  2602. } else {
  2603. do /* We do not expect a NULL string */
  2604. if (*buf <= '\x1f' || *buf == '\x7f')
  2605. *buf = '\?';
  2606. while (*++buf);
  2607. }
  2608. return wbuf;
  2609. }
  2610. static char *coolsize(off_t size)
  2611. {
  2612. const char * const U = "BKMGTPEZY";
  2613. static char size_buf[12]; /* Buffer to hold human readable size */
  2614. off_t rem = 0;
  2615. size_t ret;
  2616. int i = 0;
  2617. while (size >= 1024) {
  2618. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  2619. size >>= 10;
  2620. ++i;
  2621. }
  2622. if (i == 1) {
  2623. rem = (rem * 1000) >> 10;
  2624. rem /= 10;
  2625. if (rem % 10 >= 5) {
  2626. rem = (rem / 10) + 1;
  2627. if (rem == 10) {
  2628. ++size;
  2629. rem = 0;
  2630. }
  2631. } else
  2632. rem /= 10;
  2633. } else if (i == 2) {
  2634. rem = (rem * 1000) >> 10;
  2635. if (rem % 10 >= 5) {
  2636. rem = (rem / 10) + 1;
  2637. if (rem == 100) {
  2638. ++size;
  2639. rem = 0;
  2640. }
  2641. } else
  2642. rem /= 10;
  2643. } else if (i > 0) {
  2644. rem = (rem * 10000) >> 10;
  2645. if (rem % 10 >= 5) {
  2646. rem = (rem / 10) + 1;
  2647. if (rem == 1000) {
  2648. ++size;
  2649. rem = 0;
  2650. }
  2651. } else
  2652. rem /= 10;
  2653. }
  2654. if (i > 0 && i < 6 && rem) {
  2655. ret = xstrsncpy(size_buf, xitoa(size), 12);
  2656. size_buf[ret - 1] = '.';
  2657. char *frac = xitoa(rem);
  2658. size_t toprint = i > 3 ? 3 : i;
  2659. size_t len = xstrlen(frac);
  2660. if (len < toprint) {
  2661. size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
  2662. xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
  2663. } else
  2664. xstrsncpy(size_buf + ret, frac, toprint + 1);
  2665. ret += toprint;
  2666. } else {
  2667. ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
  2668. --ret;
  2669. }
  2670. size_buf[ret] = U[i];
  2671. size_buf[ret + 1] = '\0';
  2672. return size_buf;
  2673. }
  2674. static char get_ind(mode_t mode, bool perms)
  2675. {
  2676. switch (mode & S_IFMT) {
  2677. case S_IFREG:
  2678. if (perms)
  2679. return '-';
  2680. if (mode & 0100)
  2681. return '*';
  2682. return '\0';
  2683. case S_IFDIR:
  2684. return perms ? 'd' : '/';
  2685. case S_IFLNK:
  2686. return perms ? 'l' : '@';
  2687. case S_IFSOCK:
  2688. return perms ? 's' : '=';
  2689. case S_IFIFO:
  2690. return perms ? 'p' : '|';
  2691. case S_IFBLK:
  2692. return perms ? 'b' : '\0';
  2693. case S_IFCHR:
  2694. return perms ? 'c' : '\0';
  2695. default:
  2696. return '?';
  2697. }
  2698. }
  2699. /* Convert a mode field into "ls -l" type perms field. */
  2700. static char *get_lsperms(mode_t mode)
  2701. {
  2702. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  2703. static char bits[11] = {'\0'};
  2704. bits[0] = get_ind(mode, TRUE);
  2705. xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  2706. xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  2707. xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
  2708. if (mode & S_ISUID)
  2709. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  2710. if (mode & S_ISGID)
  2711. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  2712. if (mode & S_ISVTX)
  2713. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  2714. return bits;
  2715. }
  2716. static void print_time(const time_t *timep)
  2717. {
  2718. struct tm *t = localtime(timep);
  2719. printw("%d-%02d-%02d %02d:%02d",
  2720. t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min);
  2721. }
  2722. static void printent(const struct entry *ent, uint namecols, bool sel)
  2723. {
  2724. char ind = get_ind(ent->mode, FALSE);
  2725. int attrs = ((ind == '@' || (ent->flags & HARD_LINK)) ? A_DIM : 0) | (sel ? A_REVERSE : 0);
  2726. if (ind == '@' && (ent->flags & DIR_OR_LINK_TO_DIR))
  2727. ind = '/';
  2728. if (!ind)
  2729. ++namecols;
  2730. /* Directories are always shown on top */
  2731. resetdircolor(ent->flags);
  2732. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2733. if (attrs)
  2734. attron(attrs);
  2735. addwstr(unescape(ent->name, namecols));
  2736. if (attrs)
  2737. attroff(attrs);
  2738. if (ind)
  2739. addch(ind);
  2740. addch('\n');
  2741. }
  2742. static void printent_long(const struct entry *ent, uint namecols, bool sel)
  2743. {
  2744. bool ln = FALSE;
  2745. char ind1 = '\0', ind2 = '\0';
  2746. int attrs = sel ? A_REVERSE : 0;
  2747. uint len;
  2748. char *size;
  2749. /* Directories are always shown on top */
  2750. resetdircolor(ent->flags);
  2751. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2752. if (attrs)
  2753. attron(attrs);
  2754. /* Timestamp */
  2755. print_time(&ent->t);
  2756. addstr(" ");
  2757. /* Permissions */
  2758. addch('0' + ((ent->mode >> 6) & 7));
  2759. addch('0' + ((ent->mode >> 3) & 7));
  2760. addch('0' + (ent->mode & 7));
  2761. switch (ent->mode & S_IFMT) {
  2762. case S_IFDIR:
  2763. ind2 = '/'; // fallthrough
  2764. case S_IFREG:
  2765. if (!ind2) {
  2766. if (ent->flags & HARD_LINK)
  2767. ln = TRUE;
  2768. if (ent->mode & 0100)
  2769. ind2 = '*';
  2770. if (!ind2) /* Add a column if end indicator is not needed */
  2771. ++namecols;
  2772. }
  2773. size = coolsize(cfg.blkorder ? ent->blocks << blk_shift : ent->size);
  2774. len = 10 - (uint)xstrlen(size);
  2775. while (--len)
  2776. addch(' ');
  2777. addstr(size);
  2778. break;
  2779. case S_IFLNK:
  2780. ln = TRUE;
  2781. ind1 = '@';
  2782. ind2 = (ent->flags & DIR_OR_LINK_TO_DIR) ? '/' : '@'; // fallthrough
  2783. case S_IFSOCK:
  2784. if (!ind1)
  2785. ind1 = ind2 = '='; // fallthrough
  2786. case S_IFIFO:
  2787. if (!ind1)
  2788. ind1 = ind2 = '|'; // fallthrough
  2789. case S_IFBLK:
  2790. if (!ind1)
  2791. ind1 = 'b'; // fallthrough
  2792. case S_IFCHR:
  2793. if (!ind1)
  2794. ind1 = 'c'; // fallthrough
  2795. default:
  2796. if (!ind1)
  2797. ind1 = ind2 = '?';
  2798. addstr(" ");
  2799. addch(ind1);
  2800. break;
  2801. }
  2802. addstr(" ");
  2803. if (ln) {
  2804. attron(A_DIM);
  2805. attrs |= A_DIM;
  2806. }
  2807. addwstr(unescape(ent->name, namecols));
  2808. if (attrs)
  2809. attroff(attrs);
  2810. if (ind2)
  2811. addch(ind2);
  2812. addch('\n');
  2813. }
  2814. static void (*printptr)(const struct entry *ent, uint namecols, bool sel) = &printent;
  2815. static void savecurctx(settings *curcfg, char *path, char *curname, int r /* next context num */)
  2816. {
  2817. settings cfg = *curcfg;
  2818. context *ctxr = &g_ctx[r];
  2819. bool selmode = cfg.selmode ? TRUE : FALSE;
  2820. /* Save current context */
  2821. xstrsncpy(g_ctx[cfg.curctx].c_name, curname, NAME_MAX + 1);
  2822. g_ctx[cfg.curctx].c_cfg = cfg;
  2823. if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
  2824. /* Switch light/detail mode */
  2825. if (cfg.showdetail != ctxr->c_cfg.showdetail)
  2826. /* set the reverse */
  2827. printptr = cfg.showdetail ? &printent : &printent_long;
  2828. cfg = ctxr->c_cfg;
  2829. } else { /* Setup a new context from current context */
  2830. ctxr->c_cfg.ctxactive = 1;
  2831. xstrsncpy(ctxr->c_path, path, PATH_MAX);
  2832. ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
  2833. ctxr->c_cfg = cfg;
  2834. ctxr->c_cfg.runplugin = 0;
  2835. }
  2836. /* Continue selection mode */
  2837. cfg.selmode = selmode;
  2838. cfg.curctx = r;
  2839. *curcfg = cfg;
  2840. }
  2841. static void save_session(bool last_session, int *presel)
  2842. {
  2843. char spath[PATH_MAX];
  2844. int i;
  2845. session_header_t header;
  2846. FILE *fsession;
  2847. char *sname;
  2848. bool status = FALSE;
  2849. memset(&header, 0, sizeof(session_header_t));
  2850. header.ver = SESSIONS_VERSION;
  2851. for (i = 0; i < CTX_MAX; ++i) {
  2852. if (g_ctx[i].c_cfg.ctxactive) {
  2853. if (cfg.curctx == i && ndents)
  2854. /* Update current file name, arrows don't update it */
  2855. xstrsncpy(g_ctx[i].c_name, dents[cur].name, NAME_MAX + 1);
  2856. header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
  2857. header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
  2858. header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
  2859. header.fltrln[i] = strnlen(g_ctx[i].c_fltr, REGEX_MAX) + 1;
  2860. }
  2861. }
  2862. sname = !last_session ? xreadline(NULL, messages[MSG_SSN_NAME]) : "@";
  2863. if (!sname[0])
  2864. return;
  2865. mkpath(sessiondir, sname, spath);
  2866. fsession = fopen(spath, "wb");
  2867. if (!fsession) {
  2868. printwait(messages[MSG_SEL_MISSING], presel);
  2869. return;
  2870. }
  2871. if ((fwrite(&header, sizeof(header), 1, fsession) != 1)
  2872. || (fwrite(&cfg, sizeof(cfg), 1, fsession) != 1))
  2873. goto END;
  2874. for (i = 0; i < CTX_MAX; ++i)
  2875. if ((fwrite(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2876. || (fwrite(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2877. || (header.nameln[i] > 0
  2878. && fwrite(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2879. || (header.lastln[i] > 0
  2880. && fwrite(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2881. || (header.fltrln[i] > 0
  2882. && fwrite(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2883. || (header.pathln[i] > 0
  2884. && fwrite(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2885. goto END;
  2886. status = TRUE;
  2887. END:
  2888. fclose(fsession);
  2889. if (!status)
  2890. printwait(messages[MSG_FAILED], presel);
  2891. }
  2892. static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
  2893. {
  2894. char spath[PATH_MAX];
  2895. int i = 0;
  2896. session_header_t header;
  2897. FILE *fsession;
  2898. bool has_loaded_dynamically = !(sname || restore);
  2899. bool status = FALSE;
  2900. if (!restore) {
  2901. sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
  2902. if (!sname[0])
  2903. return FALSE;
  2904. mkpath(sessiondir, sname, spath);
  2905. } else
  2906. mkpath(sessiondir, "@", spath);
  2907. if (has_loaded_dynamically)
  2908. save_session(TRUE, NULL);
  2909. fsession = fopen(spath, "rb");
  2910. if (!fsession) {
  2911. printmsg(messages[MSG_SEL_MISSING]);
  2912. xdelay(XDELAY_INTERVAL_MS);
  2913. return FALSE;
  2914. }
  2915. if ((fread(&header, sizeof(header), 1, fsession) != 1)
  2916. || (header.ver != SESSIONS_VERSION)
  2917. || (fread(&cfg, sizeof(cfg), 1, fsession) != 1))
  2918. goto END;
  2919. g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
  2920. = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  2921. for (; i < CTX_MAX; ++i)
  2922. if ((fread(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2923. || (fread(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2924. || (header.nameln[i] > 0
  2925. && fread(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2926. || (header.lastln[i] > 0
  2927. && fread(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2928. || (header.fltrln[i] > 0
  2929. && fread(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2930. || (header.pathln[i] > 0
  2931. && fread(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2932. goto END;
  2933. *path = g_ctx[cfg.curctx].c_path;
  2934. *lastdir = g_ctx[cfg.curctx].c_last;
  2935. *lastname = g_ctx[cfg.curctx].c_name;
  2936. printptr = cfg.showdetail ? &printent_long : &printent;
  2937. status = TRUE;
  2938. END:
  2939. fclose(fsession);
  2940. if (!status) {
  2941. printmsg(messages[MSG_FAILED]);
  2942. xdelay(XDELAY_INTERVAL_MS);
  2943. } else if (restore)
  2944. unlink(spath);
  2945. return status;
  2946. }
  2947. /*
  2948. * Gets only a single line (that's what we need
  2949. * for now) or shows full command output in pager.
  2950. *
  2951. * If page is valid, returns NULL
  2952. */
  2953. static char *get_output(char *buf, const size_t bytes, const char *file,
  2954. const char *arg1, const char *arg2, const bool page)
  2955. {
  2956. pid_t pid;
  2957. int pipefd[2];
  2958. FILE *pf;
  2959. int tmp, flags;
  2960. char *ret = NULL;
  2961. if (pipe(pipefd) == -1)
  2962. errexit();
  2963. for (tmp = 0; tmp < 2; ++tmp) {
  2964. /* Get previous flags */
  2965. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  2966. /* Set bit for non-blocking flag */
  2967. flags |= O_NONBLOCK;
  2968. /* Change flags on fd */
  2969. fcntl(pipefd[tmp], F_SETFL, flags);
  2970. }
  2971. pid = fork();
  2972. if (pid == 0) {
  2973. /* In child */
  2974. close(pipefd[0]);
  2975. dup2(pipefd[1], STDOUT_FILENO);
  2976. dup2(pipefd[1], STDERR_FILENO);
  2977. close(pipefd[1]);
  2978. execlp(file, file, arg1, arg2, NULL);
  2979. _exit(1);
  2980. }
  2981. /* In parent */
  2982. waitpid(pid, &tmp, 0);
  2983. close(pipefd[1]);
  2984. if (!page) {
  2985. pf = fdopen(pipefd[0], "r");
  2986. if (pf) {
  2987. ret = fgets(buf, bytes, pf);
  2988. close(pipefd[0]);
  2989. }
  2990. return ret;
  2991. }
  2992. pid = fork();
  2993. if (pid == 0) {
  2994. /* Show in pager in child */
  2995. dup2(pipefd[0], STDIN_FILENO);
  2996. close(pipefd[0]);
  2997. spawn(pager, NULL, NULL, NULL, F_CLI);
  2998. _exit(1);
  2999. }
  3000. /* In parent */
  3001. waitpid(pid, &tmp, 0);
  3002. close(pipefd[0]);
  3003. return NULL;
  3004. }
  3005. static inline bool getutil(char *util)
  3006. {
  3007. return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
  3008. }
  3009. static void pipetof(char *cmd, FILE *fout)
  3010. {
  3011. FILE *fin = popen(cmd, "r");
  3012. if (fin) {
  3013. while (fgets(g_buf, CMD_LEN_MAX - 1, fin))
  3014. fprintf(fout, "%s", g_buf);
  3015. pclose(fin);
  3016. }
  3017. }
  3018. /*
  3019. * Follows the stat(1) output closely
  3020. */
  3021. static bool show_stats(const char *fpath, const struct stat *sb)
  3022. {
  3023. int fd;
  3024. FILE *fp;
  3025. char *p, *begin = g_buf;
  3026. size_t r;
  3027. fd = create_tmp_file();
  3028. if (fd == -1)
  3029. return FALSE;
  3030. r = xstrsncpy(g_buf, "stat \"", PATH_MAX);
  3031. r += xstrsncpy(g_buf + r - 1, fpath, PATH_MAX);
  3032. g_buf[r - 2] = '\"';
  3033. g_buf[r - 1] = '\0';
  3034. DPRINTF_S(g_buf);
  3035. fp = fdopen(fd, "w");
  3036. if (!fp) {
  3037. close(fd);
  3038. return FALSE;
  3039. }
  3040. pipetof(g_buf, fp);
  3041. if (S_ISREG(sb->st_mode)) {
  3042. /* Show file(1) output */
  3043. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  3044. if (p) {
  3045. fprintf(fp, "\n\n ");
  3046. while (*p) {
  3047. if (*p == ',') {
  3048. *p = '\0';
  3049. fprintf(fp, " %s\n", begin);
  3050. begin = p + 1;
  3051. }
  3052. ++p;
  3053. }
  3054. fprintf(fp, " %s\n ", begin);
  3055. /* Show the file mime type */
  3056. get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, fpath, FALSE);
  3057. fprintf(fp, "%s", g_buf);
  3058. }
  3059. }
  3060. fprintf(fp, "\n");
  3061. fclose(fp);
  3062. close(fd);
  3063. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3064. unlink(g_tmpfpath);
  3065. return TRUE;
  3066. }
  3067. static bool xchmod(const char *fpath, mode_t mode)
  3068. {
  3069. /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
  3070. (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
  3071. return (chmod(fpath, mode) == 0);
  3072. }
  3073. static size_t get_fs_info(const char *path, bool type)
  3074. {
  3075. struct statvfs svb;
  3076. if (statvfs(path, &svb) == -1)
  3077. return 0;
  3078. if (type == CAPACITY)
  3079. return svb.f_blocks << ffs((int)(svb.f_frsize >> 1));
  3080. return svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
  3081. }
  3082. /* List or extract archive */
  3083. static void handle_archive(char *fpath, const char *dir, char op)
  3084. {
  3085. char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
  3086. char *util;
  3087. if (getutil(utils[UTIL_ATOOL])) {
  3088. util = utils[UTIL_ATOOL];
  3089. arg[1] = op;
  3090. arg[2] = '\0';
  3091. } else if (getutil(utils[UTIL_BSDTAR])) {
  3092. util = utils[UTIL_BSDTAR];
  3093. if (op == 'x')
  3094. arg[1] = op;
  3095. } else if (is_suffix(fpath, ".zip")) {
  3096. util = utils[UTIL_UNZIP];
  3097. arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
  3098. arg[2] = '\0';
  3099. } else {
  3100. util = utils[UTIL_TAR];
  3101. if (op == 'x')
  3102. arg[1] = op;
  3103. }
  3104. if (op == 'x') /* extract */
  3105. spawn(util, arg, fpath, dir, F_NORMAL);
  3106. else /* list */
  3107. get_output(NULL, 0, util, arg, fpath, TRUE);
  3108. }
  3109. static char *visit_parent(char *path, char *newpath, int *presel)
  3110. {
  3111. char *dir;
  3112. /* There is no going back */
  3113. if (istopdir(path)) {
  3114. /* Continue in type-to-nav mode, if enabled */
  3115. if (cfg.filtermode && presel)
  3116. *presel = FILTER;
  3117. return NULL;
  3118. }
  3119. /* Use a copy as xdirname() may change the string passed */
  3120. if (newpath)
  3121. xstrsncpy(newpath, path, PATH_MAX);
  3122. else
  3123. newpath = path;
  3124. dir = xdirname(newpath);
  3125. if (access(dir, R_OK) == -1) {
  3126. printwarn(presel);
  3127. return NULL;
  3128. }
  3129. return dir;
  3130. }
  3131. static void valid_parent(char *path, char *lastname)
  3132. {
  3133. /* Save history */
  3134. xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
  3135. while (!istopdir(path))
  3136. if (visit_parent(path, NULL, NULL))
  3137. break;
  3138. printwarn(NULL);
  3139. xdelay(XDELAY_INTERVAL_MS);
  3140. }
  3141. /* Create non-existent parents and a file or dir */
  3142. static bool xmktree(char *path, bool dir)
  3143. {
  3144. char *p = path;
  3145. char *slash = path;
  3146. if (!p || !*p)
  3147. return FALSE;
  3148. /* Skip the first '/' */
  3149. ++p;
  3150. while (*p != '\0') {
  3151. if (*p == '/') {
  3152. slash = p;
  3153. *p = '\0';
  3154. } else {
  3155. ++p;
  3156. continue;
  3157. }
  3158. /* Create folder from path to '\0' inserted at p */
  3159. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3160. #ifdef __HAIKU__
  3161. // XDG_CONFIG_HOME contains a directory
  3162. // that is read-only, but the full path
  3163. // is writeable.
  3164. // Try to continue and see what happens.
  3165. // TODO: Find a more robust solution.
  3166. if (errno == B_READ_ONLY_DEVICE)
  3167. goto next;
  3168. #endif
  3169. DPRINTF_S("mkdir1!");
  3170. DPRINTF_S(strerror(errno));
  3171. *slash = '/';
  3172. return FALSE;
  3173. }
  3174. #ifdef __HAIKU__
  3175. next:
  3176. #endif
  3177. /* Restore path */
  3178. *slash = '/';
  3179. ++p;
  3180. }
  3181. if (dir) {
  3182. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3183. DPRINTF_S("mkdir2!");
  3184. DPRINTF_S(strerror(errno));
  3185. return FALSE;
  3186. }
  3187. } else {
  3188. int fd = open(path, O_CREAT, 0666);
  3189. if (fd == -1 && errno != EEXIST) {
  3190. DPRINTF_S("open!");
  3191. DPRINTF_S(strerror(errno));
  3192. return FALSE;
  3193. }
  3194. close(fd);
  3195. }
  3196. return TRUE;
  3197. }
  3198. static bool archive_mount(char *path, char *newpath)
  3199. {
  3200. char *dir, *cmd = utils[UTIL_ARCHIVEMOUNT];
  3201. char *name = dents[cur].name;
  3202. size_t len = dents[cur].nlen;
  3203. if (!getutil(cmd)) {
  3204. printmsg(messages[MSG_UTIL_MISSING]);
  3205. return FALSE;
  3206. }
  3207. dir = xstrdup(name);
  3208. if (!dir) {
  3209. printmsg(messages[MSG_FAILED]);
  3210. return FALSE;
  3211. }
  3212. while (len > 1)
  3213. if (dir[--len] == '.') {
  3214. dir[len] = '\0';
  3215. break;
  3216. }
  3217. DPRINTF_S(dir);
  3218. /* Create the mount point */
  3219. mkpath(cfgdir, dir, newpath);
  3220. free(dir);
  3221. if (!xmktree(newpath, TRUE)) {
  3222. printwarn(NULL);
  3223. return FALSE;
  3224. }
  3225. /* Mount archive */
  3226. DPRINTF_S(name);
  3227. DPRINTF_S(newpath);
  3228. if (spawn(cmd, name, newpath, path, F_NORMAL)) {
  3229. printmsg(messages[MSG_FAILED]);
  3230. return FALSE;
  3231. }
  3232. return TRUE;
  3233. }
  3234. static bool remote_mount(char *newpath, char *currentpath)
  3235. {
  3236. uchar flag = F_CLI;
  3237. int opt;
  3238. char *tmp, *env;
  3239. bool r, s;
  3240. r = getutil(utils[UTIL_RCLONE]);
  3241. s = getutil(utils[UTIL_SSHFS]);
  3242. if (!(r || s)) {
  3243. printmsg(messages[MSG_UTIL_MISSING]);
  3244. return FALSE;
  3245. }
  3246. if (r && s)
  3247. opt = get_input(messages[MSG_REMOTE_OPTS]);
  3248. else
  3249. opt = (!s) ? 'r' : 's';
  3250. if (opt == 's')
  3251. env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
  3252. else if (opt == 'r') {
  3253. flag |= F_NOWAIT | F_NOTRACE;
  3254. env = xgetenv("NNN_RCLONE", "rclone mount");
  3255. } else {
  3256. printmsg(messages[MSG_INVALID_KEY]);
  3257. return FALSE;
  3258. }
  3259. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3260. if (!tmp[0]) {
  3261. printmsg(messages[MSG_CANCEL]);
  3262. return FALSE;
  3263. }
  3264. if (tmp[0] == '-' && !tmp[1]) {
  3265. if (!strcmp(cfgdir, currentpath) && ndents && (dents[cur].flags & DIR_OR_LINK_TO_DIR))
  3266. xstrsncpy(tmp, dents[cur].name, NAME_MAX + 1);
  3267. else {
  3268. printmsg(messages[MSG_FAILED]);
  3269. return FALSE;
  3270. }
  3271. }
  3272. /* Create the mount point */
  3273. mkpath(cfgdir, tmp, newpath);
  3274. if (!xmktree(newpath, TRUE)) {
  3275. printwarn(NULL);
  3276. return FALSE;
  3277. }
  3278. /* Convert "Host" to "Host:" */
  3279. size_t len = xstrlen(tmp);
  3280. if (tmp[len - 1] != ':') { /* Append ':' if missing */
  3281. tmp[len] = ':';
  3282. tmp[len + 1] = '\0';
  3283. }
  3284. /* Connect to remote */
  3285. if (opt == 's') {
  3286. if (spawn(env, tmp, newpath, NULL, flag)) {
  3287. printmsg(messages[MSG_FAILED]);
  3288. return FALSE;
  3289. }
  3290. } else {
  3291. spawn(env, tmp, newpath, NULL, flag);
  3292. printmsg(messages[MSG_RCLONE_DELAY]);
  3293. xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
  3294. }
  3295. return TRUE;
  3296. }
  3297. /*
  3298. * Unmounts if the directory represented by name is a mount point.
  3299. * Otherwise, asks for hostname
  3300. */
  3301. static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
  3302. {
  3303. #ifdef __APPLE__
  3304. static char cmd[] = "umount";
  3305. #else
  3306. static char cmd[] = "fusermount3"; /* Arch Linux utility */
  3307. static bool found = FALSE;
  3308. #endif
  3309. char *tmp = name;
  3310. struct stat sb, psb;
  3311. bool child = FALSE;
  3312. bool parent = FALSE;
  3313. #ifndef __APPLE__
  3314. /* On Ubuntu it's fusermount */
  3315. if (!found && !getutil(cmd)) {
  3316. cmd[10] = '\0';
  3317. found = TRUE;
  3318. }
  3319. #endif
  3320. if (tmp && strcmp(cfgdir, currentpath) == 0) {
  3321. mkpath(cfgdir, tmp, newpath);
  3322. child = lstat(newpath, &sb) != -1;
  3323. parent = lstat(xdirname(newpath), &psb) != -1;
  3324. if (!child && !parent) {
  3325. *presel = MSGWAIT;
  3326. return FALSE;
  3327. }
  3328. }
  3329. if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
  3330. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3331. if (!tmp[0])
  3332. return FALSE;
  3333. }
  3334. /* Create the mount point */
  3335. mkpath(cfgdir, tmp, newpath);
  3336. if (!xdiraccess(newpath)) {
  3337. *presel = MSGWAIT;
  3338. return FALSE;
  3339. }
  3340. #ifdef __APPLE__
  3341. if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
  3342. #else
  3343. if (spawn(cmd, "-u", newpath, NULL, F_NORMAL)) {
  3344. #endif
  3345. if (!xconfirm(get_input(messages[MSG_LAZY])))
  3346. return FALSE;
  3347. #ifdef __APPLE__
  3348. if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
  3349. #else
  3350. if (spawn(cmd, "-uz", newpath, NULL, F_NORMAL)) {
  3351. #endif
  3352. printwait(messages[MSG_FAILED], presel);
  3353. return FALSE;
  3354. }
  3355. }
  3356. return TRUE;
  3357. }
  3358. static void lock_terminal(void)
  3359. {
  3360. char *tmp = utils[UTIL_LOCKER];
  3361. if (!getutil(tmp))
  3362. tmp = utils[UTIL_CMATRIX];
  3363. spawn(tmp, NULL, NULL, NULL, F_NORMAL);
  3364. }
  3365. static void printkv(kv *kvarr, FILE *fp, uchar max)
  3366. {
  3367. for (uchar i = 0; i < max && kvarr[i].key; ++i)
  3368. fprintf(fp, " %c: %s\n", (char)kvarr[i].key, kvarr[i].val);
  3369. }
  3370. static void printkeys(kv *kvarr, char *buf, uchar max)
  3371. {
  3372. uchar i = 0;
  3373. for (; i < max && kvarr[i].key; ++i) {
  3374. buf[i << 1] = ' ';
  3375. buf[(i << 1) + 1] = kvarr[i].key;
  3376. }
  3377. buf[i << 1] = '\0';
  3378. }
  3379. static size_t handle_bookmark(const char *mark, char *newpath)
  3380. {
  3381. int fd;
  3382. size_t r = xstrsncpy(g_buf, messages[MSG_BOOKMARK_KEYS], CMD_LEN_MAX);
  3383. if (mark) { /* There is a pinned directory */
  3384. g_buf[--r] = ' ';
  3385. g_buf[++r] = ',';
  3386. g_buf[++r] = '\0';
  3387. ++r;
  3388. }
  3389. printkeys(bookmark, g_buf + r - 1, maxbm);
  3390. printmsg(g_buf);
  3391. r = FALSE;
  3392. fd = get_input(NULL);
  3393. if (fd == ',') /* Visit pinned directory */
  3394. mark ? xstrsncpy(newpath, mark, PATH_MAX) : (r = MSG_NOT_SET);
  3395. else if (!get_kv_val(bookmark, newpath, fd, maxbm, TRUE))
  3396. r = MSG_INVALID_KEY;
  3397. if (!r && !xdiraccess(newpath))
  3398. r = MSG_ACCESS;
  3399. return r;
  3400. }
  3401. /*
  3402. * The help string tokens (each line) start with a HEX value
  3403. * which indicates the number of spaces to print before the
  3404. * particular token. This method was chosen instead of a flat
  3405. * string because the number of bytes in help was increasing
  3406. * the binary size by around a hundred bytes. This would only
  3407. * have increased as we keep adding new options.
  3408. */
  3409. static void show_help(const char *path)
  3410. {
  3411. int fd;
  3412. FILE *fp;
  3413. const char *start, *end;
  3414. const char helpstr[] = {
  3415. "0\n"
  3416. "1NAVIGATION\n"
  3417. "9Up k Up%-16cPgUp ^U Scroll up\n"
  3418. "9Dn j Down%-14cPgDn ^D Scroll down\n"
  3419. "9Lt h Parent%-12c~ ` @ - HOME, /, start, last\n"
  3420. "5Ret Rt l Open%-20c' First file\n"
  3421. "9g ^A Top%-18c. F5 Toggle hidden\n"
  3422. "9G ^E End%-21c0 Lock terminal\n"
  3423. "9b ^/ Bookmark key%-12c, Pin CWD\n"
  3424. "a1-4 Context 1-4%-7c(Sh)Tab Cycle context\n"
  3425. "c/ Filter%-17c^N Toggle type-to-nav\n"
  3426. "aEsc Exit prompt%-12c^L Redraw/clear prompt\n"
  3427. "c? Help, conf%-14c+ Toggle auto-advance\n"
  3428. "cq Quit context%-11c^G QuitCD\n"
  3429. "b^Q Quit%-20cQ Quit with err\n"
  3430. "1FILES\n"
  3431. "9o ^O Open with...%-12cn Create new/link\n"
  3432. "9f ^F File details%-12cd Detail mode toggle\n"
  3433. "b^R Rename/dup%-14cr Batch rename\n"
  3434. "cz Archive%-17ce Edit in EDITOR\n"
  3435. "5Space ^J (Un)select%-11cm ^K Mark range/clear\n"
  3436. "9p ^P Copy sel here%-11ca Select all\n"
  3437. "9v ^V Move sel here%-8cw ^W Cp/mv sel as\n"
  3438. "9x ^X Delete%-18cE Edit sel\n"
  3439. "c* Toggle exe%-14c> Export list\n"
  3440. "1MISC\n"
  3441. "9; ^S Select plugin%-11c= Launch app\n"
  3442. "9! ^] Shell%-19c] Cmd prompt\n"
  3443. "cc Connect remote%-10cu Unmount\n"
  3444. "9t ^T Sort toggles%-12cs Manage session\n"
  3445. "cT Set time type%-0c\n"
  3446. };
  3447. fd = create_tmp_file();
  3448. if (fd == -1)
  3449. return;
  3450. fp = fdopen(fd, "w");
  3451. if (!fp) {
  3452. close(fd);
  3453. return;
  3454. }
  3455. if ((g_states & STATE_FORTUNE) && getutil("fortune"))
  3456. pipetof("fortune -s", fp);
  3457. start = end = helpstr;
  3458. while (*end) {
  3459. if (*end == '\n') {
  3460. snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
  3461. xchartohex(*start), ' ', (int)(end - start), start + 1);
  3462. fprintf(fp, g_buf, ' ');
  3463. start = end + 1;
  3464. }
  3465. ++end;
  3466. }
  3467. fprintf(fp, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  3468. fprintf(fp, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  3469. if (bookmark) {
  3470. fprintf(fp, "BOOKMARKS\n");
  3471. printkv(bookmark, fp, maxbm);
  3472. fprintf(fp, "\n");
  3473. }
  3474. if (plug) {
  3475. fprintf(fp, "PLUGIN KEYS\n");
  3476. printkv(plug, fp, maxplug);
  3477. fprintf(fp, "\n");
  3478. }
  3479. for (uchar i = NNN_OPENER; i <= NNN_TRASH; ++i) {
  3480. start = getenv(env_cfg[i]);
  3481. if (start)
  3482. fprintf(fp, "%s: %s\n", env_cfg[i], start);
  3483. }
  3484. if (selpath)
  3485. fprintf(fp, "SELECTION FILE: %s\n", selpath);
  3486. fprintf(fp, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  3487. fclose(fp);
  3488. close(fd);
  3489. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3490. unlink(g_tmpfpath);
  3491. }
  3492. static bool run_cmd_as_plugin(const char *path, const char *file, char *runfile)
  3493. {
  3494. uchar flags = F_CLI | F_CONFIRM;
  3495. size_t len;
  3496. /* Get rid of preceding _ */
  3497. ++file;
  3498. if (!*file)
  3499. return FALSE;
  3500. /* Check if GUI flags are to be used */
  3501. if (*file == '|') {
  3502. flags = F_NOTRACE | F_NOWAIT;
  3503. ++file;
  3504. if (!*file)
  3505. return FALSE;
  3506. }
  3507. xstrsncpy(g_buf, file, PATH_MAX);
  3508. len = xstrlen(g_buf);
  3509. if (len > 1 && g_buf[len - 1] == '*') {
  3510. flags &= ~F_CONFIRM; /* Skip user confirmation */
  3511. g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
  3512. --len;
  3513. }
  3514. if (is_suffix(g_buf, " $nnn"))
  3515. g_buf[len - 5] = '\0'; /* Set `\0` to clear ' $nnn' suffix */
  3516. else
  3517. runfile = NULL;
  3518. spawn(g_buf, runfile, NULL, path, flags);
  3519. return TRUE;
  3520. }
  3521. static bool plctrl_init(void)
  3522. {
  3523. snprintf(g_buf, CMD_LEN_MAX, "nnn-pipe.%d", getpid());
  3524. /* g_tmpfpath is used to generate tmp file names */
  3525. g_tmpfpath[tmpfplen - 1] = '\0';
  3526. mkpath(g_tmpfpath, g_buf, g_pipepath);
  3527. unlink(g_pipepath);
  3528. if (mkfifo(g_pipepath, 0600) != 0)
  3529. return _FAILURE;
  3530. setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
  3531. return _SUCCESS;
  3532. }
  3533. static bool run_selected_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
  3534. {
  3535. int fd;
  3536. size_t len;
  3537. if (*file == '_')
  3538. return run_cmd_as_plugin(*path, file, runfile);
  3539. if (!(g_states & STATE_PLUGIN_INIT)) {
  3540. plctrl_init();
  3541. g_states |= STATE_PLUGIN_INIT;
  3542. }
  3543. fd = open(g_pipepath, O_RDONLY | O_NONBLOCK);
  3544. if (fd == -1)
  3545. return FALSE;
  3546. /* Generate absolute path to plugin */
  3547. mkpath(plugindir, file, g_buf);
  3548. if (runfile && runfile[0]) {
  3549. xstrsncpy(*lastname, runfile, NAME_MAX);
  3550. spawn(g_buf, *lastname, *path, *path, F_NORMAL);
  3551. } else
  3552. spawn(g_buf, NULL, *path, *path, F_NORMAL);
  3553. len = read(fd, g_buf, PATH_MAX);
  3554. g_buf[len] = '\0';
  3555. close(fd);
  3556. if (len > 1) {
  3557. int ctx = g_buf[0] - '0';
  3558. if (ctx == 0 || ctx == cfg.curctx + 1) {
  3559. xstrsncpy(*lastdir, *path, PATH_MAX);
  3560. xstrsncpy(*path, g_buf + 1, PATH_MAX);
  3561. } else if (ctx >= 1 && ctx <= CTX_MAX) {
  3562. int r = ctx - 1;
  3563. g_ctx[r].c_cfg.ctxactive = 0;
  3564. savecurctx(&cfg, g_buf + 1, dents[cur].name, r);
  3565. *path = g_ctx[r].c_path;
  3566. *lastdir = g_ctx[r].c_last;
  3567. *lastname = g_ctx[r].c_name;
  3568. }
  3569. }
  3570. return TRUE;
  3571. }
  3572. static bool plugscript(const char *plugin, const char *path, uchar flags)
  3573. {
  3574. mkpath(plugindir, plugin, g_buf);
  3575. if (!access(g_buf, X_OK)) {
  3576. spawn(g_buf, NULL, NULL, path, flags);
  3577. return TRUE;
  3578. }
  3579. return FALSE;
  3580. }
  3581. static void launch_app(const char *path, char *newpath)
  3582. {
  3583. int r = F_NORMAL;
  3584. char *tmp = newpath;
  3585. mkpath(plugindir, utils[UTIL_LAUNCH], newpath);
  3586. if (!(getutil(utils[UTIL_FZF]) || getutil(utils[UTIL_FZY])) || access(newpath, X_OK) < 0) {
  3587. tmp = xreadline(NULL, messages[MSG_APP_NAME]);
  3588. r = F_NOWAIT | F_NOTRACE | F_MULTI;
  3589. }
  3590. if (tmp && *tmp) // NOLINT
  3591. spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, path, r);
  3592. }
  3593. static int sum_bsize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3594. {
  3595. if (sb->st_blocks
  3596. && ((typeflag == FTW_F && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))
  3597. || typeflag == FTW_D))
  3598. ent_blocks += sb->st_blocks;
  3599. ++num_files;
  3600. return 0;
  3601. }
  3602. static int sum_asize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3603. {
  3604. if (sb->st_size
  3605. && ((typeflag == FTW_F && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))
  3606. || typeflag == FTW_D))
  3607. ent_blocks += sb->st_size;
  3608. ++num_files;
  3609. return 0;
  3610. }
  3611. static void dentfree(void)
  3612. {
  3613. free(pnamebuf);
  3614. free(dents);
  3615. }
  3616. static blkcnt_t dirwalk(char *path, struct stat *psb)
  3617. {
  3618. static uint open_max;
  3619. /* Increase current open file descriptor limit */
  3620. if (!open_max)
  3621. open_max = max_openfds();
  3622. ent_blocks = 0;
  3623. tolastln();
  3624. addstr(xbasename(path));
  3625. addstr(" [^C aborts]\n");
  3626. refresh();
  3627. if (nftw(path, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) < 0) {
  3628. DPRINTF_S("nftw failed");
  3629. return cfg.apparentsz ? psb->st_size : psb->st_blocks;
  3630. }
  3631. return ent_blocks;
  3632. }
  3633. /* Skip self and parent */
  3634. static bool selforparent(const char *path)
  3635. {
  3636. return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
  3637. }
  3638. static int dentfill(char *path, struct entry **dents)
  3639. {
  3640. int n = 0, flags = 0;
  3641. ulong num_saved;
  3642. struct dirent *dp;
  3643. char *namep, *pnb, *buf = NULL;
  3644. struct entry *dentp;
  3645. size_t off = 0, namebuflen = NAMEBUF_INCR;
  3646. struct stat sb_path, sb;
  3647. DIR *dirp = opendir(path);
  3648. DPRINTF_S(__FUNCTION__);
  3649. if (!dirp)
  3650. return 0;
  3651. int fd = dirfd(dirp);
  3652. if (cfg.blkorder) {
  3653. num_files = 0;
  3654. dir_blocks = 0;
  3655. buf = (char *)alloca(xstrlen(path) + NAME_MAX + 2);
  3656. if (!buf)
  3657. return 0;
  3658. if (fstatat(fd, path, &sb_path, 0) == -1)
  3659. goto exit;
  3660. if (!ihashbmp) {
  3661. ihashbmp = calloc(1, HASH_OCTETS << 3);
  3662. if (!ihashbmp)
  3663. goto exit;
  3664. } else
  3665. memset(ihashbmp, 0, HASH_OCTETS << 3);
  3666. attron(COLOR_PAIR(cfg.curctx + 1));
  3667. }
  3668. #if _POSIX_C_SOURCE >= 200112L
  3669. posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
  3670. #endif
  3671. dp = readdir(dirp);
  3672. if (!dp)
  3673. goto exit;
  3674. #if defined(__sun) || defined(__HAIKU__)
  3675. flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
  3676. #else
  3677. if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
  3678. /*
  3679. * Optimization added for filesystems which support dirent.d_type
  3680. * see readdir(3)
  3681. * Known drawbacks:
  3682. * - the symlink size is set to 0
  3683. * - the modification time of the symlink is set to that of the target file
  3684. */
  3685. flags = AT_SYMLINK_NOFOLLOW;
  3686. }
  3687. #endif
  3688. do {
  3689. namep = dp->d_name;
  3690. if (selforparent(namep))
  3691. continue;
  3692. if (!cfg.showhidden && namep[0] == '.') {
  3693. if (!cfg.blkorder)
  3694. continue;
  3695. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  3696. continue;
  3697. if (S_ISDIR(sb.st_mode)) {
  3698. if (sb_path.st_dev == sb.st_dev) { // NOLINT
  3699. mkpath(path, namep, buf);
  3700. dir_blocks += dirwalk(buf, &sb);
  3701. if (g_states & STATE_INTERRUPTED)
  3702. goto exit;
  3703. }
  3704. } else {
  3705. /* Do not recount hard links */
  3706. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3707. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3708. ++num_files;
  3709. }
  3710. continue;
  3711. }
  3712. if (fstatat(fd, namep, &sb, flags) == -1) {
  3713. /* List a symlink with target missing */
  3714. if (flags || (!flags && fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
  3715. DPRINTF_U(flags);
  3716. if (!flags) {
  3717. DPRINTF_S(namep);
  3718. DPRINTF_S(strerror(errno));
  3719. }
  3720. memset(&sb, 0, sizeof(struct stat));
  3721. }
  3722. }
  3723. if (n == total_dents) {
  3724. total_dents += ENTRY_INCR;
  3725. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  3726. if (!*dents) {
  3727. free(pnamebuf);
  3728. closedir(dirp);
  3729. errexit();
  3730. }
  3731. DPRINTF_P(*dents);
  3732. }
  3733. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  3734. if (namebuflen - off < NAME_MAX + 1) {
  3735. namebuflen += NAMEBUF_INCR;
  3736. pnb = pnamebuf;
  3737. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  3738. if (!pnamebuf) {
  3739. free(*dents);
  3740. closedir(dirp);
  3741. errexit();
  3742. }
  3743. DPRINTF_P(pnamebuf);
  3744. /* realloc() may result in memory move, we must re-adjust if that happens */
  3745. if (pnb != pnamebuf) {
  3746. dentp = *dents;
  3747. dentp->name = pnamebuf;
  3748. for (int count = 1; count < n; ++dentp, ++count)
  3749. /* Current filename starts at last filename start + length */
  3750. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  3751. }
  3752. }
  3753. dentp = *dents + n;
  3754. /* Selection file name */
  3755. dentp->name = (char *)((size_t)pnamebuf + off);
  3756. dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
  3757. off += dentp->nlen;
  3758. /* Copy other fields */
  3759. dentp->t = ((cfg.timetype == T_MOD)
  3760. ? sb.st_mtime
  3761. : ((cfg.timetype == T_ACCESS) ? sb.st_atime : sb.st_ctime));
  3762. #if !(defined(__sun) || defined(__HAIKU__))
  3763. if (!flags && dp->d_type == DT_LNK) {
  3764. /* Do not add sizes for links */
  3765. dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
  3766. dentp->size = listpath ? sb.st_size : 0;
  3767. } else {
  3768. dentp->mode = sb.st_mode;
  3769. dentp->size = sb.st_size;
  3770. }
  3771. #else
  3772. dentp->mode = sb.st_mode;
  3773. dentp->size = sb.st_size;
  3774. #endif
  3775. dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
  3776. if (cfg.blkorder) {
  3777. if (S_ISDIR(sb.st_mode)) {
  3778. num_saved = num_files + 1;
  3779. mkpath(path, namep, buf);
  3780. /* Need to show the disk usage of this dir */
  3781. dentp->blocks = dirwalk(buf, &sb);
  3782. if (sb_path.st_dev == sb.st_dev) // NOLINT
  3783. dir_blocks += dentp->blocks;
  3784. else
  3785. num_files = num_saved;
  3786. if (g_states & STATE_INTERRUPTED)
  3787. goto exit;
  3788. } else {
  3789. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3790. /* Do not recount hard links */
  3791. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3792. dir_blocks += dentp->blocks;
  3793. ++num_files;
  3794. }
  3795. }
  3796. if (flags) {
  3797. /* Flag if this is a dir or symlink to a dir */
  3798. if (S_ISLNK(sb.st_mode)) {
  3799. sb.st_mode = 0;
  3800. fstatat(fd, namep, &sb, 0);
  3801. }
  3802. if (S_ISDIR(sb.st_mode))
  3803. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3804. #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
  3805. } else if (dp->d_type == DT_DIR || (dp->d_type == DT_LNK && S_ISDIR(sb.st_mode))) {
  3806. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3807. #endif
  3808. }
  3809. ++n;
  3810. } while ((dp = readdir(dirp)));
  3811. exit:
  3812. if (cfg.blkorder)
  3813. attroff(COLOR_PAIR(cfg.curctx + 1));
  3814. /* Should never be null */
  3815. if (closedir(dirp) == -1)
  3816. errexit();
  3817. return n;
  3818. }
  3819. /*
  3820. * Return the position of the matching entry or 0 otherwise
  3821. * Note there's no NULL check for fname
  3822. */
  3823. static int dentfind(const char *fname, int n)
  3824. {
  3825. for (int i = 0; i < n; ++i)
  3826. if (xstrcmp(fname, dents[i].name) == 0)
  3827. return i;
  3828. return 0;
  3829. }
  3830. static void populate(char *path, char *lastname)
  3831. {
  3832. #ifdef DBGMODE
  3833. struct timespec ts1, ts2;
  3834. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  3835. #endif
  3836. ndents = dentfill(path, &dents);
  3837. if (!ndents)
  3838. return;
  3839. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  3840. #ifdef DBGMODE
  3841. clock_gettime(CLOCK_REALTIME, &ts2);
  3842. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  3843. #endif
  3844. /* Find cur from history */
  3845. /* No NULL check for lastname, always points to an array */
  3846. move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
  3847. // Force full redraw
  3848. last_curscroll = -1;
  3849. }
  3850. static void move_cursor(int target, int ignore_scrolloff)
  3851. {
  3852. int delta, scrolloff, onscreen = xlines - 4;
  3853. last_curscroll = curscroll;
  3854. target = MAX(0, MIN(ndents - 1, target));
  3855. delta = target - cur;
  3856. last = cur;
  3857. cur = target;
  3858. if (!ignore_scrolloff) {
  3859. scrolloff = MIN(SCROLLOFF, onscreen >> 1);
  3860. /*
  3861. * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
  3862. * margin area, but when ignore_scrolloff is 0, act like a boa
  3863. * constrictor and squeeze the cursor towards the middle region of the
  3864. * screen by allowing it to move inward and disallowing it to move
  3865. * outward (deeper into the scrolloff margin area).
  3866. */
  3867. if (((cur < (curscroll + scrolloff)) && delta < 0)
  3868. || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
  3869. curscroll += delta;
  3870. }
  3871. curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
  3872. curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
  3873. }
  3874. static void handle_screen_move(enum action sel)
  3875. {
  3876. int onscreen;
  3877. switch (sel) {
  3878. case SEL_NEXT:
  3879. if (ndents && (cfg.rollover || (cur != ndents - 1)))
  3880. move_cursor((cur + 1) % ndents, 0);
  3881. break;
  3882. case SEL_PREV:
  3883. if (ndents && (cfg.rollover || cur))
  3884. move_cursor((cur + ndents - 1) % ndents, 0);
  3885. break;
  3886. case SEL_PGDN:
  3887. onscreen = xlines - 4;
  3888. move_cursor(curscroll + (onscreen - 1), 1);
  3889. curscroll += onscreen - 1;
  3890. break;
  3891. case SEL_CTRL_D:
  3892. onscreen = xlines - 4;
  3893. move_cursor(curscroll + (onscreen - 1), 1);
  3894. curscroll += onscreen >> 1;
  3895. break;
  3896. case SEL_PGUP: // fallthrough
  3897. onscreen = xlines - 4;
  3898. move_cursor(curscroll, 1);
  3899. curscroll -= onscreen - 1;
  3900. break;
  3901. case SEL_CTRL_U:
  3902. onscreen = xlines - 4;
  3903. move_cursor(curscroll, 1);
  3904. curscroll -= onscreen >> 1;
  3905. break;
  3906. case SEL_HOME:
  3907. move_cursor(0, 1);
  3908. break;
  3909. case SEL_END:
  3910. move_cursor(ndents - 1, 1);
  3911. break;
  3912. default: /* case SEL_FIRST */
  3913. {
  3914. for (int r = 0; r < ndents; ++r) {
  3915. if (!(dents[r].flags & DIR_OR_LINK_TO_DIR)) {
  3916. move_cursor((r) % ndents, 0);
  3917. break;
  3918. }
  3919. }
  3920. break;
  3921. }
  3922. }
  3923. }
  3924. static int handle_context_switch(enum action sel)
  3925. {
  3926. int r = -1;
  3927. switch (sel) {
  3928. case SEL_CYCLE: // fallthrough
  3929. case SEL_CYCLER:
  3930. /* visit next and previous contexts */
  3931. r = cfg.curctx;
  3932. if (sel == SEL_CYCLE)
  3933. do
  3934. r = (r + 1) & ~CTX_MAX;
  3935. while (!g_ctx[r].c_cfg.ctxactive);
  3936. else
  3937. do
  3938. r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
  3939. while (!g_ctx[r].c_cfg.ctxactive);
  3940. // fallthrough
  3941. default: /* SEL_CTXN */
  3942. if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
  3943. r = sel - SEL_CTX1; /* Save the next context id */
  3944. if (cfg.curctx == r) {
  3945. if (sel == SEL_CYCLE)
  3946. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3947. else if (sel == SEL_CYCLER)
  3948. (r == 0) ? (r = CTX_MAX - 1) : --r;
  3949. else
  3950. return -1;
  3951. }
  3952. if (cfg.selmode)
  3953. lastappendpos = selbufpos;
  3954. }
  3955. return r;
  3956. }
  3957. static int set_sort_flags(int r)
  3958. {
  3959. switch (r) {
  3960. case 'a': /* Apparent du */
  3961. cfg.apparentsz ^= 1;
  3962. if (cfg.apparentsz) {
  3963. nftw_fn = &sum_asize;
  3964. cfg.blkorder = 1;
  3965. blk_shift = 0;
  3966. } else
  3967. cfg.blkorder = 0;
  3968. // fallthrough
  3969. case 'd': /* Disk usage */
  3970. if (r == 'd') {
  3971. if (!cfg.apparentsz)
  3972. cfg.blkorder ^= 1;
  3973. nftw_fn = &sum_bsize;
  3974. cfg.apparentsz = 0;
  3975. blk_shift = ffs(S_BLKSIZE) - 1;
  3976. }
  3977. if (cfg.blkorder) {
  3978. cfg.showdetail = 1;
  3979. printptr = &printent_long;
  3980. }
  3981. cfg.timeorder = 0;
  3982. cfg.sizeorder = 0;
  3983. cfg.extnorder = 0;
  3984. entrycmpfn = &entrycmp;
  3985. endselection(); /* We are going to reload dir */
  3986. break;
  3987. case 'c':
  3988. cfg.timeorder = 0;
  3989. cfg.sizeorder = 0;
  3990. cfg.apparentsz = 0;
  3991. cfg.blkorder = 0;
  3992. cfg.extnorder = 0;
  3993. entrycmpfn = &entrycmp;
  3994. namecmpfn = &xstricmp;
  3995. break;
  3996. case 'e': /* File extension */
  3997. cfg.extnorder ^= 1;
  3998. cfg.sizeorder = 0;
  3999. cfg.timeorder = 0;
  4000. cfg.apparentsz = 0;
  4001. cfg.blkorder = 0;
  4002. entrycmpfn = &entrycmp;
  4003. break;
  4004. case 'r': /* Reverse sort */
  4005. entrycmpfn = (entrycmpfn == &entrycmp) ? &reventrycmp : &entrycmp;
  4006. break;
  4007. case 's': /* File size */
  4008. cfg.sizeorder ^= 1;
  4009. cfg.timeorder = 0;
  4010. cfg.apparentsz = 0;
  4011. cfg.blkorder = 0;
  4012. cfg.extnorder = 0;
  4013. entrycmpfn = &entrycmp;
  4014. break;
  4015. case 't': /* Time */
  4016. cfg.timeorder ^= 1;
  4017. cfg.sizeorder = 0;
  4018. cfg.apparentsz = 0;
  4019. cfg.blkorder = 0;
  4020. cfg.extnorder = 0;
  4021. entrycmpfn = &entrycmp;
  4022. break;
  4023. case 'v': /* Version */
  4024. namecmpfn = (namecmpfn == &xstrverscasecmp) ? &xstricmp : &xstrverscasecmp;
  4025. cfg.timeorder = 0;
  4026. cfg.sizeorder = 0;
  4027. cfg.apparentsz = 0;
  4028. cfg.blkorder = 0;
  4029. cfg.extnorder = 0;
  4030. break;
  4031. default:
  4032. return 0;
  4033. }
  4034. return r;
  4035. }
  4036. static bool set_time_type(int *presel)
  4037. {
  4038. bool ret = FALSE;
  4039. char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
  4040. buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
  4041. int r = get_input(buf);
  4042. if (r == 'a' || r == 'c' || r == 'm') {
  4043. r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
  4044. if (cfg.timetype != r) {
  4045. cfg.timetype = r;
  4046. if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
  4047. *presel = FILTER;
  4048. ret = TRUE;
  4049. } else
  4050. r = MSG_NOCHNAGE;
  4051. } else
  4052. r = MSG_INVALID_KEY;
  4053. if (!ret)
  4054. printwait(messages[r], presel);
  4055. return ret;
  4056. }
  4057. static void statusbar(char *path)
  4058. {
  4059. int i = 0, extnlen = 0;
  4060. char *ptr;
  4061. pEntry pent = &dents[cur];
  4062. if (!ndents) {
  4063. printmsg("0/0");
  4064. return;
  4065. }
  4066. /* Get the file extension for regular files */
  4067. if (S_ISREG(pent->mode)) {
  4068. i = (int)(pent->nlen - 1);
  4069. ptr = xmemrchr((uchar *)pent->name, '.', i);
  4070. if (ptr)
  4071. extnlen = i - (ptr - pent->name);
  4072. if (!ptr || extnlen > 5 || extnlen < 2)
  4073. ptr = "\b";
  4074. } else
  4075. ptr = "\b";
  4076. tolastln();
  4077. attron(COLOR_PAIR(cfg.curctx + 1));
  4078. if (cfg.blkorder) { /* du mode */
  4079. char buf[24];
  4080. xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
  4081. printw("%d/%d [%s:%s] %cu:%s free:%s files:%lu %lldB %s\n",
  4082. cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4083. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4084. (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, FREE)),
  4085. num_files, (ll)pent->blocks << blk_shift, ptr);
  4086. } else { /* light or detail mode */
  4087. char sort[] = "\0\0\0\0";
  4088. getorderstr(sort);
  4089. printw("%d/%d [%s:%s] %s", cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4090. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4091. sort);
  4092. /* Timestamp */
  4093. print_time(&pent->t);
  4094. addch(' ');
  4095. addstr(get_lsperms(pent->mode));
  4096. addch(' ');
  4097. addstr(coolsize(pent->size));
  4098. addch(' ');
  4099. addstr(ptr);
  4100. addch('\n');
  4101. }
  4102. attroff(COLOR_PAIR(cfg.curctx + 1));
  4103. }
  4104. static int adjust_cols(int ncols)
  4105. {
  4106. /* Calculate the number of cols available to print entry name */
  4107. if (cfg.showdetail) {
  4108. /* Fallback to light mode if less than 35 columns */
  4109. if (ncols < 36) {
  4110. cfg.showdetail ^= 1;
  4111. printptr = &printent;
  4112. ncols -= 3; /* Preceding space, indicator, newline */
  4113. } else
  4114. ncols -= 35;
  4115. } else
  4116. ncols -= 3; /* Preceding space, indicator, newline */
  4117. return ncols;
  4118. }
  4119. static void draw_line(char *path, int ncols)
  4120. {
  4121. bool dir = FALSE;
  4122. ncols = adjust_cols(ncols);
  4123. if (dents[last].flags & DIR_OR_LINK_TO_DIR) {
  4124. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4125. dir = TRUE;
  4126. }
  4127. move(2 + last - curscroll, 0);
  4128. printptr(&dents[last], ncols, false);
  4129. if (dents[cur].flags & DIR_OR_LINK_TO_DIR) {
  4130. if (!dir) {/* First file is not a directory */
  4131. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4132. dir = TRUE;
  4133. }
  4134. } else if (dir) { /* Second file is not a directory */
  4135. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4136. dir = FALSE;
  4137. }
  4138. move(2 + cur - curscroll, 0);
  4139. printptr(&dents[cur], ncols, true);
  4140. /* Must reset e.g. no files in dir */
  4141. if (dir)
  4142. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4143. statusbar(path);
  4144. }
  4145. static void redraw(char *path)
  4146. {
  4147. xlines = LINES;
  4148. xcols = COLS;
  4149. DPRINTF_S(__FUNCTION__);
  4150. int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
  4151. int onscreen = xlines - 4;
  4152. int i;
  4153. char *ptr = path;
  4154. // Fast redraw
  4155. if (g_states & STATE_MOVE_OP) {
  4156. g_states &= ~STATE_MOVE_OP;
  4157. if (ndents && (last_curscroll == curscroll))
  4158. return draw_line(path, ncols);
  4159. }
  4160. /* Clear first line */
  4161. move(0, 0);
  4162. clrtoeol();
  4163. /* Enforce scroll/cursor invariants */
  4164. move_cursor(cur, 1);
  4165. /* Fail redraw if < than 10 columns, context info prints 10 chars */
  4166. if (ncols < MIN_DISPLAY_COLS) {
  4167. /* Clear from last entry to end */
  4168. clrtobot();
  4169. printmsg(messages[MSG_FEW_COLUMNS]);
  4170. return;
  4171. }
  4172. //DPRINTF_D(cur);
  4173. DPRINTF_S(path);
  4174. addch('[');
  4175. for (i = 0; i < CTX_MAX; ++i) {
  4176. if (!g_ctx[i].c_cfg.ctxactive)
  4177. addch(i + '1');
  4178. else
  4179. addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
  4180. /* active: underline, current: reverse */
  4181. | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
  4182. addch(' ');
  4183. }
  4184. addstr("\b] "); /* 10 chars printed for contexts - "[1 2 3 4] " */
  4185. attron(A_UNDERLINE);
  4186. /* Print path */
  4187. i = (int)xstrlen(path);
  4188. if ((i + MIN_DISPLAY_COLS) <= ncols)
  4189. addnstr(path, ncols - MIN_DISPLAY_COLS);
  4190. else {
  4191. char *base = xmemrchr((uchar *)path, '/', i);
  4192. i = 0;
  4193. if (base != ptr) {
  4194. while (ptr < base) {
  4195. if (*ptr == '/') {
  4196. i += 2; /* 2 characters added */
  4197. if (ncols < i + MIN_DISPLAY_COLS) {
  4198. base = NULL; /* Can't print more characters */
  4199. break;
  4200. }
  4201. addch(*ptr);
  4202. addch(*(++ptr));
  4203. }
  4204. ++ptr;
  4205. }
  4206. }
  4207. addnstr(base, ncols - (MIN_DISPLAY_COLS + i));
  4208. }
  4209. attroff(A_UNDERLINE);
  4210. /* Go to first entry */
  4211. move(2, 0);
  4212. ncols = adjust_cols(ncols);
  4213. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4214. cfg.dircolor = 1;
  4215. /* Print listing */
  4216. for (i = curscroll; i < ndents && i < curscroll + onscreen; ++i)
  4217. printptr(&dents[i], ncols, i == cur);
  4218. /* Must reset e.g. no files in dir */
  4219. if (cfg.dircolor) {
  4220. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4221. cfg.dircolor = 0;
  4222. }
  4223. /* Clear from last entry to end */
  4224. clrtobot();
  4225. statusbar(path);
  4226. }
  4227. static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
  4228. {
  4229. if (lastname)
  4230. lastname[0] = '\0';
  4231. /* Save last working directory */
  4232. xstrsncpy(lastdir, path, PATH_MAX);
  4233. /* Save the newly opted dir in path */
  4234. xstrsncpy(path, newpath, PATH_MAX);
  4235. DPRINTF_S(path);
  4236. clearfilter();
  4237. return cfg.filtermode;
  4238. }
  4239. static bool browse(char *ipath, const char *session)
  4240. {
  4241. char newpath[PATH_MAX] __attribute__ ((aligned));
  4242. char rundir[PATH_MAX] __attribute__ ((aligned));
  4243. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  4244. char *path, *lastdir, *lastname, *dir, *tmp, *mark = NULL;
  4245. enum action sel;
  4246. struct stat sb;
  4247. int r = -1, presel, selstartid = 0, selendid = 0;
  4248. const uchar opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOWAIT));
  4249. bool watch = FALSE;
  4250. #ifndef NOMOUSE
  4251. MEVENT event;
  4252. struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
  4253. bool currentmouse = 1;
  4254. bool rightclicksel = 0;
  4255. #endif
  4256. #ifndef DIR_LIMITED_SELECTION
  4257. ino_t inode = 0;
  4258. #endif
  4259. atexit(dentfree);
  4260. xlines = LINES;
  4261. xcols = COLS;
  4262. /* setup first context */
  4263. if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
  4264. xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  4265. path = g_ctx[0].c_path;
  4266. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = '\0';
  4267. lastdir = g_ctx[0].c_last; /* last visited directory */
  4268. lastname = g_ctx[0].c_name; /* last visited filename */
  4269. g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
  4270. g_ctx[0].c_cfg = cfg; /* current configuration */
  4271. }
  4272. newpath[0] = rundir[0] = runfile[0] = '\0';
  4273. presel = cfg.filtermode ? FILTER : 0;
  4274. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  4275. if (!dents)
  4276. errexit();
  4277. /* Allocate buffer to hold names */
  4278. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  4279. if (!pnamebuf)
  4280. errexit();
  4281. begin:
  4282. /* Can fail when permissions change while browsing.
  4283. * It's assumed that path IS a directory when we are here.
  4284. */
  4285. if (access(path, R_OK) == -1) {
  4286. DPRINTF_S("directory inaccessible");
  4287. valid_parent(path, lastname);
  4288. setdirwatch();
  4289. }
  4290. if (cfg.selmode && lastdir[0])
  4291. lastappendpos = selbufpos;
  4292. #ifdef LINUX_INOTIFY
  4293. if ((presel == FILTER || watch) && inotify_wd >= 0) {
  4294. inotify_rm_watch(inotify_fd, inotify_wd);
  4295. inotify_wd = -1;
  4296. watch = FALSE;
  4297. }
  4298. #elif defined(BSD_KQUEUE)
  4299. if ((presel == FILTER || watch) && event_fd >= 0) {
  4300. close(event_fd);
  4301. event_fd = -1;
  4302. watch = FALSE;
  4303. }
  4304. #elif defined(HAIKU_NM)
  4305. if ((presel == FILTER || watch) && haiku_hnd != NULL) {
  4306. haiku_stop_watch(haiku_hnd);
  4307. haiku_nm_active = FALSE;
  4308. watch = FALSE;
  4309. }
  4310. #endif
  4311. populate(path, lastname);
  4312. if (g_states & STATE_INTERRUPTED) {
  4313. g_states &= ~STATE_INTERRUPTED;
  4314. cfg.apparentsz = 0;
  4315. cfg.blkorder = 0;
  4316. blk_shift = BLK_SHIFT_512;
  4317. presel = CONTROL('L');
  4318. }
  4319. #ifdef LINUX_INOTIFY
  4320. if (presel != FILTER && inotify_wd == -1)
  4321. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  4322. #elif defined(BSD_KQUEUE)
  4323. if (presel != FILTER && event_fd == -1) {
  4324. #if defined(O_EVTONLY)
  4325. event_fd = open(path, O_EVTONLY);
  4326. #else
  4327. event_fd = open(path, O_RDONLY);
  4328. #endif
  4329. if (event_fd >= 0)
  4330. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  4331. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  4332. }
  4333. #elif defined(HAIKU_NM)
  4334. haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == _SUCCESS;
  4335. #endif
  4336. while (1) {
  4337. redraw(path);
  4338. /* Display a one-time message */
  4339. if (listpath && (g_states & STATE_MSG)) {
  4340. g_states &= ~STATE_MSG;
  4341. printwait(messages[MSG_IGNORED], &presel);
  4342. }
  4343. nochange:
  4344. /* Exit if parent has exited */
  4345. if (getppid() == 1) {
  4346. free(mark);
  4347. _exit(0);
  4348. }
  4349. /* If CWD is deleted or moved or perms changed, find an accessible parent */
  4350. if (access(path, F_OK))
  4351. goto begin;
  4352. /* If STDIN is no longer a tty (closed) we should exit */
  4353. if (!isatty(STDIN_FILENO) && !cfg.picker) {
  4354. free(mark);
  4355. return _FAILURE;
  4356. }
  4357. sel = nextsel(presel);
  4358. if (presel)
  4359. presel = 0;
  4360. switch (sel) {
  4361. #ifndef NOMOUSE
  4362. case SEL_CLICK:
  4363. if (getmouse(&event) != OK)
  4364. goto nochange;
  4365. /* Handle clicking on a context at the top */
  4366. if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
  4367. /* Get context from: "[1 2 3 4]..." */
  4368. r = event.x >> 1;
  4369. /* If clicked after contexts, go to parent */
  4370. if (r >= CTX_MAX)
  4371. sel = SEL_BACK;
  4372. else if (r >= 0 && r != cfg.curctx) {
  4373. if (cfg.selmode)
  4374. lastappendpos = selbufpos;
  4375. savecurctx(&cfg, path, dents[cur].name, r);
  4376. /* Reset the pointers */
  4377. path = g_ctx[r].c_path;
  4378. lastdir = g_ctx[r].c_last;
  4379. lastname = g_ctx[r].c_name;
  4380. setdirwatch();
  4381. goto begin;
  4382. }
  4383. }
  4384. #endif
  4385. // fallthrough
  4386. case SEL_BACK:
  4387. #ifndef NOMOUSE
  4388. if (sel == SEL_BACK) {
  4389. #endif
  4390. dir = visit_parent(path, newpath, &presel);
  4391. if (!dir)
  4392. goto nochange;
  4393. /* Save history */
  4394. xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
  4395. cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
  4396. goto begin;
  4397. #ifndef NOMOUSE
  4398. }
  4399. #endif
  4400. #ifndef NOMOUSE
  4401. /* Middle click action */
  4402. if (event.bstate == BUTTON2_PRESSED) {
  4403. presel = middle_click_key;
  4404. goto nochange;
  4405. }
  4406. #if NCURSES_MOUSE_VERSION > 1
  4407. /* Scroll up */
  4408. if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
  4409. move_cursor((cur + ndents - 1) % ndents, 0);
  4410. break;
  4411. }
  4412. /* Scroll down */
  4413. if (event.bstate == BUTTON5_PRESSED && ndents
  4414. && (cfg.rollover || (cur != ndents - 1))) {
  4415. move_cursor((cur + 1) % ndents, 0);
  4416. break;
  4417. }
  4418. #endif
  4419. /* Toggle filter mode on left click on last 2 lines */
  4420. if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
  4421. clearfilter();
  4422. cfg.filtermode ^= 1;
  4423. if (cfg.filtermode) {
  4424. presel = FILTER;
  4425. goto nochange;
  4426. }
  4427. /* Start watching the directory */
  4428. watch = TRUE;
  4429. if (ndents)
  4430. copycurname();
  4431. goto begin;
  4432. }
  4433. /* Handle clicking on a file */
  4434. if (event.y >= 2 && event.y <= ndents + 1 &&
  4435. (event.bstate == BUTTON1_PRESSED ||
  4436. event.bstate == BUTTON3_PRESSED)) {
  4437. r = curscroll + (event.y - 2);
  4438. move_cursor(r, 1);
  4439. /* Handle right click selection */
  4440. if (event.bstate == BUTTON3_PRESSED) {
  4441. rightclicksel = 1;
  4442. presel = SELECT;
  4443. goto nochange;
  4444. }
  4445. currentmouse ^= 1;
  4446. clock_gettime(
  4447. #if defined(CLOCK_MONOTONIC_RAW)
  4448. CLOCK_MONOTONIC_RAW,
  4449. #elif defined(CLOCK_MONOTONIC)
  4450. CLOCK_MONOTONIC,
  4451. #else
  4452. CLOCK_REALTIME,
  4453. #endif
  4454. &mousetimings[currentmouse]);
  4455. /*Single click just selects, double click also opens */
  4456. if (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
  4457. + (mousetimings[0].tv_nsec - mousetimings[1].tv_nsec))
  4458. > DOUBLECLICK_INTERVAL_NS)
  4459. break;
  4460. mousetimings[currentmouse].tv_sec = 0;
  4461. } else {
  4462. if (cfg.filtermode || filterset())
  4463. presel = FILTER;
  4464. if (ndents)
  4465. copycurname();
  4466. goto nochange;
  4467. }
  4468. #endif
  4469. // fallthrough
  4470. case SEL_NAV_IN: // fallthrough
  4471. case SEL_GOIN:
  4472. /* Cannot descend in empty directories */
  4473. if (!ndents)
  4474. goto begin;
  4475. mkpath(path, dents[cur].name, newpath);
  4476. DPRINTF_S(newpath);
  4477. /* Cannot use stale data in entry, file may be missing by now */
  4478. if (stat(newpath, &sb) == -1) {
  4479. printwarn(&presel);
  4480. goto nochange;
  4481. }
  4482. DPRINTF_U(sb.st_mode);
  4483. switch (sb.st_mode & S_IFMT) {
  4484. case S_IFDIR:
  4485. if (access(newpath, R_OK) == -1) {
  4486. printwarn(&presel);
  4487. goto nochange;
  4488. }
  4489. cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
  4490. goto begin;
  4491. case S_IFREG:
  4492. {
  4493. /* If opened as vim plugin and Enter/^M pressed, pick */
  4494. if (cfg.picker && sel == SEL_GOIN) {
  4495. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4496. writesel(pselbuf, selbufpos - 1);
  4497. free(mark);
  4498. return _SUCCESS;
  4499. }
  4500. /* If open file is disabled on right arrow or `l`, return */
  4501. if (cfg.nonavopen && sel == SEL_NAV_IN)
  4502. goto nochange;
  4503. /* Handle plugin selection mode */
  4504. if (cfg.runplugin) {
  4505. cfg.runplugin = 0;
  4506. /* Must be in plugin dir and same context to select plugin */
  4507. if ((cfg.runctx == cfg.curctx) && !strcmp(path, plugindir)) {
  4508. endselection();
  4509. /* Copy path so we can return back to earlier dir */
  4510. xstrsncpy(path, rundir, PATH_MAX);
  4511. rundir[0] = '\0';
  4512. if (!run_selected_plugin(&path, dents[cur].name,
  4513. runfile, &lastname, &lastdir)) {
  4514. DPRINTF_S("plugin failed!");
  4515. }
  4516. if (runfile[0])
  4517. runfile[0] = '\0';
  4518. clearfilter();
  4519. setdirwatch();
  4520. goto begin;
  4521. }
  4522. }
  4523. if (cfg.useeditor && (!sb.st_size ||
  4524. #ifdef FILE_MIME_OPTS
  4525. (get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, newpath, FALSE)
  4526. && !strncmp(g_buf, "text/", 5)))) {
  4527. #else
  4528. /* no mime option; guess from description instead */
  4529. (get_output(g_buf, CMD_LEN_MAX, "file", "-b", newpath, FALSE)
  4530. && strstr(g_buf, "text")))) {
  4531. #endif
  4532. spawn(editor, newpath, NULL, path, F_CLI);
  4533. continue;
  4534. }
  4535. if (!sb.st_size) {
  4536. printwait(messages[MSG_EMPTY_FILE], &presel);
  4537. goto nochange;
  4538. }
  4539. #ifdef PCRE
  4540. if (!pcre_exec(archive_pcre, NULL, dents[cur].name,
  4541. xstrlen(dents[cur].name), 0, 0, NULL, 0)) {
  4542. #else
  4543. if (!regexec(&archive_re, dents[cur].name, 0, NULL, 0)) {
  4544. #endif
  4545. r = get_input(messages[MSG_ARCHIVE_OPTS]);
  4546. if (r == 'l' || r == 'x') {
  4547. mkpath(path, dents[cur].name, newpath);
  4548. handle_archive(newpath, path, r);
  4549. if (r == 'l') {
  4550. statusbar(path);
  4551. goto nochange;
  4552. }
  4553. copycurname();
  4554. clearfilter();
  4555. goto begin;
  4556. }
  4557. if (r == 'm') {
  4558. if (!archive_mount(path, newpath)) {
  4559. presel = MSGWAIT;
  4560. goto nochange;
  4561. }
  4562. cdprep(lastdir, lastname, path, newpath)
  4563. ? (presel = FILTER) : (watch = TRUE);
  4564. goto begin;
  4565. }
  4566. if (r != 'd') {
  4567. printwait(messages[MSG_INVALID_KEY], &presel);
  4568. goto nochange;
  4569. }
  4570. }
  4571. /* Invoke desktop opener as last resort */
  4572. spawn(opener, newpath, NULL, NULL, opener_flags);
  4573. /* Move cursor to the next entry if not the last entry */
  4574. if ((g_states & STATE_AUTONEXT) && cur != ndents - 1)
  4575. move_cursor((cur + 1) % ndents, 0);
  4576. continue;
  4577. }
  4578. default:
  4579. printwait(messages[MSG_UNSUPPORTED], &presel);
  4580. goto nochange;
  4581. }
  4582. case SEL_NEXT: // fallthrough
  4583. case SEL_PREV: // fallthrough
  4584. case SEL_PGDN: // fallthrough
  4585. case SEL_CTRL_D: // fallthrough
  4586. case SEL_PGUP: // fallthrough
  4587. case SEL_CTRL_U: // fallthrough
  4588. case SEL_HOME: // fallthrough
  4589. case SEL_END: // fallthrough
  4590. case SEL_FIRST:
  4591. g_states |= STATE_MOVE_OP;
  4592. handle_screen_move(sel);
  4593. break;
  4594. case SEL_CDHOME: // fallthrough
  4595. case SEL_CDBEGIN: // fallthrough
  4596. case SEL_CDLAST: // fallthrough
  4597. case SEL_CDROOT:
  4598. switch (sel) {
  4599. case SEL_CDHOME:
  4600. dir = home;
  4601. break;
  4602. case SEL_CDBEGIN:
  4603. dir = ipath;
  4604. break;
  4605. case SEL_CDLAST:
  4606. dir = lastdir;
  4607. break;
  4608. default: /* SEL_CDROOT */
  4609. dir = "/";
  4610. break;
  4611. }
  4612. if (!dir || !*dir) {
  4613. printwait(messages[MSG_NOT_SET], &presel);
  4614. goto nochange;
  4615. }
  4616. if (!xdiraccess(dir)) {
  4617. presel = MSGWAIT;
  4618. goto nochange;
  4619. }
  4620. if (strcmp(path, dir) == 0) {
  4621. if (cfg.filtermode)
  4622. presel = FILTER;
  4623. goto nochange;
  4624. }
  4625. /* SEL_CDLAST: dir pointing to lastdir */
  4626. xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
  4627. case SEL_BOOKMARK:
  4628. if (sel == SEL_BOOKMARK) {
  4629. r = (int)handle_bookmark(mark, newpath);
  4630. if (r) {
  4631. printwait(messages[r], &presel);
  4632. goto nochange;
  4633. }
  4634. if (strcmp(path, newpath) == 0)
  4635. break;
  4636. } // fallthrough
  4637. case SEL_REMOTE:
  4638. if (sel == SEL_REMOTE && !remote_mount(newpath, path)) {
  4639. presel = MSGWAIT;
  4640. goto nochange;
  4641. }
  4642. cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
  4643. goto begin;
  4644. case SEL_CYCLE: // fallthrough
  4645. case SEL_CYCLER: // fallthrough
  4646. case SEL_CTX1: // fallthrough
  4647. case SEL_CTX2: // fallthrough
  4648. case SEL_CTX3: // fallthrough
  4649. case SEL_CTX4:
  4650. r = handle_context_switch(sel);
  4651. if (r < 0)
  4652. continue;
  4653. savecurctx(&cfg, path, dents[cur].name, r);
  4654. /* Reset the pointers */
  4655. path = g_ctx[r].c_path;
  4656. lastdir = g_ctx[r].c_last;
  4657. lastname = g_ctx[r].c_name;
  4658. tmp = g_ctx[r].c_fltr;
  4659. if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
  4660. presel = FILTER;
  4661. else
  4662. watch = TRUE;
  4663. goto begin;
  4664. case SEL_PIN:
  4665. free(mark);
  4666. mark = xstrdup(path);
  4667. printwait(mark, &presel);
  4668. goto nochange;
  4669. case SEL_FLTR:
  4670. /* Unwatch dir if we are still in a filtered view */
  4671. #ifdef LINUX_INOTIFY
  4672. if (inotify_wd >= 0) {
  4673. inotify_rm_watch(inotify_fd, inotify_wd);
  4674. inotify_wd = -1;
  4675. }
  4676. #elif defined(BSD_KQUEUE)
  4677. if (event_fd >= 0) {
  4678. close(event_fd);
  4679. event_fd = -1;
  4680. }
  4681. #elif defined(HAIKU_NM)
  4682. if (haiku_nm_active) {
  4683. haiku_stop_watch(haiku_hnd);
  4684. haiku_nm_active = FALSE;
  4685. }
  4686. #endif
  4687. presel = filterentries(path, lastname);
  4688. if (presel == 27) {
  4689. presel = 0;
  4690. break;
  4691. }
  4692. goto nochange;
  4693. case SEL_MFLTR: // fallthrough
  4694. case SEL_HIDDEN: // fallthrough
  4695. case SEL_DETAIL: // fallthrough
  4696. case SEL_SORT:
  4697. switch (sel) {
  4698. case SEL_MFLTR:
  4699. cfg.filtermode ^= 1;
  4700. if (cfg.filtermode) {
  4701. presel = FILTER;
  4702. clearfilter();
  4703. goto nochange;
  4704. }
  4705. watch = TRUE; // fallthrough
  4706. case SEL_HIDDEN:
  4707. if (sel == SEL_HIDDEN) {
  4708. cfg.showhidden ^= 1;
  4709. if (cfg.filtermode)
  4710. presel = FILTER;
  4711. clearfilter();
  4712. }
  4713. if (ndents)
  4714. copycurname();
  4715. goto begin;
  4716. case SEL_DETAIL:
  4717. cfg.showdetail ^= 1;
  4718. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  4719. cfg.blkorder = 0;
  4720. continue;
  4721. default: /* SEL_SORT */
  4722. r = set_sort_flags(get_input(messages[MSG_ORDER]));
  4723. if (!r) {
  4724. printwait(messages[MSG_INVALID_KEY], &presel);
  4725. goto nochange;
  4726. }
  4727. }
  4728. if (cfg.filtermode || filterset())
  4729. presel = FILTER;
  4730. if (ndents) {
  4731. copycurname();
  4732. if (r == 'd' || r == 'a')
  4733. goto begin;
  4734. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  4735. move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
  4736. }
  4737. continue;
  4738. case SEL_STATS: // fallthrough
  4739. case SEL_CHMODX:
  4740. if (ndents) {
  4741. tmp = (listpath && xstrcmp(path, listpath) == 0) ? prefixpath : path;
  4742. mkpath(tmp, dents[cur].name, newpath);
  4743. if (lstat(newpath, &sb) == -1
  4744. || (sel == SEL_STATS && !show_stats(newpath, &sb))
  4745. || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
  4746. printwarn(&presel);
  4747. goto nochange;
  4748. }
  4749. if (sel == SEL_CHMODX)
  4750. dents[cur].mode ^= 0111;
  4751. }
  4752. break;
  4753. case SEL_REDRAW: // fallthrough
  4754. case SEL_RENAMEMUL: // fallthrough
  4755. case SEL_HELP: // fallthrough
  4756. case SEL_AUTONEXT: // fallthrough
  4757. case SEL_EDIT: // fallthrough
  4758. case SEL_LOCK:
  4759. {
  4760. bool refresh = FALSE;
  4761. if (ndents)
  4762. mkpath(path, dents[cur].name, newpath);
  4763. else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
  4764. goto nochange;
  4765. switch (sel) {
  4766. case SEL_REDRAW:
  4767. refresh = TRUE;
  4768. break;
  4769. case SEL_RENAMEMUL:
  4770. endselection();
  4771. if (!(getutil(utils[UTIL_BASH])
  4772. && plugscript(utils[UTIL_NMV], path, F_CLI))
  4773. #ifndef NOBATCH
  4774. && !batch_rename(path)) {
  4775. #else
  4776. ) {
  4777. #endif
  4778. printwait(messages[MSG_FAILED], &presel);
  4779. goto nochange;
  4780. }
  4781. refresh = TRUE;
  4782. break;
  4783. case SEL_HELP:
  4784. show_help(path); // fallthrough
  4785. case SEL_AUTONEXT:
  4786. if (sel == SEL_AUTONEXT)
  4787. g_states ^= STATE_AUTONEXT;
  4788. if (cfg.filtermode)
  4789. presel = FILTER;
  4790. if (ndents)
  4791. copycurname();
  4792. goto nochange;
  4793. case SEL_EDIT:
  4794. spawn(editor, dents[cur].name, NULL, path, F_CLI);
  4795. continue;
  4796. default: /* SEL_LOCK */
  4797. lock_terminal();
  4798. break;
  4799. }
  4800. /* In case of successful operation, reload contents */
  4801. /* Continue in type-to-nav mode, if enabled */
  4802. if ((cfg.filtermode || filterset()) && !refresh)
  4803. break;
  4804. /* Save current */
  4805. if (ndents)
  4806. copycurname();
  4807. /* Repopulate as directory content may have changed */
  4808. goto begin;
  4809. }
  4810. case SEL_SEL:
  4811. if (!ndents)
  4812. goto nochange;
  4813. startselection();
  4814. if (g_states & STATE_RANGESEL)
  4815. g_states &= ~STATE_RANGESEL;
  4816. /* Toggle selection status */
  4817. dents[cur].flags ^= FILE_SELECTED;
  4818. if (dents[cur].flags & FILE_SELECTED) {
  4819. ++nselected;
  4820. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4821. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4822. } else {
  4823. selbufpos = lastappendpos;
  4824. if (--nselected) {
  4825. updateselbuf(path, newpath);
  4826. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4827. } else
  4828. writesel(NULL, 0);
  4829. }
  4830. if (cfg.x11)
  4831. plugscript(utils[UTIL_CBCP], NULL, F_NOWAIT | F_NOTRACE);
  4832. if (!nselected)
  4833. unlink(selpath);
  4834. #ifndef NOMOUSE
  4835. if (rightclicksel)
  4836. rightclicksel = 0;
  4837. else
  4838. #endif
  4839. /* move cursor to the next entry if this is not the last entry */
  4840. if (!cfg.picker && cur != ndents - 1)
  4841. move_cursor((cur + 1) % ndents, 0);
  4842. break;
  4843. case SEL_SELMUL:
  4844. if (!ndents)
  4845. goto nochange;
  4846. startselection();
  4847. g_states ^= STATE_RANGESEL;
  4848. if (stat(path, &sb) == -1) {
  4849. printwarn(&presel);
  4850. goto nochange;
  4851. }
  4852. if (g_states & STATE_RANGESEL) { /* Range selection started */
  4853. #ifndef DIR_LIMITED_SELECTION
  4854. inode = sb.st_ino;
  4855. #endif
  4856. selstartid = cur;
  4857. continue;
  4858. }
  4859. #ifndef DIR_LIMITED_SELECTION
  4860. if (inode != sb.st_ino) {
  4861. printwait(messages[MSG_DIR_CHANGED], &presel);
  4862. goto nochange;
  4863. }
  4864. #endif
  4865. if (cur < selstartid) {
  4866. selendid = selstartid;
  4867. selstartid = cur;
  4868. } else
  4869. selendid = cur;
  4870. /* Clear selection on repeat on same file */
  4871. if (selstartid == selendid) {
  4872. resetselind();
  4873. clearselection();
  4874. break;
  4875. } // fallthrough
  4876. case SEL_SELALL:
  4877. if (sel == SEL_SELALL) {
  4878. if (!ndents)
  4879. goto nochange;
  4880. startselection();
  4881. if (g_states & STATE_RANGESEL)
  4882. g_states &= ~STATE_RANGESEL;
  4883. selstartid = 0;
  4884. selendid = ndents - 1;
  4885. }
  4886. /* Remember current selection buffer position */
  4887. for (r = selstartid; r <= selendid; ++r)
  4888. if (!(dents[r].flags & FILE_SELECTED)) {
  4889. /* Write the path to selection file to avoid flush */
  4890. appendfpath(newpath, mkpath(path, dents[r].name, newpath));
  4891. dents[r].flags |= FILE_SELECTED;
  4892. ++nselected;
  4893. }
  4894. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4895. if (cfg.x11)
  4896. plugscript(utils[UTIL_CBCP], NULL, F_NOWAIT | F_NOTRACE);
  4897. continue;
  4898. case SEL_SELEDIT:
  4899. r = editselection();
  4900. if (r <= 0) {
  4901. r = !r ? MSG_0_SELECTED : MSG_FAILED;
  4902. printwait(messages[r], &presel);
  4903. } else {
  4904. if (cfg.x11)
  4905. plugscript(utils[UTIL_CBCP], NULL, F_NOWAIT | F_NOTRACE);
  4906. cfg.filtermode ? presel = FILTER : statusbar(path);
  4907. }
  4908. goto nochange;
  4909. case SEL_CP: // fallthrough
  4910. case SEL_MV: // fallthrough
  4911. case SEL_CPMVAS: // fallthrough
  4912. case SEL_RM:
  4913. {
  4914. if (sel == SEL_RM) {
  4915. r = get_cur_or_sel();
  4916. if (!r) {
  4917. statusbar(path);
  4918. goto nochange;
  4919. }
  4920. if (r == 'c') {
  4921. tmp = (listpath && xstrcmp(path, listpath) == 0)
  4922. ? prefixpath : path;
  4923. mkpath(tmp, dents[cur].name, newpath);
  4924. xrm(newpath);
  4925. if (access(newpath, F_OK) == 0) /* File not removed */
  4926. continue;
  4927. if (cur) {
  4928. cur += (cur != (ndents - 1)) ? 1 : -1;
  4929. copycurname();
  4930. } else
  4931. lastname[0] = '\0';
  4932. if (cfg.filtermode || filterset())
  4933. presel = FILTER;
  4934. goto begin;
  4935. }
  4936. }
  4937. if (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
  4938. mkpath(path, xbasename(pselbuf), newpath);
  4939. else
  4940. newpath[0] = '\0';
  4941. endselection();
  4942. if (!cpmvrm_selection(sel, path)) {
  4943. presel = MSGWAIT;
  4944. goto nochange;
  4945. }
  4946. if (cfg.filtermode)
  4947. presel = FILTER;
  4948. clearfilter();
  4949. /* Show notification on operation complete */
  4950. if (cfg.x11)
  4951. plugscript(utils[UTIL_NTFY], NULL, F_NOWAIT | F_NOTRACE);
  4952. if (newpath[0] && !access(newpath, F_OK))
  4953. xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
  4954. else if (ndents)
  4955. copycurname();
  4956. goto begin;
  4957. }
  4958. case SEL_ARCHIVE: // fallthrough
  4959. case SEL_OPENWITH: // fallthrough
  4960. case SEL_NEW: // fallthrough
  4961. case SEL_RENAME:
  4962. {
  4963. int fd, ret = 'n';
  4964. if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
  4965. break;
  4966. if (sel != SEL_OPENWITH)
  4967. endselection();
  4968. switch (sel) {
  4969. case SEL_ARCHIVE:
  4970. r = get_cur_or_sel();
  4971. if (!r) {
  4972. statusbar(path);
  4973. goto nochange;
  4974. }
  4975. if (r == 's') {
  4976. if (!selsafe()) {
  4977. presel = MSGWAIT;
  4978. goto nochange;
  4979. }
  4980. tmp = NULL;
  4981. } else
  4982. tmp = dents[cur].name;
  4983. tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
  4984. break;
  4985. case SEL_OPENWITH:
  4986. #ifdef NORL
  4987. tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
  4988. #else
  4989. presel = 0;
  4990. tmp = getreadline(messages[MSG_OPEN_WITH], path, ipath, &presel);
  4991. if (presel == MSGWAIT)
  4992. goto nochange;
  4993. #endif
  4994. break;
  4995. case SEL_NEW:
  4996. r = get_input(messages[MSG_NEW_OPTS]);
  4997. if (r == 'f' || r == 'd')
  4998. tmp = xreadline(NULL, messages[MSG_REL_PATH]);
  4999. else if (r == 's' || r == 'h')
  5000. tmp = xreadline(NULL, messages[MSG_LINK_PREFIX]);
  5001. else
  5002. tmp = NULL;
  5003. break;
  5004. default: /* SEL_RENAME */
  5005. tmp = xreadline(dents[cur].name, "");
  5006. break;
  5007. }
  5008. if (!tmp || !*tmp)
  5009. break;
  5010. /* Allow only relative, same dir paths */
  5011. if (tmp[0] == '/'
  5012. || ((r != 'f' && r != 'd') && (xstrcmp(xbasename(tmp), tmp) != 0))) {
  5013. printwait(messages[MSG_NO_TRAVERSAL], &presel);
  5014. goto nochange;
  5015. }
  5016. switch (sel) {
  5017. case SEL_ARCHIVE:
  5018. if (r == 'c' && strcmp(tmp, dents[cur].name) == 0)
  5019. goto nochange;
  5020. mkpath(path, tmp, newpath);
  5021. if (access(newpath, F_OK) == 0) {
  5022. if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
  5023. statusbar(path);
  5024. goto nochange;
  5025. }
  5026. }
  5027. get_archive_cmd(newpath, tmp);
  5028. (r == 's') ? archive_selection(newpath, tmp, path)
  5029. : spawn(newpath, tmp, dents[cur].name,
  5030. path, F_NORMAL | F_MULTI);
  5031. mkpath(path, tmp, newpath);
  5032. if (access(newpath, F_OK) == 0) { /* File created */
  5033. xstrsncpy(lastname, tmp, NAME_MAX + 1);
  5034. clearfilter(); /* Archive name may not match */
  5035. goto begin;
  5036. }
  5037. continue;
  5038. case SEL_OPENWITH:
  5039. /* Confirm if app is CLI or GUI */
  5040. r = get_input(messages[MSG_CLI_MODE]);
  5041. r = (r == 'c' ? F_CLI :
  5042. (r == 'g' ? F_NOWAIT | F_NOTRACE | F_MULTI : 0));
  5043. if (r) {
  5044. mkpath(path, dents[cur].name, newpath);
  5045. spawn(tmp, newpath, NULL, path, r);
  5046. }
  5047. cfg.filtermode ? presel = FILTER : statusbar(path);
  5048. copycurname();
  5049. goto nochange;
  5050. case SEL_RENAME:
  5051. /* Skip renaming to same name */
  5052. if (strcmp(tmp, dents[cur].name) == 0) {
  5053. tmp = xreadline(dents[cur].name, messages[MSG_COPY_NAME]);
  5054. if (!tmp || !tmp[0] || !strcmp(tmp, dents[cur].name)) {
  5055. cfg.filtermode ? presel = FILTER : statusbar(path);
  5056. copycurname();
  5057. goto nochange;
  5058. }
  5059. ret = 'd';
  5060. }
  5061. break;
  5062. default: /* SEL_NEW */
  5063. break;
  5064. }
  5065. /* Open the descriptor to currently open directory */
  5066. #ifdef O_DIRECTORY
  5067. fd = open(path, O_RDONLY | O_DIRECTORY);
  5068. #else
  5069. fd = open(path, O_RDONLY);
  5070. #endif
  5071. if (fd == -1) {
  5072. printwarn(&presel);
  5073. goto nochange;
  5074. }
  5075. /* Check if another file with same name exists */
  5076. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  5077. if (sel == SEL_RENAME) {
  5078. /* Overwrite file with same name? */
  5079. if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
  5080. close(fd);
  5081. break;
  5082. }
  5083. } else {
  5084. /* Do nothing in case of NEW */
  5085. close(fd);
  5086. printwait(messages[MSG_EXISTS], &presel);
  5087. goto nochange;
  5088. }
  5089. }
  5090. if (sel == SEL_RENAME) {
  5091. /* Rename the file */
  5092. if (ret == 'd')
  5093. spawn("cp -rp", dents[cur].name, tmp, path, F_SILENT);
  5094. else if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  5095. close(fd);
  5096. printwarn(&presel);
  5097. goto nochange;
  5098. }
  5099. close(fd);
  5100. xstrsncpy(lastname, tmp, NAME_MAX + 1);
  5101. } else { /* SEL_NEW */
  5102. close(fd);
  5103. presel = 0;
  5104. /* Check if it's a dir or file */
  5105. if (r == 'f') {
  5106. mkpath(path, tmp, newpath);
  5107. ret = xmktree(newpath, FALSE);
  5108. } else if (r == 'd') {
  5109. mkpath(path, tmp, newpath);
  5110. ret = xmktree(newpath, TRUE);
  5111. } else if (r == 's' || r == 'h') {
  5112. if (tmp[0] == '@' && tmp[1] == '\0')
  5113. tmp[0] = '\0';
  5114. ret = xlink(tmp, path, (ndents ? dents[cur].name : NULL),
  5115. newpath, &presel, r);
  5116. }
  5117. if (!ret)
  5118. printwait(messages[MSG_FAILED], &presel);
  5119. if (ret <= 0)
  5120. goto nochange;
  5121. if (r == 'f' || r == 'd')
  5122. xstrsncpy(lastname, tmp, NAME_MAX + 1);
  5123. else if (ndents) {
  5124. if (cfg.filtermode)
  5125. presel = FILTER;
  5126. copycurname();
  5127. }
  5128. clearfilter();
  5129. }
  5130. goto begin;
  5131. }
  5132. case SEL_PLUGIN:
  5133. /* Check if directory is accessible */
  5134. if (!xdiraccess(plugindir)) {
  5135. printwarn(&presel);
  5136. goto nochange;
  5137. }
  5138. r = xstrsncpy(g_buf, messages[MSG_PLUGIN_KEYS], CMD_LEN_MAX);
  5139. printkeys(plug, g_buf + r - 1, maxplug);
  5140. printmsg(g_buf);
  5141. r = get_input(NULL);
  5142. if (r != '\r') {
  5143. endselection();
  5144. tmp = get_kv_val(plug, NULL, r, maxplug, FALSE);
  5145. if (!tmp) {
  5146. printwait(messages[MSG_INVALID_KEY], &presel);
  5147. goto nochange;
  5148. }
  5149. if (tmp[0] == '-' && tmp[1]) {
  5150. ++tmp;
  5151. r = FALSE; /* Do not refresh dir after completion */
  5152. } else
  5153. r = TRUE;
  5154. if (!run_selected_plugin(&path, tmp, (ndents ? dents[cur].name : NULL),
  5155. &lastname, &lastdir)) {
  5156. printwait(messages[MSG_FAILED], &presel);
  5157. goto nochange;
  5158. }
  5159. if (ndents)
  5160. copycurname();
  5161. if (!r) {
  5162. cfg.filtermode ? presel = FILTER : statusbar(path);
  5163. goto nochange;
  5164. }
  5165. } else { /* 'Return/Enter' enters the plugin directory */
  5166. cfg.runplugin ^= 1;
  5167. if (!cfg.runplugin && rundir[0]) {
  5168. /*
  5169. * If toggled, and still in the plugin dir,
  5170. * switch to original directory
  5171. */
  5172. if (strcmp(path, plugindir) == 0) {
  5173. xstrsncpy(path, rundir, PATH_MAX);
  5174. xstrsncpy(lastname, runfile, NAME_MAX);
  5175. rundir[0] = runfile[0] = '\0';
  5176. setdirwatch();
  5177. goto begin;
  5178. }
  5179. /* Otherwise, initiate choosing plugin again */
  5180. cfg.runplugin = 1;
  5181. }
  5182. xstrsncpy(rundir, path, PATH_MAX);
  5183. xstrsncpy(path, plugindir, PATH_MAX);
  5184. if (ndents)
  5185. xstrsncpy(runfile, dents[cur].name, NAME_MAX);
  5186. cfg.runctx = cfg.curctx;
  5187. lastname[0] = '\0';
  5188. }
  5189. setdirwatch();
  5190. clearfilter();
  5191. goto begin;
  5192. case SEL_SHELL: // fallthrough
  5193. case SEL_LAUNCH: // fallthrough
  5194. case SEL_RUNCMD:
  5195. endselection();
  5196. switch (sel) {
  5197. case SEL_SHELL:
  5198. /* Set nnn nesting level */
  5199. tmp = getenv(env_cfg[NNNLVL]);
  5200. setenv(env_cfg[NNNLVL], xitoa((tmp ? atoi(tmp) : 0) + 1), 1);
  5201. setenv(envs[ENV_NCUR], (ndents ? dents[cur].name : ""), 1);
  5202. spawn(shell, NULL, NULL, path, F_CLI);
  5203. setenv(env_cfg[NNNLVL], xitoa(tmp ? atoi(tmp) : 0), 1);
  5204. r = TRUE;
  5205. break;
  5206. case SEL_LAUNCH:
  5207. launch_app(path, newpath);
  5208. r = FALSE;
  5209. break;
  5210. default: /* SEL_RUNCMD */
  5211. r = TRUE;
  5212. #ifndef NORL
  5213. if (cfg.picker) {
  5214. #endif
  5215. tmp = xreadline(NULL, ">>> ");
  5216. #ifndef NORL
  5217. } else {
  5218. presel = 0;
  5219. tmp = getreadline("\n>>> ", path, ipath, &presel);
  5220. if (presel == MSGWAIT)
  5221. goto nochange;
  5222. }
  5223. #endif
  5224. if (tmp && *tmp) // NOLINT
  5225. prompt_run(tmp, (ndents ? dents[cur].name : ""), path);
  5226. else
  5227. r = FALSE;
  5228. }
  5229. /* Continue in type-to-nav mode, if enabled */
  5230. if (cfg.filtermode)
  5231. presel = FILTER;
  5232. /* Save current */
  5233. if (ndents)
  5234. copycurname();
  5235. if (!r)
  5236. goto nochange;
  5237. /* Repopulate as directory content may have changed */
  5238. goto begin;
  5239. case SEL_UMOUNT:
  5240. tmp = ndents ? dents[cur].name : NULL;
  5241. unmount(tmp, newpath, &presel, path);
  5242. goto nochange;
  5243. case SEL_SESSIONS:
  5244. r = get_input(messages[MSG_SSN_OPTS]);
  5245. if (r == 's')
  5246. save_session(FALSE, &presel);
  5247. else if (r == 'l' || r == 'r') {
  5248. if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
  5249. setdirwatch();
  5250. goto begin;
  5251. }
  5252. }
  5253. statusbar(path);
  5254. goto nochange;
  5255. case SEL_EXPORT:
  5256. export_file_list();
  5257. cfg.filtermode ? presel = FILTER : statusbar(path);
  5258. goto nochange;
  5259. case SEL_TIMETYPE:
  5260. if (!set_time_type(&presel))
  5261. goto nochange;
  5262. goto begin;
  5263. case SEL_QUITCTX: // fallthrough
  5264. case SEL_QUITCD: // fallthrough
  5265. case SEL_QUIT:
  5266. case SEL_QUITFAIL:
  5267. if (sel == SEL_QUITCTX) {
  5268. int ctx = cfg.curctx;
  5269. for (r = (ctx + 1) & ~CTX_MAX;
  5270. (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
  5271. r = ((r + 1) & ~CTX_MAX)) {
  5272. };
  5273. if (r != ctx) {
  5274. bool selmode = cfg.selmode ? TRUE : FALSE;
  5275. g_ctx[ctx].c_cfg.ctxactive = 0;
  5276. /* Switch to next active context */
  5277. path = g_ctx[r].c_path;
  5278. lastdir = g_ctx[r].c_last;
  5279. lastname = g_ctx[r].c_name;
  5280. /* Switch light/detail mode */
  5281. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  5282. /* Set the reverse */
  5283. printptr = cfg.showdetail ?
  5284. &printent : &printent_long;
  5285. cfg = g_ctx[r].c_cfg;
  5286. /* Continue selection mode */
  5287. cfg.selmode = selmode;
  5288. cfg.curctx = r;
  5289. setdirwatch();
  5290. goto begin;
  5291. }
  5292. } else if (!(g_states & STATE_FORCEQUIT)) {
  5293. for (r = 0; r < CTX_MAX; ++r)
  5294. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  5295. r = get_input(messages[MSG_QUIT_ALL]);
  5296. break;
  5297. }
  5298. if (!(r == CTX_MAX || xconfirm(r)))
  5299. break; // fallthrough
  5300. }
  5301. /* CD on Quit */
  5302. /* In vim picker mode, clear selection and exit */
  5303. /* Picker mode: reset buffer or clear file */
  5304. if (sel == SEL_QUITCD || getenv("NNN_TMPFILE"))
  5305. cfg.picker ? selbufpos = 0 : write_lastdir(path);
  5306. free(mark);
  5307. return sel == SEL_QUITFAIL ? _FAILURE : _SUCCESS;
  5308. default:
  5309. r = FALSE;
  5310. if (xlines != LINES || xcols != COLS) {
  5311. setdirwatch(); /* Terminal resized */
  5312. r = TRUE;
  5313. } else if (idletimeout && idle == idletimeout)
  5314. lock_terminal(); /* Locker */
  5315. idle = 0;
  5316. if (ndents)
  5317. copycurname();
  5318. if (r)
  5319. continue;
  5320. goto nochange;
  5321. } /* switch (sel) */
  5322. }
  5323. }
  5324. static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
  5325. {
  5326. /* tmpdir holds the full path */
  5327. /* tmp holds the path without the tmp dir prefix */
  5328. int err, ignore = 0;
  5329. struct stat sb;
  5330. char *slash, *tmp;
  5331. ssize_t len = xstrlen(prefix);
  5332. char *tmpdir = malloc(sizeof(char) * (PATH_MAX + TMP_LEN_MAX));
  5333. if (!tmpdir) {
  5334. DPRINTF_S(strerror(errno));
  5335. return NULL;
  5336. }
  5337. tmp = tmpdir + tmpfplen - 1;
  5338. xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
  5339. xstrsncpy(tmp, "/nnnXXXXXX", 11);
  5340. /* Points right after the base tmp dir */
  5341. tmp += 10;
  5342. if (!mkdtemp(tmpdir)) {
  5343. free(tmpdir);
  5344. DPRINTF_S(strerror(errno));
  5345. return NULL;
  5346. }
  5347. listpath = tmpdir;
  5348. for (ssize_t i = 0; i < entries; ++i) {
  5349. if (!paths[i])
  5350. continue;
  5351. err = stat(paths[i], &sb);
  5352. if (err && errno == ENOENT) {
  5353. ignore = 1;
  5354. continue;
  5355. }
  5356. /* Don't copy the common prefix */
  5357. xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
  5358. /* Get the dir containing the path */
  5359. slash = xmemrchr((uchar *)tmp, '/', xstrlen(paths[i]) - len);
  5360. if (slash)
  5361. *slash = '\0';
  5362. xmktree(tmpdir, TRUE);
  5363. if (slash)
  5364. *slash = '/';
  5365. if (symlink(paths[i], tmpdir)) {
  5366. DPRINTF_S(paths[i]);
  5367. DPRINTF_S(strerror(errno));
  5368. }
  5369. }
  5370. if (ignore)
  5371. g_states |= STATE_MSG;
  5372. /* Get the dir in which to start */
  5373. *tmp = '\0';
  5374. return tmpdir;
  5375. }
  5376. static char *load_input()
  5377. {
  5378. /* 512 KiB chunk size */
  5379. ssize_t i, chunk_count = 1, chunk = 512 * 1024, entries = 0;
  5380. char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
  5381. char cwd[PATH_MAX], *next, *tmp;
  5382. size_t offsets[LIST_FILES_MAX];
  5383. char **paths = NULL;
  5384. ssize_t input_read, total_read = 0, off = 0;
  5385. if (!input) {
  5386. DPRINTF_S(strerror(errno));
  5387. return NULL;
  5388. }
  5389. if (!getcwd(cwd, PATH_MAX)) {
  5390. free(input);
  5391. return NULL;
  5392. }
  5393. while (chunk_count < 512) {
  5394. input_read = read(STDIN_FILENO, input + total_read, chunk);
  5395. if (input_read < 0) {
  5396. DPRINTF_S(strerror(errno));
  5397. goto malloc_1;
  5398. }
  5399. if (input_read == 0)
  5400. break;
  5401. total_read += input_read;
  5402. ++chunk_count;
  5403. while (off < total_read) {
  5404. next = memchr(input + off, '\0', total_read - off) + 1;
  5405. if (next == (void *)1)
  5406. break;
  5407. if (next - input == off + 1) {
  5408. off = next - input;
  5409. continue;
  5410. }
  5411. if (entries == LIST_FILES_MAX) {
  5412. fprintf(stderr, messages[MSG_LIMIT], NULL);
  5413. goto malloc_1;
  5414. }
  5415. offsets[entries++] = off;
  5416. off = next - input;
  5417. }
  5418. if (chunk_count == 512) {
  5419. fprintf(stderr, messages[MSG_LIMIT], NULL);
  5420. goto malloc_1;
  5421. }
  5422. /* We don't need to allocate another chunk */
  5423. if (chunk_count == (total_read - input_read) / chunk)
  5424. continue;
  5425. chunk_count = total_read / chunk;
  5426. if (total_read % chunk)
  5427. ++chunk_count;
  5428. if (!(input = xrealloc(input, (chunk_count + 1) * chunk)))
  5429. return NULL;
  5430. }
  5431. if (off != total_read) {
  5432. if (entries == LIST_FILES_MAX) {
  5433. fprintf(stderr, messages[MSG_LIMIT], NULL);
  5434. goto malloc_1;
  5435. }
  5436. offsets[entries++] = off;
  5437. }
  5438. DPRINTF_D(entries);
  5439. DPRINTF_D(total_read);
  5440. DPRINTF_D(chunk_count);
  5441. if (!entries)
  5442. goto malloc_1;
  5443. input[total_read] = '\0';
  5444. paths = malloc(entries * sizeof(char *));
  5445. if (!paths)
  5446. goto malloc_1;
  5447. for (i = 0; i < entries; ++i)
  5448. paths[i] = input + offsets[i];
  5449. prefixpath = malloc(sizeof(char) * PATH_MAX);
  5450. if (!prefixpath)
  5451. goto malloc_1;
  5452. prefixpath[0] = '\0';
  5453. DPRINTF_S(paths[0]);
  5454. for (i = 0; i < entries; ++i) {
  5455. if (paths[i][0] == '\n' || selforparent(paths[i])) {
  5456. paths[i] = NULL;
  5457. continue;
  5458. }
  5459. if (!(paths[i] = abspath(paths[i], cwd))) {
  5460. entries = i; // free from the previous entry
  5461. goto malloc_2;
  5462. }
  5463. DPRINTF_S(paths[i]);
  5464. xstrsncpy(g_buf, paths[i], PATH_MAX);
  5465. if (!common_prefix(xdirname(g_buf), prefixpath)) {
  5466. entries = i + 1; // free from the current entry
  5467. goto malloc_2;
  5468. }
  5469. DPRINTF_S(prefixpath);
  5470. }
  5471. DPRINTF_S(prefixpath);
  5472. if (prefixpath[0]) {
  5473. if (entries == 1) {
  5474. tmp = xmemrchr((uchar *)prefixpath, '/', xstrlen(prefixpath));
  5475. if (!tmp)
  5476. goto malloc_2;
  5477. *(tmp != prefixpath ? tmp : tmp + 1) = '\0';
  5478. }
  5479. tmpdir = make_tmp_tree(paths, entries, prefixpath);
  5480. }
  5481. malloc_2:
  5482. for (i = entries - 1; i >= 0; --i)
  5483. free(paths[i]);
  5484. malloc_1:
  5485. free(input);
  5486. free(paths);
  5487. return tmpdir;
  5488. }
  5489. static void check_key_collision(void)
  5490. {
  5491. int key;
  5492. bool bitmap[KEY_MAX] = {FALSE};
  5493. for (ulong i = 0; i < sizeof(bindings) / sizeof(struct key); ++i) {
  5494. key = bindings[i].sym;
  5495. if (bitmap[key])
  5496. fprintf(stdout, "key collision! [%s]\n", keyname(key));
  5497. else
  5498. bitmap[key] = TRUE;
  5499. }
  5500. }
  5501. static void usage(void)
  5502. {
  5503. fprintf(stdout,
  5504. "%s: nnn [OPTIONS] [PATH]\n\n"
  5505. "The missing terminal file manager for X.\n\n"
  5506. "positional args:\n"
  5507. " PATH start dir [default: .]\n\n"
  5508. "optional args:\n"
  5509. " -A no dir auto-select\n"
  5510. " -b key open bookmark key\n"
  5511. " -c cli-only opener (overrides -e)\n"
  5512. " -d detail mode\n"
  5513. " -e text in $VISUAL/$EDITOR/vi\n"
  5514. " -E use EDITOR for undetached edits\n"
  5515. #ifndef NORL
  5516. " -f use readline history file\n"
  5517. #endif
  5518. " -F show fortune\n"
  5519. " -g regex filters [default: string]\n"
  5520. " -H show hidden files\n"
  5521. " -K detect key collision\n"
  5522. " -n type-to-nav mode\n"
  5523. " -o open files only on Enter\n"
  5524. " -p file selection file [stdout if '-']\n"
  5525. " -Q no quit confirmation\n"
  5526. " -r use advcpmv patched cp, mv\n"
  5527. " -R no rollover at edges\n"
  5528. " -s name load session by name\n"
  5529. " -S du mode\n"
  5530. " -t secs timeout to lock\n"
  5531. " -T key sort order [a/d/e/r/s/t/v]\n"
  5532. " -V show version\n"
  5533. " -x notis, sel to system clipboard\n"
  5534. " -h show help\n\n"
  5535. "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
  5536. }
  5537. static bool setup_config(void)
  5538. {
  5539. size_t r, len;
  5540. char *xdgcfg = getenv("XDG_CONFIG_HOME");
  5541. bool xdg = FALSE;
  5542. /* Set up configuration file paths */
  5543. if (xdgcfg && xdgcfg[0]) {
  5544. DPRINTF_S(xdgcfg);
  5545. if (xdgcfg[0] == '~') {
  5546. r = xstrsncpy(g_buf, home, PATH_MAX);
  5547. xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
  5548. xdgcfg = g_buf;
  5549. DPRINTF_S(xdgcfg);
  5550. }
  5551. if (!xdiraccess(xdgcfg)) {
  5552. xerror();
  5553. return FALSE;
  5554. }
  5555. len = xstrlen(xdgcfg) + 1 + 13; /* add length of "/nnn/sessions" */
  5556. xdg = TRUE;
  5557. }
  5558. if (!xdg)
  5559. len = xstrlen(home) + 1 + 21; /* add length of "/.config/nnn/sessions" */
  5560. cfgdir = (char *)malloc(len);
  5561. plugindir = (char *)malloc(len);
  5562. sessiondir = (char *)malloc(len);
  5563. if (!cfgdir || !plugindir || !sessiondir) {
  5564. xerror();
  5565. return FALSE;
  5566. }
  5567. if (xdg) {
  5568. xstrsncpy(cfgdir, xdgcfg, len);
  5569. r = len - 13; /* subtract length of "/nnn/sessions" */
  5570. } else {
  5571. r = xstrsncpy(cfgdir, home, len);
  5572. /* Create ~/.config */
  5573. xstrsncpy(cfgdir + r - 1, "/.config", len - r);
  5574. DPRINTF_S(cfgdir);
  5575. r += 8; /* length of "/.config" */
  5576. }
  5577. /* Create ~/.config/nnn */
  5578. xstrsncpy(cfgdir + r - 1, "/nnn", len - r);
  5579. DPRINTF_S(cfgdir);
  5580. /* Create ~/.config/nnn/plugins */
  5581. xstrsncpy(plugindir, cfgdir, PATH_MAX);
  5582. xstrsncpy(plugindir + r + 4 - 1, "/plugins", 9); /* subtract length of "/nnn" (4) */
  5583. DPRINTF_S(plugindir);
  5584. if (access(plugindir, F_OK) && !xmktree(plugindir, TRUE)) {
  5585. xerror();
  5586. return FALSE;
  5587. }
  5588. /* Create ~/.config/nnn/sessions */
  5589. xstrsncpy(sessiondir, cfgdir, PATH_MAX);
  5590. xstrsncpy(sessiondir + r + 4 - 1, "/sessions", 10); /* subtract length of "/nnn" (4) */
  5591. DPRINTF_S(sessiondir);
  5592. if (access(sessiondir, F_OK) && !xmktree(sessiondir, TRUE)) {
  5593. xerror();
  5594. return FALSE;
  5595. }
  5596. /* Set selection file path */
  5597. if (!cfg.picker) {
  5598. /* Length of "/.config/nnn/.selection" */
  5599. selpath = (char *)malloc(len + 3);
  5600. if (!selpath) {
  5601. xerror();
  5602. return FALSE;
  5603. }
  5604. r = xstrsncpy(selpath, cfgdir, len + 3);
  5605. xstrsncpy(selpath + r - 1, "/.selection", 12);
  5606. DPRINTF_S(selpath);
  5607. }
  5608. return TRUE;
  5609. }
  5610. static bool set_tmp_path(void)
  5611. {
  5612. char *tmp = "/tmp";
  5613. char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
  5614. if (!path) {
  5615. fprintf(stderr, "set TMPDIR\n");
  5616. return FALSE;
  5617. }
  5618. tmpfplen = (uchar)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
  5619. return TRUE;
  5620. }
  5621. static void cleanup(void)
  5622. {
  5623. free(selpath);
  5624. free(plugindir);
  5625. free(sessiondir);
  5626. free(cfgdir);
  5627. free(initpath);
  5628. free(bmstr);
  5629. free(pluginstr);
  5630. free(prefixpath);
  5631. free(ihashbmp);
  5632. free(bookmark);
  5633. free(plug);
  5634. unlink(g_pipepath);
  5635. #ifdef DBGMODE
  5636. disabledbg();
  5637. #endif
  5638. }
  5639. int main(int argc, char *argv[])
  5640. {
  5641. char *arg = NULL;
  5642. char *session = NULL;
  5643. int opt, sort = 0;
  5644. #ifndef NOMOUSE
  5645. mmask_t mask;
  5646. char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
  5647. if (middle_click_env[0] == '^' && middle_click_env[1])
  5648. middle_click_key = CONTROL(middle_click_env[1]);
  5649. else
  5650. middle_click_key = (uchar)middle_click_env[0];
  5651. #endif
  5652. const char* const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
  5653. int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
  5654. #ifndef NORL
  5655. bool rlhist = FALSE;
  5656. #endif
  5657. while ((opt = (env_opts_id > 0
  5658. ? env_opts[--env_opts_id]
  5659. : getopt(argc, argv, "Ab:cdeEfFgHKnop:QrRs:St:T:Vxh"))) != -1) {
  5660. switch (opt) {
  5661. case 'A':
  5662. cfg.autoselect = 0;
  5663. break;
  5664. case 'b':
  5665. arg = optarg;
  5666. break;
  5667. case 'c':
  5668. cfg.cliopener = 1;
  5669. break;
  5670. case 'S':
  5671. cfg.blkorder = 1;
  5672. nftw_fn = sum_bsize;
  5673. blk_shift = ffs(S_BLKSIZE) - 1; // fallthrough
  5674. case 'd':
  5675. cfg.showdetail = 1;
  5676. printptr = &printent_long;
  5677. break;
  5678. case 'e':
  5679. cfg.useeditor = 1;
  5680. break;
  5681. case 'E':
  5682. cfg.waitedit = 1;
  5683. break;
  5684. case 'f':
  5685. #ifndef NORL
  5686. rlhist = TRUE;
  5687. #endif
  5688. break;
  5689. case 'F':
  5690. g_states |= STATE_FORTUNE;
  5691. break;
  5692. case 'g':
  5693. cfg.regex = 1;
  5694. filterfn = &visible_re;
  5695. break;
  5696. case 'H':
  5697. cfg.showhidden = 1;
  5698. break;
  5699. case 'K':
  5700. check_key_collision();
  5701. return _SUCCESS;
  5702. case 'n':
  5703. cfg.filtermode = 1;
  5704. break;
  5705. case 'o':
  5706. cfg.nonavopen = 1;
  5707. break;
  5708. case 'p':
  5709. if (env_opts_id >= 0)
  5710. break;
  5711. cfg.picker = 1;
  5712. if (optarg[0] == '-' && optarg[1] == '\0')
  5713. cfg.pickraw = 1;
  5714. else {
  5715. int fd = open(optarg, O_WRONLY | O_CREAT, 0600);
  5716. if (fd == -1) {
  5717. xerror();
  5718. return _FAILURE;
  5719. }
  5720. close(fd);
  5721. selpath = realpath(optarg, NULL);
  5722. unlink(selpath);
  5723. }
  5724. break;
  5725. case 'Q':
  5726. g_states |= STATE_FORCEQUIT;
  5727. break;
  5728. case 'r':
  5729. #ifdef __linux__
  5730. cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
  5731. cp[4] = mv[4] = '-';
  5732. #endif
  5733. break;
  5734. case 'R':
  5735. cfg.rollover = 0;
  5736. break;
  5737. case 's':
  5738. if (env_opts_id < 0)
  5739. session = optarg;
  5740. break;
  5741. case 't':
  5742. if (env_opts_id < 0)
  5743. idletimeout = atoi(optarg);
  5744. break;
  5745. case 'T':
  5746. if (env_opts_id < 0)
  5747. sort = (uchar)optarg[0];
  5748. break;
  5749. case 'V':
  5750. fprintf(stdout, "%s\n", VERSION);
  5751. return _SUCCESS;
  5752. case 'x':
  5753. cfg.x11 = 1;
  5754. break;
  5755. case 'h':
  5756. usage();
  5757. return _SUCCESS;
  5758. default:
  5759. usage();
  5760. return _FAILURE;
  5761. }
  5762. }
  5763. #ifdef DBGMODE
  5764. enabledbg();
  5765. DPRINTF_S(VERSION);
  5766. #endif
  5767. /* Prefix for temporary files */
  5768. if (!set_tmp_path())
  5769. return _FAILURE;
  5770. atexit(cleanup);
  5771. if (!cfg.picker) {
  5772. /* Confirm we are in a terminal */
  5773. if (!isatty(STDOUT_FILENO))
  5774. exit(1);
  5775. /* Now we are in path list mode */
  5776. if (!isatty(STDIN_FILENO)) {
  5777. /* This is the same as listpath */
  5778. initpath = load_input();
  5779. if (!initpath)
  5780. exit(1);
  5781. /* We return to tty */
  5782. dup2(STDOUT_FILENO, STDIN_FILENO);
  5783. }
  5784. }
  5785. home = getenv("HOME");
  5786. if (!home) {
  5787. fprintf(stderr, "set HOME\n");
  5788. return _FAILURE;
  5789. }
  5790. DPRINTF_S(home);
  5791. if (!setup_config())
  5792. return _FAILURE;
  5793. /* Get custom opener, if set */
  5794. opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
  5795. DPRINTF_S(opener);
  5796. /* Parse bookmarks string */
  5797. if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
  5798. fprintf(stderr, "%s\n", env_cfg[NNN_BMS]);
  5799. return _FAILURE;
  5800. }
  5801. /* Parse plugins string */
  5802. if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
  5803. fprintf(stderr, "%s\n", env_cfg[NNN_PLUG]);
  5804. return _FAILURE;
  5805. }
  5806. if (!initpath) {
  5807. if (arg) { /* Open a bookmark directly */
  5808. if (!arg[1]) /* Bookmarks keys are single char */
  5809. initpath = get_kv_val(bookmark, NULL, *arg, maxbm, TRUE);
  5810. if (!initpath) {
  5811. fprintf(stderr, "%s\n", messages[MSG_INVALID_KEY]);
  5812. return _FAILURE;
  5813. }
  5814. } else if (argc == optind) {
  5815. /* Start in the current directory */
  5816. initpath = getcwd(NULL, PATH_MAX);
  5817. if (!initpath)
  5818. initpath = "/";
  5819. } else {
  5820. arg = argv[optind];
  5821. DPRINTF_S(arg);
  5822. if (xstrlen(arg) > 7 && !strncmp(arg, "file://", 7))
  5823. arg = arg + 7;
  5824. initpath = realpath(arg, NULL);
  5825. DPRINTF_S(initpath);
  5826. if (!initpath) {
  5827. xerror();
  5828. return _FAILURE;
  5829. }
  5830. /*
  5831. * If nnn is set as the file manager, applications may try to open
  5832. * files by invoking nnn. In that case pass the file path to the
  5833. * desktop opener and exit.
  5834. */
  5835. struct stat sb;
  5836. if (stat(initpath, &sb) == -1) {
  5837. xerror();
  5838. return _FAILURE;
  5839. }
  5840. if (S_ISREG(sb.st_mode)) {
  5841. spawn(opener, arg, NULL, NULL, cfg.cliopener ? F_CLI : F_NOTRACE | F_NOWAIT);
  5842. return _SUCCESS;
  5843. }
  5844. }
  5845. }
  5846. /* Set archive handling (enveditor used as tmp var) */
  5847. enveditor = getenv(env_cfg[NNN_ARCHIVE]);
  5848. #ifdef PCRE
  5849. if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5850. #else
  5851. if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5852. #endif
  5853. fprintf(stderr, "%s\n", messages[MSG_INVALID_REG]);
  5854. return _FAILURE;
  5855. }
  5856. /* An all-CLI opener overrides option -e) */
  5857. if (cfg.cliopener)
  5858. cfg.useeditor = 0;
  5859. /* Get VISUAL/EDITOR */
  5860. enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
  5861. editor = xgetenv(envs[ENV_VISUAL], enveditor);
  5862. DPRINTF_S(getenv(envs[ENV_VISUAL]));
  5863. DPRINTF_S(getenv(envs[ENV_EDITOR]));
  5864. DPRINTF_S(editor);
  5865. /* Get PAGER */
  5866. pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
  5867. DPRINTF_S(pager);
  5868. /* Get SHELL */
  5869. shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
  5870. DPRINTF_S(shell);
  5871. DPRINTF_S(getenv("PWD"));
  5872. #ifdef LINUX_INOTIFY
  5873. /* Initialize inotify */
  5874. inotify_fd = inotify_init1(IN_NONBLOCK);
  5875. if (inotify_fd < 0) {
  5876. xerror();
  5877. return _FAILURE;
  5878. }
  5879. #elif defined(BSD_KQUEUE)
  5880. kq = kqueue();
  5881. if (kq < 0) {
  5882. xerror();
  5883. return _FAILURE;
  5884. }
  5885. #elif defined(HAIKU_NM)
  5886. haiku_hnd = haiku_init_nm();
  5887. if (!haiku_hnd) {
  5888. xerror();
  5889. return _FAILURE;
  5890. }
  5891. #endif
  5892. /* Configure trash preference */
  5893. if (xgetenv_set(env_cfg[NNN_TRASH]))
  5894. g_states |= STATE_TRASH;
  5895. /* Ignore/handle certain signals */
  5896. struct sigaction act = {.sa_handler = sigint_handler};
  5897. if (sigaction(SIGINT, &act, NULL) < 0) {
  5898. xerror();
  5899. return _FAILURE;
  5900. }
  5901. signal(SIGQUIT, SIG_IGN);
  5902. #ifndef NOLOCALE
  5903. /* Set locale */
  5904. setlocale(LC_ALL, "");
  5905. #ifdef PCRE
  5906. tables = pcre_maketables();
  5907. #endif
  5908. #endif
  5909. #ifndef NORL
  5910. #if RL_READLINE_VERSION >= 0x0603
  5911. /* readline would overwrite the WINCH signal hook */
  5912. rl_change_environment = 0;
  5913. #endif
  5914. /* Bind TAB to cycling */
  5915. rl_variable_bind("completion-ignore-case", "on");
  5916. #ifdef __linux__
  5917. rl_bind_key('\t', rl_menu_complete);
  5918. #else
  5919. rl_bind_key('\t', rl_complete);
  5920. #endif
  5921. if (rlhist) {
  5922. mkpath(cfgdir, ".history", g_buf);
  5923. read_history(g_buf);
  5924. }
  5925. #endif
  5926. #ifndef NOMOUSE
  5927. if (!initcurses(&mask))
  5928. #else
  5929. if (!initcurses(NULL))
  5930. #endif
  5931. return _FAILURE;
  5932. if (sort)
  5933. set_sort_flags(sort);
  5934. opt = browse(initpath, session);
  5935. #ifndef NOMOUSE
  5936. mousemask(mask, NULL);
  5937. #endif
  5938. if (listpath)
  5939. spawn("rm -rf", initpath, NULL, NULL, F_SILENT);
  5940. exitcurses();
  5941. #ifndef NORL
  5942. if (rlhist) {
  5943. mkpath(cfgdir, ".history", g_buf);
  5944. write_history(g_buf);
  5945. }
  5946. #endif
  5947. if (cfg.pickraw) {
  5948. if (selbufpos && (seltofile(1, NULL) != (size_t)(selbufpos)))
  5949. xerror();
  5950. } else if (cfg.picker) {
  5951. if (selbufpos)
  5952. writesel(pselbuf, selbufpos - 1);
  5953. } else if (selpath)
  5954. unlink(selpath);
  5955. /* Free the regex */
  5956. #ifdef PCRE
  5957. pcre_free(archive_pcre);
  5958. #else
  5959. regfree(&archive_re);
  5960. #endif
  5961. /* Free the selection buffer */
  5962. free(pselbuf);
  5963. #ifdef LINUX_INOTIFY
  5964. /* Shutdown inotify */
  5965. if (inotify_wd >= 0)
  5966. inotify_rm_watch(inotify_fd, inotify_wd);
  5967. close(inotify_fd);
  5968. #elif defined(BSD_KQUEUE)
  5969. if (event_fd >= 0)
  5970. close(event_fd);
  5971. close(kq);
  5972. #elif defined(HAIKU_NM)
  5973. haiku_close_nm(haiku_hnd);
  5974. #endif
  5975. return opt;
  5976. }