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.
 
 
 
 
 
 

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