My build of nnn with minor changes
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

4970 satır
108 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-2019, 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. #else
  52. #include <sys/sysmacros.h>
  53. #endif
  54. #include <sys/wait.h>
  55. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  56. #ifndef NCURSES_WIDECHAR
  57. #define NCURSES_WIDECHAR 1
  58. #endif
  59. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  60. #ifndef _XOPEN_SOURCE_EXTENDED
  61. #define _XOPEN_SOURCE_EXTENDED
  62. #endif
  63. #endif
  64. #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  65. #define __USE_XOPEN
  66. #endif
  67. #include <dirent.h>
  68. #include <errno.h>
  69. #include <fcntl.h>
  70. #include <libgen.h>
  71. #include <limits.h>
  72. #ifdef __gnu_hurd__
  73. #define PATH_MAX 4096
  74. #endif
  75. #include <locale.h>
  76. #include <stdio.h>
  77. #ifndef NORL
  78. #include <readline/history.h>
  79. #include <readline/readline.h>
  80. #endif
  81. #include <regex.h>
  82. #include <signal.h>
  83. #include <stdarg.h>
  84. #include <stdlib.h>
  85. #include <string.h>
  86. #include <strings.h>
  87. #include <time.h>
  88. #include <unistd.h>
  89. #ifndef __USE_XOPEN_EXTENDED
  90. #define __USE_XOPEN_EXTENDED 1
  91. #endif
  92. #include <ftw.h>
  93. #include <wchar.h>
  94. #include "nnn.h"
  95. #include "dbg.h"
  96. /* Macro definitions */
  97. #define VERSION "2.6"
  98. #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
  99. #ifndef S_BLKSIZE
  100. #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
  101. #endif
  102. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  103. #undef MIN
  104. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  105. #undef MAX
  106. #define MAX(x, y) ((x) > (y) ? (x) : (y))
  107. #define ISODD(x) ((x) & 1)
  108. #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
  109. #define TOUPPER(ch) \
  110. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  111. #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
  112. #define FILTER '/'
  113. #define MSGWAIT '$'
  114. #define REGEX_MAX 48
  115. #define BM_MAX 10
  116. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  117. #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per filename = 64*32B = 2KB */
  118. #define DESCRIPTOR_LEN 32
  119. #define _ALIGNMENT 0x10 /* 16-byte alignment */
  120. #define _ALIGNMENT_MASK 0xF
  121. #define TMP_LEN_MAX 64
  122. #define CTX_MAX 4
  123. #define DOT_FILTER_LEN 7
  124. #define ASCII_MAX 128
  125. #define EXEC_ARGS_MAX 8
  126. #define SCROLLOFF 3
  127. #define LONG_SIZE sizeof(ulong)
  128. #define ARCHIVE_CMD_LEN 16
  129. /* Program return codes */
  130. #define _SUCCESS 0
  131. #define _FAILURE !_SUCCESS
  132. /* Entry flags */
  133. #define DIR_OR_LINK_TO_DIR 0x1
  134. #define FILE_COPIED 0x10
  135. /* Macros to define process spawn behaviour as flags */
  136. #define F_NONE 0x00 /* no flag set */
  137. #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
  138. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  139. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  140. #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
  141. #define F_CMD 0x10 /* run command - show results before exit (must have F_NORMAL) */
  142. #define F_CLI (F_NORMAL | F_MULTI)
  143. /* CRC8 macros */
  144. #define UCHAR_BIT_WIDTH (sizeof(unsigned char) << 3)
  145. #define TOPBIT (1 << (UCHAR_BIT_WIDTH - 1))
  146. #define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
  147. #define CRC8_TABLE_LEN 256
  148. /* Version compare macros */
  149. /*
  150. * states: S_N: normal, S_I: comparing integral part, S_F: comparing
  151. * fractional parts, S_Z: idem but with leading Zeroes only
  152. */
  153. #define S_N 0x0
  154. #define S_I 0x3
  155. #define S_F 0x6
  156. #define S_Z 0x9
  157. /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
  158. #define VCMP 2
  159. #define VLEN 3
  160. /* Volume info */
  161. #define FREE 0
  162. #define CAPACITY 1
  163. /* TYPE DEFINITIONS */
  164. typedef unsigned long ulong;
  165. typedef unsigned int uint;
  166. typedef unsigned char uchar;
  167. typedef unsigned short ushort;
  168. /* STRUCTURES */
  169. /* Directory entry */
  170. typedef struct entry {
  171. char *name;
  172. time_t t;
  173. off_t size;
  174. blkcnt_t blocks; /* number of 512B blocks allocated */
  175. mode_t mode;
  176. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  177. uchar flags; /* Flags specific to the file */
  178. } __attribute__ ((aligned(_ALIGNMENT))) *pEntry;
  179. /* Bookmark */
  180. typedef struct {
  181. int key;
  182. char *loc;
  183. } bm;
  184. /*
  185. * Settings
  186. * NOTE: update default values if changing order
  187. */
  188. typedef struct {
  189. uint filtermode : 1; /* Set to enter filter mode */
  190. uint mtimeorder : 1; /* Set to sort by time modified */
  191. uint sizeorder : 1; /* Set to sort by file size */
  192. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  193. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  194. uint extnorder : 1; /* Order by extension */
  195. uint showhidden : 1; /* Set to show hidden files */
  196. uint copymode : 1; /* Set when copying files */
  197. uint showdetail : 1; /* Clear to show fewer file info */
  198. uint ctxactive : 1; /* Context active or not */
  199. uint reserved : 7;
  200. /* The following settings are global */
  201. uint curctx : 2; /* Current context number */
  202. uint dircolor : 1; /* Current status of dir color */
  203. uint picker : 1; /* Write selection to user-specified file */
  204. uint pickraw : 1; /* Write selection to sdtout before exit */
  205. uint nonavopen : 1; /* Open file on right arrow or `l` */
  206. uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
  207. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  208. uint useeditor : 1; /* Use VISUAL to open text files */
  209. uint runplugin : 1; /* Choose plugin mode */
  210. uint runctx : 2; /* The context in which plugin is to be run */
  211. uint filter_re : 1; /* Use regex filters */
  212. uint wild : 1; /* Do not sort entries on dir load */
  213. uint trash : 1; /* Move removed files to trash */
  214. } settings;
  215. /* Contexts or workspaces */
  216. typedef struct {
  217. char c_path[PATH_MAX]; /* Current dir */
  218. char c_last[PATH_MAX]; /* Last visited dir */
  219. char c_name[NAME_MAX + 1]; /* Current file name */
  220. char c_fltr[REGEX_MAX]; /* Current filter */
  221. settings c_cfg; /* Current configuration */
  222. uint color; /* Color code for directories */
  223. } context;
  224. /* GLOBALS */
  225. /* Configuration, contexts */
  226. static settings cfg = {
  227. 0, /* filtermode */
  228. 0, /* mtimeorder */
  229. 0, /* sizeorder */
  230. 0, /* apparentsz */
  231. 0, /* blkorder */
  232. 0, /* extnorder */
  233. 0, /* showhidden */
  234. 0, /* copymode */
  235. 0, /* showdetail */
  236. 1, /* ctxactive */
  237. 0, /* reserved */
  238. 0, /* curctx */
  239. 0, /* dircolor */
  240. 0, /* picker */
  241. 0, /* pickraw */
  242. 0, /* nonavopen */
  243. 1, /* autoselect */
  244. 0, /* metaviewer */
  245. 0, /* useeditor */
  246. 0, /* runplugin */
  247. 0, /* runctx */
  248. 1, /* filter_re */
  249. 0, /* wild */
  250. 0, /* trash */
  251. };
  252. static context g_ctx[CTX_MAX] __attribute__ ((aligned));
  253. static int ndents, cur, curscroll, total_dents = ENTRY_INCR;
  254. static int xlines, xcols;
  255. static uint idle;
  256. static uint idletimeout, copybufpos, copybuflen;
  257. static char *bmstr;
  258. static char *opener;
  259. static char *copier;
  260. static char *editor;
  261. static char *pager;
  262. static char *shell;
  263. static char *home;
  264. static char *initpath;
  265. static char *cfgdir;
  266. static char *g_cppath;
  267. static char *plugindir;
  268. static char *pnamebuf, *pcopybuf;
  269. static struct entry *dents;
  270. static blkcnt_t ent_blocks;
  271. static blkcnt_t dir_blocks;
  272. static ulong num_files;
  273. static bm bookmark[BM_MAX];
  274. static size_t g_tmpfplen;
  275. static uchar g_crc;
  276. static uchar BLK_SHIFT = 9;
  277. static bool interrupted = FALSE;
  278. /* Retain old signal handlers */
  279. #ifdef __linux__
  280. static sighandler_t oldsighup; /* old value of hangup signal */
  281. static sighandler_t oldsigtstp; /* old value of SIGTSTP */
  282. #else
  283. static sig_t oldsighup;
  284. static sig_t oldsigtstp;
  285. #endif
  286. /* For use in functions which are isolated and don't return the buffer */
  287. static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
  288. /* Buffer to store tmp file path to show selection, file stats and help */
  289. static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
  290. /* Replace-str for xargs on different platforms */
  291. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  292. #define REPLACE_STR 'J'
  293. #elif defined(__linux__) || defined(__CYGWIN__)
  294. #define REPLACE_STR 'I'
  295. #else
  296. #define REPLACE_STR 'I'
  297. #endif
  298. /* Options to identify file mime */
  299. #ifdef __APPLE__
  300. #define FILE_OPTS "-bIL"
  301. #else
  302. #define FILE_OPTS "-biL"
  303. #endif
  304. /* Macros for utilities */
  305. #define MEDIAINFO 0
  306. #define EXIFTOOL 1
  307. #define OPENER 2
  308. #define ATOOL 3
  309. #define BSDTAR 4
  310. #define UNZIP 5
  311. #define TAR 6
  312. #define LOCKER 7
  313. #define CMATRIX 8
  314. #define NLAUNCH 9
  315. #define UNKNOWN 10
  316. /* Utilities to open files, run actions */
  317. static char * const utils[] = {
  318. "mediainfo",
  319. "exiftool",
  320. #ifdef __APPLE__
  321. "/usr/bin/open",
  322. #elif defined __CYGWIN__
  323. "cygstart",
  324. #else
  325. "xdg-open",
  326. #endif
  327. "atool",
  328. "bsdtar",
  329. "unzip",
  330. "tar",
  331. #ifdef __APPLE__
  332. "bashlock",
  333. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  334. "lock",
  335. #else
  336. "vlock",
  337. #endif
  338. "cmatrix",
  339. "nlaunch",
  340. "UNKNOWN"
  341. };
  342. #ifdef __linux__
  343. static char cp[] = "cpg -giRp";
  344. static char mv[] = "mvg -gi";
  345. #endif
  346. /* Common strings */
  347. #define STR_INPUT_ID 0
  348. #define STR_INVBM_KEY 1
  349. #define STR_DATE_ID 2
  350. #define STR_TMPFILE 3
  351. #define NONE_SELECTED 4
  352. #define UTIL_MISSING 5
  353. static const char * const messages[] = {
  354. "no traversal",
  355. "invalid key",
  356. "%F %T %z",
  357. "/.nnnXXXXXX",
  358. "empty selection",
  359. "utility missing",
  360. };
  361. /* Supported configuration environment variables */
  362. #define NNN_BMS 0
  363. #define NNN_OPENER 1
  364. #define NNN_CONTEXT_COLORS 2
  365. #define NNN_IDLE_TIMEOUT 3
  366. #define NNN_COPIER 4
  367. #define NNN_NOTE 5
  368. #define NNNLVL 6 /* strings end here */
  369. #define NNN_USE_EDITOR 7 /* flags begin here */
  370. #define NNN_NO_AUTOSELECT 8
  371. #define NNN_RESTRICT_NAV_OPEN 9
  372. #define NNN_TRASH 10
  373. #ifdef __linux__
  374. #define NNN_OPS_PROG 11
  375. #endif
  376. static const char * const env_cfg[] = {
  377. "NNN_BMS",
  378. "NNN_OPENER",
  379. "NNN_CONTEXT_COLORS",
  380. "NNN_IDLE_TIMEOUT",
  381. "NNN_COPIER",
  382. "NNN_NOTE",
  383. "NNNLVL",
  384. "NNN_USE_EDITOR",
  385. "NNN_NO_AUTOSELECT",
  386. "NNN_RESTRICT_NAV_OPEN",
  387. "NNN_TRASH",
  388. #ifdef __linux__
  389. "NNN_OPS_PROG",
  390. #endif
  391. };
  392. /* Required environment variables */
  393. #define SHELL 0
  394. #define VISUAL 1
  395. #define EDITOR 2
  396. #define PAGER 3
  397. static const char * const envs[] = {
  398. "SHELL",
  399. "VISUAL",
  400. "EDITOR",
  401. "PAGER",
  402. };
  403. /* Event handling */
  404. #ifdef LINUX_INOTIFY
  405. #define NUM_EVENT_SLOTS 16 /* Make room for 16 events */
  406. #define EVENT_SIZE (sizeof(struct inotify_event))
  407. #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
  408. static int inotify_fd, inotify_wd = -1;
  409. static uint INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
  410. | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  411. #elif defined(BSD_KQUEUE)
  412. #define NUM_EVENT_SLOTS 1
  413. #define NUM_EVENT_FDS 1
  414. static int kq, event_fd = -1;
  415. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  416. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
  417. | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  418. static struct timespec gtimeout;
  419. #endif
  420. /* Function macros */
  421. #define exitcurses() endwin()
  422. #define clearprompt() printmsg("")
  423. #define printwarn(presel) printwait(strerror(errno), presel)
  424. #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
  425. #define copycurname() xstrlcpy(lastname, dents[cur].name, NAME_MAX + 1)
  426. #define settimeout() timeout(1000)
  427. #define cleartimeout() timeout(-1)
  428. #define errexit() printerr(__LINE__)
  429. #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (dir_changed = TRUE))
  430. /* We don't care about the return value from strcmp() */
  431. #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
  432. /* A faster version of xisdigit */
  433. #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
  434. #define xerror() perror(xitoa(__LINE__))
  435. /* Forward declarations */
  436. static void redraw(char *path);
  437. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag);
  438. static int (*nftw_fn)(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  439. static int dentfind(const char *fname, int n);
  440. static void move_cursor(int target, int ignore_scrolloff);
  441. static bool getutil(char *util);
  442. /* Functions */
  443. /*
  444. * CRC8 source:
  445. * https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
  446. */
  447. static uchar crc8fast(const uchar * const message, size_t n)
  448. {
  449. uchar data, remainder = 0;
  450. size_t byte = 0;
  451. /* CRC data */
  452. static const uchar crc8table[CRC8_TABLE_LEN] __attribute__ ((aligned)) = {
  453. 0, 94, 188, 226, 97, 63, 221, 131, 194, 156, 126, 32, 163, 253, 31, 65,
  454. 157, 195, 33, 127, 252, 162, 64, 30, 95, 1, 227, 189, 62, 96, 130, 220,
  455. 35, 125, 159, 193, 66, 28, 254, 160, 225, 191, 93, 3, 128, 222, 60, 98,
  456. 190, 224, 2, 92, 223, 129, 99, 61, 124, 34, 192, 158, 29, 67, 161, 255,
  457. 70, 24, 250, 164, 39, 121, 155, 197, 132, 218, 56, 102, 229, 187, 89, 7,
  458. 219, 133, 103, 57, 186, 228, 6, 88, 25, 71, 165, 251, 120, 38, 196, 154,
  459. 101, 59, 217, 135, 4, 90, 184, 230, 167, 249, 27, 69, 198, 152, 122, 36,
  460. 248, 166, 68, 26, 153, 199, 37, 123, 58, 100, 134, 216, 91, 5, 231, 185,
  461. 140, 210, 48, 110, 237, 179, 81, 15, 78, 16, 242, 172, 47, 113, 147, 205,
  462. 17, 79, 173, 243, 112, 46, 204, 146, 211, 141, 111, 49, 178, 236, 14, 80,
  463. 175, 241, 19, 77, 206, 144, 114, 44, 109, 51, 209, 143, 12, 82, 176, 238,
  464. 50, 108, 142, 208, 83, 13, 239, 177, 240, 174, 76, 18, 145, 207, 45, 115,
  465. 202, 148, 118, 40, 171, 245, 23, 73, 8, 86, 180, 234, 105, 55, 213, 139,
  466. 87, 9, 235, 181, 54, 104, 138, 212, 149, 203, 41, 119, 244, 170, 72, 22,
  467. 233, 183, 85, 11, 136, 214, 52, 106, 43, 117, 151, 201, 74, 20, 246, 168,
  468. 116, 42, 200, 150, 21, 75, 169, 247, 182, 232, 10, 84, 215, 137, 107, 53,
  469. };
  470. /* Divide the message by the polynomial, a byte at a time */
  471. while (byte < n) {
  472. data = message[byte] ^ (remainder >> (UCHAR_BIT_WIDTH - 8));
  473. remainder = crc8table[data] ^ (remainder << 8);
  474. ++byte;
  475. }
  476. /* The final remainder is the CRC */
  477. return remainder;
  478. }
  479. static void sigint_handler(int sig)
  480. {
  481. interrupted = TRUE;
  482. }
  483. static uint xatoi(const char *str)
  484. {
  485. int val = 0;
  486. if (!str)
  487. return 0;
  488. while (xisdigit(*str)) {
  489. val = val * 10 + (*str - '0');
  490. ++str;
  491. }
  492. return val;
  493. }
  494. static char *xitoa(uint val)
  495. {
  496. static char ascbuf[32] = {0};
  497. int i;
  498. for (i = 30; val && i; --i, val /= 10)
  499. ascbuf[i] = '0' + (val % 10);
  500. return &ascbuf[++i];
  501. }
  502. #ifdef KEY_RESIZE
  503. /* Clear the old prompt */
  504. static inline void clearoldprompt()
  505. {
  506. move(xlines - 1, 0);
  507. clrtoeol();
  508. }
  509. #endif
  510. /* Messages show up at the bottom */
  511. static inline void printmsg(const char *msg)
  512. {
  513. mvprintw(xlines - 1, 0, "%s\n", msg);
  514. }
  515. static void printwait(const char *msg, int *presel)
  516. {
  517. printmsg(msg);
  518. if (presel)
  519. *presel = MSGWAIT;
  520. }
  521. /* Kill curses and display error before exiting */
  522. static void printerr(int linenum)
  523. {
  524. exitcurses();
  525. perror(xitoa(linenum));
  526. if (!cfg.picker && g_cppath)
  527. unlink(g_cppath);
  528. free(pcopybuf);
  529. exit(1);
  530. }
  531. /* Print prompt on the last line */
  532. static void printprompt(const char *str)
  533. {
  534. clearprompt();
  535. printw(str);
  536. }
  537. static int get_input(const char *prompt)
  538. {
  539. int r;
  540. if (prompt)
  541. printprompt(prompt);
  542. cleartimeout();
  543. #ifdef KEY_RESIZE
  544. do {
  545. r = getch();
  546. if ( r == KEY_RESIZE) {
  547. if (prompt) {
  548. clearoldprompt();
  549. xlines = LINES;
  550. printprompt(prompt);
  551. }
  552. }
  553. } while ( r == KEY_RESIZE);
  554. #else
  555. r = getch();
  556. #endif
  557. settimeout();
  558. return r;
  559. }
  560. static void xdelay(void)
  561. {
  562. refresh();
  563. usleep(350000); /* 350 ms delay */
  564. }
  565. static char confirm_force(void)
  566. {
  567. int r = get_input("use force? [y/Y confirms]");
  568. if (r == 'y' || r == 'Y')
  569. return 'f'; /* forceful */
  570. return 'i'; /* interactive */
  571. }
  572. /* Increase the limit on open file descriptors, if possible */
  573. static rlim_t max_openfds(void)
  574. {
  575. struct rlimit rl;
  576. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  577. if (limit != 0)
  578. return 32;
  579. limit = rl.rlim_cur;
  580. rl.rlim_cur = rl.rlim_max;
  581. /* Return ~75% of max possible */
  582. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  583. limit = rl.rlim_max - (rl.rlim_max >> 2);
  584. /*
  585. * 20K is arbitrary. If the limit is set to max possible
  586. * value, the memory usage increases to more than double.
  587. */
  588. return limit > 20480 ? 20480 : limit;
  589. }
  590. return limit;
  591. }
  592. /*
  593. * Wrapper to realloc()
  594. * Frees current memory if realloc() fails and returns NULL.
  595. *
  596. * As per the docs, the *alloc() family is supposed to be memory aligned:
  597. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  598. * macOS: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  599. */
  600. static void *xrealloc(void *pcur, size_t len)
  601. {
  602. void *pmem = realloc(pcur, len);
  603. if (!pmem)
  604. free(pcur);
  605. return pmem;
  606. }
  607. /*
  608. * Just a safe strncpy(3)
  609. * Always null ('\0') terminates if both src and dest are valid pointers.
  610. * Returns the number of bytes copied including terminating null byte.
  611. */
  612. static size_t xstrlcpy(char *dest, const char *src, size_t n)
  613. {
  614. if (!src || !dest || !n)
  615. return 0;
  616. ulong *s, *d;
  617. size_t len = strlen(src) + 1, blocks;
  618. const uint _WSHIFT = (LONG_SIZE == 8) ? 3 : 2;
  619. if (n > len)
  620. n = len;
  621. else if (len > n)
  622. /* Save total number of bytes to copy in len */
  623. len = n;
  624. /*
  625. * To enable -O3 ensure src and dest are 16-byte aligned
  626. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  627. */
  628. if ((n >= LONG_SIZE) && (((ulong)src & _ALIGNMENT_MASK) == 0 &&
  629. ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  630. s = (ulong *)src;
  631. d = (ulong *)dest;
  632. blocks = n >> _WSHIFT;
  633. n &= LONG_SIZE - 1;
  634. while (blocks) {
  635. *d = *s; // NOLINT
  636. ++d, ++s;
  637. --blocks;
  638. }
  639. if (!n) {
  640. dest = (char *)d;
  641. *--dest = '\0';
  642. return len;
  643. }
  644. src = (char *)s;
  645. dest = (char *)d;
  646. }
  647. while (--n && (*dest = *src)) // NOLINT
  648. ++dest, ++src;
  649. if (!n)
  650. *dest = '\0';
  651. return len;
  652. }
  653. static bool is_suffix(const char *str, const char *suffix)
  654. {
  655. if (!str || !suffix)
  656. return FALSE;
  657. size_t lenstr = strlen(str);
  658. size_t lensuffix = strlen(suffix);
  659. if (lensuffix > lenstr)
  660. return FALSE;
  661. return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
  662. }
  663. /*
  664. * The poor man's implementation of memrchr(3).
  665. * We are only looking for '/' in this program.
  666. * And we are NOT expecting a '/' at the end.
  667. * Ideally 0 < n <= strlen(s).
  668. */
  669. static void *xmemrchr(uchar *s, uchar ch, size_t n)
  670. {
  671. if (!s || !n)
  672. return NULL;
  673. uchar *ptr = s + n;
  674. do {
  675. --ptr;
  676. if (*ptr == ch)
  677. return ptr;
  678. } while (s != ptr);
  679. return NULL;
  680. }
  681. static char *xbasename(char *path)
  682. {
  683. char *base = xmemrchr((uchar *)path, '/', strlen(path)); // NOLINT
  684. return base ? base + 1 : path;
  685. }
  686. static int create_tmp_file()
  687. {
  688. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - g_tmpfplen);
  689. return mkstemp(g_tmpfpath);
  690. }
  691. /* Writes buflen char(s) from buf to a file */
  692. static void writecp(const char *buf, const size_t buflen)
  693. {
  694. if (cfg.pickraw || !g_cppath)
  695. return;
  696. FILE *fp = fopen(g_cppath, "w");
  697. if (fp) {
  698. if (fwrite(buf, 1, buflen, fp) != buflen)
  699. printwarn(NULL);
  700. fclose(fp);
  701. } else
  702. printwarn(NULL);
  703. }
  704. static void appendfpath(const char *path, const size_t len)
  705. {
  706. if ((copybufpos >= copybuflen) || ((len + 3) > (copybuflen - copybufpos))) {
  707. copybuflen += PATH_MAX;
  708. pcopybuf = xrealloc(pcopybuf, copybuflen);
  709. if (!pcopybuf)
  710. errexit();
  711. }
  712. copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
  713. }
  714. /* Write selected file paths to fd, linefeed separated */
  715. static size_t selectiontofd(int fd, uint *pcount)
  716. {
  717. uint lastpos, count = 0;
  718. char *pbuf = pcopybuf;
  719. size_t pos = 0, len;
  720. ssize_t r;
  721. if (pcount)
  722. *pcount = 0;
  723. if (!copybufpos)
  724. return 0;
  725. lastpos = copybufpos - 1;
  726. while (pos <= lastpos) {
  727. len = strlen(pbuf);
  728. pos += len;
  729. r = write(fd, pbuf, len);
  730. if (r != (ssize_t)len)
  731. return pos;
  732. if (pos <= lastpos) {
  733. if (write(fd, "\n", 1) != 1)
  734. return pos;
  735. pbuf += len + 1;
  736. }
  737. ++pos;
  738. ++count;
  739. }
  740. if (pcount)
  741. *pcount = count;
  742. return pos;
  743. }
  744. /* List selection from selection buffer */
  745. static bool showcplist(void)
  746. {
  747. int fd;
  748. size_t pos;
  749. if (!copybufpos)
  750. return FALSE;
  751. fd = create_tmp_file();
  752. if (fd == -1) {
  753. DPRINTF_S("mkstemp failed!");
  754. return FALSE;
  755. }
  756. pos = selectiontofd(fd, NULL);
  757. close(fd);
  758. if (pos && pos == copybufpos)
  759. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  760. unlink(g_tmpfpath);
  761. return TRUE;
  762. }
  763. /* List selection from selection file (another instance) */
  764. static bool showcpfile(void)
  765. {
  766. struct stat sb;
  767. if (stat(g_cppath, &sb) == -1)
  768. return FALSE;
  769. /* Nothing selected if file size is 0 */
  770. if (!sb.st_size)
  771. return FALSE;
  772. snprintf(g_buf, CMD_LEN_MAX, "cat %s | tr \'\\0\' \'\\n\'", g_cppath);
  773. spawn("sh", "-c", g_buf, NULL, F_NORMAL | F_CMD);
  774. return TRUE;
  775. }
  776. static bool cpsafe(void)
  777. {
  778. /* Fail if selection file path not generated */
  779. if (!g_cppath) {
  780. printmsg("selection file not found");
  781. return FALSE;
  782. }
  783. /* Warn if selection not completed */
  784. if (cfg.copymode) {
  785. printmsg("finish selection first");
  786. return FALSE;
  787. }
  788. /* Fail if selection file path isn't accessible */
  789. if (access(g_cppath, R_OK | W_OK) == -1) {
  790. errno == ENOENT ? printmsg(messages[NONE_SELECTED]) : printwarn(NULL);
  791. return FALSE;
  792. }
  793. return TRUE;
  794. }
  795. /* Reset copy indicators */
  796. static void resetcpind(void)
  797. {
  798. int r = 0;
  799. /* Reset copy indicators */
  800. for (; r < ndents; ++r)
  801. if (dents[r].flags & FILE_COPIED)
  802. dents[r].flags &= ~FILE_COPIED;
  803. }
  804. /* Initialize curses mode */
  805. static bool initcurses(void)
  806. {
  807. short i;
  808. if (cfg.picker) {
  809. if (!newterm(NULL, stderr, stdin)) {
  810. fprintf(stderr, "newterm!\n");
  811. return FALSE;
  812. }
  813. } else if (!initscr()) {
  814. char *term = getenv("TERM");
  815. if (term)
  816. fprintf(stderr, "error opening TERM: %s\n", term);
  817. else
  818. fprintf(stderr, "initscr!\n");
  819. return FALSE;
  820. }
  821. cbreak();
  822. noecho();
  823. nonl();
  824. //intrflush(stdscr, FALSE);
  825. keypad(stdscr, TRUE);
  826. #if NCURSES_MOUSE_VERSION <= 1
  827. mousemask(BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED, NULL);
  828. #else
  829. mousemask(BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED | BUTTON4_PRESSED | BUTTON5_PRESSED, NULL);
  830. #endif
  831. mouseinterval(400);
  832. curs_set(FALSE); /* Hide cursor */
  833. start_color();
  834. use_default_colors();
  835. /* Initialize default colors */
  836. for (i = 0; i < CTX_MAX; ++i)
  837. init_pair(i + 1, g_ctx[i].color, -1);
  838. settimeout(); /* One second */
  839. set_escdelay(25);
  840. return TRUE;
  841. }
  842. /* No NULL check here as spawn() guards against it */
  843. static int parseargs(char *line, char **argv)
  844. {
  845. int count = 0;
  846. argv[count++] = line;
  847. while (*line) { // NOLINT
  848. if (ISBLANK(*line)) {
  849. *line++ = '\0';
  850. if (!*line) // NOLINT
  851. return count;
  852. argv[count++] = line;
  853. if (count == EXEC_ARGS_MAX)
  854. return -1;
  855. }
  856. ++line;
  857. }
  858. return count;
  859. }
  860. static pid_t xfork(uchar flag)
  861. {
  862. pid_t p = fork();
  863. if (p > 0) {
  864. /* the parent ignores the interrupt, quit and hangup signals */
  865. oldsighup = signal(SIGHUP, SIG_IGN);
  866. oldsigtstp = signal(SIGTSTP, SIG_DFL);
  867. } else if (p == 0) {
  868. /* so they can be used to stop the child */
  869. signal(SIGHUP, SIG_DFL);
  870. signal(SIGINT, SIG_DFL);
  871. signal(SIGQUIT, SIG_DFL);
  872. signal(SIGTSTP, SIG_DFL);
  873. if (flag & F_NOWAIT)
  874. setsid();
  875. }
  876. if (p == -1)
  877. perror("fork");
  878. return p;
  879. }
  880. static int join(pid_t p, uchar flag)
  881. {
  882. int status = 0xFFFF;
  883. if (!(flag & F_NOWAIT)) {
  884. /* wait for the child to exit */
  885. do {
  886. } while (waitpid(p, &status, 0) == -1);
  887. if (WIFEXITED(status)) {
  888. status = WEXITSTATUS(status);
  889. DPRINTF_D(status);
  890. }
  891. }
  892. /* restore parent's signal handling */
  893. signal(SIGHUP, oldsighup);
  894. signal(SIGTSTP, oldsigtstp);
  895. return status;
  896. }
  897. /*
  898. * Spawns a child process. Behaviour can be controlled using flag.
  899. * Limited to 2 arguments to a program, flag works on bit set.
  900. */
  901. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag)
  902. {
  903. pid_t pid;
  904. int status, retstatus = 0xFFFF;
  905. char *argv[EXEC_ARGS_MAX] = {0};
  906. char *cmd = NULL;
  907. if (!file || !*file)
  908. return retstatus;
  909. /* Swap args if the first arg is NULL and second isn't */
  910. if (!arg1 && arg2) {
  911. arg1 = arg2;
  912. arg2 = NULL;
  913. }
  914. if (flag & F_MULTI) {
  915. size_t len = strlen(file) + 1;
  916. cmd = (char *)malloc(len);
  917. if (!cmd) {
  918. DPRINTF_S("malloc()!");
  919. return retstatus;
  920. }
  921. xstrlcpy(cmd, file, len);
  922. status = parseargs(cmd, argv);
  923. if (status == -1 || status > (EXEC_ARGS_MAX - 3)) { /* arg1, arg2 and last NULL */
  924. free(cmd);
  925. DPRINTF_S("NULL or too many args");
  926. return retstatus;
  927. }
  928. argv[status++] = arg1;
  929. argv[status] = arg2;
  930. } else {
  931. argv[0] = file;
  932. argv[1] = arg1;
  933. argv[2] = arg2;
  934. }
  935. if (flag & F_NORMAL)
  936. exitcurses();
  937. pid = xfork(flag);
  938. if (pid == 0) {
  939. if (dir && chdir(dir) == -1)
  940. _exit(1);
  941. /* Suppress stdout and stderr */
  942. if (flag & F_NOTRACE) {
  943. int fd = open("/dev/null", O_WRONLY, 0200);
  944. dup2(fd, 1);
  945. dup2(fd, 2);
  946. close(fd);
  947. }
  948. execvp(*argv, argv);
  949. _exit(1);
  950. } else {
  951. retstatus = join(pid, flag);
  952. DPRINTF_D(pid);
  953. if (flag & F_NORMAL) {
  954. if (flag & F_CMD) {
  955. printf("\nPress Enter to continue");
  956. getchar();
  957. }
  958. refresh();
  959. }
  960. free(cmd);
  961. }
  962. return retstatus;
  963. }
  964. /* Get program name from env var, else return fallback program */
  965. static char *xgetenv(const char *name, char *fallback)
  966. {
  967. char *value = getenv(name);
  968. return value && value[0] ? value : fallback;
  969. }
  970. /* Checks if an env variable is set to 1 */
  971. static bool xgetenv_set(const char *name)
  972. {
  973. char *value = getenv(name);
  974. if (value && value[0] == '1' && !value[1])
  975. return TRUE;
  976. return FALSE;
  977. }
  978. /* Check if a dir exists, IS a dir and is readable */
  979. static bool xdiraccess(const char *path)
  980. {
  981. DIR *dirp = opendir(path);
  982. if (!dirp) {
  983. printwarn(NULL);
  984. return FALSE;
  985. }
  986. closedir(dirp);
  987. return TRUE;
  988. }
  989. static void cpstr(char *buf)
  990. {
  991. snprintf(buf, CMD_LEN_MAX,
  992. #ifdef __linux__
  993. "xargs -0 -a %s -%c src %s src .", g_cppath, REPLACE_STR, cp);
  994. #else
  995. "cat %s | xargs -0 -o -%c src cp -iRp src .", g_cppath, REPLACE_STR);
  996. #endif
  997. }
  998. static void mvstr(char *buf)
  999. {
  1000. snprintf(buf, CMD_LEN_MAX,
  1001. #ifdef __linux__
  1002. "xargs -0 -a %s -%c src %s src .", g_cppath, REPLACE_STR, mv);
  1003. #else
  1004. "cat %s | xargs -0 -o -%c src mv -i src .", g_cppath, REPLACE_STR);
  1005. #endif
  1006. }
  1007. static void rmmulstr(char *buf)
  1008. {
  1009. if (cfg.trash) {
  1010. snprintf(buf, CMD_LEN_MAX,
  1011. #ifdef __linux__
  1012. "xargs -0 -a %s trash-put", g_cppath);
  1013. #else
  1014. "cat %s | xargs -0 trash-put", g_cppath);
  1015. #endif
  1016. } else {
  1017. snprintf(buf, CMD_LEN_MAX,
  1018. #ifdef __linux__
  1019. "xargs -0 -a %s rm -%cr", g_cppath, confirm_force());
  1020. #else
  1021. "cat %s | xargs -0 -o rm -%cr", g_cppath, confirm_force());
  1022. #endif
  1023. }
  1024. }
  1025. static void xrm(char *path)
  1026. {
  1027. if (cfg.trash)
  1028. spawn("trash-put", path, NULL, NULL, F_NORMAL);
  1029. else {
  1030. char rm_opts[] = "-ir";
  1031. rm_opts[1] = confirm_force();
  1032. spawn("rm", rm_opts, path, NULL, F_NORMAL);
  1033. }
  1034. }
  1035. static bool batch_rename(const char *path)
  1036. {
  1037. int fd1, fd2, i;
  1038. uint count = 0, lines = 0;
  1039. bool dir = FALSE, ret = FALSE;
  1040. const char renamecmd[] = "awk 'FNR==NR{a[NR]=$0} a[FNR]!=$0{printf \"%%s\\0%%s\\0\",a[FNR],$0}' %s %s | xargs -0 -n2 mv 2>/dev/null";
  1041. char foriginal[TMP_LEN_MAX] = {0};
  1042. char buf[sizeof(renamecmd) + (PATH_MAX << 1)];
  1043. if ((fd1 = create_tmp_file()) == -1)
  1044. return ret;
  1045. xstrlcpy(foriginal, g_tmpfpath, strlen(g_tmpfpath)+1);
  1046. if ((fd2 = create_tmp_file()) == -1) {
  1047. unlink(foriginal);
  1048. close(fd1);
  1049. return ret;
  1050. }
  1051. if (!copybufpos) {
  1052. if (!ndents)
  1053. return TRUE;
  1054. for (i = 0; i < ndents; ++i)
  1055. appendfpath(dents[i].name, NAME_MAX);
  1056. dir = TRUE;
  1057. }
  1058. selectiontofd(fd1, &count);
  1059. selectiontofd(fd2, NULL);
  1060. close(fd2);
  1061. if (dir)
  1062. copybufpos = 0;
  1063. spawn(editor, g_tmpfpath, NULL, path, F_CLI);
  1064. /* Reopen file descriptor to get updated contents */
  1065. if ((fd2 = open(g_tmpfpath, O_RDONLY)) == -1)
  1066. goto finish;
  1067. while ((i = read(fd2, buf, sizeof(buf))) > 0) {
  1068. while (i)
  1069. lines += (buf[--i] == '\n');
  1070. }
  1071. if (i < 0)
  1072. goto finish;
  1073. DPRINTF_U(count);
  1074. DPRINTF_U(lines);
  1075. if (count != lines) {
  1076. DPRINTF_S("cannot delete files");
  1077. goto finish;
  1078. }
  1079. snprintf(buf, sizeof(buf), renamecmd, foriginal, g_tmpfpath);
  1080. spawn("sh", "-c", buf, path, F_NORMAL);
  1081. ret = TRUE;
  1082. finish:
  1083. if (fd1 >= 0)
  1084. close(fd1);
  1085. unlink(foriginal);
  1086. if (fd2 >= 0)
  1087. close(fd2);
  1088. unlink(g_tmpfpath);
  1089. return ret;
  1090. }
  1091. static void get_archive_cmd(char *cmd, char *archive)
  1092. {
  1093. if (getutil(utils[ATOOL]))
  1094. xstrlcpy(cmd, "atool -a", ARCHIVE_CMD_LEN);
  1095. else if (getutil(utils[BSDTAR]))
  1096. xstrlcpy(cmd, "bsdtar -acvf", ARCHIVE_CMD_LEN);
  1097. else if (is_suffix(archive, ".zip"))
  1098. xstrlcpy(cmd, "zip -r", ARCHIVE_CMD_LEN);
  1099. else
  1100. xstrlcpy(cmd, "tar -acvf", ARCHIVE_CMD_LEN);
  1101. }
  1102. static void archive_selection(const char *cmd, const char *archive, const char *curpath)
  1103. {
  1104. char *buf = (char *)malloc(CMD_LEN_MAX * sizeof(char));
  1105. snprintf(buf, CMD_LEN_MAX,
  1106. "awk 'BEGIN{RS=\"\\0\"} {gsub(\"%s/\", \"\", $0); printf \"%%s\\0\", $0}' %s | xargs -0 %s %s", curpath, g_cppath, cmd, archive);
  1107. spawn("sh", "-c", buf, curpath, F_NORMAL);
  1108. free(buf);
  1109. }
  1110. static bool write_lastdir(const char *curpath)
  1111. {
  1112. bool ret = TRUE;
  1113. size_t len = strlen(cfgdir);
  1114. xstrlcpy(cfgdir + len, "/.lastd", 8);
  1115. DPRINTF_S(cfgdir);
  1116. FILE *fp = fopen(cfgdir, "w");
  1117. if (fp) {
  1118. if (fprintf(fp, "cd \"%s\"", curpath) < 0)
  1119. ret = FALSE;
  1120. fclose(fp);
  1121. } else
  1122. ret = FALSE;
  1123. return ret;
  1124. }
  1125. static int digit_compare(const char *a, const char *b)
  1126. {
  1127. while (*a && *b && *a == *b)
  1128. ++a, ++b;
  1129. return *a - *b;
  1130. }
  1131. /*
  1132. * We assume none of the strings are NULL.
  1133. *
  1134. * Let's have the logic to sort numeric names in numeric order.
  1135. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  1136. *
  1137. * If the absolute numeric values are same, we fallback to alphasort.
  1138. */
  1139. static int xstricmp(const char * const s1, const char * const s2)
  1140. {
  1141. const char *c1 = s1, *c2 = s2, *m1, *m2;
  1142. int count1 = 0, count2 = 0, bias;
  1143. char sign[2] = {'+', '+'};
  1144. while (ISBLANK(*c1))
  1145. ++c1;
  1146. while (ISBLANK(*c2))
  1147. ++c2;
  1148. if (*c1 == '-' || *c1 == '+') {
  1149. if (*c1 == '-')
  1150. sign[0] = '-';
  1151. ++c1;
  1152. }
  1153. if (*c2 == '-' || *c2 == '+') {
  1154. if (*c2 == '-')
  1155. sign[1] = '-';
  1156. ++c2;
  1157. }
  1158. if (xisdigit(*c1) && xisdigit(*c2)) {
  1159. while (*c1 == '0')
  1160. ++c1;
  1161. m1 = c1;
  1162. while (*c2 == '0')
  1163. ++c2;
  1164. m2 = c2;
  1165. while (xisdigit(*c1)) {
  1166. ++count1;
  1167. ++c1;
  1168. }
  1169. while (ISBLANK(*c1))
  1170. ++c1;
  1171. while (xisdigit(*c2)) {
  1172. ++count2;
  1173. ++c2;
  1174. }
  1175. while (ISBLANK(*c2))
  1176. ++c2;
  1177. if (*c1 && !*c2)
  1178. return 1;
  1179. if (!*c1 && *c2)
  1180. return -1;
  1181. if (!*c1 && !*c2) {
  1182. if (sign[0] != sign[1])
  1183. return ((sign[0] == '+') ? 1 : -1);
  1184. if (count1 > count2)
  1185. return 1;
  1186. if (count1 < count2)
  1187. return -1;
  1188. bias = digit_compare(m1, m2);
  1189. if (bias)
  1190. return bias;
  1191. }
  1192. }
  1193. return strcoll(s1, s2);
  1194. }
  1195. /*
  1196. * Version comparison
  1197. *
  1198. * The code for version compare is a modified version of the GLIBC
  1199. * and uClibc implementation of strverscmp(). The source is here:
  1200. * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
  1201. */
  1202. /*
  1203. * Compare S1 and S2 as strings holding indices/version numbers,
  1204. * returning less than, equal to or greater than zero if S1 is less than,
  1205. * equal to or greater than S2 (for more info, see the texinfo doc).
  1206. *
  1207. * Ignores case.
  1208. */
  1209. static int xstrverscasecmp(const char * const s1, const char * const s2)
  1210. {
  1211. const uchar *p1 = (const uchar *)s1;
  1212. const uchar *p2 = (const uchar *)s2;
  1213. uchar c1, c2;
  1214. int state, diff;
  1215. /*
  1216. * Symbol(s) 0 [1-9] others
  1217. * Transition (10) 0 (01) d (00) x
  1218. */
  1219. static const uint8_t next_state[] = {
  1220. /* state x d 0 */
  1221. /* S_N */ S_N, S_I, S_Z,
  1222. /* S_I */ S_N, S_I, S_I,
  1223. /* S_F */ S_N, S_F, S_F,
  1224. /* S_Z */ S_N, S_F, S_Z
  1225. };
  1226. static const int8_t result_type[] __attribute__ ((aligned)) = {
  1227. /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
  1228. /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
  1229. /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
  1230. /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
  1231. /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
  1232. };
  1233. if (p1 == p2)
  1234. return 0;
  1235. c1 = TOUPPER(*p1);
  1236. ++p1;
  1237. c2 = TOUPPER(*p2);
  1238. ++p2;
  1239. /* Hint: '0' is a digit too. */
  1240. state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
  1241. while ((diff = c1 - c2) == 0) {
  1242. if (c1 == '\0')
  1243. return diff;
  1244. state = next_state[state];
  1245. c1 = TOUPPER(*p1);
  1246. ++p1;
  1247. c2 = TOUPPER(*p2);
  1248. ++p2;
  1249. state += (c1 == '0') + (xisdigit(c1) != 0);
  1250. }
  1251. state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))];
  1252. switch (state) {
  1253. case VCMP:
  1254. return diff;
  1255. case VLEN:
  1256. while (xisdigit(*p1++))
  1257. if (!xisdigit(*p2++))
  1258. return 1;
  1259. return xisdigit(*p2) ? -1 : diff;
  1260. default:
  1261. return state;
  1262. }
  1263. }
  1264. static int (*cmpfn)(const char * const s1, const char * const s2) = &xstricmp;
  1265. /* Return the integer value of a char representing HEX */
  1266. static char xchartohex(char c)
  1267. {
  1268. if (xisdigit(c))
  1269. return c - '0';
  1270. c = TOUPPER(c);
  1271. if (c >= 'A' && c <= 'F')
  1272. return c - 'A' + 10;
  1273. return c;
  1274. }
  1275. static int setfilter(regex_t *regex, const char *filter)
  1276. {
  1277. int r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  1278. if (r != 0 && filter && filter[0] != '\0')
  1279. mvprintw(xlines - 1, 0, "regex error: %d\n", r);
  1280. return r;
  1281. }
  1282. static int visible_re(regex_t *regex, const char *fname, const char *fltr)
  1283. {
  1284. return regexec(regex, fname, 0, NULL, 0) == 0;
  1285. }
  1286. static int visible_str(regex_t *regex, const char *fname, const char *fltr)
  1287. {
  1288. return strcasestr(fname, fltr) != NULL;
  1289. }
  1290. static int (*filterfn)(regex_t *regex, const char *fname, const char *fltr) = &visible_re;
  1291. static int entrycmp(const void *va, const void *vb)
  1292. {
  1293. const struct entry *pa = (pEntry)va;
  1294. const struct entry *pb = (pEntry)vb;
  1295. if ((pb->flags & DIR_OR_LINK_TO_DIR) != (pa->flags & DIR_OR_LINK_TO_DIR)) {
  1296. if (pb->flags & DIR_OR_LINK_TO_DIR)
  1297. return 1;
  1298. return -1;
  1299. }
  1300. /* Sort based on specified order */
  1301. if (cfg.mtimeorder) {
  1302. if (pb->t > pa->t)
  1303. return 1;
  1304. if (pb->t < pa->t)
  1305. return -1;
  1306. } else if (cfg.sizeorder) {
  1307. if (pb->size > pa->size)
  1308. return 1;
  1309. if (pb->size < pa->size)
  1310. return -1;
  1311. } else if (cfg.blkorder) {
  1312. if (pb->blocks > pa->blocks)
  1313. return 1;
  1314. if (pb->blocks < pa->blocks)
  1315. return -1;
  1316. } else if (cfg.extnorder && !(pb->flags & DIR_OR_LINK_TO_DIR)) {
  1317. char *extna = xmemrchr((uchar *)pa->name, '.', strlen(pa->name));
  1318. char *extnb = xmemrchr((uchar *)pb->name, '.', strlen(pb->name));
  1319. if (extna || extnb) {
  1320. if (!extna)
  1321. return 1;
  1322. if (!extnb)
  1323. return -1;
  1324. int ret = strcasecmp(extna, extnb);
  1325. if (ret)
  1326. return ret;
  1327. }
  1328. }
  1329. return cmpfn(pa->name, pb->name);
  1330. }
  1331. /*
  1332. * Returns SEL_* if key is bound and 0 otherwise.
  1333. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  1334. * The next keyboard input can be simulated by presel.
  1335. */
  1336. static int nextsel(int presel)
  1337. {
  1338. int c = presel;
  1339. uint i;
  1340. const uint len = LEN(bindings);
  1341. #ifdef LINUX_INOTIFY
  1342. struct inotify_event *event;
  1343. char inotify_buf[EVENT_BUF_LEN];
  1344. memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
  1345. #elif defined(BSD_KQUEUE)
  1346. struct kevent event_data[NUM_EVENT_SLOTS];
  1347. memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
  1348. #endif
  1349. if (c == 0 || c == MSGWAIT) {
  1350. c = getch();
  1351. DPRINTF_D(c);
  1352. if (presel == MSGWAIT) {
  1353. if (cfg.filtermode)
  1354. c = FILTER;
  1355. else
  1356. c = CONTROL('L');
  1357. }
  1358. }
  1359. if (c == -1) {
  1360. ++idle;
  1361. /*
  1362. * Do not check for directory changes in du mode.
  1363. * A redraw forces du calculation.
  1364. * Check for changes every odd second.
  1365. */
  1366. #ifdef LINUX_INOTIFY
  1367. if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
  1368. i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
  1369. if (i > 0) {
  1370. char *ptr;
  1371. for (ptr = inotify_buf;
  1372. ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
  1373. ptr += sizeof(struct inotify_event) + event->len) {
  1374. event = (struct inotify_event *) ptr;
  1375. DPRINTF_D(event->wd);
  1376. DPRINTF_D(event->mask);
  1377. if (!event->wd)
  1378. break;
  1379. if (event->mask & INOTIFY_MASK) {
  1380. c = CONTROL('L');
  1381. DPRINTF_S("issue refresh");
  1382. break;
  1383. }
  1384. }
  1385. DPRINTF_S("inotify read done");
  1386. }
  1387. }
  1388. #elif defined(BSD_KQUEUE)
  1389. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  1390. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
  1391. event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  1392. c = CONTROL('L');
  1393. #endif
  1394. } else
  1395. idle = 0;
  1396. for (i = 0; i < len; ++i)
  1397. if (c == bindings[i].sym)
  1398. return bindings[i].act;
  1399. return 0;
  1400. }
  1401. static inline void swap_ent(int id1, int id2)
  1402. {
  1403. struct entry _dent, *pdent1 = &dents[id1], *pdent2 = &dents[id2];
  1404. *(&_dent) = *pdent1;
  1405. *pdent1 = *pdent2;
  1406. *pdent2 = *(&_dent);
  1407. }
  1408. /*
  1409. * Move non-matching entries to the end
  1410. */
  1411. static int fill(const char *fltr, regex_t *re)
  1412. {
  1413. int count = 0;
  1414. for (; count < ndents; ++count) {
  1415. if (filterfn(re, dents[count].name, fltr) == 0) {
  1416. if (count != --ndents) {
  1417. swap_ent(count, ndents);
  1418. --count;
  1419. }
  1420. continue;
  1421. }
  1422. }
  1423. return ndents;
  1424. }
  1425. static int matches(const char *fltr)
  1426. {
  1427. regex_t re;
  1428. /* Search filter */
  1429. if (cfg.filter_re && setfilter(&re, fltr) != 0)
  1430. return -1;
  1431. ndents = fill(fltr, &re);
  1432. if (cfg.filter_re)
  1433. regfree(&re);
  1434. if (!ndents)
  1435. return 0;
  1436. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1437. return 0;
  1438. }
  1439. static int filterentries(char *path)
  1440. {
  1441. wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
  1442. char *ln = g_ctx[cfg.curctx].c_fltr;
  1443. wint_t ch[2] = {0};
  1444. int r, total = ndents, oldcur = cur, len;
  1445. char *pln = g_ctx[cfg.curctx].c_fltr + 1;
  1446. cur = 0;
  1447. if (ndents && ln[0] == FILTER && *pln) {
  1448. if (matches(pln) != -1)
  1449. redraw(path);
  1450. len = mbstowcs(wln, ln, REGEX_MAX);
  1451. } else {
  1452. ln[0] = wln[0] = FILTER;
  1453. ln[1] = wln[1] = '\0';
  1454. len = 1;
  1455. }
  1456. cleartimeout();
  1457. curs_set(TRUE);
  1458. printprompt(ln);
  1459. while ((r = get_wch(ch)) != ERR) {
  1460. switch (*ch) {
  1461. #ifdef KEY_RESIZE
  1462. case KEY_RESIZE:
  1463. clearoldprompt();
  1464. if (len == 1) {
  1465. cur = oldcur;
  1466. redraw(path);
  1467. cur = 0;
  1468. } else
  1469. redraw(path);
  1470. printprompt(ln);
  1471. continue;
  1472. #endif
  1473. case KEY_DC: // fallthrough
  1474. case KEY_BACKSPACE: // fallthrough
  1475. case '\b': // fallthrough
  1476. case CONTROL('L'): // fallthrough
  1477. case 127: /* handle DEL */
  1478. if (len == 1 && *ch != CONTROL('L')) {
  1479. cur = oldcur;
  1480. *ch = CONTROL('L');
  1481. goto end;
  1482. }
  1483. if (*ch == CONTROL('L'))
  1484. while (len > 1)
  1485. wln[--len] = '\0';
  1486. else
  1487. wln[--len] = '\0';
  1488. if (len == 1)
  1489. cur = oldcur;
  1490. wcstombs(ln, wln, REGEX_MAX);
  1491. ndents = total;
  1492. if (matches(pln) != -1)
  1493. redraw(path);
  1494. printprompt(ln);
  1495. continue;
  1496. case KEY_MOUSE: // fallthrough
  1497. case 27: /* Exit filter mode on Escape */
  1498. if (len == 1)
  1499. cur = oldcur;
  1500. goto end;
  1501. }
  1502. if (r == OK) {
  1503. /* Handle all control chars in main loop */
  1504. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^') {
  1505. if (len == 1)
  1506. cur = oldcur;
  1507. goto end;
  1508. }
  1509. switch (*ch) {
  1510. case '\r': /* with nonl(), this is ENTER key value */
  1511. if (len == 1) {
  1512. cur = oldcur;
  1513. goto end;
  1514. }
  1515. if (matches(pln) == -1)
  1516. goto end;
  1517. redraw(path);
  1518. goto end;
  1519. case '/': /* works as Leader key in filter mode */
  1520. *ch = CONTROL('_'); // fallthrough
  1521. if (len == 1)
  1522. cur = oldcur;
  1523. goto end;
  1524. case '?': /* '?' is an invalid regex, show help instead */
  1525. if (len == 1) {
  1526. cur = oldcur;
  1527. goto end;
  1528. } // fallthrough
  1529. default:
  1530. /* Reset cur in case it's a repeat search */
  1531. if (len == 1)
  1532. cur = 0;
  1533. if (len == REGEX_MAX - 1)
  1534. break;
  1535. wln[len] = (wchar_t)*ch;
  1536. wln[++len] = '\0';
  1537. wcstombs(ln, wln, REGEX_MAX);
  1538. /* Forward-filtering optimization:
  1539. * - new matches can only be a subset of current matches.
  1540. */
  1541. /* ndents = total; */
  1542. if (matches(pln) == -1)
  1543. continue;
  1544. /* If the only match is a dir, auto-select and cd into it */
  1545. if (ndents == 1 && cfg.filtermode
  1546. && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  1547. *ch = KEY_ENTER;
  1548. cur = 0;
  1549. goto end;
  1550. }
  1551. /*
  1552. * redraw() should be above the auto-select optimization, for
  1553. * the case where there's an issue with dir auto-select, say,
  1554. * due to a permission problem. The transition is _jumpy_ in
  1555. * case of such an error. However, we optimize for successful
  1556. * cases where the dir has permissions. This skips a redraw().
  1557. */
  1558. redraw(path);
  1559. printprompt(ln);
  1560. }
  1561. } else {
  1562. if (len == 1)
  1563. cur = oldcur;
  1564. goto end;
  1565. }
  1566. }
  1567. end:
  1568. if (*ch != '\t')
  1569. g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  1570. move_cursor(cur, 0);
  1571. curs_set(FALSE);
  1572. settimeout();
  1573. /* Return keys for navigation etc. */
  1574. return *ch;
  1575. }
  1576. /* Show a prompt with input string and return the changes */
  1577. static char *xreadline(char *prefill, char *prompt)
  1578. {
  1579. size_t len, pos;
  1580. int x, r;
  1581. const int WCHAR_T_WIDTH = sizeof(wchar_t);
  1582. wint_t ch[2] = {0};
  1583. wchar_t * const buf = malloc(sizeof(wchar_t) * CMD_LEN_MAX);
  1584. if (!buf)
  1585. errexit();
  1586. cleartimeout();
  1587. printprompt(prompt);
  1588. if (prefill) {
  1589. DPRINTF_S(prefill);
  1590. len = pos = mbstowcs(buf, prefill, CMD_LEN_MAX);
  1591. } else
  1592. len = (size_t)-1;
  1593. if (len == (size_t)-1) {
  1594. buf[0] = '\0';
  1595. len = pos = 0;
  1596. }
  1597. x = getcurx(stdscr);
  1598. curs_set(TRUE);
  1599. while (1) {
  1600. buf[len] = ' ';
  1601. mvaddnwstr(xlines - 1, x, buf, len + 1);
  1602. move(xlines - 1, x + wcswidth(buf, pos));
  1603. r = get_wch(ch);
  1604. if (r != ERR) {
  1605. if (r == OK) {
  1606. switch (*ch) {
  1607. case KEY_ENTER: // fallthrough
  1608. case '\n': // fallthrough
  1609. case '\r':
  1610. goto END;
  1611. case 127: // fallthrough
  1612. case '\b': /* rhel25 sends '\b' for backspace */
  1613. if (pos > 0) {
  1614. memmove(buf + pos - 1, buf + pos,
  1615. (len - pos) * WCHAR_T_WIDTH);
  1616. --len, --pos;
  1617. } // fallthrough
  1618. case '\t': /* TAB breaks cursor position, ignore it */
  1619. continue;
  1620. case CONTROL('L'):
  1621. printprompt(prompt);
  1622. len = pos = 0;
  1623. continue;
  1624. case CONTROL('A'):
  1625. pos = 0;
  1626. continue;
  1627. case CONTROL('E'):
  1628. pos = len;
  1629. continue;
  1630. case CONTROL('U'):
  1631. printprompt(prompt);
  1632. memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
  1633. len -= pos;
  1634. pos = 0;
  1635. continue;
  1636. case 27: /* Exit prompt on Escape */
  1637. len = 0;
  1638. goto END;
  1639. }
  1640. /* Filter out all other control chars */
  1641. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
  1642. continue;
  1643. if (pos < CMD_LEN_MAX - 1) {
  1644. memmove(buf + pos + 1, buf + pos,
  1645. (len - pos) * WCHAR_T_WIDTH);
  1646. buf[pos] = *ch;
  1647. ++len, ++pos;
  1648. continue;
  1649. }
  1650. } else {
  1651. switch (*ch) {
  1652. #ifdef KEY_RESIZE
  1653. case KEY_RESIZE:
  1654. clearoldprompt();
  1655. xlines = LINES;
  1656. printprompt(prompt);
  1657. break;
  1658. #endif
  1659. case KEY_LEFT:
  1660. if (pos > 0)
  1661. --pos;
  1662. break;
  1663. case KEY_RIGHT:
  1664. if (pos < len)
  1665. ++pos;
  1666. break;
  1667. case KEY_BACKSPACE:
  1668. if (pos > 0) {
  1669. memmove(buf + pos - 1, buf + pos,
  1670. (len - pos) * WCHAR_T_WIDTH);
  1671. --len, --pos;
  1672. }
  1673. break;
  1674. case KEY_DC:
  1675. if (pos < len) {
  1676. memmove(buf + pos, buf + pos + 1,
  1677. (len - pos - 1) * WCHAR_T_WIDTH);
  1678. --len;
  1679. }
  1680. break;
  1681. case KEY_END:
  1682. pos = len;
  1683. break;
  1684. case KEY_HOME:
  1685. pos = 0;
  1686. break;
  1687. default:
  1688. break;
  1689. }
  1690. }
  1691. }
  1692. }
  1693. END:
  1694. curs_set(FALSE);
  1695. settimeout();
  1696. clearprompt();
  1697. buf[len] = '\0';
  1698. pos = wcstombs(g_buf, buf, CMD_LEN_MAX - 1);
  1699. if (pos >= CMD_LEN_MAX - 1)
  1700. g_buf[CMD_LEN_MAX - 1] = '\0';
  1701. free(buf);
  1702. return g_buf;
  1703. }
  1704. #ifndef NORL
  1705. /*
  1706. * Caller should check the value of presel to confirm if it needs to wait to show warning
  1707. */
  1708. static char *getreadline(char *prompt, char *path, char *curpath, int *presel)
  1709. {
  1710. /* Switch to current path for readline(3) */
  1711. if (chdir(path) == -1) {
  1712. printwarn(presel);
  1713. return NULL;
  1714. }
  1715. exitcurses();
  1716. char *input = readline(prompt);
  1717. refresh();
  1718. if (chdir(curpath) == -1) {
  1719. printwarn(presel);
  1720. free(input);
  1721. return NULL;
  1722. }
  1723. if (input && input[0]) {
  1724. add_history(input);
  1725. xstrlcpy(g_buf, input, CMD_LEN_MAX);
  1726. free(input);
  1727. return g_buf;
  1728. }
  1729. free(input);
  1730. return NULL;
  1731. }
  1732. #endif
  1733. /*
  1734. * Updates out with "dir/name or "/name"
  1735. * Returns the number of bytes copied including the terminating NULL byte
  1736. */
  1737. static size_t mkpath(char *dir, char *name, char *out)
  1738. {
  1739. size_t len;
  1740. /* Handle absolute path */
  1741. if (name[0] == '/')
  1742. return xstrlcpy(out, name, PATH_MAX);
  1743. /* Handle root case */
  1744. if (istopdir(dir))
  1745. len = 1;
  1746. else
  1747. len = xstrlcpy(out, dir, PATH_MAX);
  1748. out[len - 1] = '/'; // NOLINT
  1749. return (xstrlcpy(out + len, name, PATH_MAX - len) + len);
  1750. }
  1751. /*
  1752. * Create symbolic/hard link(s) to file(s) in selection list
  1753. * Returns the number of links created
  1754. */
  1755. static int xlink(char *suffix, char *path, char *buf, int *presel, int type)
  1756. {
  1757. int count = 0;
  1758. char *pbuf = pcopybuf, *fname;
  1759. size_t pos = 0, len, r;
  1760. int (*link_fn)(const char *, const char *) = NULL;
  1761. /* Check if selection is empty */
  1762. if (!copybufpos) {
  1763. printwait(messages[NONE_SELECTED], presel);
  1764. return -1;
  1765. }
  1766. if (type == 's') /* symbolic link */
  1767. link_fn = &symlink;
  1768. else /* hard link */
  1769. link_fn = &link;
  1770. while (pos < copybufpos) {
  1771. len = strlen(pbuf);
  1772. fname = xbasename(pbuf);
  1773. r = mkpath(path, fname, buf);
  1774. xstrlcpy(buf + r - 1, suffix, PATH_MAX - r - 1);
  1775. if (!link_fn(pbuf, buf))
  1776. ++count;
  1777. pos += len + 1;
  1778. pbuf += len + 1;
  1779. }
  1780. if (!count)
  1781. printwait("none created", presel);
  1782. return count;
  1783. }
  1784. static bool parsebmstr(void)
  1785. {
  1786. int i = 0;
  1787. char *nextkey;
  1788. char *bms = getenv(env_cfg[NNN_BMS]);
  1789. if (!bms || !*bms)
  1790. return TRUE;
  1791. bmstr = strdup(bms);
  1792. bms = bmstr;
  1793. nextkey = bms;
  1794. while (*bms && i < BM_MAX) {
  1795. if (bms == nextkey) {
  1796. bookmark[i].key = *bms;
  1797. if (*++bms != ':')
  1798. return FALSE;
  1799. if (*++bms == '\0')
  1800. return FALSE;
  1801. bookmark[i].loc = bms;
  1802. ++i;
  1803. }
  1804. if (*bms == ';') {
  1805. /* Remove trailing space */
  1806. if (i > 0 && *(bms - 1) == '/')
  1807. *(bms - 1) = '\0';
  1808. *bms = '\0';
  1809. nextkey = bms + 1;
  1810. }
  1811. ++bms;
  1812. }
  1813. if (i < BM_MAX) {
  1814. if (*bookmark[i - 1].loc == '\0')
  1815. return FALSE;
  1816. bookmark[i].key = '\0';
  1817. }
  1818. return TRUE;
  1819. }
  1820. /*
  1821. * Get the real path to a bookmark
  1822. *
  1823. * NULL is returned in case of no match, path resolution failure etc.
  1824. * buf would be modified, so check return value before access
  1825. */
  1826. static char *get_bm_loc(char *buf, int key)
  1827. {
  1828. int r = 0;
  1829. for (; bookmark[r].key && r < BM_MAX; ++r) {
  1830. if (bookmark[r].key == key) {
  1831. if (bookmark[r].loc[0] == '~') {
  1832. ssize_t len = strlen(home);
  1833. ssize_t loclen = strlen(bookmark[r].loc);
  1834. if (!buf)
  1835. buf = (char *)malloc(len + loclen);
  1836. xstrlcpy(buf, home, len + 1);
  1837. xstrlcpy(buf + len, bookmark[r].loc + 1, loclen);
  1838. return buf;
  1839. }
  1840. return realpath(bookmark[r].loc, buf);
  1841. }
  1842. }
  1843. DPRINTF_S("Invalid key");
  1844. return NULL;
  1845. }
  1846. static inline void resetdircolor(int flags)
  1847. {
  1848. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  1849. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  1850. cfg.dircolor = 0;
  1851. }
  1852. }
  1853. /*
  1854. * Replace escape characters in a string with '?'
  1855. * Adjust string length to maxcols if > 0;
  1856. * Max supported str length: NAME_MAX;
  1857. *
  1858. * Interestingly, note that unescape() uses g_buf. What happens if
  1859. * str also points to g_buf? In this case we assume that the caller
  1860. * acknowledges that it's OK to lose the data in g_buf after this
  1861. * call to unescape().
  1862. * The API, on its part, first converts str to multibyte (after which
  1863. * it doesn't touch str anymore). Only after that it starts modifying
  1864. * g_buf. This is a phased operation.
  1865. */
  1866. static char *unescape(const char *str, uint maxcols)
  1867. {
  1868. static wchar_t wbuf[NAME_MAX + 1] __attribute__ ((aligned));
  1869. wchar_t *buf = wbuf;
  1870. size_t lencount = 0;
  1871. /* Convert multi-byte to wide char */
  1872. size_t len = mbstowcs(wbuf, str, NAME_MAX);
  1873. while (*buf && lencount <= maxcols) {
  1874. if (*buf <= '\x1f' || *buf == '\x7f')
  1875. *buf = '\?';
  1876. ++buf;
  1877. ++lencount;
  1878. }
  1879. len = lencount = wcswidth(wbuf, len);
  1880. /* Reduce number of wide chars to max columns */
  1881. if (len > maxcols) {
  1882. lencount = maxcols + 1;
  1883. /* Reduce wide chars one by one till it fits */
  1884. while (len > maxcols)
  1885. len = wcswidth(wbuf, --lencount);
  1886. wbuf[lencount] = L'\0';
  1887. }
  1888. /* Convert wide char to multi-byte */
  1889. wcstombs(g_buf, wbuf, NAME_MAX);
  1890. return g_buf;
  1891. }
  1892. static char *coolsize(off_t size)
  1893. {
  1894. const char * const U = "BKMGTPEZY";
  1895. static char size_buf[12]; /* Buffer to hold human readable size */
  1896. off_t rem = 0;
  1897. size_t ret;
  1898. int i = 0;
  1899. while (size >= 1024) {
  1900. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1901. size >>= 10;
  1902. ++i;
  1903. }
  1904. if (i == 1) {
  1905. rem = (rem * 1000) >> 10;
  1906. rem /= 10;
  1907. if (rem % 10 >= 5) {
  1908. rem = (rem / 10) + 1;
  1909. if (rem == 10) {
  1910. ++size;
  1911. rem = 0;
  1912. }
  1913. } else
  1914. rem /= 10;
  1915. } else if (i == 2) {
  1916. rem = (rem * 1000) >> 10;
  1917. if (rem % 10 >= 5) {
  1918. rem = (rem / 10) + 1;
  1919. if (rem == 100) {
  1920. ++size;
  1921. rem = 0;
  1922. }
  1923. } else
  1924. rem /= 10;
  1925. } else if (i > 0) {
  1926. rem = (rem * 10000) >> 10;
  1927. if (rem % 10 >= 5) {
  1928. rem = (rem / 10) + 1;
  1929. if (rem == 1000) {
  1930. ++size;
  1931. rem = 0;
  1932. }
  1933. } else
  1934. rem /= 10;
  1935. }
  1936. if (i > 0 && i < 6 && rem) {
  1937. ret = xstrlcpy(size_buf, xitoa(size), 12);
  1938. size_buf[ret - 1] = '.';
  1939. char *frac = xitoa(rem);
  1940. size_t toprint = i > 3 ? 3 : i;
  1941. size_t len = strlen(frac);
  1942. if (len < toprint) {
  1943. size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
  1944. xstrlcpy(size_buf + ret + (toprint - len), frac, len + 1);
  1945. } else
  1946. xstrlcpy(size_buf + ret, frac, toprint + 1);
  1947. ret += toprint;
  1948. } else {
  1949. ret = xstrlcpy(size_buf, size ? xitoa(size) : "0", 12);
  1950. --ret;
  1951. }
  1952. size_buf[ret] = U[i];
  1953. size_buf[ret + 1] = '\0';
  1954. return size_buf;
  1955. }
  1956. static void printent(const struct entry *ent, int sel, uint namecols)
  1957. {
  1958. const char *pname = unescape(ent->name, namecols);
  1959. const char cp = (ent->flags & FILE_COPIED) ? '+' : ' ';
  1960. char ind[2] = {'\0', '\0'};
  1961. mode_t mode = ent->mode;
  1962. switch (mode & S_IFMT) {
  1963. case S_IFREG:
  1964. if (mode & 0100)
  1965. ind[0] = '*';
  1966. break;
  1967. case S_IFDIR:
  1968. ind[0] = '/';
  1969. break;
  1970. case S_IFLNK:
  1971. ind[0] = '@';
  1972. break;
  1973. case S_IFSOCK:
  1974. ind[0] = '=';
  1975. break;
  1976. case S_IFIFO:
  1977. ind[0] = '|';
  1978. break;
  1979. case S_IFBLK: // fallthrough
  1980. case S_IFCHR:
  1981. break;
  1982. default:
  1983. ind[0] = '?';
  1984. break;
  1985. }
  1986. /* Directories are always shown on top */
  1987. resetdircolor(ent->flags);
  1988. if (sel)
  1989. attron(A_REVERSE);
  1990. printw("%c%s%s\n", cp, pname, ind);
  1991. if (sel)
  1992. attroff(A_REVERSE);
  1993. }
  1994. static void printent_long(const struct entry *ent, int sel, uint namecols)
  1995. {
  1996. char timebuf[18], permbuf[4], ind1 = '\0', ind2[] = "\0\0";
  1997. const char cp = (ent->flags & FILE_COPIED) ? '+' : ' ';
  1998. /* Timestamp */
  1999. strftime(timebuf, 18, "%F %R", localtime(&ent->t));
  2000. /* Permissions */
  2001. permbuf[0] = '0' + ((ent->mode >> 6) & 7);
  2002. permbuf[1] = '0' + ((ent->mode >> 3) & 7);
  2003. permbuf[2] = '0' + (ent->mode & 7);
  2004. permbuf[3] = '\0';
  2005. /* Trim escape chars from name */
  2006. const char *pname = unescape(ent->name, namecols);
  2007. /* Directories are always shown on top */
  2008. resetdircolor(ent->flags);
  2009. if (sel)
  2010. attron(A_REVERSE);
  2011. switch (ent->mode & S_IFMT) {
  2012. case S_IFREG:
  2013. if (ent->mode & 0100)
  2014. printw("%c%-16.16s %s %8.8s* %s*\n", cp, timebuf, permbuf,
  2015. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  2016. else
  2017. printw("%c%-16.16s %s %8.8s %s\n", cp, timebuf, permbuf,
  2018. coolsize(cfg.blkorder ? ent->blocks << BLK_SHIFT : ent->size), pname);
  2019. break;
  2020. case S_IFDIR:
  2021. if (cfg.blkorder)
  2022. printw("%c%-16.16s %s %8.8s/ %s/\n",
  2023. cp, timebuf, permbuf, coolsize(ent->blocks << BLK_SHIFT), pname);
  2024. else
  2025. printw("%c%-16.16s %s / %s/\n", cp, timebuf, permbuf, pname);
  2026. break;
  2027. case S_IFLNK:
  2028. if (ent->flags & DIR_OR_LINK_TO_DIR)
  2029. printw("%c%-16.16s %s @/ %s@\n", cp, timebuf, permbuf, pname);
  2030. else
  2031. printw("%c%-16.16s %s @ %s@\n", cp, timebuf, permbuf, pname);
  2032. break;
  2033. case S_IFSOCK:
  2034. ind1 = ind2[0] = '='; // fallthrough
  2035. case S_IFIFO:
  2036. if (!ind1)
  2037. ind1 = ind2[0] = '|'; // fallthrough
  2038. case S_IFBLK:
  2039. if (!ind1)
  2040. ind1 = 'b'; // fallthrough
  2041. case S_IFCHR:
  2042. if (!ind1)
  2043. ind1 = 'c'; // fallthrough
  2044. default:
  2045. if (!ind1)
  2046. ind1 = ind2[0] = '?';
  2047. printw("%c%-16.16s %s %c %s%s\n", cp, timebuf, permbuf, ind1, pname, ind2);
  2048. break;
  2049. }
  2050. if (sel)
  2051. attroff(A_REVERSE);
  2052. }
  2053. static void (*printptr)(const struct entry *ent, int sel, uint namecols) = &printent;
  2054. static void savecurctx(settings *curcfg, char *path, char *curname, int r /* next context num */)
  2055. {
  2056. settings cfg = *curcfg;
  2057. bool copymode = cfg.copymode ? TRUE : FALSE;
  2058. #ifdef DIR_LIMITED_COPY
  2059. g_crc = 0;
  2060. #endif
  2061. /* Save current context */
  2062. xstrlcpy(g_ctx[cfg.curctx].c_name, curname, NAME_MAX + 1);
  2063. g_ctx[cfg.curctx].c_cfg = cfg;
  2064. if (g_ctx[r].c_cfg.ctxactive) { /* Switch to saved context */
  2065. /* Switch light/detail mode */
  2066. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  2067. /* set the reverse */
  2068. printptr = cfg.showdetail ? &printent : &printent_long;
  2069. cfg = g_ctx[r].c_cfg;
  2070. } else { /* Setup a new context from current context */
  2071. g_ctx[r].c_cfg.ctxactive = 1;
  2072. xstrlcpy(g_ctx[r].c_path, path, PATH_MAX);
  2073. g_ctx[r].c_last[0] = '\0';
  2074. xstrlcpy(g_ctx[r].c_name, curname, NAME_MAX + 1);
  2075. g_ctx[r].c_fltr[0] = g_ctx[r].c_fltr[1] = '\0';
  2076. g_ctx[r].c_cfg = cfg;
  2077. g_ctx[r].c_cfg.runplugin = 0;
  2078. }
  2079. /* Continue copy mode */
  2080. cfg.copymode = copymode;
  2081. cfg.curctx = r;
  2082. *curcfg = cfg;
  2083. }
  2084. /*
  2085. * Gets only a single line (that's what we need
  2086. * for now) or shows full command output in pager.
  2087. *
  2088. * If page is valid, returns NULL
  2089. */
  2090. static char *get_output(char *buf, const size_t bytes, const char *file,
  2091. const char *arg1, const char *arg2, const bool page)
  2092. {
  2093. pid_t pid;
  2094. int pipefd[2];
  2095. FILE *pf;
  2096. int tmp, flags;
  2097. char *ret = NULL;
  2098. if (pipe(pipefd) == -1)
  2099. errexit();
  2100. for (tmp = 0; tmp < 2; ++tmp) {
  2101. /* Get previous flags */
  2102. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  2103. /* Set bit for non-blocking flag */
  2104. flags |= O_NONBLOCK;
  2105. /* Change flags on fd */
  2106. fcntl(pipefd[tmp], F_SETFL, flags);
  2107. }
  2108. pid = fork();
  2109. if (pid == 0) {
  2110. /* In child */
  2111. close(pipefd[0]);
  2112. dup2(pipefd[1], STDOUT_FILENO);
  2113. dup2(pipefd[1], STDERR_FILENO);
  2114. close(pipefd[1]);
  2115. execlp(file, file, arg1, arg2, NULL);
  2116. _exit(1);
  2117. }
  2118. /* In parent */
  2119. waitpid(pid, &tmp, 0);
  2120. close(pipefd[1]);
  2121. if (!page) {
  2122. pf = fdopen(pipefd[0], "r");
  2123. if (pf) {
  2124. ret = fgets(buf, bytes, pf);
  2125. close(pipefd[0]);
  2126. }
  2127. return ret;
  2128. }
  2129. pid = fork();
  2130. if (pid == 0) {
  2131. /* Show in pager in child */
  2132. dup2(pipefd[0], STDIN_FILENO);
  2133. close(pipefd[0]);
  2134. spawn(pager, NULL, NULL, NULL, F_CLI);
  2135. _exit(1);
  2136. }
  2137. /* In parent */
  2138. waitpid(pid, &tmp, 0);
  2139. close(pipefd[0]);
  2140. return NULL;
  2141. }
  2142. static inline bool getutil(char *util)
  2143. {
  2144. return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
  2145. }
  2146. /*
  2147. * Follows the stat(1) output closely
  2148. */
  2149. static bool show_stats(const char *fpath, const char *fname, const struct stat *sb)
  2150. {
  2151. int fd;
  2152. char *p, *begin = g_buf;
  2153. size_t r;
  2154. FILE *fp;
  2155. fd = create_tmp_file();
  2156. if (fd == -1)
  2157. return FALSE;
  2158. r = xstrlcpy(g_buf, "stat \"", PATH_MAX);
  2159. r += xstrlcpy(g_buf + r - 1, fpath, PATH_MAX);
  2160. g_buf[r - 2] = '\"';
  2161. g_buf[r - 1] = '\0';
  2162. DPRINTF_S(g_buf);
  2163. fp = popen(g_buf, "r");
  2164. if (fp) {
  2165. while (fgets(g_buf, CMD_LEN_MAX - 1, fp))
  2166. dprintf(fd, "%s", g_buf);
  2167. pclose(fp);
  2168. }
  2169. if (S_ISREG(sb->st_mode)) {
  2170. /* Show file(1) output */
  2171. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  2172. if (p) {
  2173. dprintf(fd, "\n\n ");
  2174. while (*p) {
  2175. if (*p == ',') {
  2176. *p = '\0';
  2177. dprintf(fd, " %s\n", begin);
  2178. begin = p + 1;
  2179. }
  2180. ++p;
  2181. }
  2182. dprintf(fd, " %s", begin);
  2183. }
  2184. }
  2185. dprintf(fd, "\n\n");
  2186. close(fd);
  2187. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  2188. unlink(g_tmpfpath);
  2189. return TRUE;
  2190. }
  2191. static size_t get_fs_info(const char *path, bool type)
  2192. {
  2193. struct statvfs svb;
  2194. if (statvfs(path, &svb) == -1)
  2195. return 0;
  2196. if (type == CAPACITY)
  2197. return svb.f_blocks << ffs((int)(svb.f_bsize >> 1));
  2198. return svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
  2199. }
  2200. static bool show_mediainfo(const char *fpath, const char *arg)
  2201. {
  2202. if (!getutil(utils[cfg.metaviewer]))
  2203. return FALSE;
  2204. exitcurses();
  2205. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, TRUE);
  2206. refresh();
  2207. return TRUE;
  2208. }
  2209. /* List or extract archive */
  2210. static void handle_archive(char *fpath, const char *dir, char op)
  2211. {
  2212. char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
  2213. char *util;
  2214. if (getutil(utils[ATOOL])) {
  2215. util = utils[ATOOL];
  2216. arg[1] = op;
  2217. arg[2] = '\0';
  2218. } else if (getutil(utils[BSDTAR])) {
  2219. util = utils[BSDTAR];
  2220. if (op == 'x')
  2221. arg[1] = op;
  2222. } else if (is_suffix(fpath, ".zip")) {
  2223. util = utils[UNZIP];
  2224. arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
  2225. arg[2] = '\0';
  2226. } else {
  2227. util = utils[TAR];
  2228. if (op == 'x')
  2229. arg[1] = op;
  2230. }
  2231. if (op == 'x') { /* extract */
  2232. spawn(util, arg, fpath, dir, F_NORMAL);
  2233. } else { /* list */
  2234. exitcurses();
  2235. get_output(NULL, 0, util, arg, fpath, TRUE);
  2236. refresh();
  2237. }
  2238. }
  2239. static char *visit_parent(char *path, char *newpath, int *presel)
  2240. {
  2241. char *dir;
  2242. /* There is no going back */
  2243. if (istopdir(path)) {
  2244. /* Continue in navigate-as-you-type mode, if enabled */
  2245. if (cfg.filtermode)
  2246. *presel = FILTER;
  2247. return NULL;
  2248. }
  2249. /* Use a copy as dirname() may change the string passed */
  2250. xstrlcpy(newpath, path, PATH_MAX);
  2251. dir = dirname(newpath);
  2252. if (access(dir, R_OK) == -1) {
  2253. printwarn(presel);
  2254. return NULL;
  2255. }
  2256. return dir;
  2257. }
  2258. static bool execute_file(int cur, char *path, char *newpath, int *presel)
  2259. {
  2260. if (!ndents)
  2261. return FALSE;
  2262. /* Check if this is a directory */
  2263. if (!S_ISREG(dents[cur].mode)) {
  2264. printwait("not regular file", presel);
  2265. return FALSE;
  2266. }
  2267. /* Check if file is executable */
  2268. if (!(dents[cur].mode & 0100)) {
  2269. printwait("permission denied", presel);
  2270. return FALSE;
  2271. }
  2272. mkpath(path, dents[cur].name, newpath);
  2273. spawn(newpath, NULL, NULL, path, F_NORMAL);
  2274. return TRUE;
  2275. }
  2276. static bool create_dir(const char *path)
  2277. {
  2278. if (!xdiraccess(path)) {
  2279. if (errno != ENOENT)
  2280. return FALSE;
  2281. if (mkdir(path, 0755) == -1)
  2282. return FALSE;
  2283. }
  2284. return TRUE;
  2285. }
  2286. static bool sshfs_mount(char *path, char *newpath, int *presel)
  2287. {
  2288. uchar flag = F_NORMAL;
  2289. int r;
  2290. char *tmp, *env, *cmd = "sshfs";
  2291. if (!getutil(cmd)) {
  2292. printwait(messages[UTIL_MISSING], presel);
  2293. return FALSE;
  2294. }
  2295. tmp = xreadline(NULL, "host: ");
  2296. if (!tmp[0])
  2297. return FALSE;
  2298. /* Create the mount point */
  2299. mkpath(cfgdir, tmp, newpath);
  2300. if (!create_dir(newpath)) {
  2301. printwait(strerror(errno), presel);
  2302. return FALSE;
  2303. }
  2304. /* Convert "Host" to "Host:" */
  2305. r = strlen(tmp);
  2306. tmp[r] = ':';
  2307. tmp[r + 1] = '\0';
  2308. env = getenv("NNN_SSHFS_OPTS");
  2309. if (env)
  2310. flag |= F_MULTI;
  2311. else
  2312. env = cmd;
  2313. /* Connect to remote */
  2314. if (spawn(env, tmp, newpath, NULL, flag)) {
  2315. printwait("mount failed", presel);
  2316. return FALSE;
  2317. }
  2318. return TRUE;
  2319. }
  2320. static bool sshfs_unmount(char *path, char *newpath, int *presel)
  2321. {
  2322. static char cmd[] = "fusermount3"; /* Arch Linux utility */
  2323. static bool found = FALSE;
  2324. char *tmp;
  2325. /* On Ubuntu it's fusermount */
  2326. if (!found && !getutil(cmd)) {
  2327. cmd[10] = '\0';
  2328. found = TRUE;
  2329. }
  2330. tmp = xreadline(NULL, "host: ");
  2331. if (!tmp[0])
  2332. return FALSE;
  2333. /* Create the mount point */
  2334. mkpath(cfgdir, tmp, newpath);
  2335. if (!xdiraccess(newpath)) {
  2336. *presel = MSGWAIT;
  2337. return FALSE;
  2338. }
  2339. if (spawn(cmd, "-u", newpath, NULL, F_NORMAL)) {
  2340. printwait("unmount failed", presel);
  2341. return FALSE;
  2342. }
  2343. return TRUE;
  2344. }
  2345. static void lock_terminal(void)
  2346. {
  2347. char *tmp = utils[LOCKER];
  2348. if (!getutil(tmp))
  2349. tmp = utils[CMATRIX];;
  2350. spawn(tmp, NULL, NULL, NULL, F_NORMAL);
  2351. }
  2352. /*
  2353. * The help string tokens (each line) start with a HEX value
  2354. * which indicates the number of spaces to print before the
  2355. * particular token. This method was chosen instead of a flat
  2356. * string because the number of bytes in help was increasing
  2357. * the binary size by around a hundred bytes. This would only
  2358. * have increased as we keep adding new options.
  2359. */
  2360. static bool show_help(const char *path)
  2361. {
  2362. int i = 0, fd;
  2363. const char *start, *end;
  2364. const char helpstr[] = {
  2365. "0\n"
  2366. "1NAVIGATION\n"
  2367. "a↑ k Up PgUp ^U Scroll up\n"
  2368. "a↓ j Down PgDn ^D Scroll down\n"
  2369. "a← h Parent dir ~ ` @ - HOME, /, start, last\n"
  2370. "8↵ → l Open file/dir . Toggle show hidden\n"
  2371. "9g ^A First entry G ^E Last entry\n"
  2372. "cb Pin current dir ^B Go to pinned dir\n"
  2373. "7Tab ^I Next context d Toggle detail view\n"
  2374. "9, ^/ Lead key N LeadN Context N\n"
  2375. "c/ Filter/Lead Ins ^T Toggle nav-as-you-type\n"
  2376. "aEsc Exit prompt ^L Redraw/clear prompt\n"
  2377. "cq Quit context Lead' First file\n"
  2378. "9Q ^Q Quit ^G QuitCD ? Help, config\n"
  2379. "1FILES\n"
  2380. "b^O Open with... n Create new/link\n"
  2381. "cD File details ^R Rename/duplicate\n"
  2382. "5⎵ ^K / Y Select entry/all r Batch rename\n"
  2383. "9K ^Y Toggle selection y List selection\n"
  2384. "cP Copy selection X Delete selection\n"
  2385. "cV Move selection ^X Delete entry\n"
  2386. "cf Create archive m M Brief/full mediainfo\n"
  2387. "b^F Extract archive F List archive\n"
  2388. "ce Edit in EDITOR p Open in PAGER\n"
  2389. "1ORDER TOGGLES\n"
  2390. "b^J du E Extn S Apparent du\n"
  2391. "b^W Random s Size t Time modified\n"
  2392. "1MISC\n"
  2393. "9! ^] Spawn SHELL C Execute entry\n"
  2394. "9R ^V Pick plugin L Lock terminal\n"
  2395. "cc SSHFS mount u Unmount\n"
  2396. "b^P Prompt ^N Note = Launcher\n"};
  2397. fd = create_tmp_file();
  2398. if (fd == -1)
  2399. return FALSE;
  2400. start = end = helpstr;
  2401. while (*end) {
  2402. if (*end == '\n') {
  2403. dprintf(fd, "%*c%.*s",
  2404. xchartohex(*start), ' ', (int)(end - start), start + 1);
  2405. start = end + 1;
  2406. }
  2407. ++end;
  2408. }
  2409. dprintf(fd, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  2410. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  2411. if (bookmark[0].loc) {
  2412. dprintf(fd, "BOOKMARKS\n");
  2413. for (; i < BM_MAX; ++i)
  2414. if (bookmark[i].key)
  2415. dprintf(fd, " %c: %s\n", (char)bookmark[i].key, bookmark[i].loc);
  2416. else
  2417. break;
  2418. dprintf(fd, "\n");
  2419. }
  2420. for (i = NNN_OPENER; i <= NNN_TRASH; ++i) {
  2421. start = getenv(env_cfg[i]);
  2422. if (start)
  2423. dprintf(fd, "%s: %s\n", env_cfg[i], start);
  2424. }
  2425. if (g_cppath)
  2426. dprintf(fd, "SELECTION FILE: %s\n", g_cppath);
  2427. dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  2428. close(fd);
  2429. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  2430. unlink(g_tmpfpath);
  2431. return TRUE;
  2432. }
  2433. static int sum_bsizes(const char *fpath, const struct stat *sb,
  2434. int typeflag, struct FTW *ftwbuf)
  2435. {
  2436. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  2437. ent_blocks += sb->st_blocks;
  2438. ++num_files;
  2439. return 0;
  2440. }
  2441. static int sum_sizes(const char *fpath, const struct stat *sb,
  2442. int typeflag, struct FTW *ftwbuf)
  2443. {
  2444. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  2445. ent_blocks += sb->st_size;
  2446. ++num_files;
  2447. return 0;
  2448. }
  2449. static void dentfree(void)
  2450. {
  2451. free(pnamebuf);
  2452. free(dents);
  2453. }
  2454. static int dentfill(char *path, struct entry **dents)
  2455. {
  2456. static uint open_max;
  2457. int n = 0, count, flags = 0;
  2458. ulong num_saved;
  2459. struct dirent *dp;
  2460. char *namep, *pnb, *buf = NULL;
  2461. struct entry *dentp;
  2462. size_t off = 0, namebuflen = NAMEBUF_INCR;
  2463. struct stat sb_path, sb;
  2464. DIR *dirp = opendir(path);
  2465. if (!dirp)
  2466. return 0;
  2467. int fd = dirfd(dirp);
  2468. if (cfg.blkorder) {
  2469. num_files = 0;
  2470. dir_blocks = 0;
  2471. buf = (char *)alloca(strlen(path) + NAME_MAX + 2);
  2472. if (fstatat(fd, path, &sb_path, 0) == -1) {
  2473. closedir(dirp);
  2474. printwarn(NULL);
  2475. return 0;
  2476. }
  2477. /* Increase current open file descriptor limit */
  2478. if (!open_max)
  2479. open_max = max_openfds();
  2480. }
  2481. dp = readdir(dirp);
  2482. if (!dp)
  2483. goto exit;
  2484. if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
  2485. /*
  2486. * Optimization added for filesystems which support dirent.d_type
  2487. * see readdir(3)
  2488. * Known drawbacks:
  2489. * - the symlink size is set to 0
  2490. * - the modification time of the symlink is set to that of the target file
  2491. */
  2492. flags = AT_SYMLINK_NOFOLLOW;
  2493. }
  2494. do {
  2495. namep = dp->d_name;
  2496. /* Skip self and parent */
  2497. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  2498. continue;
  2499. if (!cfg.showhidden && namep[0] == '.') {
  2500. if (!cfg.blkorder)
  2501. continue;
  2502. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  2503. continue;
  2504. if (S_ISDIR(sb.st_mode)) {
  2505. if (sb_path.st_dev == sb.st_dev) {
  2506. ent_blocks = 0;
  2507. mkpath(path, namep, buf);
  2508. mvprintw(xlines - 1, 0, "scanning %s [^C aborts]\n",
  2509. xbasename(buf));
  2510. refresh();
  2511. if (nftw(buf, nftw_fn, open_max,
  2512. FTW_MOUNT | FTW_PHYS) == -1) {
  2513. DPRINTF_S("nftw failed");
  2514. dir_blocks += (cfg.apparentsz
  2515. ? sb.st_size
  2516. : sb.st_blocks);
  2517. } else
  2518. dir_blocks += ent_blocks;
  2519. if (interrupted) {
  2520. closedir(dirp);
  2521. return n;
  2522. }
  2523. }
  2524. } else {
  2525. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2526. ++num_files;
  2527. }
  2528. continue;
  2529. }
  2530. if (fstatat(fd, namep, &sb, flags) == -1) {
  2531. DPRINTF_S(namep);
  2532. continue;
  2533. }
  2534. if (n == total_dents) {
  2535. total_dents += ENTRY_INCR;
  2536. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  2537. if (!*dents) {
  2538. free(pnamebuf);
  2539. closedir(dirp);
  2540. errexit();
  2541. }
  2542. DPRINTF_P(*dents);
  2543. }
  2544. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  2545. if (namebuflen - off < NAME_MAX + 1) {
  2546. namebuflen += NAMEBUF_INCR;
  2547. pnb = pnamebuf;
  2548. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  2549. if (!pnamebuf) {
  2550. free(*dents);
  2551. closedir(dirp);
  2552. errexit();
  2553. }
  2554. DPRINTF_P(pnamebuf);
  2555. /* realloc() may result in memory move, we must re-adjust if that happens */
  2556. if (pnb != pnamebuf) {
  2557. dentp = *dents;
  2558. dentp->name = pnamebuf;
  2559. for (count = 1; count < n; ++dentp, ++count)
  2560. /* Current filename starts at last filename start + length */
  2561. (dentp + 1)->name = (char *)((size_t)dentp->name
  2562. + dentp->nlen);
  2563. }
  2564. }
  2565. dentp = *dents + n;
  2566. /* Selection file name */
  2567. dentp->name = (char *)((size_t)pnamebuf + off);
  2568. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  2569. off += dentp->nlen;
  2570. /* Copy other fields */
  2571. dentp->t = sb.st_mtime;
  2572. if (dp->d_type == DT_LNK && !flags) { /* Do not add sizes for links */
  2573. dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
  2574. dentp->size = 0;
  2575. } else {
  2576. dentp->mode = sb.st_mode;
  2577. dentp->size = sb.st_size;
  2578. }
  2579. dentp->flags = 0;
  2580. if (cfg.blkorder) {
  2581. if (S_ISDIR(sb.st_mode)) {
  2582. ent_blocks = 0;
  2583. num_saved = num_files + 1;
  2584. mkpath(path, namep, buf);
  2585. mvprintw(xlines - 1, 0, "scanning %s [^C aborts]\n", xbasename(buf));
  2586. refresh();
  2587. if (nftw(buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  2588. DPRINTF_S("nftw failed");
  2589. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2590. } else
  2591. dentp->blocks = ent_blocks;
  2592. if (sb_path.st_dev == sb.st_dev) // NOLINT
  2593. dir_blocks += dentp->blocks;
  2594. else
  2595. num_files = num_saved;
  2596. if (interrupted) {
  2597. closedir(dirp);
  2598. return n;
  2599. }
  2600. } else {
  2601. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  2602. dir_blocks += dentp->blocks;
  2603. ++num_files;
  2604. }
  2605. }
  2606. if (flags) {
  2607. /* Flag if this is a dir or symlink to a dir */
  2608. if (S_ISLNK(sb.st_mode)) {
  2609. sb.st_mode = 0;
  2610. fstatat(fd, namep, &sb, 0);
  2611. }
  2612. if (S_ISDIR(sb.st_mode))
  2613. dentp->flags |= DIR_OR_LINK_TO_DIR;
  2614. } else if (dp->d_type == DT_DIR || (dp->d_type == DT_LNK && S_ISDIR(sb.st_mode)))
  2615. dentp->flags |= DIR_OR_LINK_TO_DIR;
  2616. ++n;
  2617. } while ((dp = readdir(dirp)));
  2618. exit:
  2619. /* Should never be null */
  2620. if (closedir(dirp) == -1) {
  2621. dentfree();
  2622. errexit();
  2623. }
  2624. return n;
  2625. }
  2626. /*
  2627. * Return the position of the matching entry or 0 otherwise
  2628. * Note there's no NULL check for fname
  2629. */
  2630. static int dentfind(const char *fname, int n)
  2631. {
  2632. int i = 0;
  2633. for (; i < n; ++i)
  2634. if (xstrcmp(fname, dents[i].name) == 0)
  2635. return i;
  2636. return 0;
  2637. }
  2638. static void populate(char *path, char *lastname)
  2639. {
  2640. #ifdef DBGMODE
  2641. struct timespec ts1, ts2;
  2642. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  2643. #endif
  2644. ndents = dentfill(path, &dents);
  2645. if (!ndents)
  2646. return;
  2647. if (!cfg.wild)
  2648. qsort(dents, ndents, sizeof(*dents), entrycmp);
  2649. #ifdef DBGMODE
  2650. clock_gettime(CLOCK_REALTIME, &ts2);
  2651. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  2652. #endif
  2653. /* Find cur from history */
  2654. /* No NULL check for lastname, always points to an array */
  2655. if (!*lastname)
  2656. move_cursor(0, 0);
  2657. else
  2658. move_cursor(dentfind(lastname, ndents), 0);
  2659. }
  2660. static void move_cursor(int target, int ignore_scrolloff)
  2661. {
  2662. int delta, scrolloff, onscreen = xlines - 4;
  2663. target = MAX(0, MIN(ndents - 1, target));
  2664. delta = target - cur;
  2665. cur = target;
  2666. if (!ignore_scrolloff) {
  2667. scrolloff = MIN(SCROLLOFF, onscreen >> 1);
  2668. /*
  2669. * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
  2670. * margin area, but when ignore_scrolloff is 0, act like a boa
  2671. * constrictor and squeeze the cursor towards the middle region of the
  2672. * screen by allowing it to move inward and disallowing it to move
  2673. * outward (deeper into the scrolloff margin area).
  2674. */
  2675. if (cur < curscroll + scrolloff && delta < 0)
  2676. curscroll += delta;
  2677. else if (cur > curscroll + onscreen - scrolloff - 1 && delta > 0)
  2678. curscroll += delta;
  2679. }
  2680. curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
  2681. curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
  2682. }
  2683. static void redraw(char *path)
  2684. {
  2685. xlines = LINES;
  2686. xcols = COLS;
  2687. int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
  2688. int lastln = xlines, onscreen = xlines - 4;
  2689. int i, attrs;
  2690. char buf[12];
  2691. char c;
  2692. --lastln;
  2693. /* Clear screen */
  2694. erase();
  2695. /* Enforce scroll/cursor invariants */
  2696. move_cursor(cur, 1);
  2697. #ifdef DIR_LIMITED_COPY
  2698. if (cfg.copymode)
  2699. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  2700. cfg.copymode = 0;
  2701. DPRINTF_S("selection off");
  2702. }
  2703. #endif
  2704. /* Fail redraw if < than 11 columns, context info prints 10 chars */
  2705. if (ncols < 11) {
  2706. printmsg("too few columns!");
  2707. return;
  2708. }
  2709. DPRINTF_D(cur);
  2710. DPRINTF_S(path);
  2711. printw("[");
  2712. for (i = 0; i < CTX_MAX; ++i) {
  2713. if (!g_ctx[i].c_cfg.ctxactive)
  2714. printw("%d ", i + 1);
  2715. else if (cfg.curctx != i) {
  2716. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_UNDERLINE;
  2717. attron(attrs);
  2718. printw("%d", i + 1);
  2719. attroff(attrs);
  2720. printw(" ");
  2721. } else {
  2722. /* Print current context in reverse */
  2723. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_REVERSE;
  2724. attron(attrs);
  2725. printw("%d", i + 1);
  2726. attroff(attrs);
  2727. printw(" ");
  2728. }
  2729. }
  2730. printw("\b] "); /* 10 chars printed in total for contexts - "[1 2 3 4] " */
  2731. attron(A_UNDERLINE);
  2732. /* No text wrapping in cwd line, store the truncating char in c */
  2733. c = path[ncols - 11];
  2734. path[ncols - 11] = '\0';
  2735. printw("%s\n\n", path);
  2736. attroff(A_UNDERLINE);
  2737. path[ncols - 11] = c; /* Restore c */
  2738. /* Calculate the number of cols available to print entry name */
  2739. if (cfg.showdetail) {
  2740. /* Fallback to light mode if less than 35 columns */
  2741. if (ncols < 36) {
  2742. cfg.showdetail ^= 1;
  2743. printptr = &printent;
  2744. ncols -= 5;
  2745. } else
  2746. ncols -= 35;
  2747. } else
  2748. ncols -= 5;
  2749. if (!cfg.wild) {
  2750. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2751. cfg.dircolor = 1;
  2752. }
  2753. /* Print listing */
  2754. for (i = curscroll; i < ndents && i < curscroll + onscreen; ++i) {
  2755. printptr(&dents[i], i == cur, ncols);
  2756. }
  2757. /* Must reset e.g. no files in dir */
  2758. if (cfg.dircolor) {
  2759. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2760. cfg.dircolor = 0;
  2761. }
  2762. if (ndents) {
  2763. char sort[] = "\0 ";
  2764. if (cfg.mtimeorder)
  2765. sort[0] = 'T';
  2766. else if (cfg.sizeorder)
  2767. sort[0] = 'S';
  2768. else if (cfg.extnorder)
  2769. sort[0] = 'E';
  2770. /* We need to show filename as it may be truncated in directory listing */
  2771. if (!cfg.showdetail || !cfg.blkorder)
  2772. mvprintw(lastln, 0, "%d/%d %s[%s]\n", cur + 1, ndents, sort,
  2773. unescape(dents[cur].name, NAME_MAX));
  2774. else {
  2775. xstrlcpy(buf, coolsize(dir_blocks << BLK_SHIFT), 12);
  2776. c = cfg.apparentsz ? 'a' : 'd';
  2777. mvprintw(lastln, 0, "%d/%d %cu: %s (%lu files) free: %s [%s]\n",
  2778. cur + 1, ndents, c, buf, num_files,
  2779. coolsize(get_fs_info(path, FREE)),
  2780. unescape(dents[cur].name, NAME_MAX));
  2781. }
  2782. } else
  2783. printmsg("0/0");
  2784. }
  2785. static void browse(char *ipath)
  2786. {
  2787. char newpath[PATH_MAX] __attribute__ ((aligned));
  2788. char mark[PATH_MAX] __attribute__ ((aligned));
  2789. char rundir[PATH_MAX] __attribute__ ((aligned));
  2790. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  2791. int r = -1, fd, presel, ncp = 0, copystartid = 0, copyendid = 0, onscreen;
  2792. enum action sel;
  2793. bool dir_changed = FALSE;
  2794. struct stat sb;
  2795. char *path, *lastdir, *lastname, *dir, *tmp;
  2796. MEVENT event;
  2797. atexit(dentfree);
  2798. /* setup first context */
  2799. xstrlcpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  2800. path = g_ctx[0].c_path;
  2801. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = newpath[0] = mark[0] = '\0';
  2802. rundir[0] = runfile[0] = '\0';
  2803. lastdir = g_ctx[0].c_last; /* last visited directory */
  2804. lastname = g_ctx[0].c_name; /* last visited filename */
  2805. g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
  2806. g_ctx[0].c_cfg = cfg; /* current configuration */
  2807. cfg.filtermode ? (presel = FILTER) : (presel = 0);
  2808. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2809. if (!dents)
  2810. errexit();
  2811. /* Allocate buffer to hold names */
  2812. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2813. if (!pnamebuf)
  2814. errexit();
  2815. begin:
  2816. #ifdef LINUX_INOTIFY
  2817. if ((presel == FILTER || dir_changed) && inotify_wd >= 0) {
  2818. inotify_rm_watch(inotify_fd, inotify_wd);
  2819. inotify_wd = -1;
  2820. dir_changed = FALSE;
  2821. }
  2822. #elif defined(BSD_KQUEUE)
  2823. if ((presel == FILTER || dir_changed) && event_fd >= 0) {
  2824. close(event_fd);
  2825. event_fd = -1;
  2826. dir_changed = FALSE;
  2827. }
  2828. #endif
  2829. /* Can fail when permissions change while browsing.
  2830. * It's assumed that path IS a directory when we are here.
  2831. */
  2832. if (access(path, R_OK) == -1)
  2833. printwarn(&presel);
  2834. populate(path, lastname);
  2835. if (interrupted) {
  2836. interrupted = FALSE;
  2837. cfg.apparentsz = 0;
  2838. cfg.blkorder = 0;
  2839. BLK_SHIFT = 9;
  2840. presel = CONTROL('L');
  2841. }
  2842. #ifdef LINUX_INOTIFY
  2843. if (presel != FILTER && inotify_wd == -1)
  2844. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2845. #elif defined(BSD_KQUEUE)
  2846. if (presel != FILTER && event_fd == -1) {
  2847. #if defined(O_EVTONLY)
  2848. event_fd = open(path, O_EVTONLY);
  2849. #else
  2850. event_fd = open(path, O_RDONLY);
  2851. #endif
  2852. if (event_fd >= 0)
  2853. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  2854. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2855. }
  2856. #endif
  2857. while (1) {
  2858. redraw(path);
  2859. nochange:
  2860. /* Exit if parent has exited */
  2861. if (getppid() == 1)
  2862. _exit(0);
  2863. /* If CWD is deleted or moved or perms changed, find an accessible parent */
  2864. if (access(path, F_OK)) {
  2865. DPRINTF_S("directory inaccessible");
  2866. /* Save history */
  2867. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  2868. xstrlcpy(newpath, path, PATH_MAX);
  2869. while (true) {
  2870. dir = visit_parent(path, newpath, &presel);
  2871. if (istopdir(path) || istopdir(newpath)) {
  2872. if (!dir)
  2873. dir = dirname(newpath);
  2874. break;
  2875. }
  2876. if (!dir) {
  2877. xstrlcpy(path, newpath, PATH_MAX);
  2878. continue;
  2879. }
  2880. break;
  2881. }
  2882. xstrlcpy(path, dir, PATH_MAX);
  2883. setdirwatch();
  2884. mvprintw(xlines - 1, 0, "cannot access directory\n");
  2885. xdelay();
  2886. goto begin;
  2887. }
  2888. sel = nextsel(presel);
  2889. if (presel)
  2890. presel = 0;
  2891. switch (sel) {
  2892. case SEL_CLICK:
  2893. if (getmouse(&event) != OK)
  2894. goto nochange; // fallthrough
  2895. case SEL_BACK:
  2896. /* Handle clicking on a context at the top */
  2897. if (sel == SEL_CLICK && event.bstate == BUTTON1_CLICKED && event.y == 0) {
  2898. /* Get context from: "[1 2 3 4]..." */
  2899. r = event.x >> 1;
  2900. /* If clicked after contexts, go to parent */
  2901. if (r >= CTX_MAX)
  2902. sel = SEL_BACK;
  2903. else if (0 <= r && r < CTX_MAX && r != cfg.curctx) {
  2904. savecurctx(&cfg, path, dents[cur].name, r);
  2905. /* Reset the pointers */
  2906. path = g_ctx[r].c_path;
  2907. lastdir = g_ctx[r].c_last;
  2908. lastname = g_ctx[r].c_name;
  2909. setdirwatch();
  2910. goto begin;
  2911. }
  2912. }
  2913. if (sel == SEL_BACK) {
  2914. dir = visit_parent(path, newpath, &presel);
  2915. if (!dir)
  2916. goto nochange;
  2917. /* Save last working directory */
  2918. xstrlcpy(lastdir, path, PATH_MAX);
  2919. /* Save history */
  2920. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  2921. xstrlcpy(path, dir, PATH_MAX);
  2922. setdirwatch();
  2923. goto begin;
  2924. }
  2925. #if NCURSES_MOUSE_VERSION > 1
  2926. /* Scroll up */
  2927. if (event.bstate == BUTTON4_PRESSED && ndents) {
  2928. move_cursor((cur + ndents - 1) % ndents, 0);
  2929. break;
  2930. }
  2931. /* Scroll down */
  2932. if (event.bstate == BUTTON5_PRESSED && ndents) {
  2933. move_cursor((cur + 1) % ndents, 0);
  2934. break;
  2935. }
  2936. #endif
  2937. /* Toggle filter mode on left click on last 2 lines */
  2938. if (event.y >= xlines - 2) {
  2939. cfg.filtermode ^= 1;
  2940. if (cfg.filtermode) {
  2941. presel = FILTER;
  2942. goto nochange;
  2943. }
  2944. /* Start watching the directory */
  2945. dir_changed = TRUE;
  2946. if (ndents)
  2947. copycurname();
  2948. goto begin;
  2949. }
  2950. /* Handle clicking on a file */
  2951. if (2 <= event.y && event.y <= ndents + 1) {
  2952. r = curscroll + (event.y - 2);
  2953. move_cursor(r, 1);
  2954. /*Single click just selects, double click also opens */
  2955. if (event.bstate != BUTTON1_DOUBLE_CLICKED)
  2956. break;
  2957. } else {
  2958. if (cfg.filtermode)
  2959. presel = FILTER;
  2960. goto nochange; // fallthrough
  2961. }
  2962. case SEL_NAV_IN: // fallthrough
  2963. case SEL_GOIN:
  2964. /* Cannot descend in empty directories */
  2965. if (!ndents)
  2966. goto begin;
  2967. mkpath(path, dents[cur].name, newpath);
  2968. DPRINTF_S(newpath);
  2969. /* Cannot use stale data in entry, file may be missing by now */
  2970. if (stat(newpath, &sb) == -1) {
  2971. printwarn(&presel);
  2972. goto nochange;
  2973. }
  2974. DPRINTF_U(sb.st_mode);
  2975. switch (sb.st_mode & S_IFMT) {
  2976. case S_IFDIR:
  2977. if (access(newpath, R_OK) == -1) {
  2978. printwarn(&presel);
  2979. goto nochange;
  2980. }
  2981. /* Save last working directory */
  2982. xstrlcpy(lastdir, path, PATH_MAX);
  2983. xstrlcpy(path, newpath, PATH_MAX);
  2984. lastname[0] = '\0';
  2985. setdirwatch();
  2986. goto begin;
  2987. case S_IFREG:
  2988. {
  2989. /* If opened as vim plugin and Enter/^M pressed, pick */
  2990. if (cfg.picker && sel == SEL_GOIN) {
  2991. r = mkpath(path, dents[cur].name, newpath);
  2992. appendfpath(newpath, r);
  2993. writecp(pcopybuf, copybufpos - 1);
  2994. return;
  2995. }
  2996. /* If open file is disabled on right arrow or `l`, return */
  2997. if (cfg.nonavopen && sel == SEL_NAV_IN)
  2998. continue;
  2999. /* Handle plugin selection mode */
  3000. if (cfg.runplugin) {
  3001. if (!plugindir || (cfg.runctx != cfg.curctx)
  3002. /* Must be in plugin directory to select plugin */
  3003. || (strcmp(path, plugindir) != 0))
  3004. continue;
  3005. mkpath(path, dents[cur].name, newpath);
  3006. /* Copy to path so we can return back to earlier dir */
  3007. xstrlcpy(path, rundir, PATH_MAX);
  3008. if (runfile[0]) {
  3009. xstrlcpy(lastname, runfile, NAME_MAX);
  3010. spawn(newpath, lastname, NULL, path, F_NORMAL);
  3011. runfile[0] = '\0';
  3012. } else
  3013. spawn(newpath, NULL, NULL, path, F_NORMAL);
  3014. rundir[0] = '\0';
  3015. cfg.runplugin = 0;
  3016. setdirwatch();
  3017. goto begin;
  3018. }
  3019. /* If NNN_USE_EDITOR is set, open text in EDITOR */
  3020. if (cfg.useeditor &&
  3021. get_output(g_buf, CMD_LEN_MAX, "file", FILE_OPTS, newpath, FALSE)
  3022. && g_buf[0] == 't' && g_buf[1] == 'e' && g_buf[2] == 'x'
  3023. && g_buf[3] == g_buf[0] && g_buf[4] == '/') {
  3024. spawn(editor, newpath, NULL, path, F_CLI);
  3025. continue;
  3026. }
  3027. if (!sb.st_size) {
  3028. printwait("empty: use edit or open with", &presel);
  3029. goto nochange;
  3030. }
  3031. /* Invoke desktop opener as last resort */
  3032. spawn(opener, newpath, NULL, NULL, F_NOTRACE | F_NOWAIT);
  3033. continue;
  3034. }
  3035. default:
  3036. printwait("unsupported file", &presel);
  3037. goto nochange;
  3038. }
  3039. case SEL_NEXT:
  3040. if (ndents)
  3041. move_cursor((cur + 1) % ndents, 0);
  3042. break;
  3043. case SEL_PREV:
  3044. if (ndents)
  3045. move_cursor((cur + ndents - 1) % ndents, 0);
  3046. break;
  3047. case SEL_PGDN: // fallthrough
  3048. onscreen = xlines - 4;
  3049. move_cursor(curscroll + (onscreen - 1), 1);
  3050. curscroll += onscreen - 1;
  3051. break;
  3052. case SEL_CTRL_D:
  3053. onscreen = xlines - 4;
  3054. move_cursor(curscroll + (onscreen - 1), 1);
  3055. curscroll += onscreen >> 1;
  3056. break;
  3057. case SEL_PGUP: // fallthrough
  3058. onscreen = xlines - 4;
  3059. move_cursor(curscroll, 1);
  3060. curscroll -= onscreen - 1;
  3061. break;
  3062. case SEL_CTRL_U:
  3063. onscreen = xlines - 4;
  3064. move_cursor(curscroll, 1);
  3065. curscroll -= onscreen >> 1;
  3066. break;
  3067. case SEL_HOME:
  3068. move_cursor(0, 1);
  3069. break;
  3070. case SEL_END:
  3071. move_cursor(ndents - 1, 1);
  3072. break;
  3073. case SEL_CDHOME: // fallthrough
  3074. case SEL_CDBEGIN: // fallthrough
  3075. case SEL_CDLAST: // fallthrough
  3076. case SEL_CDROOT: // fallthrough
  3077. case SEL_VISIT:
  3078. switch (sel) {
  3079. case SEL_CDHOME:
  3080. dir = home;
  3081. break;
  3082. case SEL_CDBEGIN:
  3083. dir = ipath;
  3084. break;
  3085. case SEL_CDLAST:
  3086. dir = lastdir;
  3087. break;
  3088. case SEL_CDROOT:
  3089. dir = "/";
  3090. break;
  3091. default: /* case SEL_VISIT */
  3092. dir = mark;
  3093. break;
  3094. }
  3095. if (dir[0] == '\0') {
  3096. printwait("not set", &presel);
  3097. goto nochange;
  3098. }
  3099. if (!xdiraccess(dir)) {
  3100. presel = MSGWAIT;
  3101. goto nochange;
  3102. }
  3103. if (strcmp(path, dir) == 0)
  3104. goto nochange;
  3105. /* SEL_CDLAST: dir pointing to lastdir */
  3106. xstrlcpy(newpath, dir, PATH_MAX);
  3107. /* Save last working directory */
  3108. xstrlcpy(lastdir, path, PATH_MAX);
  3109. xstrlcpy(path, newpath, PATH_MAX);
  3110. lastname[0] = '\0';
  3111. DPRINTF_S(path);
  3112. setdirwatch();
  3113. goto begin;
  3114. case SEL_LEADER: // fallthrough
  3115. case SEL_CYCLE: // fallthrough
  3116. case SEL_CTX1: // fallthrough
  3117. case SEL_CTX2: // fallthrough
  3118. case SEL_CTX3: // fallthrough
  3119. case SEL_CTX4:
  3120. if (sel == SEL_CYCLE)
  3121. fd = '>';
  3122. else if (sel >= SEL_CTX1 && sel <= SEL_CTX4)
  3123. fd = sel - SEL_CTX1 + '1';
  3124. else
  3125. fd = get_input(NULL);
  3126. switch (fd) {
  3127. case 'q': // fallthrough
  3128. case '~': // fallthrough
  3129. case '`': // fallthrough
  3130. case '-': // fallthrough
  3131. case '@':
  3132. presel = fd;
  3133. goto nochange;
  3134. case '\'':
  3135. for (r = 0; r < ndents; ++r) {
  3136. if (!(dents[r].flags & DIR_OR_LINK_TO_DIR)) {
  3137. move_cursor((r) % ndents, 0);
  3138. break;
  3139. }
  3140. }
  3141. if (r != ndents)
  3142. continue;;
  3143. goto nochange;
  3144. case '>': // fallthrough
  3145. case '.': // fallthrough
  3146. case '<': // fallthrough
  3147. case ',':
  3148. r = cfg.curctx;
  3149. if (fd == '>' || fd == '.')
  3150. do
  3151. r = (r + 1) & ~CTX_MAX;
  3152. while (!g_ctx[r].c_cfg.ctxactive);
  3153. else
  3154. do
  3155. r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
  3156. while (!g_ctx[r].c_cfg.ctxactive); // fallthrough
  3157. fd = '1' + r; // fallthrough
  3158. case '1': // fallthrough
  3159. case '2': // fallthrough
  3160. case '3': // fallthrough
  3161. case '4':
  3162. r = fd - '1'; /* Save the next context id */
  3163. if (cfg.curctx == r) {
  3164. if (sel != SEL_CYCLE)
  3165. continue;
  3166. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3167. snprintf(newpath, PATH_MAX,
  3168. "Create context %d? [Enter]", r + 1);
  3169. fd = get_input(newpath);
  3170. if (fd != '\r')
  3171. continue;
  3172. }
  3173. savecurctx(&cfg, path, dents[cur].name, r);
  3174. /* Reset the pointers */
  3175. path = g_ctx[r].c_path;
  3176. lastdir = g_ctx[r].c_last;
  3177. lastname = g_ctx[r].c_name;
  3178. setdirwatch();
  3179. goto begin;
  3180. }
  3181. if (!get_bm_loc(newpath, fd)) {
  3182. printwait(messages[STR_INVBM_KEY], &presel);
  3183. goto nochange;
  3184. }
  3185. if (!xdiraccess(newpath))
  3186. goto nochange;
  3187. if (strcmp(path, newpath) == 0)
  3188. break;
  3189. lastname[0] = '\0';
  3190. /* Save last working directory */
  3191. xstrlcpy(lastdir, path, PATH_MAX);
  3192. /* Save the newly opted dir in path */
  3193. xstrlcpy(path, newpath, PATH_MAX);
  3194. DPRINTF_S(path);
  3195. setdirwatch();
  3196. goto begin;
  3197. case SEL_PIN:
  3198. xstrlcpy(mark, path, PATH_MAX);
  3199. printwait(mark, &presel);
  3200. goto nochange;
  3201. case SEL_FLTR:
  3202. /* Unwatch dir if we are still in a filtered view */
  3203. #ifdef LINUX_INOTIFY
  3204. if (inotify_wd >= 0) {
  3205. inotify_rm_watch(inotify_fd, inotify_wd);
  3206. inotify_wd = -1;
  3207. }
  3208. #elif defined(BSD_KQUEUE)
  3209. if (event_fd >= 0) {
  3210. close(event_fd);
  3211. event_fd = -1;
  3212. }
  3213. #endif
  3214. presel = filterentries(path);
  3215. /* Save current */
  3216. if (ndents)
  3217. copycurname();
  3218. if (presel == 27) {
  3219. presel = 0;
  3220. break;
  3221. }
  3222. goto nochange;
  3223. case SEL_MFLTR: // fallthrough
  3224. case SEL_TOGGLEDOT: // fallthrough
  3225. case SEL_DETAIL: // fallthrough
  3226. case SEL_FSIZE: // fallthrough
  3227. case SEL_ASIZE: // fallthrough
  3228. case SEL_BSIZE: // fallthrough
  3229. case SEL_EXTN: // fallthrough
  3230. case SEL_MTIME: // fallthrough
  3231. case SEL_WILD:
  3232. switch (sel) {
  3233. case SEL_MFLTR:
  3234. cfg.filtermode ^= 1;
  3235. if (cfg.filtermode) {
  3236. presel = FILTER;
  3237. goto nochange;
  3238. }
  3239. /* Start watching the directory */
  3240. dir_changed = TRUE;
  3241. break;
  3242. case SEL_TOGGLEDOT:
  3243. cfg.showhidden ^= 1;
  3244. setdirwatch();
  3245. break;
  3246. case SEL_DETAIL:
  3247. cfg.showdetail ^= 1;
  3248. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  3249. continue;
  3250. case SEL_FSIZE:
  3251. cfg.sizeorder ^= 1;
  3252. cfg.mtimeorder = 0;
  3253. cfg.apparentsz = 0;
  3254. cfg.blkorder = 0;
  3255. cfg.extnorder = 0;
  3256. cfg.copymode = 0;
  3257. cfg.wild = 0;
  3258. break;
  3259. case SEL_ASIZE:
  3260. cfg.apparentsz ^= 1;
  3261. if (cfg.apparentsz) {
  3262. nftw_fn = &sum_sizes;
  3263. cfg.blkorder = 1;
  3264. BLK_SHIFT = 0;
  3265. } else
  3266. cfg.blkorder = 0; // fallthrough
  3267. case SEL_BSIZE:
  3268. if (sel == SEL_BSIZE) {
  3269. if (!cfg.apparentsz)
  3270. cfg.blkorder ^= 1;
  3271. nftw_fn = &sum_bsizes;
  3272. cfg.apparentsz = 0;
  3273. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  3274. }
  3275. if (cfg.blkorder) {
  3276. cfg.showdetail = 1;
  3277. printptr = &printent_long;
  3278. }
  3279. cfg.mtimeorder = 0;
  3280. cfg.sizeorder = 0;
  3281. cfg.extnorder = 0;
  3282. cfg.copymode = 0;
  3283. cfg.wild = 0;
  3284. break;
  3285. case SEL_EXTN:
  3286. cfg.extnorder ^= 1;
  3287. cfg.sizeorder = 0;
  3288. cfg.mtimeorder = 0;
  3289. cfg.apparentsz = 0;
  3290. cfg.blkorder = 0;
  3291. cfg.copymode = 0;
  3292. cfg.wild = 0;
  3293. break;
  3294. case SEL_MTIME:
  3295. cfg.mtimeorder ^= 1;
  3296. cfg.sizeorder = 0;
  3297. cfg.apparentsz = 0;
  3298. cfg.blkorder = 0;
  3299. cfg.extnorder = 0;
  3300. cfg.copymode = 0;
  3301. cfg.wild = 0;
  3302. break;
  3303. default: /* SEL_WILD */
  3304. cfg.wild ^= 1;
  3305. cfg.mtimeorder = 0;
  3306. cfg.sizeorder = 0;
  3307. cfg.apparentsz = 0;
  3308. cfg.blkorder = 0;
  3309. cfg.extnorder = 0;
  3310. cfg.copymode = 0;
  3311. setdirwatch();
  3312. goto nochange;
  3313. }
  3314. /* Save current */
  3315. if (ndents)
  3316. copycurname();
  3317. goto begin;
  3318. case SEL_STATS:
  3319. if (!ndents)
  3320. break;
  3321. mkpath(path, dents[cur].name, newpath);
  3322. if (lstat(newpath, &sb) == -1 || !show_stats(newpath, dents[cur].name, &sb)) {
  3323. printwarn(&presel);
  3324. goto nochange;
  3325. }
  3326. break;
  3327. case SEL_MEDIA: // fallthrough
  3328. case SEL_FMEDIA: // fallthrough
  3329. case SEL_ARCHIVELS: // fallthrough
  3330. case SEL_EXTRACT: // fallthrough
  3331. case SEL_RUNEDIT: // fallthrough
  3332. case SEL_RUNPAGE:
  3333. if (!ndents)
  3334. break; // fallthrough
  3335. case SEL_REDRAW: // fallthrough
  3336. case SEL_RENAMEALL: // fallthrough
  3337. case SEL_HELP: // fallthrough
  3338. case SEL_NOTE: // fallthrough
  3339. case SEL_LOCK:
  3340. {
  3341. if (ndents)
  3342. mkpath(path, dents[cur].name, newpath);
  3343. r = TRUE;
  3344. switch (sel) {
  3345. case SEL_MEDIA: // fallthrough
  3346. case SEL_FMEDIA:
  3347. tmp = (sel == SEL_FMEDIA) ? "-f" : NULL;
  3348. show_mediainfo(newpath, tmp);
  3349. setdirwatch();
  3350. goto nochange;
  3351. case SEL_ARCHIVELS:
  3352. handle_archive(newpath, path, 'l');
  3353. break;
  3354. case SEL_EXTRACT:
  3355. handle_archive(newpath, path, 'x');
  3356. break;
  3357. case SEL_REDRAW:
  3358. if (ndents)
  3359. copycurname();
  3360. goto begin;
  3361. case SEL_RENAMEALL:
  3362. if (!batch_rename(path)) {
  3363. printwait("batch rename failed", &presel);
  3364. goto nochange;
  3365. }
  3366. break;
  3367. case SEL_HELP:
  3368. r = show_help(path);
  3369. break;
  3370. case SEL_RUNEDIT:
  3371. spawn(editor, dents[cur].name, NULL, path, F_CLI);
  3372. break;
  3373. case SEL_RUNPAGE:
  3374. spawn(pager, dents[cur].name, NULL, path, F_CLI);
  3375. break;
  3376. case SEL_NOTE:
  3377. {
  3378. static char *notepath;
  3379. notepath = notepath ? notepath : getenv(env_cfg[NNN_NOTE]);
  3380. if (!notepath) {
  3381. printwait("set NNN_NOTE", &presel);
  3382. goto nochange;
  3383. }
  3384. spawn(editor, notepath, NULL, path, F_CLI);
  3385. break;
  3386. }
  3387. default: /* SEL_LOCK */
  3388. lock_terminal();
  3389. break;
  3390. }
  3391. if (!r) {
  3392. printwait(messages[UTIL_MISSING], &presel);
  3393. goto nochange;
  3394. }
  3395. /* In case of successful operation, reload contents */
  3396. /* Continue in navigate-as-you-type mode, if enabled */
  3397. if (cfg.filtermode)
  3398. presel = FILTER;
  3399. /* Save current */
  3400. if (ndents)
  3401. copycurname();
  3402. /* Repopulate as directory content may have changed */
  3403. goto begin;
  3404. }
  3405. case SEL_SEL:
  3406. if (!ndents)
  3407. goto nochange;
  3408. if (cfg.copymode) {
  3409. /*
  3410. * Clear the selection file on first copy.
  3411. *
  3412. * This ensures that when the first file path is
  3413. * copied into memory (but not written to tmp file
  3414. * yet to save on writes), the tmp file is cleared.
  3415. * The user may be in the middle of selection mode op
  3416. * and issue a cp, mv of multi-rm assuming the files
  3417. * in the copy list would be affected. However, these
  3418. * ops read the source file paths from the tmp file.
  3419. */
  3420. if (!ncp)
  3421. writecp(NULL, 0);
  3422. /* Do not select if already selected */
  3423. if (!(dents[cur].flags & FILE_COPIED)) {
  3424. r = mkpath(path, dents[cur].name, newpath);
  3425. appendfpath(newpath, r);
  3426. ++ncp;
  3427. dents[cur].flags |= FILE_COPIED;
  3428. }
  3429. /* move cursor to the next entry if this is not the last entry */
  3430. if (cur != ndents - 1)
  3431. move_cursor((cur + 1) % ndents, 0);
  3432. } else {
  3433. r = mkpath(path, dents[cur].name, newpath);
  3434. if (copybufpos) {
  3435. resetcpind();
  3436. /* Keep the copy buf in sync */
  3437. copybufpos = 0;
  3438. }
  3439. appendfpath(newpath, r);
  3440. writecp(newpath, r - 1); /* Truncate NULL from end */
  3441. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  3442. dents[cur].flags |= FILE_COPIED;
  3443. }
  3444. break;
  3445. case SEL_SELMUL:
  3446. cfg.copymode ^= 1;
  3447. if (cfg.copymode) {
  3448. if (copybufpos) {
  3449. resetcpind();
  3450. writecp(NULL, 0);
  3451. copybufpos = 0;
  3452. }
  3453. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  3454. copystartid = cur;
  3455. ncp = 0;
  3456. mvprintw(xlines - 1, 0, "selection on\n");
  3457. xdelay();
  3458. continue;
  3459. }
  3460. if (!ncp) { /* Handle range selection */
  3461. #ifndef DIR_LIMITED_COPY
  3462. if (g_crc != crc8fast((uchar *)dents,
  3463. ndents * sizeof(struct entry))) {
  3464. cfg.copymode = 0;
  3465. printwait("dir/content changed", &presel);
  3466. goto nochange;
  3467. }
  3468. #endif
  3469. if (cur < copystartid) {
  3470. copyendid = copystartid;
  3471. copystartid = cur;
  3472. } else
  3473. copyendid = cur;
  3474. } // fallthrough
  3475. case SEL_SELALL:
  3476. if (sel == SEL_SELALL) {
  3477. if (!ndents)
  3478. goto nochange;
  3479. cfg.copymode = 0;
  3480. copybufpos = 0;
  3481. ncp = 0; /* Override single/multi path selection */
  3482. copystartid = 0;
  3483. copyendid = ndents - 1;
  3484. }
  3485. if ((!ncp && copystartid < copyendid) || sel == SEL_SELALL) {
  3486. for (r = copystartid; r <= copyendid; ++r) {
  3487. appendfpath(newpath, mkpath(path, dents[r].name, newpath));
  3488. dents[r].flags |= FILE_COPIED;
  3489. }
  3490. ncp = copyendid - copystartid + 1;
  3491. mvprintw(xlines - 1, 0, "%d selected\n", ncp);
  3492. xdelay();
  3493. }
  3494. if (copybufpos) { /* File path(s) written to the buffer */
  3495. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  3496. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  3497. if (ncp) { /* Some files cherry picked */
  3498. mvprintw(xlines - 1, 0, "%d selected\n", ncp);
  3499. xdelay();
  3500. }
  3501. } else {
  3502. printwait("selection off", &presel);
  3503. goto nochange;
  3504. }
  3505. continue;
  3506. case SEL_SELLST:
  3507. if (showcplist() || showcpfile()) {
  3508. if (cfg.filtermode)
  3509. presel = FILTER;
  3510. break;
  3511. }
  3512. printwait(messages[NONE_SELECTED], &presel);
  3513. goto nochange;
  3514. case SEL_CP:
  3515. case SEL_MV:
  3516. case SEL_RMMUL:
  3517. {
  3518. if (!cpsafe()) {
  3519. presel = MSGWAIT;
  3520. goto nochange;
  3521. }
  3522. switch (sel) {
  3523. case SEL_CP:
  3524. cpstr(g_buf);
  3525. break;
  3526. case SEL_MV:
  3527. mvstr(g_buf);
  3528. break;
  3529. default: /* SEL_RMMUL */
  3530. rmmulstr(g_buf);
  3531. break;
  3532. }
  3533. spawn("sh", "-c", g_buf, path, F_NORMAL);
  3534. if (ndents)
  3535. copycurname();
  3536. if (cfg.filtermode)
  3537. presel = FILTER;
  3538. goto begin;
  3539. }
  3540. case SEL_RM:
  3541. {
  3542. if (!ndents)
  3543. break;
  3544. mkpath(path, dents[cur].name, newpath);
  3545. xrm(newpath);
  3546. /* Don't optimize cur if filtering is on */
  3547. if (!cfg.filtermode && cur && access(newpath, F_OK) == -1)
  3548. move_cursor(cur - 1, 0);
  3549. /* We reduce cur only if it is > 0, so it's at least 0 */
  3550. copycurname();
  3551. if (cfg.filtermode)
  3552. presel = FILTER;
  3553. goto begin;
  3554. }
  3555. case SEL_OPENWITH: // fallthrough
  3556. case SEL_RENAME:
  3557. if (!ndents)
  3558. break; // fallthrough
  3559. case SEL_ARCHIVE: // fallthrough
  3560. case SEL_NEW:
  3561. {
  3562. int dup = 'n';
  3563. switch (sel) {
  3564. case SEL_ARCHIVE:
  3565. r = get_input("archive selection (else current)? [y/Y confirms]");
  3566. if (r == 'y' || r == 'Y') {
  3567. if (!cpsafe()) {
  3568. presel = MSGWAIT;
  3569. goto nochange;
  3570. }
  3571. tmp = NULL;
  3572. } else if (!ndents) {
  3573. printwait("no files", &presel);
  3574. goto nochange;
  3575. } else
  3576. tmp = dents[cur].name;
  3577. tmp = xreadline(tmp, "archive name: ");
  3578. break;
  3579. case SEL_OPENWITH:
  3580. #ifdef NORL
  3581. tmp = xreadline(NULL, "open with: ");
  3582. #else
  3583. presel = 0;
  3584. tmp = getreadline("open with: ", path, ipath, &presel);
  3585. if (presel == MSGWAIT)
  3586. goto nochange;
  3587. #endif
  3588. break;
  3589. case SEL_NEW:
  3590. tmp = xreadline(NULL, "name/link suffix [@ for none]: ");
  3591. break;
  3592. default: /* SEL_RENAME */
  3593. dup = get_input("Press 'r'(ename) / 'd'(uplicate)");
  3594. if (dup == 'r' || dup == 'd') {
  3595. tmp = xreadline(dents[cur].name, "");
  3596. break;
  3597. }
  3598. tmp = NULL;
  3599. }
  3600. if (!tmp || !*tmp)
  3601. break;
  3602. /* Allow only relative, same dir paths */
  3603. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  3604. printwait(messages[STR_INPUT_ID], &presel);
  3605. goto nochange;
  3606. }
  3607. /* Confirm if app is CLI or GUI */
  3608. if (sel == SEL_OPENWITH) {
  3609. r = get_input("cli mode? [y/Y confirms]");
  3610. (r == 'y' || r == 'Y') ? (r = F_CLI)
  3611. : (r = F_NOWAIT | F_NOTRACE | F_MULTI);
  3612. }
  3613. switch (sel) {
  3614. case SEL_ARCHIVE:
  3615. {
  3616. char cmd[ARCHIVE_CMD_LEN];
  3617. get_archive_cmd(cmd, tmp);
  3618. (r == 'y' || r == 'Y') ? archive_selection(cmd, tmp, path)
  3619. : spawn(cmd, tmp, dents[cur].name,
  3620. path, F_NORMAL | F_MULTI);
  3621. break;
  3622. }
  3623. case SEL_OPENWITH:
  3624. mkpath(path, dents[cur].name, newpath);
  3625. spawn(tmp, newpath, NULL, path, r);
  3626. break;
  3627. case SEL_RENAME:
  3628. /* Skip renaming to same name */
  3629. if (strcmp(tmp, dents[cur].name) == 0)
  3630. goto nochange;
  3631. break;
  3632. default:
  3633. break;
  3634. }
  3635. /* Complete OPEN, LAUNCH, ARCHIVE operations */
  3636. if (sel != SEL_NEW && sel != SEL_RENAME) {
  3637. /* Continue in navigate-as-you-type mode, if enabled */
  3638. if (cfg.filtermode)
  3639. presel = FILTER;
  3640. /* Save current */
  3641. copycurname();
  3642. /* Repopulate as directory content may have changed */
  3643. goto begin;
  3644. }
  3645. /* Open the descriptor to currently open directory */
  3646. fd = open(path, O_RDONLY | O_DIRECTORY);
  3647. if (fd == -1) {
  3648. printwarn(&presel);
  3649. goto nochange;
  3650. }
  3651. /* Check if another file with same name exists */
  3652. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  3653. if (sel == SEL_RENAME) {
  3654. /* Overwrite file with same name? */
  3655. r = get_input("overwrite? [y/Y confirms]");
  3656. if (r != 'y' && r != 'Y') {
  3657. close(fd);
  3658. break;
  3659. }
  3660. } else {
  3661. /* Do nothing in case of NEW */
  3662. close(fd);
  3663. printwait("entry exists", &presel);
  3664. goto nochange;
  3665. }
  3666. }
  3667. if (sel == SEL_RENAME) {
  3668. /* Rename the file */
  3669. if (dup == 'd')
  3670. spawn("cp -r", dents[cur].name, tmp, path, F_CLI | F_NOTRACE);
  3671. else if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  3672. close(fd);
  3673. printwarn(&presel);
  3674. goto nochange;
  3675. }
  3676. } else {
  3677. /* Check if it's a dir or file */
  3678. r = get_input("create 'f'(ile) / 'd'(ir) / 's'(ym) / 'h'(ard)?");
  3679. if (r == 'f') {
  3680. r = openat(fd, tmp, O_CREAT, 0666);
  3681. close(r);
  3682. } else if (r == 'd') {
  3683. r = mkdirat(fd, tmp, 0777);
  3684. } else if (r == 's' || r == 'h') {
  3685. if (tmp[0] == '@' && tmp[1] == '\0')
  3686. tmp[0] = '\0';
  3687. r = xlink(tmp, path, newpath, &presel, r);
  3688. close(fd);
  3689. if (r <= 0)
  3690. goto nochange;
  3691. if (cfg.filtermode)
  3692. presel = FILTER;
  3693. if (ndents)
  3694. copycurname();
  3695. goto begin;
  3696. } else {
  3697. close(fd);
  3698. break;
  3699. }
  3700. /* Check if file creation failed */
  3701. if (r == -1) {
  3702. printwarn(&presel);
  3703. close(fd);
  3704. goto nochange;
  3705. }
  3706. }
  3707. close(fd);
  3708. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  3709. goto begin;
  3710. }
  3711. case SEL_EXEC: // fallthrough
  3712. case SEL_SHELL: // fallthrough
  3713. case SEL_PLUGIN: // fallthrough
  3714. case SEL_LAUNCH: // fallthrough
  3715. case SEL_RUNCMD:
  3716. switch (sel) {
  3717. case SEL_EXEC:
  3718. if (!execute_file(cur, path, newpath, &presel))
  3719. goto nochange;
  3720. break;
  3721. case SEL_SHELL:
  3722. spawn(shell, NULL, NULL, path, F_CLI);
  3723. break;
  3724. case SEL_PLUGIN:
  3725. if (!plugindir) {
  3726. printwait("plugins dir missing", &presel);
  3727. goto nochange;
  3728. }
  3729. if (stat(plugindir, &sb) == -1) {
  3730. printwarn(&presel);
  3731. goto nochange;
  3732. }
  3733. /* Must be a directory */
  3734. if (!S_ISDIR(sb.st_mode))
  3735. break;
  3736. cfg.runplugin ^= 1;
  3737. if (!cfg.runplugin && rundir[0]) {
  3738. /*
  3739. * If toggled, and still in the plugin dir,
  3740. * switch to original directory
  3741. */
  3742. if (strcmp(path, plugindir) == 0) {
  3743. xstrlcpy(path, rundir, PATH_MAX);
  3744. xstrlcpy(lastname, runfile, NAME_MAX);
  3745. rundir[0] = runfile[0] = '\0';
  3746. setdirwatch();
  3747. goto begin;
  3748. }
  3749. break;
  3750. }
  3751. /* Check if directory is accessible */
  3752. if (!xdiraccess(plugindir))
  3753. goto nochange;
  3754. xstrlcpy(rundir, path, PATH_MAX);
  3755. xstrlcpy(path, plugindir, PATH_MAX);
  3756. if (ndents)
  3757. xstrlcpy(runfile, dents[cur].name, NAME_MAX);
  3758. cfg.runctx = cfg.curctx;
  3759. lastname[0] = '\0';
  3760. setdirwatch();
  3761. goto begin;
  3762. case SEL_LAUNCH:
  3763. if (getutil(utils[NLAUNCH])) {
  3764. spawn(utils[NLAUNCH], "0", NULL, path, F_NORMAL);
  3765. break;
  3766. } // fallthrough
  3767. default: /* SEL_RUNCMD */
  3768. #ifndef NORL
  3769. if (cfg.picker) {
  3770. #endif
  3771. tmp = xreadline(NULL, "> ");
  3772. #ifndef NORL
  3773. } else {
  3774. presel = 0;
  3775. tmp = getreadline("> ", path, ipath, &presel);
  3776. if (presel == MSGWAIT)
  3777. goto nochange;
  3778. }
  3779. #endif
  3780. if (tmp && tmp[0]) // NOLINT
  3781. spawn(shell, "-c", tmp, path, F_CLI | F_CMD);
  3782. }
  3783. /* Continue in navigate-as-you-type mode, if enabled */
  3784. if (cfg.filtermode)
  3785. presel = FILTER;
  3786. /* Save current */
  3787. if (ndents)
  3788. copycurname();
  3789. /* Repopulate as directory content may have changed */
  3790. goto begin;
  3791. case SEL_SSHFS:
  3792. if (!sshfs_mount(path, newpath, &presel))
  3793. goto nochange;
  3794. lastname[0] = '\0';
  3795. /* Save last working directory */
  3796. xstrlcpy(lastdir, path, PATH_MAX);
  3797. /* Switch to mount point */
  3798. xstrlcpy(path, newpath, PATH_MAX);
  3799. setdirwatch();
  3800. goto begin;
  3801. case SEL_UMOUNT:
  3802. sshfs_unmount(path, newpath, &presel);
  3803. goto nochange;
  3804. case SEL_QUITCD: // fallthrough
  3805. case SEL_QUIT:
  3806. for (r = 0; r < CTX_MAX; ++r)
  3807. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  3808. r = get_input("Quit all contexts? [Enter]");
  3809. break;
  3810. }
  3811. if (!(r == CTX_MAX || r == '\r'))
  3812. break;
  3813. if (sel == SEL_QUITCD) {
  3814. /* In vim picker mode, clear selection and exit */
  3815. if (cfg.picker) {
  3816. /* Picker mode: reset buffer or clear file */
  3817. if (copybufpos)
  3818. cfg.pickraw ? copybufpos = 0 : writecp(NULL, 0);
  3819. } else if (!write_lastdir(path)) {
  3820. presel = MSGWAIT;
  3821. goto nochange;
  3822. }
  3823. }
  3824. return;
  3825. case SEL_QUITCTX:
  3826. fd = cfg.curctx; /* fd used as tmp var */
  3827. for (r = (fd + 1) & ~CTX_MAX;
  3828. (r != fd) && !g_ctx[r].c_cfg.ctxactive;
  3829. r = ((r + 1) & ~CTX_MAX)) {
  3830. };
  3831. if (r != fd) {
  3832. bool copymode = cfg.copymode ? TRUE : FALSE;
  3833. g_ctx[fd].c_cfg.ctxactive = 0;
  3834. /* Switch to next active context */
  3835. path = g_ctx[r].c_path;
  3836. lastdir = g_ctx[r].c_last;
  3837. lastname = g_ctx[r].c_name;
  3838. /* Switch light/detail mode */
  3839. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  3840. /* Set the reverse */
  3841. printptr = cfg.showdetail ? &printent : &printent_long;
  3842. cfg = g_ctx[r].c_cfg;
  3843. /* Continue copy mode */
  3844. cfg.copymode = copymode;
  3845. cfg.curctx = r;
  3846. setdirwatch();
  3847. goto begin;
  3848. }
  3849. return;
  3850. default:
  3851. if (xlines != LINES || xcols != COLS) {
  3852. idle = 0;
  3853. setdirwatch();
  3854. if (ndents)
  3855. copycurname();
  3856. goto begin;
  3857. }
  3858. /* Locker */
  3859. if (idletimeout && idle == idletimeout) {
  3860. idle = 0;
  3861. lock_terminal();
  3862. if (ndents)
  3863. copycurname();
  3864. goto begin;
  3865. }
  3866. goto nochange;
  3867. } /* switch (sel) */
  3868. }
  3869. }
  3870. static void usage(void)
  3871. {
  3872. fprintf(stdout,
  3873. "%s: nnn [-b key] [-d] [-e] [-H] [-i] [-n]\n"
  3874. " [-p file] [-s] [-S] [-v] [-w] [-h] [PATH]\n\n"
  3875. "The missing terminal file manager for X.\n\n"
  3876. "positional args:\n"
  3877. " PATH start dir [default: current dir]\n\n"
  3878. "optional args:\n"
  3879. " -b key open bookmark key\n"
  3880. " -d detail mode\n"
  3881. " -e use exiftool for media info\n"
  3882. " -H show hidden files\n"
  3883. " -i nav-as-you-type mode\n"
  3884. " -n version sort\n"
  3885. " -p file selection file (stdout if '-')\n"
  3886. " -s string filters [default: regex]\n"
  3887. " -S du mode\n"
  3888. " -v show version\n"
  3889. " -w wild load\n"
  3890. " -h show help\n\n"
  3891. "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
  3892. }
  3893. static bool setup_config(void)
  3894. {
  3895. size_t r, len;
  3896. char *xdgcfg = getenv("XDG_CONFIG_HOME");
  3897. bool xdg = FALSE;
  3898. /* Set up configuration file paths */
  3899. if (xdgcfg && xdgcfg[0]) {
  3900. DPRINTF_S(xdgcfg);
  3901. if (xdgcfg[0] == '~') {
  3902. r = xstrlcpy(g_buf, home, PATH_MAX);
  3903. xstrlcpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
  3904. xdgcfg = g_buf;
  3905. DPRINTF_S(xdgcfg);
  3906. }
  3907. if (!xdiraccess(xdgcfg)) {
  3908. xerror();
  3909. return FALSE;
  3910. }
  3911. len = strlen(xdgcfg) + 1 + 12; /* add length of "/nnn/plugins" */
  3912. xdg = TRUE;
  3913. }
  3914. if (!xdg)
  3915. len = strlen(home) + 1 + 20; /* add length of "/.config/nnn/plugins" */
  3916. cfgdir = (char *)malloc(len);
  3917. plugindir = (char *)malloc(len);
  3918. if (!cfgdir || !plugindir) {
  3919. xerror();
  3920. return FALSE;
  3921. }
  3922. if (xdg) {
  3923. xstrlcpy(cfgdir, xdgcfg, len);
  3924. r = len - 12;
  3925. } else {
  3926. r = xstrlcpy(cfgdir, home, len);
  3927. /* Create ~/.config */
  3928. xstrlcpy(cfgdir + r - 1, "/.config", len - r);
  3929. DPRINTF_S(cfgdir);
  3930. if (!create_dir(cfgdir)) {
  3931. xerror();
  3932. return FALSE;
  3933. }
  3934. r += 8; /* length of "/.config" */
  3935. }
  3936. /* Create ~/.config/nnn */
  3937. xstrlcpy(cfgdir + r - 1, "/nnn", len - r);
  3938. DPRINTF_S(cfgdir);
  3939. if (!create_dir(cfgdir)) {
  3940. xerror();
  3941. return FALSE;
  3942. }
  3943. /* Create ~/.config/nnn/plugins */
  3944. xstrlcpy(cfgdir + r + 4 - 1, "/plugins", 9);
  3945. DPRINTF_S(cfgdir);
  3946. xstrlcpy(plugindir, cfgdir, len);
  3947. DPRINTF_S(plugindir);
  3948. if (!create_dir(cfgdir)) {
  3949. xerror();
  3950. return FALSE;
  3951. }
  3952. /* Reset to config path */
  3953. cfgdir[r + 3] = '\0';
  3954. DPRINTF_S(cfgdir);
  3955. /* Set selection file path */
  3956. if (!cfg.picker) {
  3957. /* Length of "/.config/nnn/.selection" */
  3958. g_cppath = (char *)malloc(len + 3);
  3959. r = xstrlcpy(g_cppath, cfgdir, len + 3);
  3960. xstrlcpy(g_cppath + r - 1, "/.selection", 12);
  3961. DPRINTF_S(g_cppath);
  3962. }
  3963. return TRUE;
  3964. }
  3965. static bool set_tmp_path()
  3966. {
  3967. char *path;
  3968. if (xdiraccess("/tmp"))
  3969. g_tmpfplen = xstrlcpy(g_tmpfpath, "/tmp", TMP_LEN_MAX);
  3970. else {
  3971. path = getenv("TMPDIR");
  3972. if (path)
  3973. g_tmpfplen = xstrlcpy(g_tmpfpath, path, TMP_LEN_MAX);
  3974. else {
  3975. fprintf(stderr, "set TMPDIR\n");
  3976. return FALSE;
  3977. }
  3978. }
  3979. return TRUE;
  3980. }
  3981. static void cleanup(void)
  3982. {
  3983. free(g_cppath);
  3984. free(plugindir);
  3985. free(cfgdir);
  3986. free(initpath);
  3987. free(bmstr);
  3988. #ifdef DBGMODE
  3989. disabledbg();
  3990. #endif
  3991. }
  3992. int main(int argc, char *argv[])
  3993. {
  3994. char *arg = NULL;
  3995. int opt;
  3996. while ((opt = getopt(argc, argv, "HSib:denp:svwh")) != -1) {
  3997. switch (opt) {
  3998. case 'S':
  3999. cfg.blkorder = 1;
  4000. nftw_fn = sum_bsizes;
  4001. BLK_SHIFT = ffs(S_BLKSIZE) - 1;
  4002. break;
  4003. case 'd':
  4004. cfg.showdetail = 1;
  4005. printptr = &printent_long;
  4006. break;
  4007. case 'i':
  4008. cfg.filtermode = 1;
  4009. break;
  4010. case 'b':
  4011. arg = optarg;
  4012. break;
  4013. case 'e':
  4014. cfg.metaviewer = EXIFTOOL;
  4015. break;
  4016. case 'H':
  4017. cfg.showhidden = 1;
  4018. break;
  4019. case 'n':
  4020. cmpfn = &xstrverscasecmp;
  4021. break;
  4022. case 'p':
  4023. cfg.picker = 1;
  4024. if (optarg[0] == '-' && optarg[1] == '\0')
  4025. cfg.pickraw = 1;
  4026. else {
  4027. int fd = open(optarg, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
  4028. if (fd == -1) {
  4029. xerror();
  4030. return _FAILURE;
  4031. }
  4032. close(fd);
  4033. g_cppath = realpath(optarg, NULL);
  4034. unlink(g_cppath);
  4035. }
  4036. break;
  4037. case 's':
  4038. cfg.filter_re = 0;
  4039. filterfn = &visible_str;
  4040. break;
  4041. case 'v':
  4042. fprintf(stdout, "%s\n", VERSION);
  4043. return _SUCCESS;
  4044. case 'w':
  4045. cfg.wild = 1;
  4046. break;
  4047. case 'h':
  4048. usage();
  4049. return _SUCCESS;
  4050. default:
  4051. usage();
  4052. return _FAILURE;
  4053. }
  4054. }
  4055. /* Confirm we are in a terminal */
  4056. if (!cfg.picker && !(isatty(0) && isatty(1)))
  4057. exit(1);
  4058. /* Get the context colors; copier used as tmp var */
  4059. copier = xgetenv(env_cfg[NNN_CONTEXT_COLORS], "4444");
  4060. opt = 0;
  4061. while (opt < CTX_MAX) {
  4062. if (*copier) {
  4063. if (*copier < '0' || *copier > '7') {
  4064. fprintf(stderr, "0 <= code <= 7\n");
  4065. return _FAILURE;
  4066. }
  4067. g_ctx[opt].color = *copier - '0';
  4068. ++copier;
  4069. } else
  4070. g_ctx[opt].color = 4;
  4071. ++opt;
  4072. }
  4073. #ifdef DBGMODE
  4074. enabledbg();
  4075. #endif
  4076. atexit(cleanup);
  4077. home = getenv("HOME");
  4078. if (!home) {
  4079. fprintf(stderr, "set HOME\n");
  4080. return _FAILURE;
  4081. }
  4082. DPRINTF_S(home);
  4083. if (!setup_config())
  4084. return _FAILURE;
  4085. /* Get custom opener, if set */
  4086. opener = xgetenv(env_cfg[NNN_OPENER], utils[OPENER]);
  4087. DPRINTF_S(opener);
  4088. /* Parse bookmarks string */
  4089. if (!parsebmstr()) {
  4090. fprintf(stderr, "%s\n", env_cfg[NNN_BMS]);
  4091. return _FAILURE;
  4092. }
  4093. if (arg) { /* Open a bookmark directly */
  4094. if (arg[1] || (initpath = get_bm_loc(NULL, *arg)) == NULL) {
  4095. fprintf(stderr, "%s\n", messages[STR_INVBM_KEY]);
  4096. return _FAILURE;
  4097. }
  4098. } else if (argc == optind) {
  4099. /* Start in the current directory */
  4100. initpath = getcwd(NULL, PATH_MAX);
  4101. if (!initpath)
  4102. initpath = "/";
  4103. } else {
  4104. arg = argv[optind];
  4105. if (strlen(arg) > 7 && arg[0] == 'f' && arg[1] == 'i' && arg[2] == 'l'
  4106. && arg[3] == 'e' && arg[4] == ':' && arg[5] == '/' && arg[6] == '/')
  4107. arg = arg + 7;
  4108. initpath = realpath(arg, NULL);
  4109. DPRINTF_S(initpath);
  4110. if (!initpath) {
  4111. xerror();
  4112. return _FAILURE;
  4113. }
  4114. /*
  4115. * If nnn is set as the file manager, applications may try to open
  4116. * files by invoking nnn. In that case pass the file path to the
  4117. * desktop opener and exit.
  4118. */
  4119. struct stat sb;
  4120. if (stat(initpath, &sb) == -1) {
  4121. xerror();
  4122. return _FAILURE;
  4123. }
  4124. if (S_ISREG(sb.st_mode)) {
  4125. execlp(opener, opener, arg, NULL);
  4126. return _SUCCESS;
  4127. }
  4128. }
  4129. /* Edit text in EDITOR, if opted */
  4130. if (xgetenv_set(env_cfg[NNN_USE_EDITOR]))
  4131. cfg.useeditor = 1;
  4132. /* Get VISUAL/EDITOR */
  4133. editor = xgetenv(envs[VISUAL], xgetenv(envs[EDITOR], "vi"));
  4134. DPRINTF_S(getenv(envs[VISUAL]));
  4135. DPRINTF_S(getenv(envs[EDITOR]));
  4136. DPRINTF_S(editor);
  4137. /* Get PAGER */
  4138. pager = xgetenv(envs[PAGER], "less");
  4139. DPRINTF_S(pager);
  4140. /* Get SHELL */
  4141. shell = xgetenv(envs[SHELL], "sh");
  4142. DPRINTF_S(shell);
  4143. DPRINTF_S(getenv("PWD"));
  4144. #ifdef LINUX_INOTIFY
  4145. /* Initialize inotify */
  4146. inotify_fd = inotify_init1(IN_NONBLOCK);
  4147. if (inotify_fd < 0) {
  4148. xerror();
  4149. return _FAILURE;
  4150. }
  4151. #elif defined(BSD_KQUEUE)
  4152. kq = kqueue();
  4153. if (kq < 0) {
  4154. xerror();
  4155. return _FAILURE;
  4156. }
  4157. #endif
  4158. /* Set nnn nesting level, idletimeout used as tmp var */
  4159. idletimeout = xatoi(getenv(env_cfg[NNNLVL]));
  4160. setenv(env_cfg[NNNLVL], xitoa(++idletimeout), 1);
  4161. /* Get locker wait time, if set */
  4162. idletimeout = xatoi(getenv(env_cfg[NNN_IDLE_TIMEOUT]));
  4163. DPRINTF_U(idletimeout);
  4164. if (xgetenv_set(env_cfg[NNN_TRASH]))
  4165. cfg.trash = 1;
  4166. /* Prefix for temporary files */
  4167. if (!set_tmp_path())
  4168. return _FAILURE;
  4169. /* Get the clipboard copier, if set */
  4170. copier = getenv(env_cfg[NNN_COPIER]);
  4171. /* Disable auto-select if opted */
  4172. if (xgetenv_set(env_cfg[NNN_NO_AUTOSELECT]))
  4173. cfg.autoselect = 0;
  4174. /* Disable opening files on right arrow and `l` */
  4175. if (xgetenv_set(env_cfg[NNN_RESTRICT_NAV_OPEN]))
  4176. cfg.nonavopen = 1;
  4177. #ifdef __linux__
  4178. if (!xgetenv_set(env_cfg[NNN_OPS_PROG])) {
  4179. cp[5] = cp[4];
  4180. cp[2] = cp[4] = ' ';
  4181. mv[5] = mv[4];
  4182. mv[2] = mv[4] = ' ';
  4183. }
  4184. #endif
  4185. /* Ignore/handle certain signals */
  4186. struct sigaction act = {.sa_handler = sigint_handler};
  4187. if (sigaction(SIGINT, &act, NULL) < 0) {
  4188. xerror();
  4189. return _FAILURE;
  4190. }
  4191. signal(SIGQUIT, SIG_IGN);
  4192. /* Test initial path */
  4193. if (!xdiraccess(initpath)) {
  4194. xerror();
  4195. return _FAILURE;
  4196. }
  4197. /* Set locale */
  4198. setlocale(LC_ALL, "");
  4199. #ifndef NORL
  4200. #if RL_READLINE_VERSION >= 0x0603
  4201. /* readline would overwrite the WINCH signal hook */
  4202. rl_change_environment = 0;
  4203. #endif
  4204. /* Bind TAB to cycling */
  4205. rl_variable_bind("completion-ignore-case", "on");
  4206. #ifdef __linux__
  4207. rl_bind_key('\t', rl_menu_complete);
  4208. #else
  4209. rl_bind_key('\t', rl_complete);
  4210. #endif
  4211. read_history(NULL);
  4212. #endif
  4213. if (!initcurses())
  4214. return _FAILURE;
  4215. browse(initpath);
  4216. exitcurses();
  4217. #ifndef NORL
  4218. write_history(NULL);
  4219. #endif
  4220. if (cfg.pickraw) {
  4221. if (copybufpos) {
  4222. opt = selectiontofd(1, NULL);
  4223. if (opt != (int)(copybufpos))
  4224. xerror();
  4225. }
  4226. } else if (!cfg.picker && g_cppath)
  4227. unlink(g_cppath);
  4228. /* Free the copy buffer */
  4229. free(pcopybuf);
  4230. #ifdef LINUX_INOTIFY
  4231. /* Shutdown inotify */
  4232. if (inotify_wd >= 0)
  4233. inotify_rm_watch(inotify_fd, inotify_wd);
  4234. close(inotify_fd);
  4235. #elif defined(BSD_KQUEUE)
  4236. if (event_fd >= 0)
  4237. close(event_fd);
  4238. close(kq);
  4239. #endif
  4240. return _SUCCESS;
  4241. }