My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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