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

4906 linhas
107 KiB

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