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

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