My build of nnn with minor changes
 
 
 
 
 
 

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