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

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