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

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