My build of nnn with minor changes
 
 
 
 
 
 

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