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

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