My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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