My build of nnn with minor changes
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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