My build of nnn with minor changes
 
 
 
 
 
 

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