My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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