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