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

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