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

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