My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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