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

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