My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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