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

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