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

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