My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

7213 rindas
157 KiB

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