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

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