My build of nnn with minor changes
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

6801 lines
148 KiB

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