My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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