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

6360 lignes
139 KiB

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