My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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