My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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