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.
 
 
 
 
 
 

4480 lines
97 KiB

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