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.
 
 
 
 
 
 

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