Sync before addind submodules

This commit is contained in:
mintycube 2024-06-25 16:52:46 +05:00
parent c712824ba8
commit f8a571435e
224 changed files with 584 additions and 23053 deletions

View File

@ -5,7 +5,7 @@ width = 200
height = 500
origin = top-right
offset = 15x15
corner_radius = 10
corner_radius = 0
scale = 0
notification_limit = 0
progress_bar = true

View File

@ -175,6 +175,7 @@ cmd sanitize ${{
}}
# Bindings
map <esc> :quit
map / :fzf_search
map ? :fzf_grep
map <c-l> live_server
@ -209,10 +210,9 @@ map V push :!nvim<space>
map W $setsid -f $TERMINAL >/dev/null 2>&1
map . set hidden!
map U $printf "%s" "$fx" | xclip -selection clipboard
map u $printf "%s" "$fx" | sed 's/.*\///' | xclip -selection clipboard
map . $printf "%s" "$fx" | sed -E 's/^.+\[/https:\/\/www.youtube.com\/watch?v=/' | sed -E 's/\]\..+//' | xclip -selection clipboard
map <gt> $printf "%s" "$fx" | sed -E 's/^.+\[/https:\/\/piped.video\/watch?v=/' | sed -E 's/\]\..+//' | xclip -selection clipboard
map T $sxiv -t "$(pwd)" # opens thumbnail mode
map <c-l> unselect

View File

@ -1,14 +1,13 @@
vim.g.mapleader = " "
vim.g.maplocalleader = " "
vim.cmd.colorscheme("default")
-- vim.opt.background = "light"
require("options")
require("manager")
require("autocommands")
require("mappings")
-- vim.cmd("hi Keyword gui=italic,bold cterm=italic,bold")
vim.cmd("hi Comment gui=italic cterm=italic")
vim.api.nvim_set_hl(0, "DiagnosticVirtualTextError", { link = "Comment" })
vim.api.nvim_set_hl(0, "DiagnosticVirtualTextInfo", { link = "Comment" })
vim.api.nvim_set_hl(0, "DiagnosticVirtualTextWarn", { link = "Comment" })

View File

@ -9,14 +9,14 @@
"cmp-spell": { "branch": "master", "commit": "694a4e50809d6d645c1ea29015dad0c293f019d6" },
"cmp-vimtex": { "branch": "master", "commit": "a64b1b5eec0460144c91c4f20a45c74b8ded48ae" },
"cmp_luasnip": { "branch": "master", "commit": "05a9ab28b53f71d1aece421ef32fee2cb857a843" },
"flit.nvim": { "branch": "main", "commit": "56490317983218b09698f8c960c3669958b12b32" },
"friendly-snippets": { "branch": "main", "commit": "700c4a25caacbb4648c9a27972c2fe203948e0c2" },
"fzf-lua": { "branch": "main", "commit": "70b050799ee733e32f8e0a209beb978573d3849f" },
"gitsigns.nvim": { "branch": "main", "commit": "de18f6b749f6129eb9042a2038590872df4c94a9" },
"flit.nvim": { "branch": "main", "commit": "a9be4e76c30a128f1e51af448c8321bf8366bcd4" },
"friendly-snippets": { "branch": "main", "commit": "682157939e57bd6a2c86277dfd4d6fbfce63dbac" },
"fzf-lua": { "branch": "main", "commit": "235119b859d1d3dc136a5dbfd24b626b5af72130" },
"gitsigns.nvim": { "branch": "main", "commit": "0dc886637f9686b7cfd245a4726f93abeab19d4a" },
"harpoon": { "branch": "harpoon2", "commit": "0378a6c428a0bed6a2781d459d7943843f374bce" },
"indent-blankline.nvim": { "branch": "master", "commit": "d98f537c3492e87b6dc6c2e3f66ac517528f406f" },
"lazy.nvim": { "branch": "main", "commit": "eb4957442e3182f051b0ae11da32e06d22c190e3" },
"leap.nvim": { "branch": "main", "commit": "0d15057cc47fa49f6609bf364f5ad3842f08c58c" },
"lazy.nvim": { "branch": "main", "commit": "bc620783663ab09d16bff9fdecc07da65b2a1528" },
"leap.nvim": { "branch": "main", "commit": "eca8108dcd5f41fbde2a674dceb58b81ed887dc8" },
"lf.nvim": { "branch": "master", "commit": "69ab1efcffee6928bf68ac9bd0c016464d9b2c8b" },
"lsp-zero.nvim": { "branch": "v3.x", "commit": "16de3b18c5f7b6230d89b8e64ce9a4801b6f8d08" },
"lspkind.nvim": { "branch": "master", "commit": "1735dd5a5054c1fb7feaf8e8658dbab925f4f0cf" },
@ -26,9 +26,9 @@
"mason-lspconfig.nvim": { "branch": "main", "commit": "37a336b653f8594df75c827ed589f1c91d91ff6c" },
"mason-nvim-dap.nvim": { "branch": "main", "commit": "f5425eb1d0d794f0305d5eeebddabb74614683ff" },
"mason.nvim": { "branch": "main", "commit": "0950b15060067f752fde13a779a994f59516ce3d" },
"mini.ai": { "branch": "main", "commit": "a7e90f110e6274262616311b93cef12cd2667a2d" },
"mini.surround": { "branch": "main", "commit": "27096c1a27324ee8f2044ea2adc77366d8a782de" },
"none-ls.nvim": { "branch": "main", "commit": "8691504118b252d64fc5023a104aedd100ab754a" },
"mini.ai": { "branch": "main", "commit": "9fef1097bca44616133cde6a6769e7aa07d12d7d" },
"mini.surround": { "branch": "main", "commit": "c40ac9c0060467a82430fab12d30395c5768b5e4" },
"none-ls.nvim": { "branch": "main", "commit": "cc0a3c45047e3daf85d07c1571d65476cfce6480" },
"nvim-autopairs": { "branch": "master", "commit": "c15de7e7981f1111642e7e53799e1211d4606cb9" },
"nvim-cmp": { "branch": "main", "commit": "a110e12d0b58eefcf5b771f533fc2cf3050680ac" },
"nvim-colorizer.lua": { "branch": "master", "commit": "85855b38011114929f4058efc97af1059ab3e41d" },
@ -36,11 +36,11 @@
"nvim-dap-ui": { "branch": "master", "commit": "b7267003ba4dd860350be86f75b9d9ea287cedca" },
"nvim-dap-virtual-text": { "branch": "master", "commit": "d7c695ea39542f6da94ee4d66176f5d660ab0a77" },
"nvim-html-css": { "branch": "main", "commit": "c514bd27ad560636ed39dea3e370b3103754e244" },
"nvim-lspconfig": { "branch": "master", "commit": "4d38bece98300e3e5cd24a9aa0d0ebfea4951c16" },
"nvim-lspconfig": { "branch": "master", "commit": "6806370929cf6a35be6e5e0e74588515a4356e4d" },
"nvim-markdown": { "branch": "master", "commit": "bf5c87788156f072cfb87b994844424b164b5b44" },
"nvim-nio": { "branch": "master", "commit": "7969e0a8ffabdf210edd7978ec954a47a737bbcc" },
"nvim-spectre": { "branch": "master", "commit": "ec67d4b5370094b923dfcf6b09b39142f2964861" },
"nvim-treesitter": { "branch": "master", "commit": "9636d5a3f4f531256fba147a30b882c44f28fae1" },
"nvim-treesitter": { "branch": "master", "commit": "b967bbc27b564001c3d3b8ea93444cf6d0b21d23" },
"nvim-treesitter-textobjects": { "branch": "master", "commit": "34867c69838078df7d6919b130c0541c0b400c47" },
"nvim-ts-autotag": { "branch": "main", "commit": "06fe07d7523ba8c755fac7c913fceba43b1720ee" },
"nvim-ts-context-commentstring": { "branch": "main", "commit": "cb064386e667def1d241317deed9fd1b38f0dc2e" },
@ -53,13 +53,13 @@
"promise-async": { "branch": "main", "commit": "28c1d5a295eb5310afa2523d4ae9aa41ec5a9de2" },
"qalc.nvim": { "branch": "main", "commit": "1b800b5d8f956c4780f079333cba4d8fb8c335a3" },
"qalculate.vim": { "branch": "main", "commit": "d0269924bfa623bf0f73218041241cc83e97379e" },
"refactoring.nvim": { "branch": "master", "commit": "d2786877c91aa409c824f27b4ce8a9f560dda60a" },
"refactoring.nvim": { "branch": "master", "commit": "66fea340c84f43df696fe6d9f2a90796fbe9c9cf" },
"todo-comments.nvim": { "branch": "main", "commit": "51e10f838e84b4756c16311d0b1ef0972c6482d2" },
"toggleterm.nvim": { "branch": "main", "commit": "fee58a0473fd92b28c34f8f724e4918b15ba30a3" },
"trouble.nvim": { "branch": "main", "commit": "60b0ac3772e991bc194207afc28368a5f15d913a" },
"trouble.nvim": { "branch": "main", "commit": "2d8610a07033f2b367e71230ab128f8b89c2639d" },
"undotree": { "branch": "main", "commit": "eab459ab87dd249617b5f7187bb69e614a083047" },
"vim-repeat": { "branch": "master", "commit": "24afe922e6a05891756ecf331f39a1f6743d3d5a" },
"vimtex": { "branch": "master", "commit": "0587a064f675fd85cdfb8a76d6a3ff698af3944b" },
"vimtex": { "branch": "master", "commit": "8ed94566e6fe3f5b163131dc374d224d2d320db7" },
"which-key.nvim": { "branch": "main", "commit": "0099511294f16b81c696004fa6a403b0ae61f7a0" },
"zen-mode.nvim": { "branch": "main", "commit": "78557d972b4bfbb7488e17b5703d25164ae64e6a" }
}

View File

@ -115,6 +115,54 @@ vim.api.nvim_create_autocmd({ "BufEnter" }, {
group = vim.api.nvim_create_augroup("CloseLast", { clear = true }),
})
vim.cmd([[
command -bar -nargs=? -complete=help HelpCurwin call HelpCurwin(<q-args>)
let g:did_open_help = v:false
function! HelpCurwin(subject) abort
let mods = 'silent noautocmd keepalt'
if !g:did_open_help
execute mods .. ' help'
execute mods .. ' helpclose'
let g:did_open_help = v:true
endif
if !empty(getcompletion(a:subject, 'help'))
execute mods .. ' edit ' .. &helpfile
set buftype=help
endif
return 'help ' .. a:subject
endfunction
]])
-- Function to check if the buffer is empty
local function is_buffer_empty(buf)
local line_count = vim.api.nvim_buf_line_count(buf)
if line_count > 1 then
return false
end
local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
return lines[1] == ''
end
-- Function to close all empty buffers if the current buffer is 'help'
local function close_empty_buffers_if_help()
local current_buf = vim.api.nvim_get_current_buf()
if vim.bo.ft == 'help' then
local buffers = vim.api.nvim_list_bufs()
for _, buf in ipairs(buffers) do
if buf ~= current_buf and vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_is_loaded(buf) and is_buffer_empty(buf) then
vim.api.nvim_buf_delete(buf, { force = true })
end
end
end
end
vim.api.nvim_create_autocmd('BufWinEnter', {
callback = close_empty_buffers_if_help,
group = vim.api.nvim_create_augroup("help_in_fullscreen", { clear = true }),
})
-- [[ Autosave ]]
-- vim.api.nvim_create_autocmd({ "FocusLost", "BufLeave", "BufWinLeave", "InsertLeave" }, {
-- callback = function()

View File

@ -1,3 +1,7 @@
-- colorscheme
vim.cmd.colorscheme("default")
-- vim.opt.background = "light"
-- indentation
vim.opt.tabstop = 2
vim.opt.softtabstop = 2

View File

@ -13,7 +13,7 @@ return {
sources = {
-- Linting
lint.cppcheck, -- for c,cpp ( Install manually using pacman )
lint.proselint, -- for md
-- lint.proselint, -- for md
lint.stylelint, -- for css
lint.codespell, -- general code spellings

View File

@ -1,7 +1,21 @@
{
"shebang": {
"prefix": "shebang",
"body": [
"#!/usr/bin/env ${1:sh}",
"#",
"# ${2:Description of the script.}$0"
],
"description": [
"Shebang to specify what shell is going to run the script by default. It includes a description of the script. \n\nIt must be defined in the first line of the script.\n\nBy using #!/usr/bin/env we are making the shebang portable, meaning it is going to work correctly even if the interpreter is not located under /usr/bin"
]
},
"Print Name and Date": {
"prefix": "signature",
"body": ["${0:Author}", "${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}"],
"body": [
"${0:Author}",
"${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}"
],
"description": "Signature"
},
"MIT": {

View File

@ -1,3 +0,0 @@
*.o
dmenu
stest

View File

@ -1,30 +0,0 @@
MIT/X Consortium License
© 2006-2019 Anselm R Garbe <anselm@garbe.ca>
© 2006-2008 Sander van Dijk <a.h.vandijk@gmail.com>
© 2006-2007 Michał Janeczek <janeczek@gmail.com>
© 2007 Kris Maglione <jg@suckless.org>
© 2009 Gottox <gottox@s01.de>
© 2009 Markus Schnalke <meillo@marmaro.de>
© 2009 Evan Gates <evan.gates@gmail.com>
© 2010-2012 Connor Lane Smith <cls@lubutu.com>
© 2014-2022 Hiltjo Posthuma <hiltjo@codemadness.org>
© 2015-2019 Quentin Rameau <quinq@fifth.space>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,58 +0,0 @@
# dmenu - dynamic menu
# See LICENSE file for copyright and license details.
include config.mk
SRC = drw.c dmenu.c stest.c util.c
OBJ = $(SRC:.c=.o)
all: dmenu stest
.c.o:
$(CC) -c $(CFLAGS) $<
config.h:
cp config.def.h $@
$(OBJ): arg.h config.h config.mk drw.h
dmenu: dmenu.o drw.o util.o
$(CC) -o $@ dmenu.o drw.o util.o $(LDFLAGS)
stest: stest.o
$(CC) -o $@ stest.o $(LDFLAGS)
clean:
rm -f dmenu stest $(OBJ) dmenu-$(VERSION).tar.gz
dist: clean
mkdir -p dmenu-$(VERSION)
cp LICENSE Makefile README arg.h config.mk dmenu.1\
drw.h util.h dmenu_path dmenu_run stest.1 $(SRC)\
dmenu-$(VERSION)
tar -cf dmenu-$(VERSION).tar dmenu-$(VERSION)
gzip dmenu-$(VERSION).tar
rm -rf dmenu-$(VERSION)
install: all
mkdir -p $(DESTDIR)$(PREFIX)/bin
cp -f dmenu dmenu_path dmenu_run stest $(DESTDIR)$(PREFIX)/bin
chmod 755 $(DESTDIR)$(PREFIX)/bin/dmenu
chmod 755 $(DESTDIR)$(PREFIX)/bin/dmenu_path
chmod 755 $(DESTDIR)$(PREFIX)/bin/dmenu_run
chmod 755 $(DESTDIR)$(PREFIX)/bin/stest
mkdir -p $(DESTDIR)$(MANPREFIX)/man1
sed "s/VERSION/$(VERSION)/g" < dmenu.1 > $(DESTDIR)$(MANPREFIX)/man1/dmenu.1
sed "s/VERSION/$(VERSION)/g" < stest.1 > $(DESTDIR)$(MANPREFIX)/man1/stest.1
chmod 644 $(DESTDIR)$(MANPREFIX)/man1/dmenu.1
chmod 644 $(DESTDIR)$(MANPREFIX)/man1/stest.1
uninstall:
rm -f $(DESTDIR)$(PREFIX)/bin/dmenu\
$(DESTDIR)$(PREFIX)/bin/dmenu_path\
$(DESTDIR)$(PREFIX)/bin/dmenu_run\
$(DESTDIR)$(PREFIX)/bin/stest\
$(DESTDIR)$(MANPREFIX)/man1/dmenu.1\
$(DESTDIR)$(MANPREFIX)/man1/stest.1
.PHONY: all clean dist install uninstall

View File

@ -1,24 +0,0 @@
# dmenu
This build of dmenu was generated using [dmenu-flexipatch](https://github.com/bakkeby/dmenu-flexipatch.git) and finalized by [flexipatch-finalizer](https://github.com/bakkeby/flexipatch-finalizer).
## Patches
The patches used are listed below:
- border [link](http://tools.suckless.org/dmenu/patches/border)
- center [link](https://tools.suckless.org/dmenu/patches/center)
- ctrl_v to paste
- fuzzymatch [link](https://tools.suckless.org/dmenu/patches/fuzzymatch)
- fzfexpect [link](https://github.com/DAFF0D11/dafmenu) [link](https://github.com/DAFF0D11/dafmenu/blob/master/patches/dmenu-fzfexpect-5.1.diff)
- grid [link](https://tools.suckless.org/dmenu/patches/grid)
- gridnav [link](https://tools.suckless.org/dmenu/patches/gridnav)
- instant [link](https://tools.suckless.org/dmenu/patches/instant)
- line height [link](http://tools.suckless.org/dmenu/patches/line-height)
- mouse support [link](https://tools.suckless.org/dmenu/patches/mouse-support)
- password [link](https://tools.suckless.org/dmenu/patches/password)
- scroll [link](https://tools.suckless.org/dmenu/patches/scroll)
- tsv [link](https://tools.suckless.org/dmenu/patches/tsv)
- vertfull [link](https://tools.suckless.org/dmenu/patches/vertfull)
- xresources [link](https://tools.suckless.org/dmenu/patches/xresources)
- xyw [link](https://tools.suckless.org/dmenu/patches/xyw)

View File

@ -1,49 +0,0 @@
/*
* Copy me if you can.
* by 20h
*/
#ifndef ARG_H__
#define ARG_H__
extern char *argv0;
/* use main(int argc, char *argv[]) */
#define ARGBEGIN for (argv0 = *argv, argv++, argc--;\
argv[0] && argv[0][0] == '-'\
&& argv[0][1];\
argc--, argv++) {\
char argc_;\
char **argv_;\
int brk_;\
if (argv[0][1] == '-' && argv[0][2] == '\0') {\
argv++;\
argc--;\
break;\
}\
for (brk_ = 0, argv[0]++, argv_ = argv;\
argv[0][0] && !brk_;\
argv[0]++) {\
if (argv_ != argv)\
break;\
argc_ = argv[0][0];\
switch (argc_)
#define ARGEND }\
}
#define ARGC() argc_
#define EARGF(x) ((argv[0][1] == '\0' && argv[1] == NULL)?\
((x), abort(), (char *)0) :\
(brk_ = 1, (argv[0][1] != '\0')?\
(&argv[0][1]) :\
(argc--, argv++, argv[0])))
#define ARGF() ((argv[0][1] == '\0' && argv[1] == NULL)?\
(char *)0 :\
(brk_ = 1, (argv[0][1] != '\0')?\
(&argv[0][1]) :\
(argc--, argv++, argv[0])))
#endif

View File

@ -1,39 +0,0 @@
/* See LICENSE file for copyright and license details. */
/* Default settings; can be overriden by command line. */
static int topbar = 1; /* -b option; if 0, dmenu appears at bottom */
static int fuzzy = 1; /* -F option; if 0, dmenu doesn't use fuzzy matching */
static int instant = 0; /* -n option; if 1, selects matching item without the need to press enter */
static int center = 0; /* -c option; if 0, dmenu won't be centered on the screen */
static int min_width = 680; /* minimum width when centered */
/* -fn option overrides fonts[0]; default X11 font or font set */
static char *fonts[] =
{
"JetBrainsMono Nerd Font Semiblod:size=12"
};
static const char *prompt = NULL; /* -p option; prompt to the left of input field */
static
char *colors[][2] = {
/* fg bg */
[SchemeNorm] = { "#bbbbbb", "#222222" },
[SchemeSel] = { "#eeeeee", "#005577" },
[SchemeOut] = { "#000000", "#00ffff" },
[SchemeBorder] = { "#000000", "#005577" },
};
/* -l option; if nonzero, dmenu uses vertical list with given number of lines */
static unsigned int lines = 0;
/* -g option; if nonzero, dmenu uses a grid comprised of columns and lines */
static unsigned int columns = 0;
static unsigned int lineheight = 0; /* -h option; minimum height of a menu line */
static unsigned int min_lineheight = 8;
/*
* Characters not considered part of a word while deleting words
* for example: " /?\"&[]"
*/
static const char worddelimiters[] = " ";
/* Size of the window border */
static unsigned int border_width = 0;

View File

@ -1,42 +0,0 @@
# dmenu version
VERSION = 5.2
# paths
PREFIX = /usr/local
MANPREFIX = $(PREFIX)/share/man
X11INC = /usr/X11R6/include
X11LIB = /usr/X11R6/lib
# Xinerama, comment if you don't want it
XINERAMALIBS = -lXinerama
XINERAMAFLAGS = -DXINERAMA
# freetype
FREETYPELIBS = -lfontconfig -lXft
FREETYPEINC = /usr/include/freetype2
# OpenBSD (uncomment)
#FREETYPEINC = $(X11INC)/freetype2
#MANPREFIX = ${PREFIX}/man
# uncomment on RHEL for strcasecmp
#EXTRAFLAGS=-D_GNU_SOURCE
# Uncomment this for the alpha patch / ALPHA_PATCH
XRENDER = -lXrender
# Uncomment for the pango patch / PANGO_PATCH
#PANGOINC = `pkg-config --cflags xft pango pangoxft`
#PANGOLIB = `pkg-config --libs xft pango pangoxft`
# includes and libs
INCS = -I$(X11INC) -I$(FREETYPEINC) ${PANGOINC}
LIBS = -L$(X11LIB) -lX11 $(XINERAMALIBS) $(FREETYPELIBS) -lm $(XRENDER) ${PANGOLIB}
# flags
CPPFLAGS = -D_DEFAULT_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_POSIX_C_SOURCE=200809L -DVERSION=\"$(VERSION)\" $(XINERAMAFLAGS) $(EXTRAFLAGS)
CFLAGS = -std=c99 -pedantic -Wall -Os $(INCS) $(CPPFLAGS)
LDFLAGS = $(LIBS)
# compiler and linker
CC = cc

View File

@ -1,194 +0,0 @@
.TH DMENU 1 dmenu\-VERSION
.SH NAME
dmenu \- dynamic menu
.SH SYNOPSIS
.B dmenu
.RB [ \-bfiv ]
.RB [ \-l
.IR lines ]
.RB [ \-m
.IR monitor ]
.RB [ \-p
.IR prompt ]
.RB [ \-fn
.IR font ]
.RB [ \-nb
.IR color ]
.RB [ \-nf
.IR color ]
.RB [ \-sb
.IR color ]
.RB [ \-sf
.IR color ]
.RB [ \-w
.IR windowid ]
.P
.BR dmenu_run " ..."
.SH DESCRIPTION
.B dmenu
is a dynamic menu for X, which reads a list of newline\-separated items from
stdin. When the user selects an item and presses Return, their choice is printed
to stdout and dmenu terminates. Entering text will narrow the items to those
matching the tokens in the input.
.P
.B dmenu_run
is a script used by
.IR dwm (1)
which lists programs in the user's $PATH and runs the result in their $SHELL.
.SH OPTIONS
.TP
.B \-b
dmenu appears at the bottom of the screen.
.TP
.B \-f
dmenu grabs the keyboard before reading stdin if not reading from a tty. This
is faster, but will lock up X until stdin reaches end\-of\-file.
.TP
.B \-i
dmenu matches menu items case insensitively.
.TP
.BI \-l " lines"
dmenu lists items vertically, with the given number of lines.
.TP
.BI \-m " monitor"
dmenu is displayed on the monitor number supplied. Monitor numbers are starting
from 0.
.TP
.BI \-p " prompt"
defines the prompt to be displayed to the left of the input field.
.TP
.BI \-fn " font"
defines the font or font set used.
.TP
.BI \-nb " color"
defines the normal background color.
.IR #RGB ,
.IR #RRGGBB ,
and X color names are supported.
.TP
.BI \-nf " color"
defines the normal foreground color.
.TP
.BI \-sb " color"
defines the selected background color.
.TP
.BI \-sf " color"
defines the selected foreground color.
.TP
.B \-v
prints version information to stdout, then exits.
.TP
.BI \-w " windowid"
embed into windowid.
.SH USAGE
dmenu is completely controlled by the keyboard. Items are selected using the
arrow keys, page up, page down, home, and end.
.TP
.B Tab
Copy the selected item to the input field.
.TP
.B Return
Confirm selection. Prints the selected item to stdout and exits, returning
success.
.TP
.B Ctrl-Return
Confirm selection. Prints the selected item to stdout and continues.
.TP
.B Shift\-Return
Confirm input. Prints the input text to stdout and exits, returning success.
.TP
.B Escape
Exit without selecting an item, returning failure.
.TP
.B Ctrl-Left
Move cursor to the start of the current word
.TP
.B Ctrl-Right
Move cursor to the end of the current word
.TP
.B C\-a
Home
.TP
.B C\-b
Left
.TP
.B C\-c
Escape
.TP
.B C\-d
Delete
.TP
.B C\-e
End
.TP
.B C\-f
Right
.TP
.B C\-g
Escape
.TP
.B C\-h
Backspace
.TP
.B C\-i
Tab
.TP
.B C\-j
Return
.TP
.B C\-J
Shift-Return
.TP
.B C\-k
Delete line right
.TP
.B C\-m
Return
.TP
.B C\-M
Shift-Return
.TP
.B C\-n
Down
.TP
.B C\-p
Up
.TP
.B C\-u
Delete line left
.TP
.B C\-w
Delete word left
.TP
.B C\-y
Paste from primary X selection
.TP
.B C\-Y
Paste from X clipboard
.TP
.B M\-b
Move cursor to the start of the current word
.TP
.B M\-f
Move cursor to the end of the current word
.TP
.B M\-g
Home
.TP
.B M\-G
End
.TP
.B M\-h
Up
.TP
.B M\-j
Page down
.TP
.B M\-k
Page up
.TP
.B M\-l
Down
.SH SEE ALSO
.IR dwm (1),
.IR stest (1)

View File

@ -1,1041 +0,0 @@
/* See LICENSE file for copyright and license details. */
#include <ctype.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#ifdef XINERAMA
#include <X11/extensions/Xinerama.h>
#endif
#include <X11/Xft/Xft.h>
/* Patch incompatibility overrides */
#include "drw.h"
#include "util.h"
#include <stdbool.h>
/* macros */
#define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
* MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
/* enums */
enum {
SchemeNorm,
SchemeSel,
SchemeOut,
SchemeBorder,
SchemeLast,
}; /* color schemes */
struct item {
char *text;
char *stext;
struct item *left, *right;
int out;
double distance;
};
static char text[BUFSIZ] = "";
static char *embed;
static int bh, mw, mh;
static int dmx = 0, dmy = 0; /* put dmenu at these x and y offsets */
static unsigned int dmw = 0; /* make dmenu this wide */
static int inputw = 0, promptw;
static int passwd = 0;
static int lrpad; /* sum of left and right padding */
static size_t cursor;
static struct item *items = NULL;
static struct item *matches, *matchend;
static struct item *prev, *curr, *next, *sel;
static int mon = -1, screen;
static Atom clip, utf8;
static Display *dpy;
static Window root, parentwin, win;
static XIC xic;
static Drw *drw;
static Clr *scheme[SchemeLast];
#include "patch/include.h"
#include "config.h"
static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
static char *(*fstrstr)(const char *, const char *) = strstr;
static unsigned int
textw_clamp(const char *str, unsigned int n)
{
unsigned int w = drw_fontset_getwidth_clamp(drw, str, n) + lrpad;
return MIN(w, n);
}
static void appenditem(struct item *item, struct item **list, struct item **last);
static void calcoffsets(void);
static void cleanup(void);
static char * cistrstr(const char *s, const char *sub);
static int drawitem(struct item *item, int x, int y, int w);
static void drawmenu(void);
static void grabfocus(void);
static void grabkeyboard(void);
static void match(void);
static void insert(const char *str, ssize_t n);
static size_t nextrune(int inc);
static void movewordedge(int dir);
static void keypress(XKeyEvent *ev);
static void paste(void);
static void readstdin(void);
static void run(void);
static void setup(void);
static void usage(void);
#include "patch/include.c"
static void
appenditem(struct item *item, struct item **list, struct item **last)
{
if (*last)
(*last)->right = item;
else
*list = item;
item->left = *last;
item->right = NULL;
*last = item;
}
static void
calcoffsets(void)
{
int i, n, rpad = 0;
if (lines > 0) {
if (columns)
n = lines * columns * bh;
else
n = lines * bh;
} else {
n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">") + rpad);
}
/* calculate which items will begin the next page and previous page */
for (i = 0, next = curr; next; next = next->right)
if ((i += (lines > 0) ? bh : textw_clamp(next->text, n)) > n)
break;
for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
if ((i += (lines > 0) ? bh : textw_clamp(prev->left->text, n)) > n)
break;
}
static void
cleanup(void)
{
size_t i;
XUngrabKey(dpy, AnyKey, AnyModifier, root);
for (i = 0; i < SchemeLast; i++)
free(scheme[i]);
for (i = 0; items && items[i].text; ++i)
free(items[i].text);
free(items);
drw_free(drw);
XSync(dpy, False);
XCloseDisplay(dpy);
}
static char *
cistrstr(const char *s, const char *sub)
{
size_t len;
for (len = strlen(sub); *s; s++)
if (!strncasecmp(s, sub, len))
return (char *)s;
return NULL;
}
static int
drawitem(struct item *item, int x, int y, int w)
{
int r;
char *text = item->stext;
if (item == sel)
drw_setscheme(drw, scheme[SchemeSel]);
else if (item->out)
drw_setscheme(drw, scheme[SchemeOut]);
else
drw_setscheme(drw, scheme[SchemeNorm]);
r = drw_text(drw
, x
, y
, w
, bh
, lrpad / 2
, text
, 0
);
return r;
}
static void
drawmenu(void)
{
static int curpos, oldcurlen;
int curlen, rcurlen;
struct item *item;
int x = 0, y = 0, w, rpad = 0, itw = 0, stw = 0;
int fh = drw->fonts->h;
char *censort;
drw_setscheme(drw, scheme[SchemeNorm]);
drw_rect(drw, 0, 0, mw, mh, 1, 1);
if (prompt && *prompt) {
drw_setscheme(drw, scheme[SchemeSel]);
x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0
);
}
/* draw input field */
w = (lines > 0 || !matches) ? mw - x : inputw;
w -= lrpad / 2;
x += lrpad / 2;
rcurlen = TEXTW(text + cursor) - lrpad;
curlen = TEXTW(text) - lrpad - rcurlen;
curpos += curlen - oldcurlen;
curpos = MIN(w, MAX(0, curpos));
curpos = MAX(curpos, w - rcurlen);
curpos = MIN(curpos, curlen);
oldcurlen = curlen;
drw_setscheme(drw, scheme[SchemeNorm]);
if (passwd) {
censort = ecalloc(1, sizeof(text));
memset(censort, '.', strlen(text));
drw_text_align(drw, x, 0, curpos, bh, censort, cursor, AlignR);
drw_text_align(drw, x + curpos, 0, w - curpos, bh, censort + cursor, strlen(censort) - cursor, AlignL);
free(censort);
} else {
drw_text_align(drw, x, 0, curpos, bh, text, cursor, AlignR);
drw_text_align(drw, x + curpos, 0, w - curpos, bh, text + cursor, strlen(text) - cursor, AlignL);
}
drw_rect(drw, x + curpos - 1, 2 + (bh-fh)/2, 2, fh - 4, 1, 0);
if (lines > 0) {
/* draw grid */
int i = 0;
for (item = curr; item != next; item = item->right, i++)
if (columns)
drawitem(
item,
0 + ((i / lines) * (mw / columns)),
y + (((i % lines) + 1) * bh),
mw / columns
);
else
drawitem(item, 0, y += bh, mw);
} else if (matches) {
/* draw horizontal list */
x += inputw;
w = TEXTW("<");
if (curr->left) {
drw_setscheme(drw, scheme[SchemeNorm]);
drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0
);
}
x += w;
for (item = curr; item != next; item = item->right) {
stw = TEXTW(">");
itw = textw_clamp(item->stext, mw - x - stw - rpad);
x = drawitem(item, x, 0, itw);
}
if (next) {
w = TEXTW(">");
drw_setscheme(drw, scheme[SchemeNorm]);
drw_text(drw, mw - w - rpad, 0, w, bh, lrpad / 2
, ">"
, 0
);
}
}
drw_map(drw, win, 0, 0, mw, mh);
}
static void
grabfocus(void)
{
struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
Window focuswin;
int i, revertwin;
for (i = 0; i < 100; ++i) {
XGetInputFocus(dpy, &focuswin, &revertwin);
if (focuswin == win)
return;
XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
nanosleep(&ts, NULL);
}
die("cannot grab focus");
}
static void
grabkeyboard(void)
{
struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
int i;
if (embed)
return;
/* try to grab keyboard, we may have to wait for another process to ungrab */
for (i = 0; i < 1000; i++) {
if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
GrabModeAsync, CurrentTime) == GrabSuccess)
return;
nanosleep(&ts, NULL);
}
die("cannot grab keyboard");
}
static void
match(void)
{
if (fuzzy) {
fuzzymatch();
return;
}
static char **tokv = NULL;
static int tokn = 0;
char buf[sizeof text], *s;
int i, tokc = 0;
size_t len, textsize;
struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
strcpy(buf, text);
/* separate input text into tokens to be matched individually */
for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
die("cannot realloc %zu bytes:", tokn * sizeof *tokv);
len = tokc ? strlen(tokv[0]) : 0;
matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
textsize = strlen(text) + 1;
for (item = items; item && item->text; item++)
{
for (i = 0; i < tokc; i++)
if (!fstrstr(item->text, tokv[i]))
break;
if (i != tokc) /* not all tokens match */
continue;
/* exact matches go first, then prefixes, then substrings */
if (!tokc || !fstrncmp(text, item->text, textsize))
appenditem(item, &matches, &matchend);
else if (!fstrncmp(tokv[0], item->text, len))
appenditem(item, &lprefix, &prefixend);
else
appenditem(item, &lsubstr, &substrend);
}
if (lprefix) {
if (matches) {
matchend->right = lprefix;
lprefix->left = matchend;
} else
matches = lprefix;
matchend = prefixend;
}
if (lsubstr)
{
if (matches) {
matchend->right = lsubstr;
lsubstr->left = matchend;
} else
matches = lsubstr;
matchend = substrend;
}
curr = sel = matches;
if (instant && matches && matches==matchend && !lsubstr) {
puts(matches->text);
cleanup();
exit(0);
}
calcoffsets();
}
static void
insert(const char *str, ssize_t n)
{
if (strlen(text) + n > sizeof text - 1)
return;
/* move existing text out of the way, insert new text, and update cursor */
memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
if (n > 0)
memcpy(&text[cursor], str, n);
cursor += n;
match();
}
static size_t
nextrune(int inc)
{
ssize_t n;
/* return location of next utf8 rune in the given direction (+1 or -1) */
for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
;
return n;
}
static void
movewordedge(int dir)
{
if (dir < 0) { /* move cursor to the start of the word*/
while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
cursor = nextrune(-1);
while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
cursor = nextrune(-1);
} else { /* move cursor to the end of the word */
while (text[cursor] && strchr(worddelimiters, text[cursor]))
cursor = nextrune(+1);
while (text[cursor] && !strchr(worddelimiters, text[cursor]))
cursor = nextrune(+1);
}
}
static void
keypress(XKeyEvent *ev)
{
char buf[64];
int len;
KeySym ksym = NoSymbol;
Status status;
int i;
struct item *tmpsel;
bool offscreen = false;
len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
switch (status) {
default: /* XLookupNone, XBufferOverflow */
return;
case XLookupChars: /* composed string from input method */
goto insert;
case XLookupKeySym:
case XLookupBoth: /* a KeySym and a string are returned: use keysym */
break;
}
if (ev->state & ControlMask) {
switch(ksym) {
case XK_a: expect("ctrl-a", ev); ksym = XK_Home; break;
case XK_b: expect("ctrl-b", ev); ksym = XK_Left; break;
case XK_c: expect("ctrl-c", ev); ksym = XK_Escape; break;
case XK_d: expect("ctrl-d", ev); ksym = XK_Delete; break;
case XK_e: expect("ctrl-e", ev); ksym = XK_End; break;
case XK_f: expect("ctrl-f", ev); ksym = XK_Right; break;
case XK_g: expect("ctrl-g", ev); ksym = XK_Escape; break;
case XK_h: expect("ctrl-h", ev); ksym = XK_BackSpace; break;
case XK_i: expect("ctrl-i", ev); ksym = XK_Tab; break;
case XK_j: expect("ctrl-j", ev); ksym = XK_Down; break;
case XK_J:/* fallthrough */
case XK_l: expect("ctrl-l", ev); break;
case XK_m: expect("ctrl-m", ev); /* fallthrough */
case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
case XK_n: expect("ctrl-n", ev); ksym = XK_Down; break;
case XK_p: expect("ctrl-p", ev); ksym = XK_Up; break;
case XK_o: expect("ctrl-o", ev); break;
case XK_q: expect("ctrl-q", ev); break;
case XK_r: expect("ctrl-r", ev); break;
case XK_s: expect("ctrl-s", ev); break;
case XK_t: expect("ctrl-t", ev); break;
case XK_k: expect("ctrl-k", ev); ksym = XK_Up; break;
case XK_u: expect("ctrl-u", ev); /* delete left */
insert(NULL, 0 - cursor);
break;
case XK_w: expect("ctrl-w", ev); /* delete word */
while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
insert(NULL, nextrune(-1) - cursor);
while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
insert(NULL, nextrune(-1) - cursor);
break;
case XK_v:
expect("ctrl-v", ev);
case XK_V:
XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
utf8, utf8, win, CurrentTime);
return;
case XK_y: expect("ctrl-y", ev); /* paste selection */
case XK_Y:
XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
utf8, utf8, win, CurrentTime);
return;
case XK_x: expect("ctrl-x", ev); break;
case XK_z: expect("ctrl-z", ev); break;
case XK_Left:
case XK_KP_Left:
movewordedge(-1);
goto draw;
case XK_Right:
case XK_KP_Right:
movewordedge(+1);
goto draw;
case XK_Return:
case XK_KP_Enter:
break;
case XK_bracketleft:
cleanup();
exit(1);
default:
return;
}
} else if (ev->state & Mod1Mask) {
switch(ksym) {
case XK_b:
movewordedge(-1);
goto draw;
case XK_f:
movewordedge(+1);
goto draw;
case XK_g: ksym = XK_Home; break;
case XK_G: ksym = XK_End; break;
case XK_h: ksym = XK_Up; break;
case XK_j: ksym = XK_Next; break;
case XK_k: ksym = XK_Prior; break;
case XK_l: ksym = XK_Down; break;
default:
return;
}
}
switch(ksym) {
default:
insert:
if (!iscntrl((unsigned char)*buf))
insert(buf, len);
break;
case XK_Delete:
case XK_KP_Delete:
if (text[cursor] == '\0')
return;
cursor = nextrune(+1);
/* fallthrough */
case XK_BackSpace:
if (cursor == 0)
return;
insert(NULL, nextrune(-1) - cursor);
break;
case XK_End:
case XK_KP_End:
if (text[cursor] != '\0') {
cursor = strlen(text);
break;
}
if (next) {
/* jump to end of list and position items in reverse */
curr = matchend;
calcoffsets();
curr = prev;
calcoffsets();
while (next && (curr = curr->right))
calcoffsets();
}
sel = matchend;
break;
case XK_Escape:
cleanup();
exit(1);
case XK_Home:
case XK_KP_Home:
if (sel == matches) {
cursor = 0;
break;
}
sel = curr = matches;
calcoffsets();
break;
case XK_Left:
case XK_KP_Left:
if (columns > 1) {
if (!sel)
return;
tmpsel = sel;
for (i = 0; i < lines; i++) {
if (!tmpsel->left || tmpsel->left->right != tmpsel)
return;
if (tmpsel == curr)
offscreen = true;
tmpsel = tmpsel->left;
}
sel = tmpsel;
if (offscreen) {
curr = prev;
calcoffsets();
}
break;
}
if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
cursor = nextrune(-1);
break;
}
if (lines > 0)
return;
/* fallthrough */
case XK_Up:
case XK_KP_Up:
if (sel && sel->left && (sel = sel->left)->right == curr) {
curr = prev;
calcoffsets();
}
break;
case XK_Next:
case XK_KP_Next:
if (!next)
return;
sel = curr = next;
calcoffsets();
break;
case XK_Prior:
case XK_KP_Prior:
if (!prev)
return;
sel = curr = prev;
calcoffsets();
break;
case XK_Return:
case XK_KP_Enter:
puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
if (!(ev->state & ControlMask)) {
cleanup();
exit(0);
}
if (sel)
sel->out = 1;
break;
case XK_Right:
case XK_KP_Right:
if (columns > 1) {
if (!sel)
return;
tmpsel = sel;
for (i = 0; i < lines; i++) {
if (!tmpsel->right || tmpsel->right->left != tmpsel)
return;
tmpsel = tmpsel->right;
if (tmpsel == next)
offscreen = true;
}
sel = tmpsel;
if (offscreen) {
curr = next;
calcoffsets();
}
break;
}
if (text[cursor] != '\0') {
cursor = nextrune(+1);
break;
}
if (lines > 0)
return;
/* fallthrough */
case XK_Down:
case XK_KP_Down:
if (sel && sel->right && (sel = sel->right) == next) {
curr = next;
calcoffsets();
}
break;
case XK_Tab:
if (!sel)
return;
cursor = strnlen(sel->text, sizeof text - 1);
memcpy(text, sel->text, cursor);
text[cursor] = '\0';
match();
break;
}
draw:
drawmenu();
}
static void
paste(void)
{
char *p, *q;
int di;
unsigned long dl;
Atom da;
/* we have been given the current selection, now insert it into input */
if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
== Success && p) {
insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
XFree(p);
}
drawmenu();
}
static void
readstdin(void)
{
char *line = NULL;
char *buf, *p;
size_t i, linesiz, itemsiz = 0;
ssize_t len;
if (passwd) {
inputw = lines = 0;
return;
}
/* read each line from stdin and add it to the item list */
for (i = 0; (len = getline(&line, &linesiz, stdin)) != -1; i++) {
if (i + 1 >= itemsiz) {
itemsiz += 256;
if (!(items = realloc(items, itemsiz * sizeof(*items))))
die("cannot realloc %zu bytes:", itemsiz * sizeof(*items));
}
if (line[len - 1] == '\n')
line[len - 1] = '\0';
if (!(items[i].text = strdup(line)))
die("strdup:");
if (!(buf = strdup(line)))
die("cannot strdup %u bytes:", strlen(line) + 1);
if ((p = strchr(buf, '\t')))
*p = '\0';
items[i].stext = buf;
items[i].out = 0;
}
free(line);
if (items)
items[i].text = NULL;
lines = MIN(lines, i);
}
static void
run(void)
{
XEvent ev;
while (!XNextEvent(dpy, &ev)) {
if (XFilterEvent(&ev, win))
continue;
switch(ev.type) {
case ButtonPress:
buttonpress(&ev);
break;
case DestroyNotify:
if (ev.xdestroywindow.window != win)
break;
cleanup();
exit(1);
case Expose:
if (ev.xexpose.count == 0)
drw_map(drw, win, 0, 0, mw, mh);
break;
case FocusIn:
/* regrab focus from parent window */
if (ev.xfocus.window != win)
grabfocus();
break;
case KeyPress:
keypress(&ev.xkey);
break;
case SelectionNotify:
if (ev.xselection.property == utf8)
paste();
break;
case VisibilityNotify:
if (ev.xvisibility.state != VisibilityUnobscured)
XRaiseWindow(dpy, win);
break;
}
}
}
static void
setup(void)
{
int x, y, i, j;
unsigned int du;
XSetWindowAttributes swa;
XIM xim;
Window w, dw, *dws;
XWindowAttributes wa;
XClassHint ch = {"dmenu", "dmenu"};
#ifdef XINERAMA
XineramaScreenInfo *info;
Window pw;
int a, di, n, area = 0;
#endif
/* init appearance */
for (j = 0; j < SchemeLast; j++)
scheme[j] = drw_scm_create(drw, (const char**)colors[j], 2);
clip = XInternAtom(dpy, "CLIPBOARD", False);
utf8 = XInternAtom(dpy, "UTF8_STRING", False);
/* calculate menu geometry */
bh = drw->fonts->h + 2;
bh = MAX(bh,lineheight); /* make a menu line AT LEAST 'lineheight' tall */
lines = MAX(lines, 0);
mh = (lines + 1) * bh;
promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
#ifdef XINERAMA
i = 0;
if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
XGetInputFocus(dpy, &w, &di);
if (mon >= 0 && mon < n)
i = mon;
else if (w != root && w != PointerRoot && w != None) {
/* find top-level window containing current input focus */
do {
if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
XFree(dws);
} while (w != root && w != pw);
/* find xinerama screen with which the window intersects most */
if (XGetWindowAttributes(dpy, pw, &wa))
for (j = 0; j < n; j++)
if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
area = a;
i = j;
}
}
/* no focused window is on screen, so use pointer location instead */
if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
for (i = 0; i < n; i++)
if (INTERSECT(x, y, 1, 1, info[i]) != 0)
break;
if (center) {
mw = MIN(MAX(max_textw() + promptw, min_width), info[i].width);
x = info[i].x_org + ((info[i].width - mw) / 2);
y = info[i].y_org + ((info[i].height - mh) / 2);
} else {
x = info[i].x_org + dmx;
y = info[i].y_org + (topbar ? dmy : info[i].height - mh - dmy);
mw = (dmw>0 ? dmw : info[i].width);
}
XFree(info);
} else
#endif
{
if (!XGetWindowAttributes(dpy, parentwin, &wa))
die("could not get embedding window attributes: 0x%lx",
parentwin);
if (center) {
mw = MIN(MAX(max_textw() + promptw, min_width), wa.width);
x = (wa.width - mw) / 2;
y = (wa.height - mh) / 2;
} else {
x = dmx;
y = topbar ? dmy : wa.height - mh - dmy;
mw = (dmw>0 ? dmw : wa.width);
}
}
inputw = mw / 3; /* input width: ~33.33% of monitor width */
match();
/* create menu window */
swa.override_redirect = True;
swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask
| ButtonPressMask
;
win = XCreateWindow(
dpy, root,
x, y - (topbar ? 0 : border_width * 2), mw - border_width * 2, mh, border_width,
CopyFromParent, CopyFromParent, CopyFromParent,
CWOverrideRedirect | CWBackPixel | CWEventMask, &swa
);
if (border_width)
XSetWindowBorder(dpy, win, scheme[SchemeBorder][ColBg].pixel);
XSetClassHint(dpy, win, &ch);
/* input methods */
if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
die("XOpenIM failed: could not open input device");
xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, win, XNFocusWindow, win, NULL);
XMapRaised(dpy, win);
if (embed) {
XReparentWindow(dpy, win, parentwin, x, y);
XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
for (i = 0; i < du && dws[i] != win; ++i)
XSelectInput(dpy, dws[i], FocusChangeMask);
XFree(dws);
}
grabfocus();
}
drw_resize(drw, mw, mh);
drawmenu();
}
static void
usage(void)
{
die("usage: dmenu [-bv"
"c"
"f"
"i"
"n"
"F"
"P"
"] "
"[-g columns] "
"[-l lines] [-p prompt] [-fn font] [-m monitor]"
"\n [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]"
"\n "
" [-ex expectkey]"
" [-bw width]"
"\n "
" [-h height]"
" [-X xoffset] [-Y yoffset] [-W width]" // (arguments made upper case due to conflicts)
"\n");
}
int
main(int argc, char *argv[])
{
XWindowAttributes wa;
int i;
int fast = 0;
if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
fputs("warning: no locale support\n", stderr);
if (!(dpy = XOpenDisplay(NULL)))
die("cannot open display");
screen = DefaultScreen(dpy);
root = RootWindow(dpy, screen);
if (!embed || !(parentwin = strtol(embed, NULL, 0)))
parentwin = root;
if (!XGetWindowAttributes(dpy, parentwin, &wa))
die("could not get embedding window attributes: 0x%lx",
parentwin);
drw = drw_create(dpy, screen, root, wa.width, wa.height);
readxresources();
for (i = 1; i < argc; i++) {
if (argv[i][0] == '\0')
continue;
/* these options take no arguments */
if (!strcmp(argv[i], "-v")) { /* prints version information */
puts("dmenu-"VERSION);
exit(0);
} else if (!strcmp(argv[i], "-b")) { /* appears at the bottom of the screen */
topbar = 0;
} else if (!strcmp(argv[i], "-c")) { /* toggles centering of dmenu window on screen */
center = !center;
} else if (!strcmp(argv[i], "-f")) { /* grabs keyboard before reading stdin */
fast = 1;
} else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
fstrncmp = strncasecmp;
fstrstr = cistrstr;
} else if (!strcmp(argv[i], "-n")) { /* instant select only match */
instant = !instant;
} else if (!strcmp(argv[i], "-F")) { /* disable/enable fuzzy matching, depends on default */
fuzzy = !fuzzy;
} else if (!strcmp(argv[i], "-P")) { /* is the input a password */
passwd = 1;
} else if (!strcmp(argv[i], "-ex")) { /* expect key */
expected = argv[++i];
} else if (i + 1 == argc)
usage();
/* these options take one argument */
else if (!strcmp(argv[i], "-g")) { /* number of columns in grid */
columns = atoi(argv[++i]);
if (columns && lines == 0)
lines = 1;
}
else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
lines = atoi(argv[++i]);
else if (!strcmp(argv[i], "-X")) /* window x offset */
dmx = atoi(argv[++i]);
else if (!strcmp(argv[i], "-Y")) /* window y offset (from bottom up if -b) */
dmy = atoi(argv[++i]);
else if (!strcmp(argv[i], "-W")) /* make dmenu this wide */
dmw = atoi(argv[++i]);
else if (!strcmp(argv[i], "-m"))
mon = atoi(argv[++i]);
else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
prompt = argv[++i];
else if (!strcmp(argv[i], "-fn")) /* font or font set */
fonts[0] = argv[++i];
else if(!strcmp(argv[i], "-h")) { /* minimum height of one menu line */
lineheight = atoi(argv[++i]);
lineheight = MAX(lineheight, min_lineheight); /* reasonable default in case of value too small/negative */
}
else if (!strcmp(argv[i], "-nb")) /* normal background color */
colors[SchemeNorm][ColBg] = argv[++i];
else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
colors[SchemeNorm][ColFg] = argv[++i];
else if (!strcmp(argv[i], "-sb")) /* selected background color */
colors[SchemeSel][ColBg] = argv[++i];
else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
colors[SchemeSel][ColFg] = argv[++i];
else if (!strcmp(argv[i], "-w")) /* embedding window id */
embed = argv[++i];
else if (!strcmp(argv[i], "-bw")) /* border width around dmenu */
border_width = atoi(argv[++i]);
else {
usage();
}
}
if (!drw_fontset_create(drw, (const char**)fonts, LENGTH(fonts)))
die("no fonts could be loaded.");
lrpad = drw->fonts->h;
if (lineheight == -1)
lineheight = drw->fonts->h * 2.5;
#ifdef __OpenBSD__
if (pledge("stdio rpath", NULL) == -1)
die("pledge");
#endif
if (fast && !isatty(0)) {
grabkeyboard();
readstdin();
} else {
readstdin();
grabkeyboard();
}
setup();
run();
return 1; /* unreachable */
}

View File

@ -1,13 +0,0 @@
#!/bin/sh
cachedir="${XDG_CACHE_HOME:-"$HOME/.cache"}"
cache="$cachedir/dmenu_run"
[ ! -e "$cachedir" ] && mkdir -p "$cachedir"
IFS=:
if stest -dqr -n "$cache" $PATH; then
stest -flx $PATH | sort -u | tee "$cache"
else
cat "$cache"
fi

View File

@ -1,6 +0,0 @@
#!/bin/sh
export _JAVA_AWT_WM_NONREPARENTING=1
dmenu_path | dmenu "$@" | ${SHELL:-"/bin/sh"} &
# Uncomment for the NAVHISTORY patch (and remove the exec above)
#dmenu_path | dmenu -H "${XDG_CACHE_HOME:-$HOME/.cache/}/dmenu_run.hist" "$@" | ${SHELL:-"/bin/sh"} &

View File

@ -1,455 +0,0 @@
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/Xft/Xft.h>
#include "drw.h"
#include "util.h"
#define UTF_INVALID 0xFFFD
#define UTF_SIZ 4
static const unsigned char utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
static const unsigned char utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
static const long utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
static const long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
static long
utf8decodebyte(const char c, size_t *i)
{
for (*i = 0; *i < (UTF_SIZ + 1); ++(*i))
if (((unsigned char)c & utfmask[*i]) == utfbyte[*i])
return (unsigned char)c & ~utfmask[*i];
return 0;
}
static size_t
utf8validate(long *u, size_t i)
{
if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
*u = UTF_INVALID;
for (i = 1; *u > utfmax[i]; ++i)
;
return i;
}
static size_t
utf8decode(const char *c, long *u, size_t clen)
{
size_t i, j, len, type;
long udecoded;
*u = UTF_INVALID;
if (!clen)
return 0;
udecoded = utf8decodebyte(c[0], &len);
if (!BETWEEN(len, 1, UTF_SIZ))
return 1;
for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
if (type)
return j;
}
if (j < len)
return 0;
*u = udecoded;
utf8validate(u, len);
return len;
}
Drw *
drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h)
{
Drw *drw = ecalloc(1, sizeof(Drw));
drw->dpy = dpy;
drw->screen = screen;
drw->root = root;
drw->w = w;
drw->h = h;
drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen));
drw->gc = XCreateGC(dpy, root, 0, NULL);
XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter);
return drw;
}
void
drw_resize(Drw *drw, unsigned int w, unsigned int h)
{
if (!drw)
return;
drw->w = w;
drw->h = h;
if (drw->drawable)
XFreePixmap(drw->dpy, drw->drawable);
drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen));
}
void
drw_free(Drw *drw)
{
XFreePixmap(drw->dpy, drw->drawable);
XFreeGC(drw->dpy, drw->gc);
drw_fontset_free(drw->fonts);
free(drw);
}
/* This function is an implementation detail. Library users should use
* drw_fontset_create instead.
*/
static Fnt *
xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern)
{
Fnt *font;
XftFont *xfont = NULL;
FcPattern *pattern = NULL;
if (fontname) {
/* Using the pattern found at font->xfont->pattern does not yield the
* same substitution results as using the pattern returned by
* FcNameParse; using the latter results in the desired fallback
* behaviour whereas the former just results in missing-character
* rectangles being drawn, at least with some fonts. */
if (!(xfont = XftFontOpenName(drw->dpy, drw->screen, fontname))) {
fprintf(stderr, "error, cannot load font from name: '%s'\n", fontname);
return NULL;
}
if (!(pattern = FcNameParse((FcChar8 *) fontname))) {
fprintf(stderr, "error, cannot parse font name to pattern: '%s'\n", fontname);
XftFontClose(drw->dpy, xfont);
return NULL;
}
} else if (fontpattern) {
if (!(xfont = XftFontOpenPattern(drw->dpy, fontpattern))) {
fprintf(stderr, "error, cannot load font from pattern.\n");
return NULL;
}
} else {
die("no font specified.");
}
font = ecalloc(1, sizeof(Fnt));
font->xfont = xfont;
font->pattern = pattern;
font->h = xfont->ascent + xfont->descent;
font->dpy = drw->dpy;
return font;
}
static void
xfont_free(Fnt *font)
{
if (!font)
return;
if (font->pattern)
FcPatternDestroy(font->pattern);
XftFontClose(font->dpy, font->xfont);
free(font);
}
Fnt*
drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount)
{
Fnt *cur, *ret = NULL;
size_t i;
if (!drw || !fonts)
return NULL;
for (i = 1; i <= fontcount; i++) {
if ((cur = xfont_create(drw, fonts[fontcount - i], NULL))) {
cur->next = ret;
ret = cur;
}
}
return (drw->fonts = ret);
}
void
drw_fontset_free(Fnt *font)
{
if (font) {
drw_fontset_free(font->next);
xfont_free(font);
}
}
void
drw_clr_create(Drw *drw, Clr *dest, const char *clrname)
{
if (!drw || !dest || !clrname)
return;
if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen),
DefaultColormap(drw->dpy, drw->screen),
clrname, dest))
die("error, cannot allocate color '%s'", clrname);
}
/* Wrapper to create color schemes. The caller has to call free(3) on the
* returned color scheme when done using it. */
Clr *
drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount)
{
size_t i;
Clr *ret;
/* need at least two colors for a scheme */
if (!drw || !clrnames || clrcount < 2 || !(ret = ecalloc(clrcount, sizeof(XftColor))))
return NULL;
for (i = 0; i < clrcount; i++)
drw_clr_create(drw, &ret[i], clrnames[i]);
return ret;
}
void
drw_setfontset(Drw *drw, Fnt *set)
{
if (drw)
drw->fonts = set;
}
void
drw_setscheme(Drw *drw, Clr *scm)
{
if (drw)
drw->scheme = scm;
}
void
drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert)
{
if (!drw || !drw->scheme)
return;
XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel);
if (filled)
XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
else
XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1);
}
int
drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert)
{
int ty, ellipsis_x = 0;
unsigned int tmpw, ew, ellipsis_w = 0, ellipsis_len, hash, h0, h1;
XftDraw *d = NULL;
Fnt *usedfont, *curfont, *nextfont;
int utf8strlen, utf8charlen, render = x || y || w || h;
long utf8codepoint = 0;
const char *utf8str;
FcCharSet *fccharset;
FcPattern *fcpattern;
FcPattern *match;
XftResult result;
int charexists = 0, overflow = 0;
/* keep track of a couple codepoints for which we have no match. */
static unsigned int nomatches[128], ellipsis_width;
const char *ellipsis = "...";
if (!drw || (render && (!drw->scheme || !w)) || !text || !drw->fonts)
return 0;
if (!render) {
w = invert ? invert : ~invert;
} else {
XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel);
XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
d = XftDrawCreate(drw->dpy, drw->drawable,
DefaultVisual(drw->dpy, drw->screen),
DefaultColormap(drw->dpy, drw->screen));
x += lpad;
w -= lpad;
}
usedfont = drw->fonts;
if (!ellipsis_width && render)
ellipsis_width = drw_fontset_getwidth(drw, ellipsis);
while (1) {
ew = ellipsis_len = utf8strlen = 0;
utf8str = text;
nextfont = NULL;
while (*text) {
utf8charlen = utf8decode(text, &utf8codepoint, UTF_SIZ);
for (curfont = drw->fonts; curfont; curfont = curfont->next) {
charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint);
if (charexists) {
drw_font_getexts(curfont, text, utf8charlen, &tmpw, NULL);
if (ew + ellipsis_width <= w) {
/* keep track where the ellipsis still fits */
ellipsis_x = x + ew;
ellipsis_w = w - ew;
ellipsis_len = utf8strlen;
}
if (ew + tmpw > w) {
overflow = 1;
/* called from drw_fontset_getwidth_clamp():
* it wants the width AFTER the overflow
*/
if (!render)
x += tmpw;
else
utf8strlen = ellipsis_len;
} else if (curfont == usedfont) {
utf8strlen += utf8charlen;
text += utf8charlen;
ew += tmpw;
} else {
nextfont = curfont;
}
break;
}
}
if (overflow || !charexists || nextfont)
break;
else
charexists = 0;
}
if (utf8strlen) {
if (render) {
ty = y + (h - usedfont->h) / 2 + usedfont->xfont->ascent;
XftDrawStringUtf8(d, &drw->scheme[invert ? ColBg : ColFg],
usedfont->xfont, x, ty, (XftChar8 *)utf8str, utf8strlen);
}
x += ew;
w -= ew;
}
if (render && overflow && ellipsis_w)
drw_text(drw, ellipsis_x, y, ellipsis_w, h, 0, ellipsis, invert);
if (!*text || overflow) {
break;
} else if (nextfont) {
charexists = 0;
usedfont = nextfont;
} else {
/* Regardless of whether or not a fallback font is found, the
* character must be drawn. */
charexists = 1;
hash = (unsigned int)utf8codepoint;
hash = ((hash >> 16) ^ hash) * 0x21F0AAAD;
hash = ((hash >> 15) ^ hash) * 0xD35A2D97;
h0 = ((hash >> 15) ^ hash) % LENGTH(nomatches);
h1 = (hash >> 17) % LENGTH(nomatches);
/* avoid expensive XftFontMatch call when we know we won't find a match */
if (nomatches[h0] == utf8codepoint || nomatches[h1] == utf8codepoint)
goto no_match;
fccharset = FcCharSetCreate();
FcCharSetAddChar(fccharset, utf8codepoint);
if (!drw->fonts->pattern) {
/* Refer to the comment in xfont_create for more information. */
die("the first font in the cache must be loaded from a font string.");
}
fcpattern = FcPatternDuplicate(drw->fonts->pattern);
FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
FcPatternAddBool(fcpattern, FC_SCALABLE, FcTrue);
FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
FcDefaultSubstitute(fcpattern);
match = XftFontMatch(drw->dpy, drw->screen, fcpattern, &result);
FcCharSetDestroy(fccharset);
FcPatternDestroy(fcpattern);
if (match) {
usedfont = xfont_create(drw, NULL, match);
if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) {
for (curfont = drw->fonts; curfont->next; curfont = curfont->next)
; /* NOP */
curfont->next = usedfont;
} else {
xfont_free(usedfont);
nomatches[nomatches[h0] ? h1 : h0] = utf8codepoint;
no_match:
usedfont = drw->fonts;
}
}
}
}
if (d)
XftDrawDestroy(d);
return x + (render ? w : 0);
}
void
drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h)
{
if (!drw)
return;
XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y);
XSync(drw->dpy, False);
}
unsigned int
drw_fontset_getwidth(Drw *drw, const char *text)
{
if (!drw || !drw->fonts || !text)
return 0;
return drw_text(drw, 0, 0, 0, 0, 0, text, 0);
}
unsigned int
drw_fontset_getwidth_clamp(Drw *drw, const char *text, unsigned int n)
{
unsigned int tmp = 0;
if (drw && drw->fonts && text && n)
tmp = drw_text(drw, 0, 0, 0, 0, 0, text, n);
return MIN(n, tmp);
}
void
drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h)
{
XGlyphInfo ext;
if (!font || !text)
return;
XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *)text, len, &ext);
if (w)
*w = ext.xOff;
if (h)
*h = font->h;
}
Cur *
drw_cur_create(Drw *drw, int shape)
{
Cur *cur;
if (!drw || !(cur = ecalloc(1, sizeof(Cur))))
return NULL;
cur->cursor = XCreateFontCursor(drw->dpy, shape);
return cur;
}
void
drw_cur_free(Drw *drw, Cur *cursor)
{
if (!cursor)
return;
XFreeCursor(drw->dpy, cursor->cursor);
free(cursor);
}
#include "patch/scroll.c"

View File

@ -1,61 +0,0 @@
/* See LICENSE file for copyright and license details. */
typedef struct {
Cursor cursor;
} Cur;
typedef struct Fnt {
Display *dpy;
unsigned int h;
XftFont *xfont;
FcPattern *pattern;
struct Fnt *next;
} Fnt;
enum { ColFg, ColBg }; /* Clr scheme index */
typedef XftColor Clr;
typedef struct {
unsigned int w, h;
Display *dpy;
int screen;
Window root;
Drawable drawable;
GC gc;
Clr *scheme;
Fnt *fonts;
} Drw;
/* Drawable abstraction */
Drw *drw_create(Display *dpy, int screen, Window win, unsigned int w, unsigned int h);
void drw_resize(Drw *drw, unsigned int w, unsigned int h);
void drw_free(Drw *drw);
/* Fnt abstraction */
Fnt *drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount);
void drw_fontset_free(Fnt* set);
unsigned int drw_fontset_getwidth(Drw *drw, const char *text);
unsigned int drw_fontset_getwidth_clamp(Drw *drw, const char *text, unsigned int n);
void drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h);
/* Colorscheme abstraction */
void drw_clr_create(Drw *drw, Clr *dest, const char *clrname);
Clr *drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount);
/* Cursor abstraction */
Cur *drw_cur_create(Drw *drw, int shape);
void drw_cur_free(Drw *drw, Cur *cursor);
/* Drawing context manipulation */
void drw_setfontset(Drw *drw, Fnt *set);
void drw_setscheme(Drw *drw, Clr *scm);
/* Drawing functions */
void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert);
int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert);
/* Map functions */
void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h);
#include "patch/scroll.h"

View File

@ -1,8 +0,0 @@
static int
max_textw(void)
{
int len = 0;
for (struct item *item = items; item && item->text; item++)
len = MAX(TEXTW(item->text), len);
return len;
}

View File

@ -1,89 +0,0 @@
#include <math.h>
int
compare_distance(const void *a, const void *b)
{
struct item *da = *(struct item **) a;
struct item *db = *(struct item **) b;
if (!db)
return 1;
if (!da)
return -1;
return da->distance == db->distance ? 0 : da->distance < db->distance ? -1 : 1;
}
void
fuzzymatch(void)
{
/* bang - we have so much memory */
struct item *it;
struct item **fuzzymatches = NULL;
char c;
int number_of_matches = 0, i, pidx, sidx, eidx;
int text_len = strlen(text), itext_len;
matches = matchend = NULL;
/* walk through all items */
for (it = items; it && it->text; it++) {
if (text_len) {
itext_len = strlen(it->text);
pidx = 0; /* pointer */
sidx = eidx = -1; /* start of match, end of match */
/* walk through item text */
for (i = 0; i < itext_len && (c = it->text[i]); i++) {
/* fuzzy match pattern */
if (!fstrncmp(&text[pidx], &c, 1)) {
if (sidx == -1)
sidx = i;
pidx++;
if (pidx == text_len) {
eidx = i;
break;
}
}
}
/* build list of matches */
if (eidx != -1) {
/* compute distance */
/* add penalty if match starts late (log(sidx+2))
* add penalty for long a match without many matching characters */
it->distance = log(sidx + 2) + (double)(eidx - sidx - text_len);
/* fprintf(stderr, "distance %s %f\n", it->text, it->distance); */
appenditem(it, &matches, &matchend);
number_of_matches++;
}
} else {
appenditem(it, &matches, &matchend);
}
}
if (number_of_matches) {
/* initialize array with matches */
if (!(fuzzymatches = realloc(fuzzymatches, number_of_matches * sizeof(struct item*))))
die("cannot realloc %u bytes:", number_of_matches * sizeof(struct item*));
for (i = 0, it = matches; it && i < number_of_matches; i++, it = it->right) {
fuzzymatches[i] = it;
}
/* sort matches according to distance */
qsort(fuzzymatches, number_of_matches, sizeof(struct item*), compare_distance);
/* rebuild list of matches */
matches = matchend = NULL;
for (i = 0, it = fuzzymatches[i]; i < number_of_matches && it && \
it->text; i++, it = fuzzymatches[i]) {
appenditem(it, &matches, &matchend);
}
free(fuzzymatches);
}
curr = sel = matches;
if (instant && matches && matches==matchend) {
puts(matches->text);
cleanup();
exit(0);
}
calcoffsets();
}

View File

@ -1,15 +0,0 @@
static char *expected;
void
expect(char *expect, XKeyEvent *ignored)
{
if (sel && expected && strstr(expected, expect)) {
puts(expect);
puts(sel->text);
cleanup();
exit(1);
} else if (!sel && expected && strstr(expected, expect)){
puts(expect);
cleanup();
exit(1);
}
}

View File

@ -1 +0,0 @@
static void expect(char *expect, XKeyEvent *ev);

View File

@ -1,5 +0,0 @@
#include "center.c"
#include "fuzzymatch.c"
#include "fzfexpect.c"
#include "mousesupport.c"
#include "xresources.c"

View File

@ -1 +0,0 @@
#include "fzfexpect.h"

View File

@ -1,114 +0,0 @@
static void
buttonpress(XEvent *e)
{
struct item *item;
XButtonPressedEvent *ev = &e->xbutton;
int x = 0, y = 0, h = bh, w;
if (ev->window != win)
return;
/* right-click: exit */
if (ev->button == Button3)
exit(1);
if (prompt && *prompt)
x += promptw;
/* input field */
w = (lines > 0 || !matches) ? mw - x : inputw;
/* left-click on input: clear input,
* NOTE: if there is no left-arrow the space for < is reserved so
* add that to the input width */
if (ev->button == Button1 &&
((lines <= 0 && ev->x >= 0 && ev->x <= x + w +
((!prev || !curr->left) ? TEXTW("<") : 0)) ||
(lines > 0 && ev->y >= y && ev->y <= y + h))) {
insert(NULL, -cursor);
drawmenu();
return;
}
/* middle-mouse click: paste selection */
if (ev->button == Button2) {
XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
utf8, utf8, win, CurrentTime);
drawmenu();
return;
}
/* scroll up */
if (ev->button == Button4 && prev) {
sel = curr = prev;
calcoffsets();
drawmenu();
return;
}
/* scroll down */
if (ev->button == Button5 && next) {
sel = curr = next;
calcoffsets();
drawmenu();
return;
}
if (ev->button != Button1)
return;
if (ev->state & ~ControlMask)
return;
if (lines > 0) {
/* vertical list: (ctrl)left-click on item */
w = mw - x;
for (item = curr; item != next; item = item->right) {
y += h;
if (ev->y >= y && ev->y <= (y + h)) {
puts(item->text);
if (!(ev->state & ControlMask)) {
exit(0);
}
sel = item;
if (sel) {
sel->out = 1;
drawmenu();
}
return;
}
}
} else if (matches) {
/* left-click on left arrow */
x += inputw;
w = TEXTW("<");
if (prev && curr->left) {
if (ev->x >= x && ev->x <= x + w) {
sel = curr = prev;
calcoffsets();
drawmenu();
return;
}
}
/* horizontal list: (ctrl)left-click on item */
for (item = curr; item != next; item = item->right) {
x += w;
w = MIN(TEXTW(item->text), mw - x - TEXTW(">"));
if (ev->x >= x && ev->x <= x + w) {
puts(item->text);
if (!(ev->state & ControlMask)) {
exit(0);
}
sel = item;
if (sel) {
sel->out = 1;
drawmenu();
}
return;
}
}
/* left-click on right arrow */
w = TEXTW(">");
x = mw - w;
if (next && ev->x >= x && ev->x <= x + w) {
sel = curr = next;
calcoffsets();
drawmenu();
return;
}
}
}

View File

@ -1,168 +0,0 @@
int
utf8nextchar(const char *str, int len, int i, int inc)
{
int n;
for (n = i + inc; n + inc >= 0 && n + inc <= len
&& (str[n] & 0xc0) == 0x80; n += inc)
;
return n;
}
int
drw_text_align(Drw *drw, int x, int y, unsigned int w, unsigned int h, const char *text, int textlen, int align)
{
int ty;
unsigned int ew;
XftDraw *d = NULL;
Fnt *usedfont, *curfont, *nextfont;
size_t len;
int utf8strlen, utf8charlen, render = x || y || w || h;
long utf8codepoint = 0;
const char *utf8str;
FcCharSet *fccharset;
FcPattern *fcpattern;
FcPattern *match;
XftResult result;
int charexists = 0;
int i, n;
if (!drw || (render && !drw->scheme) || !text || !drw->fonts || textlen <= 0
|| (align != AlignL && align != AlignR))
return 0;
if (!render) {
w = ~w;
} else {
XSetForeground(drw->dpy, drw->gc, drw->scheme[ColBg].pixel);
XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
d = XftDrawCreate(drw->dpy, drw->drawable,
DefaultVisual(drw->dpy, drw->screen),
DefaultColormap(drw->dpy, drw->screen));
}
usedfont = drw->fonts;
i = align == AlignL ? 0 : textlen;
x = align == AlignL ? x : x + w;
while (1) {
utf8strlen = 0;
nextfont = NULL;
/* if (align == AlignL) */
utf8str = text + i;
while ((align == AlignL && i < textlen) || (align == AlignR && i > 0)) {
if (align == AlignL) {
utf8charlen = utf8decode(text + i, &utf8codepoint, MIN(textlen - i, UTF_SIZ));
if (!utf8charlen) {
textlen = i;
break;
}
} else {
n = utf8nextchar(text, textlen, i, -1);
utf8charlen = utf8decode(text + n, &utf8codepoint, MIN(textlen - n, UTF_SIZ));
if (!utf8charlen) {
textlen -= i;
text += i;
i = 0;
break;
}
}
for (curfont = drw->fonts; curfont; curfont = curfont->next) {
charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint);
if (charexists) {
if (curfont == usedfont) {
utf8strlen += utf8charlen;
i += align == AlignL ? utf8charlen : -utf8charlen;
} else {
nextfont = curfont;
}
break;
}
}
if (!charexists || nextfont)
break;
else
charexists = 0;
}
if (align == AlignR)
utf8str = text + i;
if (utf8strlen) {
drw_font_getexts(usedfont, utf8str, utf8strlen, &ew, NULL);
/* shorten text if necessary */
if (align == AlignL) {
for (len = utf8strlen; len && ew > w; ) {
len = utf8nextchar(utf8str, len, len, -1);
drw_font_getexts(usedfont, utf8str, len, &ew, NULL);
}
} else {
for (len = utf8strlen; len && ew > w; ) {
n = utf8nextchar(utf8str, len, 0, +1);
utf8str += n;
len -= n;
drw_font_getexts(usedfont, utf8str, len, &ew, NULL);
}
}
if (len) {
if (render) {
ty = y + (h - usedfont->h) / 2 + usedfont->xfont->ascent;
XftDrawStringUtf8(d, &drw->scheme[ColFg],
usedfont->xfont, align == AlignL ? x : x - ew, ty, (XftChar8 *)utf8str, len);
}
x += align == AlignL ? ew : -ew;
w -= ew;
}
if (len < utf8strlen)
break;
}
if ((align == AlignR && i <= 0) || (align == AlignL && i >= textlen)) {
break;
} else if (nextfont) {
charexists = 0;
usedfont = nextfont;
} else {
/* Regardless of whether or not a fallback font is found, the
* character must be drawn. */
charexists = 1;
fccharset = FcCharSetCreate();
FcCharSetAddChar(fccharset, utf8codepoint);
if (!drw->fonts->pattern) {
/* Refer to the comment in xfont_create for more information. */
die("the first font in the cache must be loaded from a font string.");
}
fcpattern = FcPatternDuplicate(drw->fonts->pattern);
FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
FcPatternAddBool(fcpattern, FC_SCALABLE, FcTrue);
FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
FcDefaultSubstitute(fcpattern);
match = XftFontMatch(drw->dpy, drw->screen, fcpattern, &result);
FcCharSetDestroy(fccharset);
FcPatternDestroy(fcpattern);
if (match) {
usedfont = xfont_create(drw, NULL, match);
if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) {
for (curfont = drw->fonts; curfont->next; curfont = curfont->next)
; /* NOP */
curfont->next = usedfont;
} else {
xfont_free(usedfont);
usedfont = drw->fonts;
}
}
}
}
if (d)
XftDrawDestroy(d);
return x;
}

View File

@ -1,3 +0,0 @@
enum { AlignL, AlignR };
int drw_text_align(Drw *drw, int x, int y, unsigned int w, unsigned int h, const char *text, int textlen, int align);

View File

@ -1,34 +0,0 @@
#include <X11/Xresource.h>
void
readxresources(void)
{
XrmInitialize();
char* xrm;
if ((xrm = XResourceManagerString(drw->dpy))) {
char *type;
XrmDatabase xdb = XrmGetStringDatabase(xrm);
XrmValue xval;
if (XrmGetResource(xdb, "dmenu.font", "*", &type, &xval))
fonts[0] = strdup(xval.addr);
else
fonts[0] = strdup(fonts[0]);
if (XrmGetResource(xdb, "dmenu.background", "*", &type, &xval))
colors[SchemeNorm][ColBg] = strdup(xval.addr);
if (XrmGetResource(xdb, "dmenu.foreground", "*", &type, &xval))
colors[SchemeNorm][ColFg] = strdup(xval.addr);
if (XrmGetResource(xdb, "dmenu.selbackground", "*", &type, &xval))
colors[SchemeSel][ColBg] = strdup(xval.addr);
if (XrmGetResource(xdb, "dmenu.selforeground", "*", &type, &xval))
colors[SchemeSel][ColFg] = strdup(xval.addr);
if (XrmGetResource(xdb, "dmenu.outbackground", "*", &type, &xval))
colors[SchemeOut][ColBg] = strdup(xval.addr);
if (XrmGetResource(xdb, "dmenu.outforeground", "*", &type, &xval))
colors[SchemeOut][ColFg] = strdup(xval.addr);
if (XrmGetResource(xdb, "dmenu.bordercolor", "*", &type, &xval))
colors[SchemeBorder][ColBg] = strdup(xval.addr);
XrmDestroyDatabase(xdb);
}
}

View File

@ -1,90 +0,0 @@
.TH STEST 1 dmenu\-VERSION
.SH NAME
stest \- filter a list of files by properties
.SH SYNOPSIS
.B stest
.RB [ -abcdefghlpqrsuwx ]
.RB [ -n
.IR file ]
.RB [ -o
.IR file ]
.RI [ file ...]
.SH DESCRIPTION
.B stest
takes a list of files and filters by the files' properties, analogous to
.IR test (1).
Files which pass all tests are printed to stdout. If no files are given, stest
reads files from stdin.
.SH OPTIONS
.TP
.B \-a
Test hidden files.
.TP
.B \-b
Test that files are block specials.
.TP
.B \-c
Test that files are character specials.
.TP
.B \-d
Test that files are directories.
.TP
.B \-e
Test that files exist.
.TP
.B \-f
Test that files are regular files.
.TP
.B \-g
Test that files have their set-group-ID flag set.
.TP
.B \-h
Test that files are symbolic links.
.TP
.B \-l
Test the contents of a directory given as an argument.
.TP
.BI \-n " file"
Test that files are newer than
.IR file .
.TP
.BI \-o " file"
Test that files are older than
.IR file .
.TP
.B \-p
Test that files are named pipes.
.TP
.B \-q
No files are printed, only the exit status is returned.
.TP
.B \-r
Test that files are readable.
.TP
.B \-s
Test that files are not empty.
.TP
.B \-u
Test that files have their set-user-ID flag set.
.TP
.B \-v
Invert the sense of tests, only failing files pass.
.TP
.B \-w
Test that files are writable.
.TP
.B \-x
Test that files are executable.
.SH EXIT STATUS
.TP
.B 0
At least one file passed all tests.
.TP
.B 1
No files passed all tests.
.TP
.B 2
An error occurred.
.SH SEE ALSO
.IR dmenu (1),
.IR test (1)

View File

@ -1,109 +0,0 @@
/* See LICENSE file for copyright and license details. */
#include <sys/stat.h>
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "arg.h"
char *argv0;
#define FLAG(x) (flag[(x)-'a'])
static void test(const char *, const char *);
static void usage(void);
static int match = 0;
static int flag[26];
static struct stat old, new;
static void
test(const char *path, const char *name)
{
struct stat st, ln;
if ((!stat(path, &st) && (FLAG('a') || name[0] != '.') /* hidden files */
&& (!FLAG('b') || S_ISBLK(st.st_mode)) /* block special */
&& (!FLAG('c') || S_ISCHR(st.st_mode)) /* character special */
&& (!FLAG('d') || S_ISDIR(st.st_mode)) /* directory */
&& (!FLAG('e') || access(path, F_OK) == 0) /* exists */
&& (!FLAG('f') || S_ISREG(st.st_mode)) /* regular file */
&& (!FLAG('g') || st.st_mode & S_ISGID) /* set-group-id flag */
&& (!FLAG('h') || (!lstat(path, &ln) && S_ISLNK(ln.st_mode))) /* symbolic link */
&& (!FLAG('n') || st.st_mtime > new.st_mtime) /* newer than file */
&& (!FLAG('o') || st.st_mtime < old.st_mtime) /* older than file */
&& (!FLAG('p') || S_ISFIFO(st.st_mode)) /* named pipe */
&& (!FLAG('r') || access(path, R_OK) == 0) /* readable */
&& (!FLAG('s') || st.st_size > 0) /* not empty */
&& (!FLAG('u') || st.st_mode & S_ISUID) /* set-user-id flag */
&& (!FLAG('w') || access(path, W_OK) == 0) /* writable */
&& (!FLAG('x') || access(path, X_OK) == 0)) != FLAG('v')) { /* executable */
if (FLAG('q'))
exit(0);
match = 1;
puts(name);
}
}
static void
usage(void)
{
fprintf(stderr, "usage: %s [-abcdefghlpqrsuvwx] "
"[-n file] [-o file] [file...]\n", argv0);
exit(2); /* like test(1) return > 1 on error */
}
int
main(int argc, char *argv[])
{
struct dirent *d;
char path[PATH_MAX], *line = NULL, *file;
size_t linesiz = 0;
ssize_t n;
DIR *dir;
int r;
ARGBEGIN {
case 'n': /* newer than file */
case 'o': /* older than file */
file = EARGF(usage());
if (!(FLAG(ARGC()) = !stat(file, (ARGC() == 'n' ? &new : &old))))
perror(file);
break;
default:
/* miscellaneous operators */
if (strchr("abcdefghlpqrsuvwx", ARGC()))
FLAG(ARGC()) = 1;
else
usage(); /* unknown flag */
} ARGEND;
if (!argc) {
/* read list from stdin */
while ((n = getline(&line, &linesiz, stdin)) > 0) {
if (line[n - 1] == '\n')
line[n - 1] = '\0';
test(line, line);
}
free(line);
} else {
for (; argc; argc--, argv++) {
if (FLAG('l') && (dir = opendir(*argv))) {
/* test directory contents */
while ((d = readdir(dir))) {
r = snprintf(path, sizeof path, "%s/%s",
*argv, d->d_name);
if (r >= 0 && (size_t)r < sizeof path)
test(path, d->d_name);
}
closedir(dir);
} else {
test(*argv, *argv);
}
}
}
return match ? 0 : 1;
}

View File

@ -1,36 +0,0 @@
/* See LICENSE file for copyright and license details. */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
void
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
fputc(' ', stderr);
perror(NULL);
} else {
fputc('\n', stderr);
}
exit(1);
}
void *
ecalloc(size_t nmemb, size_t size)
{
void *p;
if (!(p = calloc(nmemb, size)))
die("calloc:");
return p;
}

View File

@ -1,13 +0,0 @@
/* See LICENSE file for copyright and license details. */
#ifndef MAX
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#endif
#ifndef MIN
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#endif
#define BETWEEN(X, A, B) ((A) <= (X) && (X) <= (B))
#define LENGTH(X) (sizeof (X) / sizeof (X)[0])
void die(const char *fmt, ...);
void *ecalloc(size_t nmemb, size_t size);

View File

@ -1,3 +0,0 @@
*.o
dwm
dwm-msg

View File

@ -1,38 +0,0 @@
MIT/X Consortium License
© 2006-2019 Anselm R Garbe <anselm@garbe.ca>
© 2006-2009 Jukka Salmi <jukka at salmi dot ch>
© 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
© 2007-2011 Peter Hartlich <sgkkr at hartlich dot com>
© 2007-2009 Szabolcs Nagy <nszabolcs at gmail dot com>
© 2007-2009 Christof Musik <christof at sendfax dot de>
© 2007-2009 Premysl Hruby <dfenze at gmail dot com>
© 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
© 2008 Martin Hurton <martin dot hurton at gmail dot com>
© 2008 Neale Pickett <neale dot woozle dot org>
© 2009 Mate Nagy <mnagy at port70 dot net>
© 2010-2016 Hiltjo Posthuma <hiltjo@codemadness.org>
© 2010-2012 Connor Lane Smith <cls@lubutu.com>
© 2011 Christoph Lohmann <20h@r-36.net>
© 2015-2016 Quentin Rameau <quinq@fifth.space>
© 2015-2016 Eric Pruitt <eric.pruitt@gmail.com>
© 2016-2017 Markus Teich <markus.teich@stusta.mhn.de>
© 2020-2022 Chris Down <chris@chrisdown.name>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,64 +0,0 @@
# dwm - dynamic window manager
# See LICENSE file for copyright and license details.
include config.mk
SRC = drw.c dwm.c util.c
OBJ = ${SRC:.c=.o}
# FreeBSD users, prefix all ifdef, else and endif statements with a . for this to work (e.g. .ifdef)
ifdef YAJLLIBS
all: dwm dwm-msg
else
all: dwm
endif
.c.o:
${CC} -c ${CFLAGS} $<
${OBJ}: config.h config.mk
config.h:
cp config.def.h $@
dwm: ${OBJ}
${CC} -o $@ ${OBJ} ${LDFLAGS}
ifdef YAJLLIBS
dwm-msg:
${CC} -o $@ patch/ipc/dwm-msg.c ${LDFLAGS}
endif
clean:
rm -f dwm ${OBJ} dwm-${VERSION}.tar.gz
rm -f dwm-msg
dist: clean
mkdir -p dwm-${VERSION}
cp -R LICENSE Makefile README config.def.h config.mk\
dwm.1 drw.h util.h ${SRC} dwm.png transient.c dwm-${VERSION}
tar -cf dwm-${VERSION}.tar dwm-${VERSION}
gzip dwm-${VERSION}.tar
rm -rf dwm-${VERSION}
install: all
mkdir -p ${DESTDIR}${PREFIX}/bin
cp -f dwm ${DESTDIR}${PREFIX}/bin
ifdef YAJLLIBS
cp -f dwm-msg ${DESTDIR}${PREFIX}/bin
endif
cp -f patch/dwmc ${DESTDIR}${PREFIX}/bin
chmod 755 ${DESTDIR}${PREFIX}/bin/dwm
ifdef YAJLLIBS
chmod 755 ${DESTDIR}${PREFIX}/bin/dwm-msg
endif
mkdir -p ${DESTDIR}${MANPREFIX}/man1
sed "s/VERSION/${VERSION}/g" < dwm.1 > ${DESTDIR}${MANPREFIX}/man1/dwm.1
chmod 644 ${DESTDIR}${MANPREFIX}/man1/dwm.1
uninstall:
rm -f ${DESTDIR}${PREFIX}/bin/dwm\
${DESTDIR}${MANPREFIX}/man1/dwm.1
.PHONY: all clean dist install uninstall

View File

@ -1,49 +0,0 @@
# dwm - dynamic window manager
This build of dwm was generated using [dwm-flexipatch](https://github.com/bakkeby/dwm-flexipatch.git) and finalized by [flexipatch-finalizer](https://github.com/bakkeby/flexipatch-finalizer).
## Patches
The patches used are listed below:
- BAR_DWMBLOCKS_PATCH
- BAR_LTSYMBOL_PATCH
- BAR_STATUS_PATCH
- BAR_STATUSBUTTON_PATCH
- BAR_STATUSCMD_PATCH
- BAR_STATUS2D_PATCH
- BAR_STATUS2D_XRDB_TERMCOLORS_PATCH
- BAR_TAGS_PATCH
- BAR_BORDER_PATCH
- BAR_EWMHTAGS_PATCH
- BAR_HEIGHT_PATCH
- BAR_HIDEVACANTTAGS_PATCH
- BAR_HOLDBAR_PATCH
- CENTER_PATCH
- COOL_AUTOSTART_PATCH
- DWMC_PATCH
- FAKEFULLSCREEN_CLIENT_PATCH
- FOCUSDIR_PATCH
- FOCUSONCLICK_PATCH
- KILLUNSEL_PATCH
- MONOCLESYMBOL_PATCH
- NOBORDER_PATCH
- NODMENU_PATCH
- NO_TRANSPARENT_BORDERS_PATCH
- ON_EMPTY_KEYS_PATCH
- PERTAG_PATCH
- RESTARTSIG_PATCH
- ROTATESTACK_PATCH
- SAVEFLOATS_PATCH
- SCRATCHPADS_PATCH
- scratchpads_keep_position_and_size_patch
- SEAMLESS_RESTART_PATCH
- SHIFTBOTH_PATCH
- SHIFTVIEW_CLIENTS_PATCH
- SWITCHTAG_PATCH
- TAPRESIZE_PATCH
- TOGGLETAG_PATCH
- TRANSFER_PATCH
- XRDB_PATCH
- TILE_LAYOUT
- MONOCLE_LAYOUT

View File

@ -1,437 +0,0 @@
/* See LICENSE file for copyright and license details. */
#include <X11/XF86keysym.h>
/* appearance */
static const unsigned int borderpx = 1; /* border pixel of windows */
/* This allows the bar border size to be explicitly set separately from borderpx.
* If left as 0 then it will default to the borderpx value of the monitor and will
* automatically update with setborderpx. */
static const unsigned int barborderpx = 0; /* border pixel of bar */
static const unsigned int snap = 32; /* snap pixel */
static const int showbar = 1; /* 0 means no bar */
static const int topbar = 0; /* 0 means bottom bar */
static const int bar_height = 0; /* 0 means derive from font, >= 1 explicit height */
static const int focusonwheel = 0;
/* Status is to be shown on: -1 (all monitors), 0 (a specific monitor by index), 'A' (active monitor) */
static const int statusmon = 'A';
static const int horizpadbar = 2; /* horizontal padding for statusbar */
static const int vertpadbar = 0; /* vertical padding for statusbar */
static const char buttonbar[] = "";
/* Indicators: see patch/bar_indicators.h for options */
static int tagindicatortype = INDICATOR_NONE;
static int tiledindicatortype = INDICATOR_NONE;
static int floatindicatortype = INDICATOR_TOP_LEFT_SQUARE;
static int fakefsindicatortype = INDICATOR_PLUS;
static int floatfakefsindicatortype = INDICATOR_PLUS_AND_LARGER_SQUARE;
static const char *fonts[] = { "CaskaydiaCove NF :pixelsize=12" };
static const char dmenufont[] = "monospace:size=10";
static char c000000[] = "#000000"; // placeholder value
static char normfgcolor[] = "#bbbbbb";
static char normbgcolor[] = "#222222";
static char normbordercolor[] = "#444444";
static char normfloatcolor[] = "#db8fd9";
static char selfgcolor[] = "#eeeeee";
static char selbgcolor[] = "#005577";
static char selbordercolor[] = "#005577";
static char selfloatcolor[] = "#005577";
static char titlenormfgcolor[] = "#bbbbbb";
static char titlenormbgcolor[] = "#222222";
static char titlenormbordercolor[] = "#444444";
static char titlenormfloatcolor[] = "#db8fd9";
static char titleselfgcolor[] = "#eeeeee";
static char titleselbgcolor[] = "#005577";
static char titleselbordercolor[] = "#005577";
static char titleselfloatcolor[] = "#005577";
static char tagsnormfgcolor[] = "#bbbbbb";
static char tagsnormbgcolor[] = "#222222";
static char tagsnormbordercolor[] = "#444444";
static char tagsnormfloatcolor[] = "#db8fd9";
static char tagsselfgcolor[] = "#eeeeee";
static char tagsselbgcolor[] = "#005577";
static char tagsselbordercolor[] = "#005577";
static char tagsselfloatcolor[] = "#005577";
static char hidnormfgcolor[] = "#005577";
static char hidselfgcolor[] = "#227799";
static char hidnormbgcolor[] = "#222222";
static char hidselbgcolor[] = "#222222";
static char urgfgcolor[] = "#bbbbbb";
static char urgbgcolor[] = "#222222";
static char urgbordercolor[] = "#ff0000";
static char urgfloatcolor[] = "#db8fd9";
static char *colors[][ColCount] = {
/* fg bg border float */
[SchemeNorm] = { normfgcolor, normbgcolor, normbordercolor, normfloatcolor },
[SchemeSel] = { selfgcolor, selbgcolor, selbordercolor, selfloatcolor },
[SchemeTitleNorm] = { titlenormfgcolor, titlenormbgcolor, titlenormbordercolor, titlenormfloatcolor },
[SchemeTitleSel] = { titleselfgcolor, titleselbgcolor, titleselbordercolor, titleselfloatcolor },
[SchemeTagsNorm] = { tagsnormfgcolor, tagsnormbgcolor, tagsnormbordercolor, tagsnormfloatcolor },
[SchemeTagsSel] = { tagsselfgcolor, tagsselbgcolor, tagsselbordercolor, tagsselfloatcolor },
[SchemeHidNorm] = { hidnormfgcolor, hidnormbgcolor, c000000, c000000 },
[SchemeHidSel] = { hidselfgcolor, hidselbgcolor, c000000, c000000 },
[SchemeUrg] = { urgfgcolor, urgbgcolor, urgbordercolor, urgfloatcolor },
};
static const char *const autostart[] = {
// "st", NULL,
"dwmblocks", NULL,
NULL /* terminate */
};
const char *spcmd1[] = {"st", "-n", "spterm", "-g", "120x28", NULL };
const char *spcmd2[] = {"st", "-n", "spcalc", "-g", "120x28", "-e", "qalc", "--color", "--interactive", NULL };
const char *spcmd3[] = {"qalculate-gtk", NULL };
const char *spcmd4[] = {"st", "-n", "spmusic", "-g", "100x25", "-e", "ncmpcpp", NULL };
const char *spcmd5[] = {"st", "-n", "spnotes", "-g", "120x34", "-e", "nvim", NULL };
static Sp scratchpads[] = {
/* name cmd */
{"spterm", spcmd1},
{"spcalc", spcmd2},
{"spcalcgui", spcmd3},
{"spmusic", spcmd4},
{"spnotes", spcmd5},
};
/* Tags
* In a traditional dwm the number of tags in use can be changed simply by changing the number
* of strings in the tags array. This build does things a bit different which has some added
* benefits. If you need to change the number of tags here then change the NUMTAGS macro in dwm.c.
*
* Examples:
*
* 1) static char *tagicons[][NUMTAGS*2] = {
* [DEFAULT_TAGS] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I" },
* }
*
* 2) static char *tagicons[][1] = {
* [DEFAULT_TAGS] = { "" },
* }
*
* The first example would result in the tags on the first monitor to be 1 through 9, while the
* tags for the second monitor would be named A through I. A third monitor would start again at
* 1 through 9 while the tags on a fourth monitor would also be named A through I. Note the tags
* count of NUMTAGS*2 in the array initialiser which defines how many tag text / icon exists in
* the array. This can be changed to *3 to add separate icons for a third monitor.
*
* For the second example each tag would be represented as a bullet point. Both cases work the
* same from a technical standpoint - the icon index is derived from the tag index and the monitor
* index. If the icon index is is greater than the number of tag icons then it will wrap around
* until it an icon matches. Similarly if there are two tag icons then it would alternate between
* them. This works seamlessly with alternative tags and alttagsdecoration patches.
*/
static char *tagicons[][NUMTAGS] =
{
[DEFAULT_TAGS] = { "1", "2", "3", "4", "5", "6", "7", "8", "9" },
[ALTERNATIVE_TAGS] = { "A", "B", "C", "D", "E", "F", "G", "H", "I" },
[ALT_TAGS_DECORATION] = { "<1>", "<2>", "<3>", "<4>", "<5>", "<6>", "<7>", "<8>", "<9>" },
};
/* There are two options when it comes to per-client rules:
* - a typical struct table or
* - using the RULE macro
*
* A traditional struct table looks like this:
* // class instance title wintype tags mask isfloating monitor
* { "Gimp", NULL, NULL, NULL, 1 << 4, 0, -1 },
* { "Firefox", NULL, NULL, NULL, 1 << 7, 0, -1 },
*
* The RULE macro has the default values set for each field allowing you to only
* specify the values that are relevant for your rule, e.g.
*
* RULE(.class = "Gimp", .tags = 1 << 4)
* RULE(.class = "Firefox", .tags = 1 << 7)
*
* Refer to the Rule struct definition for the list of available fields depending on
* the patches you enable.
*/
static const Rule rules[] = {
/* xprop(1):
* WM_CLASS(STRING) = instance, class
* WM_NAME(STRING) = title
* WM_WINDOW_ROLE(STRING) = role
* _NET_WM_WINDOW_TYPE(ATOM) = wintype
*/
RULE(.wintype = WTYPE "DIALOG", .isfloating = 1)
RULE(.wintype = WTYPE "UTILITY", .isfloating = 1)
RULE(.wintype = WTYPE "TOOLBAR", .isfloating = 1)
RULE(.wintype = WTYPE "SPLASH", .isfloating = 1)
RULE(.class = "firefox", .tags = 1 << 1, .switchtag = 1)
RULE(.title = "nvim", .tags = 1 << 2, .switchtag = 1)
RULE(.title = "lf", .tags = 1 << 3, .switchtag = 1)
RULE(.class = "mpv", .tags = 1 << 4, .switchtag = 3)
RULE(.title = "newsboat", .tags = 1 << 5, .switchtag = 3)
RULE(.class = "Zathura", .tags = 1 << 6, .switchtag = 3)
RULE(.title = "nsxiv", .tags = 1 << 7, .switchtag = 3)
RULE(.class = "Gimp", .tags = 1 << 8, .switchtag = 3)
RULE(.instance = "libreoffice", .tags = 1 << 8, .switchtag = 3)
RULE(.instance = "spterm", .tags = SPTAG(0), .isfloating = 1)
RULE(.instance = "spcalc", .tags = SPTAG(1), .isfloating = 1)
RULE(.class = "Qalculate-gtk", .tags = SPTAG(2), .isfloating = 1)
RULE(.instance = "spmusic", .tags = SPTAG(3), .isfloating = 1)
RULE(.instance = "spnotes", .tags = SPTAG(4), .isfloating = 1)
RULE(.instance = "spterm", .tags = SPTAG(0), .isfloating = 1)
RULE(.instance = "dictionary", .isfloating = 1)
RULE(.class = "volume-ui", .isfloating = 1)
RULE(.class = "gping-ui", .isfloating = 1)
RULE(.class = "PersepolisDM", .title = "(None)None",.isfloating = 1)
RULE(.class = "gnuplot_qt", .isfloating = 1)
};
/* Bar rules allow you to configure what is shown where on the bar, as well as
* introducing your own bar modules.
*
* monitor:
* -1 show on all monitors
* 0 show on monitor 0
* 'A' show on active monitor (i.e. focused / selected) (or just -1 for active?)
* bar - bar index, 0 is default, 1 is extrabar
* alignment - how the module is aligned compared to other modules
* widthfunc, drawfunc, clickfunc - providing bar module width, draw and click functions
* name - does nothing, intended for visual clue and for logging / debugging
*/
static const BarRule barrules[] = {
/* monitor bar alignment widthfunc drawfunc clickfunc hoverfunc name */
{ -1, 0, BAR_ALIGN_LEFT, width_stbutton, draw_stbutton, click_stbutton, NULL, "statusbutton" },
{ -1, 0, BAR_ALIGN_LEFT, width_tags, draw_tags, click_tags, hover_tags, "tags" },
{ -1, 0, BAR_ALIGN_LEFT, width_ltsymbol, draw_ltsymbol, click_ltsymbol, NULL, "layout" },
{ statusmon, 0, BAR_ALIGN_RIGHT, width_status2d, draw_status2d, click_statuscmd, NULL, "status2d" },
};
/* layout(s) */
static const float mfact = 0.50; /* factor of master area size [0.05..0.95] */
static const int nmaster = 1; /* number of clients in master area */
static const int resizehints = 0; /* 1 means respect size hints in tiled resizals */
static const int lockfullscreen = 1; /* 1 will force focus on the fullscreen window */
/* mouse scroll resize */
static const int scrollsensetivity = 30; /* 1 means resize window by 1 pixel for each scroll event */
/* resizemousescroll direction argument list */
static const int scrollargs[][2] = {
/* width change height change */
{ +scrollsensetivity, 0 },
{ -scrollsensetivity, 0 },
{ 0, +scrollsensetivity },
{ 0, -scrollsensetivity },
};
static const Layout layouts[] = {
/* symbol arrange function */
{ "󰙀", tile }, /* first entry is default */
{ "󰖲", NULL }, /* no layout function means floating behavior */
{ "󰖯", monocle },
};
/* key definitions */
#define MODKEY Mod4Mask
#define ALTKEY Mod1Mask
#define TAGKEYS(KEY,TAG) \
{ MODKEY, KEY, view, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \
{ MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} },
#define HOLDKEY 0xffeb // replace 0 with the keysym to activate holdbar
/* helper for spawning shell commands in the pre dwm-5.0 fashion */
#define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } }
/* commands */
static const char* dmenu_run_cmd[] = { "dmenu_run", "-bw", "2", "-i", "-W", "390", "-X", "961", "-Y", "15", "-l", "15", "-g", "3", NULL };
static const char* clipmenu_cmd[] = { "clipmenu", "-bw", "2", "-i", "-W", "290", "-X", "1061", "-Y", "15", "-l", "15", NULL };
static const char* volume_ui_cmd[] = { "st", "-c", "volume-ui", "-g=80x15+353+20", "-e", "pulsemixer", NULL } ;
/* This defines the name of the executable that handles the bar (used for signalling purposes) */
#define STATUSBAR "dwmblocks"
static const Key on_empty_keys[] = {
/* modifier key function argument */
{0, XK_e, spawn, {.v = (const char*[]){"fuz-launcher", NULL } } },
{0, XK_f, spawn, {.v = (const char*[]){"fuz-launcher", NULL } } },
{0, XK_w, spawn, {.v = (const char*[]){"firefox", NULL } } },
{0, XK_grave, spawn, {.v = (const char*[]){"dmenunerdsymbols", NULL } } },
{0, XK_BackSpace, spawn, {.v = (const char*[]){"sysact", NULL } } },
{0, XK_r, spawn, {.v = (const char*[]){"st", "-e", "lf", NULL } } },
{0, XK_Return, spawn, {.v = (const char*[]){"st", "-c", "st-terminal", NULL } } },
{0, XK_d, spawn, {.v = dmenu_run_cmd } },
{0, XK_a, spawn, {.v = (const char*[]){"dmenu_hub", NULL } } },
{0, XK_space, spawn, {.v = (const char*[]){"dmenu_web", NULL } } },
{0, XK_n, spawn, {.v = (const char*[]){"st", "-e", "nvim", NULL } } },
{0, XK_p, spawn, {.v = (const char*[]){"st", "-c", "gping-ui", "-g=80x15+353+20", "-e", "gping", "duckduckgo.com", NULL } } },
};
static const Key keys[] = {
/* modifier key function argument */
{ 0, XF86XK_AudioMute, spawn, SHCMD("wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle; pkill -RTMIN+8 dwmblocks") },
{ 0, XF86XK_AudioRaiseVolume, spawn, SHCMD("wpctl set-volume @DEFAULT_AUDIO_SINK@ 0%- && wpctl set-volume @DEFAULT_AUDIO_SINK@ 3%+; pkill -RTMIN+8 dwmblocks") },
{ 0, XF86XK_AudioLowerVolume, spawn, SHCMD("wpctl set-volume @DEFAULT_AUDIO_SINK@ 0%+ && wpctl set-volume @DEFAULT_AUDIO_SINK@ 3%-; pkill -RTMIN+8 dwmblocks") },
{ 0, XF86XK_AudioPrev, spawn, {.v = (const char*[]){ "mpc", "prev", NULL } } },
{ 0, XF86XK_AudioNext, spawn, {.v = (const char*[]){ "mpc", "next", NULL } } },
{ 0, XF86XK_AudioPause, spawn, {.v = (const char*[]){ "mpc", "pause", NULL } } },
{ 0, XF86XK_AudioPlay, spawn, {.v = (const char*[]){ "mpc", "play", NULL } } },
{ MODKEY|ShiftMask, XK_F5, xrdb, {.v = NULL } },
{ 0, XK_F7, spawn, {.v = clipmenu_cmd } },
{ 0, XF86XK_MonBrightnessUp, spawn, {.v = (const char*[]){ "xbacklight", "-inc", "15", NULL } } },
{ 0, XF86XK_MonBrightnessDown, spawn, {.v = (const char*[]){ "xbacklight", "-dec", "15", NULL } } },
{ 0, XK_Print, spawn, {.v = (const char*[]){ "maimpick", NULL } } },
{ MODKEY, XK_Print, spawn, {.v = (const char*[]){ "dmenurecord", NULL } } },
{ MODKEY|ShiftMask, XK_Delete, quit, {0} },
{ MODKEY, XK_Delete, quit, {1} },
{ MODKEY, XK_grave, togglescratch, {.ui = 0 } },
{ MODKEY|ControlMask, XK_grave, setscratch, {.ui = 0 } },
{ MODKEY|ShiftMask, XK_grave, removescratch, {.ui = 0 } },
{ MODKEY, XK_0, view, {.ui = ~SPTAGMASK } },
{ MODKEY|ShiftMask, XK_0, tag, {.ui = ~SPTAGMASK } },
TAGKEYS( XK_1, 0)
TAGKEYS( XK_2, 1)
TAGKEYS( XK_3, 2)
TAGKEYS( XK_4, 3)
TAGKEYS( XK_5, 4)
TAGKEYS( XK_6, 5)
TAGKEYS( XK_7, 6)
TAGKEYS( XK_8, 7)
TAGKEYS( XK_9, 8)
{ MODKEY, XK_equal, spawn, {.v = volume_ui_cmd } },
{ MODKEY, XK_minus, spawn, {.v = volume_ui_cmd } },
{ MODKEY, XK_BackSpace, spawn, {.v = (const char*[]){ "sysact", NULL } } },
{ MODKEY, XK_Tab, view, {0} },
{ MODKEY, XK_q, killclient, {0} },
{ MODKEY|ShiftMask, XK_q, killunsel, {0} },
{ MODKEY, XK_w, spawn, {.v = (const char*[]){ "firefox", NULL } } },
{ MODKEY, XK_e, spawn, {.v = (const char*[]){"fuz-launcher", NULL } } },
{ ALTKEY, XK_e, spawn, {.v = (const char*[]){ "networkmanager_dmenu", NULL } } },
{ MODKEY, XK_r, spawn, {.v = (const char*[]){ "st", "-e", "lf", NULL } } },
{ MODKEY|ShiftMask, XK_r, spawn, {.v = (const char*[]){ "thunar", NULL } } },
{ MODKEY, XK_t, setlayout, {.v = &layouts[0]} },
{ MODKEY, XK_u, setlayout, {.v = &layouts[1]} },
{ MODKEY, XK_y, setlayout, {.v = &layouts[2]} },
{ MODKEY, XK_i, setlayout, {0} },
{ MODKEY, XK_o, incnmaster, {.i = +1 } },
{ MODKEY|ShiftMask, XK_o, incnmaster, {.i = -1 } },
{ MODKEY, XK_p, spawn, {.v = (const char*[]){"st", "-c", "gping-ui", "-g=80x15+353+20", "-e", "gping", "duckduckgo.com", NULL } } },
{ MODKEY, XK_a, spawn, {.v = (const char*[]){ "dmenu_hub", NULL } } },
{ MODKEY, XK_d, spawn, {.v = dmenu_run_cmd } },
{ MODKEY, XK_f, togglefakefullscreen, {0} },
{ MODKEY, XK_h, setmfact, {.f = -0.05} },
{ ALTKEY, XK_h, spawn, {.v = (const char*[]){ "dmenuhandler" , NULL} } },
{ MODKEY, XK_j, focusstack, {.i = +1 } },
{ MODKEY, XK_k, focusstack, {.i = -1 } },
{ MODKEY, XK_l, setmfact, {.f = +0.05} },
{ ALTKEY, XK_l, spawn, {.v = (const char*[]){"dictionary", NULL } } },
{ MODKEY|ShiftMask, XK_apostrophe, togglescratch, {.ui = 2 } },
{ MODKEY, XK_apostrophe, togglescratch, {.ui = 1 } },
{ MODKEY, XK_Return, spawn, {.v = (const char *[]){"st", NULL}}},
{ ALTKEY, XK_Return, spawn, {.v = (const char *[]){"kitty", NULL}}},
{ MODKEY|ShiftMask, XK_Return, togglescratch, {.ui = 0 } },
{ MODKEY, XK_x, transfer, {0} },
{ MODKEY, XK_b, togglebar, {0} },
{ MODKEY|ShiftMask, XK_b, spawn, {.v = (const char*[]){ "dmenu_web", "--add" , NULL } } },
{ MODKEY, XK_n, spawn, {.v = (const char*[]){ "st", "-e", "nvim", NULL } } },
{ ALTKEY, XK_n, spawn, {.v = (const char*[]){ "kitty", "nvim", NULL } } },
{ MODKEY|ShiftMask, XK_n, spawn, {.v = (const char*[]){ "st", "-e", "newsboat", NULL } } },
{ MODKEY, XK_m, togglescratch, {.ui = 3 } },
{ MODKEY, XK_comma, togglescratch, {.ui = 4 } },
{ MODKEY, XK_comma, focusmon, {.i = -1 } },
{ MODKEY, XK_period, focusmon, {.i = +1 } },
{ MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } },
{ MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } },
{ MODKEY, XK_slash, zoom, {0} },
{ 0, HOLDKEY, holdbar, {0} },
{ MODKEY, XK_space, spawn, {.v = (const char*[]){ "dmenu_web", NULL } } },
{ MODKEY|ShiftMask, XK_space, togglefloating, {0} },
{ MODKEY, XK_Left, focusdir, {.i = 0 } }, // left
{ MODKEY, XK_Right, focusdir, {.i = 1 } }, // right
{ MODKEY, XK_Up, focusdir, {.i = 2 } }, // up
{ MODKEY, XK_Down, focusdir, {.i = 3 } }, // down
{ MODKEY|ControlMask, XK_Up, rotatestack, {.i = +1 } },
{ MODKEY|ControlMask, XK_Down, rotatestack, {.i = -1 } },
{ MODKEY|Mod1Mask, XK_Left, shiftboth, { .i = -1 } },
{ MODKEY|Mod1Mask, XK_Right, shiftboth, { .i = +1 } },
{ MODKEY|ControlMask, XK_Left, shiftviewclients, { .i = -1 } },
{ MODKEY|ControlMask, XK_Right, shiftviewclients, { .i = +1 } },
};
/* button definitions */
/* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */
static const Button buttons[] = {
/* click event|mask button function argument */
{ ClkRootWin, 0, Button1, spawn, SHCMD("dunstctl close-all; killall dmenu") },
{ ClkRootWin, 0, Button3, spawn, SHCMD("dunstctl close-all; pgrep -x 'dmenu' > /dev/null && killall dmenu || dmenu_hub") },
{ ClkButton, 0, Button1, spawn, {.v = dmenu_run_cmd } },
{ ClkButton, 0, Button3, spawn, {.v = (const char*[]){ "dmenu_hub", NULL } } },
{ ClkLtSymbol, 0, Button1, setlayout, {0} },
{ ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]} },
{ ClkWinTitle, 0, Button2, zoom, {0} },
{ ClkStatusText, 0, Button1, sigstatusbar, {.i = 1 } },
{ ClkStatusText, 0, Button2, sigstatusbar, {.i = 2 } },
{ ClkStatusText, 0, Button3, sigstatusbar, {.i = 3 } },
{ ClkStatusText, 0, Button4, sigstatusbar, {.i = 4} },
{ ClkStatusText, 0, Button5, sigstatusbar, {.i = 5} },
{ ClkStatusText, ShiftMask, Button1, sigstatusbar, {.i = 6} },
{ ClkStatusText, MODKEY, Button1, sigstatusbar, {.i = 1 } },
{ ClkStatusText, MODKEY, Button2, sigstatusbar, {.i = 2 } },
{ ClkStatusText, MODKEY, Button3, sigstatusbar, {.i = 3 } },
{ ClkStatusText, MODKEY, Button4, sigstatusbar, {.i = 4} },
{ ClkStatusText, MODKEY, Button5, sigstatusbar, {.i = 5} },
{ ClkStatusText, MODKEY|ShiftMask, Button1, sigstatusbar, {.i = 6} },
{ ClkClientWin, 0, Button2, spawn, {.v = (const char*[]){ "dictionary", NULL } } },
{ ClkClientWin, MODKEY, Button1, movemouse, {0} },
{ ClkClientWin, MODKEY, Button2, togglefloating, {0} },
{ ClkClientWin, MODKEY, Button3, resizemouse, {0} },
{ ClkClientWin, MODKEY, Button4, resizemousescroll, {.v = &scrollargs[0]} },
{ ClkClientWin, MODKEY, Button5, resizemousescroll, {.v = &scrollargs[1]} },
{ ClkClientWin, MODKEY, Button6, resizemousescroll, {.v = &scrollargs[2]} },
{ ClkClientWin, MODKEY, Button7, resizemousescroll, {.v = &scrollargs[3]} },
{ ClkTagBar, 0, Button1, view, {0} },
{ ClkTagBar, 0, Button3, toggleview, {0} },
{ ClkTagBar, MODKEY, Button1, tag, {0} },
{ ClkTagBar, MODKEY, Button3, toggletag, {0} },
};
/* signal definitions */
/* signum must be greater than 0 */
/* trigger signals using `xsetroot -name "fsignal:<signame> [<type> <value>]"` */
static const Signal signals[] = {
/* signum function */
{ "focusstack", focusstack },
{ "setmfact", setmfact },
{ "togglebar", togglebar },
{ "incnmaster", incnmaster },
{ "togglefloating", togglefloating },
{ "focusmon", focusmon },
{ "rotatestack", rotatestack },
{ "transfer", transfer },
{ "tagmon", tagmon },
{ "zoom", zoom },
{ "view", view },
{ "viewall", viewallex },
{ "viewex", viewex },
{ "toggleview", toggleview },
{ "shiftboth", shiftboth },
{ "shiftviewclients", shiftviewclients },
{ "toggleviewex", toggleviewex },
{ "tag", tag },
{ "tagall", tagallex },
{ "tagex", tagex },
{ "toggletag", toggletag },
{ "toggletagex", toggletagex },
{ "togglefakefullscreen", togglefakefullscreen },
{ "togglescratch", togglescratch },
{ "killclient", killclient },
{ "xrdb", xrdb },
{ "quit", quit },
{ "setlayout", setlayout },
{ "setlayoutex", setlayoutex },
};

View File

@ -1,73 +0,0 @@
# dwm version
VERSION = 6.5
# Customize below to fit your system
# paths
PREFIX = /usr/local
MANPREFIX = ${PREFIX}/share/man
X11INC = /usr/X11R6/include
X11LIB = /usr/X11R6/lib
# FreeBSD (uncomment)
#X11INC = /usr/local/include
#X11LIB = /usr/local/lib
# Xinerama, comment if you don't want it
# XINERAMALIBS = -lXinerama
# XINERAMAFLAGS = -DXINERAMA
# freetype
FREETYPELIBS = -lfontconfig -lXft
FREETYPEINC = /usr/include/freetype2
# FreeBSD (uncomment)
#FREETYPEINC = /usr/local/include/freetype2
# OpenBSD (uncomment)
#FREETYPEINC = ${X11INC}/freetype2
# OpenBSD - Uncomment this for the swallow patch / SWALLOW_PATCH
#KVMLIB = -lkvm
# Uncomment this for the alpha patch and the winicon patch (BAR_ALPHA_PATCH, BAR_WINICON_PATCH)
#XRENDER = -lXrender
# Uncomment this for the mdpcontrol patch / MDPCONTROL_PATCH
#MPDCLIENT = -lmpdclient
# Uncomment for the pango patch / BAR_PANGO_PATCH
#PANGOINC = `pkg-config --cflags xft pango pangoxft`
#PANGOLIB = `pkg-config --libs xft pango pangoxft`
# Uncomment for the ipc patch / IPC_PATCH
#YAJLLIBS = -lyajl
#YAJLINC = -I/usr/include/yajl
# Uncomment this for the rounded corners patch / ROUNDED_CORNERS_PATCH
#XEXTLIB = -lXext
# Uncomment this for the swallow patch / SWALLOW_PATCH
#XCBLIBS = -lX11-xcb -lxcb -lxcb-res
# This is needed for the winicon and tagpreview patches / BAR_WINICON_PATCH / BAR_TAGPREVIEW_PATCH
#IMLIB2LIBS = -lImlib2
# Uncomment for the bidi patch
#BDINC = `pkg-config --cflags fribidi`
#BDLIBS = `pkg-config --libs fribidi`
# includes and libs
INCS = -I${X11INC} -I${FREETYPEINC} ${YAJLINC} ${PANGOINC} ${BDINC}
LIBS = -L${X11LIB} -lX11 ${XINERAMALIBS} ${FREETYPELIBS} ${XRENDER} ${MPDCLIENT} ${XEXTLIB} ${XCBLIBS} ${KVMLIB} ${PANGOLIB} ${YAJLLIBS} ${IMLIB2LIBS} $(BDLIBS)
# flags
CPPFLAGS = -D_DEFAULT_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700L -DVERSION=\"${VERSION}\" ${XINERAMAFLAGS}
#CFLAGS = -g -std=c99 -pedantic -Wall -O0 ${INCS} ${CPPFLAGS}
CFLAGS = -std=c99 -pedantic -Wall -Wno-unused-function -Wno-deprecated-declarations -Os ${INCS} ${CPPFLAGS}
LDFLAGS = ${LIBS}
# Solaris
#CFLAGS = -fast ${INCS} -DVERSION=\"${VERSION}\"
#LDFLAGS = ${LIBS}
# compiler and linker
CC = cc

View File

@ -1,432 +0,0 @@
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/Xft/Xft.h>
#include "drw.h"
#include "util.h"
#define UTF_INVALID 0xFFFD
#define UTF_SIZ 4
static const unsigned char utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
static const unsigned char utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
static const long utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
static const long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
static long
utf8decodebyte(const char c, size_t *i)
{
for (*i = 0; *i < (UTF_SIZ + 1); ++(*i))
if (((unsigned char)c & utfmask[*i]) == utfbyte[*i])
return (unsigned char)c & ~utfmask[*i];
return 0;
}
static size_t
utf8validate(long *u, size_t i)
{
if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
*u = UTF_INVALID;
for (i = 1; *u > utfmax[i]; ++i)
;
return i;
}
static size_t
utf8decode(const char *c, long *u, size_t clen)
{
size_t i, j, len, type;
long udecoded;
*u = UTF_INVALID;
if (!clen)
return 0;
udecoded = utf8decodebyte(c[0], &len);
if (!BETWEEN(len, 1, UTF_SIZ))
return 1;
for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
if (type)
return j;
}
if (j < len)
return 0;
*u = udecoded;
utf8validate(u, len);
return len;
}
Drw *
drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h)
{
Drw *drw = ecalloc(1, sizeof(Drw));
drw->dpy = dpy;
drw->screen = screen;
drw->root = root;
drw->w = w;
drw->h = h;
drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen));
drw->gc = XCreateGC(dpy, root, 0, NULL);
XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter);
return drw;
}
void
drw_resize(Drw *drw, unsigned int w, unsigned int h)
{
if (!drw)
return;
drw->w = w;
drw->h = h;
if (drw->drawable)
XFreePixmap(drw->dpy, drw->drawable);
drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen));
}
void
drw_free(Drw *drw)
{
XFreePixmap(drw->dpy, drw->drawable);
XFreeGC(drw->dpy, drw->gc);
drw_fontset_free(drw->fonts);
free(drw);
}
/* This function is an implementation detail. Library users should use
* drw_fontset_create instead.
*/
static Fnt *
xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern)
{
Fnt *font;
XftFont *xfont = NULL;
FcPattern *pattern = NULL;
if (fontname) {
/* Using the pattern found at font->xfont->pattern does not yield the
* same substitution results as using the pattern returned by
* FcNameParse; using the latter results in the desired fallback
* behaviour whereas the former just results in missing-character
* rectangles being drawn, at least with some fonts. */
if (!(xfont = XftFontOpenName(drw->dpy, drw->screen, fontname))) {
fprintf(stderr, "error, cannot load font from name: '%s'\n", fontname);
return NULL;
}
if (!(pattern = FcNameParse((FcChar8 *) fontname))) {
fprintf(stderr, "error, cannot parse font name to pattern: '%s'\n", fontname);
XftFontClose(drw->dpy, xfont);
return NULL;
}
} else if (fontpattern) {
if (!(xfont = XftFontOpenPattern(drw->dpy, fontpattern))) {
fprintf(stderr, "error, cannot load font from pattern.\n");
return NULL;
}
} else {
die("no font specified.");
}
font = ecalloc(1, sizeof(Fnt));
font->xfont = xfont;
font->pattern = pattern;
font->h = xfont->ascent + xfont->descent;
font->dpy = drw->dpy;
return font;
}
static void
xfont_free(Fnt *font)
{
if (!font)
return;
if (font->pattern)
FcPatternDestroy(font->pattern);
XftFontClose(font->dpy, font->xfont);
free(font);
}
Fnt*
drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount)
{
Fnt *cur, *ret = NULL;
size_t i;
if (!drw || !fonts)
return NULL;
for (i = 1; i <= fontcount; i++) {
if ((cur = xfont_create(drw, fonts[fontcount - i], NULL))) {
cur->next = ret;
ret = cur;
}
}
return (drw->fonts = ret);
}
void
drw_fontset_free(Fnt *font)
{
if (font) {
drw_fontset_free(font->next);
xfont_free(font);
}
}
void
drw_clr_create(
Drw *drw,
Clr *dest,
const char *clrname
) {
if (!drw || !dest || !clrname)
return;
if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen),
DefaultColormap(drw->dpy, drw->screen),
clrname, dest))
die("error, cannot allocate color '%s'", clrname);
dest->pixel |= 0xff << 24;
}
/* Wrapper to create color schemes. The caller has to call free(3) on the
* returned color scheme when done using it. */
Clr *
drw_scm_create(
Drw *drw,
char *clrnames[],
size_t clrcount
) {
size_t i;
Clr *ret;
/* need at least two colors for a scheme */
if (!drw || !clrnames || clrcount < 2 || !(ret = ecalloc(clrcount, sizeof(XftColor))))
return NULL;
for (i = 0; i < clrcount; i++)
drw_clr_create(drw, &ret[i], clrnames[i]);
return ret;
}
void
drw_setfontset(Drw *drw, Fnt *set)
{
if (drw)
drw->fonts = set;
}
void
drw_setscheme(Drw *drw, Clr *scm)
{
if (drw)
drw->scheme = scm;
}
void
drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert)
{
if (!drw || !drw->scheme)
return;
XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel);
if (filled)
XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
else
XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1);
}
int
drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert, Bool markup)
{
char buf[1024];
int ty;
unsigned int ew;
XftDraw *d = NULL;
Fnt *usedfont, *curfont, *nextfont;
size_t i, len;
int utf8strlen, utf8charlen, render = x || y || w || h;
long utf8codepoint = 0;
const char *utf8str;
FcCharSet *fccharset;
FcPattern *fcpattern;
FcPattern *match;
XftResult result;
int charexists = 0;
if (!drw || (render && !drw->scheme) || !text || !drw->fonts)
return 0;
if (!render) {
w = ~w;
} else {
XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel);
XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
d = XftDrawCreate(drw->dpy, drw->drawable,
DefaultVisual(drw->dpy, drw->screen),
DefaultColormap(drw->dpy, drw->screen));
x += lpad;
w -= lpad;
}
usedfont = drw->fonts;
while (1) {
utf8strlen = 0;
utf8str = text;
nextfont = NULL;
while (*text) {
utf8charlen = utf8decode(text, &utf8codepoint, UTF_SIZ);
for (curfont = drw->fonts; curfont; curfont = curfont->next) {
charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint);
if (charexists) {
if (curfont == usedfont) {
utf8strlen += utf8charlen;
text += utf8charlen;
} else {
nextfont = curfont;
}
break;
}
}
if (!charexists || nextfont)
break;
else
charexists = 0;
}
if (utf8strlen) {
drw_font_getexts(usedfont, utf8str, utf8strlen, &ew, NULL);
/* shorten text if necessary */
for (len = MIN(utf8strlen, sizeof(buf) - 1); len && ew > w; drw_font_getexts(usedfont, utf8str, len, &ew, NULL))
len--;
if (len) {
memcpy(buf, utf8str, len);
buf[len] = '\0';
if (len < utf8strlen)
for (i = len; i && i > len - 3; buf[--i] = '.')
; /* NOP */
if (render) {
ty = y + (h - usedfont->h) / 2 + usedfont->xfont->ascent;
XftDrawStringUtf8(d, &drw->scheme[invert ? ColBg : ColFg],
usedfont->xfont, x, ty, (XftChar8 *)buf, len);
}
x += ew;
w -= ew;
}
}
if (!*text) {
break;
} else if (nextfont) {
charexists = 0;
usedfont = nextfont;
} else {
/* Regardless of whether or not a fallback font is found, the
* character must be drawn. */
charexists = 1;
fccharset = FcCharSetCreate();
FcCharSetAddChar(fccharset, utf8codepoint);
if (!drw->fonts->pattern) {
/* Refer to the comment in xfont_create for more information. */
die("the first font in the cache must be loaded from a font string.");
}
fcpattern = FcPatternDuplicate(drw->fonts->pattern);
FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
FcPatternAddBool(fcpattern, FC_SCALABLE, FcTrue);
FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
FcDefaultSubstitute(fcpattern);
match = XftFontMatch(drw->dpy, drw->screen, fcpattern, &result);
FcCharSetDestroy(fccharset);
FcPatternDestroy(fcpattern);
if (match) {
usedfont = xfont_create(drw, NULL, match);
if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) {
for (curfont = drw->fonts; curfont->next; curfont = curfont->next)
; /* NOP */
curfont->next = usedfont;
} else {
xfont_free(usedfont);
usedfont = drw->fonts;
}
}
}
}
if (d)
XftDrawDestroy(d);
return x + (render ? w : 0);
}
void
drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h)
{
if (!drw)
return;
XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y);
XSync(drw->dpy, False);
}
unsigned int
drw_fontset_getwidth(Drw *drw, const char *text, Bool markup)
{
if (!drw || !drw->fonts || !text)
return 0;
return drw_text(drw, 0, 0, 0, 0, 0, text, 0, markup);
}
void
drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h)
{
XGlyphInfo ext;
if (!font || !text)
return;
XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *)text, len, &ext);
if (w)
*w = ext.xOff;
if (h)
*h = font->h;
}
Cur *
drw_cur_create(Drw *drw, int shape)
{
Cur *cur;
if (!drw || !(cur = ecalloc(1, sizeof(Cur))))
return NULL;
cur->cursor = XCreateFontCursor(drw->dpy, shape);
return cur;
}
void
drw_cur_free(Drw *drw, Cur *cursor)
{
if (!cursor)
return;
XFreeCursor(drw->dpy, cursor->cursor);
free(cursor);
}

View File

@ -1,66 +0,0 @@
/* See LICENSE file for copyright and license details. */
typedef struct {
Cursor cursor;
} Cur;
typedef struct Fnt {
Display *dpy;
unsigned int h;
XftFont *xfont;
FcPattern *pattern;
struct Fnt *next;
} Fnt;
enum { ColFg, ColBg, ColBorder, ColFloat, ColCount }; /* Clr scheme index */
typedef XftColor Clr;
typedef struct {
unsigned int w, h;
Display *dpy;
int screen;
Window root;
Drawable drawable;
GC gc;
Clr *scheme;
Fnt *fonts;
} Drw;
/* Drawable abstraction */
Drw *drw_create(Display *dpy, int screen, Window win, unsigned int w, unsigned int h);
void drw_resize(Drw *drw, unsigned int w, unsigned int h);
void drw_free(Drw *drw);
/* Fnt abstraction */
Fnt *drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount);
void drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h);
void drw_fontset_free(Fnt* set);
unsigned int drw_fontset_getwidth(Drw *drw, const char *text, Bool markup);
/* Colorscheme abstraction */
void drw_clr_create(
Drw *drw,
Clr *dest,
const char *clrname
);
Clr *drw_scm_create(
Drw *drw,
char *clrnames[],
size_t clrcount
);
/* Cursor abstraction */
Cur *drw_cur_create(Drw *drw, int shape);
void drw_cur_free(Drw *drw, Cur *cursor);
/* Drawing context manipulation */
void drw_setfontset(Drw *drw, Fnt *set);
void drw_setscheme(Drw *drw, Clr *scm);
/* Drawing functions */
void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert);
int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert, Bool markup);
/* Map functions */
void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h);

View File

@ -1,176 +0,0 @@
.TH DWM 1 dwm\-VERSION
.SH NAME
dwm \- dynamic window manager
.SH SYNOPSIS
.B dwm
.RB [ \-v ]
.SH DESCRIPTION
dwm is a dynamic window manager for X. It manages windows in tiled, monocle
and floating layouts. Either layout can be applied dynamically, optimising the
environment for the application in use and the task performed.
.P
In tiled layouts windows are managed in a master and stacking area. The master
area on the left contains one window by default, and the stacking area on the
right contains all other windows. The number of master area windows can be
adjusted from zero to an arbitrary number. In monocle layout all windows are
maximised to the screen size. In floating layout windows can be resized and
moved freely. Dialog windows are always managed floating, regardless of the
layout applied.
.P
Windows are grouped by tags. Each window can be tagged with one or multiple
tags. Selecting certain tags displays all windows with these tags.
.P
Each screen contains a small status bar which displays all available tags, the
layout, the title of the focused window, and the text read from the root window
name property, if the screen is focused. A floating window is indicated with an
empty square and a maximised floating window is indicated with a filled square
before the windows title. The selected tags are indicated with a different
color. The tags of the focused window are indicated with a filled square in the
top left corner. The tags which are applied to one or more windows are
indicated with an empty square in the top left corner.
.P
dwm draws a small border around windows to indicate the focus state.
.SH OPTIONS
.TP
.B \-v
prints version information to stderr, then exits.
.SH USAGE
.SS Status bar
.TP
.B X root window name
is read and displayed in the status text area. It can be set with the
.BR xsetroot (1)
command.
.TP
.B Button1
click on a tag label to display all windows with that tag, click on the layout
label toggles between tiled and floating layout.
.TP
.B Button3
click on a tag label adds/removes all windows with that tag to/from the view.
.TP
.B Mod1\-Button1
click on a tag label applies that tag to the focused window.
.TP
.B Mod1\-Button3
click on a tag label adds/removes that tag to/from the focused window.
.SS Keyboard commands
.TP
.B Mod1\-Shift\-Return
Start
.BR st(1).
.TP
.B Mod1\-p
Spawn
.BR dmenu(1)
for launching other programs.
.TP
.B Mod1\-,
Focus previous screen, if any.
.TP
.B Mod1\-.
Focus next screen, if any.
.TP
.B Mod1\-Shift\-,
Send focused window to previous screen, if any.
.TP
.B Mod1\-Shift\-.
Send focused window to next screen, if any.
.TP
.B Mod1\-b
Toggles bar on and off.
.TP
.B Mod1\-t
Sets tiled layout.
.TP
.B Mod1\-f
Sets floating layout.
.TP
.B Mod1\-m
Sets monocle layout.
.TP
.B Mod1\-space
Toggles between current and previous layout.
.TP
.B Mod1\-j
Focus next window.
.TP
.B Mod1\-k
Focus previous window.
.TP
.B Mod1\-i
Increase number of windows in master area.
.TP
.B Mod1\-d
Decrease number of windows in master area.
.TP
.B Mod1\-l
Increase master area size.
.TP
.B Mod1\-h
Decrease master area size.
.TP
.B Mod1\-Return
Zooms/cycles focused window to/from master area (tiled layouts only).
.TP
.B Mod1\-Shift\-c
Close focused window.
.TP
.B Mod1\-Shift\-space
Toggle focused window between tiled and floating state.
.TP
.B Mod1\-Tab
Toggles to the previously selected tags.
.TP
.B Mod1\-Shift\-[1..n]
Apply nth tag to focused window.
.TP
.B Mod1\-Shift\-0
Apply all tags to focused window.
.TP
.B Mod1\-Control\-Shift\-[1..n]
Add/remove nth tag to/from focused window.
.TP
.B Mod1\-[1..n]
View all windows with nth tag.
.TP
.B Mod1\-0
View all windows with any tag.
.TP
.B Mod1\-Control\-[1..n]
Add/remove all windows with nth tag to/from the view.
.TP
.B Mod1\-Shift\-q
Quit dwm.
.SS Mouse commands
.TP
.B Mod1\-Button1
Move focused window while dragging. Tiled windows will be toggled to the floating state.
.TP
.B Mod1\-Button2
Toggles focused window between floating and tiled state.
.TP
.B Mod1\-Button3
Resize focused window while dragging. Tiled windows will be toggled to the floating state.
.SH CUSTOMIZATION
dwm is customized by creating a custom config.h and (re)compiling the source
code. This keeps it fast, secure and simple.
.SH SEE ALSO
.BR dmenu (1),
.BR st (1)
.SH ISSUES
Java applications which use the XToolkit/XAWT backend may draw grey windows
only. The XToolkit/XAWT backend breaks ICCCM-compliance in recent JDK 1.5 and early
JDK 1.6 versions, because it assumes a reparenting window manager. Possible workarounds
are using JDK 1.4 (which doesn't contain the XToolkit/XAWT backend) or setting the
environment variable
.BR AWT_TOOLKIT=MToolkit
(to use the older Motif backend instead) or running
.B xprop -root -f _NET_WM_NAME 32a -set _NET_WM_NAME LG3D
or
.B wmname LG3D
(to pretend that a non-reparenting window manager is running that the
XToolkit/XAWT backend can recognize) or when using OpenJDK setting the environment variable
.BR _JAVA_AWT_WM_NONREPARENTING=1 .
.SH BUGS
Send all bug reports with a patch to hackers@suckless.org.

View File

@ -1,2812 +0,0 @@
/* See LICENSE file for copyright and license details.
*
* dynamic window manager is designed like any other X client as well. It is
* driven through handling X events. In contrast to other X clients, a window
* manager selects for SubstructureRedirectMask on the root window, to receive
* events about window (dis-)appearance. Only one X connection at a time is
* allowed to select for this event mask.
*
* The event handlers of dwm are organized in an array which is accessed
* whenever a new event has been fetched. This allows event dispatching
* in O(1) time.
*
* Each child of the root window is called a client, except windows which have
* set the override_redirect flag. Clients are organized in a linked client
* list on each monitor, the focus history is remembered through a stack list
* on each monitor. Each client contains a bit array to indicate the tags of a
* client.
*
* Keys and tagging rules are organized as arrays and defined in config.h.
*
* To understand everything else, start reading main().
*/
#include <errno.h>
#include <locale.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xproto.h>
#include <X11/Xutil.h>
#ifdef XINERAMA
#include <X11/extensions/Xinerama.h>
#endif /* XINERAMA */
#include <X11/Xft/Xft.h>
#include "drw.h"
#include "util.h"
#include <poll.h>
/* macros */
#define Button6 6
#define Button7 7
#define Button8 8
#define Button9 9
#define NUMTAGS 9
#define NUMVIEWHIST NUMTAGS
#define BARRULES 20
#define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
#define CLEANMASK(mask) (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
#define INTERSECT(x,y,w,h,m) (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
* MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
#define ISVISIBLE(C) ((C->tags & C->mon->tagset[C->mon->seltags]))
#define LENGTH(X) (sizeof X / sizeof X[0])
#define MOUSEMASK (BUTTONMASK|PointerMotionMask)
#define WIDTH(X) ((X)->w + 2 * (X)->bw)
#define HEIGHT(X) ((X)->h + 2 * (X)->bw)
#define WTYPE "_NET_WM_WINDOW_TYPE_"
#define TOTALTAGS (NUMTAGS + LENGTH(scratchpads))
#define TAGMASK ((1 << TOTALTAGS) - 1)
#define SPTAG(i) ((1 << NUMTAGS) << (i))
#define SPTAGMASK (((1 << LENGTH(scratchpads))-1) << NUMTAGS)
#define TEXTWM(X) (drw_fontset_getwidth(drw, (X), True) + lrpad)
#define TEXTW(X) (drw_fontset_getwidth(drw, (X), False) + lrpad)
#define HIDDEN(C) ((getstate(C->win) == IconicState))
/* enums */
enum {
CurNormal,
CurResize,
CurMove,
CurLast
}; /* cursor */
enum {
SchemeNorm,
SchemeSel,
SchemeTitleNorm,
SchemeTitleSel,
SchemeTagsNorm,
SchemeTagsSel,
SchemeHidNorm,
SchemeHidSel,
SchemeUrg,
}; /* color schemes */
enum {
NetSupported, NetWMName, NetWMState, NetWMCheck,
NetWMFullscreen, NetActiveWindow, NetWMWindowType,
NetDesktopNames, NetDesktopViewport, NetNumberOfDesktops, NetCurrentDesktop,
NetClientList,
NetLast
}; /* EWMH atoms */
enum {
WMProtocols,
WMDelete,
WMState,
WMTakeFocus,
WMLast
}; /* default atoms */
enum {
ClientFields,
ClientTags,
ClientLast
}; /* dwm client atoms */
enum {
ClkButton,
ClkTagBar,
ClkLtSymbol,
ClkStatusText,
ClkWinTitle,
ClkClientWin,
ClkRootWin,
ClkLast
}; /* clicks */
enum {
BAR_ALIGN_LEFT,
BAR_ALIGN_CENTER,
BAR_ALIGN_RIGHT,
BAR_ALIGN_LEFT_LEFT,
BAR_ALIGN_LEFT_RIGHT,
BAR_ALIGN_LEFT_CENTER,
BAR_ALIGN_NONE,
BAR_ALIGN_RIGHT_LEFT,
BAR_ALIGN_RIGHT_RIGHT,
BAR_ALIGN_RIGHT_CENTER,
BAR_ALIGN_LAST
}; /* bar alignment */
typedef union {
int i;
unsigned int ui;
float f;
const void *v;
} Arg;
typedef struct Monitor Monitor;
typedef struct Bar Bar;
struct Bar {
Window win;
Monitor *mon;
Bar *next;
int idx;
int showbar;
int topbar;
int external;
int borderpx;
int borderscheme;
int bx, by, bw, bh; /* bar geometry */
int w[BARRULES]; // width, array length == barrules, then use r index for lookup purposes
int x[BARRULES]; // x position, array length == ^
};
typedef struct {
int x;
int y;
int h;
int w;
} BarArg;
typedef struct {
int monitor;
int bar;
int alignment; // see bar alignment enum
int (*widthfunc)(Bar *bar, BarArg *a);
int (*drawfunc)(Bar *bar, BarArg *a);
int (*clickfunc)(Bar *bar, Arg *arg, BarArg *a);
int (*hoverfunc)(Bar *bar, BarArg *a, XMotionEvent *ev);
char *name; // for debugging
int x, w; // position, width for internal use
} BarRule;
typedef struct {
unsigned int click;
unsigned int mask;
unsigned int button;
void (*func)(const Arg *arg);
const Arg arg;
} Button;
typedef struct Client Client;
struct Client {
char name[256];
float mina, maxa;
int x, y, w, h;
int sfx, sfy, sfw, sfh; /* stored float geometry, used on mode revert */
unsigned int idx;
int oldx, oldy, oldw, oldh;
int basew, baseh, incw, inch, maxw, maxh, minw, minh, hintsvalid;
int bw, oldbw;
unsigned int tags;
unsigned int switchtag;
int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen;
int fakefullscreen;
int iscentered;
Client *next;
Client *snext;
Monitor *mon;
Window win;
};
typedef struct {
unsigned int mod;
KeySym keysym;
void (*func)(const Arg *);
const Arg arg;
} Key;
typedef struct {
const char *symbol;
void (*arrange)(Monitor *);
} Layout;
typedef struct Pertag Pertag;
struct Monitor {
char ltsymbol[16];
float mfact;
int nmaster;
int num;
int mx, my, mw, mh; /* screen size */
int wx, wy, ww, wh; /* window area */
unsigned int seltags;
unsigned int sellt;
unsigned int tagset[2];
int showbar;
Client *clients;
Client *sel;
Client *stack;
Monitor *next;
Bar *bar;
const Layout *lt[2];
Pertag *pertag;
};
typedef struct {
const char *class;
const char *instance;
const char *title;
const char *wintype;
unsigned int tags;
int switchtag;
int iscentered;
int isfloating;
int monitor;
} Rule;
#define RULE(...) { .monitor = -1, __VA_ARGS__ },
/* Cross patch compatibility rule macro helper macros */
#define FLOATING , .isfloating = 1
#define CENTERED , .iscentered = 1
#define PERMANENT
#define FAKEFULLSCREEN
#define NOSWALLOW
#define TERMINAL
#define SWITCHTAG , .switchtag = 1
/* function declarations */
static void applyrules(Client *c);
static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact);
static void arrange(Monitor *m);
static void arrangemon(Monitor *m);
static void attach(Client *c);
static void attachstack(Client *c);
static void buttonpress(XEvent *e);
static void checkotherwm(void);
static void cleanup(void);
static void cleanupmon(Monitor *mon);
static void clientmessage(XEvent *e);
static void configure(Client *c);
static void configurenotify(XEvent *e);
static void configurerequest(XEvent *e);
static Monitor *createmon(void);
static void destroynotify(XEvent *e);
static void detach(Client *c);
static void detachstack(Client *c);
static Monitor *dirtomon(int dir);
static void drawbar(Monitor *m);
static void drawbars(void);
static void drawbarwin(Bar *bar);
static void expose(XEvent *e);
static void focus(Client *c);
static void focusin(XEvent *e);
static void focusmon(const Arg *arg);
static void focusstack(const Arg *arg);
static Atom getatomprop(Client *c, Atom prop, Atom req);
static int getrootptr(int *x, int *y);
static long getstate(Window w);
static int gettextprop(Window w, Atom atom, char *text, unsigned int size);
static void grabbuttons(Client *c, int focused);
static void grabkeys(void);
static void incnmaster(const Arg *arg);
static void keypress(XEvent *e);
static void killclient(const Arg *arg);
static void manage(Window w, XWindowAttributes *wa);
static void mappingnotify(XEvent *e);
static void maprequest(XEvent *e);
static void motionnotify(XEvent *e);
static void movemouse(const Arg *arg);
static Client *nexttiled(Client *c);
static int noborder(Client *c);
static void pop(Client *c);
static void propertynotify(XEvent *e);
static void quit(const Arg *arg);
static Monitor *recttomon(int x, int y, int w, int h);
static void resize(Client *c, int x, int y, int w, int h, int interact);
static void resizeclient(Client *c, int x, int y, int w, int h);
static void resizemouse(const Arg *arg);
static void restack(Monitor *m);
static void run(void);
static void scan(void);
static int sendevent(Client *c, Atom proto);
static void sendmon(Client *c, Monitor *m);
static void setclientstate(Client *c, long state);
static void setfocus(Client *c);
static void setfullscreen(Client *c, int fullscreen);
static void setlayout(const Arg *arg);
static void setmfact(const Arg *arg);
static void setup(void);
static void seturgent(Client *c, int urg);
static void sigchld(int unused);
static void showhide(Client *c);
static void spawn(const Arg *arg);
static void tag(const Arg *arg);
static void tagmon(const Arg *arg);
static void togglebar(const Arg *arg);
static void togglefloating(const Arg *arg);
static void toggletag(const Arg *arg);
static void toggleview(const Arg *arg);
static void unfocus(Client *c, int setfocus, Client *nextfocus);
static void unmanage(Client *c, int destroyed);
static void unmapnotify(XEvent *e);
static void updatebarpos(Monitor *m);
static void updatebars(void);
static void updateclientlist(void);
static int updategeom(void);
static void updatenumlockmask(void);
static void updatesizehints(Client *c);
static void updatestatus(void);
static void updatetitle(Client *c);
static void updatewmhints(Client *c);
static void view(const Arg *arg);
static Client *wintoclient(Window w);
static Monitor *wintomon(Window w);
static int xerror(Display *dpy, XErrorEvent *ee);
static int xerrordummy(Display *dpy, XErrorEvent *ee);
static int xerrorstart(Display *dpy, XErrorEvent *ee);
static void zoom(const Arg *arg);
/* bar functions */
#include "patch/include.h"
/* variables */
static const char broken[] = "broken";
static char stext[1024];
static char rawstext[1024];
static int screen;
static int sw, sh; /* X display screen geometry width, height */
static int bh; /* bar geometry */
static int lrpad; /* sum of left and right padding for text */
/* Some clients (e.g. alacritty) helpfully send configure requests with a new size or position
* when they detect that they have been moved to another monitor. This can cause visual glitches
* when moving (or resizing) client windows from one monitor to another. This variable is used
* internally to ignore such configure requests while movemouse or resizemouse are being used. */
static int ignoreconfigurerequests = 0;
static int (*xerrorxlib)(Display *, XErrorEvent *);
static unsigned int numlockmask = 0;
static void (*handler[LASTEvent]) (XEvent *) = {
[ButtonPress] = buttonpress,
[ButtonRelease] = keyrelease,
[ClientMessage] = clientmessage,
[ConfigureRequest] = configurerequest,
[ConfigureNotify] = configurenotify,
[DestroyNotify] = destroynotify,
[Expose] = expose,
[FocusIn] = focusin,
[KeyPress] = keypress,
[KeyRelease] = keyrelease,
[MappingNotify] = mappingnotify,
[MapRequest] = maprequest,
[MotionNotify] = motionnotify,
[PropertyNotify] = propertynotify,
[UnmapNotify] = unmapnotify
};
static Atom wmatom[WMLast], netatom[NetLast];
static Atom clientatom[ClientLast];
static int isempty = 0;
static volatile sig_atomic_t running = 1;
static Cur *cursor[CurLast];
static Clr **scheme;
static Display *dpy;
static Drw *drw;
static Monitor *mons, *selmon;
static Window root, wmcheckwin;
/* configuration, allows nested code to access above variables */
#include "config.h"
#include "patch/include.c"
/* compile-time check if all tags fit into an unsigned int bit array. */
struct NumTags { char limitexceeded[NUMTAGS > 31 ? -1 : 1]; };
/* function implementations */
void
applyrules(Client *c)
{
const char *class, *instance;
Atom wintype;
unsigned int i;
unsigned int newtagset;
const Rule *r;
Monitor *m;
XClassHint ch = { NULL, NULL };
/* rule matching */
c->isfloating = 0;
c->tags = 0;
XGetClassHint(dpy, c->win, &ch);
class = ch.res_class ? ch.res_class : broken;
instance = ch.res_name ? ch.res_name : broken;
wintype = getatomprop(c, netatom[NetWMWindowType], XA_ATOM);
for (i = 0; i < LENGTH(rules); i++) {
r = &rules[i];
if ((!r->title || strstr(c->name, r->title))
&& (!r->class || strstr(class, r->class))
&& (!r->instance || strstr(instance, r->instance))
&& (!r->wintype || wintype == XInternAtom(dpy, r->wintype, False)))
{
c->iscentered = r->iscentered;
c->isfloating = r->isfloating;
c->tags |= r->tags;
if ((r->tags & SPTAGMASK) && r->isfloating) {
c->x = c->mon->wx + (c->mon->ww / 2 - WIDTH(c) / 2);
c->y = c->mon->wy + (c->mon->wh / 2 - HEIGHT(c) / 2);
}
for (m = mons; m && m->num != r->monitor; m = m->next);
if (m)
c->mon = m;
if (r->switchtag)
{
unfocus(selmon->sel, 1, NULL);
selmon = c->mon;
if (r->switchtag == 2 || r->switchtag == 4)
newtagset = c->mon->tagset[c->mon->seltags] ^ c->tags;
else
newtagset = c->tags;
/* Switch to the client's tag, but only if that tag is not already shown */
if (newtagset && !(c->tags & c->mon->tagset[c->mon->seltags])) {
if (r->switchtag == 3 || r->switchtag == 4)
c->switchtag = c->mon->tagset[c->mon->seltags];
if (r->switchtag == 1 || r->switchtag == 3) {
view(&((Arg) { .ui = newtagset }));
} else {
c->mon->tagset[c->mon->seltags] = newtagset;
arrange(c->mon);
}
}
}
}
}
if (ch.res_class)
XFree(ch.res_class);
if (ch.res_name)
XFree(ch.res_name);
c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : (c->mon->tagset[c->mon->seltags] & ~SPTAGMASK);
}
int
applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact)
{
int baseismin;
Monitor *m = c->mon;
/* set minimum possible */
*w = MAX(1, *w);
*h = MAX(1, *h);
if (interact) {
if (*x > sw)
*x = sw - WIDTH(c);
if (*y > sh)
*y = sh - HEIGHT(c);
if (*x + *w + 2 * c->bw < 0)
*x = 0;
if (*y + *h + 2 * c->bw < 0)
*y = 0;
} else {
if (*x >= m->wx + m->ww)
*x = m->wx + m->ww - WIDTH(c);
if (*y >= m->wy + m->wh)
*y = m->wy + m->wh - HEIGHT(c);
if (*x + *w + 2 * c->bw <= m->wx)
*x = m->wx;
if (*y + *h + 2 * c->bw <= m->wy)
*y = m->wy;
}
if (*h < bh)
*h = bh;
if (*w < bh)
*w = bh;
if (resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) {
if (!c->hintsvalid)
updatesizehints(c);
/* see last two sentences in ICCCM 4.1.2.3 */
baseismin = c->basew == c->minw && c->baseh == c->minh;
if (!baseismin) { /* temporarily remove base dimensions */
*w -= c->basew;
*h -= c->baseh;
}
/* adjust for aspect limits */
if (c->mina > 0 && c->maxa > 0) {
if (c->maxa < (float)*w / *h)
*w = *h * c->maxa + 0.5;
else if (c->mina < (float)*h / *w)
*h = *w * c->mina + 0.5;
}
if (baseismin) { /* increment calculation requires this */
*w -= c->basew;
*h -= c->baseh;
}
/* adjust for increment value */
if (c->incw)
*w -= *w % c->incw;
if (c->inch)
*h -= *h % c->inch;
/* restore base dimensions */
*w = MAX(*w + c->basew, c->minw);
*h = MAX(*h + c->baseh, c->minh);
if (c->maxw)
*w = MIN(*w, c->maxw);
if (c->maxh)
*h = MIN(*h, c->maxh);
}
return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
}
void
arrange(Monitor *m)
{
if (m)
showhide(m->stack);
else for (m = mons; m; m = m->next)
showhide(m->stack);
if (m) {
arrangemon(m);
restack(m);
} else for (m = mons; m; m = m->next)
arrangemon(m);
}
void
arrangemon(Monitor *m)
{
strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol);
if (m->lt[m->sellt]->arrange)
m->lt[m->sellt]->arrange(m);
}
void
attach(Client *c)
{
c->next = c->mon->clients;
c->mon->clients = c;
}
void
attachstack(Client *c)
{
c->snext = c->mon->stack;
c->mon->stack = c;
}
void
buttonpress(XEvent *e)
{
int click, i, r;
Arg arg = {0};
Client *c;
Monitor *m;
Bar *bar;
XButtonPressedEvent *ev = &e->xbutton;
const BarRule *br;
BarArg carg = { 0, 0, 0, 0 };
click = ClkRootWin;
/* focus monitor if necessary */
if ((m = wintomon(ev->window)) && m != selmon
&& (focusonwheel || (ev->button != Button4 && ev->button != Button5))
) {
unfocus(selmon->sel, 1, NULL);
selmon = m;
focus(NULL);
}
for (bar = selmon->bar; bar; bar = bar->next) {
if (ev->window == bar->win) {
for (r = 0; r < LENGTH(barrules); r++) {
br = &barrules[r];
if (br->bar != bar->idx || (br->monitor == 'A' && m != selmon) || br->clickfunc == NULL)
continue;
if (br->monitor != 'A' && br->monitor != -1 && br->monitor != bar->mon->num)
continue;
if (bar->x[r] <= ev->x && ev->x <= bar->x[r] + bar->w[r]) {
carg.x = ev->x - bar->x[r];
carg.y = ev->y - bar->borderpx;
carg.w = bar->w[r];
carg.h = bar->bh - 2 * bar->borderpx;
click = br->clickfunc(bar, &arg, &carg);
if (click < 0)
return;
break;
}
}
break;
}
}
if (click == ClkRootWin && (c = wintoclient(ev->window))) {
if (focusonwheel || (ev->button != Button4 && ev->button != Button5))
focus(c);
XAllowEvents(dpy, ReplayPointer, CurrentTime);
click = ClkClientWin;
}
for (i = 0; i < LENGTH(buttons); i++) {
if (click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
&& CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state)) {
buttons[i].func(
(
click == ClkTagBar
) && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg
);
}
}
}
void
checkotherwm(void)
{
xerrorxlib = XSetErrorHandler(xerrorstart);
/* this causes an error if some other window manager is running */
XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
XSync(dpy, False);
XSetErrorHandler(xerror);
XSync(dpy, False);
}
void
cleanup(void)
{
Monitor *m;
Layout foo = { "", NULL };
size_t i;
for (m = mons; m; m = m->next)
persistmonitorstate(m);
/* kill child processes */
for (i = 0; i < autostart_len; i++) {
if (0 < autostart_pids[i]) {
kill(autostart_pids[i], SIGTERM);
waitpid(autostart_pids[i], NULL, 0);
}
}
selmon->lt[selmon->sellt] = &foo;
for (m = mons; m; m = m->next)
while (m->stack)
unmanage(m->stack, 0);
XUngrabKey(dpy, AnyKey, AnyModifier, root);
while (mons)
cleanupmon(mons);
for (i = 0; i < CurLast; i++)
drw_cur_free(drw, cursor[i]);
for (i = 0; i < LENGTH(colors) + 1; i++)
free(scheme[i]);
free(scheme);
XDestroyWindow(dpy, wmcheckwin);
drw_free(drw);
XSync(dpy, False);
XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
}
void
cleanupmon(Monitor *mon)
{
Monitor *m;
Bar *bar;
if (mon == mons)
mons = mons->next;
else {
for (m = mons; m && m->next != mon; m = m->next);
m->next = mon->next;
}
for (bar = mon->bar; bar; bar = mon->bar) {
if (!bar->external) {
XUnmapWindow(dpy, bar->win);
XDestroyWindow(dpy, bar->win);
}
mon->bar = bar->next;
free(bar);
}
free(mon->pertag);
free(mon);
}
void
clientmessage(XEvent *e)
{
XClientMessageEvent *cme = &e->xclient;
Client *c = wintoclient(cme->window);
if (!c)
return;
if (cme->message_type == netatom[NetWMState]) {
if (cme->data.l[1] == netatom[NetWMFullscreen]
|| cme->data.l[2] == netatom[NetWMFullscreen]) {
if (c->fakefullscreen == 2 && c->isfullscreen)
c->fakefullscreen = 3;
setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD */
|| (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */
&& !c->isfullscreen
)));
}
} else if (cme->message_type == netatom[NetActiveWindow]) {
if (c != selmon->sel && !c->isurgent)
seturgent(c, 1);
}
}
void
configure(Client *c)
{
XConfigureEvent ce;
ce.type = ConfigureNotify;
ce.display = dpy;
ce.event = c->win;
ce.window = c->win;
ce.x = c->x;
ce.y = c->y;
ce.width = c->w;
ce.height = c->h;
ce.border_width = c->bw;
if (noborder(c)) {
ce.width += c->bw * 2;
ce.height += c->bw * 2;
ce.border_width = 0;
}
ce.above = None;
ce.override_redirect = False;
XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
}
void
configurenotify(XEvent *e)
{
Monitor *m;
Bar *bar;
Client *c;
XConfigureEvent *ev = &e->xconfigure;
int dirty;
/* TODO: updategeom handling sucks, needs to be simplified */
if (ev->window == root) {
dirty = (sw != ev->width || sh != ev->height);
sw = ev->width;
sh = ev->height;
if (updategeom() || dirty) {
drw_resize(drw, sw, sh);
updatebars();
for (m = mons; m; m = m->next) {
for (c = m->clients; c; c = c->next)
if (c->isfullscreen && c->fakefullscreen != 1)
resizeclient(c, m->mx, m->my, m->mw, m->mh);
for (bar = m->bar; bar; bar = bar->next)
XMoveResizeWindow(dpy, bar->win, bar->bx, bar->by, bar->bw, bar->bh);
}
arrange(NULL);
focus(NULL);
}
}
}
void
configurerequest(XEvent *e)
{
Client *c;
Monitor *m;
XConfigureRequestEvent *ev = &e->xconfigurerequest;
XWindowChanges wc;
if (ignoreconfigurerequests)
return;
if ((c = wintoclient(ev->window))) {
if (ev->value_mask & CWBorderWidth)
c->bw = ev->border_width;
else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) {
m = c->mon;
if (ev->value_mask & CWX) {
c->oldx = c->x;
c->x = m->mx + ev->x;
}
if (ev->value_mask & CWY) {
c->oldy = c->y;
c->y = m->my + ev->y;
}
if (ev->value_mask & CWWidth) {
c->oldw = c->w;
c->w = ev->width;
}
if (ev->value_mask & CWHeight) {
c->oldh = c->h;
c->h = ev->height;
}
if ((c->x + c->w) > m->mx + m->mw && c->isfloating)
c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */
if ((c->y + c->h) > m->my + m->mh && c->isfloating)
c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */
if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
configure(c);
if (ISVISIBLE(c))
XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
} else
configure(c);
} else {
wc.x = ev->x;
wc.y = ev->y;
wc.width = ev->width;
wc.height = ev->height;
wc.border_width = ev->border_width;
wc.sibling = ev->above;
wc.stack_mode = ev->detail;
XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
}
XSync(dpy, False);
}
Monitor *
createmon(void)
{
Monitor *m, *mon;
int i, n, mi, max_bars = 2, istopbar = topbar;
const BarRule *br;
Bar *bar;
m = ecalloc(1, sizeof(Monitor));
m->tagset[0] = m->tagset[1] = 1;
m->mfact = mfact;
m->nmaster = nmaster;
m->showbar = showbar;
for (mi = 0, mon = mons; mon; mon = mon->next, mi++); // monitor index
m->num = mi;
m->lt[0] = &layouts[0];
m->lt[1] = &layouts[1 % LENGTH(layouts)];
strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol);
/* Derive the number of bars for this monitor based on bar rules */
for (n = -1, i = 0; i < LENGTH(barrules); i++) {
br = &barrules[i];
if (br->monitor == 'A' || br->monitor == -1 || br->monitor == m->num)
n = MAX(br->bar, n);
}
m->bar = NULL;
for (i = 0; i <= n && i < max_bars; i++) {
bar = ecalloc(1, sizeof(Bar));
bar->mon = m;
bar->idx = i;
bar->next = m->bar;
bar->topbar = istopbar;
m->bar = bar;
istopbar = !istopbar;
bar->showbar = 1;
bar->external = 0;
bar->borderpx = (barborderpx ? barborderpx : borderpx);
bar->bh = bh + bar->borderpx * 2;
bar->borderscheme = SchemeNorm;
}
if (!(m->pertag = (Pertag *)calloc(1, sizeof(Pertag))))
die("fatal: could not malloc() %u bytes\n", sizeof(Pertag));
m->pertag->curtag = 1;
for (i = 0; i <= NUMTAGS; i++) {
/* init nmaster */
m->pertag->nmasters[i] = m->nmaster;
/* init mfacts */
m->pertag->mfacts[i] = m->mfact;
/* init layouts */
m->pertag->ltidxs[i][0] = m->lt[0];
m->pertag->ltidxs[i][1] = m->lt[1];
m->pertag->sellts[i] = m->sellt;
}
restoremonitorstate(m);
return m;
}
void
destroynotify(XEvent *e)
{
Client *c;
XDestroyWindowEvent *ev = &e->xdestroywindow;
if ((c = wintoclient(ev->window)))
unmanage(c, 1);
}
void
detach(Client *c)
{
Client **tc;
c->idx = 0;
for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
*tc = c->next;
c->next = NULL;
}
void
detachstack(Client *c)
{
Client **tc, *t;
for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
*tc = c->snext;
if (c == c->mon->sel) {
for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
c->mon->sel = t;
}
c->snext = NULL;
}
Monitor *
dirtomon(int dir)
{
Monitor *m = NULL;
if (dir > 0) {
if (!(m = selmon->next))
m = mons;
} else if (selmon == mons)
for (m = mons; m->next; m = m->next);
else
for (m = mons; m->next != selmon; m = m->next);
return m;
}
void
drawbar(Monitor *m)
{
Bar *bar;
if (m->showbar)
for (bar = m->bar; bar; bar = bar->next)
drawbarwin(bar);
}
void
drawbars(void)
{
Monitor *m;
for (m = mons; m; m = m->next)
drawbar(m);
}
void
drawbarwin(Bar *bar)
{
if (!bar || !bar->win || bar->external)
return;
int r, w, total_drawn = 0;
int rx, lx, rw, lw; // bar size, split between left and right if a center module is added
const BarRule *br;
if (bar->borderpx) {
XSetForeground(drw->dpy, drw->gc, scheme[bar->borderscheme][ColBorder].pixel);
XFillRectangle(drw->dpy, drw->drawable, drw->gc, 0, 0, bar->bw, bar->bh);
}
BarArg warg = { 0 };
BarArg darg = { 0 };
warg.h = bar->bh - 2 * bar->borderpx;
rw = lw = bar->bw - 2 * bar->borderpx;
rx = lx = bar->borderpx;
drw_setscheme(drw, scheme[SchemeNorm]);
drw_rect(drw, lx, bar->borderpx, lw, bar->bh - 2 * bar->borderpx, 1, 1);
for (r = 0; r < LENGTH(barrules); r++) {
br = &barrules[r];
if (br->bar != bar->idx || !br->widthfunc || (br->monitor == 'A' && bar->mon != selmon))
continue;
if (br->monitor != 'A' && br->monitor != -1 && br->monitor != bar->mon->num)
continue;
drw_setscheme(drw, scheme[SchemeNorm]);
warg.w = (br->alignment < BAR_ALIGN_RIGHT_LEFT ? lw : rw);
w = br->widthfunc(bar, &warg);
w = MIN(warg.w, w);
if (lw <= 0) { // if left is exhausted then switch to right side, and vice versa
lw = rw;
lx = rx;
} else if (rw <= 0) {
rw = lw;
rx = lx;
}
switch(br->alignment) {
default:
case BAR_ALIGN_NONE:
case BAR_ALIGN_LEFT_LEFT:
case BAR_ALIGN_LEFT:
bar->x[r] = lx;
if (lx == rx) {
rx += w;
rw -= w;
}
lx += w;
lw -= w;
break;
case BAR_ALIGN_LEFT_RIGHT:
case BAR_ALIGN_RIGHT:
bar->x[r] = lx + lw - w;
if (lx == rx)
rw -= w;
lw -= w;
break;
case BAR_ALIGN_LEFT_CENTER:
case BAR_ALIGN_CENTER:
bar->x[r] = lx + lw / 2 - w / 2;
if (lx == rx) {
rw = rx + rw - bar->x[r] - w;
rx = bar->x[r] + w;
}
lw = bar->x[r] - lx;
break;
case BAR_ALIGN_RIGHT_LEFT:
bar->x[r] = rx;
if (lx == rx) {
lx += w;
lw -= w;
}
rx += w;
rw -= w;
break;
case BAR_ALIGN_RIGHT_RIGHT:
bar->x[r] = rx + rw - w;
if (lx == rx)
lw -= w;
rw -= w;
break;
case BAR_ALIGN_RIGHT_CENTER:
bar->x[r] = rx + rw / 2 - w / 2;
if (lx == rx) {
lw = lx + lw - bar->x[r] + w;
lx = bar->x[r] + w;
}
rw = bar->x[r] - rx;
break;
}
bar->w[r] = w;
darg.x = bar->x[r];
darg.y = bar->borderpx;
darg.h = bar->bh - 2 * bar->borderpx;
darg.w = bar->w[r];
if (br->drawfunc)
total_drawn += br->drawfunc(bar, &darg);
}
if (total_drawn == 0 && bar->showbar) {
bar->showbar = 0;
updatebarpos(bar->mon);
XMoveResizeWindow(dpy, bar->win, bar->bx, bar->by, bar->bw, bar->bh);
arrange(bar->mon);
}
else if (total_drawn > 0 && !bar->showbar) {
bar->showbar = 1;
updatebarpos(bar->mon);
XMoveResizeWindow(dpy, bar->win, bar->bx, bar->by, bar->bw, bar->bh);
drw_map(drw, bar->win, 0, 0, bar->bw, bar->bh);
arrange(bar->mon);
} else
drw_map(drw, bar->win, 0, 0, bar->bw, bar->bh);
}
void
expose(XEvent *e)
{
Monitor *m;
XExposeEvent *ev = &e->xexpose;
if (ev->count == 0 && (m = wintomon(ev->window))) {
drawbar(m);
}
}
void
focus(Client *c)
{
if (!c || !ISVISIBLE(c))
for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
if (selmon->sel && selmon->sel != c)
unfocus(selmon->sel, 0, c);
if (c) {
if (c->mon != selmon)
selmon = c->mon;
if (c->isurgent)
seturgent(c, 0);
detachstack(c);
attachstack(c);
grabbuttons(c, 1);
if (c->isfloating)
XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColFloat].pixel);
else
XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel);
setfocus(c);
} else {
XSetInputFocus(dpy, selmon->bar && selmon->bar->win ? selmon->bar->win : root, RevertToPointerRoot, CurrentTime);
XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
}
selmon->sel = c;
drawbars();
if ((isempty && selmon->sel) || (!isempty && !selmon->sel)) {
isempty = !isempty;
grabkeys();
}
}
/* there are some broken focus acquiring clients needing extra handling */
void
focusin(XEvent *e)
{
XFocusChangeEvent *ev = &e->xfocus;
if (selmon->sel && ev->window != selmon->sel->win)
setfocus(selmon->sel);
}
void
focusmon(const Arg *arg)
{
Monitor *m;
if (!mons->next)
return;
if ((m = dirtomon(arg->i)) == selmon)
return;
unfocus(selmon->sel, 0, NULL);
selmon = m;
focus(NULL);
}
void
focusstack(const Arg *arg)
{
Client *c = NULL, *i;
if (!selmon->sel || (selmon->sel->isfullscreen && !selmon->sel->fakefullscreen))
return;
if (arg->i > 0) {
for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
if (!c)
for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
} else {
for (i = selmon->clients; i != selmon->sel; i = i->next)
if (ISVISIBLE(i))
c = i;
if (!c)
for (; i; i = i->next)
if (ISVISIBLE(i))
c = i;
}
if (c) {
focus(c);
restack(selmon);
}
}
Atom
getatomprop(Client *c, Atom prop, Atom req)
{
int di;
unsigned long dl;
unsigned char *p = NULL;
Atom da, atom = None;
/* FIXME getatomprop should return the number of items and a pointer to
* the stored data instead of this workaround */
if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, req,
&da, &di, &dl, &dl, &p) == Success && p) {
atom = *(Atom *)p;
XFree(p);
}
return atom;
}
int
getrootptr(int *x, int *y)
{
int di;
unsigned int dui;
Window dummy;
return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
}
long
getstate(Window w)
{
int format;
long result = -1;
unsigned char *p = NULL;
unsigned long n, extra;
Atom real;
if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
&real, &format, &n, &extra, (unsigned char **)&p) != Success)
return -1;
if (n != 0)
result = *p;
XFree(p);
return result;
}
int
gettextprop(Window w, Atom atom, char *text, unsigned int size)
{
char **list = NULL;
int n;
XTextProperty name;
if (!text || size == 0)
return 0;
text[0] = '\0';
if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems)
return 0;
if (name.encoding == XA_STRING) {
strncpy(text, (char *)name.value, size - 1);
} else if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
strncpy(text, *list, size - 1);
XFreeStringList(list);
}
text[size - 1] = '\0';
XFree(name.value);
return 1;
}
void
grabbuttons(Client *c, int focused)
{
updatenumlockmask();
{
unsigned int i, j;
unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
if (!focused)
XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
BUTTONMASK, GrabModeSync, GrabModeSync, None, None);
for (i = 0; i < LENGTH(buttons); i++)
if (buttons[i].click == ClkClientWin
)
for (j = 0; j < LENGTH(modifiers); j++)
XGrabButton(dpy, buttons[i].button,
buttons[i].mask | modifiers[j],
c->win, False, BUTTONMASK,
GrabModeAsync, GrabModeSync, None, None);
}
}
void
grabkeys(void)
{
updatenumlockmask();
{
unsigned int i, j, k;
unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
int start, end, skip;
KeySym *syms;
XUngrabKey(dpy, AnyKey, AnyModifier, root);
XDisplayKeycodes(dpy, &start, &end);
syms = XGetKeyboardMapping(dpy, start, end - start + 1, &skip);
if (!syms)
return;
for (k = start; k <= end; k++)
for (i = 0; i < LENGTH(keys); i++)
/* skip modifier codes, we do that ourselves */
if (keys[i].keysym == syms[(k - start) * skip])
for (j = 0; j < LENGTH(modifiers); j++)
XGrabKey(dpy, k,
keys[i].mod | modifiers[j],
root, True,
GrabModeAsync, GrabModeAsync);
if (!selmon->sel)
for (k = start; k <= end; k++)
for (i = 0; i < LENGTH(on_empty_keys); i++)
/* skip modifier codes, we do that ourselves */
if (on_empty_keys[i].keysym == syms[(k - start) * skip])
for (j = 0; j < LENGTH(modifiers); j++)
XGrabKey(dpy, k,
on_empty_keys[i].mod | modifiers[j],
root, True,
GrabModeAsync, GrabModeAsync);
XFree(syms);
}
}
void
incnmaster(const Arg *arg)
{
selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag] = MAX(selmon->nmaster + arg->i, 0);
arrange(selmon);
}
#ifdef XINERAMA
static int
isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info)
{
while (n--)
if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
&& unique[n].width == info->width && unique[n].height == info->height)
return 0;
return 1;
}
#endif /* XINERAMA */
void
keypress(XEvent *e)
{
unsigned int i;
int keysyms_return;
KeySym* keysym;
XKeyEvent *ev;
ev = &e->xkey;
keysym = XGetKeyboardMapping(dpy, (KeyCode)ev->keycode, 1, &keysyms_return);
for (i = 0; i < LENGTH(keys); i++)
if (*keysym == keys[i].keysym
&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
&& keys[i].func)
keys[i].func(&(keys[i].arg));
if (!selmon->sel)
for (i = 0; i < LENGTH(on_empty_keys); i++)
if (*keysym == on_empty_keys[i].keysym
&& CLEANMASK(on_empty_keys[i].mod) == CLEANMASK(ev->state)
&& on_empty_keys[i].func)
on_empty_keys[i].func(&(on_empty_keys[i].arg));
XFree(keysym);
}
void
killclient(const Arg *arg)
{
if (!selmon->sel)
return;
if (!sendevent(selmon->sel, wmatom[WMDelete]))
{
XGrabServer(dpy);
XSetErrorHandler(xerrordummy);
XSetCloseDownMode(dpy, DestroyAll);
XKillClient(dpy, selmon->sel->win);
XSync(dpy, False);
XSetErrorHandler(xerror);
XUngrabServer(dpy);
}
}
void
manage(Window w, XWindowAttributes *wa)
{
Client *c, *t = NULL;
int settings_restored;
Window trans = None;
XWindowChanges wc;
c = ecalloc(1, sizeof(Client));
c->win = w;
/* geometry */
c->sfx = c->sfy = c->sfw = c->sfh = -9999;
c->x = c->oldx = wa->x;
c->y = c->oldy = wa->y;
c->w = c->oldw = wa->width;
c->h = c->oldh = wa->height;
c->oldbw = wa->border_width;
settings_restored = restoreclientstate(c);
updatetitle(c);
if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
c->mon = t->mon;
c->tags = t->tags;
c->bw = borderpx;
if (c->x == c->mon->wx && c->y == c->mon->wy)
c->iscentered = 1;
} else {
if (!settings_restored || c->mon == NULL) {
c->mon = selmon;
settings_restored = 0;
}
if (c->x == c->mon->wx && c->y == c->mon->wy)
c->iscentered = 1;
c->bw = borderpx;
if (!settings_restored)
applyrules(c);
}
if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww)
c->x = c->mon->wx + c->mon->ww - WIDTH(c);
if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh)
c->y = c->mon->wy + c->mon->wh - HEIGHT(c);
c->x = MAX(c->x, c->mon->wx);
c->y = MAX(c->y, c->mon->wy);
wc.border_width = c->bw;
XConfigureWindow(dpy, w, CWBorderWidth, &wc);
if (c->isfloating)
XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColFloat].pixel);
else
XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel);
configure(c); /* propagates border_width, if size doesn't change */
updatesizehints(c);
updatewmhints(c);
if (c->iscentered) {
c->sfx = c->x = c->mon->wx + (c->mon->ww - WIDTH(c)) / 2;
c->sfy = c->y = c->mon->wy + (c->mon->wh - HEIGHT(c)) / 2;
}
if (c->sfw == -9999) {
c->sfw = c->w;
c->sfh = c->h;
}
if (getatomprop(c, netatom[NetWMState], XA_ATOM) == netatom[NetWMFullscreen])
setfullscreen(c, 1);
XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
grabbuttons(c, 0);
if (!c->isfloating)
c->isfloating = c->oldstate = trans != None || c->isfixed;
if (c->isfloating) {
XRaiseWindow(dpy, c->win);
XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColFloat].pixel);
}
attachx(c);
attachstack(c);
XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
(unsigned char *) &(c->win), 1);
XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
setclientstate(c, NormalState);
if (c->mon == selmon)
unfocus(selmon->sel, 0, c);
c->mon->sel = c;
arrange(c->mon);
XMapWindow(dpy, c->win);
focus(NULL);
setfloatinghint(c);
}
void
mappingnotify(XEvent *e)
{
XMappingEvent *ev = &e->xmapping;
XRefreshKeyboardMapping(ev);
if (ev->request == MappingKeyboard)
grabkeys();
}
void
maprequest(XEvent *e)
{
static XWindowAttributes wa;
XMapRequestEvent *ev = &e->xmaprequest;
if (!XGetWindowAttributes(dpy, ev->window, &wa) || wa.override_redirect)
return;
if (!wintoclient(ev->window))
manage(ev->window, &wa);
}
void
motionnotify(XEvent *e)
{
Bar *bar;
XMotionEvent *ev = &e->xmotion;
if ((bar = wintobar(ev->window))) {
barhover(e, bar);
return;
}
}
void
movemouse(const Arg *arg)
{
int x, y, ocx, ocy, nx, ny;
Client *c;
Monitor *m;
XEvent ev;
Time lasttime = 0;
if (!(c = selmon->sel))
return;
if (c->isfullscreen && c->fakefullscreen != 1) /* no support moving fullscreen windows by mouse */
return;
restack(selmon);
nx = ocx = c->x;
ny = ocy = c->y;
if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
return;
if (!getrootptr(&x, &y))
return;
ignoreconfigurerequests = 1;
do {
XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
switch(ev.type) {
case ConfigureRequest:
case Expose:
case MapRequest:
handler[ev.type](&ev);
break;
case MotionNotify:
if ((ev.xmotion.time - lasttime) <= (1000 / 60))
continue;
lasttime = ev.xmotion.time;
nx = ocx + (ev.xmotion.x - x);
ny = ocy + (ev.xmotion.y - y);
if (abs(selmon->wx - nx) < snap)
nx = selmon->wx;
else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
nx = selmon->wx + selmon->ww - WIDTH(c);
if (abs(selmon->wy - ny) < snap)
ny = selmon->wy;
else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
ny = selmon->wy + selmon->wh - HEIGHT(c);
if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
&& (abs(nx - c->x) > snap || abs(ny - c->y) > snap)) {
c->sfx = -9999; // disable savefloats when using movemouse
togglefloating(NULL);
}
if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) {
resize(c, nx, ny, c->w, c->h, 1);
}
break;
}
} while (ev.type != ButtonRelease);
XUngrabPointer(dpy, CurrentTime);
if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
if (c->tags & SPTAGMASK) {
c->mon->tagset[c->mon->seltags] ^= (c->tags & SPTAGMASK);
m->tagset[m->seltags] |= (c->tags & SPTAGMASK);
}
sendmon(c, m);
selmon = m;
focus(NULL);
}
/* save last known float coordinates */
if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) {
c->sfx = nx;
c->sfy = ny;
}
ignoreconfigurerequests = 0;
}
Client *
nexttiled(Client *c)
{
for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
return c;
}
int
noborder(Client *c)
{
int monocle_layout = 0;
if (&monocle == c->mon->lt[c->mon->sellt]->arrange)
monocle_layout = 1;
if (!monocle_layout && (nexttiled(c->mon->clients) != c || nexttiled(c->next)))
return 0;
if (c->isfloating)
return 0;
if (!c->mon->lt[c->mon->sellt]->arrange)
return 0;
if (c->fakefullscreen != 1 && c->isfullscreen)
return 0;
return 1;
}
void
pop(Client *c)
{
detach(c);
attach(c);
focus(c);
arrange(c->mon);
}
void
propertynotify(XEvent *e)
{
Client *c;
Window trans;
XPropertyEvent *ev = &e->xproperty;
if ((ev->window == root) && (ev->atom == XA_WM_NAME)) {
if (!fake_signal())
updatestatus();
} else if (ev->state == PropertyDelete) {
return; /* ignore */
} else if ((c = wintoclient(ev->window))) {
switch(ev->atom) {
default: break;
case XA_WM_TRANSIENT_FOR:
if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
(c->isfloating = (wintoclient(trans)) != NULL))
arrange(c->mon);
break;
case XA_WM_NORMAL_HINTS:
c->hintsvalid = 0;
break;
case XA_WM_HINTS:
updatewmhints(c);
if (c->isurgent)
drawbars();
break;
}
if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
updatetitle(c);
if (c == c->mon->sel)
drawbar(c->mon);
}
}
}
void
quit(const Arg *arg)
{
restart = arg->i;
running = 0;
}
Monitor *
recttomon(int x, int y, int w, int h)
{
Monitor *m, *r = selmon;
int a, area = 0;
for (m = mons; m; m = m->next)
if ((a = INTERSECT(x, y, w, h, m)) > area) {
area = a;
r = m;
}
return r;
}
void
resize(Client *c, int x, int y, int w, int h, int interact)
{
if (applysizehints(c, &x, &y, &w, &h, interact))
resizeclient(c, x, y, w, h);
}
void
resizeclient(Client *c, int x, int y, int w, int h)
{
XWindowChanges wc;
c->oldx = c->x; c->x = wc.x = x;
c->oldy = c->y; c->y = wc.y = y;
c->oldw = c->w; c->w = wc.width = w;
c->oldh = c->h; c->h = wc.height = h;
wc.border_width = c->bw;
if (noborder(c)) {
wc.width += c->bw * 2;
wc.height += c->bw * 2;
wc.border_width = 0;
}
XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
configure(c);
XSync(dpy, False);
}
void
resizemouse(const Arg *arg)
{
int ocx, ocy, nw, nh, nx, ny;
Client *c;
Monitor *m;
XEvent ev;
Time lasttime = 0;
if (!(c = selmon->sel))
return;
if (c->isfullscreen && c->fakefullscreen != 1) /* no support resizing fullscreen windows by mouse */
return;
restack(selmon);
nx = ocx = c->x;
ny = ocy = c->y;
nh = c->h;
nw = c->w;
if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
return;
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
ignoreconfigurerequests = 1;
do {
XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
switch(ev.type) {
case ConfigureRequest:
case Expose:
case MapRequest:
handler[ev.type](&ev);
break;
case MotionNotify:
if ((ev.xmotion.time - lasttime) <= (1000 / 60))
continue;
lasttime = ev.xmotion.time;
nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
&& c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
{
if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
&& (abs(nw - c->w) > snap || abs(nh - c->h) > snap)) {
c->sfx = -9999; // disable savefloats when using resizemouse
togglefloating(NULL);
}
}
if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) {
resize(c, nx, ny, nw, nh, 1);
}
break;
}
} while (ev.type != ButtonRelease);
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
XUngrabPointer(dpy, CurrentTime);
while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
if (c->tags & SPTAGMASK) {
c->mon->tagset[c->mon->seltags] ^= (c->tags & SPTAGMASK);
m->tagset[m->seltags] |= (c->tags & SPTAGMASK);
}
sendmon(c, m);
selmon = m;
focus(NULL);
}
/* save last known float dimensions */
if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) {
c->sfx = nx;
c->sfy = ny;
c->sfw = nw;
c->sfh = nh;
}
ignoreconfigurerequests = 0;
}
void
restack(Monitor *m)
{
Client *c, *f = NULL;
XEvent ev;
XWindowChanges wc;
drawbar(m);
if (!m->sel)
return;
if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
XRaiseWindow(dpy, m->sel->win);
if (m->lt[m->sellt]->arrange) {
wc.stack_mode = Below;
if (m->bar) {
wc.sibling = m->bar->win;
} else {
for (f = m->stack; f && (f->isfloating || !ISVISIBLE(f)); f = f->snext); // find first tiled stack client
if (f)
wc.sibling = f->win;
}
for (c = m->stack; c; c = c->snext)
if (!c->isfloating && ISVISIBLE(c) && c != f) {
XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
wc.sibling = c->win;
}
}
XSync(dpy, False);
while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
}
void
run(void)
{
XEvent ev;
XSync(dpy, False);
/* main event loop */
while (running) {
struct pollfd pfd = {
.fd = ConnectionNumber(dpy),
.events = POLLIN,
};
int pending = XPending(dpy) > 0 || poll(&pfd, 1, -1) > 0;
if (!running)
break;
if (!pending)
continue;
XNextEvent(dpy, &ev);
if (handler[ev.type])
handler[ev.type](&ev); /* call handler */
}
}
void
scan(void)
{
unsigned int i, num;
Window d1, d2, *wins = NULL;
XWindowAttributes wa;
if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
for (i = 0; i < num; i++) {
if (!XGetWindowAttributes(dpy, wins[i], &wa)
|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
continue;
if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
manage(wins[i], &wa);
}
for (i = 0; i < num; i++) { /* now the transients */
if (!XGetWindowAttributes(dpy, wins[i], &wa))
continue;
if (XGetTransientForHint(dpy, wins[i], &d1)
&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
manage(wins[i], &wa);
}
XFree(wins);
}
}
void
sendmon(Client *c, Monitor *m)
{
if (c->mon == m)
return;
unfocus(c, 1, NULL);
detach(c);
detachstack(c);
c->mon = m;
if (!(c->tags & SPTAGMASK))
c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
attach(c);
attachstack(c);
arrange(NULL);
focus(NULL);
if (c->switchtag)
c->switchtag = 0;
}
void
setclientstate(Client *c, long state)
{
long data[] = { state, None };
XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
PropModeReplace, (unsigned char *)data, 2);
}
int
sendevent(Client *c, Atom proto)
{
int n;
Atom *protocols;
int exists = 0;
XEvent ev;
if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
while (!exists && n--)
exists = protocols[n] == proto;
XFree(protocols);
}
if (exists) {
ev.type = ClientMessage;
ev.xclient.window = c->win;
ev.xclient.message_type = wmatom[WMProtocols];
ev.xclient.format = 32;
ev.xclient.data.l[0] = proto;
ev.xclient.data.l[1] = CurrentTime;
XSendEvent(dpy, c->win, False, NoEventMask, &ev);
}
return exists;
}
void
setfocus(Client *c)
{
if (!c->neverfocus) {
XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
XChangeProperty(dpy, root, netatom[NetActiveWindow],
XA_WINDOW, 32, PropModeReplace,
(unsigned char *) &(c->win), 1);
}
sendevent(c, wmatom[WMTakeFocus]);
}
void
setfullscreen(Client *c, int fullscreen)
{
XEvent ev;
int savestate = 0, restorestate = 0;
if ((c->fakefullscreen == 0 && fullscreen && !c->isfullscreen) // normal fullscreen
|| (c->fakefullscreen == 2 && fullscreen)) // fake fullscreen --> actual fullscreen
savestate = 1; // go actual fullscreen
else if ((c->fakefullscreen == 0 && !fullscreen && c->isfullscreen) // normal fullscreen exit
|| (c->fakefullscreen >= 2 && !fullscreen)) // fullscreen exit --> fake fullscreen
restorestate = 1; // go back into tiled
/* If leaving fullscreen and the window was previously fake fullscreen (2), then restore
* that while staying in fullscreen. The exception to this is if we are in said state, but
* the client itself disables fullscreen (3) then we let the client go out of fullscreen
* while keeping fake fullscreen enabled (as otherwise there will be a mismatch between the
* client and the window manager's perception of the client's fullscreen state). */
if (c->fakefullscreen == 2 && !fullscreen && c->isfullscreen) {
c->fakefullscreen = 1;
c->isfullscreen = 1;
fullscreen = 1;
} else if (c->fakefullscreen == 3) // client exiting actual fullscreen
c->fakefullscreen = 1;
if (fullscreen != c->isfullscreen) { // only send property change if necessary
if (fullscreen)
XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
else
XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
PropModeReplace, (unsigned char*)0, 0);
}
c->isfullscreen = fullscreen;
/* Some clients, e.g. firefox, will send a client message informing the window manager
* that it is going into fullscreen after receiving the above signal. This has the side
* effect of this function (setfullscreen) sometimes being called twice when toggling
* fullscreen on and off via the window manager as opposed to the application itself.
* To protect against obscure issues where the client settings are stored or restored
* when they are not supposed to we add an additional bit-lock on the old state so that
* settings can only be stored and restored in that precise order. */
if (savestate && !(c->oldstate & (1 << 1))) {
c->oldbw = c->bw;
c->oldstate = c->isfloating | (1 << 1);
c->bw = 0;
c->isfloating = 1;
resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
XRaiseWindow(dpy, c->win);
} else if (restorestate && (c->oldstate & (1 << 1))) {
c->bw = c->oldbw;
c->isfloating = c->oldstate = c->oldstate & 1;
c->x = c->oldx;
c->y = c->oldy;
c->w = c->oldw;
c->h = c->oldh;
resizeclient(c, c->x, c->y, c->w, c->h);
restack(c->mon);
} else
resizeclient(c, c->x, c->y, c->w, c->h);
/* Exception: if the client was in actual fullscreen and we exit out to fake fullscreen
* mode, then the focus would sometimes drift to whichever window is under the mouse cursor
* at the time. To avoid this we ask X for all EnterNotify events and just ignore them.
*/
if (!c->isfullscreen)
while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
}
void
setlayout(const Arg *arg)
{
if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt]) {
selmon->pertag->sellts[selmon->pertag->curtag] ^= 1;
selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
}
if (arg && arg->v)
selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt] = (Layout *)arg->v;
selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
if (selmon->sel)
arrange(selmon);
else
drawbar(selmon);
}
/* arg > 1.0 will set mfact absolutely */
void
setmfact(const Arg *arg)
{
float f;
if (!arg || !selmon->lt[selmon->sellt]->arrange)
return;
f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
if (f < 0.05 || f > 0.95)
return;
selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag] = f;
arrange(selmon);
}
void
setup(void)
{
int i;
XSetWindowAttributes wa;
Atom utf8string;
/* clean up any zombies immediately */
sigchld(0);
signal(SIGHUP, sighup);
signal(SIGTERM, sigterm);
/* the one line of bloat that would have saved a lot of time for a lot of people */
putenv("_JAVA_AWT_WM_NONREPARENTING=1");
/* init screen */
screen = DefaultScreen(dpy);
sw = DisplayWidth(dpy, screen);
sh = DisplayHeight(dpy, screen);
root = RootWindow(dpy, screen);
drw = drw_create(dpy, screen, root, sw, sh);
if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
die("no fonts could be loaded.");
lrpad = drw->fonts->h + horizpadbar;
bh = drw->fonts->h + vertpadbar;
updategeom();
/* init atoms */
utf8string = XInternAtom(dpy, "UTF8_STRING", False);
wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
clientatom[ClientFields] = XInternAtom(dpy, "_DWM_CLIENT_FIELDS", False);
clientatom[ClientTags] = XInternAtom(dpy, "_DWM_CLIENT_TAGS", False);
netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
netatom[NetDesktopViewport] = XInternAtom(dpy, "_NET_DESKTOP_VIEWPORT", False);
netatom[NetNumberOfDesktops] = XInternAtom(dpy, "_NET_NUMBER_OF_DESKTOPS", False);
netatom[NetCurrentDesktop] = XInternAtom(dpy, "_NET_CURRENT_DESKTOP", False);
netatom[NetDesktopNames] = XInternAtom(dpy, "_NET_DESKTOP_NAMES", False);
netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
/* init cursors */
cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
cursor[CurResize] = drw_cur_create(drw, XC_sizing);
cursor[CurMove] = drw_cur_create(drw, XC_fleur);
/* init appearance */
scheme = ecalloc(LENGTH(colors) + 1, sizeof(Clr *));
scheme[LENGTH(colors)] = drw_scm_create(drw, colors[0], ColCount);
for (i = 0; i < LENGTH(colors); i++)
scheme[i] = drw_scm_create(drw, colors[i], ColCount);
updatebars();
updatestatus();
/* supporting window for NetWMCheck */
wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
PropModeReplace, (unsigned char *) &wmcheckwin, 1);
XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
PropModeReplace, (unsigned char *) "dwm", 3);
XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
PropModeReplace, (unsigned char *) &wmcheckwin, 1);
/* EWMH support per view */
XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
PropModeReplace, (unsigned char *) netatom, NetLast);
setnumdesktops();
setcurrentdesktop();
setdesktopnames();
setviewport();
XDeleteProperty(dpy, root, netatom[NetClientList]);
/* select events */
wa.cursor = cursor[CurNormal]->cursor;
wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
|ButtonPressMask|PointerMotionMask|EnterWindowMask
|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
XSelectInput(dpy, root, wa.event_mask);
grabkeys();
focus(NULL);
}
void
seturgent(Client *c, int urg)
{
XWMHints *wmh;
c->isurgent = urg;
if (!(wmh = XGetWMHints(dpy, c->win)))
return;
wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
XSetWMHints(dpy, c->win, wmh);
XFree(wmh);
}
void
showhide(Client *c)
{
if (!c)
return;
if (ISVISIBLE(c)) {
if (
(c->tags & SPTAGMASK) &&
c->isfloating &&
(
c->x < c->mon->mx ||
c->x > c->mon->mx + c->mon->mw ||
c->y < c->mon->my ||
c->y > c->mon->my + c->mon->mh
)
) {
c->x = c->mon->wx + (c->mon->ww / 2 - WIDTH(c) / 2);
c->y = c->mon->wy + (c->mon->wh / 2 - HEIGHT(c) / 2);
}
/* show clients top down */
if (!c->mon->lt[c->mon->sellt]->arrange && c->sfx != -9999 && !c->isfullscreen) {
XMoveResizeWindow(dpy, c->win, c->sfx, c->sfy, c->sfw, c->sfh);
resize(c, c->sfx, c->sfy, c->sfw, c->sfh, 0);
showhide(c->snext);
return;
}
XMoveWindow(dpy, c->win, c->x, c->y);
if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating)
&& !c->isfullscreen
)
resize(c, c->x, c->y, c->w, c->h, 0);
showhide(c->snext);
} else {
/* hide clients bottom up */
showhide(c->snext);
XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
}
}
void
sigchld(int unused)
{
pid_t pid;
if (signal(SIGCHLD, sigchld) == SIG_ERR)
die("can't install SIGCHLD handler:");
while (0 < (pid = waitpid(-1, NULL, WNOHANG))) {
pid_t *p, *lim;
if (!(p = autostart_pids))
continue;
lim = &p[autostart_len];
for (; p < lim; p++) {
if (*p == pid) {
*p = -1;
break;
}
}
}
}
void
spawn(const Arg *arg)
{
struct sigaction sa;
if (fork() == 0)
{
if (dpy)
close(ConnectionNumber(dpy));
setsid();
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = SIG_DFL;
sigaction(SIGCHLD, &sa, NULL);
execvp(((char **)arg->v)[0], (char **)arg->v);
die("dwm: execvp '%s' failed:", ((char **)arg->v)[0]);
}
}
void
tag(const Arg *arg)
{
if (selmon->sel && arg->ui & TAGMASK) {
selmon->sel->tags = arg->ui & TAGMASK;
if (selmon->sel->switchtag)
selmon->sel->switchtag = 0;
arrange(selmon);
focus(NULL);
}
}
void
tagmon(const Arg *arg)
{
Client *c = selmon->sel;
Monitor *dest;
int restored;
if (!c || !mons->next)
return;
dest = dirtomon(arg->i);
savewindowfloatposition(c, c->mon);
restored = restorewindowfloatposition(c, dest);
if (restored && (!dest->lt[dest->sellt]->arrange || c->isfloating)) {
XMoveResizeWindow(dpy, c->win, c->sfx, c->sfy, c->sfw, c->sfh);
resize(c, c->sfx, c->sfy, c->sfw, c->sfh, 1);
}
sendmon(c, dest);
}
void
togglebar(const Arg *arg)
{
Bar *bar;
selmon->showbar = (selmon->showbar == 2 ? 1 : !selmon->showbar);
updatebarpos(selmon);
for (bar = selmon->bar; bar; bar = bar->next)
XMoveResizeWindow(dpy, bar->win, bar->bx, bar->by, bar->bw, bar->bh);
arrange(selmon);
}
void
togglefloating(const Arg *arg)
{
Client *c = selmon->sel;
if (arg && arg->v)
c = (Client*)arg->v;
if (!c)
return;
if (c->isfullscreen && c->fakefullscreen != 1) /* no support for fullscreen windows */
return;
c->isfloating = !c->isfloating || c->isfixed;
if (c->isfloating)
XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColFloat].pixel);
else
XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel);
if (c->isfloating) {
if (c->sfx != -9999) {
/* restore last known float dimensions */
resize(c, c->sfx, c->sfy, c->sfw, c->sfh, 0);
} else
resize(c, c->x, c->y, c->w, c->h, 0);
} else {
/* save last known float dimensions */
c->sfx = c->x;
c->sfy = c->y;
c->sfw = c->w;
c->sfh = c->h;
}
arrange(c->mon);
setfloatinghint(c);
}
void
toggletag(const Arg *arg)
{
unsigned int newtags;
if (!selmon->sel)
return;
newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
if (newtags) {
selmon->sel->tags = newtags;
arrange(selmon);
focus(NULL);
}
updatecurrentdesktop();
}
void
toggleview(const Arg *arg)
{
unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);;
int i;
if (newtagset) {
selmon->tagset[selmon->seltags] = newtagset;
if (newtagset == ~SPTAGMASK)
{
selmon->pertag->curtag = 0;
}
/* test if the user did not select the same tag */
if (!(newtagset & 1 << (selmon->pertag->curtag - 1))) {
for (i = 0; !(newtagset & 1 << i); i++) ;
selmon->pertag->curtag = i + 1;
}
/* apply settings for this view */
selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
arrange(selmon);
focus(NULL);
}
updatecurrentdesktop();
}
void
unfocus(Client *c, int setfocus, Client *nextfocus)
{
if (!c)
return;
grabbuttons(c, 0);
if (c->isfloating)
XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColFloat].pixel);
else
XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
if (setfocus) {
XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
}
}
void
unmanage(Client *c, int destroyed)
{
Monitor *m;
unsigned int switchtag = c->switchtag;
XWindowChanges wc;
m = c->mon;
detach(c);
detachstack(c);
if (!destroyed) {
wc.border_width = c->oldbw;
XGrabServer(dpy); /* avoid race conditions */
XSetErrorHandler(xerrordummy);
XSelectInput(dpy, c->win, NoEventMask);
XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
setclientstate(c, WithdrawnState);
XSync(dpy, False);
XSetErrorHandler(xerror);
XUngrabServer(dpy);
}
free(c);
arrange(m);
focus(NULL);
updateclientlist();
if (switchtag && ((switchtag & TAGMASK) != selmon->tagset[selmon->seltags]))
view(&((Arg) { .ui = switchtag }));
}
void
unmapnotify(XEvent *e)
{
Client *c;
XUnmapEvent *ev = &e->xunmap;
if ((c = wintoclient(ev->window))) {
if (ev->send_event)
setclientstate(c, WithdrawnState);
else
unmanage(c, 0);
}
}
void
updatebars(void)
{
Bar *bar;
Monitor *m;
XSetWindowAttributes wa = {
.override_redirect = True,
.background_pixmap = ParentRelative,
.event_mask = ButtonPressMask|ExposureMask
};
XClassHint ch = {"dwm", "dwm"};
for (m = mons; m; m = m->next) {
for (bar = m->bar; bar; bar = bar->next) {
if (bar->external)
continue;
if (!bar->win) {
bar->win = XCreateWindow(dpy, root, bar->bx, bar->by, bar->bw, bar->bh, 0, DefaultDepth(dpy, screen),
CopyFromParent, DefaultVisual(dpy, screen),
CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
XDefineCursor(dpy, bar->win, cursor[CurNormal]->cursor);
XMapRaised(dpy, bar->win);
XSetClassHint(dpy, bar->win, &ch);
}
}
}
}
void
updatebarpos(Monitor *m)
{
m->wx = m->mx;
m->wy = m->my;
m->ww = m->mw;
m->wh = m->mh;
Bar *bar;
int y_pad = 0;
int x_pad = 0;
for (bar = m->bar; bar; bar = bar->next) {
bar->bx = m->wx + x_pad;
bar->bw = m->ww - 2 * x_pad;
}
for (bar = m->bar; bar; bar = bar->next)
if (!m->showbar || !bar->showbar)
bar->by = -bar->bh - y_pad;
if (!m->showbar)
return;
for (bar = m->bar; bar; bar = bar->next) {
if (!bar->showbar)
continue;
if (bar->topbar)
m->wy = m->wy + bar->bh + y_pad;
m->wh -= y_pad + bar->bh;
bar->by = (bar->topbar ? m->wy - bar->bh : m->wy + m->wh);
}
}
void
updateclientlist()
{
Client *c;
Monitor *m;
XDeleteProperty(dpy, root, netatom[NetClientList]);
for (m = mons; m; m = m->next)
for (c = m->clients; c; c = c->next)
XChangeProperty(dpy, root, netatom[NetClientList],
XA_WINDOW, 32, PropModeAppend,
(unsigned char *) &(c->win), 1);
}
int
updategeom(void)
{
int dirty = 0;
#ifdef XINERAMA
if (XineramaIsActive(dpy)) {
int i, j, n, nn;
Client *c;
Monitor *m;
XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
XineramaScreenInfo *unique = NULL;
for (n = 0, m = mons; m; m = m->next, n++);
/* only consider unique geometries as separate screens */
unique = ecalloc(nn, sizeof(XineramaScreenInfo));
for (i = 0, j = 0; i < nn; i++)
if (isuniquegeom(unique, j, &info[i]))
memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
XFree(info);
nn = j;
/* new monitors if nn > n */
for (i = n; i < nn; i++) {
for (m = mons; m && m->next; m = m->next);
if (m)
m->next = createmon();
else
mons = createmon();
}
for (i = 0, m = mons; i < nn && m; m = m->next, i++)
if (i >= n
|| unique[i].x_org != m->mx || unique[i].y_org != m->my
|| unique[i].width != m->mw || unique[i].height != m->mh)
{
dirty = 1;
m->num = i;
m->mx = m->wx = unique[i].x_org;
m->my = m->wy = unique[i].y_org;
m->mw = m->ww = unique[i].width;
m->mh = m->wh = unique[i].height;
updatebarpos(m);
}
/* removed monitors if n > nn */
for (i = nn; i < n; i++) {
for (m = mons; m && m->next; m = m->next);
while ((c = m->clients)) {
dirty = 1;
m->clients = c->next;
detachstack(c);
c->mon = mons;
attach(c);
attachstack(c);
}
if (m == selmon)
selmon = mons;
cleanupmon(m);
}
free(unique);
} else
#endif /* XINERAMA */
{ /* default monitor setup */
if (!mons)
mons = createmon();
if (mons->mw != sw || mons->mh != sh) {
dirty = 1;
mons->mw = mons->ww = sw;
mons->mh = mons->wh = sh;
updatebarpos(mons);
}
}
if (dirty) {
selmon = mons;
selmon = wintomon(root);
}
return dirty;
}
void
updatenumlockmask(void)
{
unsigned int i, j;
XModifierKeymap *modmap;
numlockmask = 0;
modmap = XGetModifierMapping(dpy);
for (i = 0; i < 8; i++)
for (j = 0; j < modmap->max_keypermod; j++)
if (modmap->modifiermap[i * modmap->max_keypermod + j]
== XKeysymToKeycode(dpy, XK_Num_Lock))
numlockmask = (1 << i);
XFreeModifiermap(modmap);
}
void
updatesizehints(Client *c)
{
long msize;
XSizeHints size;
if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
/* size is uninitialized, ensure that size.flags aren't used */
size.flags = PSize;
if (size.flags & PBaseSize) {
c->basew = size.base_width;
c->baseh = size.base_height;
} else if (size.flags & PMinSize) {
c->basew = size.min_width;
c->baseh = size.min_height;
} else
c->basew = c->baseh = 0;
if (size.flags & PResizeInc) {
c->incw = size.width_inc;
c->inch = size.height_inc;
} else
c->incw = c->inch = 0;
if (size.flags & PMaxSize) {
c->maxw = size.max_width;
c->maxh = size.max_height;
} else
c->maxw = c->maxh = 0;
if (size.flags & PMinSize) {
c->minw = size.min_width;
c->minh = size.min_height;
} else if (size.flags & PBaseSize) {
c->minw = size.base_width;
c->minh = size.base_height;
} else
c->minw = c->minh = 0;
if (size.flags & PAspect) {
c->mina = (float)size.min_aspect.y / size.min_aspect.x;
c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
} else
c->maxa = c->mina = 0.0;
c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
c->hintsvalid = 1;
}
void
updatestatus(void)
{
Monitor *m;
if (!gettextprop(root, XA_WM_NAME, rawstext, sizeof(rawstext)))
strcpy(stext, "dwm-"VERSION);
else
copyvalidchars(stext, rawstext);
for (m = mons; m; m = m->next)
drawbar(m);
}
void
updatetitle(Client *c)
{
if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
if (c->name[0] == '\0') /* hack to mark broken clients */
strcpy(c->name, broken);
}
void
updatewmhints(Client *c)
{
XWMHints *wmh;
if ((wmh = XGetWMHints(dpy, c->win))) {
if (c == selmon->sel && wmh->flags & XUrgencyHint) {
wmh->flags &= ~XUrgencyHint;
XSetWMHints(dpy, c->win, wmh);
} else
c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
if (c->isurgent) {
if (c->isfloating)
XSetWindowBorder(dpy, c->win, scheme[SchemeUrg][ColFloat].pixel);
else
XSetWindowBorder(dpy, c->win, scheme[SchemeUrg][ColBorder].pixel);
}
if (wmh->flags & InputHint)
c->neverfocus = !wmh->input;
else
c->neverfocus = 0;
XFree(wmh);
}
}
void
view(const Arg *arg)
{
if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
{
view(&((Arg) { .ui = 0 }));
return;
}
selmon->seltags ^= 1; /* toggle sel tagset */
if (arg->ui & TAGMASK)
selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
pertagview(arg);
arrange(selmon);
focus(NULL);
updatecurrentdesktop();
}
Client *
wintoclient(Window w)
{
Client *c;
Monitor *m;
for (m = mons; m; m = m->next)
for (c = m->clients; c; c = c->next)
if (c->win == w)
return c;
return NULL;
}
Monitor *
wintomon(Window w)
{
int x, y;
Client *c;
Monitor *m;
Bar *bar;
if (w == root && getrootptr(&x, &y))
return recttomon(x, y, 1, 1);
for (m = mons; m; m = m->next)
for (bar = m->bar; bar; bar = bar->next)
if (w == bar->win)
return m;
if ((c = wintoclient(w)))
return c->mon;
return selmon;
}
/* There's no way to check accesses to destroyed windows, thus those cases are
* ignored (especially on UnmapNotify's). Other types of errors call Xlibs
* default error handler, which may call exit. */
int
xerror(Display *dpy, XErrorEvent *ee)
{
if (ee->error_code == BadWindow
|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
return 0;
fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
ee->request_code, ee->error_code);
return xerrorxlib(dpy, ee); /* may call exit */
}
int
xerrordummy(Display *dpy, XErrorEvent *ee)
{
return 0;
}
/* Startup Error handler to check if another window manager
* is already running. */
int
xerrorstart(Display *dpy, XErrorEvent *ee)
{
die("dwm: another window manager is already running");
return -1;
}
void
zoom(const Arg *arg)
{
Client *c = selmon->sel;
if (arg && arg->v)
c = (Client*)arg->v;
if (!c)
return;
if (!c->mon->lt[c->mon->sellt]->arrange || !c || c->isfloating)
return;
if (c == nexttiled(selmon->clients) && !(c = nexttiled(c->next)))
return;
pop(c);
}
int
main(int argc, char *argv[])
{
if (argc == 2 && !strcmp("-v", argv[1]))
die("dwm-"VERSION);
else if (argc != 1)
die("usage: dwm [-v]");
if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
fputs("warning: no locale support\n", stderr);
if (!(dpy = XOpenDisplay(NULL)))
die("dwm: cannot open display");
checkotherwm();
XrmInitialize();
loadxrdb();
autostart_exec();
setup();
#ifdef __OpenBSD__
if (pledge("stdio rpath proc exec", NULL) == -1)
die("pledge");
#endif /* __OpenBSD__ */
scan();
run();
cleanup();
XCloseDisplay(dpy);
if (restart)
execvp(argv[0], argv);
return EXIT_SUCCESS;
}

View File

@ -1,22 +0,0 @@
void
attachx(Client *c)
{
Client *at;
if (c->idx > 0) { /* then the client has a designated position in the client list */
for (at = c->mon->clients; at; at = at->next) {
if (c->idx < at->idx) {
c->next = at;
c->mon->clients = c;
return;
} else if (at->idx <= c->idx && (!at->next || c->idx <= at->next->idx)) {
c->next = at->next;
at->next = c;
return;
}
}
}
attach(c); // master (default)
}

View File

@ -1,2 +0,0 @@
static void attachx(Client *c);

View File

@ -1,39 +0,0 @@
void
barhover(XEvent *e, Bar *bar)
{
const BarRule *br;
Monitor *m = bar->mon;
XMotionEvent *ev = &e->xmotion;
BarArg barg = { 0, 0, 0, 0 };
int r;
for (r = 0; r < LENGTH(barrules); r++) {
br = &barrules[r];
if (br->bar != bar->idx || (br->monitor == 'A' && m != selmon) || br->hoverfunc == NULL)
continue;
if (br->monitor != 'A' && br->monitor != -1 && br->monitor != bar->mon->num)
continue;
if (bar->x[r] > ev->x || ev->x > bar->x[r] + bar->w[r])
continue;
barg.x = ev->x - bar->x[r];
barg.y = ev->y - bar->borderpx;
barg.w = bar->w[r];
barg.h = bar->bh - 2 * bar->borderpx;
br->hoverfunc(bar, &barg, ev);
break;
}
}
Bar *
wintobar(Window win)
{
Monitor *m;
Bar *bar;
for (m = mons; m; m = m->next)
for (bar = m->bar; bar; bar = bar->next)
if (bar->win == win)
return bar;
return NULL;
}

View File

@ -1,2 +0,0 @@
static void barhover(XEvent *e, Bar *bar);
static Bar *wintobar(Window win);

View File

@ -1,41 +0,0 @@
static int statussig;
pid_t statuspid = -1;
pid_t
getstatusbarpid()
{
char buf[32], *str = buf, *c;
FILE *fp;
if (statuspid > 0) {
snprintf(buf, sizeof(buf), "/proc/%u/cmdline", statuspid);
if ((fp = fopen(buf, "r"))) {
fgets(buf, sizeof(buf), fp);
while ((c = strchr(str, '/')))
str = c + 1;
fclose(fp);
if (!strcmp(str, STATUSBAR))
return statuspid;
}
}
if (!(fp = popen("pgrep -o "STATUSBAR, "r")))
return -1;
fgets(buf, sizeof(buf), fp);
pclose(fp);
return strtol(buf, NULL, 10);
}
void
sigstatusbar(const Arg *arg)
{
union sigval sv;
if (!statussig)
return;
if ((statuspid = getstatusbarpid()) <= 0)
return;
sv.sival_int = arg->i;
sigqueue(statuspid, SIGRTMIN+statussig, sv);
}

View File

@ -1,3 +0,0 @@
static int getstatusbarpid();
static void sigstatusbar(const Arg *arg);

View File

@ -1,52 +0,0 @@
void
setcurrentdesktop(void)
{
long data[] = { 0 };
XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}
void
setdesktopnames(void)
{
int i;
XTextProperty text;
char *tags[NUMTAGS];
for (i = 0; i < NUMTAGS; i++)
tags[i] = tagicon(selmon, i);
Xutf8TextListToTextProperty(dpy, tags, NUMTAGS, XUTF8StringStyle, &text);
XSetTextProperty(dpy, root, &text, netatom[NetDesktopNames]);
}
void
setfloatinghint(Client *c)
{
Atom target = XInternAtom(dpy, "_IS_FLOATING", 0);
unsigned int floating[1] = {c->isfloating};
XChangeProperty(dpy, c->win, target, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)floating, 1);
}
void
setnumdesktops(void)
{
long data[] = { NUMTAGS };
XChangeProperty(dpy, root, netatom[NetNumberOfDesktops], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}
void
setviewport(void)
{
long data[] = { 0, 0 };
XChangeProperty(dpy, root, netatom[NetDesktopViewport], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 2);
}
void
updatecurrentdesktop(void)
{
long rawdata[] = { selmon->tagset[selmon->seltags] };
int i = 0;
while (*rawdata >> (i + 1)) {
i++;
}
long data[] = { i };
XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}

View File

@ -1,7 +0,0 @@
static void setcurrentdesktop(void);
static void setdesktopnames(void);
static void setfloatinghint(Client *c);
static void setnumdesktops(void);
static void setviewport(void);
static void updatecurrentdesktop(void);

View File

@ -1,36 +0,0 @@
void
holdbar(const Arg *arg)
{
if (selmon->showbar)
return;
Bar *bar;
selmon->showbar = 2;
updatebarpos(selmon);
for (bar = selmon->bar; bar; bar = bar->next)
XMoveResizeWindow(dpy, bar->win, bar->bx, bar->by, bar->bw, bar->bh);
drawbar(selmon);
}
void
keyrelease(XEvent *e)
{
Bar *bar;
if (XEventsQueued(dpy, QueuedAfterReading)) {
XEvent ne;
XPeekEvent(dpy, &ne);
if (ne.type == KeyPress && ne.xkey.time == e->xkey.time &&
ne.xkey.keycode == e->xkey.keycode) {
XNextEvent(dpy, &ne);
return;
}
}
if (e->xkey.keycode == XKeysymToKeycode(dpy, HOLDKEY) && selmon->showbar == 2) {
selmon->showbar = 0;
updatebarpos(selmon);
for (bar = selmon->bar; bar; bar = bar->next)
XMoveResizeWindow(dpy, bar->win, bar->bx, bar->by, bar->bw, bar->bh);
arrange(selmon);
}
}

View File

@ -1,3 +0,0 @@
static void keyrelease(XEvent *e);
static void holdbar(const Arg *arg);

View File

@ -1,109 +0,0 @@
/* Indicator properties, you can override these in your config.h if you want. */
#ifndef TAGSINDICATOR
#define TAGSINDICATOR 1 // 0 = off, 1 = on if >1 client/view tag, 2 = always on
#endif
#ifndef TAGSPX
#define TAGSPX 5 // # pixels for tag grid boxes
#endif
#ifndef TAGSROWS
#define TAGSROWS 3 // # rows in tag grid (9 tags, e.g. 3x3)
#endif
void
drawindicator(Monitor *m, Client *c, unsigned int occ, int x, int y, int w, int h, unsigned int tag, int filled, int invert, int type)
{
int i, boxw, boxs, indn = 0;
if (!(occ & 1 << tag) || type == INDICATOR_NONE)
return;
boxs = drw->fonts->h / 9;
boxw = drw->fonts->h / 6 + 2;
if (filled == -1)
filled = m == selmon && m->sel && m->sel->tags & 1 << tag;
switch (type) {
default:
case INDICATOR_TOP_LEFT_SQUARE:
drw_rect(drw, x + boxs, y + boxs, boxw, boxw, filled, invert);
break;
case INDICATOR_TOP_LEFT_LARGER_SQUARE:
drw_rect(drw, x + boxs + 2, y + boxs+1, boxw+1, boxw+1, filled, invert);
break;
case INDICATOR_TOP_BAR:
drw_rect(drw, x + boxw, y, w - ( 2 * boxw + 1), boxw/2, filled, invert);
break;
case INDICATOR_TOP_BAR_SLIM:
drw_rect(drw, x + boxw, y, w - ( 2 * boxw + 1), 1, 0, invert);
break;
case INDICATOR_BOTTOM_BAR:
drw_rect(drw, x + boxw, y + h - boxw/2, w - ( 2 * boxw + 1), boxw/2, filled, invert);
break;
case INDICATOR_BOTTOM_BAR_SLIM:
drw_rect(drw, x + boxw, y + h - 1, w - ( 2 * boxw + 1), 1, 0, invert);
break;
case INDICATOR_BOX:
drw_rect(drw, x + boxw, y, w - 2 * boxw, h, 0, invert);
break;
case INDICATOR_BOX_WIDER:
drw_rect(drw, x + boxw/2, y, w - boxw, h, 0, invert);
break;
case INDICATOR_BOX_FULL:
drw_rect(drw, x, y, w - 2, h, 0, invert);
break;
case INDICATOR_CLIENT_DOTS:
for (c = m->clients; c; c = c->next) {
if (c->tags & (1 << tag)) {
drw_rect(drw, x, 1 + (indn * 2), m->sel == c ? 6 : 1, 1, 1, invert);
indn++;
}
if (h <= 1 + (indn * 2)) {
indn = 0;
x += 2;
}
}
break;
case INDICATOR_RIGHT_TAGS:
if (!c)
break;
for (i = 0; i < NUMTAGS; i++) {
drw_rect(drw,
( x + w - 2 - ((NUMTAGS / TAGSROWS) * TAGSPX)
- (i % (NUMTAGS/TAGSROWS)) + ((i % (NUMTAGS / TAGSROWS)) * TAGSPX)
),
( y + 2 + ((i / (NUMTAGS/TAGSROWS)) * TAGSPX)
- ((i / (NUMTAGS/TAGSROWS)))
),
TAGSPX, TAGSPX, (c->tags >> i) & 1, 0
);
}
break;
case INDICATOR_PLUS_AND_LARGER_SQUARE:
boxs += 2;
boxw += 2;
/* falls through */
case INDICATOR_PLUS_AND_SQUARE:
drw_rect(drw, x + boxs, y + boxs, boxw % 2 ? boxw : boxw + 1, boxw % 2 ? boxw : boxw + 1, filled, invert);
/* falls through */
case INDICATOR_PLUS:
if (!(boxw % 2))
boxw += 1;
drw_rect(drw, x + boxs + boxw / 2, y + boxs, 1, boxw, filled, invert); // |
drw_rect(drw, x + boxs, y + boxs + boxw / 2, boxw + 1, 1, filled, invert); //
break;
}
}
void
drawstateindicator(Monitor *m, Client *c, unsigned int occ, int x, int y, int w, int h, unsigned int tag, int filled, int invert)
{
if (c->fakefullscreen && c->isfloating)
drawindicator(m, c, occ, x, y, w, h, tag, filled, invert, floatfakefsindicatortype);
else if (c->fakefullscreen)
drawindicator(m, c, occ, x, y, w, h, tag, filled, invert, fakefsindicatortype);
else
if (c->isfloating)
drawindicator(m, c, occ, x, y, w, h, tag, filled, invert, floatindicatortype);
else
drawindicator(m, c, occ, x, y, w, h, tag, filled, invert, tiledindicatortype);
}

View File

@ -1,21 +0,0 @@
enum {
INDICATOR_NONE,
INDICATOR_TOP_LEFT_SQUARE,
INDICATOR_TOP_LEFT_LARGER_SQUARE,
INDICATOR_TOP_BAR,
INDICATOR_TOP_BAR_SLIM,
INDICATOR_BOTTOM_BAR,
INDICATOR_BOTTOM_BAR_SLIM,
INDICATOR_BOX,
INDICATOR_BOX_WIDER,
INDICATOR_BOX_FULL,
INDICATOR_CLIENT_DOTS,
INDICATOR_RIGHT_TAGS,
INDICATOR_PLUS,
INDICATOR_PLUS_AND_SQUARE,
INDICATOR_PLUS_AND_LARGER_SQUARE,
};
static void drawindicator(Monitor *m, Client *c, unsigned int occ, int x, int y, int w, int h, unsigned int tag, int filled, int invert, int type);
static void drawstateindicator(Monitor *m, Client *c, unsigned int occ, int x, int y, int w, int h, unsigned int tag, int filled, int invert);

View File

@ -1,18 +0,0 @@
int
width_ltsymbol(Bar *bar, BarArg *a)
{
return TEXTW(bar->mon->ltsymbol);
}
int
draw_ltsymbol(Bar *bar, BarArg *a)
{
return drw_text(drw, a->x, a->y, a->w, a->h, lrpad / 2, bar->mon->ltsymbol, 0, False);
}
int
click_ltsymbol(Bar *bar, Arg *arg, BarArg *a)
{
return ClkLtSymbol;
}

View File

@ -1,4 +0,0 @@
static int width_ltsymbol(Bar *bar, BarArg *a);
static int draw_ltsymbol(Bar *bar, BarArg *a);
static int click_ltsymbol(Bar *bar, Arg *arg, BarArg *a);

View File

@ -1,18 +0,0 @@
int
width_status(Bar *bar, BarArg *a)
{
return TEXTWM(stext);
}
int
draw_status(Bar *bar, BarArg *a)
{
return drw_text(drw, a->x, a->y, a->w, a->h, lrpad / 2, stext, 0, True);
}
int
click_status(Bar *bar, Arg *arg, BarArg *a)
{
return ClkStatusText;
}

View File

@ -1,4 +0,0 @@
static int width_status(Bar *bar, BarArg *a);
static int draw_status(Bar *bar, BarArg *a);
static int click_status(Bar *bar, Arg *arg, BarArg *a);

View File

@ -1,190 +0,0 @@
static char termcol0[] = "#000000"; /* black */
static char termcol1[] = "#ff0000"; /* red */
static char termcol2[] = "#33ff00"; /* green */
static char termcol3[] = "#ff0099"; /* yellow */
static char termcol4[] = "#0066ff"; /* blue */
static char termcol5[] = "#cc00ff"; /* magenta */
static char termcol6[] = "#00ffff"; /* cyan */
static char termcol7[] = "#d0d0d0"; /* white */
static char termcol8[] = "#808080"; /* black */
static char termcol9[] = "#ff0000"; /* red */
static char termcol10[] = "#33ff00"; /* green */
static char termcol11[] = "#ff0099"; /* yellow */
static char termcol12[] = "#0066ff"; /* blue */
static char termcol13[] = "#cc00ff"; /* magenta */
static char termcol14[] = "#00ffff"; /* cyan */
static char termcol15[] = "#ffffff"; /* white */
static char *termcolor[] = {
termcol0, termcol1, termcol2, termcol3, termcol4, termcol5, termcol6, termcol7,
termcol8, termcol9, termcol10, termcol11, termcol12, termcol13, termcol14, termcol15,
};
int
width_status2d(Bar *bar, BarArg *a)
{
int width;
width = status2dtextlength(rawstext);
return width ? width + lrpad : 0;
}
int
draw_status2d(Bar *bar, BarArg *a)
{
return drawstatusbar(a, rawstext);
}
int
drawstatusbar(BarArg *a, char* stext)
{
int i, w, len;
int x = a->x;
int y = a->y;
short isCode = 0;
char *text;
char *p;
Clr oldbg, oldfg;
len = strlen(stext);
if (!(text = (char*) malloc(sizeof(char)*(len + 1))))
die("malloc");
p = text;
copyvalidchars(text, stext);
x += lrpad / 2;
drw_setscheme(drw, scheme[LENGTH(colors)]);
drw->scheme[ColFg] = scheme[SchemeNorm][ColFg];
drw->scheme[ColBg] = scheme[SchemeNorm][ColBg];
/* process status text */
i = -1;
while (text[++i]) {
if (text[i] == '^' && !isCode) {
isCode = 1;
text[i] = '\0';
w = TEXTWM(text) - lrpad;
drw_text(drw, x, y, w, bh, 0, text, 0, True);
x += w;
/* process code */
while (text[++i] != '^') {
if (text[i] == 'c') {
char buf[8];
if (i + 7 >= len) {
i += 7;
len = 0;
break;
}
memcpy(buf, (char*)text+i+1, 7);
buf[7] = '\0';
drw_clr_create(drw, &drw->scheme[ColFg], buf);
i += 7;
} else if (text[i] == 'b') {
char buf[8];
if (i + 7 >= len) {
i += 7;
len = 0;
break;
}
memcpy(buf, (char*)text+i+1, 7);
buf[7] = '\0';
drw_clr_create(drw, &drw->scheme[ColBg], buf);
i += 7;
} else if (text[i] == 'C') {
int c = atoi(text + ++i) % 16;
drw_clr_create(drw, &drw->scheme[ColFg], termcolor[c]);
} else if (text[i] == 'B') {
int c = atoi(text + ++i) % 16;
drw_clr_create(drw, &drw->scheme[ColBg], termcolor[c]);
} else if (text[i] == 'd') {
drw->scheme[ColFg] = scheme[SchemeNorm][ColFg];
drw->scheme[ColBg] = scheme[SchemeNorm][ColBg];
} else if (text[i] == 'w') {
Clr swp;
swp = drw->scheme[ColFg];
drw->scheme[ColFg] = drw->scheme[ColBg];
drw->scheme[ColBg] = swp;
} else if (text[i] == 'v') {
oldfg = drw->scheme[ColFg];
oldbg = drw->scheme[ColBg];
} else if (text[i] == 't') {
drw->scheme[ColFg] = oldfg;
drw->scheme[ColBg] = oldbg;
} else if (text[i] == 'r') {
int rx = atoi(text + ++i);
while (text[++i] != ',');
int ry = atoi(text + ++i);
while (text[++i] != ',');
int rw = atoi(text + ++i);
while (text[++i] != ',');
int rh = atoi(text + ++i);
if (ry < 0)
ry = 0;
if (rx < 0)
rx = 0;
drw_rect(drw, rx + x, y + ry, rw, rh, 1, 0);
} else if (text[i] == 'f') {
x += atoi(text + ++i);
}
}
text = text + i + 1;
len -= i + 1;
i = -1;
isCode = 0;
if (len <= 0)
break;
}
}
if (!isCode && len > 0) {
w = TEXTWM(text) - lrpad;
drw_text(drw, x, y, w, bh, 0, text, 0, True);
x += w;
}
free(p);
drw_setscheme(drw, scheme[SchemeNorm]);
return 1;
}
int
status2dtextlength(char* stext)
{
int i, w, len;
short isCode = 0;
char *text;
char *p;
len = strlen(stext) + 1;
if (!(text = (char*) malloc(sizeof(char)*len)))
die("malloc");
p = text;
copyvalidchars(text, stext);
/* compute width of the status text */
w = 0;
i = -1;
while (text[++i]) {
if (text[i] == '^') {
if (!isCode) {
isCode = 1;
text[i] = '\0';
w += TEXTWM(text) - lrpad;
text[i] = '^';
if (text[++i] == 'f')
w += atoi(text + ++i);
} else {
isCode = 0;
text = text + i + 1;
i = -1;
}
}
}
if (!isCode)
w += TEXTWM(text) - lrpad;
free(p);
return w;
}

View File

@ -1,5 +0,0 @@
static int width_status2d(Bar *bar, BarArg *a);
static int draw_status2d(Bar *bar, BarArg *a);
static int drawstatusbar(BarArg *a, char *text);
static int status2dtextlength(char *stext);

View File

@ -1,18 +0,0 @@
int
width_stbutton(Bar *bar, BarArg *a)
{
return TEXTW(buttonbar);
}
int
draw_stbutton(Bar *bar, BarArg *a)
{
return drw_text(drw, a->x, a->y, a->w, a->h, lrpad / 2, buttonbar, 0, False);
}
int
click_stbutton(Bar *bar, Arg *arg, BarArg *a)
{
return ClkButton;
}

View File

@ -1,4 +0,0 @@
static int width_stbutton(Bar *bar, BarArg *a);
static int draw_stbutton(Bar *bar, BarArg *a);
static int click_stbutton(Bar *bar, Arg *arg, BarArg *a);

View File

@ -1,44 +0,0 @@
int
click_statuscmd(Bar *bar, Arg *arg, BarArg *a)
{
return click_statuscmd_text(arg, a->x, rawstext);
}
int
click_statuscmd_text(Arg *arg, int rel_x, char *text)
{
int i = -1;
int x = 0;
char ch;
statussig = -1;
while (text[++i]) {
if ((unsigned char)text[i] < ' ') {
ch = text[i];
text[i] = '\0';
x += status2dtextlength(text);
text[i] = ch;
text += i+1;
i = -1;
if (x >= rel_x && statussig != -1)
break;
statussig = ch;
}
}
if (statussig == -1)
statussig = 0;
return ClkStatusText;
}
void
copyvalidchars(char *text, char *rawtext)
{
int i = -1, j = 0;
while (rawtext[++i]) {
if ((unsigned char)rawtext[i] >= ' ') {
text[j++] = rawtext[i];
}
}
text[j] = '\0';
}

View File

@ -1,9 +0,0 @@
static int click_statuscmd(Bar *bar, Arg *arg, BarArg *a);
static int click_statuscmd_text(Arg *arg, int rel_x, char *text);
static void copyvalidchars(char *text, char *rawtext);
typedef struct {
const char *cmd;
int id;
} StatusCmd;

View File

@ -1,9 +0,0 @@
char *
tagicon(Monitor *m, int tag)
{
int tagindex = tag + NUMTAGS * m->num;
if (tagindex >= LENGTH(tagicons[DEFAULT_TAGS]))
tagindex = tagindex % LENGTH(tagicons[DEFAULT_TAGS]);
return tagicons[DEFAULT_TAGS][tagindex];
}

View File

@ -1,8 +0,0 @@
enum {
DEFAULT_TAGS,
ALTERNATIVE_TAGS,
ALT_TAGS_DECORATION,
};
static char * tagicon(Monitor *m, int tag);

View File

@ -1,81 +0,0 @@
int
width_tags(Bar *bar, BarArg *a)
{
int w, i;
Client *c;
unsigned int occ = 0;
for (c = bar->mon->clients; c; c = c->next)
occ |= c->tags == 255 ? 0 : c->tags;
for (w = 0, i = 0; i < NUMTAGS; i++) {
if (!(occ & 1 << i || bar->mon->tagset[bar->mon->seltags] & 1 << i))
continue;
w += TEXTW(tagicon(bar->mon, i));
}
return w;
}
int
draw_tags(Bar *bar, BarArg *a)
{
int invert;
int w, x = a->x;
unsigned int i, occ = 0, urg = 0;
char *icon;
Client *c;
Monitor *m = bar->mon;
for (c = m->clients; c; c = c->next) {
occ |= c->tags == 255 ? 0 : c->tags;
if (c->isurgent)
urg |= c->tags;
}
for (i = 0; i < NUMTAGS; i++) {
/* do not draw vacant tags */
if (!(occ & 1 << i || m->tagset[m->seltags] & 1 << i))
continue;
icon = tagicon(bar->mon, i);
invert = 0;
w = TEXTW(icon);
drw_setscheme(drw, scheme[
m->tagset[m->seltags] & 1 << i
? SchemeTagsSel
: urg & 1 << i
? SchemeUrg
: SchemeTagsNorm
]);
drw_text(drw, x, a->y, w, a->h, lrpad / 2, icon, invert, False);
drawindicator(m, NULL, occ, x, a->y, w, a->h, i, -1, invert, tagindicatortype);
x += w;
}
return 1;
}
int
click_tags(Bar *bar, Arg *arg, BarArg *a)
{
int i = 0, x = 0;
Client *c;
unsigned int occ = 0;
for (c = bar->mon->clients; c; c = c->next)
occ |= c->tags == 255 ? 0 : c->tags;
do {
if (!(occ & 1 << i || bar->mon->tagset[bar->mon->seltags] & 1 << i))
continue;
x += TEXTW(tagicon(bar->mon, i));
} while (a->x >= x && ++i < NUMTAGS);
if (i < NUMTAGS) {
arg->ui = 1 << i;
}
return ClkTagBar;
}
int
hover_tags(Bar *bar, BarArg *a, XMotionEvent *ev)
{
return 1;
}

View File

@ -1,4 +0,0 @@
static int width_tags(Bar *bar, BarArg *a);
static int draw_tags(Bar *bar, BarArg *a);
static int click_tags(Bar *bar, Arg *arg, BarArg *a);
static int hover_tags(Bar *bar, BarArg *a, XMotionEvent *ev);

View File

@ -1,37 +0,0 @@
/* dwm will keep pid's of processes from autostart array and kill them at quit */
static pid_t *autostart_pids;
static size_t autostart_len;
/* execute command from autostart array */
static void
autostart_exec()
{
const char *const *p;
struct sigaction sa;
size_t i = 0;
/* count entries */
for (p = autostart; *p; autostart_len++, p++)
while (*++p);
autostart_pids = malloc(autostart_len * sizeof(pid_t));
for (p = autostart; *p; i++, p++) {
if ((autostart_pids[i] = fork()) == 0) {
setsid();
/* Restore SIGCHLD sighandler to default before spawning a program */
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = SIG_DFL;
sigaction(SIGCHLD, &sa, NULL);
execvp(*p, (char *const *)p);
fprintf(stderr, "dwm: execvp %s\n", *p);
perror(" failed");
_exit(EXIT_FAILURE);
}
/* skip arguments */
while (*++p);
}
}

View File

@ -1,2 +0,0 @@
static void autostart_exec(void);

View File

@ -1,136 +0,0 @@
#!/usr/bin/env bash
signal() {
xsetroot -name "fsignal:$*"
}
case $# in
1)
case $1 in
focusurgent) ;&
mirrorlayout) ;&
mpdcontrol) ;&
nametag) ;&
pushdown) ;&
pushup) ;&
self_restart) ;&
setlayout) ;&
setcfact) ;&
showhideclient) ;&
switchcol) ;&
view) ;&
viewall) ;&
viewtoleft) ;&
viewtoright) ;&
tagtoleft) ;&
tagtoright) ;&
tagandviewtoleft) ;&
tagandviewtoright) ;&
transfer) ;&
transferall) ;&
togglealttag) ;&
togglebar) ;&
toggletopbar) ;&
togglefloating) ;&
togglefullscreen) ;&
fullscreen) ;&
togglefakefullscreen) ;&
togglesticky) ;&
togglehorizontalmax) ;&
toggleverticalmax) ;&
togglemax) ;&
togglegaps) ;&
defaultgaps) ;&
unfloatvisible) ;&
winview) ;&
xrdb) ;&
zoom) ;&
killclient) ;&
quit)
signal $1
;;
*)
echo "Unknown command ($1) or missing one argument."
exit 1
;;
esac
;;
2)
case $1 in
cyclelayout) ;&
explace) ;&
moveplace) ;&
mpdchange) ;&
setkeymode) ;&
switchtag) ;&
togglescratch) ;&
view)
signal $1 ui $2
;;
viewex) ;&
toggleviewex) ;&
tagallmon) ;&
tagswapmon) ;&
tagex) ;&
toggletagex) ;&
setborderpx) ;&
setgaps) ;&
setlayoutex) ;&
setlayoutaxisex) ;&
swapfocus) ;&
focusstack) ;&
pushstack) ;&
inplacerotate) ;&
rotatestack) ;&
rotatelayoutaxis) ;&
incnmaster) ;&
incnstack) ;&
incrgaps) ;&
incrigaps) ;&
incrogaps) ;&
incrihgaps) ;&
incrivgaps) ;&
incrohgaps) ;&
incrovgaps) ;&
movestack) ;&
shiftview) ;&
shiftviewclients) ;&
focusmon) ;&
tagmon)
signal $1 i $2
;;
setcfact) ;&
setmfact)
signal $1 f $2
;;
floatpos)
signal $1 v $2
;;
*)
echo "Unknown command ($1) or too many arguments"
exit 1
;;
esac
;;
5)
case $1 in
setgaps)
# Expects "setgaps oh ov ih iv" where -1 means to keep existing values
[ $2 = -1 ] && oh=128 || oh=$2
[ $3 = -1 ] && ov=128 || ov=$3
[ $4 = -1 ] && ih=128 || ih=$4
[ $5 = -1 ] && iv=128 || iv=$5
signal $1 i $(((oh << 24) + (ov << 16) + (ih << 8) + iv))
;;
*)
echo "Unknown command ($1) or too many arguments"
exit 1
;;
esac
;;
*)
echo "Unknown command ($1) or too many arguments"
exit 1
;;
esac

View File

@ -1,87 +0,0 @@
void
setlayoutex(const Arg *arg)
{
setlayout(&((Arg) { .v = &layouts[arg->i] }));
}
void
viewex(const Arg *arg)
{
view(&((Arg) { .ui = 1 << arg->ui }));
}
void
viewallex(const Arg *arg)
{
view(&((Arg){.ui = ~SPTAGMASK}));
}
void
toggleviewex(const Arg *arg)
{
toggleview(&((Arg) { .ui = 1 << arg->ui }));
}
void
tagex(const Arg *arg)
{
tag(&((Arg) { .ui = 1 << arg->ui }));
}
void
toggletagex(const Arg *arg)
{
toggletag(&((Arg) { .ui = 1 << arg->ui }));
}
void
tagallex(const Arg *arg)
{
tag(&((Arg){.ui = ~SPTAGMASK}));
}
int
fake_signal(void)
{
char fsignal[256];
char indicator[9] = "fsignal:";
char str_sig[50];
char param[16];
int i, len_str_sig, n, paramn;
size_t len_fsignal, len_indicator = strlen(indicator);
Arg arg;
// Get root name property
if (gettextprop(root, XA_WM_NAME, fsignal, sizeof(fsignal))) {
len_fsignal = strlen(fsignal);
// Check if this is indeed a fake signal
if (len_indicator > len_fsignal ? 0 : strncmp(indicator, fsignal, len_indicator) == 0) {
paramn = sscanf(fsignal+len_indicator, "%s%n%s%n", str_sig, &len_str_sig, param, &n);
if (paramn == 1) arg = (Arg) {0};
else if (paramn > 2) return 1;
else if (strncmp(param, "i", n - len_str_sig) == 0)
sscanf(fsignal + len_indicator + n, "%i", &(arg.i));
else if (strncmp(param, "ui", n - len_str_sig) == 0)
sscanf(fsignal + len_indicator + n, "%u", &(arg.ui));
else if (strncmp(param, "f", n - len_str_sig) == 0)
sscanf(fsignal + len_indicator + n, "%f", &(arg.f));
else if (strncmp(param, "v", n - len_str_sig) == 0)
arg.v = &(fsignal[len_indicator + n + 1]);
else return 1;
// Check if a signal was found, and if so handle it
for (i = 0; i < LENGTH(signals); i++)
if (strncmp(str_sig, signals[i].sig, len_str_sig) == 0 && signals[i].func)
signals[i].func(&(arg));
// A fake signal was sent
return 1;
}
}
// No fake signal was sent, so proceed with update
return 0;
}

View File

@ -1,14 +0,0 @@
typedef struct {
const char * sig;
void (*func)(const Arg *);
} Signal;
static void setlayoutex(const Arg *arg);
static void viewex(const Arg *arg);
static void viewallex(const Arg *arg);
static void toggleviewex(const Arg *arg);
static void tagex(const Arg *arg);
static void toggletagex(const Arg *arg);
static void tagallex(const Arg *arg);
static int fake_signal(void);

View File

@ -1,19 +0,0 @@
void
togglefakefullscreen(const Arg *arg)
{
Client *c = selmon->sel;
if (!c)
return;
if (c->fakefullscreen != 1 && c->isfullscreen) { // exit fullscreen --> fake fullscreen
c->fakefullscreen = 2;
setfullscreen(c, 0);
} else if (c->fakefullscreen == 1) {
setfullscreen(c, 0);
c->fakefullscreen = 0;
} else {
c->fakefullscreen = 1;
setfullscreen(c, 1);
}
}

View File

@ -1,2 +0,0 @@
static void togglefakefullscreen(const Arg *arg);

View File

@ -1,66 +0,0 @@
void
focusdir(const Arg *arg)
{
Client *s = selmon->sel, *f = NULL, *c, *next;
if (!s)
return;
unsigned int score = -1;
unsigned int client_score;
int dist;
int dirweight = 20;
int isfloating = s->isfloating;
next = s->next;
if (!next)
next = s->mon->clients;
for (c = next; c != s; c = next) {
next = c->next;
if (!next)
next = s->mon->clients;
if (!ISVISIBLE(c) || c->isfloating != isfloating) // || HIDDEN(c)
continue;
switch (arg->i) {
case 0: // left
dist = s->x - c->x - c->w;
client_score =
dirweight * MIN(abs(dist), abs(dist + s->mon->ww)) +
abs(s->y - c->y);
break;
case 1: // right
dist = c->x - s->x - s->w;
client_score =
dirweight * MIN(abs(dist), abs(dist + s->mon->ww)) +
abs(c->y - s->y);
break;
case 2: // up
dist = s->y - c->y - c->h;
client_score =
dirweight * MIN(abs(dist), abs(dist + s->mon->wh)) +
abs(s->x - c->x);
break;
default:
case 3: // down
dist = c->y - s->y - s->h;
client_score =
dirweight * MIN(abs(dist), abs(dist + s->mon->wh)) +
abs(c->x - s->x);
break;
}
if (((arg->i == 0 || arg->i == 2) && client_score <= score) || client_score < score) {
score = client_score;
f = c;
}
}
if (f && f != s) {
focus(f);
restack(f->mon);
}
}

View File

@ -1,2 +0,0 @@
static void focusdir(const Arg *arg);

View File

@ -1,38 +0,0 @@
/* Bar functionality */
#include "bar_indicators.c"
#include "bar_tagicons.c"
#include "bar.c"
#include "bar_dwmblocks.c"
#include "bar_ewmhtags.c"
#include "bar_ltsymbol.c"
#include "bar_status.c"
#include "bar_status2d.c"
#include "bar_statusbutton.c"
#include "bar_statuscmd.c"
#include "bar_tags.c"
#include "bar_holdbar.c"
/* Other patches */
#include "attachx.c"
#include "cool_autostart.c"
#include "dwmc.c"
#include "fakefullscreenclient.c"
#include "focusdir.c"
#include "killunsel.c"
#include "pertag.c"
#include "restartsig.c"
#include "rotatestack.c"
#include "scratchpad.c"
#include "shift.c"
#include "shiftboth.c"
#include "shiftviewclients.c"
#include "tapresize.c"
#include "transfer.c"
#include "xrdb.c"
#include "seamless_restart.c"
/* Layouts */
#include "layout_facts.c"
#include "layout_monocle.c"
#include "layout_tile.c"

View File

@ -1,37 +0,0 @@
/* Bar functionality */
#include "bar_indicators.h"
#include "bar_tagicons.h"
#include "bar.h"
#include "bar_dwmblocks.h"
#include "bar_ewmhtags.h"
#include "bar_holdbar.h"
#include "bar_ltsymbol.h"
#include "bar_status.h"
#include "bar_status2d.h"
#include "bar_statusbutton.h"
#include "bar_statuscmd.h"
#include "bar_tags.h"
/* Other patches */
#include "attachx.h"
#include "cool_autostart.h"
#include "dwmc.h"
#include "fakefullscreenclient.h"
#include "focusdir.h"
#include "killunsel.h"
#include "pertag.h"
#include "restartsig.h"
#include "rotatestack.h"
#include "scratchpad.h"
#include "seamless_restart.h"
#include "shift.h"
#include "shiftboth.h"
#include "shiftviewclients.h"
#include "tapresize.h"
#include "transfer.h"
#include "xrdb.h"
/* Layouts */
#include "layout_monocle.h"
#include "layout_tile.h"

View File

@ -1,62 +0,0 @@
#ifndef IPC_CLIENT_H_
#define IPC_CLIENT_H_
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
typedef struct IPCClient IPCClient;
/**
* This structure contains the details of an IPC Client and pointers for a
* linked list
*/
struct IPCClient {
int fd;
int subscriptions;
char *buffer;
uint32_t buffer_size;
struct epoll_event event;
IPCClient *next;
IPCClient *prev;
};
typedef IPCClient *IPCClientList;
/**
* Allocate memory for new IPCClient with the specified file descriptor and
* initialize struct.
*
* @param fd File descriptor of IPC client
*
* @return Address to allocated IPCClient struct
*/
IPCClient *ipc_client_new(int fd);
/**
* Add an IPC Client to the specified list
*
* @param list Address of the list to add the client to
* @param nc Address of the IPCClient
*/
void ipc_list_add_client(IPCClientList *list, IPCClient *nc);
/**
* Remove an IPCClient from the specified list
*
* @param list Address of the list to remove the client from
* @param c Address of the IPCClient
*/
void ipc_list_remove_client(IPCClientList *list, IPCClient *c);
/**
* Get an IPCClient from the specified IPCClient list
*
* @param list List to remove the client from
* @param fd File descriptor of the IPCClient
*/
IPCClient *ipc_list_get_client(IPCClientList list, int fd);
#endif // IPC_CLIENT_H_

View File

@ -1,549 +0,0 @@
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <yajl/yajl_gen.h>
#define IPC_MAGIC "DWM-IPC"
// clang-format off
#define IPC_MAGIC_ARR { 'D', 'W', 'M', '-', 'I', 'P', 'C' }
// clang-format on
#define IPC_MAGIC_LEN 7 // Not including null char
#define IPC_EVENT_TAG_CHANGE "tag_change_event"
#define IPC_EVENT_CLIENT_FOCUS_CHANGE "client_focus_change_event"
#define IPC_EVENT_LAYOUT_CHANGE "layout_change_event"
#define IPC_EVENT_MONITOR_FOCUS_CHANGE "monitor_focus_change_event"
#define IPC_EVENT_FOCUSED_TITLE_CHANGE "focused_title_change_event"
#define IPC_EVENT_FOCUSED_STATE_CHANGE "focused_state_change_event"
#define YSTR(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
#define YINT(num) yajl_gen_integer(gen, num)
#define YDOUBLE(num) yajl_gen_double(gen, num)
#define YBOOL(v) yajl_gen_bool(gen, v)
#define YNULL() yajl_gen_null(gen)
#define YARR(body) \
{ \
yajl_gen_array_open(gen); \
body; \
yajl_gen_array_close(gen); \
}
#define YMAP(body) \
{ \
yajl_gen_map_open(gen); \
body; \
yajl_gen_map_close(gen); \
}
typedef unsigned long Window;
const char *DEFAULT_SOCKET_PATH = "/tmp/dwm.sock";
static int sock_fd = -1;
static unsigned int ignore_reply = 0;
typedef enum IPCMessageType {
IPC_TYPE_RUN_COMMAND = 0,
IPC_TYPE_GET_MONITORS = 1,
IPC_TYPE_GET_TAGS = 2,
IPC_TYPE_GET_LAYOUTS = 3,
IPC_TYPE_GET_DWM_CLIENT = 4,
IPC_TYPE_SUBSCRIBE = 5,
IPC_TYPE_EVENT = 6
} IPCMessageType;
// Every IPC message must begin with this
typedef struct dwm_ipc_header {
uint8_t magic[IPC_MAGIC_LEN];
uint32_t size;
uint8_t type;
} __attribute((packed)) dwm_ipc_header_t;
static int
recv_message(uint8_t *msg_type, uint32_t *reply_size, uint8_t **reply)
{
uint32_t read_bytes = 0;
const int32_t to_read = sizeof(dwm_ipc_header_t);
char header[to_read];
char *walk = header;
// Try to read header
while (read_bytes < to_read) {
ssize_t n = read(sock_fd, header + read_bytes, to_read - read_bytes);
if (n == 0) {
if (read_bytes == 0) {
fprintf(stderr, "Unexpectedly reached EOF while reading header.");
fprintf(stderr,
"Read %" PRIu32 " bytes, expected %" PRIu32 " total bytes.\n",
read_bytes, to_read);
return -2;
} else {
fprintf(stderr, "Unexpectedly reached EOF while reading header.");
fprintf(stderr,
"Read %" PRIu32 " bytes, expected %" PRIu32 " total bytes.\n",
read_bytes, to_read);
return -3;
}
} else if (n == -1) {
return -1;
}
read_bytes += n;
}
// Check if magic string in header matches
if (memcmp(walk, IPC_MAGIC, IPC_MAGIC_LEN) != 0) {
fprintf(stderr, "Invalid magic string. Got '%.*s', expected '%s'\n",
IPC_MAGIC_LEN, walk, IPC_MAGIC);
return -3;
}
walk += IPC_MAGIC_LEN;
// Extract reply size
memcpy(reply_size, walk, sizeof(uint32_t));
walk += sizeof(uint32_t);
// Extract message type
memcpy(msg_type, walk, sizeof(uint8_t));
walk += sizeof(uint8_t);
(*reply) = malloc(*reply_size);
// Extract payload
read_bytes = 0;
while (read_bytes < *reply_size) {
ssize_t n = read(sock_fd, *reply + read_bytes, *reply_size - read_bytes);
if (n == 0) {
fprintf(stderr, "Unexpectedly reached EOF while reading payload.");
fprintf(stderr, "Read %" PRIu32 " bytes, expected %" PRIu32 " bytes.\n",
read_bytes, *reply_size);
free(*reply);
return -2;
} else if (n == -1) {
if (errno == EINTR || errno == EAGAIN) continue;
free(*reply);
return -1;
}
read_bytes += n;
}
return 0;
}
static int
read_socket(IPCMessageType *msg_type, uint32_t *msg_size, char **msg)
{
int ret = -1;
while (ret != 0) {
ret = recv_message((uint8_t *)msg_type, msg_size, (uint8_t **)msg);
if (ret < 0) {
// Try again (non-fatal error)
if (ret == -1 && (errno == EINTR || errno == EAGAIN)) continue;
fprintf(stderr, "Error receiving response from socket. ");
fprintf(stderr, "The connection might have been lost.\n");
exit(2);
}
}
return 0;
}
static ssize_t
write_socket(const void *buf, size_t count)
{
size_t written = 0;
while (written < count) {
const ssize_t n =
write(sock_fd, ((uint8_t *)buf) + written, count - written);
if (n == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
continue;
else
return n;
}
written += n;
}
return written;
}
static void
connect_to_socket()
{
struct sockaddr_un addr;
int sock = socket(AF_UNIX, SOCK_STREAM, 0);
// Initialize struct to 0
memset(&addr, 0, sizeof(struct sockaddr_un));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, DEFAULT_SOCKET_PATH);
connect(sock, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un));
sock_fd = sock;
}
static int
send_message(IPCMessageType msg_type, uint32_t msg_size, uint8_t *msg)
{
dwm_ipc_header_t header = {
.magic = IPC_MAGIC_ARR, .size = msg_size, .type = msg_type};
size_t header_size = sizeof(dwm_ipc_header_t);
size_t total_size = header_size + msg_size;
uint8_t buffer[total_size];
// Copy header to buffer
memcpy(buffer, &header, header_size);
// Copy message to buffer
memcpy(buffer + header_size, msg, header.size);
write_socket(buffer, total_size);
return 0;
}
static int
is_float(const char *s)
{
size_t len = strlen(s);
int is_dot_used = 0;
int is_minus_used = 0;
// Floats can only have one decimal point in between or digits
// Optionally, floats can also be below zero (negative)
for (int i = 0; i < len; i++) {
if (isdigit(s[i]))
continue;
else if (!is_dot_used && s[i] == '.' && i != 0 && i != len - 1) {
is_dot_used = 1;
continue;
} else if (!is_minus_used && s[i] == '-' && i == 0) {
is_minus_used = 1;
continue;
} else
return 0;
}
return 1;
}
static int
is_unsigned_int(const char *s)
{
size_t len = strlen(s);
// Unsigned int can only have digits
for (int i = 0; i < len; i++) {
if (isdigit(s[i]))
continue;
else
return 0;
}
return 1;
}
static int
is_signed_int(const char *s)
{
size_t len = strlen(s);
// Signed int can only have digits and a negative sign at the start
for (int i = 0; i < len; i++) {
if (isdigit(s[i]))
continue;
else if (i == 0 && s[i] == '-') {
continue;
} else
return 0;
}
return 1;
}
static void
flush_socket_reply()
{
IPCMessageType reply_type;
uint32_t reply_size;
char *reply;
read_socket(&reply_type, &reply_size, &reply);
free(reply);
}
static void
print_socket_reply()
{
IPCMessageType reply_type;
uint32_t reply_size;
char *reply;
read_socket(&reply_type, &reply_size, &reply);
printf("%.*s\n", reply_size, reply);
fflush(stdout);
free(reply);
}
static int
run_command(const char *name, char *args[], int argc)
{
const unsigned char *msg;
size_t msg_size;
yajl_gen gen = yajl_gen_alloc(NULL);
// Message format:
// {
// "command": "<name>",
// "args": [ ... ]
// }
// clang-format off
YMAP(
YSTR("command"); YSTR(name);
YSTR("args"); YARR(
for (int i = 0; i < argc; i++) {
if (is_signed_int(args[i])) {
long long num = atoll(args[i]);
YINT(num);
} else if (is_float(args[i])) {
float num = atof(args[i]);
YDOUBLE(num);
} else {
YSTR(args[i]);
}
}
)
)
// clang-format on
yajl_gen_get_buf(gen, &msg, &msg_size);
send_message(IPC_TYPE_RUN_COMMAND, msg_size, (uint8_t *)msg);
if (!ignore_reply)
print_socket_reply();
else
flush_socket_reply();
yajl_gen_free(gen);
return 0;
}
static int
get_monitors()
{
send_message(IPC_TYPE_GET_MONITORS, 1, (uint8_t *)"");
print_socket_reply();
return 0;
}
static int
get_tags()
{
send_message(IPC_TYPE_GET_TAGS, 1, (uint8_t *)"");
print_socket_reply();
return 0;
}
static int
get_layouts()
{
send_message(IPC_TYPE_GET_LAYOUTS, 1, (uint8_t *)"");
print_socket_reply();
return 0;
}
static int
get_dwm_client(Window win)
{
const unsigned char *msg;
size_t msg_size;
yajl_gen gen = yajl_gen_alloc(NULL);
// Message format:
// {
// "client_window_id": "<win>"
// }
// clang-format off
YMAP(
YSTR("client_window_id"); YINT(win);
)
// clang-format on
yajl_gen_get_buf(gen, &msg, &msg_size);
send_message(IPC_TYPE_GET_DWM_CLIENT, msg_size, (uint8_t *)msg);
print_socket_reply();
yajl_gen_free(gen);
return 0;
}
static int
subscribe(const char *event)
{
const unsigned char *msg;
size_t msg_size;
yajl_gen gen = yajl_gen_alloc(NULL);
// Message format:
// {
// "event": "<event>",
// "action": "subscribe"
// }
// clang-format off
YMAP(
YSTR("event"); YSTR(event);
YSTR("action"); YSTR("subscribe");
)
// clang-format on
yajl_gen_get_buf(gen, &msg, &msg_size);
send_message(IPC_TYPE_SUBSCRIBE, msg_size, (uint8_t *)msg);
if (!ignore_reply)
print_socket_reply();
else
flush_socket_reply();
yajl_gen_free(gen);
return 0;
}
static void
usage_error(const char *prog_name, const char *format, ...)
{
va_list args;
va_start(args, format);
fprintf(stderr, "Error: ");
vfprintf(stderr, format, args);
fprintf(stderr, "\nusage: %s <command> [...]\n", prog_name);
fprintf(stderr, "Try '%s help'\n", prog_name);
va_end(args);
exit(1);
}
static void
print_usage(const char *name)
{
printf("usage: %s [options] <command> [...]\n", name);
puts("");
puts("Commands:");
puts(" run_command <name> [args...] Run an IPC command");
puts("");
puts(" get_monitors Get monitor properties");
puts("");
puts(" get_tags Get list of tags");
puts("");
puts(" get_layouts Get list of layouts");
puts("");
puts(" get_dwm_client <window_id> Get dwm client proprties");
puts("");
puts(" subscribe [events...] Subscribe to specified events");
puts(" Options: " IPC_EVENT_TAG_CHANGE ",");
puts(" " IPC_EVENT_LAYOUT_CHANGE ",");
puts(" " IPC_EVENT_CLIENT_FOCUS_CHANGE ",");
puts(" " IPC_EVENT_MONITOR_FOCUS_CHANGE ",");
puts(" " IPC_EVENT_FOCUSED_TITLE_CHANGE ",");
puts(" " IPC_EVENT_FOCUSED_STATE_CHANGE);
puts("");
puts(" help Display this message");
puts("");
puts("Options:");
puts(" --ignore-reply Don't print reply messages from");
puts(" run_command and subscribe.");
puts("");
}
int
main(int argc, char *argv[])
{
const char *prog_name = argv[0];
connect_to_socket();
if (sock_fd == -1) {
fprintf(stderr, "Failed to connect to socket\n");
return 1;
}
int i = 1;
if (i < argc && strcmp(argv[i], "--ignore-reply") == 0) {
ignore_reply = 1;
i++;
}
if (i >= argc) usage_error(prog_name, "Expected an argument, got none");
if (!argc || strcmp(argv[i], "help") == 0)
print_usage(prog_name);
else if (strcmp(argv[i], "run_command") == 0) {
if (++i >= argc) usage_error(prog_name, "No command specified");
// Command name
char *command = argv[i];
// Command arguments are everything after command name
char **command_args = argv + ++i;
// Number of command arguments
int command_argc = argc - i;
run_command(command, command_args, command_argc);
} else if (strcmp(argv[i], "get_monitors") == 0) {
get_monitors();
} else if (strcmp(argv[i], "get_tags") == 0) {
get_tags();
} else if (strcmp(argv[i], "get_layouts") == 0) {
get_layouts();
} else if (strcmp(argv[i], "get_dwm_client") == 0) {
if (++i < argc) {
if (is_unsigned_int(argv[i])) {
Window win = atol(argv[i]);
get_dwm_client(win);
} else
usage_error(prog_name, "Expected unsigned integer argument");
} else
usage_error(prog_name, "Expected the window id");
} else if (strcmp(argv[i], "subscribe") == 0) {
if (++i < argc) {
for (int j = i; j < argc; j++) subscribe(argv[j]);
} else
usage_error(prog_name, "Expected event name");
// Keep listening for events forever
while (1) {
print_socket_reply();
}
} else
usage_error(prog_name, "Invalid argument '%s'", argv[i]);
return 0;
}

View File

@ -1,66 +0,0 @@
#ifndef YAJL_DUMPS_H_
#define YAJL_DUMPS_H_
#include <string.h>
#include <yajl/yajl_gen.h>
#define YSTR(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
#define YINT(num) yajl_gen_integer(gen, num)
#define YDOUBLE(num) yajl_gen_double(gen, num)
#define YBOOL(v) yajl_gen_bool(gen, v)
#define YNULL() yajl_gen_null(gen)
#define YARR(body) \
{ \
yajl_gen_array_open(gen); \
body; \
yajl_gen_array_close(gen); \
}
#define YMAP(body) \
{ \
yajl_gen_map_open(gen); \
body; \
yajl_gen_map_close(gen); \
}
int dump_tag(yajl_gen gen, const char *name, const int tag_mask);
int dump_tags(yajl_gen gen, int tags_len);
int dump_client(yajl_gen gen, Client *c);
int dump_monitor(yajl_gen gen, Monitor *mon, int is_selected);
int dump_monitors(yajl_gen gen, Monitor *mons, Monitor *selmon);
int dump_layouts(yajl_gen gen, const Layout layouts[], const int layouts_len);
int dump_tag_state(yajl_gen gen, TagState state);
int dump_tag_event(yajl_gen gen, int mon_num, TagState old_state,
TagState new_state);
int dump_client_focus_change_event(yajl_gen gen, Client *old_client,
Client *new_client, int mon_num);
int dump_layout_change_event(yajl_gen gen, const int mon_num,
const char *old_symbol, const Layout *old_layout,
const char *new_symbol, const Layout *new_layout);
int dump_monitor_focus_change_event(yajl_gen gen, const int last_mon_num,
const int new_mon_num);
int dump_focused_title_change_event(yajl_gen gen, const int mon_num,
const Window client_id,
const char *old_name, const char *new_name);
int dump_client_state(yajl_gen gen, const ClientState *state);
int dump_focused_state_change_event(yajl_gen gen, const int mon_num,
const Window client_id,
const ClientState *old_state,
const ClientState *new_state);
int dump_error_message(yajl_gen gen, const char *reason);
#endif // YAJL_DUMPS_H_

View File

@ -1,24 +0,0 @@
void
killunsel(const Arg *arg)
{
Client *i = NULL;
if (!selmon->sel)
return;
for (i = selmon->clients; i; i = i->next) {
if (ISVISIBLE(i) && i != selmon->sel) {
if (!sendevent(i, wmatom[WMDelete]))
{
XGrabServer(dpy);
XSetErrorHandler(xerrordummy);
XSetCloseDownMode(dpy, DestroyAll);
XKillClient(dpy, i->win);
XSync(dpy, False);
XSetErrorHandler(xerror);
XUngrabServer(dpy);
}
}
}
}

View File

@ -1,2 +0,0 @@
static void killunsel(const Arg *arg);

View File

@ -1,24 +0,0 @@
void
getfacts(Monitor *m, int msize, int ssize, float *mf, float *sf, int *mr, int *sr)
{
unsigned int n;
float mfacts, sfacts;
int mtotal = 0, stotal = 0;
Client *c;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
mfacts = MIN(n, m->nmaster);
sfacts = n - m->nmaster;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++)
if (n < m->nmaster)
mtotal += msize / mfacts;
else
stotal += ssize / sfacts;
*mf = mfacts; // total factor of master area
*sf = sfacts; // total factor of stack area
*mr = msize - mtotal; // the remainder (rest) of pixels after an even master split
*sr = ssize - stotal; // the remainder (rest) of pixels after an even stack split
}

View File

@ -1,9 +0,0 @@
void
monocle(Monitor *m)
{
Client *c;
for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0);
}

View File

@ -1,2 +0,0 @@
static void monocle(Monitor *m);

View File

@ -1,38 +0,0 @@
static void
tile(Monitor *m)
{
unsigned int i, n;
int mx = 0, my = 0, mh = 0, mw = 0;
int sx = 0, sy = 0, sh = 0, sw = 0;
float mfacts, sfacts;
int mrest, srest;
Client *c;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
if (n == 0)
return;
sx = mx = m->wx;
sy = my = m->wy;
sh = mh = m->wh;
sw = mw = m->ww;
if (m->nmaster && n > m->nmaster) {
sw = mw * (1 - m->mfact);
mw = mw * m->mfact;
sx = mx + mw;
}
getfacts(m, mh, sh, &mfacts, &sfacts, &mrest, &srest);
for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
if (i < m->nmaster) {
resize(c, mx, my, mw - (2*c->bw), (mh / mfacts) + (i < mrest ? 1 : 0) - (2*c->bw), 0);
my += HEIGHT(c);
} else {
resize(c, sx, sy, sw - (2*c->bw), (sh / sfacts) + ((i - m->nmaster) < srest ? 1 : 0) - (2*c->bw), 0);
sy += HEIGHT(c);
}
}

View File

@ -1,2 +0,0 @@
static void tile(Monitor *m);

View File

@ -1,28 +0,0 @@
struct Pertag {
unsigned int curtag; /* current tag index */
int nmasters[NUMTAGS + 1]; /* number of windows in master area */
const Layout *ltidxs[NUMTAGS + 1][2]; /* matrix of tags and layouts indexes */
float mfacts[NUMTAGS + 1]; /* mfacts per tag */
unsigned int sellts[NUMTAGS + 1]; /* selected layouts */
};
void
pertagview(const Arg *arg)
{
int i;
if (arg->ui == ~SPTAGMASK)
selmon->pertag->curtag = 0;
else {
for (i = 0; !(selmon->tagset[selmon->seltags] & 1 << i); i++);
selmon->pertag->curtag = i + 1;
}
selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
}

View File

@ -1,2 +0,0 @@
static void pertagview(const Arg *arg);

View File

@ -1,16 +0,0 @@
static int restart = 0;
void
sighup(int unused)
{
Arg a = {.i = 1};
quit(&a);
}
void
sigterm(int unused)
{
Arg a = {.i = 0};
quit(&a);
}

View File

@ -1,3 +0,0 @@
static void sighup(int unused);
static void sigterm(int unused);

View File

@ -1,53 +0,0 @@
void
enqueue(Client *c)
{
Client *l;
for (l = c->mon->clients; l && l->next; l = l->next);
if (l) {
l->next = c;
c->next = NULL;
}
}
void
enqueuestack(Client *c)
{
Client *l;
for (l = c->mon->stack; l && l->snext; l = l->snext);
if (l) {
l->snext = c;
c->snext = NULL;
}
}
void
rotatestack(const Arg *arg)
{
Client *c = NULL, *f;
if (!selmon->sel)
return;
f = selmon->sel;
if (arg->i > 0) {
for (c = nexttiled(selmon->clients); c && nexttiled(c->next); c = nexttiled(c->next));
if (c){
detach(c);
attach(c);
detachstack(c);
attachstack(c);
}
} else {
if ((c = nexttiled(selmon->clients))){
detach(c);
enqueue(c);
detachstack(c);
enqueuestack(c);
}
}
if (c){
arrange(selmon);
focus(f);
restack(selmon);
}
}

View File

@ -1,4 +0,0 @@
static void enqueue(Client *c);
static void enqueuestack(Client *c);
static void rotatestack(const Arg *arg);

View File

@ -1,77 +0,0 @@
void
removescratch(const Arg *arg)
{
Client *c = selmon->sel;
if (!c)
return;
unsigned int scratchtag = SPTAG(arg->ui);
c->tags = c->mon->tagset[c->mon->seltags] ^ scratchtag;
arrange(c->mon);
}
void
setscratch(const Arg *arg)
{
Client *c = selmon->sel;
if (!c)
return;
unsigned int scratchtag = SPTAG(arg->ui);
c->tags = scratchtag;
arrange(c->mon);
}
void
togglescratch(const Arg *arg)
{
Client *c = NULL, *next = NULL, *found = NULL;
Monitor *mon;
unsigned int scratchtag = SPTAG(arg->ui);
unsigned int newtagset = 0;
int nh = 0, nw = 0;
Arg sparg = {.v = scratchpads[arg->ui].cmd};
for (mon = mons; mon; mon = mon->next) {
for (c = mon->clients; c; c = next) {
next = c->next;
if (!(c->tags & scratchtag))
continue;
found = c;
if (HIDDEN(c)) {
XMapWindow(dpy, c->win);
setclientstate(c, NormalState);
newtagset = 0;
} else
newtagset = selmon->tagset[selmon->seltags] ^ scratchtag;
if (c->mon != selmon) {
if (c->mon->tagset[c->mon->seltags] & SPTAGMASK)
c->mon->tagset[c->mon->seltags] ^= scratchtag;
if (c->w > selmon->ww)
nw = selmon->ww - c->bw * 2;
if (c->h > selmon->wh)
nh = selmon->wh - c->bw * 2;
if (nw > 0 || nh > 0)
resizeclient(c, c->x, c->y, nw ? nw : c->w, nh ? nh : c->h);
sendmon(c, selmon);
}
}
}
if (found) {
if (newtagset) {
selmon->tagset[selmon->seltags] = newtagset;
arrange(selmon);
focus(NULL);
}
if (ISVISIBLE(found)) {
focus(found);
restack(selmon);
}
} else {
selmon->tagset[selmon->seltags] |= scratchtag;
spawn(&sparg);
}
}

View File

@ -1,9 +0,0 @@
typedef struct {
const char *name;
const void *cmd;
} Sp;
static void removescratch(const Arg *arg);
static void setscratch(const Arg *arg);
static void togglescratch(const Arg *arg);

View File

@ -1,314 +0,0 @@
void
persistmonitorstate(Monitor *m)
{
Client *c;
unsigned int i;
setmonitortags(m);
setmonitorfields(m);
/* Set client atoms */
for (i = 1, c = m->clients; c; c = c->next, ++i) {
c->idx = i;
persistclientstate(c);
}
}
int
restoremonitorstate(Monitor *m)
{
return getmonitortags(m) | getmonitorfields(m);
}
void
persistclientstate(Client *c)
{
setclienttags(c);
setclientfields(c);
savewindowfloatposition(c, c->mon);
}
int
restoreclientstate(Client *c)
{
int restored = getclientfields(c);
getclienttags(c);
restorewindowfloatposition(c, c->mon ? c->mon : selmon);
return restored;
}
void setmonitorfields(Monitor *m)
{
unsigned int i;
char atom[22] = {0};
Atom monitor_fields;
sprintf(atom, "_DWM_MONITOR_FIELDS_%u", m->num);
monitor_fields = XInternAtom(dpy, atom, False);
/* Perists workspace information in 32 bits laid out like this:
*
* |0|0000|0|0000|0000|0000|0000|0000|000|000
* | | | | | | | | | |-- nmaster
* | | | | | | | | |-- nstack
* | | | | | | | |-- layout
* | | | | | | |-- flextile LAYOUT (split)
* | | | | | |-- flextile MASTER
* | | | | |-- flextile STACK1
* | | | |-- flextile STACK2
* | | |-- flextile mirror layout (indicated by negative layout)
* | |
* | |-- reserved
* |-- showbar
*/
for (i = 0; i <= NUMTAGS; i++) {
uint32_t data[] = {
(m->pertag->nmasters[i] & 0x7) |
(getlayoutindex(m->pertag->ltidxs[i][m->pertag->sellts[i]]) & 0xF) << 6 |
m->showbar << 31
};
XChangeProperty(dpy, root, monitor_fields, XA_CARDINAL, 32,
i ? PropModeAppend : PropModeReplace, (unsigned char *)data, 1);
}
}
int
getlayoutindex(const Layout *layout)
{
int i;
for (i = 0; i < LENGTH(layouts) && &layouts[i] != layout; i++);
if (i == LENGTH(layouts))
i = 0;
return i;
}
int
getmonitorfields(Monitor *m)
{
int di, layout_index;
unsigned int i, restored = 0;
unsigned int tags = m->tagset[m->seltags] << 1;
unsigned long dl, nitems;
unsigned char *p = NULL;
char atom[22] = {0};
Atom da, state = None;
sprintf(atom, "_DWM_MONITOR_FIELDS_%u", m->num);
Atom dwm_monitor = XInternAtom(dpy, atom, False);
if (!dwm_monitor)
return 0;
for (i = 0; i <= NUMTAGS; i++) {
if (!(XGetWindowProperty(dpy, root, dwm_monitor, i, (NUMTAGS + 1) * sizeof dl,
False, AnyPropertyType, &da, &di, &nitems, &dl, &p) == Success && p)) {
break;
}
if (!nitems) {
XFree(p);
break;
}
/* See bit layout in the persistmonitorstate function */
state = *(Atom *)p;
m->pertag->nmasters[i] = state & 0x7;
layout_index = (state >> 6) & 0xF;
if (layout_index < LENGTH(layouts))
m->pertag->ltidxs[i][m->pertag->sellts[i]] = &layouts[layout_index];
if (!restored && i && (tags & (1 << i))) {
m->nmaster = m->pertag->nmasters[i];
m->sellt = m->pertag->sellts[i];
m->lt[m->sellt] = m->pertag->ltidxs[i][m->sellt];
m->showbar = (state >> 31) & 0x1;
restored = 1;
}
XFree(p);
}
return restored;
}
void
setmonitortags(Monitor *m)
{
char atom[22] = {0};
Atom monitor_tags;
sprintf(atom, "_DWM_MONITOR_TAGS_%u", m->num);
monitor_tags = XInternAtom(dpy, atom, False);
uint32_t data[] = { m->tagset[m->seltags] };
XChangeProperty(dpy, root, monitor_tags, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}
int
getmonitortags(Monitor *m)
{
int di;
unsigned long dl, nitems;
unsigned char *p = NULL;
char atom[22] = {0};
Atom da, monitor_tags = None, tags;
sprintf(atom, "_DWM_MONITOR_TAGS_%u", m->num);
monitor_tags = XInternAtom(dpy, atom, False);
if (!(XGetWindowProperty(dpy, root, monitor_tags, 0L, sizeof dl,
False, AnyPropertyType, &da, &di, &nitems, &dl, &p) == Success && p)) {
return 0;
}
if (nitems) {
tags = *(Atom *)p;
m->tagset[m->seltags] = tags & TAGMASK;
}
XFree(p);
return 1;
}
void
setclientfields(Client *c)
{
/* Perists client information in 32 bits laid out like this:
*
* |00000000|00000|0|0|0|0|0|0|0|0|00000000|000
* | | | | | | | | | | | |-- monitor index
* | | | | | | | | | | |-- client index
* | | | | | | | | | |-- isfloating
* | | | | | | | | |-- ispermanent
* | | | | | | | |-- isterminal
* | | | | | | |-- noswallow
* | | | | | |-- issteam
* | | | | |-- issticky
* | | | |-- fakefullscreen
* | | |-- isfreesize
* | |
* | |-- reserved
* |-- scratchkey (for scratchpads)
*/
uint32_t data[] = {
(c->mon->num & 0x7)
| (c->idx & 0xFF) << 3
| (c->isfloating & 0x1) << 11
| (c->fakefullscreen & 0x1) << 17
};
XChangeProperty(dpy, c->win, clientatom[ClientFields], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}
int
getclientfields(Client *c)
{
Monitor *m;
Atom fields = getatomprop(c, clientatom[ClientFields], AnyPropertyType);
if (fields == None)
return 0;
/* See bit layout in the setclientfields function */
for (m = mons; m; m = m->next)
if (m->num == (fields & 0x7)) {
c->mon = m;
break;
}
c->idx = (fields >> 3) & 0xFF;
c->isfloating = (fields >> 11) & 0x1;
c->fakefullscreen = (fields >> 17) & 0x1;
return 1;
}
void
setclienttags(Client *c)
{
uint32_t data[] = { c->tags };
XChangeProperty(dpy, c->win, clientatom[ClientTags], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}
int
getclienttags(Client *c)
{
Atom tags = getatomprop(c, clientatom[ClientTags], AnyPropertyType);
if (tags == None)
return 0;
c->tags = tags & TAGMASK;
return 1;
}
void
savewindowfloatposition(Client *c, Monitor *m)
{
char atom[22] = {0};
if (c->sfx == -9999)
return;
sprintf(atom, "_DWM_FLOATPOS_%u", m->num);
uint32_t pos[] = { (MAX(c->sfx - m->mx, 0) & 0xffff) | ((MAX(c->sfy - m->my, 0) & 0xffff) << 16) };
XChangeProperty(dpy, c->win, XInternAtom(dpy, atom, False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pos, 1);
sprintf(atom, "_DWM_FLOATSIZE_%u", m->num);
uint32_t size[] = { (c->sfw & 0xffff) | ((c->sfh & 0xffff) << 16) };
XChangeProperty(dpy, c->win, XInternAtom(dpy, atom, False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *)size, 1);
XSync(dpy, False);
}
int
restorewindowfloatposition(Client *c, Monitor *m)
{
char atom[22] = {0};
Atom key, value;
int x, y, w, h;
if (m == NULL)
return 0;
sprintf(atom, "_DWM_FLOATPOS_%u", m->num);
key = XInternAtom(dpy, atom, False);
if (!key)
return 0;
value = getatomprop(c, key, AnyPropertyType);
if (!value)
return 0;
x = value & 0xffff;
y = value >> 16;
sprintf(atom, "_DWM_FLOATSIZE_%u", m->num);
key = XInternAtom(dpy, atom, False);
if (!key)
return 0;
value = getatomprop(c, key, AnyPropertyType);
if (!value)
return 0;
w = value & 0xffff;
h = value >> 16;
if (w <= 0 || h <= 0) {
fprintf(stderr, "restorewindowfloatposition: bad float values x = %d, y = %d, w = %d, h = %d for client = %s\n", x, y, w, h, c->name);
return 0;
}
c->sfx = m->mx + x;
c->sfy = m->my + y;
c->sfw = w;
c->sfh = h;
if (c->isfloating) {
c->x = c->sfx;
c->y = c->sfy;
c->w = c->sfw;
c->h = c->sfh;
}
return 1;
}

View File

@ -1,17 +0,0 @@
#include <stdint.h>
static void persistmonitorstate(Monitor *m);
static int restoremonitorstate(Monitor *m);
static void persistclientstate(Client *c);
static int restoreclientstate(Client *c);
static void setmonitorfields(Monitor *m);
static int getmonitorfields(Monitor *m);
static void setmonitortags(Monitor *m);
static int getmonitortags(Monitor *m);
static void setclientfields(Client *c);
static int getclientfields(Client *c);
static void setclienttags(Client *c);
static int getclienttags(Client *c);
static int getlayoutindex(const Layout *layout);
static void savewindowfloatposition(Client *c, Monitor *m);
static int restorewindowfloatposition(Client *c, Monitor *m);

View File

@ -1,26 +0,0 @@
static Arg
shift(const Arg *arg, int clients)
{
Arg shifted;
Client *c;
unsigned int tagmask = 0;
shifted.ui = selmon->tagset[selmon->seltags] & ~SPTAGMASK;
for (c = selmon->clients; c && clients; c = c->next) {
if (c == selmon->sel)
continue;
if (!(c->tags & SPTAGMASK))
tagmask |= c->tags;
}
do {
if (arg->i > 0) // left circular shift
shifted.ui = (shifted.ui << arg->i) | (shifted.ui >> (NUMTAGS - arg->i));
else // right circular shift
shifted.ui = (shifted.ui >> -arg->i) | (shifted.ui << (NUMTAGS + arg->i));
shifted.ui &= ~SPTAGMASK;
} while (tagmask && !(shifted.ui & tagmask));
return shifted;
}

View File

@ -1 +0,0 @@
static Arg shift(const Arg *arg, int clients);

View File

@ -1,7 +0,0 @@
void
shiftboth(const Arg *arg)
{
Arg shifted = shift(arg, 0);
tag(&shifted);
view(&shifted);
}

View File

@ -1 +0,0 @@
static void shiftboth(const Arg *arg);

View File

@ -1,6 +0,0 @@
void
shiftviewclients(const Arg *arg)
{
Arg shifted = shift(arg, 1);
view(&shifted);
}

View File

@ -1 +0,0 @@
static void shiftviewclients(const Arg *arg);

View File

@ -1,39 +0,0 @@
void
resizemousescroll(const Arg *arg)
{
int nw, nh;
Client *c;
Monitor *m;
XEvent ev;
int dw = *((int*)arg->v + 1);
int dh = *(int*)arg->v;
if (!(c = selmon->sel))
return;
if (c->isfullscreen && c->fakefullscreen != 1) /* no support resizing fullscreen windows by mouse */
return;
restack(selmon);
if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
return;
nw = MAX(c->w + dw, 1);
nh = MAX(c->h + dh, 1);
if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
&& c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
{
if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
&& (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
togglefloating(NULL);
}
if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
resize(c, c->x, c->y, nw, nh, 1);
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
XUngrabPointer(dpy, CurrentTime);
while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
sendmon(c, m);
selmon = m;
focus(NULL);
}
}

View File

@ -1,2 +0,0 @@
static void resizemousescroll(const Arg *arg);

View File

@ -1,34 +0,0 @@
void
transfer(const Arg *arg)
{
Client *c, *mtail = selmon->clients, *stail = NULL, *insertafter;
int transfertostack = 0, i, nmasterclients;
for (i = 0, c = selmon->clients; c; c = c->next) {
if (!ISVISIBLE(c) || c->isfloating) continue;
if (selmon->sel == c) { transfertostack = i < selmon->nmaster && selmon->nmaster != 0; }
if (i < selmon->nmaster) { nmasterclients++; mtail = c; }
stail = c;
i++;
}
if (!selmon->sel || selmon->sel->isfloating || i == 0) {
return;
} else if (transfertostack) {
selmon->nmaster = MIN(i, selmon->nmaster) - 1;
insertafter = stail;
} else {
selmon->nmaster = selmon->nmaster + 1;
insertafter = mtail;
}
if (insertafter != selmon->sel) {
detach(selmon->sel);
if (selmon->nmaster == 1 && !transfertostack) {
attach(selmon->sel); // Head prepend case
} else {
selmon->sel->next = insertafter->next;
insertafter->next = selmon->sel;
}
}
arrange(selmon);
}

View File

@ -1,2 +0,0 @@
static void transfer(const Arg *arg);

View File

@ -1,87 +0,0 @@
void
loadxrdb()
{
Display *display;
char * resm;
XrmDatabase xrdb;
char *type;
XrmValue value;
display = XOpenDisplay(NULL);
if (display != NULL) {
resm = XResourceManagerString(display);
if (resm != NULL) {
xrdb = XrmGetStringDatabase(resm);
if (xrdb != NULL) {
XRDB_LOAD_COLOR("dwm.normfgcolor", normfgcolor);
XRDB_LOAD_COLOR("dwm.normbgcolor", normbgcolor);
XRDB_LOAD_COLOR("dwm.normbordercolor", normbordercolor);
XRDB_LOAD_COLOR("dwm.normfloatcolor", normfloatcolor);
XRDB_LOAD_COLOR("dwm.selfgcolor", selfgcolor);
XRDB_LOAD_COLOR("dwm.selbgcolor", selbgcolor);
XRDB_LOAD_COLOR("dwm.selbordercolor", selbordercolor);
XRDB_LOAD_COLOR("dwm.selfloatcolor", selfloatcolor);
XRDB_LOAD_COLOR("dwm.titlenormfgcolor", titlenormfgcolor);
XRDB_LOAD_COLOR("dwm.titlenormbgcolor", titlenormbgcolor);
XRDB_LOAD_COLOR("dwm.titlenormbordercolor", titlenormbordercolor);
XRDB_LOAD_COLOR("dwm.titlenormfloatcolor", titlenormfloatcolor);
XRDB_LOAD_COLOR("dwm.titleselfgcolor", titleselfgcolor);
XRDB_LOAD_COLOR("dwm.titleselbgcolor", titleselbgcolor);
XRDB_LOAD_COLOR("dwm.titleselbordercolor", titleselbordercolor);
XRDB_LOAD_COLOR("dwm.titleselfloatcolor", titleselfloatcolor);
XRDB_LOAD_COLOR("dwm.tagsnormfgcolor", tagsnormfgcolor);
XRDB_LOAD_COLOR("dwm.tagsnormbgcolor", tagsnormbgcolor);
XRDB_LOAD_COLOR("dwm.tagsnormbordercolor", tagsnormbordercolor);
XRDB_LOAD_COLOR("dwm.tagsnormfloatcolor", tagsnormfloatcolor);
XRDB_LOAD_COLOR("dwm.tagsselfgcolor", tagsselfgcolor);
XRDB_LOAD_COLOR("dwm.tagsselbgcolor", tagsselbgcolor);
XRDB_LOAD_COLOR("dwm.tagsselbordercolor", tagsselbordercolor);
XRDB_LOAD_COLOR("dwm.tagsselfloatcolor", tagsselfloatcolor);
XRDB_LOAD_COLOR("dwm.hidnormfgcolor", hidnormfgcolor);
XRDB_LOAD_COLOR("dwm.hidnormbgcolor", hidnormbgcolor);
XRDB_LOAD_COLOR("dwm.hidselfgcolor", hidselfgcolor);
XRDB_LOAD_COLOR("dwm.hidselbgcolor", hidselbgcolor);
XRDB_LOAD_COLOR("dwm.urgfgcolor", urgfgcolor);
XRDB_LOAD_COLOR("dwm.urgbgcolor", urgbgcolor);
XRDB_LOAD_COLOR("dwm.urgbordercolor", urgbordercolor);
XRDB_LOAD_COLOR("dwm.urgfloatcolor", urgfloatcolor);
XRDB_LOAD_COLOR("color0", termcol0);
XRDB_LOAD_COLOR("color1", termcol1);
XRDB_LOAD_COLOR("color2", termcol2);
XRDB_LOAD_COLOR("color3", termcol3);
XRDB_LOAD_COLOR("color4", termcol4);
XRDB_LOAD_COLOR("color5", termcol5);
XRDB_LOAD_COLOR("color6", termcol6);
XRDB_LOAD_COLOR("color7", termcol7);
XRDB_LOAD_COLOR("color8", termcol8);
XRDB_LOAD_COLOR("color9", termcol9);
XRDB_LOAD_COLOR("color10", termcol10);
XRDB_LOAD_COLOR("color11", termcol11);
XRDB_LOAD_COLOR("color12", termcol12);
XRDB_LOAD_COLOR("color13", termcol13);
XRDB_LOAD_COLOR("color14", termcol14);
XRDB_LOAD_COLOR("color15", termcol15);
XrmDestroyDatabase(xrdb);
}
}
}
XCloseDisplay(display);
}
void
xrdb(const Arg *arg)
{
loadxrdb();
int i;
for (i = 0; i < LENGTH(colors); i++)
scheme[i] = drw_scm_create(drw, colors[i],
ColCount
);
arrange(NULL);
focus(NULL);
}

View File

@ -1,21 +0,0 @@
#include <X11/Xresource.h>
#define XRDB_LOAD_COLOR(R,V) if (XrmGetResource(xrdb, R, NULL, &type, &value) == True) { \
if (value.addr != NULL && strnlen(value.addr, 8) == 7 && value.addr[0] == '#') { \
int i = 1; \
for (; i <= 6; i++) { \
if (value.addr[i] < 48) break; \
if (value.addr[i] > 57 && value.addr[i] < 65) break; \
if (value.addr[i] > 70 && value.addr[i] < 97) break; \
if (value.addr[i] > 102) break; \
} \
if (i == 7) { \
strncpy(V, value.addr, 7); \
V[7] = '\0'; \
} \
} \
}
static void loadxrdb(void);
static void xrdb(const Arg *arg);

View File

@ -1,36 +0,0 @@
/* See LICENSE file for copyright and license details. */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
void
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
fputc(' ', stderr);
perror(NULL);
} else {
fputc('\n', stderr);
}
exit(1);
}
void *
ecalloc(size_t nmemb, size_t size)
{
void *p;
if (!(p = calloc(nmemb, size)))
die("calloc:");
return p;
}

View File

@ -1,19 +0,0 @@
/* See LICENSE file for copyright and license details. */
#ifndef MAX
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#endif
#ifndef MIN
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#endif
#define BETWEEN(X, A, B) ((A) <= (X) && (X) <= (B))
#ifdef _DEBUG
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG(...)
#endif
void die(const char *fmt, ...);
void *ecalloc(size_t nmemb, size_t size);

View File

@ -1,53 +0,0 @@
# Prerequisites
*.d
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
dwmblocks
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf

View File

@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -1,52 +0,0 @@
.POSIX:
BIN := dwmblocks
BUILD_DIR := build
SRC_DIR := src
INC_DIR := include
VERBOSE := 0
LIBS := xcb-atom
PREFIX := /usr/local
CFLAGS := -Ofast -I. -I$(INC_DIR) -std=c99
CFLAGS += -DBINARY=\"$(BIN)\" -D_POSIX_C_SOURCE=200809L
CFLAGS += -Wall -Wpedantic -Wextra -Wswitch-enum
CFLAGS += $(shell pkg-config --cflags $(LIBS))
LDLIBS := $(shell pkg-config --libs $(LIBS))
SRCS := $(wildcard $(SRC_DIR)/*.c)
OBJS := $(subst $(SRC_DIR)/,$(BUILD_DIR)/,$(SRCS:.c=.o))
INSTALL_DIR := $(DESTDIR)$(PREFIX)/bin
# Prettify output
PRINTF := @printf "%-8s %s\n"
ifeq ($(VERBOSE), 0)
Q := @
endif
all: $(BUILD_DIR)/$(BIN)
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c config.h
$Qmkdir -p $(@D)
$(PRINTF) "CC" $@
$Q$(COMPILE.c) -o $@ $<
$(BUILD_DIR)/$(BIN): $(OBJS)
$(PRINTF) "LD" $@
$Q$(LINK.o) $^ $(LDLIBS) -o $@
clean:
$(PRINTF) "CLEAN" $(BUILD_DIR)
$Q$(RM) $(BUILD_DIR)/*
install: $(BUILD_DIR)/$(BIN)
$(PRINTF) "INSTALL" $(INSTALL_DIR)/$(BIN)
$Qinstall -D -m 755 $< $(INSTALL_DIR)/$(BIN)
uninstall:
$(PRINTF) "RM" $(INSTALL_DIR)/$(BIN)
$Q$(RM) $(INSTALL_DIR)/$(BIN)
.PHONY: all clean install uninstall

View File

@ -1,4 +0,0 @@
# dwmblocks
Lightweight, Modular and Async status bar for [dwm](https://dwm.suckless.org)
Borrowed from [dwmblocks-async](https://github.com/UtkarshVerma/dwmblocks-async)

View File

@ -1,28 +0,0 @@
#ifndef CONFIG_H
#define CONFIG_H
// String used to delimit block outputs in the status.
#define DELIMITER " ^c#37474f^󰄽 ^d^"
// #define DELIMITER " ^c#37474f^^d^ "
// Maximum number of Unicode characters that a block can output.
#define MAX_BLOCK_OUTPUT_LENGTH 45
// Control whether blocks are clickable.
#define CLICKABLE_BLOCKS 1
// Control whether a leading delimiter should be prepended to the status.
#define LEADING_DELIMITER 0
// Control whether a trailing delimiter should be appended to the status.
#define TRAILING_DELIMITER 0
// Define blocks for the status feed as X(cmd, interval, signal).
#define BLOCKS(X) \
X("cat /tmp/recordingicon 2>/dev/null", 0, 9) \
X("sb-internet", 5, 4) \
X("sb-volume", 0, 8) \
X("sb-battery", 5, 21) \
X("sb-clock", 60, 1)
#endif // CONFIG_H

View File

@ -1,29 +0,0 @@
#ifndef BLOCK_H
#define BLOCK_H
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#include "config.h"
#include "util.h"
typedef struct {
const char *const command;
const unsigned int interval;
const int signal;
int pipe[PIPE_FD_COUNT];
char output[MAX_BLOCK_OUTPUT_LENGTH * UTF8_MAX_BYTE_COUNT + 1];
pid_t fork_pid;
} block;
block block_new(const char *const command, const unsigned int interval,
const int signal);
int block_init(block *const block);
int block_deinit(block *const block);
int block_execute(block *const block, const uint8_t button);
int block_update(block *const block);
bool block_must_run(const block *const block, const unsigned int time);
#endif // BLOCK_H

View File

@ -1,13 +0,0 @@
#ifndef CLI_H
#define CLI_H
#include <stdbool.h>
typedef struct {
bool is_debug_mode;
} cli_arguments;
int cli_init(cli_arguments* const args, const char* const argv[],
const int argc);
#endif // CLI_H

View File

@ -1,16 +0,0 @@
#ifndef MAIN_H
#define MAIN_H
#include <signal.h>
#include "config.h"
#include "util.h"
#define REFRESH_SIGNAL SIGUSR1
// Utilise C's adjacent string concatenation to count the number of blocks.
#define X(...) "."
enum { BLOCK_COUNT = LEN(BLOCKS(X)) - 1 };
#undef X
#endif // MAIN_H

View File

@ -1,33 +0,0 @@
#ifndef SIGNAL_HANDLER_H
#define SIGNAL_HANDLER_H
#include <signal.h>
#include "block.h"
#include "timer.h"
typedef sigset_t signal_set;
typedef int (*signal_refresh_callback)(block* const blocks,
const unsigned short block_count);
typedef int (*signal_timer_callback)(block* const blocks,
const unsigned short block_code,
timer* const timer);
typedef struct {
int fd;
const signal_refresh_callback refresh_callback;
const signal_timer_callback timer_callback;
block* const blocks;
const unsigned short block_count;
} signal_handler;
signal_handler signal_handler_new(
block* const blocks, const unsigned short block_count,
const signal_refresh_callback refresh_callback,
const signal_timer_callback timer_callback);
int signal_handler_init(signal_handler* const handler);
int signal_handler_deinit(signal_handler* const handler);
int signal_handler_process(signal_handler* const handler, timer* const timer);
#endif // SIGNAL_HANDLER_H

View File

@ -1,31 +0,0 @@
#ifndef STATUS_H
#define STATUS_H
#include <stdbool.h>
#include "block.h"
#include "config.h"
#include "main.h"
#include "util.h"
#include "x11.h"
typedef struct {
#define STATUS_LENGTH \
((BLOCK_COUNT * (MEMBER_LENGTH(block, output) - 1) + CLICKABLE_BLOCKS) + \
(BLOCK_COUNT - 1 + LEADING_DELIMITER + TRAILING_DELIMITER) * \
(LEN(DELIMITER) - 1) + \
1)
char current[STATUS_LENGTH];
char previous[STATUS_LENGTH];
#undef STATUS_LENGTH
const block* const blocks;
const unsigned short block_count;
} status;
status status_new(const block* const blocks, const unsigned short block_count);
bool status_update(status* const status);
int status_write(const status* const status, const bool is_debug_mode,
x11_connection* const connection);
#endif // STATUS_H

View File

@ -1,19 +0,0 @@
#ifndef TIMER_H
#define TIMER_H
#include <signal.h>
#include "block.h"
#define TIMER_SIGNAL SIGALRM
typedef struct {
unsigned int time;
const unsigned int tick;
const unsigned int reset_value;
} timer;
timer timer_new(const block *const blocks, const unsigned short block_count);
int timer_arm(timer *const timer);
#endif // TIMER_H

View File

@ -1,28 +0,0 @@
#ifndef UTIL_H
#define UTIL_H
#include <stddef.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define LEN(arr) (sizeof(arr) / sizeof((arr)[0]))
#define BIT(n) (1 << (n))
// NOLINTBEGIN(bugprone-macro-parentheses)
#define MEMBER_SIZE(type, member) sizeof(((type*)NULL)->member)
#define MEMBER_LENGTH(type, member) \
(MEMBER_SIZE(type, member) / MEMBER_SIZE(type, member[0]))
// NOLINTEND(bugprone-macro-parentheses)
#define UTF8_MAX_BYTE_COUNT 4
enum pipe_fd_index {
READ_END,
WRITE_END,
PIPE_FD_COUNT,
};
unsigned int gcd(unsigned int a, unsigned int b);
size_t truncate_utf8_string(char* const buffer, const size_t size,
const size_t char_limit);
#endif // UTIL_H

View File

@ -1,28 +0,0 @@
#ifndef WATCHER_H
#define WATCHER_H
#include <poll.h>
#include <stdbool.h>
#include "block.h"
#include "main.h"
enum watcher_fd_index {
SIGNAL_FD = BLOCK_COUNT,
WATCHER_FD_COUNT,
};
typedef struct pollfd watcher_fd;
typedef struct {
watcher_fd fds[WATCHER_FD_COUNT];
unsigned short active_blocks[BLOCK_COUNT];
unsigned short active_block_count;
bool got_signal;
} watcher;
int watcher_init(watcher *const watcher, const block *const blocks,
const unsigned short block_count, const int signal_fd);
int watcher_poll(watcher *const watcher, const int timeout_ms);
#endif // WATCHER_H

View File

@ -1,13 +0,0 @@
#ifndef X11_H
#define X11_H
#include <xcb/xcb.h>
typedef xcb_connection_t x11_connection;
x11_connection* x11_connection_open(void);
void x11_connection_close(x11_connection* const connection);
int x11_set_root_name(x11_connection* const connection,
const char* const name);
#endif // X11_H

View File

@ -1,158 +0,0 @@
#include "block.h"
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "config.h"
#include "util.h"
block block_new(const char *const command, const unsigned int interval,
const int signal) {
block block = {
.command = command,
.interval = interval,
.signal = signal,
.output = {[0] = '\0'},
.fork_pid = -1,
};
return block;
}
int block_init(block *const block) {
if (pipe(block->pipe) != 0) {
(void)fprintf(stderr,
"error: could not create a pipe for \"%s\" block\n",
block->command);
return 1;
}
return 0;
}
int block_deinit(block *const block) {
int status = close(block->pipe[READ_END]);
status |= close(block->pipe[WRITE_END]);
if (status != 0) {
(void)fprintf(stderr, "error: could not close \"%s\" block's pipe\n",
block->command);
return 1;
}
return 0;
}
int block_execute(block *const block, const uint8_t button) {
// Ensure only one child process exists per block at an instance.
if (block->fork_pid != -1) {
return 0;
}
block->fork_pid = fork();
if (block->fork_pid == -1) {
(void)fprintf(
stderr, "error: could not create a subprocess for \"%s\" block\n",
block->command);
return 1;
}
if (block->fork_pid == 0) {
const int write_fd = block->pipe[WRITE_END];
int status = close(block->pipe[READ_END]);
if (button != 0) {
char button_str[4];
(void)snprintf(button_str, LEN(button_str), "%hhu", button);
status |= setenv("BLOCK_BUTTON", button_str, 1);
}
const char null = '\0';
if (status != 0) {
(void)write(write_fd, &null, sizeof(null));
exit(EXIT_FAILURE);
}
FILE *const file = popen(block->command, "r");
if (file == NULL) {
(void)write(write_fd, &null, sizeof(null));
exit(EXIT_FAILURE);
}
// Ensure null-termination since fgets() will leave buffer untouched on
// no output.
char buffer[LEN(block->output)] = {[0] = null};
(void)fgets(buffer, LEN(buffer), file);
// Remove trailing newlines.
const size_t length = strcspn(buffer, "\n");
buffer[length] = null;
// Exit if command execution failed or if file could not be closed.
if (pclose(file) != 0) {
(void)write(write_fd, &null, sizeof(null));
exit(EXIT_FAILURE);
}
const size_t output_size =
truncate_utf8_string(buffer, LEN(buffer), MAX_BLOCK_OUTPUT_LENGTH);
(void)write(write_fd, buffer, output_size);
exit(EXIT_SUCCESS);
}
return 0;
}
int block_update(block *const block) {
char buffer[LEN(block->output)];
const ssize_t bytes_read =
read(block->pipe[READ_END], buffer, LEN(buffer));
if (bytes_read == -1) {
(void)fprintf(stderr,
"error: could not fetch output of \"%s\" block\n",
block->command);
return 2;
}
// Collect exit-status of the subprocess to avoid zombification.
int fork_status = 0;
if (waitpid(block->fork_pid, &fork_status, 0) == -1) {
(void)fprintf(stderr,
"error: could not obtain exit status for \"%s\" block\n",
block->command);
return 2;
}
block->fork_pid = -1;
if (fork_status != 0) {
(void)fprintf(stderr,
"error: \"%s\" block exited with non-zero status\n",
block->command);
return 1;
}
(void)strncpy(block->output, buffer, LEN(buffer));
return 0;
}
bool block_must_run(const block *const block, const unsigned int time) {
if (time == 0) {
return true;
}
if (block->interval == 0) {
return false;
}
return time % block->interval == 0;
}

View File

@ -1,30 +0,0 @@
#include "cli.h"
#include <getopt.h>
#include <stdbool.h>
#include <stdio.h>
int cli_init(cli_arguments *const args, const char *const argv[],
const int argc) {
args->is_debug_mode = false;
int opt = -1;
opterr = 0; // Suppress getopt's built-in invalid opt message
while ((opt = getopt(argc, (char *const *)argv, "dh")) != -1) {
switch (opt) {
case 'd':
args->is_debug_mode = true;
break;
case '?':
(void)fprintf(stderr, "error: unknown option `-%c'\n", optopt);
// fall through
case 'h':
// fall through
default:
(void)fprintf(stderr, "usage: %s [-d]\n", BINARY);
return 1;
}
}
return 0;
}

View File

@ -1,166 +0,0 @@
#include "main.h"
#include <stdbool.h>
#include <stddef.h>
#include "block.h"
#include "cli.h"
#include "config.h"
#include "signal-handler.h"
#include "status.h"
#include "timer.h"
#include "util.h"
#include "watcher.h"
#include "x11.h"
static int init_blocks(block *const blocks, const unsigned short block_count) {
for (unsigned short i = 0; i < block_count; ++i) {
block *const block = &blocks[i];
if (block_init(block) != 0) {
return 1;
}
}
return 0;
}
static int deinit_blocks(block *const blocks,
const unsigned short block_count) {
for (unsigned short i = 0; i < block_count; ++i) {
block *const block = &blocks[i];
if (block_deinit(block) != 0) {
return 1;
}
}
return 0;
}
static int execute_blocks(block *const blocks,
const unsigned short block_count,
const unsigned int time) {
for (unsigned short i = 0; i < block_count; ++i) {
block *const block = &blocks[i];
if (!block_must_run(block, time)) {
continue;
}
if (block_execute(&blocks[i], 0) != 0) {
return 1;
}
}
return 0;
}
static int trigger_event(block *const blocks, const unsigned short block_count,
timer *const timer) {
if (execute_blocks(blocks, block_count, timer->time) != 0) {
return 1;
}
if (timer_arm(timer) != 0) {
return 1;
}
return 0;
}
static int refresh_callback(block *const blocks,
const unsigned short block_count) {
if (execute_blocks(blocks, block_count, 0) != 0) {
return 1;
}
return 0;
}
static int event_loop(block *const blocks, const unsigned short block_count,
const bool is_debug_mode,
x11_connection *const connection,
signal_handler *const signal_handler) {
timer timer = timer_new(blocks, block_count);
// Kickstart the event loop with an initial execution.
if (trigger_event(blocks, block_count, &timer) != 0) {
return 1;
}
watcher watcher;
if (watcher_init(&watcher, blocks, block_count, signal_handler->fd) != 0) {
return 1;
}
status status = status_new(blocks, block_count);
bool is_alive = true;
while (is_alive) {
if (watcher_poll(&watcher, -1) != 0) {
return 1;
}
if (watcher.got_signal) {
is_alive = signal_handler_process(signal_handler, &timer) == 0;
}
for (unsigned short i = 0; i < watcher.active_block_count; ++i) {
(void)block_update(&blocks[watcher.active_blocks[i]]);
}
const bool has_status_changed = status_update(&status);
if (has_status_changed &&
status_write(&status, is_debug_mode, connection) != 0) {
return 1;
}
}
return 0;
}
int main(const int argc, const char *const argv[]) {
cli_arguments cli_args;
if (cli_init(&cli_args, argv, argc) != 0) {
return 1;
}
x11_connection *const connection = x11_connection_open();
if (connection == NULL) {
return 1;
}
#define BLOCK(command, interval, signal) block_new(command, interval, signal),
block blocks[BLOCK_COUNT] = {BLOCKS(BLOCK)};
#undef BLOCK
const unsigned short block_count = LEN(blocks);
int status = 0;
if (init_blocks(blocks, block_count) != 0) {
status = 1;
goto x11_close;
}
signal_handler signal_handler = signal_handler_new(
blocks, block_count, refresh_callback, trigger_event);
if (signal_handler_init(&signal_handler) != 0) {
status = 1;
goto deinit_blocks;
}
if (event_loop(blocks, block_count, cli_args.is_debug_mode, connection,
&signal_handler) != 0) {
status = 1;
}
if (signal_handler_deinit(&signal_handler) != 0) {
status = 1;
}
deinit_blocks:
if (deinit_blocks(blocks, block_count) != 0) {
status = 1;
}
x11_close:
x11_connection_close(connection);
return status;
}

View File

@ -1,124 +0,0 @@
#include "signal-handler.h"
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/signalfd.h>
#include <sys/types.h>
#include <unistd.h>
#include "block.h"
#include "main.h"
#include "timer.h"
typedef struct signalfd_siginfo signal_info;
signal_handler signal_handler_new(
block *const blocks, const unsigned short block_count,
const signal_refresh_callback refresh_callback,
const signal_timer_callback timer_callback) {
signal_handler handler = {
.refresh_callback = refresh_callback,
.timer_callback = timer_callback,
.blocks = blocks,
.block_count = block_count,
};
return handler;
}
int signal_handler_init(signal_handler *const handler) {
signal_set set;
(void)sigemptyset(&set);
// Handle user-generated signal for refreshing the status.
(void)sigaddset(&set, REFRESH_SIGNAL);
// Handle SIGALRM generated by the timer.
(void)sigaddset(&set, TIMER_SIGNAL);
// Handle termination signals.
(void)sigaddset(&set, SIGINT);
(void)sigaddset(&set, SIGTERM);
for (unsigned short i = 0; i < handler->block_count; ++i) {
const block *const block = &handler->blocks[i];
if (block->signal > 0) {
if (sigaddset(&set, SIGRTMIN + block->signal) != 0) {
(void)fprintf(
stderr,
"error: invalid or unsupported signal specified for "
"\"%s\" block\n",
block->command);
return 1;
}
}
}
// Create a signal file descriptor for epoll to watch.
handler->fd = signalfd(-1, &set, 0);
if (handler->fd == -1) {
(void)fprintf(stderr,
"error: could not create file descriptor for signals\n");
return 1;
}
// Block all realtime and handled signals.
for (int i = SIGRTMIN; i <= SIGRTMAX; ++i) {
(void)sigaddset(&set, i);
}
(void)sigprocmask(SIG_BLOCK, &set, NULL);
return 0;
}
int signal_handler_deinit(signal_handler *const handler) {
if (close(handler->fd) != 0) {
(void)fprintf(stderr,
"error: could not close signal file descriptor\n");
return 1;
}
return 0;
}
int signal_handler_process(signal_handler *const handler, timer *const timer) {
signal_info info;
const ssize_t bytes_read = read(handler->fd, &info, sizeof(info));
if (bytes_read == -1) {
(void)fprintf(stderr, "error: could not read info of incoming signal");
return 1;
}
const int signal = (int)info.ssi_signo;
switch (signal) {
case TIMER_SIGNAL:
if (handler->timer_callback(handler->blocks, handler->block_count,
timer) != 0) {
return 1;
}
return 0;
case REFRESH_SIGNAL:
if (handler->refresh_callback(handler->blocks,
handler->block_count) != 0) {
return 1;
}
return 0;
case SIGTERM:
// fall through
case SIGINT:
return 1;
}
for (unsigned short i = 0; i < handler->block_count; ++i) {
block *const block = &handler->blocks[i];
if (block->signal == signal - SIGRTMIN) {
const uint8_t button = (uint8_t)info.ssi_int;
block_execute(block, button);
break;
}
}
return 0;
}

View File

@ -1,77 +0,0 @@
#include "status.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "block.h"
#include "config.h"
#include "util.h"
#include "x11.h"
static bool has_status_changed(const status *const status) {
return strcmp(status->current, status->previous) != 0;
}
status status_new(const block *const blocks,
const unsigned short block_count) {
status status = {
.current = {[0] = '\0'},
.previous = {[0] = '\0'},
.blocks = blocks,
.block_count = block_count,
};
return status;
}
bool status_update(status *const status) {
(void)strncpy(status->previous, status->current, LEN(status->current));
status->current[0] = '\0';
for (unsigned short i = 0; i < status->block_count; ++i) {
const block *const block = &status->blocks[i];
if (strlen(block->output) > 0) {
#if LEADING_DELIMITER
(void)strncat(status->current, DELIMITER, LEN(DELIMITER));
#else
if (status->current[0] != '\0') {
(void)strncat(status->current, DELIMITER, LEN(DELIMITER));
}
#endif
#if CLICKABLE_BLOCKS
if (block->signal > 0) {
const char signal[] = {(char)block->signal, '\0'};
(void)strncat(status->current, signal, LEN(signal));
}
#endif
(void)strncat(status->current, block->output, LEN(block->output));
}
}
#if TRAILING_DELIMITER
if (status->current[0] != '\0') {
(void)strncat(status->current, DELIMITER, LEN(DELIMITER));
}
#endif
return has_status_changed(status);
}
int status_write(const status *const status, const bool is_debug_mode,
x11_connection *const connection) {
if (is_debug_mode) {
(void)printf("%s\n", status->current);
return 0;
}
if (x11_set_root_name(connection, status->current) != 0) {
return 1;
}
return 0;
}

View File

@ -1,57 +0,0 @@
#include "timer.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include "block.h"
#include "util.h"
static unsigned int compute_tick(const block *const blocks,
const unsigned short block_count) {
unsigned int tick = 0;
for (unsigned short i = 0; i < block_count; ++i) {
const block *const block = &blocks[i];
tick = gcd(block->interval, tick);
}
return tick;
}
static unsigned int compute_reset_value(const block *const blocks,
const unsigned short block_count) {
unsigned int reset_value = 1;
for (unsigned short i = 0; i < block_count; ++i) {
const block *const block = &blocks[i];
reset_value = MAX(block->interval, reset_value);
}
return reset_value;
}
timer timer_new(const block *const blocks, const unsigned short block_count) {
timer timer = {
.time = 0,
.tick = compute_tick(blocks, block_count),
.reset_value = compute_reset_value(blocks, block_count),
};
return timer;
}
int timer_arm(timer *const timer) {
errno = 0;
(void)alarm(timer->tick);
if (errno != 0) {
(void)fprintf(stderr, "error: could not arm timer\n");
return 1;
}
// Wrap `time` to the interval [1, reset_value].
timer->time = (timer->time + timer->tick) % timer->reset_value + 1;
return 0;
}

View File

@ -1,49 +0,0 @@
#include "util.h"
#define UTF8_MULTIBYTE_BIT BIT(7)
unsigned int gcd(unsigned int a, unsigned int b) {
while (b > 0) {
const unsigned int temp = a % b;
a = b;
b = temp;
}
return a;
}
size_t truncate_utf8_string(char* const buffer, const size_t size,
const size_t char_limit) {
size_t char_count = 0;
size_t i = 0;
while (char_count < char_limit) {
char ch = buffer[i];
if (ch == '\0') {
break;
}
unsigned short skip = 1;
// Multibyte unicode character.
if ((ch & UTF8_MULTIBYTE_BIT) != 0) {
// Skip continuation bytes.
ch <<= 1;
while ((ch & UTF8_MULTIBYTE_BIT) != 0) {
ch <<= 1;
++skip;
}
}
// Avoid buffer overflow.
if (i + skip >= size) {
break;
}
++char_count;
i += skip;
}
buffer[i] = '\0';
return i + 1;
}

View File

@ -1,69 +0,0 @@
#include "watcher.h"
#include <errno.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include "block.h"
#include "util.h"
static bool watcher_fd_is_readable(const watcher_fd* const watcher_fd) {
return (watcher_fd->revents & POLLIN) != 0;
}
int watcher_init(watcher* const watcher, const block* const blocks,
const unsigned short block_count, const int signal_fd) {
if (signal_fd == -1) {
(void)fprintf(
stderr,
"error: invalid signal file descriptor passed to watcher\n");
return 1;
}
watcher_fd* const fd = &watcher->fds[SIGNAL_FD];
fd->fd = signal_fd;
fd->events = POLLIN;
for (unsigned short i = 0; i < block_count; ++i) {
const int block_fd = blocks[i].pipe[READ_END];
if (block_fd == -1) {
(void)fprintf(
stderr,
"error: invalid block file descriptors passed to watcher\n");
return 1;
}
watcher_fd* const fd = &watcher->fds[i];
fd->fd = block_fd;
fd->events = POLLIN;
}
return 0;
}
int watcher_poll(watcher* watcher, const int timeout_ms) {
int event_count = poll(watcher->fds, LEN(watcher->fds), timeout_ms);
// Don't return non-zero status for signal interruptions.
if (event_count == -1 && errno != EINTR) {
(void)fprintf(stderr, "error: watcher could not poll blocks\n");
return 1;
}
watcher->got_signal = watcher_fd_is_readable(&watcher->fds[SIGNAL_FD]);
watcher->active_block_count = event_count - (int)watcher->got_signal;
unsigned short i = 0;
unsigned short j = 0;
while (i < event_count && j < LEN(watcher->active_blocks)) {
if (watcher_fd_is_readable(&watcher->fds[j])) {
watcher->active_blocks[i] = j;
++i;
}
++j;
}
return 0;
}

View File

@ -1,44 +0,0 @@
#include "x11.h"
#include <stdio.h>
#include <string.h>
#include <xcb/xcb.h>
#include <xcb/xproto.h>
x11_connection *x11_connection_open(void) {
xcb_connection_t *const connection = xcb_connect(NULL, NULL);
if (xcb_connection_has_error(connection)) {
(void)fprintf(stderr, "error: could not connect to X server\n");
return NULL;
}
return connection;
}
void x11_connection_close(xcb_connection_t *const connection) {
xcb_disconnect(connection);
}
int x11_set_root_name(x11_connection *const connection, const char *name) {
xcb_screen_t *const screen =
xcb_setup_roots_iterator(xcb_get_setup(connection)).data;
const xcb_window_t root_window = screen->root;
const unsigned short name_format = 8;
const xcb_void_cookie_t cookie = xcb_change_property(
connection, XCB_PROP_MODE_REPLACE, root_window, XCB_ATOM_WM_NAME,
XCB_ATOM_STRING, name_format, strlen(name), name);
xcb_generic_error_t *error = xcb_request_check(connection, cookie);
if (error != NULL) {
(void)fprintf(stderr, "error: could not set X root name\n");
return 1;
}
if (xcb_flush(connection) <= 0) {
(void)fprintf(stderr, "error: could not flush X output buffer\n");
return 1;
}
return 0;
}

View File

@ -1,2 +0,0 @@
slock
*.o

View File

@ -1,25 +0,0 @@
MIT/X Consortium License
© 2015-2016 Markus Teich <markus.teich@stusta.mhn.de>
© 2014 Dimitris Papastamos <sin@2f30.org>
© 2006-2014 Anselm R Garbe <anselm@garbe.us>
© 2014-2016 Laslo Hunhold <dev@frign.de>
© 2016-2023 Hiltjo Posthuma <hiltjo@codemadness.org>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,47 +0,0 @@
# slock - simple screen locker
# See LICENSE file for copyright and license details.
include config.mk
SRC = slock.c ${COMPATSRC}
OBJ = ${SRC:.c=.o}
all: slock
.c.o:
${CC} -c ${CFLAGS} $<
${OBJ}: config.h config.mk arg.h util.h
config.h:
cp config.def.h $@
slock: ${OBJ}
${CC} -o $@ ${OBJ} ${LDFLAGS}
clean:
rm -f slock ${OBJ} slock-${VERSION}.tar.gz
dist: clean
mkdir -p slock-${VERSION}
cp -R LICENSE Makefile README slock.1 config.mk \
${SRC} config.def.h arg.h util.h slock-${VERSION}
tar -cf slock-${VERSION}.tar slock-${VERSION}
gzip slock-${VERSION}.tar
rm -rf slock-${VERSION}
install: all
mkdir -p ${DESTDIR}${PREFIX}/bin
cp -f slock ${DESTDIR}${PREFIX}/bin
chmod 755 ${DESTDIR}${PREFIX}/bin/slock
chmod u+s ${DESTDIR}${PREFIX}/bin/slock
echo installing manual page to ${DESTDIR}${MANPREFIX}/man1
mkdir -p ${DESTDIR}${MANPREFIX}/man1
sed "s/VERSION/${VERSION}/g" <slock.1 >${DESTDIR}${MANPREFIX}/man1/slock.1
chmod 644 ${DESTDIR}${MANPREFIX}/man1/slock.1
uninstall:
rm -f ${DESTDIR}${PREFIX}/bin/slock
rm -f ${DESTDIR}${MANPREFIX}/man1/slock.1
.PHONY: all clean dist install uninstall

View File

@ -1,12 +0,0 @@
# slock - simple screen locker
This build of slock was generated using [slock-flexipatch](https://github.com/bakkeby/st-flexipatch.git) and finalized by [flexipatch-finalizer](https://github.com/bakkeby/flexipatch-finalizer).
## Patches
- blur pixelated screen [link](https://tools.suckless.org/slock/patches/blur-pixelated-screen)
- controlclear [link](https://tools.suckless.org/slock/patches/control-clear)
- dpms [link](https://tools.suckless.org/slock/patches/dpms)
- dwm logo [link](https://tools.suckless.org/slock/patches/failure-command)
- mediakeys [link](https://tools.suckless.org/slock/patches/mediakeys)
- xresources [link](https://tools.suckless.org/slock/patches/xresources)

View File

@ -1,65 +0,0 @@
/*
* Copy me if you can.
* by 20h
*/
#ifndef ARG_H__
#define ARG_H__
extern char *argv0;
/* use main(int argc, char *argv[]) */
#define ARGBEGIN for (argv0 = *argv, argv++, argc--;\
argv[0] && argv[0][0] == '-'\
&& argv[0][1];\
argc--, argv++) {\
char argc_;\
char **argv_;\
int brk_;\
if (argv[0][1] == '-' && argv[0][2] == '\0') {\
argv++;\
argc--;\
break;\
}\
for (brk_ = 0, argv[0]++, argv_ = argv;\
argv[0][0] && !brk_;\
argv[0]++) {\
if (argv_ != argv)\
break;\
argc_ = argv[0][0];\
switch (argc_)
/* Handles obsolete -NUM syntax */
#define ARGNUM case '0':\
case '1':\
case '2':\
case '3':\
case '4':\
case '5':\
case '6':\
case '7':\
case '8':\
case '9'
#define ARGEND }\
}
#define ARGC() argc_
#define ARGNUMF() (brk_ = 1, estrtonum(argv[0], 0, INT_MAX))
#define EARGF(x) ((argv[0][1] == '\0' && argv[1] == NULL)?\
((x), abort(), (char *)0) :\
(brk_ = 1, (argv[0][1] != '\0')?\
(&argv[0][1]) :\
(argc--, argv++, argv[0])))
#define ARGF() ((argv[0][1] == '\0' && argv[1] == NULL)?\
(char *)0 :\
(brk_ = 1, (argv[0][1] != '\0')?\
(&argv[0][1]) :\
(argc--, argv++, argv[0])))
#define LNGARG() &argv[0][0]
#endif

View File

@ -1,51 +0,0 @@
// user and group to drop privileges to
static const char *user = "nobody";
static const char *group = "nobody"; // use "nobody" for arch
static const char *colorname[NUMCOLS] = {
[INIT] = "black", // after initialization
[INPUT] = "#005577", // during input
[FAILED] = "#CC3333", // wrong password
};
// insert grid pattern with scale 1:1, the size can be changed with logosize
static const int logosize = 8;
static const int logow =
12; // grid width and height for right center alignment*/
static const int logoh = 6;
static XRectangle rectangles[] = {
// x y w h
{ 0, 3, 1, 3 },
{ 1, 3, 2, 1 },
{ 0, 5, 8, 1 },
{ 3, 0, 1, 5 },
{ 5, 3, 1, 2 },
{ 7, 3, 1, 2 },
{ 8, 3, 4, 1 },
{ 9, 4, 1, 2 },
{ 11, 4, 1, 2 },
};
// Xresources preferences to load at startup
ResourcePref resources[] = {
{"locked", STRING, &colorname[INIT]},
{"input", STRING, &colorname[INPUT]},
{"failed", STRING, &colorname[FAILED]},
};
// treat a cleared input like a wrong password (color)
static const int failonclear = 1;
// Enable blur
#define BLUR
static const int blurRadius = 5; // Set blur radius
// Enable Pixelation
// #define PIXELATION
static const int pixelSize = 10; // Set pixelation radius
// allow control key to trigger fail on clear
static const int controlkeyclear = 1;
// time in seconds before the monitor shuts down
static const int monitortime = 5;

View File

@ -1,45 +0,0 @@
# slock version
VERSION = 1.4
# Customize below to fit your system
# paths
PREFIX = /usr/local
MANPREFIX = ${PREFIX}/share/man
X11INC = /usr/X11R6/include
X11LIB = /usr/X11R6/lib
# Uncomment for BSD
#BSD=-D_BSD_SOURCE
# Uncomment for NetBSD
#NETBSD=-D_NETBSD_SOURCE
# Uncomment for message patch / MESSAGE_PATCH / COLORMESSAGE_PATCH / DWM_LOGO_PATCH
XINERAMA=-lXinerama
XINERAMAFLAGS = -DXINERAMA
# Uncomment for pam auth patch / PAMAUTH_PATCH
#PAM=-lpam
# Uncomment for blur pixelated screen and background image patches / BLUR_PIXELATED_SCREEN_PATCH, BACKGROUND_IMAGE_PATCH
IMLIB=-lImlib2
# includes and libs
INCS = -I. -I/usr/include -I${X11INC}
LIBS = -L/usr/lib -lc -lcrypt -L${X11LIB} -lX11 -lXext -lXrandr ${XINERAMA} ${PAM} ${IMLIB}
# flags
CPPFLAGS = -DVERSION=\"${VERSION}\" -D_DEFAULT_SOURCE -DHAVE_SHADOW_H ${XINERAMAFLAGS} ${BSD} ${NETBSD}
CFLAGS = -std=c99 -pedantic -Wall -Os ${INCS} ${CPPFLAGS}
LDFLAGS = -s ${LIBS}
COMPATSRC = explicit_bzero.c
# On OpenBSD and Darwin remove -lcrypt from LIBS
#LIBS = -L/usr/lib -lc -L${X11LIB} -lX11 -lXext -lXrandr
# On *BSD remove -DHAVE_SHADOW_H from CPPFLAGS
# On NetBSD add -D_NETBSD_SOURCE to CPPFLAGS
#CPPFLAGS = -DVERSION=\"${VERSION}\" -D_BSD_SOURCE -D_NETBSD_SOURCE
# On OpenBSD set COMPATSRC to empty
#COMPATSRC =

View File

@ -1,19 +0,0 @@
/* $OpenBSD: explicit_bzero.c,v 1.3 2014/06/21 02:34:26 matthew Exp $ */
/*
* Public domain.
* Written by Matthew Dempsky.
*/
#include <string.h>
__attribute__((weak)) void
__explicit_bzero_hook(void *buf, size_t len)
{
}
void
explicit_bzero(void *buf, size_t len)
{
memset(buf, 0, len);
__explicit_bzero_hook(buf, len);
}

View File

@ -1,70 +0,0 @@
#include <Imlib2.h>
Imlib_Image image;
void
render_lock_image(Display *dpy, struct lock *lock, Imlib_Image image)
{
if (image) {
lock->bgmap = XCreatePixmap(dpy, lock->root, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen), DefaultDepth(dpy, lock->screen));
imlib_context_set_image(image);
imlib_context_set_display(dpy);
imlib_context_set_visual(DefaultVisual(dpy, lock->screen));
imlib_context_set_colormap(DefaultColormap(dpy, lock->screen));
imlib_context_set_drawable(lock->bgmap);
imlib_render_image_on_drawable(0, 0);
imlib_free_image();
}
}
void
create_lock_image(Display *dpy)
{
/* Create screenshot Image */
Screen *scr = ScreenOfDisplay(dpy, DefaultScreen(dpy));
image = imlib_create_image(scr->width,scr->height);
imlib_context_set_image(image);
imlib_context_set_display(dpy);
imlib_context_set_visual(DefaultVisual(dpy,0));
imlib_context_set_drawable(RootWindow(dpy,XScreenNumberOfScreen(scr)));
imlib_copy_drawable_to_image(0,0,0,scr->width,scr->height,0,0,1);
#ifdef BLUR
/* Blur function */
imlib_image_blur(blurRadius);
#endif // BLUR
#ifdef PIXELATION
/* Pixelation */
int width = scr->width;
int height = scr->height;
for (int y = 0; y < height; y += pixelSize) {
for (int x = 0; x < width; x += pixelSize) {
int red = 0;
int green = 0;
int blue = 0;
Imlib_Color pixel;
Imlib_Color* pp;
pp = &pixel;
for (int j = 0; j < pixelSize && j < height; j++) {
for (int i = 0; i < pixelSize && i < width; i++) {
imlib_image_query_pixel(x + i, y + j, pp);
red += pixel.red;
green += pixel.green;
blue += pixel.blue;
}
}
red /= (pixelSize * pixelSize);
green /= (pixelSize * pixelSize);
blue /= (pixelSize * pixelSize);
imlib_context_set_color(red, green, blue, pixel.alpha);
imlib_image_fill_rectangle(x, y, pixelSize, pixelSize);
red = 0;
green = 0;
blue = 0;
}
}
#endif
}

View File

@ -1,4 +0,0 @@
#include <Imlib2.h>
static void create_lock_image(Display *dpy);
static void render_lock_image(Display *dpy, struct lock *lock, Imlib_Image image);

View File

@ -1,24 +0,0 @@
static void
resizerectangles(struct lock *lock)
{
int i;
for (i = 0; i < LENGTH(rectangles); i++){
lock->rectangles[i].x = (rectangles[i].x * logosize)
+ lock->xoff + ((lock->mw) / 2) - (logow / 2 * logosize);
lock->rectangles[i].y = (rectangles[i].y * logosize)
+ lock->yoff + ((lock->mh) / 2) - (logoh / 2 * logosize);
lock->rectangles[i].width = rectangles[i].width * logosize;
lock->rectangles[i].height = rectangles[i].height * logosize;
}
}
static void
drawlogo(Display *dpy, struct lock *lock, int color)
{
lock->drawable = lock->bgmap;
XSetForeground(dpy, lock->gc, lock->colors[color]);
XFillRectangles(dpy, lock->drawable, lock->gc, lock->rectangles, LENGTH(rectangles));
XCopyArea(dpy, lock->drawable, lock->win, lock->gc, 0, 0, lock->x, lock->y, 0, 0);
XSync(dpy, False);
}

View File

@ -1,2 +0,0 @@
static void resizerectangles(struct lock *lock);
static void drawlogo(Display *dpy, struct lock *lock, int color);

View File

@ -1,6 +0,0 @@
/* Patches */
#include "blur_pixelated_screen.c"
#include "dwmlogo.c"
#include "xresources.c"

View File

@ -1,5 +0,0 @@
/* Patches */
#include "blur_pixelated_screen.h"
#include "dwmlogo.h"

View File

@ -1,53 +0,0 @@
#include <X11/Xresource.h>
#include <math.h>
int
resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
{
char **sdst = dst;
int *idst = dst;
float *fdst = dst;
char fullname[256];
char fullclass[256];
char *type;
XrmValue ret;
snprintf(fullname, sizeof(fullname), "%s.%s", "slock", name);
snprintf(fullclass, sizeof(fullclass), "%s.%s", "Slock", name);
fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0';
XrmGetResource(db, fullname, fullclass, &type, &ret);
if (ret.addr == NULL || strncmp("String", type, 64))
return 1;
switch (rtype) {
case STRING:
*sdst = ret.addr;
break;
case INTEGER:
*idst = strtoul(ret.addr, NULL, 10);
break;
case FLOAT:
*fdst = strtof(ret.addr, NULL);
break;
}
return 0;
}
void
config_init(Display *dpy)
{
char *resm;
XrmDatabase db;
ResourcePref *p;
XrmInitialize();
resm = XResourceManagerString(dpy);
if (!resm)
return;
db = XrmGetStringDatabase(resm);
for (p = resources; p < resources + LENGTH(resources); p++)
resource_load(db, p->name, p->type, p->dst);
}

View File

@ -1,45 +0,0 @@
.Dd October 6, 2023
.Dt SLOCK 1
.Os
.Sh NAME
.Nm slock
.Nd simple X screen locker
.Sh SYNOPSIS
.Nm
.Op Fl v
.Op Ar cmd Op Ar arg ...
.Sh DESCRIPTION
.Nm
is a simple X screen locker.
If provided,
.Ar cmd
is executed after the screen has been locked.
.Pp
The options are as follows:
.Bl -tag -width Ds
.It Fl v
Print version information to stdout and exit.
.El
.Sh EXIT STATUS
.Ex -std
.Sh EXAMPLES
$
.Nm
/usr/sbin/s2ram
.Sh SECURITY CONSIDERATIONS
To make sure a locked screen can not be bypassed by switching VTs
or killing the X server with Ctrl+Alt+Backspace, it is recommended
to disable both in
.Xr xorg.conf 5
for maximum security:
.Bd -literal
Section "ServerFlags"
Option "DontVTSwitch" "True"
Option "DontZap" "True"
EndSection
.Ed
.Sh CUSTOMIZATION
.Nm
can be customized by creating a custom config.h from config.def.h and
(re)compiling the source code.
This keeps it fast, secure and simple.

View File

@ -1,497 +0,0 @@
/* See LICENSE file for license details. */
#define _XOPEN_SOURCE 500
#define LENGTH(X) (sizeof X / sizeof X[0])
#if HAVE_SHADOW_H
#include <shadow.h>
#endif
#include <ctype.h>
#include <errno.h>
#include <grp.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <X11/extensions/Xrandr.h>
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XF86keysym.h>
#include <X11/extensions/dpms.h>
#ifdef XINERAMA
#include <X11/extensions/Xinerama.h>
#endif
#include "arg.h"
#include "util.h"
char *argv0;
enum {
INIT,
INPUT,
FAILED,
NUMCOLS
};
/* Xresources preferences */
enum resource_type {
STRING = 0,
INTEGER = 1,
FLOAT = 2
};
typedef struct {
char *name;
enum resource_type type;
void *dst;
} ResourcePref;
#include "config.h"
struct lock {
int screen;
Window root, win;
Pixmap pmap;
Pixmap bgmap;
unsigned long colors[NUMCOLS];
unsigned int x, y;
unsigned int xoff, yoff, mw, mh;
Drawable drawable;
GC gc;
XRectangle rectangles[LENGTH(rectangles)];
};
struct xrandr {
int active;
int evbase;
int errbase;
};
#include "patch/include.h"
static void
die(const char *errstr, ...)
{
va_list ap;
va_start(ap, errstr);
vfprintf(stderr, errstr, ap);
va_end(ap);
exit(1);
}
#include "patch/include.c"
#ifdef __linux__
#include <fcntl.h>
#include <linux/oom.h>
static void
dontkillme(void)
{
FILE *f;
const char oomfile[] = "/proc/self/oom_score_adj";
if (!(f = fopen(oomfile, "w"))) {
if (errno == ENOENT)
return;
die("slock: fopen %s: %s\n", oomfile, strerror(errno));
}
fprintf(f, "%d", OOM_SCORE_ADJ_MIN);
if (fclose(f)) {
if (errno == EACCES)
die("slock: unable to disable OOM killer. "
"Make sure to suid or sgid slock.\n");
else
die("slock: fclose %s: %s\n", oomfile, strerror(errno));
}
}
#endif
static const char *
gethash(void)
{
const char *hash;
struct passwd *pw;
/* Check if the current user has a password entry */
errno = 0;
if (!(pw = getpwuid(getuid()))) {
if (errno)
die("slock: getpwuid: %s\n", strerror(errno));
else
die("slock: cannot retrieve password entry\n");
}
hash = pw->pw_passwd;
#if HAVE_SHADOW_H
if (!strcmp(hash, "x")) {
struct spwd *sp;
if (!(sp = getspnam(pw->pw_name)))
die("slock: getspnam: cannot retrieve shadow entry. "
"Make sure to suid or sgid slock.\n");
hash = sp->sp_pwdp;
}
#else
if (!strcmp(hash, "*")) {
#ifdef __OpenBSD__
if (!(pw = getpwuid_shadow(getuid())))
die("slock: getpwnam_shadow: cannot retrieve shadow entry. "
"Make sure to suid or sgid slock.\n");
hash = pw->pw_passwd;
#else
die("slock: getpwuid: cannot retrieve shadow entry. "
"Make sure to suid or sgid slock.\n");
#endif /* __OpenBSD__ */
}
#endif /* HAVE_SHADOW_H */
return hash;
}
static void
readpw(Display *dpy, struct xrandr *rr, struct lock **locks, int nscreens,
const char *hash)
{
XRRScreenChangeNotifyEvent *rre;
char buf[32], passwd[256], *inputhash;
int num, screen, running, failure, oldc;
unsigned int len, color;
KeySym ksym;
XEvent ev;
len = 0;
running = 1;
failure = 0;
oldc = INIT;
while (running && !XNextEvent(dpy, &ev))
{
if (ev.type == KeyPress) {
explicit_bzero(&buf, sizeof(buf));
num = XLookupString(&ev.xkey, buf, sizeof(buf), &ksym, 0);
if (IsKeypadKey(ksym)) {
if (ksym == XK_KP_Enter)
ksym = XK_Return;
else if (ksym >= XK_KP_0 && ksym <= XK_KP_9)
ksym = (ksym - XK_KP_0) + XK_0;
}
if (IsFunctionKey(ksym) ||
IsKeypadKey(ksym) ||
IsMiscFunctionKey(ksym) ||
IsPFKey(ksym) ||
IsPrivateKeypadKey(ksym))
continue;
switch (ksym) {
case XK_Return:
passwd[len] = '\0';
errno = 0;
if (!(inputhash = crypt(passwd, hash)))
fprintf(stderr, "slock: crypt: %s\n", strerror(errno));
else
running = !!strcmp(inputhash, hash);
if (running) {
XBell(dpy, 100);
failure = 1;
}
explicit_bzero(&passwd, sizeof(passwd));
len = 0;
break;
case XK_Escape:
explicit_bzero(&passwd, sizeof(passwd));
len = 0;
break;
case XK_BackSpace:
if (len)
passwd[--len] = '\0';
break;
case XF86XK_AudioLowerVolume:
case XF86XK_AudioMute:
case XF86XK_AudioRaiseVolume:
case XF86XK_AudioPlay:
case XF86XK_AudioStop:
case XF86XK_AudioPrev:
case XF86XK_AudioNext:
XSendEvent(dpy, DefaultRootWindow(dpy), True, KeyPressMask, &ev);
break;
default:
if (controlkeyclear && iscntrl((int)buf[0]))
continue;
if (num && (len + num < sizeof(passwd)))
{
memcpy(passwd + len, buf, num);
len += num;
}
break;
}
color = len ? INPUT : ((failure || failonclear) ? FAILED : INIT);
if (running && oldc != color) {
for (screen = 0; screen < nscreens; screen++) {
drawlogo(dpy, locks[screen], color);
}
oldc = color;
}
} else if (rr->active && ev.type == rr->evbase + RRScreenChangeNotify) {
rre = (XRRScreenChangeNotifyEvent*)&ev;
for (screen = 0; screen < nscreens; screen++) {
if (locks[screen]->win == rre->window) {
if (rre->rotation == RR_Rotate_90 ||
rre->rotation == RR_Rotate_270)
XResizeWindow(dpy, locks[screen]->win,
rre->height, rre->width);
else
XResizeWindow(dpy, locks[screen]->win,
rre->width, rre->height);
XClearWindow(dpy, locks[screen]->win);
break;
}
}
} else {
for (screen = 0; screen < nscreens; screen++)
XRaiseWindow(dpy, locks[screen]->win);
}
}
}
static struct lock *
lockscreen(Display *dpy, struct xrandr *rr, int screen)
{
char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
int i, ptgrab, kbgrab;
struct lock *lock;
XColor color, dummy;
XSetWindowAttributes wa;
Cursor invisible;
#ifdef XINERAMA
XineramaScreenInfo *info;
int n;
#endif
if (dpy == NULL || screen < 0 || !(lock = malloc(sizeof(struct lock))))
return NULL;
lock->screen = screen;
lock->root = RootWindow(dpy, lock->screen);
render_lock_image(dpy, lock, image);
for (i = 0; i < NUMCOLS; i++) {
XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen),
colorname[i], &color, &dummy);
lock->colors[i] = color.pixel;
}
lock->x = DisplayWidth(dpy, lock->screen);
lock->y = DisplayHeight(dpy, lock->screen);
#ifdef XINERAMA
if ((info = XineramaQueryScreens(dpy, &n))) {
lock->xoff = info[0].x_org;
lock->yoff = info[0].y_org;
lock->mw = info[0].width;
lock->mh = info[0].height;
} else
#endif // XINERAMA
{
lock->xoff = lock->yoff = 0;
lock->mw = lock->x;
lock->mh = lock->y;
}
lock->drawable = XCreatePixmap(dpy, lock->root, lock->x, lock->y, DefaultDepth(dpy, screen));
lock->gc = XCreateGC(dpy, lock->root, 0, NULL);
XSetLineAttributes(dpy, lock->gc, 1, LineSolid, CapButt, JoinMiter);
/* init */
wa.override_redirect = 1;
lock->win = XCreateWindow(dpy, lock->root, 0, 0,
lock->x,
lock->y,
0, DefaultDepth(dpy, lock->screen),
CopyFromParent,
DefaultVisual(dpy, lock->screen),
CWOverrideRedirect | CWBackPixel, &wa);
if (lock->bgmap)
XSetWindowBackgroundPixmap(dpy, lock->win, lock->bgmap);
lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap,
&color, &color, 0, 0);
XDefineCursor(dpy, lock->win, invisible);
resizerectangles(lock);
/* Try to grab mouse pointer *and* keyboard for 600ms, else fail the lock */
for (i = 0, ptgrab = kbgrab = -1; i < 6; i++) {
if (ptgrab != GrabSuccess) {
ptgrab = XGrabPointer(dpy, lock->root, False,
ButtonPressMask | ButtonReleaseMask |
PointerMotionMask, GrabModeAsync,
GrabModeAsync, None,
invisible,
CurrentTime);
}
if (kbgrab != GrabSuccess) {
kbgrab = XGrabKeyboard(dpy, lock->root, True,
GrabModeAsync, GrabModeAsync, CurrentTime);
}
/* input is grabbed: we can lock the screen */
if (ptgrab == GrabSuccess && kbgrab == GrabSuccess) {
XMapRaised(dpy, lock->win);
if (rr->active)
XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);
XSelectInput(dpy, lock->root, SubstructureNotifyMask);
drawlogo(dpy, lock, INIT);
return lock;
}
/* retry on AlreadyGrabbed but fail on other errors */
if ((ptgrab != AlreadyGrabbed && ptgrab != GrabSuccess) ||
(kbgrab != AlreadyGrabbed && kbgrab != GrabSuccess))
break;
usleep(100000);
}
/* we couldn't grab all input: fail out */
if (ptgrab != GrabSuccess)
fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n",
screen);
if (kbgrab != GrabSuccess)
fprintf(stderr, "slock: unable to grab keyboard for screen %d\n",
screen);
return NULL;
}
static void
usage(void)
{
die("usage: slock [-v] [cmd [arg ...]]\n");
}
int
main(int argc, char **argv) {
struct xrandr rr;
struct lock **locks;
struct passwd *pwd;
struct group *grp;
uid_t duid;
gid_t dgid;
const char *hash;
Display *dpy;
int s, nlocks, nscreens;
CARD16 standby, suspend, off;
ARGBEGIN {
case 'v':
puts("slock-"VERSION);
return 0;
default:
usage();
} ARGEND
/* validate drop-user and -group */
errno = 0;
if (!(pwd = getpwnam(user)))
die("slock: getpwnam %s: %s\n", user,
errno ? strerror(errno) : "user entry not found");
duid = pwd->pw_uid;
errno = 0;
if (!(grp = getgrnam(group)))
die("slock: getgrnam %s: %s\n", group,
errno ? strerror(errno) : "group entry not found");
dgid = grp->gr_gid;
#ifdef __linux__
dontkillme();
#endif
hash = gethash();
errno = 0;
if (!crypt("", hash))
die("slock: crypt: %s\n", strerror(errno));
if (!(dpy = XOpenDisplay(NULL)))
die("slock: cannot open display\n");
/* drop privileges */
if (setgroups(0, NULL) < 0)
die("slock: setgroups: %s\n", strerror(errno));
if (setgid(dgid) < 0)
die("slock: setgid: %s\n", strerror(errno));
if (setuid(duid) < 0)
die("slock: setuid: %s\n", strerror(errno));
config_init(dpy);
create_lock_image(dpy);
/* check for Xrandr support */
rr.active = XRRQueryExtension(dpy, &rr.evbase, &rr.errbase);
/* get number of screens in display "dpy" and blank them */
nscreens = ScreenCount(dpy);
if (!(locks = calloc(nscreens, sizeof(struct lock *))))
die("slock: out of memory\n");
for (nlocks = 0, s = 0; s < nscreens; s++) {
if ((locks[s] = lockscreen(dpy, &rr, s)) != NULL) {
nlocks++;
} else {
break;
}
}
XSync(dpy, 0);
/* did we manage to lock everything? */
if (nlocks != nscreens)
return 1;
/* DPMS magic to disable the monitor */
if (!DPMSCapable(dpy))
die("slock: DPMSCapable failed\n");
if (!DPMSEnable(dpy))
die("slock: DPMSEnable failed\n");
if (!DPMSGetTimeouts(dpy, &standby, &suspend, &off))
die("slock: DPMSGetTimeouts failed\n");
if (!standby || !suspend || !off)
die("slock: at least one DPMS variable is zero\n");
if (!DPMSSetTimeouts(dpy, monitortime, monitortime, monitortime))
die("slock: DPMSSetTimeouts failed\n");
XSync(dpy, 0);
/* run post-lock command */
if (argc > 0) {
switch (fork()) {
case -1:
die("slock: fork failed: %s\n", strerror(errno));
case 0:
if (close(ConnectionNumber(dpy)) < 0)
die("slock: close: %s\n", strerror(errno));
execvp(argv[0], argv);
fprintf(stderr, "slock: execvp %s: %s\n", argv[0], strerror(errno));
_exit(1);
}
}
/* everything is now blank. Wait for the correct password */
readpw(dpy, &rr, locks, nscreens, hash);
/* reset DPMS values to inital ones */
DPMSSetTimeouts(dpy, standby, suspend, off);
XSync(dpy, 0);
for (nlocks = 0, s = 0; s < nscreens; s++) {
XFreePixmap(dpy, locks[s]->drawable);
XFreeGC(dpy, locks[s]->gc);
}
XSync(dpy, 0);
XCloseDisplay(dpy);
return 0;
}

View File

@ -1,2 +0,0 @@
#undef explicit_bzero
void explicit_bzero(void *, size_t);

View File

@ -1,2 +0,0 @@
*.o
st

View File

@ -1,34 +0,0 @@
MIT/X Consortium License
© 2014-2022 Hiltjo Posthuma <hiltjo at codemadness dot org>
© 2018 Devin J. Pohly <djpohly at gmail dot com>
© 2014-2017 Quentin Rameau <quinq at fifth dot space>
© 2009-2012 Aurélien APTEL <aurelien dot aptel at gmail dot com>
© 2008-2017 Anselm R Garbe <garbeam at gmail dot com>
© 2012-2017 Roberto E. Vargas Caballero <k0ga at shike2 dot com>
© 2012-2016 Christoph Lohmann <20h at r-36 dot net>
© 2013 Eon S. Jeon <esjeon at hyunmu dot am>
© 2013 Alexander Sedov <alex0player at gmail dot com>
© 2013 Mark Edgar <medgar123 at gmail dot com>
© 2013-2014 Eric Pruitt <eric.pruitt at gmail dot com>
© 2013 Michael Forney <mforney at mforney dot org>
© 2013-2014 Markus Teich <markus dot teich at stusta dot mhn dot de>
© 2014-2015 Laslo Hunhold <dev at frign dot de>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,60 +0,0 @@
# st - simple terminal
# See LICENSE file for copyright and license details.
.POSIX:
include config.mk
SRC = st.c x.c $(LIGATURES_C) $(SIXEL_C)
OBJ = $(SRC:.c=.o)
all: st
config.h:
cp config.def.h config.h
.c.o:
$(CC) $(STCFLAGS) -c $<
st.o: config.h st.h win.h
x.o: arg.h config.h st.h win.h $(LIGATURES_H)
$(OBJ): config.h config.mk
st: $(OBJ)
$(CC) -o $@ $(OBJ) $(STLDFLAGS)
clean:
rm -f st $(OBJ) st-$(VERSION).tar.gz
dist: clean
mkdir -p st-$(VERSION)
cp -R FAQ LEGACY TODO LICENSE Makefile README config.mk\
config.def.h st.info st.1 arg.h st.h win.h $(LIGATURES_H) $(SRC)\
st-$(VERSION)
tar -cf - st-$(VERSION) | gzip > st-$(VERSION).tar.gz
rm -rf st-$(VERSION)
install: st
mkdir -p $(DESTDIR)$(PREFIX)/bin
cp -f st $(DESTDIR)$(PREFIX)/bin
cp -f st-copyout $(DESTDIR)$(PREFIX)/bin
cp -f st-urlhandler $(DESTDIR)$(PREFIX)/bin
chmod 755 $(DESTDIR)$(PREFIX)/bin/st
chmod 755 $(DESTDIR)$(PREFIX)/bin/st-copyout
chmod 755 $(DESTDIR)$(PREFIX)/bin/st-urlhandler
mkdir -p $(DESTDIR)$(MANPREFIX)/man1
sed "s/VERSION/$(VERSION)/g" < st.1 > $(DESTDIR)$(MANPREFIX)/man1/st.1
chmod 644 $(DESTDIR)$(MANPREFIX)/man1/st.1
tic -sx st.info
mkdir -p $(DESTDIR)$(PREFIX)/share/applications # desktop-entry patch
test -f ${DESTDIR}${PREFIX}/share/applications/st.desktop || cp -n st.desktop $(DESTDIR)$(PREFIX)/share/applications # desktop-entry patch
@echo Please see the README file regarding the terminfo entry of st.
uninstall:
rm -f $(DESTDIR)$(PREFIX)/bin/st
rm -f $(DESTDIR)$(PREFIX)/bin/st-copyout
rm -f $(DESTDIR)$(PREFIX)/bin/st-urlhandler
rm -f $(DESTDIR)$(MANPREFIX)/man1/st.1
rm -f $(DESTDIR)$(PREFIX)/share/applications/st.desktop # desktop-entry patch
.PHONY: all clean dist install uninstall

View File

@ -1,31 +0,0 @@
# st - simple terminal
This build of st was generated using [st-flexipatch](https://github.com/bakkeby/st-flexipatch.git) and finalized by [flexipatch-finalizer](https://github.com/bakkeby/flexipatch-finalizer).
## Patches
The patches used are listed below:
- alpha [link](https://st.suckless.org/patches/alpha)
- blinking cursor [link](https://st.suckless.org/patches/blinking_cursor)
- bold is not bright [link](https://st.suckless.org/patches/bold-is-not-bright)
- boxdraw [link](https://st.suckless.org/patches/boxdraw)
- clipboard [link](https://st.suckless.org/patches/clipboard)
- externalpipe [link](https://st.suckless.org/patches/externalpipe)
- font2 [link](https://st.suckless.org/patches/font2)
- hidecursor [link](https://st.suckless.org/patches/hidecursor)
- hide terminal cursor [link](https://www.reddit.com/r/suckless/comments/nvee8h/how_to_hide_cursor_in_st_is_there_a_patch_for_it)
- invert [link](https://st.suckless.org/patches/invert)
- iso14755 [link](https://st.suckless.org/patches/iso14755)
- ligatures [link](https://st.suckless.org/patches/ligatures)
- newterm [link](https://st.suckless.org/patches/newterm)
- reflow
- rightclicktoplumb [link](https://st.suckless.org/patches/right_click_to_plumb)
- scrollback [link](https://st.suckless.org/patches/scrollback)
- scrollback mouse altscreen [link](https://st.suckless.org/patches/scrollback)
- sixel [link](https://gist.github.com/saitoha/70e0fdf22e3e8f63ce937c7f7da71809)
- swapmouse [link](https://st.suckless.org/patches/swapmouse)
- use xftfontmatch [link](https://git.suckless.org/st/commit/528241aa3835e2f1f052abeeaf891737712955a0.html)
- wide glyphs [link](https://github.com/Dreomite/st/commit/e3b821dcb3511d60341dec35ee05a4a0abfef7f2) [link](https://www.reddit.com/r/suckless/comments/jt90ai/update_support_for_proper_glyph_rendering_in_st)
- xresources [link](https://st.suckless.org/patches/xresources)
- xresources reload

View File

@ -1,50 +0,0 @@
/*
* Copy me if you can.
* by 20h
*/
#ifndef ARG_H__
#define ARG_H__
extern char *argv0;
/* use main(int argc, char *argv[]) */
#define ARGBEGIN for (argv0 = *argv, argv++, argc--;\
argv[0] && argv[0][0] == '-'\
&& argv[0][1];\
argc--, argv++) {\
char argc_;\
char **argv_;\
int brk_;\
if (argv[0][1] == '-' && argv[0][2] == '\0') {\
argv++;\
argc--;\
break;\
}\
int i_;\
for (i_ = 1, brk_ = 0, argv_ = argv;\
argv[0][i_] && !brk_;\
i_++) {\
if (argv_ != argv)\
break;\
argc_ = argv[0][i_];\
switch (argc_)
#define ARGEND }\
}
#define ARGC() argc_
#define EARGF(x) ((argv[0][i_+1] == '\0' && argv[1] == NULL)?\
((x), abort(), (char *)0) :\
(brk_ = 1, (argv[0][i_+1] != '\0')?\
(&argv[0][i_+1]) :\
(argc--, argv++, argv[0])))
#define ARGF() ((argv[0][i_+1] == '\0' && argv[1] == NULL)?\
(char *)0 :\
(brk_ = 1, (argv[0][i_+1] != '\0')?\
(&argv[0][i_+1]) :\
(argc--, argv++, argv[0])))
#endif

View File

@ -1,566 +0,0 @@
/* See LICENSE file for copyright and license details. */
/*
* appearance
*
* font: see http://freedesktop.org/software/fontconfig/fontconfig-user.html
*/
static char *font =
"JetBrainsMono Nerd Font:pixelsize=12:antialias=true:autohint=true";
/* Spare fonts */
static char *font2[] = {
"Symbols Nerd Font:pixelsize=12:antialias=true:autohint=true",
"NotoColorEmoji:pixelsize=10:antialias=true:autohint=true",
"Unifont:pixelsize=12"};
static int borderpx = 10;
/*
* What program is execed by st depends of these precedence rules:
* 1: program passed with -e
* 2: scroll and/or utmp
* 3: SHELL environment variable
* 4: value of shell in /etc/passwd
* 5: value of shell in config.h
*/
static char *shell = "/bin/sh";
char *utmp = NULL;
/* scroll program: to enable use a string like "scroll" */
char *scroll = NULL;
char *stty_args = "stty raw pass8 nl -echo -iexten -cstopb 38400";
/* identification sequence returned in DA and DECID */
char *vtiden = "\033[?62;4c"; /* VT200 family (62) with sixel (4) */
/* sixel rgb byte order: LSBFirst or MSBFirst */
int const sixelbyteorder = LSBFirst;
/* Kerning / character bounding-box multipliers */
static float cwscale = 1.0;
static float chscale = 1.0;
/*
* word delimiter string
*
* More advanced example: L" `'\"()[]{}"
*/
wchar_t *worddelimiters = L" ";
/* selection timeouts (in milliseconds) */
static unsigned int doubleclicktimeout = 300;
static unsigned int tripleclicktimeout = 600;
/* alt screens */
int allowaltscreen = 1;
/* allow certain non-interactive (insecure) window operations such as:
setting the clipboard text */
int allowwindowops = 0;
/*
* draw latency range in ms - from new content/keypress/etc until drawing.
* within this range, st draws when content stops arriving (idle). mostly it's
* near minlatency, but it waits longer for slow updates to avoid partial draw.
* low minlatency will tear/flicker more, as it can "detect" idle too early.
*/
static double minlatency = 2;
static double maxlatency = 33;
/*
* blinking timeout (set to 0 to disable blinking) for the terminal blinking
* attribute.
*/
static unsigned int blinktimeout = 800;
/*
* thickness of underline and bar cursors
*/
static unsigned int cursorthickness = 2;
/* Hide the X cursor whenever a key is pressed. 0: off, 1: on */
int hidecursor = 1;
/*
* 1: render most of the lines/blocks characters without using the font for
* perfect alignment between cells (U2500 - U259F except dashes/diagonals).
* Bold affects lines thickness if boxdraw_bold is not 0. Italic is ignored.
* 0: disable (render all U25XX glyphs normally from the font).
*/
const int boxdraw = 1;
const int boxdraw_bold = 0;
/* braille (U28XX): 1: render as adjacent "pixels", 0: use font */
const int boxdraw_braille = 1;
/*
* bell volume. It must be a value between -100 and 100. Use 0 for disabling
* it
*/
static int bellvolume = 0;
/* default TERM value */
char *termname = "st-256color";
/*
* spaces per tab
*
* When you are changing this value, don't forget to adapt the »it« value in
* the st.info and appropriately install the st.info in the environment where
* you use this st version.
*
* it#$tabspaces,
*
* Secondly make sure your kernel is not expanding tabs. When running `stty
* -a` »tab0« should appear. You can tell the terminal to not expand tabs by
* running following command:
*
* stty tabs
*/
unsigned int tabspaces = 8;
/* bg opacity */
float alpha = 1.0;
/* Terminal colors (16 first used in escape sequence) */
static const char *colorname[] = {
/* 8 normal colors */
"black", "red3", "green3", "yellow3", "blue2", "magenta3", "cyan3",
"gray90",
/* 8 bright colors */
"gray50", "red", "green", "yellow", "#5c5cff", "magenta", "cyan", "white",
[255] = 0,
/* more colors can be added after 255 to use with DefaultXX */
"#add8e6", /* 256 -> cursor */
"#555555", /* 257 -> rev cursor*/
"#000000", /* 258 -> bg */
"#e5e5e5", /* 259 -> fg */
};
/*
* Default colors (colorname index)
* foreground, background, cursor, reverse cursor
*/
unsigned int defaultbg = 258;
unsigned int defaultfg = 259;
unsigned int defaultcs = 256;
unsigned int defaultrcs = 257;
/*
* https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h4-Functions-using-CSI-_-ordered-by-the-final-character-lparen-s-rparen:CSI-Ps-SP-q.1D81
* Default style of cursor
* 0: Blinking block
* 1: Blinking block (default)
* 2: Steady block ("â–ˆ")
* 3: Blinking underline
* 4: Steady underline ("_")
* 5: Blinking bar
* 6: Steady bar ("|")
* 7: Blinking st cursor
* 8: Steady st cursor
*/
static unsigned int cursorstyle = 3;
static Rune stcursor = 0x2603; /* snowman (U+2603) */
/*
* Default columns and rows numbers
*/
static unsigned int cols = 80;
static unsigned int rows = 24;
/*
* Default colour and shape of the mouse cursor
*/
static unsigned int mouseshape = XC_xterm;
static unsigned int mousefg = 7;
static unsigned int mousebg = 0;
/*
* Color used to display font attributes when fontconfig selected a font which
* doesn't match the ones requested.
*/
static unsigned int defaultattr = 11;
/*
* Xresources preferences to load at startup
*/
ResourcePref resources[] = {
{"font", STRING, &font},
{"color0", STRING, &colorname[0]},
{"color1", STRING, &colorname[1]},
{"color2", STRING, &colorname[2]},
{"color3", STRING, &colorname[3]},
{"color4", STRING, &colorname[4]},
{"color5", STRING, &colorname[5]},
{"color6", STRING, &colorname[6]},
{"color7", STRING, &colorname[7]},
{"color8", STRING, &colorname[8]},
{"color9", STRING, &colorname[9]},
{"color10", STRING, &colorname[10]},
{"color11", STRING, &colorname[11]},
{"color12", STRING, &colorname[12]},
{"color13", STRING, &colorname[13]},
{"color14", STRING, &colorname[14]},
{"color15", STRING, &colorname[15]},
{"background", STRING, &colorname[258]},
{"foreground", STRING, &colorname[259]},
{"cursorColor", STRING, &colorname[256]},
{"termname", STRING, &termname},
{"shell", STRING, &shell},
{"minlatency", INTEGER, &minlatency},
{"maxlatency", INTEGER, &maxlatency},
{"blinktimeout", INTEGER, &blinktimeout},
{"bellvolume", INTEGER, &bellvolume},
{"tabspaces", INTEGER, &tabspaces},
{"borderpx", INTEGER, &borderpx},
{"cwscale", FLOAT, &cwscale},
{"chscale", FLOAT, &chscale},
{"alpha", FLOAT, &alpha},
};
/*
* Force mouse select/shortcuts while mask is active (when MODE_MOUSE is set).
* Note that if you want to use ShiftMask with selmasks, set this to an other
* modifier, set to 0 to not use it.
*/
static uint forcemousemod = ShiftMask;
/*
* Internal mouse shortcuts.
* Beware that overloading Button1 will disable the selection.
*/
static MouseShortcut mshortcuts[] = {
/* mask button function argument release
screen */
{XK_ANY_MOD, Button2, clippaste, {.i = 0}, 1},
{ShiftMask, Button4, ttysend, {.s = "\033[5;2~"}},
{ShiftMask, Button5, ttysend, {.s = "\033[6;2~"}},
{XK_NO_MOD, Button4, kscrollup, {.i = 1}, 0, S_PRI},
{XK_NO_MOD, Button5, kscrolldown, {.i = 1}, 0, S_PRI},
{XK_ANY_MOD, Button4, ttysend, {.s = "\031"}, 0, S_ALT},
{XK_ANY_MOD, Button5, ttysend, {.s = "\005"}, 0, S_ALT},
};
/* Internal keyboard shortcuts. */
#define MODKEY Mod1Mask
#define TERMMOD (ControlMask | ShiftMask)
// static char *openurlcmd[] = { "/bin/sh", "-c",
// "xurls | dmenu -l 10 -w $WINDOWID | xargs -r open",
// "externalpipe", NULL };
static char *openurlcmd[] = {"/bin/sh", "-c", "st-urlhandler -o",
"externalpipe", NULL};
static char *copyurlcmd[] = {"/bin/sh", "-c", "st-urlhandler -c",
"externalpipe", NULL};
static char *copyoutput[] = {"/bin/sh", "-c", "st-copyout", "externalpipe",
NULL};
static char *setbgcolorcmd[] = {"/bin/sh", "-c", "printf '\033]11;#008000\007'",
"externalpipein", NULL};
static Shortcut shortcuts[] = {
/* mask keysym function argument screen
*/
{XK_ANY_MOD, XK_Break, sendbreak, {.i = 0}},
{ControlMask, XK_Print, toggleprinter, {.i = 0}},
{ShiftMask, XK_Print, printscreen, {.i = 0}},
{XK_ANY_MOD, XK_Print, printsel, {.i = 0}},
{TERMMOD, XK_Up, zoom, {.f = +1}},
{TERMMOD, XK_Down, zoom, {.f = -1}},
{TERMMOD, XK_Home, zoomreset, {.f = 0}},
{TERMMOD, XK_C, clipcopy, {.i = 0}},
{TERMMOD, XK_V, clippaste, {.i = 0}},
{TERMMOD, XK_A, changealpha, {.f = +0.05}},
{TERMMOD, XK_S, changealpha, {.f = -0.05}},
{ShiftMask, XK_Page_Up, kscrollup, {.i = -1}, S_PRI},
{ShiftMask, XK_Page_Down, kscrolldown, {.i = -1}, S_PRI},
{TERMMOD, XK_Y, clippaste, {.i = 0}},
{ShiftMask, XK_Insert, clippaste, {.i = 0}},
{TERMMOD, XK_Num_Lock, numlock, {.i = 0}},
{TERMMOD, XK_Return, newterm, {.i = 0}},
{TERMMOD, XK_U, externalpipe, {.v = openurlcmd}},
{MODKEY, XK_l, externalpipe, {.v = openurlcmd}},
{MODKEY, XK_y, externalpipe, {.v = copyurlcmd}},
{MODKEY, XK_o, externalpipe, {.v = copyoutput}},
{TERMMOD, XK_I, iso14755, {.i = 0}},
{TERMMOD, XK_X, invert, {0}},
};
/*
* Special keys (change & recompile st.info accordingly)
*
* Mask value:
* * Use XK_ANY_MOD to match the key no matter modifiers state
* * Use XK_NO_MOD to match the key alone (no modifiers)
* appkey value:
* * 0: no value
* * > 0: keypad application mode enabled
* * = 2: term.numlock = 1
* * < 0: keypad application mode disabled
* appcursor value:
* * 0: no value
* * > 0: cursor application mode enabled
* * < 0: cursor application mode disabled
*
* Be careful with the order of the definitions because st searches in
* this table sequentially, so any XK_ANY_MOD must be in the last
* position for a key.
*/
/*
* If you want keys other than the X11 function keys (0xFD00 - 0xFFFF)
* to be mapped below, add them to this array.
*/
static KeySym mappedkeys[] = {-1};
/*
* State bits to ignore when matching key or button events. By default,
* numlock (Mod2Mask) and keyboard layout (XK_SWITCH_MOD) are ignored.
*/
static uint ignoremod = Mod2Mask | XK_SWITCH_MOD;
/*
* This is the huge key array which defines all compatibility to the Linux
* world. Please decide about changes wisely.
*/
static Key key[] = {
/* keysym mask string appkey appcursor */
{XK_KP_Home, ShiftMask, "\033[2J", 0, -1},
{XK_KP_Home, ShiftMask, "\033[1;2H", 0, +1},
{XK_KP_Home, XK_ANY_MOD, "\033[H", 0, -1},
{XK_KP_Home, XK_ANY_MOD, "\033[1~", 0, +1},
{XK_KP_Up, XK_ANY_MOD, "\033Ox", +1, 0},
{XK_KP_Up, XK_ANY_MOD, "\033[A", 0, -1},
{XK_KP_Up, XK_ANY_MOD, "\033OA", 0, +1},
{XK_KP_Down, XK_ANY_MOD, "\033Or", +1, 0},
{XK_KP_Down, XK_ANY_MOD, "\033[B", 0, -1},
{XK_KP_Down, XK_ANY_MOD, "\033OB", 0, +1},
{XK_KP_Left, XK_ANY_MOD, "\033Ot", +1, 0},
{XK_KP_Left, XK_ANY_MOD, "\033[D", 0, -1},
{XK_KP_Left, XK_ANY_MOD, "\033OD", 0, +1},
{XK_KP_Right, XK_ANY_MOD, "\033Ov", +1, 0},
{XK_KP_Right, XK_ANY_MOD, "\033[C", 0, -1},
{XK_KP_Right, XK_ANY_MOD, "\033OC", 0, +1},
{XK_KP_Prior, ShiftMask, "\033[5;2~", 0, 0},
{XK_KP_Prior, XK_ANY_MOD, "\033[5~", 0, 0},
{XK_KP_Begin, XK_ANY_MOD, "\033[E", 0, 0},
{XK_KP_End, ControlMask, "\033[J", -1, 0},
{XK_KP_End, ControlMask, "\033[1;5F", +1, 0},
{XK_KP_End, ShiftMask, "\033[K", -1, 0},
{XK_KP_End, ShiftMask, "\033[1;2F", +1, 0},
{XK_KP_End, XK_ANY_MOD, "\033[4~", 0, 0},
{XK_KP_Next, ShiftMask, "\033[6;2~", 0, 0},
{XK_KP_Next, XK_ANY_MOD, "\033[6~", 0, 0},
{XK_KP_Insert, ShiftMask, "\033[2;2~", +1, 0},
{XK_KP_Insert, ShiftMask, "\033[4l", -1, 0},
{XK_KP_Insert, ControlMask, "\033[L", -1, 0},
{XK_KP_Insert, ControlMask, "\033[2;5~", +1, 0},
{XK_KP_Insert, XK_ANY_MOD, "\033[4h", -1, 0},
{XK_KP_Insert, XK_ANY_MOD, "\033[2~", +1, 0},
{XK_KP_Delete, ControlMask, "\033[M", -1, 0},
{XK_KP_Delete, ControlMask, "\033[3;5~", +1, 0},
{XK_KP_Delete, ShiftMask, "\033[2K", -1, 0},
{XK_KP_Delete, ShiftMask, "\033[3;2~", +1, 0},
{XK_KP_Delete, XK_ANY_MOD, "\033[P", -1, 0},
{XK_KP_Delete, XK_ANY_MOD, "\033[3~", +1, 0},
{XK_KP_Multiply, XK_ANY_MOD, "\033Oj", +2, 0},
{XK_KP_Add, XK_ANY_MOD, "\033Ok", +2, 0},
{XK_KP_Enter, XK_ANY_MOD, "\033OM", +2, 0},
{XK_KP_Enter, XK_ANY_MOD, "\r", -1, 0},
{XK_KP_Subtract, XK_ANY_MOD, "\033Om", +2, 0},
{XK_KP_Decimal, XK_ANY_MOD, "\033On", +2, 0},
{XK_KP_Divide, XK_ANY_MOD, "\033Oo", +2, 0},
{XK_KP_0, XK_ANY_MOD, "\033Op", +2, 0},
{XK_KP_1, XK_ANY_MOD, "\033Oq", +2, 0},
{XK_KP_2, XK_ANY_MOD, "\033Or", +2, 0},
{XK_KP_3, XK_ANY_MOD, "\033Os", +2, 0},
{XK_KP_4, XK_ANY_MOD, "\033Ot", +2, 0},
{XK_KP_5, XK_ANY_MOD, "\033Ou", +2, 0},
{XK_KP_6, XK_ANY_MOD, "\033Ov", +2, 0},
{XK_KP_7, XK_ANY_MOD, "\033Ow", +2, 0},
{XK_KP_8, XK_ANY_MOD, "\033Ox", +2, 0},
{XK_KP_9, XK_ANY_MOD, "\033Oy", +2, 0},
{XK_Up, ShiftMask, "\033[1;2A", 0, 0},
{XK_Up, Mod1Mask, "\033[1;3A", 0, 0},
{XK_Up, ShiftMask | Mod1Mask, "\033[1;4A", 0, 0},
{XK_Up, ControlMask, "\033[1;5A", 0, 0},
{XK_Up, ShiftMask | ControlMask, "\033[1;6A", 0, 0},
{XK_Up, ControlMask | Mod1Mask, "\033[1;7A", 0, 0},
{XK_Up, ShiftMask | ControlMask | Mod1Mask, "\033[1;8A", 0, 0},
{XK_Up, XK_ANY_MOD, "\033[A", 0, -1},
{XK_Up, XK_ANY_MOD, "\033OA", 0, +1},
{XK_Down, ShiftMask, "\033[1;2B", 0, 0},
{XK_Down, Mod1Mask, "\033[1;3B", 0, 0},
{XK_Down, ShiftMask | Mod1Mask, "\033[1;4B", 0, 0},
{XK_Down, ControlMask, "\033[1;5B", 0, 0},
{XK_Down, ShiftMask | ControlMask, "\033[1;6B", 0, 0},
{XK_Down, ControlMask | Mod1Mask, "\033[1;7B", 0, 0},
{XK_Down, ShiftMask | ControlMask | Mod1Mask, "\033[1;8B", 0, 0},
{XK_Down, XK_ANY_MOD, "\033[B", 0, -1},
{XK_Down, XK_ANY_MOD, "\033OB", 0, +1},
{XK_Left, ShiftMask, "\033[1;2D", 0, 0},
{XK_Left, Mod1Mask, "\033[1;3D", 0, 0},
{XK_Left, ShiftMask | Mod1Mask, "\033[1;4D", 0, 0},
{XK_Left, ControlMask, "\033[1;5D", 0, 0},
{XK_Left, ShiftMask | ControlMask, "\033[1;6D", 0, 0},
{XK_Left, ControlMask | Mod1Mask, "\033[1;7D", 0, 0},
{XK_Left, ShiftMask | ControlMask | Mod1Mask, "\033[1;8D", 0, 0},
{XK_Left, XK_ANY_MOD, "\033[D", 0, -1},
{XK_Left, XK_ANY_MOD, "\033OD", 0, +1},
{XK_Right, ShiftMask, "\033[1;2C", 0, 0},
{XK_Right, Mod1Mask, "\033[1;3C", 0, 0},
{XK_Right, ShiftMask | Mod1Mask, "\033[1;4C", 0, 0},
{XK_Right, ControlMask, "\033[1;5C", 0, 0},
{XK_Right, ShiftMask | ControlMask, "\033[1;6C", 0, 0},
{XK_Right, ControlMask | Mod1Mask, "\033[1;7C", 0, 0},
{XK_Right, ShiftMask | ControlMask | Mod1Mask, "\033[1;8C", 0, 0},
{XK_Right, XK_ANY_MOD, "\033[C", 0, -1},
{XK_Right, XK_ANY_MOD, "\033OC", 0, +1},
{XK_ISO_Left_Tab, ShiftMask, "\033[Z", 0, 0},
{XK_Return, Mod1Mask, "\033\r", 0, 0},
{XK_Return, XK_ANY_MOD, "\r", 0, 0},
{XK_Insert, ShiftMask, "\033[4l", -1, 0},
{XK_Insert, ShiftMask, "\033[2;2~", +1, 0},
{XK_Insert, ControlMask, "\033[L", -1, 0},
{XK_Insert, ControlMask, "\033[2;5~", +1, 0},
{XK_Insert, XK_ANY_MOD, "\033[4h", -1, 0},
{XK_Insert, XK_ANY_MOD, "\033[2~", +1, 0},
{XK_Delete, ControlMask, "\033[M", -1, 0},
{XK_Delete, ControlMask, "\033[3;5~", +1, 0},
{XK_Delete, ShiftMask, "\033[2K", -1, 0},
{XK_Delete, ShiftMask, "\033[3;2~", +1, 0},
{XK_Delete, XK_ANY_MOD, "\033[P", -1, 0},
{XK_Delete, XK_ANY_MOD, "\033[3~", +1, 0},
{XK_BackSpace, XK_NO_MOD, "\177", 0, 0},
{XK_BackSpace, Mod1Mask, "\033\177", 0, 0},
{XK_Home, ShiftMask, "\033[2J", 0, -1},
{XK_Home, ShiftMask, "\033[1;2H", 0, +1},
{XK_Home, XK_ANY_MOD, "\033[H", 0, -1},
{XK_Home, XK_ANY_MOD, "\033[1~", 0, +1},
{XK_End, ControlMask, "\033[J", -1, 0},
{XK_End, ControlMask, "\033[1;5F", +1, 0},
{XK_End, ShiftMask, "\033[K", -1, 0},
{XK_End, ShiftMask, "\033[1;2F", +1, 0},
{XK_End, XK_ANY_MOD, "\033[4~", 0, 0},
{XK_Prior, ControlMask, "\033[5;5~", 0, 0},
{XK_Prior, ShiftMask, "\033[5;2~", 0, 0},
{XK_Prior, XK_ANY_MOD, "\033[5~", 0, 0},
{XK_Next, ControlMask, "\033[6;5~", 0, 0},
{XK_Next, ShiftMask, "\033[6;2~", 0, 0},
{XK_Next, XK_ANY_MOD, "\033[6~", 0, 0},
{XK_F1, XK_NO_MOD, "\033OP", 0, 0},
{XK_F1, /* F13 */ ShiftMask, "\033[1;2P", 0, 0},
{XK_F1, /* F25 */ ControlMask, "\033[1;5P", 0, 0},
{XK_F1, /* F37 */ Mod4Mask, "\033[1;6P", 0, 0},
{XK_F1, /* F49 */ Mod1Mask, "\033[1;3P", 0, 0},
{XK_F1, /* F61 */ Mod3Mask, "\033[1;4P", 0, 0},
{XK_F2, XK_NO_MOD, "\033OQ", 0, 0},
{XK_F2, /* F14 */ ShiftMask, "\033[1;2Q", 0, 0},
{XK_F2, /* F26 */ ControlMask, "\033[1;5Q", 0, 0},
{XK_F2, /* F38 */ Mod4Mask, "\033[1;6Q", 0, 0},
{XK_F2, /* F50 */ Mod1Mask, "\033[1;3Q", 0, 0},
{XK_F2, /* F62 */ Mod3Mask, "\033[1;4Q", 0, 0},
{XK_F3, XK_NO_MOD, "\033OR", 0, 0},
{XK_F3, /* F15 */ ShiftMask, "\033[1;2R", 0, 0},
{XK_F3, /* F27 */ ControlMask, "\033[1;5R", 0, 0},
{XK_F3, /* F39 */ Mod4Mask, "\033[1;6R", 0, 0},
{XK_F3, /* F51 */ Mod1Mask, "\033[1;3R", 0, 0},
{XK_F3, /* F63 */ Mod3Mask, "\033[1;4R", 0, 0},
{XK_F4, XK_NO_MOD, "\033OS", 0, 0},
{XK_F4, /* F16 */ ShiftMask, "\033[1;2S", 0, 0},
{XK_F4, /* F28 */ ControlMask, "\033[1;5S", 0, 0},
{XK_F4, /* F40 */ Mod4Mask, "\033[1;6S", 0, 0},
{XK_F4, /* F52 */ Mod1Mask, "\033[1;3S", 0, 0},
{XK_F5, XK_NO_MOD, "\033[15~", 0, 0},
{XK_F5, /* F17 */ ShiftMask, "\033[15;2~", 0, 0},
{XK_F5, /* F29 */ ControlMask, "\033[15;5~", 0, 0},
{XK_F5, /* F41 */ Mod4Mask, "\033[15;6~", 0, 0},
{XK_F5, /* F53 */ Mod1Mask, "\033[15;3~", 0, 0},
{XK_F6, XK_NO_MOD, "\033[17~", 0, 0},
{XK_F6, /* F18 */ ShiftMask, "\033[17;2~", 0, 0},
{XK_F6, /* F30 */ ControlMask, "\033[17;5~", 0, 0},
{XK_F6, /* F42 */ Mod4Mask, "\033[17;6~", 0, 0},
{XK_F6, /* F54 */ Mod1Mask, "\033[17;3~", 0, 0},
{XK_F7, XK_NO_MOD, "\033[18~", 0, 0},
{XK_F7, /* F19 */ ShiftMask, "\033[18;2~", 0, 0},
{XK_F7, /* F31 */ ControlMask, "\033[18;5~", 0, 0},
{XK_F7, /* F43 */ Mod4Mask, "\033[18;6~", 0, 0},
{XK_F7, /* F55 */ Mod1Mask, "\033[18;3~", 0, 0},
{XK_F8, XK_NO_MOD, "\033[19~", 0, 0},
{XK_F8, /* F20 */ ShiftMask, "\033[19;2~", 0, 0},
{XK_F8, /* F32 */ ControlMask, "\033[19;5~", 0, 0},
{XK_F8, /* F44 */ Mod4Mask, "\033[19;6~", 0, 0},
{XK_F8, /* F56 */ Mod1Mask, "\033[19;3~", 0, 0},
{XK_F9, XK_NO_MOD, "\033[20~", 0, 0},
{XK_F9, /* F21 */ ShiftMask, "\033[20;2~", 0, 0},
{XK_F9, /* F33 */ ControlMask, "\033[20;5~", 0, 0},
{XK_F9, /* F45 */ Mod4Mask, "\033[20;6~", 0, 0},
{XK_F9, /* F57 */ Mod1Mask, "\033[20;3~", 0, 0},
{XK_F10, XK_NO_MOD, "\033[21~", 0, 0},
{XK_F10, /* F22 */ ShiftMask, "\033[21;2~", 0, 0},
{XK_F10, /* F34 */ ControlMask, "\033[21;5~", 0, 0},
{XK_F10, /* F46 */ Mod4Mask, "\033[21;6~", 0, 0},
{XK_F10, /* F58 */ Mod1Mask, "\033[21;3~", 0, 0},
{XK_F11, XK_NO_MOD, "\033[23~", 0, 0},
{XK_F11, /* F23 */ ShiftMask, "\033[23;2~", 0, 0},
{XK_F11, /* F35 */ ControlMask, "\033[23;5~", 0, 0},
{XK_F11, /* F47 */ Mod4Mask, "\033[23;6~", 0, 0},
{XK_F11, /* F59 */ Mod1Mask, "\033[23;3~", 0, 0},
{XK_F12, XK_NO_MOD, "\033[24~", 0, 0},
{XK_F12, /* F24 */ ShiftMask, "\033[24;2~", 0, 0},
{XK_F12, /* F36 */ ControlMask, "\033[24;5~", 0, 0},
{XK_F12, /* F48 */ Mod4Mask, "\033[24;6~", 0, 0},
{XK_F12, /* F60 */ Mod1Mask, "\033[24;3~", 0, 0},
{XK_F13, XK_NO_MOD, "\033[1;2P", 0, 0},
{XK_F14, XK_NO_MOD, "\033[1;2Q", 0, 0},
{XK_F15, XK_NO_MOD, "\033[1;2R", 0, 0},
{XK_F16, XK_NO_MOD, "\033[1;2S", 0, 0},
{XK_F17, XK_NO_MOD, "\033[15;2~", 0, 0},
{XK_F18, XK_NO_MOD, "\033[17;2~", 0, 0},
{XK_F19, XK_NO_MOD, "\033[18;2~", 0, 0},
{XK_F20, XK_NO_MOD, "\033[19;2~", 0, 0},
{XK_F21, XK_NO_MOD, "\033[20;2~", 0, 0},
{XK_F22, XK_NO_MOD, "\033[21;2~", 0, 0},
{XK_F23, XK_NO_MOD, "\033[23;2~", 0, 0},
{XK_F24, XK_NO_MOD, "\033[24;2~", 0, 0},
{XK_F25, XK_NO_MOD, "\033[1;5P", 0, 0},
{XK_F26, XK_NO_MOD, "\033[1;5Q", 0, 0},
{XK_F27, XK_NO_MOD, "\033[1;5R", 0, 0},
{XK_F28, XK_NO_MOD, "\033[1;5S", 0, 0},
{XK_F29, XK_NO_MOD, "\033[15;5~", 0, 0},
{XK_F30, XK_NO_MOD, "\033[17;5~", 0, 0},
{XK_F31, XK_NO_MOD, "\033[18;5~", 0, 0},
{XK_F32, XK_NO_MOD, "\033[19;5~", 0, 0},
{XK_F33, XK_NO_MOD, "\033[20;5~", 0, 0},
{XK_F34, XK_NO_MOD, "\033[21;5~", 0, 0},
{XK_F35, XK_NO_MOD, "\033[23;5~", 0, 0},
};
/*
* Selection types' masks.
* Use the same masks as usual.
* Button1Mask is always unset, to make masks match between ButtonPress.
* ButtonRelease and MotionNotify.
* If no match is found, regular selection is used.
*/
static uint selmasks[] = {
[SEL_RECTANGULAR] = Mod1Mask,
};
/*
* Printable characters in ASCII, used to estimate the advance width
* of single wide characters.
*/
static char ascii_printable[] = " !\"#$%&'()*+,-./0123456789:;<=>?"
"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
"`abcdefghijklmnopqrstuvwxyz{|}~";
/*
* plumb_cmd is run on mouse button 3 click, with argument set to
* current selection and with cwd set to the cwd of the active shell
*/
static char *plumb_cmd = "dmenuhandler";

View File

@ -1,60 +0,0 @@
# st version
VERSION = 0.9.1
# Customize below to fit your system
# paths
PREFIX = /usr/local
MANPREFIX = $(PREFIX)/share/man
ICONPREFIX = $(PREFIX)/share/pixmaps
ICONNAME = st.png
X11INC = /usr/X11R6/include
X11LIB = /usr/X11R6/lib
PKG_CONFIG = pkg-config
# Uncomment this for the alpha patch / ALPHA_PATCH
XRENDER = `$(PKG_CONFIG) --libs xrender`
# Uncomment this for the themed cursor patch / THEMED_CURSOR_PATCH
#XCURSOR = `$(PKG_CONFIG) --libs xcursor`
# Uncomment the lines below for the ligatures patch / LIGATURES_PATCH
LIGATURES_C = hb.c
LIGATURES_H = hb.h
LIGATURES_INC = `$(PKG_CONFIG) --cflags harfbuzz`
LIGATURES_LIBS = `$(PKG_CONFIG) --libs harfbuzz`
# Uncomment this for the SIXEL patch / SIXEL_PATCH
SIXEL_C = sixel.c sixel_hls.c
SIXEL_LIBS = `$(PKG_CONFIG) --libs imlib2`
# Uncomment for the netwmicon patch / NETWMICON_PATCH
#NETWMICON_LIBS = `$(PKG_CONFIG) --libs gdlib`
# includes and libs, uncomment harfbuzz for the ligatures patch
INCS = -I$(X11INC) \
`$(PKG_CONFIG) --cflags fontconfig` \
`$(PKG_CONFIG) --cflags freetype2` \
$(LIGATURES_INC)
LIBS = -L$(X11LIB) -lm -lrt -lX11 -lutil -lXft ${SIXEL_LIBS} ${XRENDER} ${XCURSOR}\
`$(PKG_CONFIG) --libs fontconfig` \
`$(PKG_CONFIG) --libs freetype2` \
$(LIGATURES_LIBS) \
$(NETWMICON_LIBS)
# flags
STCPPFLAGS = -DVERSION=\"$(VERSION)\" -DICON=\"$(ICONPREFIX)/$(ICONNAME)\" -D_XOPEN_SOURCE=600
STCFLAGS = $(INCS) $(STCPPFLAGS) $(CPPFLAGS) $(CFLAGS)
STLDFLAGS = $(LIBS) $(LDFLAGS)
# OpenBSD:
#CPPFLAGS = -DVERSION=\"$(VERSION)\" -D_XOPEN_SOURCE=600 -D_BSD_SOURCE
#LIBS = -L$(X11LIB) -lm -lX11 -lutil -lXft \
# `pkg-config --libs fontconfig` \
# `pkg-config --libs freetype2`
#MANPREFIX = ${PREFIX}/man
# compiler and linker
# CC = c99

View File

@ -1,139 +0,0 @@
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <X11/Xft/Xft.h>
#include <X11/cursorfont.h>
#include <hb.h>
#include <hb-ft.h>
#include "st.h"
#include "hb.h"
#define FEATURE(c1,c2,c3,c4) { .tag = HB_TAG(c1,c2,c3,c4), .value = 1, .start = HB_FEATURE_GLOBAL_START, .end = HB_FEATURE_GLOBAL_END }
#define BUFFER_STEP 256
hb_font_t *hbfindfont(XftFont *match);
typedef struct {
XftFont *match;
hb_font_t *font;
} HbFontMatch;
typedef struct {
size_t capacity;
HbFontMatch *fonts;
} HbFontCache;
static HbFontCache hbfontcache = { 0, NULL };
typedef struct {
size_t capacity;
Rune *runes;
} RuneBuffer;
static RuneBuffer hbrunebuffer = { 0, NULL };
static hb_buffer_t *hbbuffer;
/*
* Poplulate the array with a list of font features, wrapped in FEATURE macro,
* e. g.
* FEATURE('c', 'a', 'l', 't'), FEATURE('d', 'l', 'i', 'g')
*/
hb_feature_t features[] = { };
void
hbcreatebuffer(void)
{
hbbuffer = hb_buffer_create();
}
void
hbdestroybuffer(void)
{
hb_buffer_destroy(hbbuffer);
}
void
hbunloadfonts(void)
{
for (int i = 0; i < hbfontcache.capacity; i++) {
hb_font_destroy(hbfontcache.fonts[i].font);
XftUnlockFace(hbfontcache.fonts[i].match);
}
if (hbfontcache.fonts != NULL) {
free(hbfontcache.fonts);
hbfontcache.fonts = NULL;
}
hbfontcache.capacity = 0;
}
hb_font_t *
hbfindfont(XftFont *match)
{
for (int i = 0; i < hbfontcache.capacity; i++) {
if (hbfontcache.fonts[i].match == match)
return hbfontcache.fonts[i].font;
}
/* Font not found in cache, caching it now. */
hbfontcache.fonts = realloc(hbfontcache.fonts, sizeof(HbFontMatch) * (hbfontcache.capacity + 1));
FT_Face face = XftLockFace(match);
hb_font_t *font = hb_ft_font_create(face, NULL);
if (font == NULL)
die("Failed to load Harfbuzz font.");
hbfontcache.fonts[hbfontcache.capacity].match = match;
hbfontcache.fonts[hbfontcache.capacity].font = font;
hbfontcache.capacity += 1;
return font;
}
void
hbtransform(HbTransformData *data, XftFont *xfont, const Glyph *glyphs, int start, int length)
{
uint32_t mode;
unsigned int glyph_count;
int rune_idx, glyph_idx, end = start + length;
hb_buffer_t *buffer = hbbuffer;
hb_font_t *font = hbfindfont(xfont);
if (font == NULL) {
data->count = 0;
return;
}
hb_buffer_reset(buffer);
hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
/* Resize the buffer if required length is larger. */
if (hbrunebuffer.capacity < length) {
hbrunebuffer.capacity = (length / BUFFER_STEP + 1) * BUFFER_STEP;
hbrunebuffer.runes = realloc(hbrunebuffer.runes, hbrunebuffer.capacity * sizeof(Rune));
}
/* Fill buffer with codepoints. */
for (rune_idx = 0, glyph_idx = start; glyph_idx < end; glyph_idx++, rune_idx++) {
hbrunebuffer.runes[rune_idx] = glyphs[glyph_idx].u;
mode = glyphs[glyph_idx].mode;
if (mode & ATTR_WDUMMY)
hbrunebuffer.runes[rune_idx] = 0x0020;
}
hb_buffer_add_codepoints(buffer, hbrunebuffer.runes, length, 0, length);
/* Shape the segment. */
hb_shape(font, buffer, features, sizeof(features)/sizeof(hb_feature_t));
/* Get new glyph info. */
hb_glyph_info_t *info = hb_buffer_get_glyph_infos(buffer, &glyph_count);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions(buffer, &glyph_count);
/* Fill the output. */
data->buffer = buffer;
data->glyphs = info;
data->positions = pos;
data->count = glyph_count;
}

View File

@ -1,15 +0,0 @@
#include <X11/Xft/Xft.h>
#include <hb.h>
#include <hb-ft.h>
typedef struct {
hb_buffer_t *buffer;
hb_glyph_info_t *glyphs;
hb_glyph_position_t *positions;
unsigned int count;
} HbTransformData;
void hbcreatebuffer(void);
void hbdestroybuffer(void);
void hbunloadfonts(void);
void hbtransform(HbTransformData *, XftFont *, const Glyph *, int, int);

View File

@ -1,19 +0,0 @@
float
clamp(float value, float lower, float upper) {
if (value < lower)
return lower;
if (value > upper)
return upper;
return value;
}
void
changealpha(const Arg *arg)
{
if ((alpha > 0 && arg->f < 0) || (alpha < 1 && arg->f > 0))
alpha += arg->f;
alpha = clamp(alpha, 0.0, 1.0);
xloadcols();
redraw();
}

View File

@ -1,2 +0,0 @@
static float clamp(float value, float lower, float upper);
static void changealpha(const Arg *);

View File

@ -1,192 +0,0 @@
/*
* Copyright 2018 Avi Halachmi (:avih) avihpit@yahoo.com https://github.com/avih
* MIT/X Consortium License
*/
#include <X11/Xft/Xft.h>
/* Rounded non-negative integers division of n / d */
#define DIV(n, d) (((n) + (d) / 2) / (d))
static Display *xdpy;
static Colormap xcmap;
static XftDraw *xd;
static Visual *xvis;
static void drawbox(int, int, int, int, XftColor *, XftColor *, ushort);
static void drawboxlines(int, int, int, int, XftColor *, ushort);
/* public API */
void
boxdraw_xinit(Display *dpy, Colormap cmap, XftDraw *draw, Visual *vis)
{
xdpy = dpy; xcmap = cmap; xd = draw, xvis = vis;
}
int
isboxdraw(Rune u)
{
Rune block = u & ~0xff;
return (boxdraw && block == 0x2500 && boxdata[(uint8_t)u]) ||
(boxdraw_braille && block == 0x2800);
}
/* the "index" is actually the entire shape data encoded as ushort */
ushort
boxdrawindex(const Glyph *g)
{
if (boxdraw_braille && (g->u & ~0xff) == 0x2800)
return BRL | (uint8_t)g->u;
if (boxdraw_bold && (g->mode & ATTR_BOLD))
return BDB | boxdata[(uint8_t)g->u];
return boxdata[(uint8_t)g->u];
}
void
drawboxes(int x, int y, int cw, int ch, XftColor *fg, XftColor *bg,
const XftGlyphFontSpec *specs, int len)
{
for ( ; len-- > 0; x += cw, specs++)
drawbox(x, y, cw, ch, fg, bg, (ushort)specs->glyph);
}
/* implementation */
void
drawbox(int x, int y, int w, int h, XftColor *fg, XftColor *bg, ushort bd)
{
ushort cat = bd & ~(BDB | 0xff); /* mask out bold and data */
if (bd & (BDL | BDA)) {
/* lines (light/double/heavy/arcs) */
drawboxlines(x, y, w, h, fg, bd);
} else if (cat == BBD) {
/* lower (8-X)/8 block */
int d = DIV((uint8_t)bd * h, 8);
XftDrawRect(xd, fg, x, y + d, w, h - d);
} else if (cat == BBU) {
/* upper X/8 block */
XftDrawRect(xd, fg, x, y, w, DIV((uint8_t)bd * h, 8));
} else if (cat == BBL) {
/* left X/8 block */
XftDrawRect(xd, fg, x, y, DIV((uint8_t)bd * w, 8), h);
} else if (cat == BBR) {
/* right (8-X)/8 block */
int d = DIV((uint8_t)bd * w, 8);
XftDrawRect(xd, fg, x + d, y, w - d, h);
} else if (cat == BBQ) {
/* Quadrants */
int w2 = DIV(w, 2), h2 = DIV(h, 2);
if (bd & TL)
XftDrawRect(xd, fg, x, y, w2, h2);
if (bd & TR)
XftDrawRect(xd, fg, x + w2, y, w - w2, h2);
if (bd & BL)
XftDrawRect(xd, fg, x, y + h2, w2, h - h2);
if (bd & BR)
XftDrawRect(xd, fg, x + w2, y + h2, w - w2, h - h2);
} else if (bd & BBS) {
/* Shades - data is 1/2/3 for 25%/50%/75% alpha, respectively */
int d = (uint8_t)bd;
XftColor xfc;
XRenderColor xrc = { .alpha = 0xffff };
xrc.red = DIV(fg->color.red * d + bg->color.red * (4 - d), 4);
xrc.green = DIV(fg->color.green * d + bg->color.green * (4 - d), 4);
xrc.blue = DIV(fg->color.blue * d + bg->color.blue * (4 - d), 4);
XftColorAllocValue(xdpy, xvis, xcmap, &xrc, &xfc);
XftDrawRect(xd, &xfc, x, y, w, h);
XftColorFree(xdpy, xvis, xcmap, &xfc);
} else if (cat == BRL) {
/* braille, each data bit corresponds to one dot at 2x4 grid */
int w1 = DIV(w, 2);
int h1 = DIV(h, 4), h2 = DIV(h, 2), h3 = DIV(3 * h, 4);
if (bd & 1) XftDrawRect(xd, fg, x, y, w1, h1);
if (bd & 2) XftDrawRect(xd, fg, x, y + h1, w1, h2 - h1);
if (bd & 4) XftDrawRect(xd, fg, x, y + h2, w1, h3 - h2);
if (bd & 8) XftDrawRect(xd, fg, x + w1, y, w - w1, h1);
if (bd & 16) XftDrawRect(xd, fg, x + w1, y + h1, w - w1, h2 - h1);
if (bd & 32) XftDrawRect(xd, fg, x + w1, y + h2, w - w1, h3 - h2);
if (bd & 64) XftDrawRect(xd, fg, x, y + h3, w1, h - h3);
if (bd & 128) XftDrawRect(xd, fg, x + w1, y + h3, w - w1, h - h3);
}
}
void
drawboxlines(int x, int y, int w, int h, XftColor *fg, ushort bd)
{
/* s: stem thickness. width/8 roughly matches underscore thickness. */
/* We draw bold as 1.5 * normal-stem and at least 1px thicker. */
/* doubles draw at least 3px, even when w or h < 3. bold needs 6px. */
int mwh = MIN(w, h);
int base_s = MAX(1, DIV(mwh, 8));
int bold = (bd & BDB) && mwh >= 6; /* possibly ignore boldness */
int s = bold ? MAX(base_s + 1, DIV(3 * base_s, 2)) : base_s;
int w2 = DIV(w - s, 2), h2 = DIV(h - s, 2);
/* the s-by-s square (x + w2, y + h2, s, s) is the center texel. */
/* The base length (per direction till edge) includes this square. */
int light = bd & (LL | LU | LR | LD);
int double_ = bd & (DL | DU | DR | DD);
if (light) {
/* d: additional (negative) length to not-draw the center */
/* texel - at arcs and avoid drawing inside (some) doubles */
int arc = bd & BDA;
int multi_light = light & (light - 1);
int multi_double = double_ & (double_ - 1);
/* light crosses double only at DH+LV, DV+LH (ref. shapes) */
int d = arc || (multi_double && !multi_light) ? -s : 0;
if (bd & LL)
XftDrawRect(xd, fg, x, y + h2, w2 + s + d, s);
if (bd & LU)
XftDrawRect(xd, fg, x + w2, y, s, h2 + s + d);
if (bd & LR)
XftDrawRect(xd, fg, x + w2 - d, y + h2, w - w2 + d, s);
if (bd & LD)
XftDrawRect(xd, fg, x + w2, y + h2 - d, s, h - h2 + d);
}
/* double lines - also align with light to form heavy when combined */
if (double_) {
/*
* going clockwise, for each double-ray: p is additional length
* to the single-ray nearer to the previous direction, and n to
* the next. p and n adjust from the base length to lengths
* which consider other doubles - shorter to avoid intersections
* (p, n), or longer to draw the far-corner texel (n).
*/
int dl = bd & DL, du = bd & DU, dr = bd & DR, dd = bd & DD;
if (dl) {
int p = dd ? -s : 0, n = du ? -s : dd ? s : 0;
XftDrawRect(xd, fg, x, y + h2 + s, w2 + s + p, s);
XftDrawRect(xd, fg, x, y + h2 - s, w2 + s + n, s);
}
if (du) {
int p = dl ? -s : 0, n = dr ? -s : dl ? s : 0;
XftDrawRect(xd, fg, x + w2 - s, y, s, h2 + s + p);
XftDrawRect(xd, fg, x + w2 + s, y, s, h2 + s + n);
}
if (dr) {
int p = du ? -s : 0, n = dd ? -s : du ? s : 0;
XftDrawRect(xd, fg, x + w2 - p, y + h2 - s, w - w2 + p, s);
XftDrawRect(xd, fg, x + w2 - n, y + h2 + s, w - w2 + n, s);
}
if (dd) {
int p = dr ? -s : 0, n = dl ? -s : dr ? s : 0;
XftDrawRect(xd, fg, x + w2 + s, y + h2 - p, s, h - h2 + p);
XftDrawRect(xd, fg, x + w2 - s, y + h2 - n, s, h - h2 + n);
}
}
}

View File

@ -1,214 +0,0 @@
/*
* Copyright 2018 Avi Halachmi (:avih) avihpit@yahoo.com https://github.com/avih
* MIT/X Consortium License
*/
/*
* U+25XX codepoints data
*
* References:
* http://www.unicode.org/charts/PDF/U2500.pdf
* http://www.unicode.org/charts/PDF/U2580.pdf
*
* Test page:
* https://github.com/GNOME/vte/blob/master/doc/boxes.txt
*/
/* Each shape is encoded as 16-bits. Higher bits are category, lower are data */
/* Categories (mutually exclusive except BDB): */
/* For convenience, BDL/BDA/BBS/BDB are 1 bit each, the rest are enums */
#define BDL (1<<8) /* Box Draw Lines (light/double/heavy) */
#define BDA (1<<9) /* Box Draw Arc (light) */
#define BBD (1<<10) /* Box Block Down (lower) X/8 */
#define BBL (2<<10) /* Box Block Left X/8 */
#define BBU (3<<10) /* Box Block Upper X/8 */
#define BBR (4<<10) /* Box Block Right X/8 */
#define BBQ (5<<10) /* Box Block Quadrants */
#define BRL (6<<10) /* Box Braille (data is lower byte of U28XX) */
#define BBS (1<<14) /* Box Block Shades */
#define BDB (1<<15) /* Box Draw is Bold */
/* (BDL/BDA) Light/Double/Heavy x Left/Up/Right/Down/Horizontal/Vertical */
/* Heavy is light+double (literally drawing light+double align to form heavy) */
#define LL (1<<0)
#define LU (1<<1)
#define LR (1<<2)
#define LD (1<<3)
#define LH (LL+LR)
#define LV (LU+LD)
#define DL (1<<4)
#define DU (1<<5)
#define DR (1<<6)
#define DD (1<<7)
#define DH (DL+DR)
#define DV (DU+DD)
#define HL (LL+DL)
#define HU (LU+DU)
#define HR (LR+DR)
#define HD (LD+DD)
#define HH (HL+HR)
#define HV (HU+HD)
/* (BBQ) Quadrants Top/Bottom x Left/Right */
#define TL (1<<0)
#define TR (1<<1)
#define BL (1<<2)
#define BR (1<<3)
/* Data for U+2500 - U+259F except dashes/diagonals */
static const unsigned short boxdata[256] = {
/* light lines */
[0x00] = BDL + LH, /* light horizontal */
[0x02] = BDL + LV, /* light vertical */
[0x0c] = BDL + LD + LR, /* light down and right */
[0x10] = BDL + LD + LL, /* light down and left */
[0x14] = BDL + LU + LR, /* light up and right */
[0x18] = BDL + LU + LL, /* light up and left */
[0x1c] = BDL + LV + LR, /* light vertical and right */
[0x24] = BDL + LV + LL, /* light vertical and left */
[0x2c] = BDL + LH + LD, /* light horizontal and down */
[0x34] = BDL + LH + LU, /* light horizontal and up */
[0x3c] = BDL + LV + LH, /* light vertical and horizontal */
[0x74] = BDL + LL, /* light left */
[0x75] = BDL + LU, /* light up */
[0x76] = BDL + LR, /* light right */
[0x77] = BDL + LD, /* light down */
/* heavy [+light] lines */
[0x01] = BDL + HH,
[0x03] = BDL + HV,
[0x0d] = BDL + HR + LD,
[0x0e] = BDL + HD + LR,
[0x0f] = BDL + HD + HR,
[0x11] = BDL + HL + LD,
[0x12] = BDL + HD + LL,
[0x13] = BDL + HD + HL,
[0x15] = BDL + HR + LU,
[0x16] = BDL + HU + LR,
[0x17] = BDL + HU + HR,
[0x19] = BDL + HL + LU,
[0x1a] = BDL + HU + LL,
[0x1b] = BDL + HU + HL,
[0x1d] = BDL + HR + LV,
[0x1e] = BDL + HU + LD + LR,
[0x1f] = BDL + HD + LR + LU,
[0x20] = BDL + HV + LR,
[0x21] = BDL + HU + HR + LD,
[0x22] = BDL + HD + HR + LU,
[0x23] = BDL + HV + HR,
[0x25] = BDL + HL + LV,
[0x26] = BDL + HU + LD + LL,
[0x27] = BDL + HD + LU + LL,
[0x28] = BDL + HV + LL,
[0x29] = BDL + HU + HL + LD,
[0x2a] = BDL + HD + HL + LU,
[0x2b] = BDL + HV + HL,
[0x2d] = BDL + HL + LD + LR,
[0x2e] = BDL + HR + LL + LD,
[0x2f] = BDL + HH + LD,
[0x30] = BDL + HD + LH,
[0x31] = BDL + HD + HL + LR,
[0x32] = BDL + HR + HD + LL,
[0x33] = BDL + HH + HD,
[0x35] = BDL + HL + LU + LR,
[0x36] = BDL + HR + LU + LL,
[0x37] = BDL + HH + LU,
[0x38] = BDL + HU + LH,
[0x39] = BDL + HU + HL + LR,
[0x3a] = BDL + HU + HR + LL,
[0x3b] = BDL + HH + HU,
[0x3d] = BDL + HL + LV + LR,
[0x3e] = BDL + HR + LV + LL,
[0x3f] = BDL + HH + LV,
[0x40] = BDL + HU + LH + LD,
[0x41] = BDL + HD + LH + LU,
[0x42] = BDL + HV + LH,
[0x43] = BDL + HU + HL + LD + LR,
[0x44] = BDL + HU + HR + LD + LL,
[0x45] = BDL + HD + HL + LU + LR,
[0x46] = BDL + HD + HR + LU + LL,
[0x47] = BDL + HH + HU + LD,
[0x48] = BDL + HH + HD + LU,
[0x49] = BDL + HV + HL + LR,
[0x4a] = BDL + HV + HR + LL,
[0x4b] = BDL + HV + HH,
[0x78] = BDL + HL,
[0x79] = BDL + HU,
[0x7a] = BDL + HR,
[0x7b] = BDL + HD,
[0x7c] = BDL + HR + LL,
[0x7d] = BDL + HD + LU,
[0x7e] = BDL + HL + LR,
[0x7f] = BDL + HU + LD,
/* double [+light] lines */
[0x50] = BDL + DH,
[0x51] = BDL + DV,
[0x52] = BDL + DR + LD,
[0x53] = BDL + DD + LR,
[0x54] = BDL + DR + DD,
[0x55] = BDL + DL + LD,
[0x56] = BDL + DD + LL,
[0x57] = BDL + DL + DD,
[0x58] = BDL + DR + LU,
[0x59] = BDL + DU + LR,
[0x5a] = BDL + DU + DR,
[0x5b] = BDL + DL + LU,
[0x5c] = BDL + DU + LL,
[0x5d] = BDL + DL + DU,
[0x5e] = BDL + DR + LV,
[0x5f] = BDL + DV + LR,
[0x60] = BDL + DV + DR,
[0x61] = BDL + DL + LV,
[0x62] = BDL + DV + LL,
[0x63] = BDL + DV + DL,
[0x64] = BDL + DH + LD,
[0x65] = BDL + DD + LH,
[0x66] = BDL + DD + DH,
[0x67] = BDL + DH + LU,
[0x68] = BDL + DU + LH,
[0x69] = BDL + DH + DU,
[0x6a] = BDL + DH + LV,
[0x6b] = BDL + DV + LH,
[0x6c] = BDL + DH + DV,
/* (light) arcs */
[0x6d] = BDA + LD + LR,
[0x6e] = BDA + LD + LL,
[0x6f] = BDA + LU + LL,
[0x70] = BDA + LU + LR,
/* Lower (Down) X/8 block (data is 8 - X) */
[0x81] = BBD + 7, [0x82] = BBD + 6, [0x83] = BBD + 5, [0x84] = BBD + 4,
[0x85] = BBD + 3, [0x86] = BBD + 2, [0x87] = BBD + 1, [0x88] = BBD + 0,
/* Left X/8 block (data is X) */
[0x89] = BBL + 7, [0x8a] = BBL + 6, [0x8b] = BBL + 5, [0x8c] = BBL + 4,
[0x8d] = BBL + 3, [0x8e] = BBL + 2, [0x8f] = BBL + 1,
/* upper 1/2 (4/8), 1/8 block (X), right 1/2, 1/8 block (8-X) */
[0x80] = BBU + 4, [0x94] = BBU + 1,
[0x90] = BBR + 4, [0x95] = BBR + 7,
/* Quadrants */
[0x96] = BBQ + BL,
[0x97] = BBQ + BR,
[0x98] = BBQ + TL,
[0x99] = BBQ + TL + BL + BR,
[0x9a] = BBQ + TL + BR,
[0x9b] = BBQ + TL + TR + BL,
[0x9c] = BBQ + TL + TR + BR,
[0x9d] = BBQ + TR,
[0x9e] = BBQ + BL + TR,
[0x9f] = BBQ + BL + TR + BR,
/* Shades, data is an alpha value in 25% units (1/4, 1/2, 3/4) */
[0x91] = BBS + 1, [0x92] = BBS + 2, [0x93] = BBS + 3,
/* U+2504 - U+250B, U+254C - U+254F: unsupported (dashes) */
/* U+2571 - U+2573: unsupported (diagonals) */
};

View File

@ -1,56 +0,0 @@
int extpipeactive = 0;
void
externalpipe(const Arg *arg)
{
int to[2];
char buf[UTF_SIZ];
void (*oldsigpipe)(int);
Glyph *bp, *end;
int lastpos, n, newline;
if (pipe(to) == -1)
return;
switch (fork()) {
case -1:
close(to[0]);
close(to[1]);
return;
case 0:
dup2(to[0], STDIN_FILENO);
close(to[0]);
close(to[1]);
execvp(((char **)arg->v)[0], (char **)arg->v);
fprintf(stderr, "st: execvp %s\n", ((char **)arg->v)[0]);
perror("failed");
exit(0);
}
close(to[0]);
/* ignore sigpipe for now, in case child exists early */
oldsigpipe = signal(SIGPIPE, SIG_IGN);
newline = 0;
for (n = 0; n < term.row; n++) {
bp = term.line[n];
lastpos = MIN(tlinelen(TLINE(n)) + 1, term.col) - 1;
if (lastpos < 0)
break;
end = &bp[lastpos + 1];
for (; bp < end; ++bp)
if (xwrite(to[1], buf, utf8encode(bp->u, buf)) < 0)
break;
if ((newline = term.line[n][lastpos].mode & ATTR_WRAP))
continue;
if (xwrite(to[1], "\n", 1) < 0)
break;
newline = 0;
}
if (newline)
(void)xwrite(to[1], "\n", 1);
close(to[1]);
/* restore */
signal(SIGPIPE, oldsigpipe);
extpipeactive = 1;
}

View File

@ -1 +0,0 @@
void externalpipe(const Arg *);

View File

@ -1,95 +0,0 @@
int
xloadsparefont(FcPattern *pattern, int flags)
{
FcPattern *match;
FcResult result;
match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
if (!match) {
return 1;
}
if (!(frc[frclen].font = XftFontOpenPattern(xw.dpy, match))) {
FcPatternDestroy(match);
return 1;
}
frc[frclen].flags = flags;
/* Believe U+0000 glyph will present in each default font */
frc[frclen].unicodep = 0;
frclen++;
return 0;
}
void
xloadsparefonts(void)
{
FcPattern *pattern;
double fontval;
int fc;
char **fp;
if (frclen != 0)
die("can't embed spare fonts. cache isn't empty");
/* Calculate count of spare fonts */
fc = sizeof(font2) / sizeof(*font2);
if (fc == 0)
return;
/* Allocate memory for cache entries. */
if (frccap < 4 * fc) {
frccap += 4 * fc - frccap;
frc = xrealloc(frc, frccap * sizeof(Fontcache));
}
for (fp = font2; fp - font2 < fc; ++fp) {
if (**fp == '-')
pattern = XftXlfdParse(*fp, False, False);
else
pattern = FcNameParse((FcChar8 *)*fp);
if (!pattern)
die("can't open spare font %s\n", *fp);
if (defaultfontsize > 0 && defaultfontsize != usedfontsize) {
if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
FcResultMatch) {
fontval *= usedfontsize / defaultfontsize;
FcPatternDel(pattern, FC_PIXEL_SIZE);
FcPatternDel(pattern, FC_SIZE);
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, fontval);
} else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
FcResultMatch) {
fontval *= usedfontsize / defaultfontsize;
FcPatternDel(pattern, FC_PIXEL_SIZE);
FcPatternDel(pattern, FC_SIZE);
FcPatternAddDouble(pattern, FC_SIZE, fontval);
}
}
FcPatternAddBool(pattern, FC_SCALABLE, 1);
if (xloadsparefont(pattern, FRC_NORMAL))
die("can't open spare font %s\n", *fp);
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
if (xloadsparefont(pattern, FRC_ITALIC))
die("can't open spare font %s\n", *fp);
FcPatternDel(pattern, FC_WEIGHT);
FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
if (xloadsparefont(pattern, FRC_ITALICBOLD))
die("can't open spare font %s\n", *fp);
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
if (xloadsparefont(pattern, FRC_BOLD))
die("can't open spare font %s\n", *fp);
FcPatternDestroy(pattern);
}
}

View File

@ -1,2 +0,0 @@
static int xloadsparefont(FcPattern *, int);
static void xloadsparefonts(void);

View File

@ -1,21 +0,0 @@
static int invertcolors = 0;
void
invert(const Arg *dummy)
{
invertcolors = !invertcolors;
redraw();
}
Color
invertedcolor(Color *clr)
{
XRenderColor rc;
Color inverted;
rc.red = ~clr->color.red;
rc.green = ~clr->color.green;
rc.blue = ~clr->color.blue;
rc.alpha = clr->color.alpha;
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &rc, &inverted);
return inverted;
}

View File

@ -1 +0,0 @@
static void invert(const Arg *);

View File

@ -1,21 +0,0 @@
void
iso14755(const Arg *arg)
{
FILE *p;
char *us, *e, codepoint[9], uc[UTF_SIZ];
unsigned long utf32;
if (!(p = popen(ISO14755CMD, "r")))
return;
us = fgets(codepoint, sizeof(codepoint), p);
pclose(p);
if (!us || *us == '\0' || *us == '-' || strlen(us) > 7)
return;
if ((utf32 = strtoul(us, &e, 16)) == ULONG_MAX ||
(*e != '\n' && *e != '\0'))
return;
ttywrite(uc, utf8encode(utf32, uc), 1);
}

View File

@ -1,6 +0,0 @@
#define NUMMAXLEN(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
/* constants */
#define ISO14755CMD "dmenu -w \"$WINDOWID\" -p codepoint: </dev/null"
void iso14755(const Arg *);

View File

@ -1,29 +0,0 @@
Shortcuts in keyboard selection mode:
h, j, k, l: move cursor left/down/up/right (also with arrow keys)
H, M, L: move cursor to the top/middle/bottom of the screen
Home, End: move cursor to the top/bottom of the screen
Backspace or 0, $ or A: move cursor to the beginning/end of the line
^ or I: move cursor to the beginning of the indented line
!: move cursor to the middle of the row
_: move cursor to the right edge of the screen
*: move cursor to the center of the screen
w, W jump forward to the start of a word
e, E jump forward to the end of a word
b, B jump backward to the start of a word
g, G: go to the first/last line
z: center the screen on the cursor
PgUp or K, PgDown or J: scroll the page up/down
/, ?: activate input mode and search up/down
n, N: repeat last search and search forward/backward
f, F: jump forward/backward to the given character
t, T: jump forward/backward to before the given character
; or r repeat previous f, t, F or T movement and move forward
, or R repeat previous f, t, F or T movement and move backward
v: toggle selection mode
V: toggle line selection mode
s: toggle regular/rectangular selection type
y: yank (copy) selected text
0 - 9: set the quantifier
Return: quit keyboard_select, yank and keep the highlight of the selection
Escape, q: quit keyboard_select/exit input mode/exit selection mode/reset quantifier

View File

@ -1,30 +0,0 @@
void
newterm(const Arg* a)
{
int res;
switch (fork()) {
case -1:
die("fork failed: %s\n", strerror(errno));
break;
case 0:
switch (fork()) {
case -1:
die("fork failed: %s\n", strerror(errno));
break;
case 0:
res = chdir(getcwd_by_pid(pid));
execlp("st", "./st", NULL);
break;
default:
exit(0);
}
default:
wait(NULL);
}
}
static char *getcwd_by_pid(pid_t pid) {
char buf[32];
snprintf(buf, sizeof buf, "/proc/%d/cwd", pid);
return realpath(buf, NULL);
}

View File

@ -1,2 +0,0 @@
void newterm(const Arg *);
static char *getcwd_by_pid(pid_t pid);

View File

@ -1,865 +0,0 @@
void
tloaddefscreen(int clear, int loadcursor)
{
int col, row, alt = IS_SET(MODE_ALTSCREEN);
if (alt) {
if (clear) {
tclearregion(0, 0, term.col-1, term.row-1, 1);
tdeleteimages();
}
col = term.col, row = term.row;
tswapscreen();
}
if (loadcursor)
tcursor(CURSOR_LOAD);
if (alt)
tresizedef(col, row);
}
void
tloadaltscreen(int clear, int savecursor)
{
int col, row, def = !IS_SET(MODE_ALTSCREEN);
if (savecursor)
tcursor(CURSOR_SAVE);
if (def) {
col = term.col, row = term.row;
kscrolldown(&((Arg){ .i = term.scr }));
tswapscreen();
tresizealt(col, row);
}
if (clear) {
tclearregion(0, 0, term.col-1, term.row-1, 1);
tdeleteimages();
}
}
void
selmove(int n)
{
sel.ob.y += n, sel.nb.y += n;
sel.oe.y += n, sel.ne.y += n;
}
void
tclearglyph(Glyph *gp, int usecurattr)
{
if (usecurattr) {
gp->fg = term.c.attr.fg;
gp->bg = term.c.attr.bg;
} else {
gp->fg = defaultfg;
gp->bg = defaultbg;
}
gp->mode = ATTR_NULL;
gp->u = ' ';
}
void
treflow_moveimages(int oldy, int newy)
{
ImageList *im;
for (im = term.images; im; im = im->next) {
if (im->y == oldy)
im->reflow_y = newy;
}
}
void
treflow(int col, int row)
{
int i, j, x, x2;
int oce, nce, bot, scr;
int ox = 0, oy = -term.histf, nx = 0, ny = -1, len;
int cy = -1; /* proxy for new y coordinate of cursor */
int buflen, nlines;
Line *buf, bufline, line;
ImageList *im, *next;
for (im = term.images; im; im = im->next)
im->reflow_y = INT_MIN; /* unset reflow_y */
/* y coordinate of cursor line end */
for (oce = term.c.y; oce < term.row - 1 &&
tiswrapped(term.line[oce]); oce++);
nlines = HISTSIZE + row;
buf = xmalloc(nlines * sizeof(Line));
do {
if (!nx && ++ny < nlines)
buf[ny] = xmalloc(col * sizeof(Glyph));
if (!ox) {
line = TLINEABS(oy);
len = tlinelen(line);
}
if (oy == term.c.y) {
if (!ox)
len = MAX(len, term.c.x + 1);
/* update cursor */
if (cy < 0 && term.c.x - ox < col - nx) {
term.c.x = nx + term.c.x - ox, cy = ny;
UPDATEWRAPNEXT(0, col);
}
}
/* get reflowed lines in buf */
bufline = buf[ny % nlines];
if (col - nx > len - ox) {
memcpy(&bufline[nx], &line[ox], (len-ox) * sizeof(Glyph));
nx += len - ox;
if (len == 0 || !(line[len - 1].mode & ATTR_WRAP)) {
for (j = nx; j < col; j++)
tclearglyph(&bufline[j], 0);
treflow_moveimages(oy+term.scr, ny);
nx = 0;
} else if (nx > 0) {
bufline[nx - 1].mode &= ~ATTR_WRAP;
}
ox = 0, oy++;
} else if (col - nx == len - ox) {
memcpy(&bufline[nx], &line[ox], (col-nx) * sizeof(Glyph));
treflow_moveimages(oy+term.scr, ny);
ox = 0, oy++, nx = 0;
} else/* if (col - nx < len - ox) */ {
memcpy(&bufline[nx], &line[ox], (col-nx) * sizeof(Glyph));
if (bufline[col - 1].mode & ATTR_WIDE) {
bufline[col - 2].mode |= ATTR_WRAP;
tclearglyph(&bufline[col - 1], 0);
ox--;
} else {
bufline[col - 1].mode |= ATTR_WRAP;
}
treflow_moveimages(oy+term.scr, ny);
ox += col - nx;
nx = 0;
}
} while (oy <= oce);
if (nx)
for (j = nx; j < col; j++)
tclearglyph(&bufline[j], 0);
/* free extra lines */
for (i = row; i < term.row; i++)
free(term.line[i]);
/* resize to new height */
term.line = xrealloc(term.line, row * sizeof(Line));
buflen = MIN(ny + 1, nlines);
bot = MIN(ny, row - 1);
scr = MAX(row - term.row, 0);
/* update y coordinate of cursor line end */
nce = MIN(oce + scr, bot);
/* update cursor y coordinate */
term.c.y = nce - (ny - cy);
if (term.c.y < 0) {
j = nce, nce = MIN(nce + -term.c.y, bot);
term.c.y += nce - j;
while (term.c.y < 0) {
free(buf[ny-- % nlines]);
buflen--;
term.c.y++;
}
}
/* allocate new rows */
for (i = row - 1; i > nce; i--) {
if (i >= term.row)
term.line[i] = xmalloc(col * sizeof(Glyph));
else
term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
for (j = 0; j < col; j++)
tclearglyph(&term.line[i][j], 0);
}
/* fill visible area */
for (/*i = nce */; i >= term.row; i--, ny--, buflen--)
term.line[i] = buf[ny % nlines];
for (/*i = term.row - 1 */; i >= 0; i--, ny--, buflen--) {
free(term.line[i]);
term.line[i] = buf[ny % nlines];
}
/* fill lines in history buffer and update term.histf */
for (/*i = -1 */; buflen > 0 && i >= -HISTSIZE; i--, ny--, buflen--) {
j = (term.histi + i + 1 + HISTSIZE) % HISTSIZE;
free(term.hist[j]);
term.hist[j] = buf[ny % nlines];
}
term.histf = -i - 1;
term.scr = MIN(term.scr, term.histf);
/* resize rest of the history lines */
for (/*i = -term.histf - 1 */; i >= -HISTSIZE; i--) {
j = (term.histi + i + 1 + HISTSIZE) % HISTSIZE;
term.hist[j] = xrealloc(term.hist[j], col * sizeof(Glyph));
}
/* move images to the final position */
for (im = term.images; im; im = next) {
next = im->next;
if (im->reflow_y == INT_MIN) {
delete_image(im);
} else {
im->y = im->reflow_y - term.histf + term.scr - (ny + 1);
if (im->y - term.scr < -HISTSIZE || im->y - term.scr >= row)
delete_image(im);
}
}
/* expand images into new text cells */
for (im = term.images; im; im = next) {
next = im->next;
if (im->x < col) {
line = TLINE(im->y);
x2 = MIN(im->x + im->cols, col);
for (x = im->x; x < x2; x++)
line[x].mode |= ATTR_SIXEL;
}
}
for (; buflen > 0; ny--, buflen--)
free(buf[ny % nlines]);
free(buf);
}
void
rscrolldown(int n)
{
int i;
Line temp;
/* can never be true as of now
if (IS_SET(MODE_ALTSCREEN))
return; */
if ((n = MIN(n, term.histf)) <= 0)
return;
for (i = term.c.y + n; i >= n; i--) {
temp = term.line[i];
term.line[i] = term.line[i-n];
term.line[i-n] = temp;
}
for (/*i = n - 1 */; i >= 0; i--) {
temp = term.line[i];
term.line[i] = term.hist[term.histi];
term.hist[term.histi] = temp;
term.histi = (term.histi - 1 + HISTSIZE) % HISTSIZE;
}
term.c.y += n;
term.histf -= n;
if ((i = term.scr - n) >= 0) {
term.scr = i;
} else {
scroll_images(n - term.scr);
term.scr = 0;
if (sel.ob.x != -1 && !sel.alt)
selmove(-i);
}
}
void
tresizedef(int col, int row)
{
int i, j;
/* return if dimensions haven't changed */
if (term.col == col && term.row == row) {
tfulldirt();
return;
}
if (col != term.col) {
if (!sel.alt)
selremove();
treflow(col, row);
} else {
/* slide screen up if otherwise cursor would get out of the screen */
if (term.c.y >= row) {
tscrollup(0, term.row - 1, term.c.y - row + 1, SCROLL_RESIZE);
term.c.y = row - 1;
}
for (i = row; i < term.row; i++)
free(term.line[i]);
/* resize to new height */
term.line = xrealloc(term.line, row * sizeof(Line));
/* allocate any new rows */
for (i = term.row; i < row; i++) {
term.line[i] = xmalloc(col * sizeof(Glyph));
for (j = 0; j < col; j++)
tclearglyph(&term.line[i][j], 0);
}
/* scroll down as much as height has increased */
rscrolldown(row - term.row);
}
/* update terminal size */
term.col = col, term.row = row;
/* reset scrolling region */
term.top = 0, term.bot = row - 1;
/* dirty all lines */
tfulldirt();
}
void
tresizealt(int col, int row)
{
int i, j;
ImageList *im, *next;
/* return if dimensions haven't changed */
if (term.col == col && term.row == row) {
tfulldirt();
return;
}
if (sel.alt)
selremove();
/* slide screen up if otherwise cursor would get out of the screen */
for (i = 0; i <= term.c.y - row; i++)
free(term.line[i]);
if (i > 0) {
/* ensure that both src and dst are not NULL */
memmove(term.line, term.line + i, row * sizeof(Line));
scroll_images(-i);
term.c.y = row - 1;
}
for (i += row; i < term.row; i++)
free(term.line[i]);
/* resize to new height */
term.line = xrealloc(term.line, row * sizeof(Line));
/* resize to new width */
for (i = 0; i < MIN(row, term.row); i++) {
term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
for (j = term.col; j < col; j++)
tclearglyph(&term.line[i][j], 0);
}
/* allocate any new rows */
for (/*i = MIN(row, term.row) */; i < row; i++) {
term.line[i] = xmalloc(col * sizeof(Glyph));
for (j = 0; j < col; j++)
tclearglyph(&term.line[i][j], 0);
}
/* update cursor */
if (term.c.x >= col) {
term.c.state &= ~CURSOR_WRAPNEXT;
term.c.x = col - 1;
} else {
UPDATEWRAPNEXT(1, col);
}
/* update terminal size */
term.col = col, term.row = row;
/* reset scrolling region */
term.top = 0, term.bot = row - 1;
/* delete or clip images if they are not inside the screen */
for (im = term.images; im; im = next) {
next = im->next;
if (im->x >= term.col || im->y >= term.row || im->y < 0) {
delete_image(im);
} else {
if ((im->cols = MIN(im->x + im->cols, term.col) - im->x) <= 0)
delete_image(im);
}
}
/* dirty all lines */
tfulldirt();
}
void
kscrolldown(const Arg* a)
{
int n = a->i;
if (!term.scr || IS_SET(MODE_ALTSCREEN))
return;
if (n < 0)
n = MAX(term.row / -n, 1);
if (n <= term.scr) {
term.scr -= n;
} else {
n = term.scr;
term.scr = 0;
}
if (sel.ob.x != -1 && !sel.alt)
selmove(-n); /* negate change in term.scr */
tfulldirt();
scroll_images(-1*n);
}
void
kscrollup(const Arg* a)
{
int n = a->i;
if (!term.histf || IS_SET(MODE_ALTSCREEN))
return;
if (n < 0)
n = MAX(term.row / -n, 1);
if (term.scr + n <= term.histf) {
term.scr += n;
} else {
n = term.histf - term.scr;
term.scr = term.histf;
}
if (sel.ob.x != -1 && !sel.alt)
selmove(n); /* negate change in term.scr */
tfulldirt();
scroll_images(n);
}
void
tscrollup(int top, int bot, int n, int mode)
{
int i, j, s;
Line temp;
int alt = IS_SET(MODE_ALTSCREEN);
int savehist = !alt && top == 0 && mode != SCROLL_NOSAVEHIST;
int scr = alt ? 0 : term.scr;
int itop = top + scr, ibot = bot + scr;
ImageList *im, *next;
if (n <= 0)
return;
n = MIN(n, bot-top+1);
if (savehist) {
for (i = 0; i < n; i++) {
term.histi = (term.histi + 1) % HISTSIZE;
temp = term.hist[term.histi];
for (j = 0; j < term.col; j++)
tclearglyph(&temp[j], 1);
term.hist[term.histi] = term.line[i];
term.line[i] = temp;
}
term.histf = MIN(term.histf + n, HISTSIZE);
s = n;
if (term.scr) {
j = term.scr;
term.scr = MIN(j + n, HISTSIZE);
s = j + n - term.scr;
}
if (mode != SCROLL_RESIZE)
tfulldirt();
} else {
tclearregion(0, top, term.col-1, top+n-1, 1);
tsetdirt(top + scr, bot + scr);
}
for (i = top; i <= bot-n; i++) {
temp = term.line[i];
term.line[i] = term.line[i+n];
term.line[i+n] = temp;
}
if (alt || !savehist) {
/* move images, if they are inside the scrolling region */
for (im = term.images; im; im = next) {
next = im->next;
if (im->y >= itop && im->y <= ibot) {
im->y -= n;
if (im->y < itop)
delete_image(im);
}
}
} else {
/* move images, if they are inside the scrolling region or scrollback */
for (im = term.images; im; im = next) {
next = im->next;
im->y -= scr;
if (im->y < 0) {
im->y -= n;
} else if (im->y >= top && im->y <= bot) {
im->y -= n;
if (im->y < top)
im->y -= top; // move to scrollback
}
if (im->y < -HISTSIZE)
delete_image(im);
else
im->y += term.scr;
}
}
if (sel.ob.x != -1 && sel.alt == alt) {
if (!savehist) {
selscroll(top, bot, -n);
} else if (s > 0) {
selmove(-s);
if (-term.scr + sel.nb.y < -term.histf)
selremove();
}
}
}
void
tscrolldown(int top, int n)
{
int i, bot = term.bot;
int scr = IS_SET(MODE_ALTSCREEN) ? 0 : term.scr;
int itop = top + scr, ibot = bot + scr;
Line temp;
ImageList *im, *next;
if (n <= 0)
return;
n = MIN(n, bot-top+1);
tsetdirt(top + scr, bot + scr);
tclearregion(0, bot-n+1, term.col-1, bot, 1);
for (i = bot; i >= top+n; i--) {
temp = term.line[i];
term.line[i] = term.line[i-n];
term.line[i-n] = temp;
}
/* move images, if they are inside the scrolling region */
for (im = term.images; im; im = next) {
next = im->next;
if (im->y >= itop && im->y <= ibot) {
im->y += n;
if (im->y > ibot)
delete_image(im);
}
}
if (sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN))
selscroll(top, bot, n);
}
void
tresize(int col, int row)
{
int *bp;
term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
if (col > term.col) {
bp = term.tabs + term.col;
memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
while (--bp > term.tabs && !*bp)
/* nothing */ ;
for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
*bp = 1;
}
if (IS_SET(MODE_ALTSCREEN))
tresizealt(col, row);
else
tresizedef(col, row);
}
void
tclearregion(int x1, int y1, int x2, int y2, int usecurattr)
{
int x, y;
/* regionselected() takes relative coordinates */
if (regionselected(x1+term.scr, y1+term.scr, x2+term.scr, y2+term.scr))
selremove();
for (y = y1; y <= y2; y++) {
term.dirty[y] = 1;
for (x = x1; x <= x2; x++)
tclearglyph(&term.line[y][x], usecurattr);
}
}
void
tnew(int col, int row)
{
int i, j;
for (i = 0; i < 2; i++) {
term.line = xmalloc(row * sizeof(Line));
for (j = 0; j < row; j++)
term.line[j] = xmalloc(col * sizeof(Glyph));
term.col = col, term.row = row;
tswapscreen();
}
term.dirty = xmalloc(row * sizeof(*term.dirty));
term.tabs = xmalloc(col * sizeof(*term.tabs));
for (i = 0; i < HISTSIZE; i++)
term.hist[i] = xmalloc(col * sizeof(Glyph));
treset();
}
void
tdeletechar(int n)
{
int src, dst, size;
Line line;
if (n <= 0)
return;
dst = term.c.x;
src = MIN(term.c.x + n, term.col);
size = term.col - src;
if (size > 0) { /* otherwise src would point beyond the array
https://stackoverflow.com/questions/29844298 */
line = term.line[term.c.y];
memmove(&line[dst], &line[src], size * sizeof(Glyph));
}
tclearregion(dst + size, term.c.y, term.col - 1, term.c.y, 1);
}
void
tinsertblank(int n)
{
int src, dst, size;
Line line;
if (n <= 0)
return;
dst = MIN(term.c.x + n, term.col);
src = term.c.x;
size = term.col - dst;
if (size > 0) { /* otherwise dst would point beyond the array */
line = term.line[term.c.y];
memmove(&line[dst], &line[src], size * sizeof(Glyph));
}
tclearregion(src, term.c.y, dst - 1, term.c.y, 1);
}
int
tlinelen(Line line)
{
int i = term.col - 1;
/* We are using a different algorithm on the alt screen because an
* application might use spaces to clear the screen and in that case it is
* impossible to find the end of the line when every cell has the ATTR_SET
* attribute. The second algorithm is more accurate on the main screen and
* and we can use it there. */
if (IS_SET(MODE_ALTSCREEN))
for (; i >= 0 && !(line[i].mode & ATTR_WRAP) && line[i].u == ' '; i--);
else
for (; i >= 0 && !(line[i].mode & (ATTR_SET | ATTR_WRAP)); i--);
return i + 1;
}
int
tiswrapped(Line line)
{
int len = tlinelen(line);
return len > 0 && (line[len - 1].mode & ATTR_WRAP);
}
char *
tgetglyphs(char *buf, const Glyph *gp, const Glyph *lgp)
{
while (gp <= lgp)
if (gp->mode & ATTR_WDUMMY) {
gp++;
} else {
buf += utf8encode((gp++)->u, buf);
}
return buf;
}
size_t
tgetline(char *buf, const Glyph *fgp)
{
char *ptr;
const Glyph *lgp = &fgp[term.col - 1];
while (lgp > fgp && !(lgp->mode & (ATTR_SET | ATTR_WRAP)))
lgp--;
ptr = tgetglyphs(buf, fgp, lgp);
if (!(lgp->mode & ATTR_WRAP))
*(ptr++) = '\n';
return ptr - buf;
}
int
regionselected(int x1, int y1, int x2, int y2)
{
if (sel.ob.x == -1 || sel.mode == SEL_EMPTY ||
sel.alt != IS_SET(MODE_ALTSCREEN) || sel.nb.y > y2 || sel.ne.y < y1)
return 0;
return (sel.type == SEL_RECTANGULAR) ? sel.nb.x <= x2 && sel.ne.x >= x1
: (sel.nb.y != y2 || sel.nb.x <= x2) &&
(sel.ne.y != y1 || sel.ne.x >= x1);
}
int
selected(int x, int y)
{
return regionselected(x, y, x, y);
}
void
selsnap(int *x, int *y, int direction)
{
int newx, newy;
int rtop = 0, rbot = term.row - 1;
int delim, prevdelim, maxlen;
const Glyph *gp, *prevgp;
if (!IS_SET(MODE_ALTSCREEN))
rtop += -term.histf + term.scr, rbot += term.scr;
switch (sel.snap) {
case SNAP_WORD:
/*
* Snap around if the word wraps around at the end or
* beginning of a line.
*/
maxlen = (TLINE(*y)[term.col-2].mode & ATTR_WRAP) ? term.col-1 : term.col;
LIMIT(*x, 0, maxlen - 1);
prevgp = &TLINE(*y)[*x];
prevdelim = ISDELIM(prevgp->u);
for (;;) {
newx = *x + direction;
newy = *y;
if (!BETWEEN(newx, 0, maxlen - 1)) {
newy += direction;
if (!BETWEEN(newy, rtop, rbot))
break;
if (!tiswrapped(TLINE(direction > 0 ? *y : newy)))
break;
maxlen = (TLINE(newy)[term.col-2].mode & ATTR_WRAP) ? term.col-1 : term.col;
newx = direction > 0 ? 0 : maxlen - 1;
}
gp = &TLINE(newy)[newx];
delim = ISDELIM(gp->u);
if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
|| (delim && gp->u != prevgp->u)))
break;
*x = newx;
*y = newy;
if (!(gp->mode & ATTR_WDUMMY)) {
prevgp = gp;
prevdelim = delim;
}
}
break;
case SNAP_LINE:
/*
* Snap around if the the previous line or the current one
* has set ATTR_WRAP at its end. Then the whole next or
* previous line will be selected.
*/
*x = (direction < 0) ? 0 : term.col - 1;
if (direction < 0) {
for (; *y > rtop; *y -= 1) {
if (!tiswrapped(TLINE(*y-1)))
break;
}
} else if (direction > 0) {
for (; *y < rbot; *y += 1) {
if (!tiswrapped(TLINE(*y)))
break;
}
}
break;
}
}
void
selscroll(int top, int bot, int n)
{
/* turn absolute coordinates into relative */
top += term.scr, bot += term.scr;
if (BETWEEN(sel.nb.y, top, bot) != BETWEEN(sel.ne.y, top, bot)) {
selclear();
} else if (BETWEEN(sel.nb.y, top, bot)) {
selmove(n);
if (sel.nb.y < top || sel.ne.y > bot)
selclear();
}
}
void
tswapscreen(void)
{
static Line *altline;
static int altcol, altrow;
Line *tmpline = term.line;
int tmpcol = term.col, tmprow = term.row;
ImageList *im = term.images;
term.line = altline;
term.col = altcol, term.row = altrow;
altline = tmpline;
altcol = tmpcol, altrow = tmprow;
term.mode ^= MODE_ALTSCREEN;
term.images = term.images_alt;
term.images_alt = im;
}
char *
getsel(void)
{
char *str, *ptr;
int y, lastx, linelen;
const Glyph *gp, *lgp;
if (sel.ob.x == -1 || sel.alt != IS_SET(MODE_ALTSCREEN))
return NULL;
str = xmalloc((term.col + 1) * (sel.ne.y - sel.nb.y + 1) * UTF_SIZ);
ptr = str;
/* append every set & selected glyph to the selection */
for (y = sel.nb.y; y <= sel.ne.y; y++) {
Line line = TLINE(y);
if ((linelen = tlinelen(line)) == 0) {
*ptr++ = '\n';
continue;
}
if (sel.type == SEL_RECTANGULAR) {
gp = &line[sel.nb.x];
lastx = sel.ne.x;
} else {
gp = &line[sel.nb.y == y ? sel.nb.x : 0];
lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
}
lgp = &line[MIN(lastx, linelen-1)];
ptr = tgetglyphs(ptr, gp, lgp);
/*
* Copy and pasting of line endings is inconsistent
* in the inconsistent terminal and GUI world.
* The best solution seems like to produce '\n' when
* something is copied from st and convert '\n' to
* '\r', when something to be pasted is received by
* st.
* FIXME: Fix the computer world.
*/
if ((y < sel.ne.y || lastx >= linelen) &&
(!(lgp->mode & ATTR_WRAP) || sel.type == SEL_RECTANGULAR))
*ptr++ = '\n';
}
*ptr = '\0';
return str;
}
void
tdumpline(int n)
{
char str[(term.col + 1) * UTF_SIZ];
tprinter(str, tgetline(str, &term.line[n][0]));
}

View File

@ -1,44 +0,0 @@
#define TLINE(y) ( \
(y) < term.scr ? term.hist[(term.histi + (y) - term.scr + 1 + HISTSIZE) % HISTSIZE] \
: term.line[(y) - term.scr] \
)
#define TLINEABS(y) ( \
(y) < 0 ? term.hist[(term.histi + (y) + 1 + HISTSIZE) % HISTSIZE] : term.line[(y)] \
)
#define UPDATEWRAPNEXT(alt, col) do { \
if ((term.c.state & CURSOR_WRAPNEXT) && term.c.x + term.wrapcwidth[alt] < col) { \
term.c.x += term.wrapcwidth[alt]; \
term.c.state &= ~CURSOR_WRAPNEXT; \
} \
} while (0);
static int tiswrapped(Line line);
static size_t tgetline(char *, const Glyph *);
static inline int regionselected(int, int, int, int);
static void tloaddefscreen(int, int);
static void tloadaltscreen(int, int);
static void selmove(int);
static inline void tclearglyph(Glyph *, int);
static void treflow(int, int);
static void rscrolldown(int);
static void tresizedef(int, int);
static void tresizealt(int, int);
void kscrolldown(const Arg *);
void kscrollup(const Arg *);
static void tscrollup(int, int, int, int);
static void tclearregion(int, int, int, int, int);
static void tdeletechar(int);
static int tlinelen(Line len);
static char * tgetglyphs(char *buf, const Glyph *gp, const Glyph *lgp);
static void selscroll(int, int, int);
typedef struct {
uint b;
uint mask;
void (*func)(const Arg *);
const Arg arg;
} MouseKey;
extern MouseKey mkeys[];

View File

@ -1,19 +0,0 @@
#if defined(__OpenBSD__)
#include <sys/sysctl.h>
#endif
int
subprocwd(char *path)
{
#if defined(__linux)
if (snprintf(path, PATH_MAX, "/proc/%d/cwd", pid) < 0)
return -1;
return 0;
#elif defined(__OpenBSD__)
size_t sz = PATH_MAX;
int name[3] = {CTL_KERN, KERN_PROC_CWD, pid};
if (sysctl(name, 3, path, &sz, 0, 0) == -1)
return -1;
return 0;
#endif
}

View File

@ -1 +0,0 @@
int subprocwd(char *);

View File

@ -1,24 +0,0 @@
#include <sys/wait.h>
void
plumb(char *sel) {
if (sel == NULL)
return;
char cwd[PATH_MAX];
pid_t child;
if (subprocwd(cwd) != 0)
return;
switch(child = fork()) {
case -1:
return;
case 0:
if (chdir(cwd) != 0)
exit(1);
if (execvp(plumb_cmd, (char *const []){plumb_cmd, sel, 0}) == -1)
exit(1);
exit(0);
default:
waitpid(child, NULL, 0);
}
}

View File

@ -1 +0,0 @@
void plumb(char *);

View File

@ -1,6 +0,0 @@
/* Patches */
#include "externalpipe.c"
#include "iso14755.c"
#include "rightclicktoplumb_st.c"
#include "newterm.c"
#include "reflow.c"

View File

@ -1,6 +0,0 @@
/* Patches */
#include "externalpipe.h"
#include "iso14755.h"
#include "rightclicktoplumb_st.h"
#include "newterm.h"
#include "reflow.h"

View File

@ -1,23 +0,0 @@
/// Dynamic memory-chunk, with (1) datatype size, (2/3) initialized / allocated chunk, (4) content
typedef struct { uint8_t const elSize; uint32_t init, alloc; char* content; } DynamicArray;
#define UTF8_ARRAY {4, 0, 0, NULL}
static inline int p_alloc(DynamicArray *s, uint32_t amount) {
uint32_t const diff=s->init+s->elSize*amount-s->alloc, nas=s->alloc+max(diff,15)*s->elSize;
if (s->alloc < s->init + s->elSize * amount) {
char* tmp = realloc(s->content, nas);
if (!tmp) return 0;
s->alloc = nas, s->content = tmp;
}
return 1;
}
static inline char *view(DynamicArray * s, uint32_t i) { return s->content + i*s->elSize; }
static inline char *end(DynamicArray *s, uint32_t i) { return s->content +s->init-(i+1)*s->elSize; }
static inline uint32_t getU32(DynamicArray* s, uint32_t i, int b) { return *((uint32_t*) (b ?view(s,i) :end(s,i))); }
static char *expand(DynamicArray *s) { if (!p_alloc(s, 1)) return NULL; s->init += s->elSize; return end(s, 0); }
static inline void pop(DynamicArray* s) { s->init -= s->elSize; }
static inline void empty(DynamicArray* s) { s->init = 0; }
static inline int size(DynamicArray const * s) { return s->init / s->elSize; }
static inline void assign(DynamicArray* s, DynamicArray const *o) {
if (p_alloc(s, size(o))) memcpy(s->content, o->content, (s->init=o->init));
}

View File

@ -1,7 +0,0 @@
/* Patches */
#include "alpha.c"
#include "boxdraw.c"
#include "font2.c"
#include "invert.c"
#include "rightclicktoplumb_x.c"
#include "xresources.c"

View File

@ -1,7 +0,0 @@
/* Patches */
#include "alpha.h"
#include "boxdraw.h"
#include "font2.h"
#include "invert.h"
#include "rightclicktoplumb_x.h"
#include "xresources.h"

View File

@ -1,78 +0,0 @@
int
resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
{
char **sdst = dst;
int *idst = dst;
float *fdst = dst;
char fullname[256];
char fullclass[256];
char *type;
XrmValue ret;
snprintf(fullname, sizeof(fullname), "%s.%s",
opt_name ? opt_name : "st", name);
snprintf(fullclass, sizeof(fullclass), "%s.%s",
opt_class ? opt_class : "St", name);
fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0';
XrmGetResource(db, fullname, fullclass, &type, &ret);
if (ret.addr == NULL || strncmp("String", type, 64))
return 1;
switch (rtype) {
case STRING:
*sdst = ret.addr;
break;
case INTEGER:
*idst = strtoul(ret.addr, NULL, 10);
break;
case FLOAT:
*fdst = strtof(ret.addr, NULL);
break;
}
return 0;
}
void
config_init(Display *dpy)
{
char *resm;
XrmDatabase db;
ResourcePref *p;
XrmInitialize();
resm = XResourceManagerString(dpy);
if (!resm)
return;
db = XrmGetStringDatabase(resm);
for (p = resources; p < resources + LEN(resources); p++)
resource_load(db, p->name, p->type, p->dst);
}
void
reload_config(int sig)
{
/* Recreate a Display object to have up to date Xresources entries */
Display *dpy;
if (!(dpy = XOpenDisplay(NULL)))
die("Can't open display\n");
config_init(dpy);
xloadcols();
/* nearly like zoomabs() */
xunloadfonts();
xloadfonts(font, 0); /* font <- config_init() */
xloadsparefonts();
cresize(0, 0);
redraw();
xhints();
XCloseDisplay(dpy);
/* from https://st.suckless.org/patches/xresources-with-reload-signal */
/* triggers re-render if we're visible */
ttywrite("\033[O", 3, 1);
}

View File

@ -1,17 +0,0 @@
#include <X11/Xresource.h>
/* Xresources preferences */
enum resource_type {
STRING = 0,
INTEGER = 1,
FLOAT = 2
};
typedef struct {
char *name;
enum resource_type type;
void *dst;
} ResourcePref;
int resource_load(XrmDatabase, char *, enum resource_type, void *);
void config_init(Display *dpy);

View File

@ -1,687 +0,0 @@
// sixel.c (part of mintty)
// originally written by kmiya@cluti (https://github.com/saitoha/sixel/blob/master/fromsixel.c)
// Licensed under the terms of the GNU General Public License v3 or later.
#include <stdlib.h>
#include <string.h> /* memcpy */
#include "st.h"
#include "win.h"
#include "sixel.h"
#include "sixel_hls.h"
#define SIXEL_RGB(r, g, b) ((255 << 24) + ((r) << 16) + ((g) << 8) + (b))
#define SIXEL_PALVAL(n,a,m) (((n) * (a) + ((m) / 2)) / (m))
#define SIXEL_XRGB(r,g,b) SIXEL_RGB(SIXEL_PALVAL(r, 255, 100), SIXEL_PALVAL(g, 255, 100), SIXEL_PALVAL(b, 255, 100))
static sixel_color_t const sixel_default_color_table[] = {
SIXEL_XRGB( 0, 0, 0), /* 0 Black */
SIXEL_XRGB(20, 20, 80), /* 1 Blue */
SIXEL_XRGB(80, 13, 13), /* 2 Red */
SIXEL_XRGB(20, 80, 20), /* 3 Green */
SIXEL_XRGB(80, 20, 80), /* 4 Magenta */
SIXEL_XRGB(20, 80, 80), /* 5 Cyan */
SIXEL_XRGB(80, 80, 20), /* 6 Yellow */
SIXEL_XRGB(53, 53, 53), /* 7 Gray 50% */
SIXEL_XRGB(26, 26, 26), /* 8 Gray 25% */
SIXEL_XRGB(33, 33, 60), /* 9 Blue* */
SIXEL_XRGB(60, 26, 26), /* 10 Red* */
SIXEL_XRGB(33, 60, 33), /* 11 Green* */
SIXEL_XRGB(60, 33, 60), /* 12 Magenta* */
SIXEL_XRGB(33, 60, 60), /* 13 Cyan* */
SIXEL_XRGB(60, 60, 33), /* 14 Yellow* */
SIXEL_XRGB(80, 80, 80), /* 15 Gray 75% */
};
void
scroll_images(int n) {
ImageList *im, *next;
int top = tisaltscr() ? 0 : term.scr - HISTSIZE;
for (im = term.images; im; im = next) {
next = im->next;
im->y += n;
/* check if the current sixel has exceeded the maximum
* draw distance, and should therefore be deleted */
if (im->y < top) {
//fprintf(stderr, "im@0x%08x exceeded maximum distance\n");
delete_image(im);
}
}
}
void
delete_image(ImageList *im)
{
if (im->prev)
im->prev->next = im->next;
else
term.images = im->next;
if (im->next)
im->next->prev = im->prev;
if (im->pixmap)
XFreePixmap(xw.dpy, (Drawable)im->pixmap);
if (im->clipmask)
XFreePixmap(xw.dpy, (Drawable)im->clipmask);
free(im->pixels);
free(im);
}
static int
set_default_color(sixel_image_t *image)
{
int i;
int n;
int r;
int g;
int b;
/* palette initialization */
for (n = 1; n < 17; n++) {
image->palette[n] = sixel_default_color_table[n - 1];
}
/* colors 17-232 are a 6x6x6 color cube */
for (r = 0; r < 6; r++) {
for (g = 0; g < 6; g++) {
for (b = 0; b < 6; b++) {
image->palette[n++] = SIXEL_RGB(r * 51, g * 51, b * 51);
}
}
}
/* colors 233-256 are a grayscale ramp, intentionally leaving out */
for (i = 0; i < 24; i++) {
image->palette[n++] = SIXEL_RGB(i * 11, i * 11, i * 11);
}
for (; n < DECSIXEL_PALETTE_MAX; n++) {
image->palette[n] = SIXEL_RGB(255, 255, 255);
}
return (0);
}
static int
sixel_image_init(
sixel_image_t *image,
int width,
int height,
int fgcolor,
int bgcolor,
int use_private_register)
{
int status = (-1);
size_t size;
size = (size_t)(width * height) * sizeof(sixel_color_no_t);
image->width = width;
image->height = height;
image->data = (sixel_color_no_t *)malloc(size);
image->ncolors = 2;
image->use_private_register = use_private_register;
if (image->data == NULL) {
status = (-1);
goto end;
}
memset(image->data, 0, size);
image->palette[0] = bgcolor;
if (image->use_private_register)
image->palette[1] = fgcolor;
image->palette_modified = 0;
status = (0);
end:
return status;
}
static int
image_buffer_resize(
sixel_image_t *image,
int width,
int height)
{
int status = (-1);
size_t size;
sixel_color_no_t *alt_buffer;
int n;
int min_height;
size = (size_t)(width * height) * sizeof(sixel_color_no_t);
alt_buffer = (sixel_color_no_t *)malloc(size);
if (alt_buffer == NULL) {
/* free source image */
free(image->data);
image->data = NULL;
status = (-1);
goto end;
}
min_height = height > image->height ? image->height: height;
if (width > image->width) { /* if width is extended */
for (n = 0; n < min_height; ++n) {
/* copy from source image */
memcpy(alt_buffer + width * n,
image->data + image->width * n,
(size_t)image->width * sizeof(sixel_color_no_t));
/* fill extended area with background color */
memset(alt_buffer + width * n + image->width,
0,
(size_t)(width - image->width) * sizeof(sixel_color_no_t));
}
} else {
for (n = 0; n < min_height; ++n) {
/* copy from source image */
memcpy(alt_buffer + width * n,
image->data + image->width * n,
(size_t)width * sizeof(sixel_color_no_t));
}
}
if (height > image->height) { /* if height is extended */
/* fill extended area with background color */
memset(alt_buffer + width * image->height,
0,
(size_t)(width * (height - image->height)) * sizeof(sixel_color_no_t));
}
/* free source image */
free(image->data);
image->data = alt_buffer;
image->width = width;
image->height = height;
status = (0);
end:
return status;
}
static void
sixel_image_deinit(sixel_image_t *image)
{
if (image->data)
free(image->data);
image->data = NULL;
}
int
sixel_parser_init(sixel_state_t *st,
int transparent,
sixel_color_t fgcolor, sixel_color_t bgcolor,
unsigned char use_private_register,
int cell_width, int cell_height)
{
int status = (-1);
st->state = PS_DECSIXEL;
st->pos_x = 0;
st->pos_y = 0;
st->max_x = 0;
st->max_y = 0;
st->attributed_pan = 2;
st->attributed_pad = 1;
st->attributed_ph = 0;
st->attributed_pv = 0;
st->transparent = transparent;
st->repeat_count = 1;
st->color_index = 16;
st->grid_width = cell_width;
st->grid_height = cell_height;
st->nparams = 0;
st->param = 0;
/* buffer initialization */
status = sixel_image_init(&st->image, 1, 1, fgcolor, transparent ? 0 : bgcolor, use_private_register);
return status;
}
int
sixel_parser_set_default_color(sixel_state_t *st)
{
return set_default_color(&st->image);
}
int
sixel_parser_finalize(sixel_state_t *st, ImageList **newimages, int cx, int cy, int cw, int ch)
{
sixel_image_t *image = &st->image;
int x, y;
sixel_color_no_t *src;
sixel_color_t *dst;
int color;
int w, h;
int i, j, cols, numimages;
ImageList *im, *next, *tail;
if (!image->data)
return -1;
if (++st->max_x < st->attributed_ph)
st->max_x = st->attributed_ph;
if (++st->max_y < st->attributed_pv)
st->max_y = st->attributed_pv;
if (image->use_private_register && image->ncolors > 2 && !image->palette_modified) {
if (set_default_color(image) < 0)
return -1;
}
w = MIN(st->max_x, image->width);
h = MIN(st->max_y, image->height);
if ((numimages = (h + ch-1) / ch) <= 0)
return -1;
cols = (w + cw-1) / cw;
*newimages = NULL, tail = NULL;
for (y = 0, i = 0; i < numimages; i++) {
if ((im = malloc(sizeof(ImageList)))) {
if (!tail) {
*newimages = tail = im;
im->prev = im->next = NULL;
} else {
tail->next = im;
im->prev = tail;
im->next = NULL;
tail = im;
}
im->x = cx;
im->y = cy + i;
im->cols = cols;
im->width = w;
im->height = MIN(h - ch * i, ch);
im->pixels = malloc(im->width * im->height * 4);
im->pixmap = NULL;
im->clipmask = NULL;
im->cw = cw;
im->ch = ch;
im->transparent = st->transparent;
}
if (!im || !im->pixels) {
for (im = *newimages; im; im = next) {
next = im->next;
if (im->pixels)
free(im->pixels);
free(im);
}
*newimages = NULL;
return -1;
}
dst = (sixel_color_t *)im->pixels;
for (j = 0; j < im->height && y < h; j++, y++) {
src = st->image.data + image->width * y;
for (x = 0; x < w; x++)
*dst++ = st->image.palette[*src++];
}
}
return numimages;
}
/* convert sixel data into indexed pixel bytes and palette data */
int
sixel_parser_parse(sixel_state_t *st, const unsigned char *p, size_t len)
{
int n = 0;
int i;
int x;
int y;
int bits;
int sx;
int sy;
int c;
int pos;
int width;
const unsigned char *p0 = p, *p2 = p + len;
sixel_image_t *image = &st->image;
sixel_color_no_t *data, color_index;
if (!image->data)
st->state = PS_ERROR;
while (p < p2) {
switch (st->state) {
case PS_ESC:
goto end;
case PS_DECSIXEL:
switch (*p) {
case '\x1b':
st->state = PS_ESC;
break;
case '"':
st->param = 0;
st->nparams = 0;
st->state = PS_DECGRA;
p++;
break;
case '!':
st->param = 0;
st->nparams = 0;
st->state = PS_DECGRI;
p++;
break;
case '#':
st->param = 0;
st->nparams = 0;
st->state = PS_DECGCI;
p++;
break;
case '$':
/* DECGCR Graphics Carriage Return */
st->pos_x = 0;
p++;
break;
case '-':
/* DECGNL Graphics Next Line */
st->pos_x = 0;
if (st->pos_y < DECSIXEL_HEIGHT_MAX - 5 - 6)
st->pos_y += 6;
else
st->pos_y = DECSIXEL_HEIGHT_MAX + 1;
p++;
break;
default:
if (*p >= '?' && *p <= '~') { /* sixel characters */
if ((image->width < (st->pos_x + st->repeat_count) || image->height < (st->pos_y + 6))
&& image->width < DECSIXEL_WIDTH_MAX && image->height < DECSIXEL_HEIGHT_MAX) {
sx = image->width * 2;
sy = image->height * 2;
while (sx < (st->pos_x + st->repeat_count) || sy < (st->pos_y + 6)) {
sx *= 2;
sy *= 2;
}
sx = MIN(sx, DECSIXEL_WIDTH_MAX);
sy = MIN(sy, DECSIXEL_HEIGHT_MAX);
if (image_buffer_resize(image, sx, sy) < 0) {
perror("sixel_parser_parse() failed");
st->state = PS_ERROR;
p++;
break;
}
}
if (st->color_index > image->ncolors)
image->ncolors = st->color_index;
if (st->pos_x + st->repeat_count > image->width)
st->repeat_count = image->width - st->pos_x;
if (st->repeat_count > 0 && st->pos_y + 5 < image->height) {
bits = *p - '?';
if (bits != 0) {
data = image->data + image->width * st->pos_y + st->pos_x;
width = image->width;
color_index = st->color_index;
if (st->repeat_count <= 1) {
if (bits & 0x01)
*data = color_index, n = 0;
data += width;
if (bits & 0x02)
*data = color_index, n = 1;
data += width;
if (bits & 0x04)
*data = color_index, n = 2;
data += width;
if (bits & 0x08)
*data = color_index, n = 3;
data += width;
if (bits & 0x10)
*data = color_index, n = 4;
if (bits & 0x20)
data[width] = color_index, n = 5;
if (st->max_x < st->pos_x)
st->max_x = st->pos_x;
} else {
/* st->repeat_count > 1 */
for (i = 0; bits; bits >>= 1, i++, data += width) {
if (bits & 1) {
data[0] = color_index;
data[1] = color_index;
for (x = 2; x < st->repeat_count; x++)
data[x] = color_index;
n = i;
}
}
if (st->max_x < (st->pos_x + st->repeat_count - 1))
st->max_x = st->pos_x + st->repeat_count - 1;
}
if (st->max_y < (st->pos_y + n))
st->max_y = st->pos_y + n;
}
}
if (st->repeat_count > 0)
st->pos_x += st->repeat_count;
st->repeat_count = 1;
}
p++;
break;
}
break;
case PS_DECGRA:
/* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */
switch (*p) {
case '\x1b':
st->state = PS_ESC;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
st->param = st->param * 10 + *p - '0';
st->param = MIN(st->param, DECSIXEL_PARAMVALUE_MAX);
p++;
break;
case ';':
if (st->nparams < DECSIXEL_PARAMS_MAX)
st->params[st->nparams++] = st->param;
st->param = 0;
p++;
break;
default:
if (st->nparams < DECSIXEL_PARAMS_MAX)
st->params[st->nparams++] = st->param;
if (st->nparams > 0)
st->attributed_pad = st->params[0];
if (st->nparams > 1)
st->attributed_pan = st->params[1];
if (st->nparams > 2 && st->params[2] > 0)
st->attributed_ph = st->params[2];
if (st->nparams > 3 && st->params[3] > 0)
st->attributed_pv = st->params[3];
if (st->attributed_pan <= 0)
st->attributed_pan = 1;
if (st->attributed_pad <= 0)
st->attributed_pad = 1;
if (image->width < st->attributed_ph ||
image->height < st->attributed_pv) {
sx = MAX(image->width, st->attributed_ph);
sy = MAX(image->height, st->attributed_pv);
/* the height of the image buffer must be divisible by 6
* to avoid unnecessary resizing of the image buffer when
* parsing the last sixel line */
sy = (sy + 5) / 6 * 6;
sx = MIN(sx, DECSIXEL_WIDTH_MAX);
sy = MIN(sy, DECSIXEL_HEIGHT_MAX);
if (image_buffer_resize(image, sx, sy) < 0) {
perror("sixel_parser_parse() failed");
st->state = PS_ERROR;
break;
}
}
st->state = PS_DECSIXEL;
st->param = 0;
st->nparams = 0;
}
break;
case PS_DECGRI:
/* DECGRI Graphics Repeat Introducer ! Pn Ch */
switch (*p) {
case '\x1b':
st->state = PS_ESC;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
st->param = st->param * 10 + *p - '0';
st->param = MIN(st->param, DECSIXEL_PARAMVALUE_MAX);
p++;
break;
default:
st->repeat_count = MAX(st->param, 1);
st->state = PS_DECSIXEL;
st->param = 0;
st->nparams = 0;
break;
}
break;
case PS_DECGCI:
/* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */
switch (*p) {
case '\x1b':
st->state = PS_ESC;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
st->param = st->param * 10 + *p - '0';
st->param = MIN(st->param, DECSIXEL_PARAMVALUE_MAX);
p++;
break;
case ';':
if (st->nparams < DECSIXEL_PARAMS_MAX)
st->params[st->nparams++] = st->param;
st->param = 0;
p++;
break;
default:
st->state = PS_DECSIXEL;
if (st->nparams < DECSIXEL_PARAMS_MAX)
st->params[st->nparams++] = st->param;
st->param = 0;
if (st->nparams > 0) {
st->color_index = 1 + st->params[0]; /* offset 1(background color) added */
if (st->color_index < 0)
st->color_index = 0;
else if (st->color_index >= DECSIXEL_PALETTE_MAX)
st->color_index = DECSIXEL_PALETTE_MAX - 1;
}
if (st->nparams > 4) {
st->image.palette_modified = 1;
if (st->params[1] == 1) {
/* HLS */
st->params[2] = MIN(st->params[2], 360);
st->params[3] = MIN(st->params[3], 100);
st->params[4] = MIN(st->params[4], 100);
image->palette[st->color_index]
= hls_to_rgb(st->params[2], st->params[3], st->params[4]);
} else if (st->params[1] == 2) {
/* RGB */
st->params[2] = MIN(st->params[2], 100);
st->params[3] = MIN(st->params[3], 100);
st->params[4] = MIN(st->params[4], 100);
image->palette[st->color_index]
= SIXEL_XRGB(st->params[2], st->params[3], st->params[4]);
}
}
break;
}
break;
case PS_ERROR:
if (*p == '\x1b') {
st->state = PS_ESC;
goto end;
}
p++;
break;
default:
break;
}
}
end:
return p - p0;
}
void
sixel_parser_deinit(sixel_state_t *st)
{
if (st)
sixel_image_deinit(&st->image);
}
Pixmap
sixel_create_clipmask(char *pixels, int width, int height)
{
char c, *clipdata, *dst;
int b, i, n, y, w;
int msb = (XBitmapBitOrder(xw.dpy) == MSBFirst);
sixel_color_t *src = (sixel_color_t *)pixels;
Pixmap clipmask;
clipdata = dst = malloc((width+7)/8 * height);
if (!clipdata)
return (Pixmap)None;
for (y = 0; y < height; y++) {
for (w = width; w > 0; w -= n) {
n = MIN(w, 8);
if (msb) {
for (b = 0x80, c = 0, i = 0; i < n; i++, b >>= 1)
c |= (*src++) ? b : 0;
} else {
for (b = 0x01, c = 0, i = 0; i < n; i++, b <<= 1)
c |= (*src++) ? b : 0;
}
*dst++ = c;
}
}
clipmask = XCreateBitmapFromData(xw.dpy, xw.win, clipdata, width, height);
free(clipdata);
return clipmask;
}

View File

@ -1,63 +0,0 @@
#ifndef SIXEL_H
#define SIXEL_H
#define DECSIXEL_PARAMS_MAX 16
#define DECSIXEL_PALETTE_MAX 1024
#define DECSIXEL_PARAMVALUE_MAX 65535
#define DECSIXEL_WIDTH_MAX 4096
#define DECSIXEL_HEIGHT_MAX 4096
typedef unsigned short sixel_color_no_t;
typedef unsigned int sixel_color_t;
typedef struct sixel_image_buffer {
sixel_color_no_t *data;
int width;
int height;
sixel_color_t palette[DECSIXEL_PALETTE_MAX];
sixel_color_no_t ncolors;
int palette_modified;
int use_private_register;
} sixel_image_t;
typedef enum parse_state {
PS_ESC = 1, /* ESC */
PS_DECSIXEL = 2, /* DECSIXEL body part ", $, -, ? ... ~ */
PS_DECGRA = 3, /* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */
PS_DECGRI = 4, /* DECGRI Graphics Repeat Introducer ! Pn Ch */
PS_DECGCI = 5, /* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */
PS_ERROR = 6,
} parse_state_t;
typedef struct parser_context {
parse_state_t state;
int pos_x;
int pos_y;
int max_x;
int max_y;
int attributed_pan;
int attributed_pad;
int attributed_ph;
int attributed_pv;
int transparent;
int repeat_count;
int color_index;
int bgindex;
int grid_width;
int grid_height;
int param;
int nparams;
int params[DECSIXEL_PARAMS_MAX];
sixel_image_t image;
} sixel_state_t;
void scroll_images(int n);
void delete_image(ImageList *im);
int sixel_parser_init(sixel_state_t *st, int transparent, sixel_color_t fgcolor, sixel_color_t bgcolor, unsigned char use_private_register, int cell_width, int cell_height);
int sixel_parser_parse(sixel_state_t *st, const unsigned char *p, size_t len);
int sixel_parser_set_default_color(sixel_state_t *st);
int sixel_parser_finalize(sixel_state_t *st, ImageList **newimages, int cx, int cy, int cw, int ch);
void sixel_parser_deinit(sixel_state_t *st);
Pixmap sixel_create_clipmask(char *pixels, int width, int height);
#endif

View File

@ -1,115 +0,0 @@
// sixel.c (part of mintty)
// this function is derived from a part of graphics.c
// in Xterm pl#310 originally written by Ross Combs.
//
// Copyright 2013,2014 by Ross Combs
//
// All Rights Reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Except as contained in this notice, the name(s) of the above copyright
// holders shall not be used in advertising or otherwise to promote the
// sale, use or other dealings in this Software without prior written
// authorization.
#define SIXEL_RGB(r, g, b) ((r) + ((g) << 8) + ((b) << 16) + (255 << 24))
int
hls_to_rgb(int hue, int lum, int sat)
{
double hs = (hue + 240) % 360;
double hv = hs / 360.0;
double lv = lum / 100.0;
double sv = sat / 100.0;
double c, x, m, c2;
double r1, g1, b1;
int r, g, b;
int hpi;
if (sat == 0) {
r = g = b = lum * 255 / 100;
return SIXEL_RGB(r, g, b);
}
if ((c2 = ((2.0 * lv) - 1.0)) < 0.0) {
c2 = -c2;
}
c = (1.0 - c2) * sv;
hpi = (int) (hv * 6.0);
x = (hpi & 1) ? c : 0.0;
m = lv - 0.5 * c;
switch (hpi) {
case 0:
r1 = c;
g1 = x;
b1 = 0.0;
break;
case 1:
r1 = x;
g1 = c;
b1 = 0.0;
break;
case 2:
r1 = 0.0;
g1 = c;
b1 = x;
break;
case 3:
r1 = 0.0;
g1 = x;
b1 = c;
break;
case 4:
r1 = x;
g1 = 0.0;
b1 = c;
break;
case 5:
r1 = c;
g1 = 0.0;
b1 = x;
break;
default:
return SIXEL_RGB(255, 255, 255);
}
r = (int) ((r1 + m) * 100.0 + 0.5);
g = (int) ((g1 + m) * 100.0 + 0.5);
b = (int) ((b1 + m) * 100.0 + 0.5);
if (r < 0) {
r = 0;
} else if (r > 100) {
r = 100;
}
if (g < 0) {
g = 0;
} else if (g > 100) {
g = 100;
}
if (b < 0) {
b = 0;
} else if (b > 100) {
b = 100;
}
return SIXEL_RGB(r * 255 / 100, g * 255 / 100, b * 255 / 100);
}

View File

@ -1,7 +0,0 @@
/*
* Primary color hues:
* blue: 0 degrees
* red: 120 degrees
* green: 240 degrees
*/
int hls_to_rgb(int hue, int lum, int sat);

View File

@ -1,13 +0,0 @@
#!/bin/sh
# Using external pipe with st, give a dmenu prompt of recent commands,
# allowing the user to copy the output of one.
# xclip required for this script.
# By Jaywalker and Luke
tmpfile=$(mktemp /tmp/st-cmd-output.XXXXXX)
trap 'rm "$tmpfile"' 0 1 15
sed -n "w $tmpfile"
sed -i 's/\x0//g' "$tmpfile"
ps1="$(grep "\S" "$tmpfile" | tail -n 1 | sed 's/^\s*//' | cut -d' ' -f1)"
chosen="$(grep -F "$ps1" "$tmpfile" | sed '$ d' | tac | dmenu -p "Copy which command's output?" -i -l 10 | sed 's/[^^]/[&]/g; s/\^/\\^/g')"
eps1="$(echo "$ps1" | sed 's/[^^]/[&]/g; s/\^/\\^/g')"
awk "/^$chosen$/{p=1;print;next} p&&/$eps1/{p=0};p" "$tmpfile" | xclip -selection clipboard

View File

@ -1,19 +0,0 @@
#!/bin/sh
urlregex="(((http|https|gopher|gemini|ftp|ftps|git)://|www\\.)[a-zA-Z0-9.]*[:;a-zA-Z0-9./+@$&%?$\#=_~-]*)|((magnet:\\?xt=urn:btih:)[a-zA-Z0-9]*)"
urls="$(sed 's/.*│//g' | tr -d '\n' | # First remove linebreaks and mutt sidebars:
grep -aEo "$urlregex" | # grep only urls as defined above.
uniq | # Ignore neighboring duplicates.
sed "s/\(\.\|,\|;\|\!\\|\?\)$//;
s/^www./http:\/\/www\./")" # xdg-open will not detect url without http
[ -z "$urls" ] && exit 1
while getopts "hoc" o; do case "${o}" in
h) printf "Optional arguments for custom use:\\n -c: copy\\n -o: dmenuhandler\\n -h: Show this message\\n" && exit 1 ;;
o) chosen="$(echo "$urls" | dmenu -i -p 'Use which url?' -l 10)"
setsid dmenuhandler "$chosen" >/dev/null 2>&1 & ;;
c) echo "$urls" | dmenu -i -p 'Copy which url?' -l 10 | tr -d '\n' | xclip -selection clipboard ;;
*) printf "Invalid option: -%s\\n" "$OPTARG" && exit 1 ;;
esac done

View File

@ -1,177 +0,0 @@
.TH ST 1 st\-VERSION
.SH NAME
st \- simple terminal
.SH SYNOPSIS
.B st
.RB [ \-aiv ]
.RB [ \-c
.IR class ]
.RB [ \-f
.IR font ]
.RB [ \-g
.IR geometry ]
.RB [ \-n
.IR name ]
.RB [ \-o
.IR iofile ]
.RB [ \-T
.IR title ]
.RB [ \-t
.IR title ]
.RB [ \-l
.IR line ]
.RB [ \-w
.IR windowid ]
.RB [[ \-e ]
.IR command
.RI [ arguments ...]]
.PP
.B st
.RB [ \-aiv ]
.RB [ \-c
.IR class ]
.RB [ \-f
.IR font ]
.RB [ \-g
.IR geometry ]
.RB [ \-n
.IR name ]
.RB [ \-o
.IR iofile ]
.RB [ \-T
.IR title ]
.RB [ \-t
.IR title ]
.RB [ \-w
.IR windowid ]
.RB \-l
.IR line
.RI [ stty_args ...]
.SH DESCRIPTION
.B st
is a simple terminal emulator.
.SH OPTIONS
.TP
.B \-a
disable alternate screens in terminal
.TP
.BI \-c " class"
defines the window class (default $TERM).
.TP
.BI \-f " font"
defines the
.I font
to use when st is run.
.TP
.BI \-g " geometry"
defines the X11 geometry string.
The form is [=][<cols>{xX}<rows>][{+-}<xoffset>{+-}<yoffset>]. See
.BR XParseGeometry (3)
for further details.
.TP
.B \-i
will fixate the position given with the -g option.
.TP
.BI \-n " name"
defines the window instance name (default $TERM).
.TP
.BI \-o " iofile"
writes all the I/O to
.I iofile.
This feature is useful when recording st sessions. A value of "-" means
standard output.
.TP
.BI \-T " title"
defines the window title (default 'st').
.TP
.BI \-t " title"
defines the window title (default 'st').
.TP
.BI \-w " windowid"
embeds st within the window identified by
.I windowid
.TP
.BI \-l " line"
use a tty
.I line
instead of a pseudo terminal.
.I line
should be a (pseudo-)serial device (e.g. /dev/ttyS0 on Linux for serial port
0).
When this flag is given
remaining arguments are used as flags for
.BR stty(1).
By default st initializes the serial line to 8 bits, no parity, 1 stop bit
and a 38400 baud rate. The speed is set by appending it as last argument
(e.g. 'st -l /dev/ttyS0 115200'). Arguments before the last one are
.BR stty(1)
flags. If you want to set odd parity on 115200 baud use for example 'st -l
/dev/ttyS0 parenb parodd 115200'. Set the number of bits by using for
example 'st -l /dev/ttyS0 cs7 115200'. See
.BR stty(1)
for more arguments and cases.
.TP
.B \-v
prints version information to stderr, then exits.
.TP
.BI \-e " command " [ " arguments " "... ]"
st executes
.I command
instead of the shell. If this is used it
.B must be the last option
on the command line, as in xterm / rxvt.
This option is only intended for compatibility,
and all the remaining arguments are used as a command
even without it.
.SH SHORTCUTS
.TP
.B Break
Send a break in the serial line.
Break key is obtained in PC keyboards
pressing at the same time control and pause.
.TP
.B Ctrl-Print Screen
Toggle if st should print to the
.I iofile.
.TP
.B Shift-Print Screen
Print the full screen to the
.I iofile.
.TP
.B Print Screen
Print the selection to the
.I iofile.
.TP
.B Ctrl-Shift-Page Up
Increase font size.
.TP
.B Ctrl-Shift-Page Down
Decrease font size.
.TP
.B Ctrl-Shift-Home
Reset to default font size.
.TP
.B Ctrl-Shift-y
Paste from primary selection (middle mouse button).
.TP
.B Ctrl-Shift-c
Copy the selected text to the clipboard selection.
.TP
.B Ctrl-Shift-v
Paste from the clipboard selection.
.SH CUSTOMIZATION
.B st
can be customized by creating a custom config.h and (re)compiling the source
code. This keeps it fast, secure and simple.
.SH AUTHORS
See the LICENSE file for the authors.
.SH LICENSE
See the LICENSE file for the terms of redistribution.
.SH SEE ALSO
.BR tabbed (1),
.BR utmp (1),
.BR stty (1),
.BR scroll (1)
.SH BUGS
See the TODO file in the distribution.

View File

@ -1,2540 +0,0 @@
/* See LICENSE for license details. */
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <wchar.h>
#include "st.h"
#include "win.h"
#include "sixel.h"
#if defined(__linux)
#include <pty.h>
#elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
#include <util.h>
#elif defined(__FreeBSD__) || defined(__DragonFly__)
#include <libutil.h>
#endif
/* Arbitrary sizes */
#define UTF_INVALID 0xFFFD
#define UTF_SIZ 4
#define ESC_BUF_SIZ (128*UTF_SIZ)
#define ESC_ARG_SIZ 16
#define STR_BUF_SIZ ESC_BUF_SIZ
#define STR_ARG_SIZ ESC_ARG_SIZ
#define STR_TERM_ST "\033\\"
#define STR_TERM_BEL "\007"
/* macros */
#define IS_SET(flag) ((term.mode & (flag)) != 0)
#define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == 0x7f)
#define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
#define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
#define ISDELIM(u) (u && wcschr(worddelimiters, u))
enum term_mode {
MODE_WRAP = 1 << 0,
MODE_INSERT = 1 << 1,
MODE_ALTSCREEN = 1 << 2,
MODE_CRLF = 1 << 3,
MODE_ECHO = 1 << 4,
MODE_PRINT = 1 << 5,
MODE_UTF8 = 1 << 6,
MODE_SIXEL = 1 << 7,
MODE_SIXEL_CUR_RT = 1 << 8,
MODE_SIXEL_SDM = 1 << 9
};
enum scroll_mode {
SCROLL_RESIZE = -1,
SCROLL_NOSAVEHIST = 0,
SCROLL_SAVEHIST = 1
};
enum cursor_movement {
CURSOR_SAVE,
CURSOR_LOAD
};
enum cursor_state {
CURSOR_DEFAULT = 0,
CURSOR_WRAPNEXT = 1,
CURSOR_ORIGIN = 2
};
enum charset {
CS_GRAPHIC0,
CS_GRAPHIC1,
CS_UK,
CS_USA,
CS_MULTI,
CS_GER,
CS_FIN
};
enum escape_state {
ESC_START = 1,
ESC_CSI = 2,
ESC_STR = 4, /* DCS, OSC, PM, APC */
ESC_ALTCHARSET = 8,
ESC_STR_END = 16, /* a final string was encountered */
ESC_TEST = 32, /* Enter in test mode */
ESC_UTF8 = 64,
ESC_DCS =128,
};
typedef struct {
int mode;
int type;
int snap;
/*
* Selection variables:
* nb normalized coordinates of the beginning of the selection
* ne normalized coordinates of the end of the selection
* ob original coordinates of the beginning of the selection
* oe original coordinates of the end of the selection
*/
struct {
int x, y;
} nb, ne, ob, oe;
int alt;
} Selection;
/* CSI Escape sequence structs */
/* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
typedef struct {
char buf[ESC_BUF_SIZ]; /* raw string */
size_t len; /* raw string length */
char priv;
int arg[ESC_ARG_SIZ];
int narg; /* nb of args */
char mode[2];
} CSIEscape;
/* STR Escape sequence structs */
/* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
typedef struct {
char type; /* ESC type ... */
char *buf; /* allocated raw string */
size_t siz; /* allocation size */
size_t len; /* raw string length */
char *args[STR_ARG_SIZ];
int narg; /* nb of args */
char *term; /* terminator: ST or BEL */
} STREscape;
static void execsh(char *, char **);
static void stty(char **);
static void sigchld(int);
static void ttywriteraw(const char *, size_t);
static void csidump(void);
static void csihandle(void);
static void dcshandle(void);
static void csiparse(void);
static void csireset(void);
static void osc_color_response(int, int, int);
static int eschandle(uchar);
static void strdump(void);
static void strhandle(void);
static void strparse(void);
static void strreset(void);
static void tprinter(char *, size_t);
static void tdumpsel(void);
static void tdumpline(int);
static void tdump(void);
static void tcursor(int);
static void tresetcursor(void);
static void tdeleteimages(void);
static void tdeleteline(int);
static void tinsertblank(int);
static void tinsertblankline(int);
static void tmoveto(int, int);
static void tmoveato(int, int);
static void tnewline(int);
static void tputtab(int);
static void tputc(Rune);
static void treset(void);
static void tscrolldown(int, int);
static void tsetattr(const int *, int);
static void tsetchar(Rune, const Glyph *, int, int);
static void tsetdirt(int, int);
static void tsetscroll(int, int);
static void tswapscreen(void);
static void tsetmode(int, int, const int *, int);
static int twrite(const char *, int, int);
static void tcontrolcode(uchar );
static void tdectest(char );
static void tdefutf8(char);
static int32_t tdefcolor(const int *, int *, int);
static void tdeftran(char);
static void tstrsequence(uchar);
static void selnormalize(void);
static void selsnap(int *, int *, int);
static size_t utf8decode(const char *, Rune *, size_t);
static inline Rune utf8decodebyte(char, size_t *);
static inline char utf8encodebyte(Rune, size_t);
static inline size_t utf8validate(Rune *, size_t);
static char *base64dec(const char *);
static char base64dec_getc(const char **);
static ssize_t xwrite(int, const char *, size_t);
/* Globals */
static Selection sel;
static CSIEscape csiescseq;
static STREscape strescseq;
static int iofd = 1;
static int cmdfd;
static pid_t pid;
sixel_state_t sixel_st;
static const uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
static const uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
static const Rune utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
static const Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
#include "patch/st_include.h"
ssize_t
xwrite(int fd, const char *s, size_t len)
{
size_t aux = len;
ssize_t r;
while (len > 0) {
r = write(fd, s, len);
if (r < 0)
return r;
len -= r;
s += r;
}
return aux;
}
void *
xmalloc(size_t len)
{
void *p;
if (!(p = malloc(len)))
die("malloc: %s\n", strerror(errno));
return p;
}
void *
xrealloc(void *p, size_t len)
{
if ((p = realloc(p, len)) == NULL)
die("realloc: %s\n", strerror(errno));
return p;
}
char *
xstrdup(const char *s)
{
char *p;
if ((p = strdup(s)) == NULL)
die("strdup: %s\n", strerror(errno));
return p;
}
size_t
utf8decode(const char *c, Rune *u, size_t clen)
{
size_t i, len;
Rune udecoded;
*u = UTF_INVALID;
if (!clen)
return 0;
udecoded = utf8decodebyte(c[0], &len);
if (!BETWEEN(len, 2, UTF_SIZ)) {
*u = (len == 1) ? udecoded : UTF_INVALID;
return 1;
}
clen = MIN(clen, len);
for (i = 1; i < clen; ++i) {
if ((c[i] & 0xC0) != 0x80)
return i;
udecoded = (udecoded << 6) | (c[i] & 0x3F);
}
if (i < len)
return 0;
*u = (!BETWEEN(udecoded, utfmin[len], utfmax[len]) || BETWEEN(udecoded, 0xD800, 0xDFFF))
? UTF_INVALID : udecoded;
return len;
}
Rune
utf8decodebyte(char c, size_t *i)
{
for (*i = 0; *i < LEN(utfmask); ++(*i))
if (((uchar)c & utfmask[*i]) == utfbyte[*i])
return (uchar)c & ~utfmask[*i];
return 0;
}
size_t
utf8encode(Rune u, char *c)
{
size_t len, i;
len = utf8validate(&u, 0);
if (len > UTF_SIZ)
return 0;
for (i = len - 1; i != 0; --i) {
c[i] = utf8encodebyte(u, 0);
u >>= 6;
}
c[0] = utf8encodebyte(u, len);
return len;
}
char
utf8encodebyte(Rune u, size_t i)
{
return utfbyte[i] | (u & ~utfmask[i]);
}
size_t
utf8validate(Rune *u, size_t i)
{
if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
*u = UTF_INVALID;
for (i = 1; *u > utfmax[i]; ++i)
;
return i;
}
char
base64dec_getc(const char **src)
{
while (**src && !isprint((unsigned char)**src))
(*src)++;
return **src ? *((*src)++) : '='; /* emulate padding if string ends */
}
char *
base64dec(const char *src)
{
size_t in_len = strlen(src);
char *result, *dst;
static const char base64_digits[256] = {
[43] = 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
0, 0, 0, -1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0,
0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
if (in_len % 4)
in_len += 4 - (in_len % 4);
result = dst = xmalloc(in_len / 4 * 3 + 1);
while (*src) {
int a = base64_digits[(unsigned char) base64dec_getc(&src)];
int b = base64_digits[(unsigned char) base64dec_getc(&src)];
int c = base64_digits[(unsigned char) base64dec_getc(&src)];
int d = base64_digits[(unsigned char) base64dec_getc(&src)];
/* invalid input. 'a' can be -1, e.g. if src is "\n" (c-str) */
if (a == -1 || b == -1)
break;
*dst++ = (a << 2) | ((b & 0x30) >> 4);
if (c == -1)
break;
*dst++ = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2);
if (d == -1)
break;
*dst++ = ((c & 0x03) << 6) | d;
}
*dst = '\0';
return result;
}
void
selinit(void)
{
sel.mode = SEL_IDLE;
sel.snap = 0;
sel.ob.x = -1;
}
void
selstart(int col, int row, int snap)
{
selclear();
sel.mode = SEL_EMPTY;
sel.type = SEL_REGULAR;
sel.alt = IS_SET(MODE_ALTSCREEN);
sel.snap = snap;
sel.oe.x = sel.ob.x = col;
sel.oe.y = sel.ob.y = row;
selnormalize();
if (sel.snap != 0)
sel.mode = SEL_READY;
tsetdirt(sel.nb.y, sel.ne.y);
}
void
selextend(int col, int row, int type, int done)
{
int oldey, oldex, oldsby, oldsey, oldtype;
if (sel.mode == SEL_IDLE)
return;
if (done && sel.mode == SEL_EMPTY) {
selclear();
return;
}
oldey = sel.oe.y;
oldex = sel.oe.x;
oldsby = sel.nb.y;
oldsey = sel.ne.y;
oldtype = sel.type;
sel.oe.x = col;
sel.oe.y = row;
sel.type = type;
selnormalize();
if (oldey != sel.oe.y || oldex != sel.oe.x || oldtype != sel.type || sel.mode == SEL_EMPTY)
tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
sel.mode = done ? SEL_IDLE : SEL_READY;
}
void
selnormalize(void)
{
int i;
if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
} else {
sel.nb.x = MIN(sel.ob.x, sel.oe.x);
sel.ne.x = MAX(sel.ob.x, sel.oe.x);
}
sel.nb.y = MIN(sel.ob.y, sel.oe.y);
sel.ne.y = MAX(sel.ob.y, sel.oe.y);
selsnap(&sel.nb.x, &sel.nb.y, -1);
selsnap(&sel.ne.x, &sel.ne.y, +1);
/* expand selection over line breaks */
if (sel.type == SEL_RECTANGULAR)
return;
i = tlinelen(TLINE(sel.nb.y));
if (sel.nb.x > i)
sel.nb.x = i;
if (sel.ne.x >= tlinelen(TLINE(sel.ne.y)))
sel.ne.x = term.col - 1;
}
void
selclear(void)
{
if (sel.ob.x == -1)
return;
selremove();
tsetdirt(sel.nb.y, sel.ne.y);
}
void
selremove(void)
{
sel.mode = SEL_IDLE;
sel.ob.x = -1;
}
void
die(const char *errstr, ...)
{
va_list ap;
va_start(ap, errstr);
vfprintf(stderr, errstr, ap);
va_end(ap);
exit(1);
}
void
execsh(char *cmd, char **args)
{
char *sh, *prog, *arg;
const struct passwd *pw;
errno = 0;
if ((pw = getpwuid(getuid())) == NULL) {
if (errno)
die("getpwuid: %s\n", strerror(errno));
else
die("who are you?\n");
}
if ((sh = getenv("SHELL")) == NULL)
sh = (pw->pw_shell[0]) ? pw->pw_shell : cmd;
if (args) {
prog = args[0];
arg = NULL;
} else if (scroll) {
prog = scroll;
arg = utmp ? utmp : sh;
} else if (utmp) {
prog = utmp;
arg = NULL;
} else {
prog = sh;
arg = NULL;
}
DEFAULT(args, ((char *[]) {prog, arg, NULL}));
unsetenv("COLUMNS");
unsetenv("LINES");
unsetenv("TERMCAP");
setenv("LOGNAME", pw->pw_name, 1);
setenv("USER", pw->pw_name, 1);
setenv("SHELL", sh, 1);
setenv("HOME", pw->pw_dir, 1);
setenv("TERM", termname, 1);
setenv("COLORTERM", "truecolor", 1);
signal(SIGCHLD, SIG_DFL);
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGALRM, SIG_DFL);
execvp(prog, args);
_exit(1);
}
void
sigchld(int a)
{
int stat;
pid_t p;
if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
die("waiting for pid %hd failed: %s\n", pid, strerror(errno));
if (pid != p) {
if (!extpipeactive)
return;
if (p == 0 && wait(&stat) < 0)
die("wait: %s\n", strerror(errno));
/* reinstall sigchld handler */
signal(SIGCHLD, sigchld);
extpipeactive = 0;
return;
}
if (WIFEXITED(stat) && WEXITSTATUS(stat))
die("child exited with status %d\n", WEXITSTATUS(stat));
else if (WIFSIGNALED(stat))
die("child terminated due to signal %d\n", WTERMSIG(stat));
_exit(0);
}
void
stty(char **args)
{
char cmd[_POSIX_ARG_MAX], **p, *q, *s;
size_t n, siz;
if ((n = strlen(stty_args)) > sizeof(cmd)-1)
die("incorrect stty parameters\n");
memcpy(cmd, stty_args, n);
q = cmd + n;
siz = sizeof(cmd) - n;
for (p = args; p && (s = *p); ++p) {
if ((n = strlen(s)) > siz-1)
die("stty parameter length too long\n");
*q++ = ' ';
memcpy(q, s, n);
q += n;
siz -= n + 1;
}
*q = '\0';
if (system(cmd) != 0)
perror("Couldn't call stty");
}
int
ttynew(const char *line, char *cmd, const char *out, char **args)
{
int m, s;
if (out) {
term.mode |= MODE_PRINT;
iofd = (!strcmp(out, "-")) ?
1 : open(out, O_WRONLY | O_CREAT, 0666);
if (iofd < 0) {
fprintf(stderr, "Error opening %s:%s\n",
out, strerror(errno));
}
}
if (line) {
if ((cmdfd = open(line, O_RDWR)) < 0)
die("open line '%s' failed: %s\n",
line, strerror(errno));
dup2(cmdfd, 0);
stty(args);
return cmdfd;
}
/* seems to work fine on linux, openbsd and freebsd */
if (openpty(&m, &s, NULL, NULL, NULL) < 0)
die("openpty failed: %s\n", strerror(errno));
switch (pid = fork()) {
case -1:
die("fork failed: %s\n", strerror(errno));
break;
case 0:
close(iofd);
close(m);
setsid(); /* create a new process group */
dup2(s, 0);
dup2(s, 1);
dup2(s, 2);
if (ioctl(s, TIOCSCTTY, NULL) < 0)
die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
if (s > 2)
close(s);
#ifdef __OpenBSD__
if (pledge("stdio getpw proc exec", NULL) == -1)
die("pledge\n");
#endif
execsh(cmd, args);
break;
default:
#ifdef __OpenBSD__
if (pledge("stdio rpath tty proc ps exec", NULL) == -1)
die("pledge\n");
#endif
close(s);
cmdfd = m;
signal(SIGCHLD, sigchld);
break;
}
return cmdfd;
}
size_t
ttyread(void)
{
static char buf[BUFSIZ];
static int buflen = 0;
int ret, written;
/* append read bytes to unprocessed bytes */
ret = read(cmdfd, buf+buflen, LEN(buf)-buflen);
switch (ret) {
case 0:
exit(0);
case -1:
die("couldn't read from shell: %s\n", strerror(errno));
default:
buflen += ret;
written = twrite(buf, buflen, 0);
buflen -= written;
/* keep any incomplete UTF-8 byte sequence for the next call */
if (buflen > 0)
memmove(buf, buf + written, buflen);
return ret;
}
}
void
ttywrite(const char *s, size_t n, int may_echo)
{
const char *next;
kscrolldown(&((Arg){ .i = term.scr }));
if (may_echo && IS_SET(MODE_ECHO))
twrite(s, n, 1);
if (!IS_SET(MODE_CRLF)) {
ttywriteraw(s, n);
return;
}
/* This is similar to how the kernel handles ONLCR for ttys */
while (n > 0) {
if (*s == '\r') {
next = s + 1;
ttywriteraw("\r\n", 2);
} else {
next = memchr(s, '\r', n);
DEFAULT(next, s + n);
ttywriteraw(s, next - s);
}
n -= next - s;
s = next;
}
}
void
ttywriteraw(const char *s, size_t n)
{
fd_set wfd, rfd;
ssize_t r;
size_t lim = 256;
/*
* Remember that we are using a pty, which might be a modem line.
* Writing too much will clog the line. That's why we are doing this
* dance.
* FIXME: Migrate the world to Plan 9.
*/
while (n > 0) {
FD_ZERO(&wfd);
FD_ZERO(&rfd);
FD_SET(cmdfd, &wfd);
FD_SET(cmdfd, &rfd);
/* Check if we can write. */
if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) {
if (errno == EINTR)
continue;
die("select failed: %s\n", strerror(errno));
}
if (FD_ISSET(cmdfd, &wfd)) {
/*
* Only write the bytes written by ttywrite() or the
* default of 256. This seems to be a reasonable value
* for a serial line. Bigger values might clog the I/O.
*/
if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0)
goto write_error;
if (r < n) {
/*
* We weren't able to write out everything.
* This means the buffer is getting full
* again. Empty it.
*/
if (n < lim)
lim = ttyread();
n -= r;
s += r;
} else {
/* All bytes have been written. */
break;
}
}
if (FD_ISSET(cmdfd, &rfd))
lim = ttyread();
}
return;
write_error:
die("write error on tty: %s\n", strerror(errno));
}
void
ttyresize(int tw, int th)
{
struct winsize w;
w.ws_row = term.row;
w.ws_col = term.col;
w.ws_xpixel = tw;
w.ws_ypixel = th;
if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
}
void
ttyhangup(void)
{
/* Send SIGHUP to shell */
kill(pid, SIGHUP);
}
int
tattrset(int attr)
{
int i, j;
for (i = 0; i < term.row-1; i++) {
for (j = 0; j < term.col-1; j++) {
if (term.line[i][j].mode & attr)
return 1;
}
}
return 0;
}
int
tisaltscr(void)
{
return IS_SET(MODE_ALTSCREEN);
}
void
tsetdirt(int top, int bot)
{
int i;
LIMIT(top, 0, term.row-1);
LIMIT(bot, 0, term.row-1);
for (i = top; i <= bot; i++)
term.dirty[i] = 1;
}
void
tsetdirtattr(int attr)
{
int i, j;
for (i = 0; i < term.row-1; i++) {
for (j = 0; j < term.col-1; j++) {
if (term.line[i][j].mode & attr) {
term.dirty[i] = 1;
break;
}
}
}
}
void
tfulldirt(void)
{
for (int i = 0; i < term.row; i++)
term.dirty[i] = 1;
}
void
tcursor(int mode)
{
static TCursor c[2];
int alt = IS_SET(MODE_ALTSCREEN);
if (mode == CURSOR_SAVE) {
c[alt] = term.c;
} else if (mode == CURSOR_LOAD) {
term.c = c[alt];
tmoveto(c[alt].x, c[alt].y);
}
}
void
tresetcursor(void)
{
term.c = (TCursor){ { .mode = ATTR_NULL, .fg = defaultfg, .bg = defaultbg },
.x = 0, .y = 0, .state = CURSOR_DEFAULT };
}
void
treset(void)
{
uint i;
int x, y;
tresetcursor();
memset(term.tabs, 0, term.col * sizeof(*term.tabs));
for (i = tabspaces; i < term.col; i += tabspaces)
term.tabs[i] = 1;
term.top = 0;
term.bot = term.row - 1;
term.mode = MODE_WRAP|MODE_UTF8;
memset(term.trantbl, CS_USA, sizeof(term.trantbl));
term.charset = 0;
term.histf = 0;
term.histi = 0;
term.scr = 0;
selremove();
for (i = 0; i < 2; i++) {
tcursor(CURSOR_SAVE); /* reset saved cursor */
for (y = 0; y < term.row; y++)
for (x = 0; x < term.col; x++)
tclearglyph(&term.line[y][x], 0);
tdeleteimages();
tswapscreen();
}
tfulldirt();
}
void
tnewline(int first_col)
{
int y = term.c.y;
if (y == term.bot) {
tscrollup(term.top, term.bot, 1, SCROLL_SAVEHIST);
} else {
y++;
}
tmoveto(first_col ? 0 : term.c.x, y);
}
void
csiparse(void)
{
char *p = csiescseq.buf, *np;
long int v;
csiescseq.narg = 0;
if (*p == '?') {
csiescseq.priv = 1;
p++;
}
csiescseq.buf[csiescseq.len] = '\0';
while (p < csiescseq.buf+csiescseq.len) {
np = NULL;
v = strtol(p, &np, 10);
if (np == p)
v = 0;
if (v == LONG_MAX || v == LONG_MIN)
v = -1;
csiescseq.arg[csiescseq.narg++] = v;
p = np;
if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
break;
p++;
}
csiescseq.mode[0] = *p++;
csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
}
/* for absolute user moves, when decom is set */
void
tmoveato(int x, int y)
{
tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
}
void
tmoveto(int x, int y)
{
int miny, maxy;
if (term.c.state & CURSOR_ORIGIN) {
miny = term.top;
maxy = term.bot;
} else {
miny = 0;
maxy = term.row - 1;
}
term.c.state &= ~CURSOR_WRAPNEXT;
term.c.x = LIMIT(x, 0, term.col-1);
term.c.y = LIMIT(y, miny, maxy);
}
void
tsetchar(Rune u, const Glyph *attr, int x, int y)
{
static const char *vt100_0[62] = { /* 0x41 - 0x7e */
"", "", "", "", "", "", "", /* A - G */
0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
"", "", "", "", "", "", "°", "±", /* ` - g */
"", "", "", "", "", "", "", "", /* h - o */
"", "", "", "", "", "", "", "", /* p - w */
"", "", "", "π", "", "£", "·", /* x - ~ */
};
/*
* The table is proudly stolen from rxvt.
*/
if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
if (term.line[y][x].mode & ATTR_WIDE) {
if (x+1 < term.col) {
term.line[y][x+1].u = ' ';
term.line[y][x+1].mode &= ~ATTR_WDUMMY;
}
} else if (term.line[y][x].mode & ATTR_WDUMMY) {
term.line[y][x-1].u = ' ';
term.line[y][x-1].mode &= ~ATTR_WIDE;
}
term.dirty[y] = 1;
term.line[y][x] = *attr;
term.line[y][x].u = u;
term.line[y][x].mode |= ATTR_SET;
if (isboxdraw(u))
term.line[y][x].mode |= ATTR_BOXDRAW;
}
void
tinsertblankline(int n)
{
if (BETWEEN(term.c.y, term.top, term.bot))
tscrolldown(term.c.y, n);
}
void
tdeleteimages(void)
{
ImageList *im, *next;
for (im = term.images; im; im = next) {
next = im->next;
delete_image(im);
}
}
void
tdeleteline(int n)
{
if (BETWEEN(term.c.y, term.top, term.bot)) {
tscrollup(term.c.y, term.bot, n, SCROLL_NOSAVEHIST);
}
}
int32_t
tdefcolor(const int *attr, int *npar, int l)
{
int32_t idx = -1;
uint r, g, b;
switch (attr[*npar + 1]) {
case 2: /* direct color in RGB space */
if (*npar + 4 >= l) {
fprintf(stderr,
"erresc(38): Incorrect number of parameters (%d)\n",
*npar);
break;
}
r = attr[*npar + 2];
g = attr[*npar + 3];
b = attr[*npar + 4];
*npar += 4;
if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
r, g, b);
else
idx = TRUECOLOR(r, g, b);
break;
case 5: /* indexed color */
if (*npar + 2 >= l) {
fprintf(stderr,
"erresc(38): Incorrect number of parameters (%d)\n",
*npar);
break;
}
*npar += 2;
if (!BETWEEN(attr[*npar], 0, 255))
fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
else
idx = attr[*npar];
break;
case 0: /* implemented defined (only foreground) */
case 1: /* transparent */
case 3: /* direct color in CMY space */
case 4: /* direct color in CMYK space */
default:
fprintf(stderr,
"erresc(38): gfx attr %d unknown\n", attr[*npar]);
break;
}
return idx;
}
void
tsetattr(const int *attr, int l)
{
int i;
int32_t idx;
for (i = 0; i < l; i++) {
switch (attr[i]) {
case 0:
term.c.attr.mode &= ~(
ATTR_BOLD |
ATTR_FAINT |
ATTR_ITALIC |
ATTR_UNDERLINE |
ATTR_BLINK |
ATTR_REVERSE |
ATTR_INVISIBLE |
ATTR_STRUCK );
term.c.attr.fg = defaultfg;
term.c.attr.bg = defaultbg;
break;
case 1:
term.c.attr.mode |= ATTR_BOLD;
break;
case 2:
term.c.attr.mode |= ATTR_FAINT;
break;
case 3:
term.c.attr.mode |= ATTR_ITALIC;
break;
case 4:
term.c.attr.mode |= ATTR_UNDERLINE;
break;
case 5: /* slow blink */
/* FALLTHROUGH */
case 6: /* rapid blink */
term.c.attr.mode |= ATTR_BLINK;
break;
case 7:
term.c.attr.mode |= ATTR_REVERSE;
break;
case 8:
term.c.attr.mode |= ATTR_INVISIBLE;
break;
case 9:
term.c.attr.mode |= ATTR_STRUCK;
break;
case 22:
term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
break;
case 23:
term.c.attr.mode &= ~ATTR_ITALIC;
break;
case 24:
term.c.attr.mode &= ~ATTR_UNDERLINE;
break;
case 25:
term.c.attr.mode &= ~ATTR_BLINK;
break;
case 27:
term.c.attr.mode &= ~ATTR_REVERSE;
break;
case 28:
term.c.attr.mode &= ~ATTR_INVISIBLE;
break;
case 29:
term.c.attr.mode &= ~ATTR_STRUCK;
break;
case 38:
if ((idx = tdefcolor(attr, &i, l)) >= 0)
term.c.attr.fg = idx;
break;
case 39:
term.c.attr.fg = defaultfg;
break;
case 48:
if ((idx = tdefcolor(attr, &i, l)) >= 0)
term.c.attr.bg = idx;
break;
case 49:
term.c.attr.bg = defaultbg;
break;
default:
if (BETWEEN(attr[i], 30, 37)) {
term.c.attr.fg = attr[i] - 30;
} else if (BETWEEN(attr[i], 40, 47)) {
term.c.attr.bg = attr[i] - 40;
} else if (BETWEEN(attr[i], 90, 97)) {
term.c.attr.fg = attr[i] - 90 + 8;
} else if (BETWEEN(attr[i], 100, 107)) {
term.c.attr.bg = attr[i] - 100 + 8;
} else {
fprintf(stderr,
"erresc(default): gfx attr %d unknown\n",
attr[i]);
csidump();
}
break;
}
}
}
void
tsetscroll(int t, int b)
{
int temp;
LIMIT(t, 0, term.row-1);
LIMIT(b, 0, term.row-1);
if (t > b) {
temp = t;
t = b;
b = temp;
}
term.top = t;
term.bot = b;
}
void
tsetmode(int priv, int set, const int *args, int narg)
{
int alt;
const int *lim;
for (lim = args + narg; args < lim; ++args) {
if (priv) {
switch (*args) {
case 1: /* DECCKM -- Cursor key */
xsetmode(set, MODE_APPCURSOR);
break;
case 5: /* DECSCNM -- Reverse video */
xsetmode(set, MODE_REVERSE);
break;
case 6: /* DECOM -- Origin */
MODBIT(term.c.state, set, CURSOR_ORIGIN);
tmoveato(0, 0);
break;
case 7: /* DECAWM -- Auto wrap */
MODBIT(term.mode, set, MODE_WRAP);
break;
case 0: /* Error (IGNORED) */
case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
case 3: /* DECCOLM -- Column (IGNORED) */
case 4: /* DECSCLM -- Scroll (IGNORED) */
case 8: /* DECARM -- Auto repeat (IGNORED) */
case 18: /* DECPFF -- Printer feed (IGNORED) */
case 19: /* DECPEX -- Printer extent (IGNORED) */
case 42: /* DECNRCM -- National characters (IGNORED) */
case 12: /* att610 -- Start blinking cursor (IGNORED) */
break;
case 25: /* DECTCEM -- Text Cursor Enable Mode */
xsetmode(!set, MODE_HIDE);
break;
case 9: /* X10 mouse compatibility mode */
xsetpointermotion(0);
xsetmode(0, MODE_MOUSE);
xsetmode(set, MODE_MOUSEX10);
break;
case 1000: /* 1000: report button press */
xsetpointermotion(0);
xsetmode(0, MODE_MOUSE);
xsetmode(set, MODE_MOUSEBTN);
break;
case 1002: /* 1002: report motion on button press */
xsetpointermotion(0);
xsetmode(0, MODE_MOUSE);
xsetmode(set, MODE_MOUSEMOTION);
break;
case 1003: /* 1003: enable all mouse motions */
xsetpointermotion(set);
xsetmode(0, MODE_MOUSE);
xsetmode(set, MODE_MOUSEMANY);
break;
case 1004: /* 1004: send focus events to tty */
xsetmode(set, MODE_FOCUS);
break;
case 1006: /* 1006: extended reporting mode */
xsetmode(set, MODE_MOUSESGR);
break;
case 1034:
xsetmode(set, MODE_8BIT);
break;
case 1049: /* swap screen & set/restore cursor as xterm */
if (!allowaltscreen)
break;
tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
/* FALLTHROUGH */
case 47: /* swap screen */
case 1047:
if (!allowaltscreen)
break;
if (set)
tloadaltscreen(*args != 47, *args == 1049);
else
tloaddefscreen(*args != 47, *args == 1049);
break;
case 1048:
if (!allowaltscreen)
break;
tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
break;
case 2004: /* 2004: bracketed paste mode */
xsetmode(set, MODE_BRCKTPASTE);
break;
/* Not implemented mouse modes. See comments there. */
case 1001: /* mouse highlight mode; can hang the
terminal by design when implemented. */
case 1005: /* UTF-8 mouse mode; will confuse
applications not supporting UTF-8
and luit. */
case 1015: /* urxvt mangled mouse mode; incompatible
and can be mistaken for other control
codes. */
break;
case 80: /* DECSDM -- Sixel Display Mode */
MODBIT(term.mode, set, MODE_SIXEL_SDM);
break;
case 8452: /* sixel scrolling leaves cursor to right of graphic */
MODBIT(term.mode, set, MODE_SIXEL_CUR_RT);
break;
default:
fprintf(stderr,
"erresc: unknown private set/reset mode %d\n",
*args);
break;
}
} else {
switch (*args) {
case 0: /* Error (IGNORED) */
break;
case 2:
xsetmode(set, MODE_KBDLOCK);
break;
case 4: /* IRM -- Insertion-replacement */
MODBIT(term.mode, set, MODE_INSERT);
break;
case 12: /* SRM -- Send/Receive */
MODBIT(term.mode, !set, MODE_ECHO);
break;
case 20: /* LNM -- Linefeed/new line */
MODBIT(term.mode, set, MODE_CRLF);
break;
default:
fprintf(stderr,
"erresc: unknown set/reset mode %d\n",
*args);
break;
}
}
}
}
void
csihandle(void)
{
char buffer[40];
int n = 0, len;
ImageList *im, *next;
int pi, pa;
int x;
int maxcol = term.col;
switch (csiescseq.mode[0]) {
default:
unknown:
fprintf(stderr, "erresc: unknown csi ");
csidump();
/* die(""); */
break;
case '@': /* ICH -- Insert <n> blank char */
DEFAULT(csiescseq.arg[0], 1);
tinsertblank(csiescseq.arg[0]);
break;
case 'A': /* CUU -- Cursor <n> Up */
DEFAULT(csiescseq.arg[0], 1);
tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
break;
case 'B': /* CUD -- Cursor <n> Down */
case 'e': /* VPR --Cursor <n> Down */
DEFAULT(csiescseq.arg[0], 1);
tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
break;
case 'i': /* MC -- Media Copy */
switch (csiescseq.arg[0]) {
case 0:
tdump();
break;
case 1:
tdumpline(term.c.y);
break;
case 2:
tdumpsel();
break;
case 4:
term.mode &= ~MODE_PRINT;
break;
case 5:
term.mode |= MODE_PRINT;
break;
}
break;
case 'c': /* DA -- Device Attributes */
if (csiescseq.arg[0] == 0)
ttywrite(vtiden, strlen(vtiden), 0);
break;
case 'b': /* REP -- if last char is printable print it <n> more times */
LIMIT(csiescseq.arg[0], 1, 65535);
if (term.lastc)
while (csiescseq.arg[0]-- > 0)
tputc(term.lastc);
break;
case 'C': /* CUF -- Cursor <n> Forward */
case 'a': /* HPR -- Cursor <n> Forward */
DEFAULT(csiescseq.arg[0], 1);
tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
break;
case 'D': /* CUB -- Cursor <n> Backward */
DEFAULT(csiescseq.arg[0], 1);
tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
break;
case 'E': /* CNL -- Cursor <n> Down and first col */
DEFAULT(csiescseq.arg[0], 1);
tmoveto(0, term.c.y+csiescseq.arg[0]);
break;
case 'F': /* CPL -- Cursor <n> Up and first col */
DEFAULT(csiescseq.arg[0], 1);
tmoveto(0, term.c.y-csiescseq.arg[0]);
break;
case 'g': /* TBC -- Tabulation clear */
switch (csiescseq.arg[0]) {
case 0: /* clear current tab stop */
term.tabs[term.c.x] = 0;
break;
case 3: /* clear all the tabs */
memset(term.tabs, 0, term.col * sizeof(*term.tabs));
break;
default:
goto unknown;
}
break;
case 'G': /* CHA -- Move to <col> */
case '`': /* HPA */
DEFAULT(csiescseq.arg[0], 1);
tmoveto(csiescseq.arg[0]-1, term.c.y);
break;
case 'H': /* CUP -- Move to <row> <col> */
case 'f': /* HVP */
DEFAULT(csiescseq.arg[0], 1);
DEFAULT(csiescseq.arg[1], 1);
tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
break;
case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
DEFAULT(csiescseq.arg[0], 1);
tputtab(csiescseq.arg[0]);
break;
case 'J': /* ED -- Clear screen */
switch (csiescseq.arg[0]) {
case 0: /* below */
tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
if (term.c.y < term.row-1)
tclearregion(0, term.c.y+1, term.col-1, term.row-1, 1);
break;
case 1: /* above */
if (term.c.y >= 1)
tclearregion(0, 0, term.col-1, term.c.y-1, 1);
tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
break;
case 2: /* screen */
if (IS_SET(MODE_ALTSCREEN)) {
tclearregion(0, 0, term.col-1, term.row-1, 1);
tdeleteimages();
break;
}
/* vte does this:
tscrollup(0, term.row-1, term.row, SCROLL_SAVEHIST); */
/* alacritty does this: */
for (n = term.row-1; n >= 0 && tlinelen(term.line[n]) == 0; n--)
;
for (im = term.images; im; im = im->next)
n = MAX(im->y - term.scr, n);
if (n >= 0)
tscrollup(0, term.row-1, n+1, SCROLL_SAVEHIST);
tscrollup(0, term.row-1, term.row-n-1, SCROLL_NOSAVEHIST);
break;
break;
case 3: /* scrollback */
if (IS_SET(MODE_ALTSCREEN))
break;
kscrolldown(&((Arg){ .i = term.scr }));
term.scr = 0;
term.histi = 0;
term.histf = 0;
for (im = term.images; im; im = next) {
next = im->next;
if (im->y < 0)
delete_image(im);
}
break;
case 6: /* sixels */
tdeleteimages();
tfulldirt();
break;
default:
goto unknown;
}
break;
case 'K': /* EL -- Clear line */
switch (csiescseq.arg[0]) {
case 0: /* right */
tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
break;
case 1: /* left */
tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
break;
case 2: /* all */
tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
break;
}
break;
case 'S': /* SU -- Scroll <n> line up ; XTSMGRAPHICS */
if (csiescseq.priv) {
if (csiescseq.narg > 1) {
/* XTSMGRAPHICS */
pi = csiescseq.arg[0];
pa = csiescseq.arg[1];
if (pi == 1 && (pa == 1 || pa == 2 || pa == 4)) {
/* number of sixel color registers */
/* (read, reset and read the maximum value give the same response) */
n = snprintf(buffer, sizeof buffer, "\033[?1;0;%dS", DECSIXEL_PALETTE_MAX);
ttywrite(buffer, n, 1);
break;
} else if (pi == 2 && (pa == 1 || pa == 2 || pa == 4)) {
/* sixel graphics geometry (in pixels) */
/* (read, reset and read the maximum value give the same response) */
n = snprintf(buffer, sizeof buffer, "\033[?2;0;%d;%dS",
MIN(term.col * win.cw, DECSIXEL_WIDTH_MAX),
MIN(term.row * win.ch, DECSIXEL_HEIGHT_MAX));
ttywrite(buffer, n, 1);
break;
}
/* the number of color registers and sixel geometry can't be changed */
n = snprintf(buffer, sizeof buffer, "\033[?%d;3;0S", pi); /* failure */
ttywrite(buffer, n, 1);
}
goto unknown;
}
DEFAULT(csiescseq.arg[0], 1);
/* xterm, urxvt, alacritty save this in history */
tscrollup(term.top, term.bot, csiescseq.arg[0], SCROLL_SAVEHIST);
break;
case 'T': /* SD -- Scroll <n> line down */
DEFAULT(csiescseq.arg[0], 1);
tscrolldown(term.top, csiescseq.arg[0]);
break;
case 'L': /* IL -- Insert <n> blank lines */
DEFAULT(csiescseq.arg[0], 1);
tinsertblankline(csiescseq.arg[0]);
break;
case 'l': /* RM -- Reset Mode */
tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
break;
case 'M': /* DL -- Delete <n> lines */
DEFAULT(csiescseq.arg[0], 1);
tdeleteline(csiescseq.arg[0]);
break;
case 'X': /* ECH -- Erase <n> char */
if (csiescseq.arg[0] < 0)
return;
DEFAULT(csiescseq.arg[0], 1);
x = MIN(term.c.x + csiescseq.arg[0], term.col) - 1;
tclearregion(term.c.x, term.c.y, x, term.c.y, 1);
break;
case 'P': /* DCH -- Delete <n> char */
DEFAULT(csiescseq.arg[0], 1);
tdeletechar(csiescseq.arg[0]);
break;
case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
DEFAULT(csiescseq.arg[0], 1);
tputtab(-csiescseq.arg[0]);
break;
case 'd': /* VPA -- Move to <row> */
DEFAULT(csiescseq.arg[0], 1);
tmoveato(term.c.x, csiescseq.arg[0]-1);
break;
case 'h': /* SM -- Set terminal mode */
tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
break;
case 'm': /* SGR -- Terminal attribute (color) */
tsetattr(csiescseq.arg, csiescseq.narg);
break;
case 'n': /* DSR -- Device Status Report */
switch (csiescseq.arg[0]) {
case 5: /* Status Report "OK" `0n` */
ttywrite("\033[0n", sizeof("\033[0n") - 1, 0);
break;
case 6: /* Report Cursor Position (CPR) "<row>;<column>R" */
len = snprintf(buffer, sizeof(buffer), "\033[%i;%iR",
term.c.y+1, term.c.x+1);
ttywrite(buffer, len, 0);
break;
default:
goto unknown;
}
break;
case 'r': /* DECSTBM -- Set Scrolling Region */
if (csiescseq.priv) {
goto unknown;
} else {
DEFAULT(csiescseq.arg[0], 1);
DEFAULT(csiescseq.arg[1], term.row);
tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
tmoveato(0, 0);
}
break;
case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
tcursor(CURSOR_SAVE);
break;
case 't': /* title stack operations ; XTWINOPS */
switch (csiescseq.arg[0]) {
case 14: /* text area size in pixels */
if (csiescseq.narg > 1)
goto unknown;
n = snprintf(buffer, sizeof buffer, "\033[4;%d;%dt",
term.row * win.ch, term.col * win.cw);
ttywrite(buffer, n, 1);
break;
case 16: /* character cell size in pixels */
n = snprintf(buffer, sizeof buffer, "\033[6;%d;%dt", win.ch, win.cw);
ttywrite(buffer, n, 1);
break;
case 18: /* size of the text area in characters */
n = snprintf(buffer, sizeof buffer, "\033[8;%d;%dt", term.row, term.col);
ttywrite(buffer, n, 1);
break;
default:
goto unknown;
}
break;
case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
tcursor(CURSOR_LOAD);
break;
case ' ':
switch (csiescseq.mode[1]) {
case 'q': /* DECSCUSR -- Set Cursor Style */
if (xsetcursor(csiescseq.arg[0]))
goto unknown;
break;
default:
goto unknown;
}
break;
}
}
void
csidump(void)
{
size_t i;
uint c;
fprintf(stderr, "ESC[");
for (i = 0; i < csiescseq.len; i++) {
c = csiescseq.buf[i] & 0xff;
if (isprint(c)) {
putc(c, stderr);
} else if (c == '\n') {
fprintf(stderr, "(\\n)");
} else if (c == '\r') {
fprintf(stderr, "(\\r)");
} else if (c == 0x1b) {
fprintf(stderr, "(\\e)");
} else {
fprintf(stderr, "(%02x)", c);
}
}
putc('\n', stderr);
}
void
csireset(void)
{
memset(&csiescseq, 0, sizeof(csiescseq));
}
void
osc_color_response(int num, int index, int is_osc4)
{
int n;
char buf[32];
unsigned char r, g, b;
if (xgetcolor(is_osc4 ? num : index, &r, &g, &b)) {
fprintf(stderr, "erresc: failed to fetch %s color %d\n",
is_osc4 ? "osc4" : "osc",
is_osc4 ? num : index);
return;
}
n = snprintf(buf, sizeof buf, "\033]%s%d;rgb:%02x%02x/%02x%02x/%02x%02x%s",
is_osc4 ? "4;" : "", num, r, r, g, g, b, b, strescseq.term);
if (n < 0 || n >= sizeof(buf)) {
fprintf(stderr, "error: %s while printing %s response\n",
n < 0 ? "snprintf failed" : "truncation occurred",
is_osc4 ? "osc4" : "osc");
} else {
ttywrite(buf, n, 1);
}
}
void
strhandle(void)
{
char *p = NULL, *dec;
int j, narg, par;
const struct { int idx; char *str; } osc_table[] = {
{ defaultfg, "foreground" },
{ defaultbg, "background" },
{ defaultcs, "cursor" }
};
ImageList *im, *newimages, *next, *tail;
int i, x, y, x1, y1, x2, y2, numimages;
int cx, cy;
Line line;
int scr = IS_SET(MODE_ALTSCREEN) ? 0 : term.scr;
term.esc &= ~(ESC_STR_END|ESC_STR);
strparse();
par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
switch (strescseq.type) {
case ']': /* OSC -- Operating System Command */
switch (par) {
case 0:
if (narg > 1) {
xsettitle(strescseq.args[1]);
xseticontitle(strescseq.args[1]);
}
return;
case 1:
if (narg > 1)
xseticontitle(strescseq.args[1]);
return;
case 2:
if (narg > 1)
xsettitle(strescseq.args[1]);
return;
case 52:
if (narg > 2 && allowwindowops) {
dec = base64dec(strescseq.args[2]);
if (dec) {
xsetsel(dec);
xclipcopy();
} else {
fprintf(stderr, "erresc: invalid base64\n");
}
}
return;
case 8: /* Clear Hyperlinks */
return;
case 10:
case 11:
case 12:
if (narg < 2)
break;
p = strescseq.args[1];
if ((j = par - 10) < 0 || j >= LEN(osc_table))
break; /* shouldn't be possible */
if (!strcmp(p, "?")) {
osc_color_response(par, osc_table[j].idx, 0);
} else if (xsetcolorname(osc_table[j].idx, p)) {
fprintf(stderr, "erresc: invalid %s color: %s\n",
osc_table[j].str, p);
} else {
tfulldirt();
}
return;
case 4: /* color set */
if (narg < 3)
break;
p = strescseq.args[2];
/* FALLTHROUGH */
case 104: /* color reset */
j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
if (p && !strcmp(p, "?")) {
osc_color_response(j, 0, 1);
} else if (xsetcolorname(j, p)) {
if (par == 104 && narg <= 1) {
xloadcols();
return; /* color reset without parameter */
}
fprintf(stderr, "erresc: invalid color j=%d, p=%s\n",
j, p ? p : "(null)");
} else {
/*
* TODO if defaultbg color is changed, borders
* are dirty
*/
tfulldirt();
}
return;
}
break;
case 'k': /* old title set compatibility */
xsettitle(strescseq.args[0]);
return;
case 'P': /* DCS -- Device Control String */
if (IS_SET(MODE_SIXEL)) {
term.mode &= ~MODE_SIXEL;
if (!sixel_st.image.data) {
sixel_parser_deinit(&sixel_st);
return;
}
cx = IS_SET(MODE_SIXEL_SDM) ? 0 : term.c.x;
cy = IS_SET(MODE_SIXEL_SDM) ? 0 : term.c.y;
if ((numimages = sixel_parser_finalize(&sixel_st, &newimages,
cx, cy + scr, win.cw, win.ch)) <= 0) {
sixel_parser_deinit(&sixel_st);
perror("sixel_parser_finalize() failed");
return;
}
sixel_parser_deinit(&sixel_st);
x1 = newimages->x;
y1 = newimages->y;
x2 = x1 + newimages->cols;
y2 = y1 + numimages;
if (newimages->transparent) {
for (tail = term.images; tail && tail->next; tail = tail->next);
} else {
for (tail = NULL, im = term.images; im; im = next) {
next = im->next;
if (im->x >= x1 && im->x + im->cols <= x2 &&
im->y >= y1 && im->y <= y2) {
delete_image(im);
continue;
}
tail = im;
}
}
if (tail) {
tail->next = newimages;
newimages->prev = tail;
} else {
term.images = newimages;
}
x2 = MIN(x2, term.col);
for (i = 0, im = newimages; im; im = next, i++) {
next = im->next;
scr = IS_SET(MODE_ALTSCREEN) ? 0 : term.scr;
if (IS_SET(MODE_SIXEL_SDM)) {
if (i >= term.row) {
delete_image(im);
continue;
}
im->y = i + scr;
line = term.line[i];
} else {
im->y = term.c.y + scr;
line = term.line[term.c.y];
}
for (x = im->x; x < x2; x++) {
line[x].mode |= ATTR_SIXEL;
}
term.dirty[MIN(im->y, term.row-1)] = 1;
if (!IS_SET(MODE_SIXEL_SDM) && i < numimages-1) {
im->next = NULL;
tnewline(0);
im->next = next;
}
}
/* if mode 8452 is set, sixel scrolling leaves cursor to right of graphic */
if (!IS_SET(MODE_SIXEL_SDM) && IS_SET(MODE_SIXEL_CUR_RT))
term.c.x = MIN(term.c.x + newimages->cols, term.col-1);
}
return;
case '_': /* APC -- Application Program Command */
case '^': /* PM -- Privacy Message */
return;
}
fprintf(stderr, "erresc: unknown str ");
strdump();
}
void
strparse(void)
{
int c;
char *p = strescseq.buf;
strescseq.narg = 0;
strescseq.buf[strescseq.len] = '\0';
if (*p == '\0')
return;
while (strescseq.narg < STR_ARG_SIZ) {
strescseq.args[strescseq.narg++] = p;
while ((c = *p) != ';' && c != '\0')
++p;
if (c == '\0')
return;
*p++ = '\0';
}
}
void
strdump(void)
{
size_t i;
uint c;
fprintf(stderr, "ESC%c", strescseq.type);
for (i = 0; i < strescseq.len; i++) {
c = strescseq.buf[i] & 0xff;
if (c == '\0') {
putc('\n', stderr);
return;
} else if (isprint(c)) {
putc(c, stderr);
} else if (c == '\n') {
fprintf(stderr, "(\\n)");
} else if (c == '\r') {
fprintf(stderr, "(\\r)");
} else if (c == 0x1b) {
fprintf(stderr, "(\\e)");
} else {
fprintf(stderr, "(%02x)", c);
}
}
fprintf(stderr, (strescseq.term[0] == 0x1b) ? "ESC\\\n" : "BEL\n");
}
void
strreset(void)
{
strescseq = (STREscape){
.buf = xrealloc(strescseq.buf, STR_BUF_SIZ),
.siz = STR_BUF_SIZ,
};
}
void
sendbreak(const Arg *arg)
{
if (tcsendbreak(cmdfd, 0))
perror("Error sending break");
}
void
tprinter(char *s, size_t len)
{
if (iofd != -1 && xwrite(iofd, s, len) < 0) {
perror("Error writing to output file");
close(iofd);
iofd = -1;
}
}
void
toggleprinter(const Arg *arg)
{
term.mode ^= MODE_PRINT;
}
void
printscreen(const Arg *arg)
{
tdump();
}
void
printsel(const Arg *arg)
{
tdumpsel();
}
void
tdumpsel(void)
{
char *ptr;
if ((ptr = getsel())) {
tprinter(ptr, strlen(ptr));
free(ptr);
}
}
void
tdump(void)
{
int i;
for (i = 0; i < term.row; ++i)
tdumpline(i);
}
void
tputtab(int n)
{
uint x = term.c.x;
if (n > 0) {
while (x < term.col && n--)
for (++x; x < term.col && !term.tabs[x]; ++x)
/* nothing */ ;
} else if (n < 0) {
while (x > 0 && n++)
for (--x; x > 0 && !term.tabs[x]; --x)
/* nothing */ ;
}
term.c.x = LIMIT(x, 0, term.col-1);
}
void
tdefutf8(char ascii)
{
if (ascii == 'G')
term.mode |= MODE_UTF8;
else if (ascii == '@')
term.mode &= ~MODE_UTF8;
}
void
tdeftran(char ascii)
{
static char cs[] = "0B";
static int vcs[] = {CS_GRAPHIC0, CS_USA};
char *p;
if ((p = strchr(cs, ascii)) == NULL) {
fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
} else {
term.trantbl[term.icharset] = vcs[p - cs];
}
}
void
tdectest(char c)
{
int x, y;
if (c == '8') { /* DEC screen alignment test. */
for (x = 0; x < term.col; ++x) {
for (y = 0; y < term.row; ++y)
tsetchar('E', &term.c.attr, x, y);
}
}
}
void
tstrsequence(uchar c)
{
strreset();
switch (c) {
case 0x90: /* DCS -- Device Control String */
c = 'P';
term.esc |= ESC_DCS;
break;
case 0x9f: /* APC -- Application Program Command */
c = '_';
break;
case 0x9e: /* PM -- Privacy Message */
c = '^';
break;
case 0x9d: /* OSC -- Operating System Command */
c = ']';
break;
}
strescseq.type = c;
term.esc |= ESC_STR;
}
void
tcontrolcode(uchar ascii)
{
switch (ascii) {
case '\t': /* HT */
tputtab(1);
return;
case '\b': /* BS */
tmoveto(term.c.x-1, term.c.y);
return;
case '\r': /* CR */
tmoveto(0, term.c.y);
return;
case '\f': /* LF */
case '\v': /* VT */
case '\n': /* LF */
/* go to first col if the mode is set */
tnewline(IS_SET(MODE_CRLF));
return;
case '\a': /* BEL */
if (term.esc & ESC_STR_END) {
/* backwards compatibility to xterm */
strescseq.term = STR_TERM_BEL;
strhandle();
} else {
xbell();
}
break;
case '\033': /* ESC */
csireset();
term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
term.esc |= ESC_START;
return;
case '\016': /* SO (LS1 -- Locking shift 1) */
case '\017': /* SI (LS0 -- Locking shift 0) */
term.charset = 1 - (ascii - '\016');
return;
case '\032': /* SUB */
tsetchar('?', &term.c.attr, term.c.x, term.c.y);
/* FALLTHROUGH */
case '\030': /* CAN */
csireset();
break;
case '\005': /* ENQ (IGNORED) */
case '\000': /* NUL (IGNORED) */
case '\021': /* XON (IGNORED) */
case '\023': /* XOFF (IGNORED) */
case 0177: /* DEL (IGNORED) */
return;
case 0x80: /* TODO: PAD */
case 0x81: /* TODO: HOP */
case 0x82: /* TODO: BPH */
case 0x83: /* TODO: NBH */
case 0x84: /* TODO: IND */
break;
case 0x85: /* NEL -- Next line */
tnewline(1); /* always go to first col */
break;
case 0x86: /* TODO: SSA */
case 0x87: /* TODO: ESA */
break;
case 0x88: /* HTS -- Horizontal tab stop */
term.tabs[term.c.x] = 1;
break;
case 0x89: /* TODO: HTJ */
case 0x8a: /* TODO: VTS */
case 0x8b: /* TODO: PLD */
case 0x8c: /* TODO: PLU */
case 0x8d: /* TODO: RI */
case 0x8e: /* TODO: SS2 */
case 0x8f: /* TODO: SS3 */
case 0x91: /* TODO: PU1 */
case 0x92: /* TODO: PU2 */
case 0x93: /* TODO: STS */
case 0x94: /* TODO: CCH */
case 0x95: /* TODO: MW */
case 0x96: /* TODO: SPA */
case 0x97: /* TODO: EPA */
case 0x98: /* TODO: SOS */
case 0x99: /* TODO: SGCI */
break;
case 0x9a: /* DECID -- Identify Terminal */
ttywrite(vtiden, strlen(vtiden), 0);
break;
case 0x9b: /* TODO: CSI */
case 0x9c: /* TODO: ST */
break;
case 0x90: /* DCS -- Device Control String */
case 0x9d: /* OSC -- Operating System Command */
case 0x9e: /* PM -- Privacy Message */
case 0x9f: /* APC -- Application Program Command */
tstrsequence(ascii);
return;
}
/* only CAN, SUB, \a and C1 chars interrupt a sequence */
term.esc &= ~(ESC_STR_END|ESC_STR);
}
void
dcshandle(void)
{
int bgcolor, transparent;
unsigned char r, g, b, a = 255;
switch (csiescseq.mode[0]) {
default:
unknown:
fprintf(stderr, "erresc: unknown csi ");
csidump();
/* die(""); */
break;
case 'q': /* DECSIXEL */
transparent = (csiescseq.narg >= 2 && csiescseq.arg[1] == 1);
if (IS_TRUECOL(term.c.attr.bg)) {
r = term.c.attr.bg >> 16 & 255;
g = term.c.attr.bg >> 8 & 255;
b = term.c.attr.bg >> 0 & 255;
} else {
xgetcolor(term.c.attr.bg, &r, &g, &b);
if (term.c.attr.bg == defaultbg)
a = dc.col[defaultbg].pixel >> 24 & 255;
}
bgcolor = a << 24 | r << 16 | g << 8 | b;
if (sixel_parser_init(&sixel_st, transparent, (255 << 24), bgcolor, 1, win.cw, win.ch) != 0)
perror("sixel_parser_init() failed");
term.mode |= MODE_SIXEL;
break;
}
}
/*
* returns 1 when the sequence is finished and it hasn't to read
* more characters for this sequence, otherwise 0
*/
int
eschandle(uchar ascii)
{
switch (ascii) {
case '[':
term.esc |= ESC_CSI;
return 0;
case '#':
term.esc |= ESC_TEST;
return 0;
case '%':
term.esc |= ESC_UTF8;
return 0;
case 'P': /* DCS -- Device Control String */
term.esc |= ESC_DCS;
case '_': /* APC -- Application Program Command */
case '^': /* PM -- Privacy Message */
case ']': /* OSC -- Operating System Command */
case 'k': /* old title set compatibility */
tstrsequence(ascii);
return 0;
case 'n': /* LS2 -- Locking shift 2 */
case 'o': /* LS3 -- Locking shift 3 */
term.charset = 2 + (ascii - 'n');
break;
case '(': /* GZD4 -- set primary charset G0 */
case ')': /* G1D4 -- set secondary charset G1 */
case '*': /* G2D4 -- set tertiary charset G2 */
case '+': /* G3D4 -- set quaternary charset G3 */
term.icharset = ascii - '(';
term.esc |= ESC_ALTCHARSET;
return 0;
case 'D': /* IND -- Linefeed */
if (term.c.y == term.bot) {
tscrollup(term.top, term.bot, 1, SCROLL_SAVEHIST);
} else {
tmoveto(term.c.x, term.c.y+1);
}
break;
case 'E': /* NEL -- Next line */
tnewline(1); /* always go to first col */
break;
case 'H': /* HTS -- Horizontal tab stop */
term.tabs[term.c.x] = 1;
break;
case 'M': /* RI -- Reverse index */
if (term.c.y == term.top) {
tscrolldown(term.top, 1);
} else {
tmoveto(term.c.x, term.c.y-1);
}
break;
case 'Z': /* DECID -- Identify Terminal */
ttywrite(vtiden, strlen(vtiden), 0);
break;
case 'c': /* RIS -- Reset to initial state */
treset();
resettitle();
xloadcols();
xsetmode(0, MODE_HIDE);
break;
case '=': /* DECPAM -- Application keypad */
xsetmode(1, MODE_APPKEYPAD);
break;
case '>': /* DECPNM -- Normal keypad */
xsetmode(0, MODE_APPKEYPAD);
break;
case '7': /* DECSC -- Save Cursor */
tcursor(CURSOR_SAVE);
break;
case '8': /* DECRC -- Restore Cursor */
tcursor(CURSOR_LOAD);
break;
case '\\': /* ST -- String Terminator */
if (term.esc & ESC_STR_END) {
strescseq.term = STR_TERM_ST;
strhandle();
}
break;
default:
fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
(uchar) ascii, isprint(ascii)? ascii:'.');
break;
}
return 1;
}
void
tputc(Rune u)
{
char c[UTF_SIZ];
int control;
int width, len;
Glyph *gp;
control = ISCONTROL(u);
if (u < 127 || !IS_SET(MODE_UTF8))
{
c[0] = u;
width = len = 1;
} else {
len = utf8encode(u, c);
if (!control && (width = wcwidth(u)) == -1)
width = 1;
}
if (IS_SET(MODE_PRINT))
tprinter(c, len);
/*
* STR sequence must be checked before anything else
* because it uses all following characters until it
* receives a ESC, a SUB, a ST or any other C1 control
* character.
*/
if (term.esc & ESC_STR) {
if (u == '\a' || u == 030 || u == 032 || u == 033 ||
ISCONTROLC1(u)) {
term.esc &= ~(ESC_START|ESC_STR|ESC_DCS);
term.esc |= ESC_STR_END;
goto check_control_code;
}
if (term.esc & ESC_DCS)
goto check_control_code;
if (strescseq.len+len >= strescseq.siz) {
/*
* Here is a bug in terminals. If the user never sends
* some code to stop the str or esc command, then st
* will stop responding. But this is better than
* silently failing with unknown characters. At least
* then users will report back.
*
* In the case users ever get fixed, here is the code:
*/
/*
* term.esc = 0;
* strhandle();
*/
if (strescseq.siz > (SIZE_MAX - UTF_SIZ) / 2)
return;
strescseq.siz *= 2;
strescseq.buf = xrealloc(strescseq.buf, strescseq.siz);
}
memmove(&strescseq.buf[strescseq.len], c, len);
strescseq.len += len;
return;
}
check_control_code:
/*
* Actions of control codes must be performed as soon they arrive
* because they can be embedded inside a control sequence, and
* they must not cause conflicts with sequences.
*/
if (control) {
/* in UTF-8 mode ignore handling C1 control characters */
if (IS_SET(MODE_UTF8) && ISCONTROLC1(u))
return;
tcontrolcode(u);
/*
* control codes are not shown ever
*/
if (!term.esc)
term.lastc = 0;
return;
} else if (term.esc & ESC_START) {
if (term.esc & ESC_CSI) {
csiescseq.buf[csiescseq.len++] = u;
if (BETWEEN(u, 0x40, 0x7E)
|| csiescseq.len >= \
sizeof(csiescseq.buf)-1) {
term.esc = 0;
csiparse();
csihandle();
}
return;
} else if (term.esc & ESC_DCS) {
csiescseq.buf[csiescseq.len++] = u;
if (BETWEEN(u, 0x40, 0x7E)
|| csiescseq.len >= \
sizeof(csiescseq.buf)-1) {
csiparse();
dcshandle();
}
return;
} else if (term.esc & ESC_UTF8) {
tdefutf8(u);
} else if (term.esc & ESC_ALTCHARSET) {
tdeftran(u);
} else if (term.esc & ESC_TEST) {
tdectest(u);
} else {
if (!eschandle(u))
return;
/* sequence already finished */
}
term.esc = 0;
/*
* All characters which form part of a sequence are not
* printed
*/
return;
}
/* selected() takes relative coordinates */
if (selected(term.c.x + term.scr, term.c.y + term.scr))
selclear();
gp = &term.line[term.c.y][term.c.x];
if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
gp->mode |= ATTR_WRAP;
tnewline(1);
gp = &term.line[term.c.y][term.c.x];
}
if (IS_SET(MODE_INSERT) && term.c.x+width < term.col) {
memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
gp->mode &= ~ATTR_WIDE;
}
if (term.c.x+width > term.col) {
if (IS_SET(MODE_WRAP))
tnewline(1);
else
tmoveto(term.col - width, term.c.y);
gp = &term.line[term.c.y][term.c.x];
}
tsetchar(u, &term.c.attr, term.c.x, term.c.y);
term.lastc = u;
if (width == 2) {
gp->mode |= ATTR_WIDE;
if (term.c.x+1 < term.col) {
if (gp[1].mode == ATTR_WIDE && term.c.x+2 < term.col) {
gp[2].u = ' ';
gp[2].mode &= ~ATTR_WDUMMY;
}
gp[1].u = '\0';
gp[1].mode = ATTR_WDUMMY;
}
}
if (term.c.x+width < term.col) {
tmoveto(term.c.x+width, term.c.y);
} else {
term.wrapcwidth[IS_SET(MODE_ALTSCREEN)] = width;
term.c.state |= CURSOR_WRAPNEXT;
}
}
int
twrite(const char *buf, int buflen, int show_ctrl)
{
int charsize;
Rune u;
int n;
for (n = 0; n < buflen; n += charsize) {
if (IS_SET(MODE_SIXEL) && sixel_st.state != PS_ESC) {
charsize = sixel_parser_parse(&sixel_st, (const unsigned char*)buf + n, buflen - n);
continue;
} else if (IS_SET(MODE_UTF8))
{
/* process a complete utf8 char */
charsize = utf8decode(buf + n, &u, buflen - n);
if (charsize == 0)
break;
} else {
u = buf[n] & 0xFF;
charsize = 1;
}
if (show_ctrl && ISCONTROL(u)) {
if (u & 0x80) {
u &= 0x7f;
tputc('^');
tputc('[');
} else if (u != '\n' && u != '\r' && u != '\t') {
u ^= 0x40;
tputc('^');
}
}
tputc(u);
}
return n;
}
void
resettitle(void)
{
xsettitle(NULL);
}
void
drawregion(int x1, int y1, int x2, int y2)
{
int y;
for (y = y1; y < y2; y++) {
if (!term.dirty[y])
continue;
term.dirty[y] = 0;
xdrawline(TLINE(y), x1, y, x2);
}
}
#include "patch/st_include.c"
void
draw(void)
{
int cx = term.c.x, ocx = term.ocx, ocy = term.ocy;
if (!xstartdraw())
return;
/* adjust cursor position */
LIMIT(term.ocx, 0, term.col-1);
LIMIT(term.ocy, 0, term.row-1);
if (term.line[term.ocy][term.ocx].mode & ATTR_WDUMMY)
term.ocx--;
if (term.line[term.c.y][cx].mode & ATTR_WDUMMY)
cx--;
drawregion(0, 0, term.col, term.row);
if (term.scr == 0)
xdrawcursor(cx, term.c.y, term.line[term.c.y][cx],
term.ocx, term.ocy, term.line[term.ocy][term.ocx],
term.line[term.ocy], term.col);
term.ocx = cx;
term.ocy = term.c.y;
xfinishdraw();
if (ocx != term.ocx || ocy != term.ocy)
xximspot(term.ocx, term.ocy);
}
void
redraw(void)
{
tfulldirt();
draw();
}

View File

@ -1,8 +0,0 @@
[Desktop Entry]
Name=st
Comment=st is a simple terminal implementation for X
Exec=st
Icon=utilities-terminal
Terminal=false
Type=Application
Categories=System;TerminalEmulator;

View File

@ -1,335 +0,0 @@
/* See LICENSE for license details. */
#include <stdint.h>
#include <time.h>
#include <sys/types.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <X11/Xft/Xft.h>
#include <X11/XKBlib.h>
/* macros */
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) < (b) ? (b) : (a))
#define LEN(a) (sizeof(a) / sizeof(a)[0])
#define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
#define DIVCEIL(n, d) (((n) + ((d) - 1)) / (d))
#define DEFAULT(a, b) (a) = (a) ? (a) : (b)
#define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
#define ATTRCMP(a, b) (((a).mode & (~ATTR_WRAP) & (~ATTR_LIGA)) != ((b).mode & (~ATTR_WRAP) & (~ATTR_LIGA)) || \
(a).fg != (b).fg || \
(a).bg != (b).bg)
#define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + \
(t1.tv_nsec-t2.tv_nsec)/1E6)
#define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
#define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
#define IS_TRUECOL(x) (1 << 24 & (x))
#define HISTSIZE 2000
enum glyph_attribute {
ATTR_NULL = 0,
ATTR_SET = 1 << 0,
ATTR_BOLD = 1 << 1,
ATTR_FAINT = 1 << 2,
ATTR_ITALIC = 1 << 3,
ATTR_UNDERLINE = 1 << 4,
ATTR_BLINK = 1 << 5,
ATTR_REVERSE = 1 << 6,
ATTR_INVISIBLE = 1 << 7,
ATTR_STRUCK = 1 << 8,
ATTR_WRAP = 1 << 9,
ATTR_WIDE = 1 << 10,
ATTR_WDUMMY = 1 << 11,
ATTR_BOXDRAW = 1 << 13,
ATTR_LIGA = 1 << 15,
ATTR_SIXEL = 1 << 16,
ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
};
typedef struct _ImageList {
struct _ImageList *next, *prev;
unsigned char *pixels;
void *pixmap;
void *clipmask;
int width;
int height;
int x;
int y;
int reflow_y;
int cols;
int cw;
int ch;
int transparent;
} ImageList;
enum drawing_mode {
DRAW_NONE = 0,
DRAW_BG = 1 << 0,
DRAW_FG = 1 << 1,
};
/* Used to control which screen(s) keybindings and mouse shortcuts apply to. */
enum screen {
S_PRI = -1, /* primary screen */
S_ALL = 0, /* both primary and alt screen */
S_ALT = 1 /* alternate screen */
};
enum selection_mode {
SEL_IDLE = 0,
SEL_EMPTY = 1,
SEL_READY = 2
};
enum selection_type {
SEL_REGULAR = 1,
SEL_RECTANGULAR = 2
};
enum selection_snap {
SNAP_WORD = 1,
SNAP_LINE = 2
};
typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned short ushort;
typedef uint_least32_t Rune;
typedef XftDraw *Draw;
typedef XftColor Color;
typedef XftGlyphFontSpec GlyphFontSpec;
#define Glyph Glyph_
typedef struct {
Rune u; /* character code */
uint32_t mode; /* attribute flags */
uint32_t fg; /* foreground */
uint32_t bg; /* background */
} Glyph;
typedef Glyph *Line;
typedef struct {
int ox;
int charlen;
int numspecs;
Glyph base;
} GlyphFontSeq;
typedef struct {
Glyph attr; /* current char attributes */
int x;
int y;
char state;
} TCursor;
/* Internal representation of the screen */
typedef struct {
int row; /* nb row */
int col; /* nb col */
Line *line; /* screen */
Line *alt; /* alternate screen */
Line hist[HISTSIZE]; /* history buffer */
int histi; /* history index */
int histf; /* nb history available */
int scr; /* scroll back */
int wrapcwidth[2]; /* used in updating WRAPNEXT when resizing */
int *dirty; /* dirtyness of lines */
TCursor c; /* cursor */
int ocx; /* old cursor col */
int ocy; /* old cursor row */
int top; /* top scroll limit */
int bot; /* bottom scroll limit */
int mode; /* terminal mode flags */
int esc; /* escape state flags */
char trantbl[4]; /* charset table translation */
int charset; /* current charset */
int icharset; /* selected charset for sequence */
int *tabs;
ImageList *images; /* sixel images */
ImageList *images_alt; /* sixel images for alternate screen */
Rune lastc; /* last printed char outside of sequence, 0 if control */
} Term;
typedef union {
int i;
uint ui;
float f;
const void *v;
const char *s;
} Arg;
/* Purely graphic info */
typedef struct {
int tw, th; /* tty width and height */
int w, h; /* window width and height */
int ch; /* char height */
int cw; /* char width */
int mode; /* window state/mode flags */
int cursor; /* cursor style */
} TermWindow;
typedef struct {
Display *dpy;
Colormap cmap;
Window win;
Drawable buf;
GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
GlyphFontSeq *specseq;
Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
struct {
XIM xim;
XIC xic;
XPoint spot;
XVaNestedList spotlist;
} ime;
Draw draw;
Visual *vis;
XSetWindowAttributes attrs;
/* Here, we use the term *pointer* to differentiate the cursor
* one sees when hovering the mouse over the terminal from, e.g.,
* a green rectangle where text would be entered. */
Cursor vpointer, bpointer; /* visible and hidden pointers */
int pointerisvisible;
int scr;
int isfixed; /* is fixed geometry? */
int depth; /* bit depth */
int l, t; /* left and top offset */
int gm; /* geometry mask */
} XWindow;
typedef struct {
Atom xtarget;
char *primary, *clipboard;
struct timespec tclick1;
struct timespec tclick2;
} XSelection;
/* types used in config.h */
typedef struct {
uint mod;
KeySym keysym;
void (*func)(const Arg *);
const Arg arg;
int screen;
} Shortcut;
typedef struct {
uint mod;
uint button;
void (*func)(const Arg *);
const Arg arg;
uint release;
int screen;
} MouseShortcut;
typedef struct {
KeySym k;
uint mask;
char *s;
/* three-valued logic variables: 0 indifferent, 1 on, -1 off */
signed char appkey; /* application keypad */
signed char appcursor; /* application cursor */
} Key;
/* Font structure */
#define Font Font_
typedef struct {
int height;
int width;
int ascent;
int descent;
int badslant;
int badweight;
short lbearing;
short rbearing;
XftFont *match;
FcFontSet *set;
FcPattern *pattern;
} Font;
/* Drawing Context */
typedef struct {
Color *col;
size_t collen;
Font font, bfont, ifont, ibfont;
GC gc;
} DC;
void die(const char *, ...);
void redraw(void);
void draw(void);
void drawregion(int, int, int, int);
void tfulldirt(void);
void printscreen(const Arg *);
void printsel(const Arg *);
void sendbreak(const Arg *);
void toggleprinter(const Arg *);
int tattrset(int);
int tisaltscr(void);
void tnew(int, int);
void tresize(int, int);
void tsetdirtattr(int);
void ttyhangup(void);
int ttynew(const char *, char *, const char *, char **);
size_t ttyread(void);
void ttyresize(int, int);
void ttywrite(const char *, size_t, int);
void resettitle(void);
void selclear(void);
void selinit(void);
void selremove(void);
void selstart(int, int, int);
void selextend(int, int, int, int);
int selected(int, int);
char *getsel(void);
size_t utf8encode(Rune, char *);
void *xmalloc(size_t);
void *xrealloc(void *, size_t);
char *xstrdup(const char *);
int xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b);
int isboxdraw(Rune);
ushort boxdrawindex(const Glyph *);
#ifdef XFT_VERSION
/* only exposed to x.c, otherwise we'll need Xft.h for the types */
void boxdraw_xinit(Display *, Colormap, XftDraw *, Visual *);
void drawboxes(int, int, int, int, XftColor *, XftColor *, const XftGlyphFontSpec *, int);
#endif // XFT_VERSION
/* config.h globals */
extern char *utmp;
extern char *scroll;
extern char *stty_args;
extern char *vtiden;
extern wchar_t *worddelimiters;
extern int allowaltscreen;
extern int allowwindowops;
extern char *termname;
extern unsigned int tabspaces;
extern unsigned int defaultfg;
extern unsigned int defaultbg;
extern unsigned int defaultcs;
extern int extpipeactive;
extern const int boxdraw, boxdraw_bold, boxdraw_braille;
extern float alpha;
extern DC dc;
extern XWindow xw;
extern XSelection xsel;
extern TermWindow win;
extern Term term;

View File

@ -1,252 +0,0 @@
st-mono| simpleterm monocolor,
# undercurl patch / UNDERCURL_PATCH
Su,
acsc=+C\,D-A.B0E``aaffgghFiGjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~,
am,
bce,
bel=^G,
blink=\E[5m,
bold=\E[1m,
cbt=\E[Z,
cvvis=\E[?25h,
civis=\E[?25l,
clear=\E[H\E[2J,
cnorm=\E[?12l\E[?25h,
colors#2,
cols#80,
cr=^M,
csr=\E[%i%p1%d;%p2%dr,
cub=\E[%p1%dD,
cub1=^H,
cud1=^J,
cud=\E[%p1%dB,
cuf1=\E[C,
cuf=\E[%p1%dC,
cup=\E[%i%p1%d;%p2%dH,
cuu1=\E[A,
cuu=\E[%p1%dA,
dch=\E[%p1%dP,
dch1=\E[P,
dim=\E[2m,
dl=\E[%p1%dM,
dl1=\E[M,
ech=\E[%p1%dX,
ed=\E[J,
el=\E[K,
el1=\E[1K,
enacs=\E)0,
E3=\E[3J,
flash=\E[?5h$<80/>\E[?5l,
fsl=^G,
home=\E[H,
hpa=\E[%i%p1%dG,
hs,
ht=^I,
hts=\EH,
ich=\E[%p1%d@,
il1=\E[L,
il=\E[%p1%dL,
ind=^J,
indn=\E[%p1%dS,
invis=\E[8m,
is2=\E[4l\E>\E[?1034l,
it#8,
kel=\E[1;2F,
ked=\E[1;5F,
ka1=\E[1~,
ka3=\E[5~,
kc1=\E[4~,
kc3=\E[6~,
kbs=\177,
kcbt=\E[Z,
kb2=\EOu,
kcub1=\EOD,
kcud1=\EOB,
kcuf1=\EOC,
kcuu1=\EOA,
kDC=\E[3;2~,
kent=\EOM,
kEND=\E[1;2F,
kIC=\E[2;2~,
kNXT=\E[6;2~,
kPRV=\E[5;2~,
kHOM=\E[1;2H,
kLFT=\E[1;2D,
kRIT=\E[1;2C,
kind=\E[1;2B,
kri=\E[1;2A,
kclr=\E[3;5~,
kdl1=\E[3;2~,
kdch1=\E[3~,
kich1=\E[2~,
kend=\E[4~,
kf1=\EOP,
kf2=\EOQ,
kf3=\EOR,
kf4=\EOS,
kf5=\E[15~,
kf6=\E[17~,
kf7=\E[18~,
kf8=\E[19~,
kf9=\E[20~,
kf10=\E[21~,
kf11=\E[23~,
kf12=\E[24~,
kf13=\E[1;2P,
kf14=\E[1;2Q,
kf15=\E[1;2R,
kf16=\E[1;2S,
kf17=\E[15;2~,
kf18=\E[17;2~,
kf19=\E[18;2~,
kf20=\E[19;2~,
kf21=\E[20;2~,
kf22=\E[21;2~,
kf23=\E[23;2~,
kf24=\E[24;2~,
kf25=\E[1;5P,
kf26=\E[1;5Q,
kf27=\E[1;5R,
kf28=\E[1;5S,
kf29=\E[15;5~,
kf30=\E[17;5~,
kf31=\E[18;5~,
kf32=\E[19;5~,
kf33=\E[20;5~,
kf34=\E[21;5~,
kf35=\E[23;5~,
kf36=\E[24;5~,
kf37=\E[1;6P,
kf38=\E[1;6Q,
kf39=\E[1;6R,
kf40=\E[1;6S,
kf41=\E[15;6~,
kf42=\E[17;6~,
kf43=\E[18;6~,
kf44=\E[19;6~,
kf45=\E[20;6~,
kf46=\E[21;6~,
kf47=\E[23;6~,
kf48=\E[24;6~,
kf49=\E[1;3P,
kf50=\E[1;3Q,
kf51=\E[1;3R,
kf52=\E[1;3S,
kf53=\E[15;3~,
kf54=\E[17;3~,
kf55=\E[18;3~,
kf56=\E[19;3~,
kf57=\E[20;3~,
kf58=\E[21;3~,
kf59=\E[23;3~,
kf60=\E[24;3~,
kf61=\E[1;4P,
kf62=\E[1;4Q,
kf63=\E[1;4R,
khome=\E[1~,
kil1=\E[2;5~,
krmir=\E[2;2~,
knp=\E[6~,
kmous=\E[M,
kpp=\E[5~,
lines#24,
mir,
msgr,
npc,
op=\E[39;49m,
pairs#64,
mc0=\E[i,
mc4=\E[4i,
mc5=\E[5i,
rc=\E8,
rev=\E[7m,
ri=\EM,
rin=\E[%p1%dT,
ritm=\E[23m,
rmacs=\E(B,
# CSI 22, 23 patch / CSI_22_23_PATCH
# rmcup=\E[?1049l,
rmcup=\E[?1049l\E[23;0;0t,
rmir=\E[4l,
rmkx=\E[?1l\E>,
rmso=\E[27m,
rmul=\E[24m,
rs1=\Ec,
rs2=\E[4l\E>\E[?1034l,
sc=\E7,
sitm=\E[3m,
sgr0=\E[0m,
smacs=\E(0,
# CSI 22, 23 patch / CSI_22_23_PATCH
# smcup=\E[?1049h,
smcup=\E[?1049h\E[22;0;0t,
smir=\E[4h,
smkx=\E[?1h\E=,
smso=\E[7m,
smul=\E[4m,
tbc=\E[3g,
tsl=\E]0;,
xenl,
vpa=\E[%i%p1%dd,
# XTerm extensions
rmxx=\E[29m,
smxx=\E[9m,
BE=\E[?2004h,
BD=\E[?2004l,
PS=\E[200~,
PE=\E[201~,
# disabled rep for now: causes some issues with older ncurses versions.
# rep=%p1%c\E[%p2%{1}%-%db,
# tmux extensions, see TERMINFO EXTENSIONS in tmux(1)
Tc,
Ms=\E]52;%p1%s;%p2%s\007,
Se=\E[2 q,
Ss=\E[%p1%d q,
# sync patch / SYNC_PATCH
Sync=\EP=%p1%ds\E\\,
st| simpleterm,
use=st-mono,
colors#8,
setab=\E[4%p1%dm,
setaf=\E[3%p1%dm,
setb=\E[4%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m,
setf=\E[3%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m,
sgr=%?%p9%t\E(0%e\E(B%;\E[0%?%p6%t;1%;%?%p2%t;4%;%?%p1%p3%|%t;7%;%?%p4%t;5%;%?%p7%t;8%;m,
st-256color| simpleterm with 256 colors,
use=st,
ccc,
colors#256,
oc=\E]104\007,
pairs#32767,
# Nicked from xterm-256color
initc=\E]4;%p1%d;rgb\:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\E\\,
setab=\E[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m,
setaf=\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m,
st-meta| simpleterm with meta key,
use=st,
km,
rmm=\E[?1034l,
smm=\E[?1034h,
rs2=\E[4l\E>\E[?1034h,
is2=\E[4l\E>\E[?1034h,
st-meta-256color| simpleterm with meta key and 256 colors,
use=st-256color,
km,
rmm=\E[?1034l,
smm=\E[?1034h,
rs2=\E[4l\E>\E[?1034h,
is2=\E[4l\E>\E[?1034h,
st-bs| simpleterm with backspace as backspace,
use=st,
kbs=\010,
kdch1=\177,
st-bs-256color| simpleterm with backspace as backspace and 256colors,
use=st-256color,
kbs=\010,
kdch1=\177,

View File

@ -1,42 +0,0 @@
/* See LICENSE for license details. */
enum win_mode {
MODE_VISIBLE = 1 << 0,
MODE_FOCUSED = 1 << 1,
MODE_APPKEYPAD = 1 << 2,
MODE_MOUSEBTN = 1 << 3,
MODE_MOUSEMOTION = 1 << 4,
MODE_REVERSE = 1 << 5,
MODE_KBDLOCK = 1 << 6,
MODE_HIDE = 1 << 7,
MODE_APPCURSOR = 1 << 8,
MODE_MOUSESGR = 1 << 9,
MODE_8BIT = 1 << 10,
MODE_BLINK = 1 << 11,
MODE_FBLINK = 1 << 12,
MODE_FOCUS = 1 << 13,
MODE_MOUSEX10 = 1 << 14,
MODE_MOUSEMANY = 1 << 15,
MODE_BRCKTPASTE = 1 << 16,
MODE_NUMLOCK = 1 << 17,
MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
|MODE_MOUSEMANY,
MODE_PLACEHOLDER = 1 << 18,
};
void xbell(void);
void xclipcopy(void);
void xdrawcursor(int, int, Glyph, int, int, Glyph, Line, int);
void xdrawline(Line, int, int, int);
void xfinishdraw(void);
void xloadcols(void);
int xsetcolorname(int, const char *);
void xseticontitle(char *);
void xsettitle(char *);
int xsetcursor(int);
void xsetmode(int, unsigned int);
void xsetpointermotion(int);
void xsetsel(char *);
int xstartdraw(void);
void xximspot(int, int);
void xclearwin(void);

View File

@ -1,2341 +0,0 @@
/* See LICENSE for license details. */
#include <errno.h>
#include <math.h>
#include <limits.h>
#include <locale.h>
#include <signal.h>
#include <sys/select.h>
#include <time.h>
#include <unistd.h>
#include <libgen.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <X11/Xft/Xft.h>
#include <X11/XKBlib.h>
char *argv0;
#include "arg.h"
#include "st.h"
#include "win.h"
#include "hb.h"
#include <Imlib2.h>
#include "sixel.h"
/* X modifiers */
#define XK_ANY_MOD UINT_MAX
#define XK_NO_MOD 0
#define XK_SWITCH_MOD (1<<13|1<<14)
/* function definitions used in config.h */
static void clipcopy(const Arg *);
static void clippaste(const Arg *);
static void numlock(const Arg *);
static void selpaste(const Arg *);
static void ttysend(const Arg *);
static void zoom(const Arg *);
static void zoomabs(const Arg *);
static void zoomreset(const Arg *);
#include "patch/st_include.h"
#include "patch/x_include.h"
/* config.h for applying patches and the configuration. */
#include "config.h"
/* XEMBED messages */
#define XEMBED_FOCUS_IN 4
#define XEMBED_FOCUS_OUT 5
/* macros */
#define IS_SET(flag) ((win.mode & (flag)) != 0)
#define TRUERED(x) (((x) & 0xff0000) >> 8)
#define TRUEGREEN(x) (((x) & 0xff00))
#define TRUEBLUE(x) (((x) & 0xff) << 8)
static inline ushort sixd_to_16bit(int);
static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int, int, int);
static inline void xresetfontsettings(uint32_t mode, Font **font, int *frcflags);
void xdrawglyph(Glyph, int, int);
static void xclear(int, int, int, int);
static int xgeommasktogravity(int);
static int ximopen(Display *);
static void ximinstantiate(Display *, XPointer, XPointer);
static void ximdestroy(XIM, XPointer, XPointer);
static int xicdestroy(XIC, XPointer, XPointer);
static void xinit(int, int);
static void cresize(int, int);
static void xresize(int, int);
static void xhints(void);
static int xloadcolor(int, const char *, Color *);
static int xloadfont(Font *, FcPattern *);
static void xloadfonts(const char *, double);
static void xunloadfont(Font *);
static void xunloadfonts(void);
static void xsetenv(void);
static void xseturgency(int);
static int evcol(XEvent *);
static int evrow(XEvent *);
static void expose(XEvent *);
static void visibility(XEvent *);
static void unmap(XEvent *);
static void kpress(XEvent *);
static void cmessage(XEvent *);
static void resize(XEvent *);
static void focus(XEvent *);
static uint buttonmask(uint);
static void brelease(XEvent *);
static void bpress(XEvent *);
static void bmotion(XEvent *);
static void propnotify(XEvent *);
static void selnotify(XEvent *);
static void selclear_(XEvent *);
static void selrequest(XEvent *);
static void setsel(char *, Time);
static void sigusr1_reload(int sig);
static int mouseaction(XEvent *, uint);
static void mousesel(XEvent *, int);
static void mousereport(XEvent *);
static char *kmap(KeySym, uint);
static int match(uint, uint);
static void run(void);
static void usage(void);
static void (*handler[LASTEvent])(XEvent *) = {
[KeyPress] = kpress,
[ClientMessage] = cmessage,
[ConfigureNotify] = resize,
[VisibilityNotify] = visibility,
[UnmapNotify] = unmap,
[Expose] = expose,
[FocusIn] = focus,
[FocusOut] = focus,
[MotionNotify] = bmotion,
[ButtonPress] = bpress,
[ButtonRelease] = brelease,
/*
* Uncomment if you want the selection to disappear when you select something
* different in another window.
*/
/* [SelectionClear] = selclear_, */
[SelectionNotify] = selnotify,
/*
* PropertyNotify is only turned on when there is some INCR transfer happening
* for the selection retrieval.
*/
[PropertyNotify] = propnotify,
[SelectionRequest] = selrequest,
};
/* Globals */
Term term;
DC dc;
XWindow xw;
XSelection xsel;
TermWindow win;
/* Font Ring Cache */
enum {
FRC_NORMAL,
FRC_ITALIC,
FRC_BOLD,
FRC_ITALICBOLD
};
typedef struct {
XftFont *font;
int flags;
Rune unicodep;
} Fontcache;
/* Fontcache is an array now. A new font will be appended to the array. */
static Fontcache *frc = NULL;
static int frclen = 0;
static int frccap = 0;
static char *usedfont = NULL;
static double usedfontsize = 0;
static double defaultfontsize = 0;
static char *opt_alpha = NULL;
static char *opt_class = NULL;
static char **opt_cmd = NULL;
static char *opt_embed = NULL;
static char *opt_font = NULL;
static char *opt_io = NULL;
static char *opt_line = NULL;
static char *opt_name = NULL;
static char *opt_title = NULL;
static uint buttons; /* bit field of pressed buttons */
static int cursorblinks = 0;
static Cursor cursor;
static XColor xmousefg, xmousebg;
#include "patch/x_include.c"
void
clipcopy(const Arg *dummy)
{
Atom clipboard;
free(xsel.clipboard);
xsel.clipboard = NULL;
if (xsel.primary != NULL) {
xsel.clipboard = xstrdup(xsel.primary);
clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
}
}
void
clippaste(const Arg *dummy)
{
Atom clipboard;
clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
xw.win, CurrentTime);
}
void
numlock(const Arg *dummy)
{
win.mode ^= MODE_NUMLOCK;
}
void
selpaste(const Arg *dummy)
{
XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
xw.win, CurrentTime);
}
void
ttysend(const Arg *arg)
{
ttywrite(arg->s, strlen(arg->s), 1);
}
void
zoom(const Arg *arg)
{
Arg larg;
larg.f = usedfontsize + arg->f;
if (larg.f >= 1.0)
zoomabs(&larg);
}
void
zoomabs(const Arg *arg)
{
ImageList *im;
xunloadfonts();
xloadfonts(usedfont, arg->f);
xloadsparefonts();
/* deleting old pixmaps forces the new scaled pixmaps to be created */
for (im = term.images; im; im = im->next) {
if (im->pixmap)
XFreePixmap(xw.dpy, (Drawable)im->pixmap);
if (im->clipmask)
XFreePixmap(xw.dpy, (Drawable)im->clipmask);
im->pixmap = NULL;
im->clipmask = NULL;
}
cresize(0, 0);
redraw();
xhints();
}
void
zoomreset(const Arg *arg)
{
Arg larg;
if (defaultfontsize > 0) {
larg.f = defaultfontsize;
zoomabs(&larg);
}
}
int
evcol(XEvent *e)
{
int x = e->xbutton.x - borderpx;
LIMIT(x, 0, win.tw - 1);
return x / win.cw;
}
int
evrow(XEvent *e)
{
int y = e->xbutton.y - borderpx;
LIMIT(y, 0, win.th - 1);
return y / win.ch;
}
uint
buttonmask(uint button)
{
return button == Button1 ? Button1Mask
: button == Button2 ? Button2Mask
: button == Button3 ? Button3Mask
: button == Button4 ? Button4Mask
: button == Button5 ? Button5Mask
: 0;
}
int
mouseaction(XEvent *e, uint release)
{
MouseShortcut *ms;
int screen = tisaltscr() ? S_ALT : S_PRI;
/* ignore Button<N>mask for Button<N> - it's set on release */
uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
if (ms->release == release &&
ms->button == e->xbutton.button &&
(!ms->screen || (ms->screen == screen)) &&
(match(ms->mod, state) || /* exact or forced */
match(ms->mod, state & ~forcemousemod))) {
ms->func(&(ms->arg));
return 1;
}
}
return 0;
}
void
mousesel(XEvent *e, int done)
{
int type, seltype = SEL_REGULAR;
uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
for (type = 1; type < LEN(selmasks); ++type) {
if (match(selmasks[type], state)) {
seltype = type;
break;
}
}
selextend(evcol(e), evrow(e), seltype, done);
if (done)
setsel(getsel(), e->xbutton.time);
}
void
mousereport(XEvent *e)
{
int len, btn, code;
int x = evcol(e), y = evrow(e);
int state = e->xbutton.state;
char buf[40];
static int ox, oy;
if (e->type == MotionNotify) {
if (x == ox && y == oy)
return;
if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
return;
/* MODE_MOUSEMOTION: no reporting if no button is pressed */
if (IS_SET(MODE_MOUSEMOTION) && buttons == 0)
return;
/* Set btn to lowest-numbered pressed button, or 12 if no
* buttons are pressed. */
for (btn = 1; btn <= 11 && !(buttons & (1<<(btn-1))); btn++)
;
code = 32;
} else {
btn = e->xbutton.button;
/* Only buttons 1 through 11 can be encoded */
if (btn < 1 || btn > 11)
return;
if (e->type == ButtonRelease) {
/* MODE_MOUSEX10: no button release reporting */
if (IS_SET(MODE_MOUSEX10))
return;
/* Don't send release events for the scroll wheel */
if (btn == 4 || btn == 5)
return;
}
code = 0;
}
ox = x;
oy = y;
/* Encode btn into code. If no button is pressed for a motion event in
* MODE_MOUSEMANY, then encode it as a release. */
if ((!IS_SET(MODE_MOUSESGR) && e->type == ButtonRelease) || btn == 12)
code += 3;
else if (btn >= 8)
code += 128 + btn - 8;
else if (btn >= 4)
code += 64 + btn - 4;
else
code += btn - 1;
if (!IS_SET(MODE_MOUSEX10)) {
code += ((state & ShiftMask ) ? 4 : 0)
+ ((state & Mod1Mask ) ? 8 : 0) /* meta key: alt */
+ ((state & ControlMask) ? 16 : 0);
}
if (IS_SET(MODE_MOUSESGR)) {
len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
code, x+1, y+1,
e->type == ButtonRelease ? 'm' : 'M');
} else if (x < 223 && y < 223) {
len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
32+code, 32+x+1, 32+y+1);
} else {
return;
}
ttywrite(buf, len, 0);
}
void
bpress(XEvent *e)
{
int btn = e->xbutton.button;
struct timespec now;
int snap;
if (1 <= btn && btn <= 11)
buttons |= 1 << (btn-1);
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
if (mouseaction(e, 0))
return;
if (btn == Button1) {
/*
* If the user clicks below predefined timeouts specific
* snapping behaviour is exposed.
*/
clock_gettime(CLOCK_MONOTONIC, &now);
if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
snap = SNAP_LINE;
} else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
snap = SNAP_WORD;
} else {
snap = 0;
}
xsel.tclick2 = xsel.tclick1;
xsel.tclick1 = now;
selstart(evcol(e), evrow(e), snap);
}
}
void
propnotify(XEvent *e)
{
XPropertyEvent *xpev;
Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
xpev = &e->xproperty;
if (xpev->state == PropertyNewValue &&
(xpev->atom == XA_PRIMARY ||
xpev->atom == clipboard)) {
selnotify(e);
}
}
void
selnotify(XEvent *e)
{
ulong nitems, ofs, rem;
int format;
uchar *data, *last, *repl;
Atom type, incratom, property = None;
incratom = XInternAtom(xw.dpy, "INCR", 0);
ofs = 0;
if (e->type == SelectionNotify)
property = e->xselection.property;
else if (e->type == PropertyNotify)
property = e->xproperty.atom;
if (property == None)
return;
do {
if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
BUFSIZ/4, False, AnyPropertyType,
&type, &format, &nitems, &rem,
&data)) {
fprintf(stderr, "Clipboard allocation failed\n");
return;
}
if (e->type == PropertyNotify && nitems == 0 && rem == 0)
{
/*
* If there is some PropertyNotify with no data, then
* this is the signal of the selection owner that all
* data has been transferred. We won't need to receive
* PropertyNotify events anymore.
*/
MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
&xw.attrs);
}
if (type == incratom) {
/*
* Activate the PropertyNotify events so we receive
* when the selection owner does send us the next
* chunk of data.
*/
MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
&xw.attrs);
/*
* Deleting the property is the transfer start signal.
*/
XDeleteProperty(xw.dpy, xw.win, (int)property);
continue;
}
/*
* As seen in getsel:
* Line endings are inconsistent in the terminal and GUI world
* copy and pasting. When receiving some selection data,
* replace all '\n' with '\r'.
* FIXME: Fix the computer world.
*/
repl = data;
last = data + nitems * format / 8;
while ((repl = memchr(repl, '\n', last - repl))) {
*repl++ = '\r';
}
if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
ttywrite("\033[200~", 6, 0);
ttywrite((char *)data, nitems * format / 8, 1);
if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
ttywrite("\033[201~", 6, 0);
XFree(data);
/* number of 32-bit chunks returned */
ofs += nitems * format / 32;
} while (rem > 0);
/*
* Deleting the property again tells the selection owner to send the
* next data chunk in the property.
*/
XDeleteProperty(xw.dpy, xw.win, (int)property);
}
void
xclipcopy(void)
{
clipcopy(NULL);
}
void
selclear_(XEvent *e)
{
selclear();
}
void
selrequest(XEvent *e)
{
XSelectionRequestEvent *xsre;
XSelectionEvent xev;
Atom xa_targets, string, clipboard;
char *seltext;
xsre = (XSelectionRequestEvent *) e;
xev.type = SelectionNotify;
xev.requestor = xsre->requestor;
xev.selection = xsre->selection;
xev.target = xsre->target;
xev.time = xsre->time;
if (xsre->property == None)
xsre->property = xsre->target;
/* reject */
xev.property = None;
xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
if (xsre->target == xa_targets) {
/* respond with the supported type */
string = xsel.xtarget;
XChangeProperty(xsre->display, xsre->requestor, xsre->property,
XA_ATOM, 32, PropModeReplace,
(uchar *) &string, 1);
xev.property = xsre->property;
} else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
/*
* xith XA_STRING non ascii characters may be incorrect in the
* requestor. It is not our problem, use utf8.
*/
clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
if (xsre->selection == XA_PRIMARY) {
seltext = xsel.primary;
} else if (xsre->selection == clipboard) {
seltext = xsel.clipboard;
} else {
fprintf(stderr,
"Unhandled clipboard selection 0x%lx\n",
xsre->selection);
return;
}
if (seltext != NULL) {
XChangeProperty(xsre->display, xsre->requestor,
xsre->property, xsre->target,
8, PropModeReplace,
(uchar *)seltext, strlen(seltext));
xev.property = xsre->property;
}
}
/* all done, send a notification to the listener */
if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
fprintf(stderr, "Error sending SelectionNotify event\n");
}
void
setsel(char *str, Time t)
{
if (!str)
return;
free(xsel.primary);
xsel.primary = str;
XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
selclear();
clipcopy(NULL);
}
void
sigusr1_reload(int sig)
{
reload_config(sig);
signal(SIGUSR1, sigusr1_reload);
}
void
xsetsel(char *str)
{
setsel(str, CurrentTime);
}
void
brelease(XEvent *e)
{
int btn = e->xbutton.button;
if (1 <= btn && btn <= 11)
buttons &= ~(1 << (btn-1));
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
if (mouseaction(e, 1))
return;
if (btn == Button1) {
mousesel(e, 1);
}
else if (btn == Button3)
plumb(xsel.primary);
}
void
bmotion(XEvent *e)
{
if (!xw.pointerisvisible) {
if (win.mode & MODE_MOUSE)
XUndefineCursor(xw.dpy, xw.win);
else
XDefineCursor(xw.dpy, xw.win, xw.vpointer);
xw.pointerisvisible = 1;
if (!IS_SET(MODE_MOUSEMANY))
xsetpointermotion(0);
}
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
mousesel(e, 0);
}
void
cresize(int width, int height)
{
int col, row;
if (width != 0)
win.w = width;
if (height != 0)
win.h = height;
col = (win.w - 2 * borderpx) / win.cw;
row = (win.h - 2 * borderpx) / win.ch;
col = MAX(2, col);
row = MAX(1, row);
tresize(col, row);
xresize(col, row);
ttyresize(win.tw, win.th);
}
void
xresize(int col, int row)
{
win.tw = col * win.cw;
win.th = row * win.ch;
XFreePixmap(xw.dpy, xw.buf);
xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
xw.depth
);
XftDrawChange(xw.draw, xw.buf);
xclear(0, 0, win.w, win.h);
/* resize to new width */
xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec) * 4);
xw.specseq = xrealloc(xw.specseq, col * sizeof(GlyphFontSeq));
}
ushort
sixd_to_16bit(int x)
{
return x == 0 ? 0 : 0x3737 + 0x2828 * x;
}
int
xloadcolor(int i, const char *name, Color *ncolor)
{
XRenderColor color = { .alpha = 0xffff };
if (!name) {
if (BETWEEN(i, 16, 255)) { /* 256 color */
if (i < 6*6*6+16) { /* same colors as xterm */
color.red = sixd_to_16bit( ((i-16)/36)%6 );
color.green = sixd_to_16bit( ((i-16)/6) %6 );
color.blue = sixd_to_16bit( ((i-16)/1) %6 );
} else { /* greyscale */
color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
color.green = color.blue = color.red;
}
return XftColorAllocValue(xw.dpy, xw.vis,
xw.cmap, &color, ncolor);
} else
name = colorname[i];
}
return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
}
void
xloadcols(void)
{
int i;
static int loaded;
Color *cp;
if (loaded) {
for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
} else {
dc.collen = MAX(LEN(colorname), 256);
dc.col = xmalloc(dc.collen * sizeof(Color));
}
for (i = 0; i < dc.collen; i++)
if (!xloadcolor(i, NULL, &dc.col[i])) {
if (colorname[i])
die("could not allocate color '%s'\n", colorname[i]);
else
die("could not allocate color %d\n", i);
}
/* set alpha value of bg color */
if (opt_alpha)
alpha = strtof(opt_alpha, NULL);
dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha);
dc.col[defaultbg].pixel &= 0x00FFFFFF;
dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24;
dc.col[defaultbg].color.red *= alpha;
dc.col[defaultbg].color.green *= alpha;
dc.col[defaultbg].color.blue *= alpha;
loaded = 1;
}
int
xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b)
{
if (!BETWEEN(x, 0, dc.collen - 1))
return 1;
*r = dc.col[x].color.red >> 8;
*g = dc.col[x].color.green >> 8;
*b = dc.col[x].color.blue >> 8;
return 0;
}
int
xsetcolorname(int x, const char *name)
{
Color ncolor;
if (!BETWEEN(x, 0, dc.collen - 1))
return 1;
if (!xloadcolor(x, name, &ncolor))
return 1;
XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
dc.col[x] = ncolor;
/* set alpha value of bg color */
if (x == defaultbg) {
if (opt_alpha)
alpha = strtof(opt_alpha, NULL);
dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha);
dc.col[defaultbg].pixel &= 0x00FFFFFF;
dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24;
dc.col[defaultbg].color.red *= alpha;
dc.col[defaultbg].color.green *= alpha;
dc.col[defaultbg].color.blue *= alpha;
}
return 0;
}
/*
* Absolute coordinates.
*/
void
xclear(int x1, int y1, int x2, int y2)
{
Color c;
c = dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg];
if (invertcolors) {
c = invertedcolor(&c);
}
XftDrawRect(xw.draw, &c, x1, y1, x2-x1, y2-y1);
}
void
xclearwin(void)
{
xclear(0, 0, win.w, win.h);
}
void
xhints(void)
{
XClassHint class = {opt_name ? opt_name : "st",
opt_class ? opt_class : "St"};
XWMHints wm = {.flags = InputHint, .input = 1};
XSizeHints *sizeh;
sizeh = XAllocSizeHints();
sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
sizeh->height = win.h;
sizeh->width = win.w;
sizeh->height_inc = win.ch;
sizeh->width_inc = win.cw;
sizeh->base_height = 2 * borderpx;
sizeh->base_width = 2 * borderpx;
sizeh->min_height = win.ch + 2 * borderpx;
sizeh->min_width = win.cw + 2 * borderpx;
if (xw.isfixed) {
sizeh->flags |= PMaxSize;
sizeh->min_width = sizeh->max_width = win.w;
sizeh->min_height = sizeh->max_height = win.h;
}
if (xw.gm & (XValue|YValue)) {
sizeh->flags |= USPosition | PWinGravity;
sizeh->x = xw.l;
sizeh->y = xw.t;
sizeh->win_gravity = xgeommasktogravity(xw.gm);
}
XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
&class);
XFree(sizeh);
}
int
xgeommasktogravity(int mask)
{
switch (mask & (XNegative|YNegative)) {
case 0:
return NorthWestGravity;
case XNegative:
return NorthEastGravity;
case YNegative:
return SouthWestGravity;
}
return SouthEastGravity;
}
int
ximopen(Display *dpy)
{
XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
if (xw.ime.xim == NULL)
return 0;
if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
fprintf(stderr, "XSetIMValues: "
"Could not set XNDestroyCallback.\n");
xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
NULL);
if (xw.ime.xic == NULL) {
xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, xw.win,
XNDestroyCallback, &icdestroy,
NULL);
}
if (xw.ime.xic == NULL)
fprintf(stderr, "XCreateIC: Could not create input context.\n");
return 1;
}
void
ximinstantiate(Display *dpy, XPointer client, XPointer call)
{
if (ximopen(dpy))
XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
}
void
ximdestroy(XIM xim, XPointer client, XPointer call)
{
xw.ime.xim = NULL;
XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
XFree(xw.ime.spotlist);
}
int
xicdestroy(XIC xim, XPointer client, XPointer call)
{
xw.ime.xic = NULL;
return 1;
}
int
xloadfont(Font *f, FcPattern *pattern)
{
FcPattern *configured;
FcPattern *match;
FcResult result;
XGlyphInfo extents;
int wantattr, haveattr;
/*
* Manually configure instead of calling XftMatchFont
* so that we can use the configured pattern for
* "missing glyph" lookups.
*/
configured = FcPatternDuplicate(pattern);
if (!configured)
return 1;
FcConfigSubstitute(NULL, configured, FcMatchPattern);
XftDefaultSubstitute(xw.dpy, xw.scr, configured);
match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
if (!match) {
FcPatternDestroy(configured);
return 1;
}
if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
FcPatternDestroy(configured);
FcPatternDestroy(match);
return 1;
}
if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
XftResultMatch)) {
/*
* Check if xft was unable to find a font with the appropriate
* slant but gave us one anyway. Try to mitigate.
*/
if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
&haveattr) != XftResultMatch) || haveattr < wantattr) {
f->badslant = 1;
fputs("font slant does not match\n", stderr);
}
}
if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
XftResultMatch)) {
if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
&haveattr) != XftResultMatch) || haveattr != wantattr) {
f->badweight = 1;
fputs("font weight does not match\n", stderr);
}
}
XftTextExtentsUtf8(xw.dpy, f->match,
(const FcChar8 *) ascii_printable,
strlen(ascii_printable), &extents);
f->set = NULL;
f->pattern = configured;
f->ascent = f->match->ascent;
f->descent = f->match->descent;
f->lbearing = 0;
f->rbearing = f->match->max_advance_width;
f->height = f->ascent + f->descent;
f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
return 0;
}
void
xloadfonts(const char *fontstr, double fontsize)
{
FcPattern *pattern;
double fontval;
if (fontstr[0] == '-')
pattern = XftXlfdParse(fontstr, False, False);
else
pattern = FcNameParse((const FcChar8 *)fontstr);
if (!pattern)
die("can't open font %s\n", fontstr);
if (fontsize > 1) {
FcPatternDel(pattern, FC_PIXEL_SIZE);
FcPatternDel(pattern, FC_SIZE);
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
usedfontsize = fontsize;
} else {
if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
FcResultMatch) {
usedfontsize = fontval;
} else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
FcResultMatch) {
usedfontsize = -1;
} else {
/*
* Default font size is 12, if none given. This is to
* have a known usedfontsize value.
*/
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
usedfontsize = 12;
}
defaultfontsize = usedfontsize;
}
if (xloadfont(&dc.font, pattern))
die("can't open font %s\n", fontstr);
if (usedfontsize < 0) {
FcPatternGetDouble(dc.font.match->pattern,
FC_PIXEL_SIZE, 0, &fontval);
usedfontsize = fontval;
if (fontsize == 0)
defaultfontsize = fontval;
}
/* Setting character width and height. */
win.cw = ceilf(dc.font.width * cwscale);
win.ch = ceilf(dc.font.height * chscale);
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
if (xloadfont(&dc.ifont, pattern))
die("can't open font %s\n", fontstr);
FcPatternDel(pattern, FC_WEIGHT);
FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
if (xloadfont(&dc.ibfont, pattern))
die("can't open font %s\n", fontstr);
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
if (xloadfont(&dc.bfont, pattern))
die("can't open font %s\n", fontstr);
FcPatternDestroy(pattern);
}
void
xunloadfont(Font *f)
{
XftFontClose(xw.dpy, f->match);
FcPatternDestroy(f->pattern);
if (f->set)
FcFontSetDestroy(f->set);
}
void
xunloadfonts(void)
{
/* Clear Harfbuzz font cache. */
hbunloadfonts();
/* Free the loaded fonts in the font cache. */
while (frclen > 0)
XftFontClose(xw.dpy, frc[--frclen].font);
xunloadfont(&dc.font);
xunloadfont(&dc.bfont);
xunloadfont(&dc.ifont);
xunloadfont(&dc.ibfont);
}
void
xinit(int cols, int rows)
{
XGCValues gcvalues;
Pixmap blankpm;
Window parent;
pid_t thispid = getpid();
XWindowAttributes attr;
XVisualInfo vis;
xw.scr = XDefaultScreen(xw.dpy);
if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) {
parent = XRootWindow(xw.dpy, xw.scr);
xw.depth = 32;
} else {
XGetWindowAttributes(xw.dpy, parent, &attr);
xw.depth = attr.depth;
}
XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis);
xw.vis = vis.visual;
/* font */
if (!FcInit())
die("could not init fontconfig.\n");
usedfont = (opt_font == NULL)? font : opt_font;
xloadfonts(usedfont, 0);
/* spare fonts */
xloadsparefonts();
/* colors */
xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None);
xloadcols();
/* adjust fixed window geometry */
win.w = 2 * borderpx + cols * win.cw;
win.h = 2 * borderpx + rows * win.ch;
if (xw.gm & XNegative)
xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
if (xw.gm & YNegative)
xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
/* Events */
xw.attrs.background_pixel = dc.col[defaultbg].pixel;
xw.attrs.border_pixel = dc.col[defaultbg].pixel;
xw.attrs.bit_gravity = NorthWestGravity;
xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
| ExposureMask | VisibilityChangeMask | StructureNotifyMask
| ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
;
xw.attrs.colormap = xw.cmap;
xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
win.w, win.h, 0, xw.depth, InputOutput,
xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
| CWEventMask | CWColormap, &xw.attrs);
memset(&gcvalues, 0, sizeof(gcvalues));
gcvalues.graphics_exposures = False;
xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth);
dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues);
XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
/* font spec buffer */
xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec) * 4);
xw.specseq = xmalloc(cols * sizeof(GlyphFontSeq));
/* Xft rendering context */
xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
/* input methods */
if (!ximopen(xw.dpy)) {
XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
}
/* white cursor, black outline */
xw.pointerisvisible = 1;
xw.vpointer = XCreateFontCursor(xw.dpy, mouseshape);
XDefineCursor(xw.dpy, xw.win, xw.vpointer);
if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
xmousefg.red = 0xffff;
xmousefg.green = 0xffff;
xmousefg.blue = 0xffff;
}
if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
xmousebg.red = 0x0000;
xmousebg.green = 0x0000;
xmousebg.blue = 0x0000;
}
XRecolorCursor(xw.dpy, xw.vpointer, &xmousefg, &xmousebg);
blankpm = XCreateBitmapFromData(xw.dpy, xw.win, &(char){0}, 1, 1);
xw.bpointer = XCreatePixmapCursor(xw.dpy, blankpm, blankpm,
&xmousefg, &xmousebg, 0, 0);
xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
PropModeReplace, (uchar *)&thispid, 1);
win.mode = MODE_NUMLOCK;
resettitle();
xhints();
XMapWindow(xw.dpy, xw.win);
XSync(xw.dpy, False);
clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
xsel.primary = NULL;
xsel.clipboard = NULL;
xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
if (xsel.xtarget == None)
xsel.xtarget = XA_STRING;
boxdraw_xinit(xw.dpy, xw.cmap, xw.draw, xw.vis);
}
void
xresetfontsettings(uint32_t mode, Font **font, int *frcflags)
{
*font = &dc.font;
if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
*font = &dc.ibfont;
*frcflags = FRC_ITALICBOLD;
} else if (mode & ATTR_ITALIC) {
*font = &dc.ifont;
*frcflags = FRC_ITALIC;
} else if (mode & ATTR_BOLD) {
*font = &dc.bfont;
*frcflags = FRC_BOLD;
}
}
int
xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
{
float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
ushort mode, prevmode = USHRT_MAX;
Font *font = &dc.font;
int frcflags = FRC_NORMAL;
float runewidth = win.cw * ((glyphs[0].mode & ATTR_WIDE) ? 2.0f : 1.0f);
Rune rune;
FT_UInt glyphidx;
FcResult fcres;
FcPattern *fcpattern, *fontpattern;
FcFontSet *fcsets[] = { NULL };
FcCharSet *fccharset;
int i, f, numspecs = 0;
float cluster_xp, cluster_yp;
HbTransformData shaped;
/* Initial values. */
xresetfontsettings(glyphs[0].mode, &font, &frcflags);
xp = winx, yp = winy + font->ascent;
cluster_xp = xp; cluster_yp = yp;
/* Shape the segment. */
hbtransform(&shaped, font->match, glyphs, 0, len);
for (int code_idx = 0; code_idx < shaped.count; code_idx++)
{
/* Fetch rune and mode for current glyph. */
int idx = shaped.glyphs[code_idx].cluster;
/* Skip dummy wide-character spacing. */
if (glyphs[idx].mode & ATTR_WDUMMY)
continue;
/* Advance the drawing cursor if we've moved to a new cluster */
if (code_idx > 0 && idx != shaped.glyphs[code_idx - 1].cluster) {
xp += runewidth;
cluster_xp = xp;
cluster_yp = yp;
}
if (glyphs[idx].mode & ATTR_BOXDRAW) {
/* minor shoehorning: boxdraw uses only this ushort */
specs[numspecs].font = font->match;
specs[numspecs].glyph = boxdrawindex(&glyphs[idx]);
specs[numspecs].x = xp;
specs[numspecs].y = yp;
numspecs++;
} else if (shaped.glyphs[code_idx].codepoint != 0) {
/* If symbol is found, put it into the specs. */
specs[numspecs].font = font->match;
specs[numspecs].glyph = shaped.glyphs[code_idx].codepoint;
specs[numspecs].x = cluster_xp + (short)(shaped.positions[code_idx].x_offset / 64.);
specs[numspecs].y = cluster_yp - (short)(shaped.positions[code_idx].y_offset / 64.);
cluster_xp += shaped.positions[code_idx].x_advance / 64.;
cluster_yp += shaped.positions[code_idx].y_advance / 64.;
numspecs++;
} else {
/* If it's not found, try to fetch it through the font cache. */
rune = glyphs[idx].u;
for (f = 0; f < frclen; f++) {
glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
/* Everything correct. */
if (glyphidx && frc[f].flags == frcflags)
break;
/* We got a default font for a not found glyph. */
if (!glyphidx && frc[f].flags == frcflags
&& frc[f].unicodep == rune) {
break;
}
}
/* Nothing was found. Use fontconfig to find matching font. */
if (f >= frclen) {
if (!font->set)
font->set = FcFontSort(0, font->pattern, 1, 0, &fcres);
fcsets[0] = font->set;
/*
* Nothing was found in the cache. Now use
* some dozen of Fontconfig calls to get the
* font for one single character.
*
* Xft and fontconfig are design failures.
*/
fcpattern = FcPatternDuplicate(font->pattern);
fccharset = FcCharSetCreate();
FcCharSetAddChar(fccharset, rune);
FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
FcConfigSubstitute(0, fcpattern, FcMatchPattern);
FcDefaultSubstitute(fcpattern);
fontpattern = FcFontSetMatch(0, fcsets, 1, fcpattern, &fcres);
/* Allocate memory for the new cache entry. */
if (frclen >= frccap) {
frccap += 16;
frc = xrealloc(frc, frccap * sizeof(Fontcache));
}
frc[frclen].font = XftFontOpenPattern(xw.dpy, fontpattern);
if (!frc[frclen].font)
die("XftFontOpenPattern failed seeking fallback font: %s\n",
strerror(errno));
frc[frclen].flags = frcflags;
frc[frclen].unicodep = rune;
glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
f = frclen;
frclen++;
FcPatternDestroy(fcpattern);
FcCharSetDestroy(fccharset);
}
specs[numspecs].font = frc[f].font;
specs[numspecs].glyph = glyphidx;
specs[numspecs].x = (short)xp;
specs[numspecs].y = (short)yp;
numspecs++;
}
}
return numspecs;
}
void
xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y
,int dmode
, int charlen
) {
int width = charlen * win.cw;
int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch;
Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
XRenderColor colfg, colbg;
XRectangle r;
/* Fallback on color display for attributes not supported by the font */
if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
if (dc.ibfont.badslant || dc.ibfont.badweight)
base.fg = defaultattr;
} else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
(base.mode & ATTR_BOLD && dc.bfont.badweight)) {
base.fg = defaultattr;
}
if (IS_TRUECOL(base.fg)) {
colfg.alpha = 0xffff;
colfg.red = TRUERED(base.fg);
colfg.green = TRUEGREEN(base.fg);
colfg.blue = TRUEBLUE(base.fg);
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
fg = &truefg;
} else {
fg = &dc.col[base.fg];
}
if (IS_TRUECOL(base.bg)) {
colbg.alpha = 0xffff;
colbg.green = TRUEGREEN(base.bg);
colbg.red = TRUERED(base.bg);
colbg.blue = TRUEBLUE(base.bg);
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
bg = &truebg;
} else {
bg = &dc.col[base.bg];
}
if (IS_SET(MODE_REVERSE)) {
if (fg == &dc.col[defaultfg]) {
fg = &dc.col[defaultbg];
} else {
colfg.red = ~fg->color.red;
colfg.green = ~fg->color.green;
colfg.blue = ~fg->color.blue;
colfg.alpha = fg->color.alpha;
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
&revfg);
fg = &revfg;
}
if (bg == &dc.col[defaultbg]) {
bg = &dc.col[defaultfg];
} else {
colbg.red = ~bg->color.red;
colbg.green = ~bg->color.green;
colbg.blue = ~bg->color.blue;
colbg.alpha = bg->color.alpha;
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
&revbg);
bg = &revbg;
}
}
if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
colfg.red = fg->color.red / 2;
colfg.green = fg->color.green / 2;
colfg.blue = fg->color.blue / 2;
colfg.alpha = fg->color.alpha;
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
fg = &revfg;
}
if (base.mode & ATTR_REVERSE) {
temp = fg;
fg = bg;
bg = temp;
}
if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
fg = bg;
if (base.mode & ATTR_INVISIBLE)
fg = bg;
if (invertcolors) {
revfg = invertedcolor(fg);
revbg = invertedcolor(bg);
fg = &revfg;
bg = &revbg;
}
if (dmode & DRAW_BG) {
/* Intelligent cleaning up of the borders. */
if (x == 0) {
xclear(0, (y == 0)? 0 : winy, borderpx,
winy + win.ch +
((winy + win.ch >= borderpx + win.th)? win.h : 0));
}
if (winx + width >= borderpx + win.tw) {
xclear(winx + width, (y == 0)? 0 : winy, win.w,
((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
}
if (y == 0)
xclear(winx, 0, winx + width, borderpx);
if (winy + win.ch >= borderpx + win.th)
xclear(winx, winy + win.ch, winx + width, win.h);
/* Clean up the region we want to draw to. */
/* Set the clip region because Xft is sometimes dirty. */
r.x = 0;
r.y = 0;
r.height = win.ch;
r.width = width;
XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
/* Fill the background */
XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
}
if (dmode & DRAW_FG) {
if (base.mode & ATTR_BOXDRAW) {
drawboxes(winx, winy, width / len, win.ch, fg, bg, specs, len);
} else {
/* Render the glyphs. */
XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
}
/* Render underline and strikethrough. */
if (base.mode & ATTR_UNDERLINE) {
XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent * chscale + 1,
width, 1);
}
if (base.mode & ATTR_STRUCK) {
XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent * chscale / 3,
width, 1);
}
}
/* Reset clip to none. */
XftDrawSetClip(xw.draw, 0);
}
void
xdrawglyph(Glyph g, int x, int y)
{
int numspecs;
XftGlyphFontSpec *specs = xw.specbuf;
numspecs = xmakeglyphfontspecs(specs, &g, 1, x, y);
xdrawglyphfontspecs(specs, g, numspecs, x, y
,DRAW_BG | DRAW_FG
,(g.mode & ATTR_WIDE) ? 2 : 1
);
}
void
xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og, Line line, int len)
{
Color drawcol;
/* remove the old cursor */
if (selected(ox, oy))
og.mode ^= ATTR_REVERSE;
/* Redraw the line where cursor was previously.
* It will restore the ligatures broken by the cursor. */
xdrawline(line, 0, oy, len);
if (IS_SET(MODE_HIDE) || !IS_SET(MODE_FOCUSED))
return;
/*
* Select the right color for the right mode.
*/
g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE
|ATTR_BOXDRAW
;
if (IS_SET(MODE_REVERSE)) {
g.mode |= ATTR_REVERSE;
g.bg = defaultfg;
if (selected(cx, cy)) {
drawcol = dc.col[defaultcs];
g.fg = defaultrcs;
} else {
drawcol = dc.col[defaultrcs];
g.fg = defaultcs;
}
} else {
if (selected(cx, cy)) {
g.fg = defaultfg;
g.bg = defaultrcs;
} else {
g.fg = defaultbg;
g.bg = defaultcs;
}
drawcol = dc.col[g.bg];
}
/* draw the new one */
if (IS_SET(MODE_FOCUSED)) {
switch (win.cursor) {
case 0: /* Blinking block */
case 1: /* Blinking block (default) */
if (IS_SET(MODE_BLINK))
break;
/* FALLTHROUGH */
case 2: /* Steady block */
xdrawglyph(g, cx, cy);
break;
case 3: /* Blinking underline */
if (IS_SET(MODE_BLINK))
break;
/* FALLTHROUGH */
case 4: /* Steady underline */
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + (cy + 1) * win.ch - \
cursorthickness,
win.cw, cursorthickness);
break;
case 5: /* Blinking bar */
if (IS_SET(MODE_BLINK))
break;
/* FALLTHROUGH */
case 6: /* Steady bar */
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + cy * win.ch,
cursorthickness, win.ch);
break;
case 7: /* Blinking st cursor */
if (IS_SET(MODE_BLINK))
break;
/* FALLTHROUGH */
case 8: /* Steady st cursor */
g.u = stcursor;
xdrawglyph(g, cx, cy);
break;
}
} else {
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + cy * win.ch,
win.cw - 1, 1);
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + cy * win.ch,
1, win.ch - 1);
XftDrawRect(xw.draw, &drawcol,
borderpx + (cx + 1) * win.cw - 1,
borderpx + cy * win.ch,
1, win.ch - 1);
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + (cy + 1) * win.ch - 1,
win.cw, 1);
}
}
void
xsetenv(void)
{
char buf[sizeof(long) * 8 + 1];
snprintf(buf, sizeof(buf), "%lu", xw.win);
setenv("WINDOWID", buf, 1);
}
void
xseticontitle(char *p)
{
XTextProperty prop;
DEFAULT(p, opt_title);
if (p[0] == '\0')
p = opt_title;
if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
&prop) != Success)
return;
XSetWMIconName(xw.dpy, xw.win, &prop);
XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
XFree(prop.value);
}
void
xsettitle(char *p)
{
XTextProperty prop;
DEFAULT(p, opt_title);
if (p[0] == '\0')
p = opt_title;
if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
&prop) != Success)
return;
XSetWMName(xw.dpy, xw.win, &prop);
XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
XFree(prop.value);
}
int
xstartdraw(void)
{
return IS_SET(MODE_VISIBLE);
}
void
xdrawline(Line line, int x1, int y1, int x2)
{
int i, j, x, ox, numspecs;
Glyph new;
GlyphFontSeq *seq = xw.specseq;
XftGlyphFontSpec *specs = xw.specbuf;
/* Draw line in 2 passes: background and foreground. This way wide glyphs
won't get truncated (#223) */
/* background */
i = j = ox = 0;
for (x = x1; x < x2; x++) {
new = line[x];
if (new.mode == ATTR_WDUMMY)
continue;
if (selected(x, y1))
new.mode ^= ATTR_REVERSE;
if ((i > 0) && ATTRCMP(seq[j].base, new)) {
numspecs = xmakeglyphfontspecs(specs, &line[ox], x - ox, ox, y1);
xdrawglyphfontspecs(specs, seq[j].base, numspecs, ox, y1, DRAW_BG, x - ox);
seq[j].charlen = x - ox;
seq[j++].numspecs = numspecs;
specs += numspecs;
i = 0;
}
if (i == 0) {
ox = x;
seq[j].ox= ox;
seq[j].base = new;
}
i++;
}
if (i > 0) {
numspecs = xmakeglyphfontspecs(specs, &line[ox], x2 - ox, ox, y1);
xdrawglyphfontspecs(specs, seq[j].base, numspecs, ox, y1, DRAW_BG, x2 - ox);
seq[j].charlen = x2 - ox;
seq[j++].numspecs = numspecs;
}
/* foreground */
specs = xw.specbuf;
for (i = 0; i < j; i++) {
xdrawglyphfontspecs(specs, seq[i].base, seq[i].numspecs, seq[i].ox, y1, DRAW_FG, seq[i].charlen);
specs += seq[i].numspecs;
}
}
void
xfinishdraw(void)
{
ImageList *im, *next;
Imlib_Image origin, scaled;
XGCValues gcvalues;
GC gc;
int width, height;
int x, x2, del, destx, desty;
Line line;
for (im = term.images; im; im = next) {
next = im->next;
/* do not draw or process the image, if it is not visible */
if (im->x >= term.col || im->y >= term.row || im->y < 0)
continue;
/* scale the image */
width = MAX(im->width * win.cw / im->cw, 1);
height = MAX(im->height * win.ch / im->ch, 1);
if (!im->pixmap) {
im->pixmap = (void *)XCreatePixmap(xw.dpy, xw.win, width, height,
xw.depth
);
if (!im->pixmap)
continue;
if (win.cw == im->cw && win.ch == im->ch) {
XImage ximage = {
.format = ZPixmap,
.data = (char *)im->pixels,
.width = im->width,
.height = im->height,
.xoffset = 0,
.byte_order = sixelbyteorder,
.bitmap_bit_order = MSBFirst,
.bits_per_pixel = 32,
.bytes_per_line = im->width * 4,
.bitmap_unit = 32,
.bitmap_pad = 32,
.depth = xw.depth
};
XPutImage(xw.dpy, (Drawable)im->pixmap, dc.gc, &ximage, 0, 0, 0, 0, width, height);
if (im->transparent)
im->clipmask = (void *)sixel_create_clipmask((char *)im->pixels, width, height);
} else {
origin = imlib_create_image_using_data(im->width, im->height, (DATA32 *)im->pixels);
if (!origin)
continue;
imlib_context_set_image(origin);
imlib_image_set_has_alpha(1);
imlib_context_set_anti_alias(im->transparent ? 0 : 1); /* anti-aliasing messes up the clip mask */
scaled = imlib_create_cropped_scaled_image(0, 0, im->width, im->height, width, height);
imlib_free_image_and_decache();
if (!scaled)
continue;
imlib_context_set_image(scaled);
imlib_image_set_has_alpha(1);
XImage ximage = {
.format = ZPixmap,
.data = (char *)imlib_image_get_data_for_reading_only(),
.width = width,
.height = height,
.xoffset = 0,
.byte_order = sixelbyteorder,
.bitmap_bit_order = MSBFirst,
.bits_per_pixel = 32,
.bytes_per_line = width * 4,
.bitmap_unit = 32,
.bitmap_pad = 32,
.depth = xw.depth
};
XPutImage(xw.dpy, (Drawable)im->pixmap, dc.gc, &ximage, 0, 0, 0, 0, width, height);
if (im->transparent)
im->clipmask = (void *)sixel_create_clipmask((char *)imlib_image_get_data_for_reading_only(), width, height);
imlib_free_image_and_decache();
}
}
/* clip the image so it does not go over to borders */
x2 = MIN(im->x + im->cols, term.col);
width = MIN(width, (x2 - im->x) * win.cw);
/* delete the image if the text cells behind it have been changed */
line = TLINE(im->y);
for (del = 0, x = im->x; x < x2; x++) {
if ((del = !(line[x].mode & ATTR_SIXEL)))
break;
}
if (del) {
delete_image(im);
continue;
}
/* draw the image */
memset(&gcvalues, 0, sizeof(gcvalues));
gcvalues.graphics_exposures = False;
gc = XCreateGC(xw.dpy, xw.win, GCGraphicsExposures, &gcvalues);
destx = borderpx + im->x * win.cw;
desty = borderpx + im->y * win.ch;
if (im->clipmask) {
XSetClipMask(xw.dpy, gc, (Drawable)im->clipmask);
XSetClipOrigin(xw.dpy, gc, destx, desty);
}
XCopyArea(xw.dpy, (Drawable)im->pixmap, xw.buf, gc, 0, 0, width, height, destx, desty);
XFreeGC(xw.dpy, gc);
}
XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w, win.h, 0, 0);
XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
}
void
xximspot(int x, int y)
{
if (xw.ime.xic == NULL)
return;
xw.ime.spot.x = borderpx + x * win.cw;
xw.ime.spot.y = borderpx + (y + 1) * win.ch;
XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
}
void
expose(XEvent *ev)
{
redraw();
}
void
visibility(XEvent *ev)
{
XVisibilityEvent *e = &ev->xvisibility;
MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
}
void
unmap(XEvent *ev)
{
win.mode &= ~MODE_VISIBLE;
}
void
xsetpointermotion(int set)
{
if (!set && !xw.pointerisvisible)
return;
MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
}
void
xsetmode(int set, unsigned int flags)
{
int mode = win.mode;
MODBIT(win.mode, set, flags);
if ((flags & MODE_MOUSE)
&& xw.pointerisvisible
) {
if (win.mode & MODE_MOUSE)
XUndefineCursor(xw.dpy, xw.win);
else
XDefineCursor(xw.dpy, xw.win, xw.vpointer);
}
if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
redraw();
}
int
xsetcursor(int cursor)
{
if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
return 1;
win.cursor = cursor;
cursorblinks = win.cursor == 0 || win.cursor == 1 ||
win.cursor == 3 || win.cursor == 5 ||
win.cursor == 7;
return 0;
}
void
xseturgency(int add)
{
XWMHints *h = XGetWMHints(xw.dpy, xw.win);
MODBIT(h->flags, add, XUrgencyHint);
XSetWMHints(xw.dpy, xw.win, h);
XFree(h);
}
void
xbell(void)
{
if (!(IS_SET(MODE_FOCUSED)))
xseturgency(1);
if (bellvolume)
XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
}
void
focus(XEvent *ev)
{
XFocusChangeEvent *e = &ev->xfocus;
if (e->mode == NotifyGrab)
return;
if (ev->type == FocusIn) {
if (xw.ime.xic)
XSetICFocus(xw.ime.xic);
win.mode |= MODE_FOCUSED;
xseturgency(0);
if (IS_SET(MODE_FOCUS))
ttywrite("\033[I", 3, 0);
} else {
if (xw.ime.xic)
XUnsetICFocus(xw.ime.xic);
win.mode &= ~MODE_FOCUSED;
if (IS_SET(MODE_FOCUS))
ttywrite("\033[O", 3, 0);
}
}
int
match(uint mask, uint state)
{
return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
}
char*
kmap(KeySym k, uint state)
{
Key *kp;
int i;
/* Check for mapped keys out of X11 function keys. */
for (i = 0; i < LEN(mappedkeys); i++) {
if (mappedkeys[i] == k)
break;
}
if (i == LEN(mappedkeys)) {
if ((k & 0xFFFF) < 0xFD00)
return NULL;
}
for (kp = key; kp < key + LEN(key); kp++) {
if (kp->k != k)
continue;
if (!match(kp->mask, state))
continue;
if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
continue;
if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
continue;
if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
continue;
return kp->s;
}
return NULL;
}
void
kpress(XEvent *ev)
{
XKeyEvent *e = &ev->xkey;
KeySym ksym = NoSymbol;
char buf[64], *customkey;
int len, screen;
Rune c;
Status status;
Shortcut *bp;
if (xw.pointerisvisible && hidecursor) {
XDefineCursor(xw.dpy, xw.win, xw.bpointer);
xsetpointermotion(1);
xw.pointerisvisible = 0;
}
if (IS_SET(MODE_KBDLOCK))
return;
if (xw.ime.xic) {
len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
if (status == XBufferOverflow)
return;
} else {
len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
}
screen = tisaltscr() ? S_ALT : S_PRI;
/* 1. shortcuts */
for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
if (ksym == bp->keysym && match(bp->mod, e->state) &&
(!bp->screen || bp->screen == screen)) {
bp->func(&(bp->arg));
return;
}
}
/* 2. custom keys from config.h */
if ((customkey = kmap(ksym, e->state))) {
ttywrite(customkey, strlen(customkey), 1);
return;
}
/* 3. composed string from input method */
if (len == 0)
return;
if (len == 1 && e->state & Mod1Mask) {
if (IS_SET(MODE_8BIT)) {
if (*buf < 0177) {
c = *buf | 0x80;
len = utf8encode(c, buf);
}
} else {
buf[1] = buf[0];
buf[0] = '\033';
len = 2;
}
}
ttywrite(buf, len, 1);
}
void
cmessage(XEvent *e)
{
/*
* See xembed specs
* http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
*/
if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
win.mode |= MODE_FOCUSED;
xseturgency(0);
} else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
win.mode &= ~MODE_FOCUSED;
}
} else if (e->xclient.data.l[0] == xw.wmdeletewin) {
ttyhangup();
exit(0);
}
}
void
resize(XEvent *e)
{
if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
return;
cresize(e->xconfigure.width, e->xconfigure.height);
}
void
run(void)
{
XEvent ev;
int w = win.w, h = win.h;
fd_set rfd;
int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
struct timespec seltv, *tv, now, lastblink, trigger;
double timeout;
/* Waiting for window mapping */
do {
XNextEvent(xw.dpy, &ev);
/*
* This XFilterEvent call is required because of XOpenIM. It
* does filter out the key event and some client message for
* the input method too.
*/
if (XFilterEvent(&ev, None))
continue;
if (ev.type == ConfigureNotify) {
w = ev.xconfigure.width;
h = ev.xconfigure.height;
}
} while (ev.type != MapNotify);
ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
cresize(w, h);
for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
FD_ZERO(&rfd);
FD_SET(ttyfd, &rfd);
FD_SET(xfd, &rfd);
if (XPending(xw.dpy))
timeout = 0; /* existing events might not set xfd */
seltv.tv_sec = timeout / 1E3;
seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
tv = timeout >= 0 ? &seltv : NULL;
if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
if (errno == EINTR)
continue;
die("select failed: %s\n", strerror(errno));
}
clock_gettime(CLOCK_MONOTONIC, &now);
if (FD_ISSET(ttyfd, &rfd))
ttyread();
xev = 0;
while (XPending(xw.dpy)) {
xev = 1;
XNextEvent(xw.dpy, &ev);
if (XFilterEvent(&ev, None))
continue;
if (handler[ev.type])
(handler[ev.type])(&ev);
}
/*
* To reduce flicker and tearing, when new content or event
* triggers drawing, we first wait a bit to ensure we got
* everything, and if nothing new arrives - we draw.
* We start with trying to wait minlatency ms. If more content
* arrives sooner, we retry with shorter and shorter periods,
* and eventually draw even without idle after maxlatency ms.
* Typically this results in low latency while interacting,
* maximum latency intervals during `cat huge.txt`, and perfect
* sync with periodic updates from animations/key-repeats/etc.
*/
if (FD_ISSET(ttyfd, &rfd) || xev)
{
if (!drawing) {
trigger = now;
if (IS_SET(MODE_BLINK)) {
win.mode ^= MODE_BLINK;
}
lastblink = now;
drawing = 1;
}
timeout = (maxlatency - TIMEDIFF(now, trigger)) \
/ maxlatency * minlatency;
if (timeout > 0)
continue; /* we have time, try to find idle */
}
/* idle detected or maxlatency exhausted -> draw */
timeout = -1;
if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK)))
{
timeout = blinktimeout - TIMEDIFF(now, lastblink);
if (timeout <= 0) {
if (-timeout > blinktimeout) /* start visible */
win.mode |= MODE_BLINK;
win.mode ^= MODE_BLINK;
tsetdirtattr(ATTR_BLINK);
lastblink = now;
timeout = blinktimeout;
}
}
draw();
XFlush(xw.dpy);
drawing = 0;
}
}
void
usage(void)
{
die("usage: %s [-aiv] [-c class]"
" [-f font] [-g geometry]"
" [-n name] [-o file]\n"
" [-T title] [-t title] [-w windowid]"
" [[-e] command [args ...]]\n"
" %s [-aiv] [-c class]"
" [-f font] [-g geometry]"
" [-n name] [-o file]\n"
" [-T title] [-t title] [-w windowid] -l line"
" [stty_args ...]\n", argv0, argv0);
}
int
main(int argc, char *argv[])
{
xw.l = xw.t = 0;
xw.isfixed = False;
xsetcursor(cursorstyle);
ARGBEGIN {
case 'a':
allowaltscreen = 0;
break;
case 'A':
opt_alpha = EARGF(usage());
break;
case 'c':
opt_class = EARGF(usage());
break;
case 'e':
if (argc > 0)
--argc, ++argv;
goto run;
case 'f':
opt_font = EARGF(usage());
break;
case 'g':
xw.gm = XParseGeometry(EARGF(usage()),
&xw.l, &xw.t, &cols, &rows);
break;
case 'i':
xw.isfixed = 1;
break;
case 'o':
opt_io = EARGF(usage());
break;
case 'l':
opt_line = EARGF(usage());
break;
case 'n':
opt_name = EARGF(usage());
break;
case 't':
case 'T':
opt_title = EARGF(usage());
break;
case 'w':
opt_embed = EARGF(usage());
break;
case 'v':
die("%s " VERSION "\n", argv0);
break;
default:
usage();
} ARGEND;
run:
if (argc > 0) /* eat all remaining arguments */
opt_cmd = argv;
if (!opt_title)
opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
setlocale(LC_CTYPE, "");
XSetLocaleModifiers("");
signal(SIGUSR1, sigusr1_reload);
if (!(xw.dpy = XOpenDisplay(NULL)))
die("Can't open display\n");
config_init(xw.dpy);
hbcreatebuffer();
cols = MAX(cols, 1);
rows = MAX(rows, 1);
tnew(cols, rows);
xinit(cols, rows);
xsetenv();
selinit();
run();
hbdestroybuffer();
return 0;
}

View File

@ -31,9 +31,22 @@ dwm.tagsnormbgcolor: #14161B
dwm.tagsselfgcolor: #a6adc8
dwm.tagsselbgcolor: #313244
dwm.titlenormfgcolor: #a6adc8
dwm.titlenormbgcolor: #14161B
dwm.titlenormbordercolor: #444444
dwm.titlenormfloatcolor: #db8fd9
dwm.titleselfgcolor: #eeeeee
dwm.titleselbgcolor: #313244
dwm.titleselbordercolor: #313244
dwm.titleselfloatcolor: #313244
dwm.hidnormfgcolor: #a6adc8
dwm.hidselfgcolor: #a6adc8
dwm.hidnormbgcolor: #222222
dwm.hidselbgcolor: #222222
dmenu.foreground: #a6adc8
dmenu.background: #14161B
dmenu.selforeground: #14161B
dmenu.background: #1e1e2e
dmenu.selforeground: #1e1e2e
dmenu.selbackground: #cba6f7
dmenu.bordercolor: #cba6f7

View File

@ -2,7 +2,7 @@
xrandr --dpi 96 # Set DPI. User may want to use a larger number for larger screens.
setbg & # set the background with the `setbg` script
nvim --headless "+Lazy! load all" +qa &
# nvim --headless "+Lazy! load all" +qa &
xrdb "${XDG_CONFIG_HOME:-$HOME/.config}"/x11/xresources &
xrdbpid=$! # Uncomment to use Xresources colors/settings on startup

View File

@ -7,11 +7,11 @@
Xcursor.theme: Bibata-Modern-Ice
Xcursor.size: 24
st.font: JetBrains Mono Nerd Font:style:Medium:size=10
st.font: JetBrains Mono:size=10
st.borderpx: 10
st.alpha: 1.0
st.tabspaces: 2
st.cwscale: 1.0
st.chscale: 1.0
dmenu.font: JetBrainsMono Nerd Font:style:medium:size=10
dmenu.font: JetBrainsMono Nerd Font:style:Medium:size=10

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2023 - sxyazi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2022 Himanshu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,37 +0,0 @@
<div align="center">
<img src="https://github.com/sxyazi/yazi/blob/main/assets/logo.png?raw=true" alt="Yazi logo" width="20%">
</div>
<h3 align="center">
Tokyo Night Flavor for <a href="https://github.com/sxyazi/yazi">Yazi</a>
</h3>
## 👀 Preview
<img src="preview.png" width="600" />
## 🎨 Installation
```bash
# Linux/macOS
git clone https://github.com/BennyOe/tokyo-night.yazi.git ~/.config/yazi/flavors/tokyo-night.yazi
# Windows
git clone https://github.com/BennyOe/tokyo-night.yazi.git %AppData%\yazi\config\flavors\tokyo-night.yazi
```
## ⚙️ Usage
Add the these lines to your `theme.toml` configuration file to use it:
```toml
[flavor]
use = "tokyo-night"
```
## 📜 License
The flavor is MIT-licensed, and the included tmTheme is also MIT-licensed.
Check the [LICENSE](LICENSE) and [LICENSE-tmtheme](LICENSE-tmtheme) file for more details.

View File

@ -1,167 +0,0 @@
# : Manager {{{
[manager]
cwd = { fg = "#7aa2f7" } # Blue
# Hovered
hovered = { reversed = true }
preview_hovered = { underline = true }
# Find
find_keyword = { fg = "#f7768e", bold = true, italic = true, underline = true } # Red
find_position = { fg = "#bb9af7", bg = "reset", bold = true, italic = true } # Magenta
# Marker
marker_copied = { fg = "#9ece6a", bg = "#9ece6a" } # Green
marker_cut = { fg = "#e0af68", bg = "#f7768e" } # Red
marker_marked = { fg = "#7aa2f7", bg = "#7dcfff" } # Cyan
marker_selected = { fg = "#e0af68", bg = "#e0af68" } # Yellow
# Tab
tab_active = { bg = "#282C34", fg = "#7aa2f7" } # Darkened background, Blue text
tab_inactive = {}
tab_width = 1
# Count
count_copied = { fg = "#414868", bg = "#9ece6a" } # Darkened black on Green
count_cut = { fg = "#414868", bg = "#e0af68" } # Darkened black on Yellow
count_selected = { fg = "#414868", bg = "#7aa2f7" } # Darkened black on Blue
# Border
border_symbol = "│"
border_style = { fg = "#414868" } # Darkened black
# : }}}
# : Status {{{
[status]
separator_open = ""
separator_close = ""
separator_style = { fg = "#7aa2f7", bg = "#414868" } # Blue on Darkened black
# Mode
mode_normal = { fg = "#414868", bg = "#7aa2f7", bold = true } # Darkened black on Blue
mode_select = { fg = "#414868", bg = "#9ece6a", bold = true } # Darkened black on Green
mode_unset = { fg = "#414868", bg = "#bb9af7", bold = true } # Darkened black on Magenta
# Progress
progress_label = { fg = "#a9b1d6", bold = true } # White
progress_normal = { fg = "#7aa2f7", bg = "#414868" } # Blue on Darkened black
progress_error = { fg = "#f7768e", bg = "#414868" } # Red on Darkened black
# Permissions
permissions_t = { fg = "#7aa2f7" } # Blue
permissions_r = { fg = "#f7768e" } # Red
permissions_w = { fg = "#e0af68" } # Yellow
permissions_x = { fg = "#9ece6a" } # Green
permissions_s = { fg = "#bb9af7" } # Magenta
# : }}}
# : Select {{{
[select]
border = { fg = "#7aa2f7" } # Blue
active = { fg = "#bb9af7", bold = true } # Magenta
inactive = {}
# : }}}
# : Input {{{
[input]
border = { fg = "#7aa2f7" } # Blue
title = {}
value = {}
selected = { reversed = true }
# : }}}
# : Completion {{{
[completion]
border = { fg = "#7aa2f7" } # Blue
# : }}}
# : Tasks {{{
[tasks]
border = { fg = "#7aa2f7" } # Blue
title = {}
hovered = { fg = "#bb9af7", underline = true } # Magenta
# : }}}
# : Which {{{
[which]
mask = { bg = "#414868" } # Darkened black
cand = { fg = "#9ece6a" } # Green
rest = { fg = "#a9b1d6" } # White
desc = { fg = "#bb9af7" } # Magenta
separator = "  "
separator_style = { fg = "#626880" } # Darkened gray
# : }}}
# : Help {{{
[help]
on = { fg = "#9ece6a" } # Green
run = { fg = "#bb9af7" } # Magenta
hovered = { reversed = true, bold = true }
footer = { fg = "#a9b1d6", bg = "#c6d0f5" } # White on Light gray
# : }}}
# : Notify {{{
[notify]
title_info = { fg = "#9ece6a" } # Green
title_warn = { fg = "#f7768e" } # Red
title_error = { fg = "#e0af68" } # Yellow
# : }}}
# : File-specific styles {{{
[filetype]
rules = [
# Images
{ mime = "image/*", fg = "#e0af68" }, # Yellow
# Media
{ mime = "video/*", fg = "#f7768e" }, # Red
{ mime = "audio/*", fg = "#f7768e" }, # Red
# Archives
{ mime = "application/zip", fg = "#bb9af7" }, # Magenta
{ mime = "application/x-tar", fg = "#bb9af7" }, # Magenta
{ mime = "application/x-bzip*", fg = "#bb9af7" }, # Magenta
{ mime = "application/x-bzip2", fg = "#bb9af7" }, # Magenta
{ mime = "application/x-7z-compressed", fg = "#bb9af7" }, # Magenta
{ mime = "application/x-rar", fg = "#bb9af7" }, # Magenta
{ mime = "application/x-xz", fg = "#bb9af7" }, # Magenta
# Documents
{ mime = "application/doc", fg = "#9ece6a" }, # Green
{ mime = "application/pdf", fg = "#9ece6a" }, # Green
{ mime = "application/rtf", fg = "#9ece6a" }, # Green
{ mime = "application/vnd.*", fg = "#9ece6a" }, # Green
# Fallback
{ name = "*", fg = "#c6d0f5" }, # Light gray
{ name = "*/", fg = "#7aa2f7" } # Blue
]
# : }}}

View File

@ -1,1329 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>author</key>
<string>Kristi Russell (http://github.com/enkia)</string>
<key>colorSpaceName</key>
<string>sRGB</string>
<key>name</key>
<string>Enki-Tokyo-Night</string>
<key>semanticClass</key>
<string>enki.theme.tokyo</string>
<key>settings</key>
<array>
<dict>
<key>settings</key>
<dict>
<key>activeGuide</key>
<string>#363b54</string>
<key>background</key>
<string>#1d1f29</string>
<key>caret</key>
<string>#DBC08A</string>
<key>findHighlight</key>
<string>#ffa300</string>
<key>findHighlightForeground</key>
<string>#000000</string>
<key>foreground</key>
<string>#AFBAD4ff</string>
<key>guide</key>
<string>#4f4f5e40</string>
<key>gutterForeground</key>
<string>#3b415caa</string>
<key>inactiveSelection</key>
<string>#282833</string>
<key>invisibles</key>
<string>#4f4f5e</string>
<key>lineHighlight</key>
<string>#00000030</string>
<key>phantomCss</key>
<string>&lt;![CDATA[ html { position: relative; } ]]&gt;</string>
<key>popupCss</key>
<string>&lt;![CDATA[ html { color: #B376B3; background-color: #2b2d3a; padding: 10px; } a { color: #6189BB; line-height: 1.2; text-decoration: none; } .error, .deleted { color: #50B4DC; } .success, .inserted { color: #9DBA72; } .warning, .modified { color: #ffa300; } ]]&gt;</string>
<key>selection</key>
<string>#9D599D40</string>
<key>selectionBorder</key>
<string>#9D599D</string>
<key>shadow</key>
<string>#00000010</string>
<key>stackGuide</key>
<string>#4f4f5e60</string>
<key>tagsOptions</key>
<string>underline</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Italics - Comments, Storage, Keyword Flow, Vue attributes, Decorators</string>
<key>scope</key>
<string>comment, meta.var.expr storage.type, keyword.control.flow, meta.directive.vue punctuation.separator.key-value.html, meta.directive.vue entity.other.attribute-name.html, tag.decorator.js entity.name.tag.js, tag.decorator.js punctuation.definition.tag.js, storage.modifier</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>italic</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Comment</string>
<key>scope</key>
<string>comment, comment.block.documentation, punctuation.definition.comment</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#444b6a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Comment Doc</string>
<key>scope</key>
<string>comment.block.documentation variable, comment.block.documentation storage, comment.block.documentation punctuation, comment.block.documentation keyword, comment.block.documentation support, comment.block.documentation markup, comment.block.documentation markup.inline.raw.string.markdown, keyword.other.phpdoc.php</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7982a9</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Number, Boolean, Undefined, Null</string>
<key>scope</key>
<string>variable.other.constant, punctuation.definition.constant, constant.language, constant.numeric, support.constant</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#ff9e64</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>String, Symbols, Markup Heading</string>
<key>scope</key>
<string>string, constant.other.symbol, constant.other.key, markup.heading, meta.attribute-selector</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string></string>
<key>foreground</key>
<string>#9ece6a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Colors</string>
<key>scope</key>
<string>constant.other.color, constant.other.color.rgb-value.hex punctuation.definition.constant</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9aa5ce</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Invalid</string>
<key>scope</key>
<string>invalid, invalid.illegal</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#ff5370</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Invalid deprecated</string>
<key>scope</key>
<string>invalid.deprecated</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Storage Type</string>
<key>scope</key>
<string>storage.type</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Storage - modifier, var, const, let</string>
<key>scope</key>
<string>meta.var.expr storage.type, storage.modifier</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9d7cd8</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Interpolation</string>
<key>scope</key>
<string>punctuation.definition.template-expression, punctuation.section.embedded</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7dcfff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Spread</string>
<key>scope</key>
<string>keyword.operator.spread, keyword.operator.rest</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Operator, Misc</string>
<key>scope</key>
<string>keyword.operator, keyword.control.as, keyword.other, keyword.operator.bitwise.shift, punctuation, punctuation.definition.constant.markdown, punctuation.definition.string, punctuation.support.type.property-name, text.html.vue-html meta.tag, punctuation.definition.keyword, punctuation.terminator.rule, punctuation.definition.entity, punctuation.definition.tag, punctuation.separator.inheritance.php, punctuation.definition.tag.html, keyword.other.template, keyword.other.substitution, entity.name.operator, text.html.vue meta.tag.block.any.html, text.html.vue meta.tag.inline.any.html, text.html.vue meta.tag.other.html, text.html.twig meta.tag.inline.any.html, text.html.twig meta.tag.block.any.html, text.html.twig meta.tag.structure.any.html, text.html.twig meta.tag.any.html</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#89ddff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Import, Export, From, Default</string>
<key>scope</key>
<string>keyword.control.import, keyword.control.export, keyword.control.from, keyword.control.default, meta.import keyword.other</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7dcfff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Keyword</string>
<key>scope</key>
<string>keyword, keyword.control, keyword.other.important</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Keyword SQL</string>
<key>scope</key>
<string>keyword.other.DML</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7dcfff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Keyword Operator Logical, Arrow, Ternary, Comparison</string>
<key>scope</key>
<string>keyword.operator.logical, storage.type.function, keyword.operator.bitwise, keyword.operator.ternary, keyword.operator.comparison, keyword.operator.relational, keyword.operator.or.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Tag</string>
<key>scope</key>
<string>entity.name.tag, entity.name.tag support.class.component, meta.tag</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Tag Punctuation</string>
<key>scope</key>
<string>punctuation.definition.tag, punctuation.definition.tag.html, punctuation.definition.tag.begin.html, punctuation.definition.tag.end.html</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#ba3c97</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Blade</string>
<key>scope</key>
<string>keyword.blade, entity.name.function.blade</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>PHP - Embedded Tag</string>
<key>scope</key>
<string>punctuation.section.embedded.begin.php, punctuation.section.embedded.end.php</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Smarty - Twig tag - Blade</string>
<key>scope</key>
<string>punctuation.definition.variable.smarty, punctuation.section.embedded.begin.smarty, punctuation.section.embedded.end.smarty, meta.tag.template.value.twig, punctuation.section.tag.twig, meta.tag.expression.twig, punctuation.definition.tag.expression.twig, punctuation.definition.tag.output.twig, variable.parameter.smarty</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7DCFFF</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Smarty - Twig variable - function</string>
<key>scope</key>
<string>variable.other.property.twig, support.function.twig, meta.function-call.twig, keyword.control.twig, keyword.control.smarty, keyword.operator.other.twig, keyword.operator.comparison.twig, support.function.functions.twig, support.function.functions.twig, keyword.operator.assignment.twig, support.function.filters.twig, support.function.built-in.smarty, keyword.operator.smarty, text.blade text.html.blade custom.compiler.blade.php punctuation.section.embedded.php entity.name.tag.block.any.html, text.blade text.html.blade custom.compiler.blade.php punctuation.section.embedded.php constant.other.inline-data.html, text.blade text.html.blade custom.compiler.blade.php support.function constant.other.inline-data.html</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Globals - PHP Constants etc</string>
<key>scope</key>
<string>constant.other.php, variable.other.global.safer, variable.other.global.safer punctuation.definition.variable, variable.other.global, variable.other.global punctuation.definition.variable, constant.other</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0af68</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Variables</string>
<key>scope</key>
<string>variable, support.variable, string constant.other.placeholder</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Object Variable</string>
<key>scope</key>
<string>variable.other.object, support.module.node</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Object Key</string>
<key>scope</key>
<string>meta.object-literal.key, meta.group.braces.curly constant.other.object.key.js string.unquoted.label.js, string.alias.graphql, string.unquoted.graphql, string.unquoted.alias.graphql, meta.field.declaration.ts variable.object.property</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#73daca</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Object Property</string>
<key>scope</key>
<string>variable.other.property, support.variable.property, support.variable.property.dom, meta.function-call variable.other.object.property, variable.language.prototype, meta.property.object, variable.other.member</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7dcfff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Object Property</string>
<key>scope</key>
<string>variable.other.object.property</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Object Literal Member lvl 3 (Vue Prop Validation)</string>
<key>scope</key>
<string>meta.objectliteral meta.object.member meta.objectliteral meta.object.member meta.objectliteral meta.object.member meta.object-literal.key</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#41a6b5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>C-related Block Level Variables</string>
<key>scope</key>
<string>source.cpp meta.block variable.other</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Other Variable</string>
<key>scope</key>
<string>support.other.variable</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Methods</string>
<key>scope</key>
<string>meta.class-method.js entity.name.function.js, entity.name.method.js, variable.function.constructor, keyword.other.special-method, storage.type.cs</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Function Definition</string>
<key>scope</key>
<string>entity.name.function, meta.function-call, meta.function-call entity.name.function, variable.function, meta.definition.method entity.name.function, meta.object-literal entity.name.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Function Argument</string>
<key>scope</key>
<string>variable.parameter.function.language.special, variable.parameter, meta.function.parameters punctuation.definition.variable, meta.function.parameter variable</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0af68</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Constant, Tag Attribute</string>
<key>scope</key>
<string>keyword.other.type.php, storage.type.php, constant.character, constant.escape, keyword.other.unit</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Variable Definition</string>
<key>scope</key>
<string>meta.definition.variable variable.other.constant, meta.definition.variable variable.other.readwrite, variable.other.declaration</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Inherited Class</string>
<key>scope</key>
<string>entity.other.inherited-class</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string></string>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Class, Support, DOM, etc</string>
<key>scope</key>
<string>support.class, support.type, variable.other.readwrite.alias, support.orther.namespace.use.php, meta.use.php, support.other.namespace.php, support.type.sys-types, support.variable.dom, support.constant.math, support.type.object.module, support.constant.json, entity.name.namespace, meta.import.qualifier, entity.name.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Class Name</string>
<key>scope</key>
<string>entity.name</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Support Function</string>
<key>scope</key>
<string>support.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Class and Support</string>
<key>scope</key>
<string>source.css support.type.property-name, source.sass support.type.property-name, source.scss support.type.property-name, source.less support.type.property-name, source.stylus support.type.property-name, source.postcss support.type.property-name, support.type.property-name.css, support.type.vendored.property-name, support.type.map.key</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Font</string>
<key>scope</key>
<string>support.constant.font-name, meta.definition.variable</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ece6a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Class</string>
<key>scope</key>
<string>entity.other.attribute-name.class, meta.at-rule.mixin.scss entity.name.function.scss</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ece6a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS ID</string>
<key>scope</key>
<string>entity.other.attribute-name.id</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#fc7b7b</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Tag</string>
<key>scope</key>
<string>entity.name.tag.css, entity.name.tag.reference, entity.name.tag.scss</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Tag Reference</string>
<key>scope</key>
<string>entity.name.tag.reference</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0af68</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Property Separator</string>
<key>scope</key>
<string>meta.property-list punctuation.separator.key-value</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9abdf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Punctuation</string>
<key>scope</key>
<string>meta.property-list, punctuation.definition.entity.css</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0af68</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>SCSS @</string>
<key>scope</key>
<string>meta.at-rule.mixin keyword.control.at-rule.mixin, meta.at-rule.include entity.name.function.scss, meta.at-rule.include keyword.control.at-rule.include</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>SCSS Mixins, Extends, Include Keyword</string>
<key>scope</key>
<string>keyword.control.at-rule.include punctuation.definition.keyword, keyword.control.at-rule.mixin punctuation.definition.keyword, meta.at-rule.include keyword.control.at-rule.include, keyword.control.at-rule.extend punctuation.definition.keyword, meta.at-rule.extend keyword.control.at-rule.extend, entity.other.attribute-name.placeholder.css punctuation.definition.entity.css, meta.at-rule.media keyword.control.at-rule.media, meta.at-rule.mixin keyword.control.at-rule.mixin, meta.at-rule.function keyword.control.at-rule.function, keyword.control punctuation.definition.keyword, meta.at-rule.import.scss entity.other.attribute-name.placeholder.scss punctuation.definition.entity.scss, meta.at-rule.import.scss keyword.control.at-rule.import.scss</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9d7cd8</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>SCSS Include Mixin Argument</string>
<key>scope</key>
<string>meta.property-list meta.at-rule.include</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS value</string>
<key>scope</key>
<string>support.constant.property-value</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#ff9e64</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Sub-methods</string>
<key>scope</key>
<string>entity.name.module.js, variable.import.parameter.js, variable.other.class.js</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Language methods</string>
<key>scope</key>
<string>variable.language</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Variable punctuation</string>
<key>scope</key>
<string>variable.other punctuation.definition.variable</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Keyword this with Punctuation, ES7 Bind Operator</string>
<key>scope</key>
<string>source.js constant.other.object.key.js string.unquoted.label.js, variable.language.this punctuation.definition.variable, keyword.other.this</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>HTML Attributes</string>
<key>scope</key>
<string>entity.other.attribute-name, text.html.basic entity.other.attribute-name.html, text.html.basic entity.other.attribute-name, text.blade entity.other.attribute-name.class, text.html.smarty entity.other.attribute-name.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Vue Template attributes</string>
<key>scope</key>
<string>meta.directive.vue punctuation.separator.key-value.html, meta.directive.vue entity.other.attribute-name.html</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Vue Template attribute separator</string>
<key>scope</key>
<string>meta.directive.vue punctuation.separator.key-value.html</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#89ddff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS IDs</string>
<key>scope</key>
<string>source.sass keyword.control</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS psuedo selectors</string>
<key>scope</key>
<string>entity.other.attribute-name.pseudo-class, entity.other.attribute-name.pseudo-element, entity.other.attribute-name.placeholder, meta.property-list meta.property-value</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Inserted</string>
<key>scope</key>
<string>markup.inserted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#449dab</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Deleted</string>
<key>scope</key>
<string>markup.deleted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#914c54</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Changed</string>
<key>scope</key>
<string>markup.changed</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#6183bb</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions</string>
<key>scope</key>
<string>string.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#b4f9f8</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions - Punctuation</string>
<key>scope</key>
<string>punctuation.definition.group</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions - Character Class</string>
<key>scope</key>
<string>constant.other.character-class.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions - Character Class Set</string>
<key>scope</key>
<string>constant.other.character-class.set.regexp, punctuation.definition.character-class.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0af68</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions - Quantifier</string>
<key>scope</key>
<string>keyword.operator.quantifier.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#89ddff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions - Backslash</string>
<key>scope</key>
<string>constant.character.escape.backslash</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Escape Characters</string>
<key>scope</key>
<string>constant.character.escape</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#89ddff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Decorators</string>
<key>scope</key>
<string>tag.decorator.js entity.name.tag.js, tag.decorator.js punctuation.definition.tag.js</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>CSS Units</string>
<key>scope</key>
<string>keyword.other.unit</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 0</string>
<key>scope</key>
<string>source.json meta.mapping.key.json string.quoted.double.json, source.json meta.structure.dictionary.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 1</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.sequence.json meta.mapping.key.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 2</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.mapping.key.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7dcfff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 3</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.key.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 4</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.key.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0af68</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 5</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.key.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 6</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.key.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#73daca</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 7</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.key.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - Level 8</string>
<key>scope</key>
<string>source.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.value.json meta.sequence.json meta.mapping.key.json string.quoted.double.json punctuation.definition.string.end.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ece6a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>JSON Key - value</string>
<key>scope</key>
<string>source.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json, source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.array.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ece6a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Plain Punctuation</string>
<key>scope</key>
<string>punctuation.definition.list_item.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9abdf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Block Punctuation</string>
<key>scope</key>
<string>meta.block, meta.brace, punctuation.definition.block, punctuation.definition.use, punctuation.definition.group.shell, punctuation.definition.class, punctuation.definition.begin.bracket, punctuation.definition.end.bracket, punctuation.definition.parameters, punctuation.definition.arguments, punctuation.definition.dictionary, punctuation.definition.array, punctuation.section</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9abdf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Plain</string>
<key>scope</key>
<string>meta.jsx.children, meta.embedded.block</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>HTML text</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9aa5ce</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Markup Raw Inline</string>
<key>scope</key>
<string>text.html.markdown markup.inline.raw.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#bb9af7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Markup Raw Inline Punctuation</string>
<key>scope</key>
<string>text.html.markdown markup.inline.raw.markdown punctuation.definition.raw.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#4E5579</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Heading 1</string>
<key>scope</key>
<string>heading.1.markdown entity.name, heading.1.markdown punctuation.definition.heading.markdown</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#89ddff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Heading 2</string>
<key>scope</key>
<string>heading.2.markdown entity.name, heading.2.markdown punctuation.definition.heading.markdown</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#61bdf2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Heading 3</string>
<key>scope</key>
<string>heading.3.markdown entity.name, heading.3.markdown punctuation.definition.heading.markdown</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Heading 4</string>
<key>scope</key>
<string>heading.4.markdown entity.name, heading.4.markdown punctuation.definition.heading.markdown</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#6d91de</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Heading 5</string>
<key>scope</key>
<string>heading.5.markdown entity.name, heading.5.markdown punctuation.definition.heading.markdown</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#9aa5ce</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Heading 6</string>
<key>scope</key>
<string>heading.6.markdown entity.name, heading.6.markdown punctuation.definition.heading.markdown</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#747ca1</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markup - Italic</string>
<key>scope</key>
<string>markup.italic, markup.italic punctuation</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>italic</string>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markup - Bold</string>
<key>scope</key>
<string>markup.bold, markup.bold punctuation</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markup - Bold-Italic</string>
<key>scope</key>
<string>markup.bold markup.italic, markup.bold markup.italic punctuation</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold italic</string>
<key>foreground</key>
<string>#c0caf5</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markup - Underline</string>
<key>scope</key>
<string>markup.underline, markup.underline punctuation</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>underline</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Blockquote</string>
<key>scope</key>
<string>markup.quote punctuation.definition.blockquote.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#4e5579</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markup - Quote</string>
<key>scope</key>
<string>markup.quote</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>italic</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Link</string>
<key>scope</key>
<string>string.other.link, markup.underline.link, constant.other.reference.link.markdown, string.other.link.description.title.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#73daca</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Fenced Code Block</string>
<key>scope</key>
<string>markup.fenced_code.block.markdown, markup.inline.raw.string.markdown, variable.language.fenced.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#89ddff</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markdown - Separator</string>
<key>scope</key>
<string>meta.separator</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#444b6a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Markup - Table</string>
<key>scope</key>
<string>markup.table</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c0cefc</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Token - Info</string>
<key>scope</key>
<string>token.info-token</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#0db9d7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Token - Warn</string>
<key>scope</key>
<string>token.warn-token</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#ffdb69</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Token - Error</string>
<key>scope</key>
<string>token.error-token</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#db4b4b</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Token - Debug</string>
<key>scope</key>
<string>token.debug-token</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#b267e6</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Apache Tag</string>
<key>scope</key>
<string>entity.tag.apacheconf</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f7768e</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Preprocessor</string>
<key>scope</key>
<string>meta.preprocessor</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#73daca</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>ENV value</string>
<key>scope</key>
<string>source.env</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#7aa2f7</string>
</dict>
</dict>
</array>
<key>uuid</key>
<string>06f855e3-9fb7-4fb1-b790-aef06065f34e</string>
</dict>
</plist>

View File

@ -1 +1,28 @@
require("starship"):setup()
-- Show symlink path in status bar
function Status:name()
local h = cx.active.current.hovered
if not h then
return ui.Span("")
end
local linked = ""
if h.link_to ~= nil then
linked = " -> " .. tostring(h.link_to)
end
return ui.Span(" " .. h.name .. linked)
end
-- Remove file size from status bar
function Status:render(area)
self.area = area
local left = ui.Line { self:mode(), self:name() }
local right = ui.Line { self:permissions(), self:position() }
return {
ui.Paragraph(area, { left }),
ui.Paragraph(area, { right }):align(ui.Paragraph.RIGHT),
table.unpack(Progress:render(area, right:width())),
}
end

View File

@ -1,2 +1,400 @@
[flavor]
use = "tokyo-night"
# A TOML linter such as https://taplo.tamasfe.dev/ can use this schema to validate your config.
# If you encounter any issues, please make an issue at https://github.com/yazi-rs/schemas.
"$schema" = "https://yazi-rs.github.io/schemas/theme.json"
# vim:fileencoding=utf-8:foldmethod=marker
# : Manager {{{
[manager]
cwd = { fg = "white", bold = true }
# Hovered
hovered = { reversed = true }
preview_hovered = { underline = true }
# Find
find_keyword = { fg = "yellow", italic = true }
find_position = { fg = "magenta", bg = "reset", italic = true }
# Marker
marker_selected = { fg = "lightgreen", bg = "lightgreen" }
marker_copied = { fg = "lightyellow", bg = "lightyellow" }
marker_cut = { fg = "lightred", bg = "lightred" }
# Tab
tab_active = { fg = "black", bg = "lightblue" }
tab_inactive = { fg = "white", bg = "darkgray" }
tab_width = 1
# Border
border_symbol = "│"
border_style = { fg = "#14161B" }
# Highlighting
syntect_theme = ""
# : }}}
# : Status {{{
[status]
separator_open = ""
separator_close = ""
separator_style = { fg = "darkgray", bg = "darkgray" }
# Mode
mode_normal = { bg = "reset", fg = "lightblue", bold = false }
mode_select = { bg = "reset", fg = "lightgreen", bold = false }
mode_unset = { bg = "reset", fg = "lightmagenta", bold = false }
# Progress
progress_label = { bold = true }
progress_normal = { fg = "blue", bg = "reset" }
progress_error = { fg = "red", bg = "reset" }
# Permissions
permissions_t = { fg = "lightgreen" }
permissions_r = { fg = "lightyellow" }
permissions_w = { fg = "lightred" }
permissions_x = { fg = "lightcyan" }
permissions_s = { fg = "darkgray" }
# : }}}
# : Select {{{
[select]
border = { fg = "blue" }
active = { fg = "magenta" }
inactive = {}
# : }}}
# : Input {{{
[input]
border = { fg = "blue" }
title = {}
value = {}
selected = { reversed = true }
# : }}}
# : Completion {{{
[completion]
border = { fg = "blue" }
active = { bg = "darkgray" }
inactive = {}
# Icons
icon_file = ""
icon_folder = ""
icon_command = ""
# : }}}
# : Tasks {{{
[tasks]
border = { fg = "blue" }
title = {}
hovered = { underline = true }
# : }}}
# : Which {{{
[which]
cols = 3
mask = { bg = "black" }
cand = { fg = "lightcyan" }
rest = { fg = "darkgray" }
desc = { fg = "magenta" }
separator = "  "
separator_style = { fg = "darkgray" }
# : }}}
# : Help {{{
[help]
on = { fg = "magenta" }
exec = { fg = "cyan" }
desc = { fg = "gray" }
hovered = { bg = "darkgray", bold = true }
footer = { fg = "black", bg = "white" }
# : }}}
# : File-specific styles {{{
[filetype]
rules = [
# Images
{ mime = "image/*", fg = "magenta" },
# Videos
{ mime = "video/*", fg = "green" },
{ mime = "audio/*", fg = "green" },
# Archives
{ mime = "application/zip", fg = "red" },
{ mime = "application/gzip", fg = "red" },
{ mime = "application/x-tar", fg = "red" },
{ mime = "application/x-bzip", fg = "red" },
{ mime = "application/x-bzip2", fg = "red" },
{ mime = "application/x-7z-compressed", fg = "red" },
{ mime = "application/x-rar", fg = "red" },
{ mime = "application/xz", fg = "red" },
# Documents
# { mime = "application/doc", fg = "green" },
{ mime = "application/pdf", fg = "magenta" },
# { mime = "application/rtf", fg = "green" },
# { mime = "application/vnd.*", fg = "green" },
# Fallback
# { name = "*", fg = "white" },
{ name = "*", fg = "cyan", bold = true, is = "link" },
{ name = "*", fg = "green", bold = true, is = "exec" },
{ name = "*/", fg = "cyan", bold = true, is = "link" },
{ name = "*/", fg = "blue", bold = true }
]
[icon]
rules = [
# Programming
{ name = "*.cpp" , text = "", fg = "#519aba" },
{ name = "*.css" , text = "", fg = "#42a5f5" },
{ name = "*.c" , text = "", fg = "#599eff" },
{ name = "*.fish" , text = "" },
{ name = "*.go" , text = "", fg = "#519aba" },
{ name = "*.hpp" , text = "", fg = "#a074c4" },
{ name = "*.h" , text = "", fg = "#a074c4" },
{ name = "*.htm" , text = "", fg = "#e44d26" },
{ name = "*.html" , text = "", fg = "#e44d26" },
{ name = "*.java" , text = "", fg = "#cc3e44" },
{ name = "*.js" , text = "", fg = "#F1F134" },
{ name = "*.jsx" , text = "", fg = "#20c2e3" },
{ name = "*.lua" , text = "", fg = "#51a0cf" },
{ name = "*.nix" , text = "", fg = "#7ab1db" },
{ name = "*.php" , text = "" },
{ name = "*.rb" , text = "" },
{ name = "*.rs" , text = "", fg = "#dea584" },
{ name = "*.scss" , text = "" },
{ name = "*.sh" , text = "", fg = "#4d5a5e" },
{ name = "*.swift", text = "" },
{ name = "*.ts" , text = "", fg = "#519aba" },
{ name = "*.tsx" , text = "" },
{ name = "*.vim" , text = "" },
{ name = "*.vue" , text = "󰡄" },
{ name = "*.py" , text = "", fg = "#ffbc03" },
{ name = "*.pyc" , text = "", fg = "#ffe291" },
# Text
{ name = "*.txt" , text = "", fg = "#bbbbbb" },
{ name = "*.csv" , text = "", fg = "#89e051" },
{ name = "*.json" , text = "", fg = "#cbcb41" },
{ name = "*.conf" , text = "", fg = "#6d8086" }, # Configuration
{ name = "*.ini" , text = "", fg = "#6d8086" },
{ name = "*.yaml" , text = "", fg = "#6d8086" },
{ name = "*.yml" , text = "", fg = "#6d8086" },
{ name = "*.toml" , text = "", fg = "#6d8086" },
{ name = "*.org" , text = "", fg = "#77aa99" },
{ name = "*.tex" , text = "󰙩", fg = "#3d6117" }, # Plaintext typesetting
{ name = "*.typ" , text = "󰙩", fg = "#0e606a" },
{ name = "*.markdown", text = "", fg = "#519aba" }, # Markdown
{ name = "*.md" , text = "", fg = "#519aba" },
{ name = "*.mdx" , text = "", fg = "#519aba" },
{ name = "*.rmd" , text = "", fg = "#519aba" },
# Archives
{ name = "*.7z" , text = "" },
{ name = "*.ace" , text = "" },
{ name = "*.alz" , text = "" },
{ name = "*.arc" , text = "" },
{ name = "*.arj" , text = "" },
{ name = "*.bz2" , text = "" },
{ name = "*.bz" , text = "" },
{ name = "*.cab" , text = "" },
{ name = "*.cpio", text = "" },
{ name = "*.deb" , text = "" },
{ name = "*.dwm" , text = "" },
{ name = "*.dz" , text = "" },
{ name = "*.ear" , text = "" },
{ name = "*.esd" , text = "" },
{ name = "*.gz" , text = "" },
{ name = "*.jar" , text = "" },
{ name = "*.lha" , text = "" },
{ name = "*.lrz" , text = "" },
{ name = "*.lz4" , text = "" },
{ name = "*.lzh" , text = "" },
{ name = "*.lzma", text = "" },
{ name = "*.lzo" , text = "" },
{ name = "*.lz" , text = "" },
{ name = "*.rar" , text = "" },
{ name = "*.rpm" , text = "" },
{ name = "*.rz" , text = "" },
{ name = "*.sar" , text = "" },
{ name = "*.swm" , text = "" },
{ name = "*.t7z" , text = "" },
{ name = "*.tar" , text = "" },
{ name = "*.taz" , text = "" },
{ name = "*.tbz2", text = "" },
{ name = "*.tbz" , text = "" },
{ name = "*.tgz" , text = "" },
{ name = "*.tlz" , text = "" },
{ name = "*.txz" , text = "" },
{ name = "*.tzo" , text = "" },
{ name = "*.tzst", text = "" },
{ name = "*.tz" , text = "" },
{ name = "*.war" , text = "" },
{ name = "*.wim" , text = "" },
{ name = "*.xz" , text = "" },
{ name = "*.zip" , text = "" },
{ name = "*.zoo" , text = "" },
{ name = "*.zst" , text = "" },
{ name = "*.z" , text = "" },
# Images
{ name = "*.bmp" , text = "" }, # Lossless
{ name = "*.gif" , text = "" },
{ name = "*.png" , text = "" },
{ name = "*.tiff" , text = "" },
{ name = "*.webp" , text = "" },
{ name = "*.jpeg" , text = "" }, # Lossy
{ name = "*.jpg" , text = "" },
{ name = "*.mjpeg", text = "" },
{ name = "*.mjpg" , text = "" },
{ name = "*.mng" , text = "" },
{ name = "*.pbm" , text = "" },
{ name = "*.pcx" , text = "" },
{ name = "*.pgm" , text = "" },
{ name = "*.ppm" , text = "" },
{ name = "*.svg" , text = "" },
{ name = "*.svgz" , text = "" },
{ name = "*.tga" , text = "" },
{ name = "*.tif" , text = "" },
{ name = "*.xbm" , text = "" },
{ name = "*.xpm" , text = "" },
# Movies
{ name = "*.asf" , text = "" },
{ name = "*.avi" , text = "" },
{ name = "*.cgm" , text = "" },
{ name = "*.dl" , text = "" },
{ name = "*.emf" , text = "" },
{ name = "*.flc" , text = "" },
{ name = "*.fli" , text = "" },
{ name = "*.flv" , text = "" },
{ name = "*.gl" , text = "" },
{ name = "*.m2v" , text = "" },
{ name = "*.m4v" , text = "" },
{ name = "*.mkv" , text = "" },
{ name = "*.mov" , text = "" },
{ name = "*.mp4" , text = "" },
{ name = "*.mp4v", text = "" },
{ name = "*.mpeg", text = "" },
{ name = "*.mpg" , text = "" },
{ name = "*.nuv" , text = "" },
{ name = "*.ogm" , text = "" },
{ name = "*.ogv" , text = "" },
{ name = "*.ogx" , text = "" },
{ name = "*.qt" , text = "" },
{ name = "*.rm" , text = "" },
{ name = "*.rmvb", text = "" },
{ name = "*.vob" , text = "" },
{ name = "*.webm", text = "" },
{ name = "*.wmv" , text = "" },
{ name = "*.xcf" , text = "" },
{ name = "*.xwd" , text = "" },
{ name = "*.yuv" , text = "" },
# Audio
{ name = "*.aac" , text = "" },
{ name = "*.au" , text = "" },
{ name = "*.flac", text = "" },
{ name = "*.m4a" , text = "" },
{ name = "*.mid" , text = "" },
{ name = "*.midi", text = "" },
{ name = "*.mka" , text = "" },
{ name = "*.mp3" , text = "" },
{ name = "*.mpc" , text = "" },
{ name = "*.oga" , text = "" },
{ name = "*.ogg" , text = "" },
{ name = "*.opus", text = "" },
{ name = "*.ra" , text = "" },
{ name = "*.spx" , text = "" },
{ name = "*.wav" , text = "" },
{ name = "*.xspf", text = "" },
# Documents
{ name = "*.pdf" , text = "", fg = "#b30b00" }, # Printable
{ name = "*.doc" , text = "", fg = "#185abd" }, # Non plaintext docs
{ name = "*.doct", text = "", fg = "#185abd" },
{ name = "*.docx", text = "", fg = "#185abd" },
{ name = "*.dot" , text = "", fg = "#185abd" },
{ name = "*.pom" , text = "󰈩", fg = "#cb4a32" }, # Presentations
{ name = "*.pot" , text = "󰈩", fg = "#cb4a32" },
{ name = "*.potx", text = "󰈩", fg = "#cb4a32" },
{ name = "*.ppm" , text = "󰈩", fg = "#cb4a32" },
{ name = "*.ppmx", text = "󰈩", fg = "#cb4a32" },
{ name = "*.pps" , text = "󰈩", fg = "#cb4a32" },
{ name = "*.ppsx", text = "󰈩", fg = "#cb4a32" },
{ name = "*.ppt" , text = "󰈩", fg = "#cb4a32" },
{ name = "*.pptx", text = "󰈩", fg = "#cb4a32" },
{ name = "*.xlc" , text = "" },
{ name = "*.xlm" , text = "" },
{ name = "*.xls" , text = "" },
{ name = "*.xlsm", text = "" },
{ name = "*.xlsx", text = "" },
{ name = "*.xlt" , text = "" },
{ name = "*.ods" , text = "" },
{ name = "*.ots" , text = "" },
{ name = "*.odg" , text = "󰽉" },
# Lockfiles
{ name = "*.lock", text = "", fg = "#bbbbbb" },
# Misc
{ name = "*.bin", text = "" },
{ name = "*.exe", text = "" },
{ name = "*.pkg", text = "" },
# Dotfiles
{ name = ".DS_Store" , text = "" },
{ name = ".bashprofile" , text = "" },
{ name = ".bashrc" , text = "" },
{ name = ".gitattributes", text = "" },
{ name = ".gitignore" , text = "" },
{ name = ".gitmodules" , text = "" },
{ name = ".vimrc" , text = "" },
{ name = ".zprofile" , text = "" },
{ name = ".zshenv" , text = "" },
{ name = ".zshrc" , text = "" },
# Named files
{ name = "COPYING" , text = "󰿃" },
{ name = "Containerfile", text = "󰡨", fg = "#458ee6" },
{ name = "Dockerfile" , text = "󰡨", fg = "#458ee6" },
{ name = "LICENSE" , text = "", fg = "#d0bf41" },
# Default
{ name = "*", text = "", is = "exec" },
{ name = "*" , text = "" },
{ name = "*/", text = "󰝰", fg = "yellow" },
]
# : }}}

View File

@ -1,5 +1,6 @@
# vim: filetype=zathurarc
set database sqlite
set notification-error-bg "#f7768e"
set notification-error-fg "#a0a8cd"
set notification-warning-bg "#e0af68"

View File

@ -195,7 +195,11 @@
# Red prompt symbol if the last command failed.
typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=1
# Default prompt symbol.
typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION=' '
# typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION=' '
typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION=' '
# typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION=' '
# typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION=' '
# typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION=' '
# Prompt symbol in command vi mode.
typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION=' '
# Prompt symbol in visual vi mode.

View File

@ -3,7 +3,7 @@
# Populated by fuz-cache script through xprofile at startup
CACHE_DIR="/tmp/fuz_cache"
h_padding=$(printf '%*s' 20 ' ')
h_padding=$(printf '%*s' 14 ' ')
h_gap=$(printf '%*s' 4 ' ')
# Define the header using the escape sequences
@ -12,7 +12,8 @@ HEADER="${h_padding}\
 1:All/Folders/Git${h_gap}\
 2:Documents${h_gap}\
 3:Images${h_gap}\
 4:Videos"
 4:Videos${h_gap}\
 f:lf"
OPENER="fuz-opener"
PREVIEWER="fuz-preview"
@ -29,4 +30,5 @@ cat $CACHE_DIR/all | fzf --ansi --prompt " All  " \
--height=100% --pointer=" " --ellipsis= --header-first --scheme=path --algo=v2 --color="16" \
--preview-window "bottom,60%,border-top" --border=none --margin=5%,10%,5%,10% --info=inline-right \
--preview "$PREVIEWER {}" \
--bind "enter:execute:$OPENER {}"
--bind "enter:execute:$OPENER {}" \
--bind "alt-f:execute:lf {}"

View File

@ -27,6 +27,8 @@ populate_cache &
MONITOR_EXCLUDE_DIRS=(
"$HOME/.cache"
"$HOME/.mozilla"
"$HOME/.pki"
"$HOME/.terminfo"
"$HOME/.local/state"
)

View File

@ -35,7 +35,7 @@ for battery in /sys/class/power_supply/BAT?*; do
"Full") status=" " ;;
"Discharging") status=" " ;;
"Charging") status="󱐋 " ;;
"Not charging") status="󱐋 " ;;
"Not charging") status=" 󱈸 " ;;
"Unknown") status=" " ;;
*) exit 1 ;;
esac
@ -44,7 +44,7 @@ for battery in /sys/class/power_supply/BAT?*; do
"Full") status="^C2^ ^d^" ;;
"Discharging") status="^C5^ ^d^" ;;
"Charging") status="^C3^󱐋 ^d^" ;;
"Not charging") status="^C1^󱐋 ^d^" ;;
"Not charging") status="^C1^ 󱈸 ^d^" ;;
"Unknown") status="^C6^ ^d^" ;;
*) exit 1 ;;
esac