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.
 
 
 
 
 
 

5068 lines
112 KiB

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