My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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