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

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