My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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