My build of nnn with minor changes
 
 
 
 
 
 

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