My build of nnn with minor changes
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

6203 lines
136 KiB

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