My build of nnn with minor changes
 
 
 
 
 
 

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