My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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