My build of nnn with minor changes
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

5953 wiersze
130 KiB

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