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

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