diff --git a/dwm/picom/.builds/freebsd.yml b/dwm/picom/.builds/freebsd.yml
new file mode 100644
index 0000000..41c3d92
--- /dev/null
+++ b/dwm/picom/.builds/freebsd.yml
@@ -0,0 +1,28 @@
+image: freebsd/latest
+packages:
+ - libev
+ - libXext
+ - libxcb
+ - meson
+ - pkgconf
+ - cmake
+ - xcb-util-renderutil
+ - xcb-util-image
+ - pixman
+ - uthash
+ - libconfig
+ - libglvnd
+ - dbus
+ - pcre
+sources:
+ - https://github.com/yshui/picom
+tasks:
+ - setup: |
+ cd picom
+ CPPFLAGS="-I/usr/local/include" meson -Dunittest=true build
+ - build: |
+ cd picom
+ ninja -C build
+ - unittest: |
+ cd picom
+ ninja -C build test
diff --git a/dwm/picom/.circleci/config.yml b/dwm/picom/.circleci/config.yml
new file mode 100644
index 0000000..6c348fa
--- /dev/null
+++ b/dwm/picom/.circleci/config.yml
@@ -0,0 +1,135 @@
+executors:
+ e:
+ docker:
+ - image: yshui/comptonci
+ working_directory: "/tmp/workspace"
+ environment:
+ UBSAN_OPTIONS: "halt_on_error=1"
+
+version: 2.1
+commands:
+ build:
+ parameters:
+ build-config:
+ type: string
+ default: ""
+ cc:
+ type: string
+ default: cc
+ steps:
+ - restore_cache:
+ keys:
+ - source-v1-{{ .Branch }}-{{ .Revision }}
+ - source-v1-{{ .Branch }}-
+ - source-v1-
+ - checkout
+ - save_cache:
+ key: source-v1-{{ .Branch }}-{{ .Revision }}
+ paths:
+ - ".git"
+ - run:
+ name: config
+ command: CC=<< parameters.cc >> meson << parameters.build-config >> -Dunittest=true --werror . build
+ - run:
+ name: build
+ command: ninja -vC build
+
+jobs:
+ basic:
+ executor: e
+ steps:
+ - build:
+ build-config: -Dwith_docs=true -Db_coverage=true
+ - persist_to_workspace:
+ root: .
+ paths:
+ - .
+ test:
+ executor: e
+ steps:
+ - attach_workspace:
+ at: /tmp/workspace
+ - run:
+ name: unit test
+ command: ninja -vC build test
+ - run:
+ name: test config file parsing
+ command: xvfb-run -s "-screen 0 640x480x24" build/src/picom --config picom.sample.conf --no-vsync --diagnostics
+ - run:
+ name: run testsuite
+ command: tests/run_tests.sh build/src/picom
+ - run:
+ name: generate coverage reports
+ command: cd build; find -name '*.gcno' -exec gcov -pb {} +
+ - run:
+ name: download codecov scripts
+ command: curl -s https://codecov.io/bash > codecov.sh
+ - run:
+ name: upload coverage reports
+ command: bash ./codecov.sh -X gcov
+
+ minimal:
+ executor: e
+ steps:
+ - build:
+ build-config: -Dopengl=false -Ddbus=false -Dregex=false -Dconfig_file=false
+ release:
+ executor: e
+ steps:
+ - build:
+ build-config: --buildtype=release
+ release-clang:
+ executor: e
+ steps:
+ - build:
+ cc: clang
+ build-config: --buildtype=release
+ nogl:
+ executor: e
+ steps:
+ - build:
+ build-config: -Dopengl=false
+ noregex:
+ executor: e
+ steps:
+ - build:
+ build-config: -Dregex=false
+ clang_basic:
+ executor: e
+ steps:
+ - build:
+ cc: clang
+ clang_minimal:
+ executor: e
+ steps:
+ - build:
+ cc: clang
+ build-config: -Dopengl=false -Ddbus=false -Dregex=false -Dconfig_file=false
+ clang_nogl:
+ executor: e
+ steps:
+ - build:
+ cc: clang
+ build-config: -Dopengl=false
+ clang_noregex:
+ executor: e
+ steps:
+ - build:
+ cc: clang
+ build-config: -Dregex=false
+
+workflows:
+ all_builds:
+ jobs:
+ - basic
+ - clang_basic
+ - minimal
+ - clang_minimal
+ - nogl
+ - clang_nogl
+ - release
+ - release-clang
+ - test:
+ requires:
+ - basic
+# vim: set sw=2 ts=8 et:
diff --git a/dwm/picom/.clang-format b/dwm/picom/.clang-format
new file mode 100644
index 0000000..82c938a
--- /dev/null
+++ b/dwm/picom/.clang-format
@@ -0,0 +1,38 @@
+BasedOnStyle: LLVM
+TabWidth: 8
+UseTab: ForIndentation
+BreakBeforeBraces: Attach
+#BreakStringLiterals: true
+IndentWidth: 8
+AlignAfterOpenBracket: Align
+ColumnLimit: 90
+#ExperimentalAutoDetectBinPacking: true
+BinPackArguments: true
+BinPackParameters: true
+#ReflowComments: true
+AlignTrailingComments: true
+SpacesBeforeTrailingComments: 8
+SpaceBeforeAssignmentOperators: true
+SpaceBeforeParens: ControlStatements
+AllowShortIfStatementsOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: true
+AllowShortFunctionsOnASingleLine: false
+IndentCaseLabels: false
+IndentPPDirectives: None
+PenaltyReturnTypeOnItsOwnLine: 0
+PenaltyBreakAssignment: 0
+PenaltyBreakBeforeFirstCallParameter: 1
+PenaltyBreakComment: 1
+PenaltyBreakString: 36
+PenaltyExcessCharacter: 3
+PenaltyBreakFirstLessLess: 0
+PenaltyBreakTemplateDeclaration: 0
+BreakBeforeBinaryOperators: None
+IncludeCategories:
+ - Regex: '<.*\.h>'
+ Priority: 1
+ - Regex: '".*\.h"'
+ Priority: 2
+SortIncludes: true
+#ForEachMacros: [ list_for_each_entry, list_for_each_entry_safe, HASH_ITER ]
+#AlignConsecutiveAssignments: true
diff --git a/dwm/picom/.clang-tidy b/dwm/picom/.clang-tidy
new file mode 100644
index 0000000..7b59c22
--- /dev/null
+++ b/dwm/picom/.clang-tidy
@@ -0,0 +1,21 @@
+Checks: >
+ readability-*,
+ performance-*,
+ modernize-*,
+ google-readability-todo,
+ cert-err34-c,
+ cert-flp30-c,
+ bugprone-*,
+ misc-misplaced-const,
+ misc-redundant-expression,
+ misc-static-assert,
+ -clang-analyzer-*,
+ -readability-isolate-declaration,
+ -readability-magic-numbers
+AnalyzeTemporaryDtors: false
+FormatStyle: file
+CheckOptions:
+ - key: readability-magic-numbers.IgnoredIntegerValues
+ value: 4;8;16;24;32;1;2;3;4096;65536;
+ - key: readability-magic-numbers.IgnoredFloatingPointValues
+ value: 255.0;1.0;
diff --git a/dwm/picom/.editorconfig b/dwm/picom/.editorconfig
new file mode 100644
index 0000000..b40d8e8
--- /dev/null
+++ b/dwm/picom/.editorconfig
@@ -0,0 +1,5 @@
+root = true
+[*.{c,h}]
+indent_style = tab
+indent_size = 8
+max_line_length = 90
diff --git a/dwm/picom/.github/issue_template.md b/dwm/picom/.github/issue_template.md
new file mode 100644
index 0000000..4aee88a
--- /dev/null
+++ b/dwm/picom/.github/issue_template.md
@@ -0,0 +1,57 @@
+
+
+### Platform
+
+
+### GPU, drivers, and screen setup
+
+
+### Environment
+
+
+### picom version
+
+
+
+Diagnostics
+
+
+
+
+### Configuration:
+
+ Configuration file
+
+```
+// Paste your configuration here
+```
+
+
+### Steps of reproduction
+
+
+1.
+2.
+
+### Expected behavior
+
+### Current Behavior
+
+### Stack trace
+
+
+
+
+### Other details
+
diff --git a/dwm/picom/.github/pull_request_template.md b/dwm/picom/.github/pull_request_template.md
new file mode 100644
index 0000000..2dd690f
--- /dev/null
+++ b/dwm/picom/.github/pull_request_template.md
@@ -0,0 +1 @@
+
diff --git a/dwm/picom/.github/workflows/codeql-analysis.yml b/dwm/picom/.github/workflows/codeql-analysis.yml
new file mode 100644
index 0000000..8b65b61
--- /dev/null
+++ b/dwm/picom/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,47 @@
+name: "CodeQL"
+
+on:
+ push:
+ branches: [next]
+ pull_request:
+ branches: [next]
+
+jobs:
+ analyze:
+ name: Analyze
+ runs-on: ubuntu-latest
+
+ strategy:
+ fail-fast: false
+ matrix:
+ language: ['cpp', 'python']
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v2
+ with:
+ # We must fetch at least the immediate parents so that if this is
+ # a pull request then we can checkout the head.
+ fetch-depth: 2
+
+ # If this run was triggered by a pull request event, then checkout
+ # the head of the pull request instead of the merge commit.
+ - run: git checkout HEAD^2
+ if: ${{ github.event_name == 'pull_request' }}
+
+ # Initializes the CodeQL tools for scanning.
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@v1
+ with:
+ languages: ${{ matrix.language }}
+
+ # Install dependencies
+ - run: sudo apt update && sudo apt install libxext-dev libxcb1-dev libxcb-damage0-dev libxcb-xfixes0-dev libxcb-shape0-dev libxcb-render-util0-dev libxcb-render0-dev libxcb-randr0-dev libxcb-composite0-dev libxcb-image0-dev libxcb-present-dev libxcb-xinerama0-dev libxcb-glx0-dev libpixman-1-dev libdbus-1-dev libconfig-dev libgl1-mesa-dev libpcre2-dev libevdev-dev uthash-dev libev-dev libx11-xcb-dev meson ninja-build
+ if: ${{ matrix.language == 'cpp' }}
+
+ # Autobuild
+ - name: Autobuild
+ uses: github/codeql-action/autobuild@v1
+
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@v1
diff --git a/dwm/picom/.github/workflows/coding-style-pr.yml b/dwm/picom/.github/workflows/coding-style-pr.yml
new file mode 100644
index 0000000..e5b40c5
--- /dev/null
+++ b/dwm/picom/.github/workflows/coding-style-pr.yml
@@ -0,0 +1,13 @@
+name: coding-style
+on: pull_request
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v2
+ - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
+ - uses: yshui/git-clang-format-lint@v1.11
+ with:
+ base: ${{ github.event.pull_request.base.sha }}
diff --git a/dwm/picom/.github/workflows/coding-style.yml b/dwm/picom/.github/workflows/coding-style.yml
new file mode 100644
index 0000000..79c7edc
--- /dev/null
+++ b/dwm/picom/.github/workflows/coding-style.yml
@@ -0,0 +1,14 @@
+name: coding-style
+on: push
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v2
+ with:
+ fetch-depth: 2
+ - uses: yshui/git-clang-format-lint@v1.12
+ with:
+ base: ${{ github.event.ref }}~1
diff --git a/dwm/picom/.gitignore b/dwm/picom/.gitignore
new file mode 100644
index 0000000..20b39d0
--- /dev/null
+++ b/dwm/picom/.gitignore
@@ -0,0 +1,58 @@
+# Build files
+.deps
+aclocal.m4
+autom4te.cache
+config.log
+config.status
+configure
+depcomp
+install-sh
+missing
+stamp-h1
+compton
+*.o
+*.d
+build/
+compile_commands.json
+build.ninja
+
+# language servers
+.ccls-cache
+.clangd
+.cache
+
+# CMake files
+compton-*.deb
+compton-*.rpm
+compton-*.tar.bz2
+release/
+_CPack_Packages/
+CMakeCache.txt
+CMakeFiles/
+cmake_install.cmake
+CPackSourceConfig.cmake
+install_manifest.txt
+
+
+# Vim files
+.sw[a-z]
+.*.sw[a-z]
+*~
+
+# Misc files
+core.*
+.gdb_history
+oprofile_data/
+compton.plist
+callgrind.out.*
+man/*.html
+man/*.1
+doxygen/
+.clang_complete
+.ycm_extra_conf.py
+.ycm_extra_conf.pyc
+/src/backtrace-symbols.[ch]
+/compton*.trace
+*.orig
+/tests/log
+/tests/testcases/__pycache__/
diff --git a/dwm/picom/.gitmodules b/dwm/picom/.gitmodules
new file mode 100644
index 0000000..e69de29
diff --git a/dwm/picom/CONTRIBUTORS b/dwm/picom/CONTRIBUTORS
new file mode 100644
index 0000000..9512bf8
--- /dev/null
+++ b/dwm/picom/CONTRIBUTORS
@@ -0,0 +1,85 @@
+Sorted in alphabetical order
+Open an issue or pull request if you don't want your name listed here.
+
+Adam Jackson
+adelin-b
+Alexander Kapshuna
+Antonin Décimo
+Antonio Vivace
+Avi-D-coder
+Ben Friesen
+Bernd Busse
+Bert Gijsbers
+bhagwan
+Bodhi
+Brottweiler
+Carl Worth
+Christopher Jeffrey
+Corax26
+Dan Elkouby
+Dana Jansens
+Daniel Kwan
+Dave Airlie
+David Schlachter
+dolio
+Duncan
+Dylan Araps
+Einar Lielmanis
+Eric Anholt
+Greg Flynn
+Harish Rajagopal
+hasufell
+Ignacio Taranto
+Istvan Petres
+James Cloos
+Jamey Sharp
+Jan Beich
+Jarrad
+Javeed Shaikh
+Jerónimo Navarro
+jialeens
+Johnny Pribyl
+Keith Packard
+Kevin Kelley
+ktprograms
+Lukas Schmelzeisen
+mæp
+Mark Tiefenbruck
+Matthew Allum
+Maxim Solovyov
+Michael Reed
+Michele Lambertucci
+Namkhai Bourquin
+Nate Hart
+nia
+notfoss
+Omar Polo
+orbea
+@Paradigm0001
+Patrick Collins
+Peter Mattern
+Phil Blundell
+Que Quotion
+Rafael Kitover
+Richard Grenville
+Rytis Karpuska
+Samuel Hand
+Scott Leggett
+scrouthtv
+Sebastien Waegeneire
+Subhaditya Nath
+Tasos Sahanidis
+Thiago Kenji Okada
+Tilman Sauerbeck
+Tim van Dalen
+Tomas Janousek
+Tom Dörr
+Toni Jarjour
+Tuomas Kinnunen
+Uli Schlachter
+Walter Lapchynski
+Will Dietz
+XeCycle
+Yuxuan Shui
+zilrich
+ಠ_ಠ
diff --git a/dwm/picom/COPYING b/dwm/picom/COPYING
new file mode 100644
index 0000000..f13a75b
--- /dev/null
+++ b/dwm/picom/COPYING
@@ -0,0 +1,20 @@
+picom - a compositor for X11
+
+Based on xcompmgr, originally written by Keith Packard, with modifications
+from several contributors (according to the xcompmgr man page): Matthew Allum,
+Eric Anholt, Dan Doel, Thomas Luebking, Matthew Hawn, Ely Levy, Phil Blundell,
+and Carl Worth. Menu transparency was implemented by Dana Jansens.
+
+Numerous contributions to picom from Richard Grenville.
+
+See the CONTRIBUTORS file for a complete list of contributors
+
+This source code is provided under:
+
+ SPDX-License-Identifier: MPL-2.0 AND MIT
+
+And the preferred license for new source files in this project is:
+
+ SPDX-License-Identifier: MPL-2.0
+
+You can find the text of the licenses in the LICENSES directory.
diff --git a/dwm/picom/Doxyfile b/dwm/picom/Doxyfile
new file mode 100644
index 0000000..741325c
--- /dev/null
+++ b/dwm/picom/Doxyfile
@@ -0,0 +1,1808 @@
+# Doxyfile 1.8.2
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING = UTF-8
+
+# The PROJECT_NAME tag is a single word (or sequence of words) that should
+# identify the project. Note that if you do not use Doxywizard you need
+# to put quotes around the project name if it contains spaces.
+
+PROJECT_NAME = "compton"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER =
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer
+# a quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF =
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is
+# included in the documentation. The maximum height of the logo should not
+# exceed 55 pixels and the maximum width should not exceed 200 pixels.
+# Doxygen will copy the logo to the output directory.
+
+PROJECT_LOGO =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY = doxygen
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip. Note that you specify absolute paths here, but also
+# relative paths, which will be relative from the directory where doxygen is
+# started.
+
+STRIP_FROM_PATH =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful if your file system
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE = 4
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding
+# "class=itcl::class" will allow you to use the command class in the
+# itcl::class meaning.
+
+TCL_SUBST =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C = YES
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension,
+# and language is one of the parsers supported by doxygen: IDL, Java,
+# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C,
+# C++. For instance to make doxygen treat .inc files as Fortran files (default
+# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note
+# that for custom extensions you also need to set FILE_PATTERNS otherwise the
+# files are not read by doxygen.
+
+EXTENSION_MAPPING =
+
+# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all
+# comments according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you
+# can mix doxygen, HTML, and XML commands with Markdown formatting.
+# Disable only in case of backward compatibilities issues.
+
+MARKDOWN_SUPPORT = YES
+
+# When enabled doxygen tries to link words that correspond to documented classes,
+# or namespaces to their corresponding documentation. Such a link can be
+# prevented in individual cases by by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+
+AUTOLINK_SUPPORT = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also makes the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter and setter methods for a property. Setting this option to YES (the default) will make doxygen replace the get and set methods by a property in the documentation. This will only work if the methods are indeed getting or setting a simple type. If this is not the case, or you want to show the methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and
+# unions are shown inside the group in which they are included (e.g. using
+# @ingroup) instead of on a separate page (for HTML and Man pages) or
+# section (for LaTeX and RTF).
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and
+# unions with only public data fields will be shown inline in the documentation
+# of the scope in which they are defined (i.e. file, namespace, or group
+# documentation), provided this scope is documented. If set to NO (the default),
+# structs, classes, and unions are shown on a separate page (for HTML and Man
+# pages) or section (for LaTeX and RTF).
+
+INLINE_SIMPLE_STRUCTS = NO
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penalty.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will roughly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols.
+
+SYMBOL_CACHE_SIZE = 0
+
+# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be
+# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given
+# their name and scope. Since this can be an expensive process and often the
+# same symbol appear multiple times in the code, doxygen keeps a cache of
+# pre-resolved symbols. If the cache is too small doxygen will become slower.
+# If the cache is too large, memory is wasted. The cache size is given by this
+# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols.
+
+LOOKUP_CACHE_SIZE = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+
+EXTRACT_PACKAGE = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC = YES
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespaces are hidden.
+
+EXTRACT_ANON_NSPACES = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
+# will sort the (brief and detailed) documentation of class members so that
+# constructors and destructors are listed first. If set to NO (the default)
+# the constructors will appear in the respective orders defined by
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to
+# do proper type resolution of all parameters of a function it will reject a
+# match between the prototype and the implementation of a member function even
+# if there is only one candidate or it is obvious which candidate to choose
+# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
+# will still accept a match between prototype and implementation in such cases.
+
+STRICT_PROTO_MATCHING = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or macro consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and macros in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.
+# This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command , where is the value of
+# the FILE_VERSION_FILTER tag, and is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option.
+# You can optionally specify a file name after the option, if omitted
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files
+# containing the references data. This must be a list of .bib files. The
+# .bib extension is automatically appended if omitted. Using this command
+# requires the bibtex tool to be installed. See also
+# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style
+# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this
+# feature you need bibtex and perl available in the search path.
+
+CITE_BIB_FILES =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR = YES
+
+# The WARN_NO_PARAMDOC option can be enabled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT = src
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh
+# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py
+# *.f90 *.f *.for *.vhd *.vhdl
+
+FILE_PATTERNS = *.c *.h
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command , where
+# is the value of the INPUT_FILTER tag, and is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.
+# If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.
+# Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.
+# The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty or if
+# non of the patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
+# and it is also possible to disable source filtering for a specific pattern
+# using *.ext= (so without naming a filter). This option only has effect when
+# FILTER_SOURCE_FILES is enabled.
+
+FILTER_SOURCE_PATTERNS =
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C, C++ and Fortran comments will always remain visible.
+
+STRIP_CODE_COMMENTS = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.
+# Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header. Note that when using a custom header you are responsible
+# for the proper inclusion of any scripts and style sheets that doxygen
+# needs, which is dependent on the configuration options used.
+# It is advised to generate a default header using "doxygen -w html
+# header.html footer.html stylesheet.css YourConfigFile" and then modify
+# that header. Note that the header is subject to change so you typically
+# have to redo this when upgrading to a newer version of doxygen or when
+# changing the value of configuration settings such as GENERATE_TREEVIEW!
+
+HTML_HEADER =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If left blank doxygen will
+# generate a default style sheet. Note that it is recommended to use
+# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this
+# tag will in the future become obsolete.
+
+HTML_STYLESHEET =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional
+# user-defined cascading style sheet that is included after the standard
+# style sheets created by doxygen. Using this option one can overrule
+# certain style aspects. This is preferred over using HTML_STYLESHEET
+# since it does not replace the standard style sheet and is therefor more
+# robust against future updates. Doxygen will copy the style sheet file to
+# the output directory.
+
+HTML_EXTRA_STYLESHEET =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that
+# the files will be copied as-is; there are no commands or markers available.
+
+HTML_EXTRA_FILES =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
+# Doxygen will adjust the colors in the style sheet and background images
+# according to this color. Hue is specified as an angle on a colorwheel,
+# see http://en.wikipedia.org/wiki/Hue for more information.
+# For instance the value 0 represents red, 60 is yellow, 120 is green,
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
+# the colors in the HTML output. For a value of 0 the output will use
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
+# the luminance component of the colors in the HTML output. Values below
+# 100 gradually make the output lighter, whereas values above 100 make
+# the output darker. The value divided by 100 is the actual gamma applied,
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+
+HTML_DYNAMIC_SECTIONS = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of
+# entries shown in the various tree structured indices initially; the user
+# can expand and collapse entries dynamically later on. Doxygen will expand
+# the tree to such a level that at most the specified number of entries are
+# visible (unless a fully collapsed tree already exceeds this amount).
+# So setting the number of entries 1 will produce a full collapsed tree by
+# default. 0 is a special value representing an infinite number of entries
+# and will result in a full expanded tree by default.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+
+GENERATE_DOCSET = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely
+# identify the documentation publisher. This should be a reverse domain-name
+# style string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
+# that can be used as input for Qt's qhelpgenerator to generate a
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
+# add. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see
+#
+# Qt Help Project / Custom Filters.
+
+QHP_CUST_FILTER_ATTRS =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's
+# filter section matches.
+#
+# Qt Help Project / Filter Attributes.
+
+QHP_SECT_FILTER_ATTRS =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
+# the help appears.
+
+GENERATE_ECLIPSEHELP = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs)
+# at top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it. Since the tabs have the same information as the
+# navigation tree you can set this option to NO if you already set
+# GENERATE_TREEVIEW to YES.
+
+DISABLE_INDEX = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+# Since the tree basically has the same information as the tab index you
+# could consider to set DISABLE_INDEX to NO when enabling this option.
+
+GENERATE_TREEVIEW = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values
+# (range [0,1..20]) that doxygen will group on one line in the generated HTML
+# documentation. Note that a value of 0 will completely suppress the enum
+# values from appearing in the overview section.
+
+ENUM_VALUES_PER_LINE = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW = NO
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are
+# not supported properly for IE 6.0, but are supported on all modern browsers.
+# Note that when changing this option you need to delete any form_*.png files
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
+# (see http://www.mathjax.org) which uses client side Javascript for the
+# rendering instead of using prerendered bitmaps. Use this if you do not
+# have LaTeX installed or if you want to formulas look prettier in the HTML
+# output. When enabled you may also need to install MathJax separately and
+# configure the path to it using the MATHJAX_RELPATH option.
+
+USE_MATHJAX = NO
+
+# When MathJax is enabled you need to specify the location relative to the
+# HTML output directory using the MATHJAX_RELPATH option. The destination
+# directory should contain the MathJax.js script. For instance, if the mathjax
+# directory is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to
+# the MathJax Content Delivery Network so you can quickly see the result without
+# installing MathJax.
+# However, it is strongly recommended to install a local
+# copy of MathJax from http://www.mathjax.org before deployment.
+
+MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension
+# names that should be enabled during MathJax rendering.
+
+MATHJAX_EXTENSIONS =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box
+# for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
+# (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a PHP enabled web server instead of at the web client
+# using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server
+# based approach is that it scales better to large projects and allows
+# full text search. The disadvantages are that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE = a4
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for
+# the generated latex document. The footer should contain everything after
+# the last chapter. If it is left blank doxygen will generate a
+# standard footer. Notice: only use this tag if you know what you are doing!
+
+LATEX_FOOTER =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include
+# source code with syntax highlighting in the LaTeX output.
+# Note that which sources are shown also depends on other settings
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See
+# http://en.wikipedia.org/wiki/BibTeX for more info.
+
+LATEX_BIB_STYLE = plain
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS = NO
+
+# Load style sheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.
+# This is useful
+# if you want to understand what is going on.
+# On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION = YES
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF = YES
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# pointed to by INCLUDE_PATH will be searched when a #include is found.
+
+SEARCH_INCLUDES = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED = __attribute__(x)=
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition that
+# overrules the definition found in the source code.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all references to function-like macros
+# that are alone on a line, have an all uppercase name, and do not end with a
+# semicolon, because these will confuse the parser if not removed.
+
+SKIP_FUNCTION_MACROS = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles. For each
+# tag file the location of the external documentation should be added. The
+# format of a tag file without this location is as follows:
+#
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths
+# or URLs. Note that each tag file must have a unique name (where the name does
+# NOT include the path). If a tag file is not located in the directory in which
+# doxygen is run, you must also specify the path to the tagfile here.
+
+TAGFILES =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option also works with HAVE_DOT disabled, but it is recommended to
+# install and use dot, since it yields more powerful graphs.
+
+CLASS_DIAGRAMS = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
+# allowed to run in parallel. When set to 0 (the default) doxygen will
+# base this on the number of processors available in the system. You can set it
+# explicitly to a value larger than 0 to get control over the balance
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS = 0
+
+# By default doxygen will use the Helvetica font for all dot files that
+# doxygen generates. When you want a differently looking font you can specify
+# the font name using DOT_FONTNAME. You need to make sure dot is able to find
+# the font, which can be done by putting it in a standard location or by setting
+# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
+# directory containing the font.
+
+DOT_FONTNAME = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE = 10
+
+# By default doxygen will tell dot to use the Helvetica font.
+# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to
+# set the path where dot can find it.
+
+DOT_FONTPATH =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside
+# the class node. If there are many fields or methods and many nodes the
+# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS
+# threshold limits the number of items for each type to make the size more
+# manageable. Set this to 0 for no limit. Note that the threshold may be
+# exceeded by 50% before the limit is enforced.
+
+UML_LIMIT_NUM_FIELDS = 10
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will generate a graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY = YES
+
+# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are svg, png, jpg, or gif.
+# If left blank png will be used. If you choose svg you need to set
+# HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible in IE 9+ (other browsers do not have this requirement).
+
+DOT_IMAGE_FORMAT = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+# Note that this requires a modern browser other than Internet Explorer.
+# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you
+# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible. Older versions of IE do not have SVG support.
+
+INTERACTIVE_SVG = NO
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the
+# \mscfile command).
+
+MSCFILE_DIRS =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP = YES
diff --git a/dwm/picom/History.md b/dwm/picom/History.md
new file mode 100644
index 0000000..8e5a9b4
--- /dev/null
+++ b/dwm/picom/History.md
@@ -0,0 +1,156 @@
+# Picom History
+
+Picom was forked in 2016 from the original Compton because it seemed to have become unmaintained.
+
+The battle plan of the fork was to refactor it to make the code _possible_ to maintain, so potential contributors won't be scared away when they take a look at the code.
+
+And also to try to fix bugs.
+
+## Rename
+
+In 2019 the project name was changed from Compton to picom (git revision 8ddbeb and following).
+
+### Rationale
+
+Since the inception of this fork, the existence of two compton repositories has caused some number of confusions. Mainly, people will report issues of this fork to the original compton, or report issues of the original compton here. Later, when distros started packaging this fork of compton, some wanted to differentiate the newer compton from the older version. They found themselves having no choice but to invent a name for this fork. This is less than ideal since this has the potential to cause more confusions among users.
+
+Therefore, we decided to move this fork to a new name. Personally, I consider this more than justified since this version of compton has gone through significant changes since it was forked.
+
+### The name
+
+The criteria for a good name were
+
+0. Being short, so it's easy to remember.
+1. Pronounceability, again, helps memorability
+2. Searchability, so when people search the name, it's easy for them to find this repository.
+
+Of course, choosing a name is never easy, and there is no apparent way to objectively evaluate the names. Yet, we have to solve the aforementioned problems as soon as possible.
+
+In the end, we picked `picom` (a portmanteau of `pico` and `composite`) as our new name. This name might not be perfect, but is what we will move forward with unless there's a compelling reason not to.
+
+
+# Compton
+
+This is a copy of the README of the [original Compton project](https://github.com/chjj/compton/).
+
+[](https://gitter.im/chjj/compton?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
+__Compton__ is a compositor for X, and a fork of __xcompmgr-dana__.
+
+I was frustrated by the low amount of standalone lightweight compositors.
+Compton was forked from Dana Jansens' fork of xcompmgr and refactored. I fixed
+whatever bug I found, and added features I wanted. Things seem stable, but don't
+quote me on it. I will most likely be actively working on this until I get the
+features I want. This is also a learning experience for me. That is, I'm
+partially doing this out of a desire to learn Xlib.
+
+## Changes from xcompmgr:
+
+* OpenGL backend (`--backend glx`), in addition to the old X Render backend.
+* Inactive window transparency (`-i`) / dimming (`--inactive-dim`).
+* Titlebar/frame transparency (`-e`).
+* Menu transparency (`-m`, thanks to Dana).
+* shadows are now enabled for argb windows, e.g. terminals with transparency
+* removed serverside shadows (and simple compositing) to clean the code,
+ the only option that remains is clientside shadows
+* configuration files (see the man page for more details)
+* colored shadows (`--shadow-[red/green/blue]`)
+* a new fade system
+* VSync support (not always working)
+* Blur of background of transparent windows, window color inversion (bad in performance)
+* Some more options...
+
+## Fixes from the original xcompmgr:
+
+* fixed a segfault when opening certain window types
+* fixed a memory leak caused by not freeing up shadows (from the freedesktop
+ repo)
+* fixed the conflict with chromium and similar windows
+* [many more](https://github.com/chjj/compton/issues)
+
+## Building
+
+### Dependencies:
+
+__B__ for build-time
+
+__R__ for runtime
+
+* libx11 (B,R)
+* libxcomposite (B,R)
+* libxdamage (B,R)
+* libxfixes (B,R)
+* libXext (B,R)
+* libxrender (B,R)
+* libXrandr (B,R)
+* libXinerama (B,R) (Can be disabled with `NO_XINERAMA` at compile time)
+* pkg-config (B)
+* make (B)
+* xproto / x11proto (B)
+* sh (R)
+* xprop,xwininfo / x11-utils (R)
+* libpcre (B,R) (Can be disabled with `NO_REGEX_PCRE` at compile time)
+* libconfig (B,R) (Can be disabled with `NO_LIBCONFIG` at compile time)
+* libdrm (B) (Can be disabled with `NO_VSYNC_DRM` at compile time)
+* libGL (B,R) (Can be disabled with `NO_VSYNC_OPENGL` at compile time)
+* libdbus (B,R) (Can be disabled with `NO_DBUS` at compile time)
+* asciidoc (B) (and docbook-xml-dtd-4.5, libxml-utils, libxslt, xsltproc, xmlto, etc. if your distro doesn't pull them in)
+
+### How to build
+
+To build, make sure you have the dependencies above:
+
+```bash
+# Make the main program
+$ make
+# Make the man pages
+$ make docs
+# Install
+$ make install
+```
+
+(Compton does include a `_CMakeLists.txt` in the tree, but we haven't decided whether we should switch to CMake yet. The `Makefile` is fully usable right now.)
+
+## Known issues
+
+* Our [FAQ](https://github.com/chjj/compton/wiki/faq) covers some known issues.
+
+* VSync does not work too well. You may check the [VSync Guide](https://github.com/chjj/compton/wiki/vsync-guide) for how to get (possibly) better effects.
+
+* If `--unredir-if-possible` is enabled, when compton redirects/unredirects windows, the screen may flicker. Using `--paint-on-overlay` minimizes the problem from my observation, yet I do not know if there's a cure.
+
+* compton may not track focus correctly in all situations. The focus tracking code is experimental. `--use-ewmh-active-win` might be helpful.
+
+* The performance of blur under X Render backend might be pretty bad. OpenGL backend could be faster.
+
+* With `--blur-background` you may sometimes see weird lines around damaged area. `--resize-damage YOUR_BLUR_RADIUS` might be helpful in the case.
+
+## Usage
+
+Please refer to the Asciidoc man pages (`man/compton.1.asciidoc` & `man/compton-trans.1.asciidoc`) for more details and examples.
+
+Note a sample configuration file `compton.sample.conf` is included in the repository.
+
+## Support
+
+* Bug reports and feature requests should go to the "Issues" section above.
+
+* Our (semi?) official IRC channel is #compton on FreeNode.
+
+* Some information is available on the wiki, including [FAQ](https://github.com/chjj/compton/wiki/faq), [VSync Guide](https://github.com/chjj/compton/wiki/vsync-guide), and [Performance Guide](https://github.com/chjj/compton/wiki/perf-guide).
+
+## License
+
+Although compton has kind of taken on a life of its own, it was originally
+an xcompmgr fork. xcompmgr has gotten around. As far as I can tell, the lineage
+for this particular tree is something like:
+
+* Keith Packard (original author)
+* Matthew Hawn
+* ...
+* Dana Jansens
+* chjj and richardgv
+
+Not counting the tens of people who forked it in between.
+
+Compton is distributed under MIT license, as far as I (richardgv) know. See LICENSE for more info.
diff --git a/dwm/picom/LICENSE.spdx b/dwm/picom/LICENSE.spdx
new file mode 100644
index 0000000..83aa2da
--- /dev/null
+++ b/dwm/picom/LICENSE.spdx
@@ -0,0 +1,4 @@
+SPDXVersion: SPDX-2.1
+DataLicense: CC0-1.0
+PackageName: picom
+PackageLicenseDeclared: MPL-2.0 AND MIT
diff --git a/dwm/picom/LICENSES/MIT b/dwm/picom/LICENSES/MIT
new file mode 100644
index 0000000..1f95d26
--- /dev/null
+++ b/dwm/picom/LICENSES/MIT
@@ -0,0 +1,5 @@
+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.
diff --git a/dwm/picom/LICENSES/MPL-2.0 b/dwm/picom/LICENSES/MPL-2.0
new file mode 100644
index 0000000..14e2f77
--- /dev/null
+++ b/dwm/picom/LICENSES/MPL-2.0
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/dwm/picom/README.md b/dwm/picom/README.md
new file mode 100644
index 0000000..58343a5
--- /dev/null
+++ b/dwm/picom/README.md
@@ -0,0 +1,136 @@
+picom
+=====
+
+__picom__ is a compositor for X, and a [fork of Compton](History.md).
+
+**This is a development branch, bugs to be expected**
+
+You can leave your feedback or thoughts in the [discussion tab](https://github.com/yshui/picom/discussions).
+
+## About this Fork
+
+Extended animation support (auto, fly-in, zoom, squeeze, slide-up, slide-down, slide-left, slide-right) from original [repo](https://github.com/dccsillag/picom) by @dccsillag, added slide-out, slide-in for workspace switching with [Custom Fluxbox](https://github.com/pijulius/fluxbox/commit/83ee4dbee67a68fe38b0f96431473719e165bf1e) , animation on window type basis (for e.g. make transient windows like "about us" slide down and slide backup to the titlebar of the owner window), animation-exclude list for disabling animations on window/program basis and some fixes.
+
+Reason: original picom by @yshui [repo](https://github.com/yshui/picom/) didn't have animation support and @dccsillag implementation was the best could find so building uppon his work this repo was made. FYI: looks like original picom will have animation support starting with version 12 but will keep this repo as atm looks like the animation here are smoother/better (of course everyone's own point of view) and had some trouble with the latest picom so till find out the reasons will use this repo personally and everyone is velcome to do so.
+
+**Would like to thank everyone working on all 3 repos of picom as without their work we (old timers) wouldn't have a good compositor so thank you guys for your hard work/time to keep it updated and maintenanced regularly!**
+
+**IMPORTANT**: always run picom with `--experimental-backends` argument as otherwise animations won't really look good.
+
+## Call for testers
+
+### `--experimental-backends`
+
+This flag enables the refactored/partially rewritten backends.
+
+Currently, new backends feature better vsync with the xrender backend and improved input lag with the glx backend (for non-NVIDIA users). The performance should be on par with the old backends.
+
+New backend features will only be implemented on the new backends from now on, and the old backends will eventually be phased out after the new backends stabilize.
+
+To test the new backends, add the `--experimental-backends` flag to the command you use to run picom. This flag is not available from the configuration file.
+
+To report issues with the new backends, please state explicitly you are using the new backends in your report.
+
+## Change Log
+
+See [Releases](https://github.com/yshui/picom/releases)
+
+## Build
+
+### Dependencies
+
+Assuming you already have all the usual building tools installed (e.g. gcc, python, meson, ninja, etc.), you still need:
+
+* libx11
+* libx11-xcb
+* libXext
+* xproto
+* xcb
+* xcb-damage
+* xcb-xfixes
+* xcb-shape
+* xcb-renderutil
+* xcb-render
+* xcb-randr
+* xcb-composite
+* xcb-image
+* xcb-present
+* xcb-xinerama
+* xcb-glx
+* pixman
+* libdbus (optional, disable with the `-Ddbus=false` meson configure flag)
+* libconfig (optional, disable with the `-Dconfig_file=false` meson configure flag)
+* libGL (optional, disable with the `-Dopengl=false` meson configure flag)
+* libpcre (optional, disable with the `-Dregex=false` meson configure flag)
+* libev
+* uthash
+
+On Debian based distributions (e.g. Ubuntu), the needed packages are
+
+```
+libxext-dev libxcb1-dev libxcb-damage0-dev libxcb-xfixes0-dev libxcb-shape0-dev libxcb-render-util0-dev libxcb-render0-dev libxcb-randr0-dev libxcb-composite0-dev libxcb-image0-dev libxcb-present-dev libxcb-xinerama0-dev libxcb-glx0-dev libpixman-1-dev libdbus-1-dev libconfig-dev libgl1-mesa-dev libpcre2-dev libpcre3-dev libevdev-dev uthash-dev libev-dev libx11-xcb-dev meson
+```
+
+On Fedora, the needed packages are
+
+```
+dbus-devel gcc git libconfig-devel libdrm-devel libev-devel libX11-devel libX11-xcb libXext-devel libxcb-devel mesa-libGL-devel meson pcre-devel pixman-devel uthash-devel xcb-util-image-devel xcb-util-renderutil-devel xorg-x11-proto-devel
+```
+
+To build the documents, you need `asciidoc`
+
+### To build
+
+```bash
+$ git submodule update --init --recursive
+$ meson --buildtype=release . build
+$ ninja -C build
+```
+
+Built binary can be found in `build/src`
+
+If you have libraries and/or headers installed at non-default location (e.g. under `/usr/local/`), you might need to tell meson about them, since meson doesn't look for dependencies there by default.
+
+You can do that by setting the `CPPFLAGS` and `LDFLAGS` environment variables when running `meson`. Like this:
+
+```bash
+$ LDFLAGS="-L/path/to/libraries" CPPFLAGS="-I/path/to/headers" meson --buildtype=release . build
+
+```
+
+As an example, on FreeBSD, you might have to run meson with:
+```bash
+$ LDFLAGS="-L/usr/local/lib" CPPFLAGS="-I/usr/local/include" meson --buildtype=release . build
+$ ninja -C build
+```
+
+### To install
+
+``` bash
+$ ninja -C build install
+```
+
+Default install prefix is `/usr/local`, you can change it with `meson configure -Dprefix= build`
+
+## How to Contribute
+
+### Code
+
+You can look at the [Projects](https://github.com/yshui/picom/projects) page, and see if there is anything that interests you. Or you can take a look at the [Issues](https://github.com/yshui/picom/issues).
+
+### Non-code
+
+Even if you don't want to contribute code, you can still contribute by compiling and running this branch, and report any issue you can find.
+
+Contributions to the documents and wiki will also be appreciated.
+
+## Contributors
+
+See [CONTRIBUTORS](CONTRIBUTORS)
+
+The README for the [original Compton project](https://github.com/chjj/compton/) can be found [here](History.md#Compton).
+
+## Licensing
+
+picom is free software, made available under the [MIT](LICENSES/MIT) and [MPL-2.0](LICENSES/MPL-2.0) software
+licenses. See the individual source files for details.
diff --git a/dwm/picom/bin/picom-trans b/dwm/picom/bin/picom-trans
new file mode 100755
index 0000000..b686128
--- /dev/null
+++ b/dwm/picom/bin/picom-trans
@@ -0,0 +1,407 @@
+#!/bin/sh
+# SPDX-License-Identifier: MIT
+
+#
+# picom-trans
+# Copyright (c) 2021, Subhaditya Nath
+# Based on previous works of Christopher Jeffrey
+#
+
+#
+# Conforming to POSIX-1.2007
+# https://pubs.opengroup.org/onlinepubs/9699919799
+#
+
+# Usage:
+# $ picom-trans [options] [+|-]opacity
+# By window id
+# $ picom-trans -w "$WINDOWID" 75
+# By name
+# $ picom-trans -n "urxvt" 75
+# By current window
+# $ picom-trans -c 75
+# By selection
+# $ picom-trans 75
+# $ picom-trans -s 75
+# Increment current window 5%
+# $ picom-trans -c +5
+# Delete current window's opacity
+# $ picom-trans -c --delete
+# Toggle current window's opacity between 90 and unset
+# $ picom-trans -c --toggle 90
+# Reset all windows
+# $ picom-trans --reset
+
+
+# Save $0 now to print correct value while printing from functions.
+# Printing errormsgs from functions using "$0" prints the function name
+# instead of the executable name.
+EXE_NAME="$0"
+
+
+# Instead of printing the full path to this file (e.g. /usr/bin/picom-trans)
+# only print the base name (i.e. picom-trans)
+EXE_NAME="$(basename "$EXE_NAME")"
+
+
+print_usage()
+{ #{{
+ echo "Usage: $EXE_NAME [options] [+|-]opacity"
+ echo ""
+ echo "Options:"
+ echo " -h, --help Print this help message."
+ echo " -o, --opacity OPACITY Specify the new opacity value in range 0-100 for the window. If"
+ echo " prefixed with + or -, increment or decrement from the current"
+ echo " opacity of the target window."
+ echo ""
+ echo "Actions:"
+ echo " -g, --get Print current opacity of the target window."
+ echo " -d, --delete Delete opacity of the target window."
+ echo " -t, --toggle Toggle the target window's opacity, i.e. set if not already set"
+ echo " and delete else."
+ echo " -r, --reset Reset opacity for all windows."
+ echo ""
+ echo "Window Selection:"
+ echo " -s, --select Select target window with mouse cursor. (DEFAULT)"
+ echo " -c, --current Select the currently active window as target."
+ echo " -n, --name WINDOW_NAME Specify and try to match a window name."
+ echo " -w, --window WINDOW_ID Specify the window id of the target window."
+} #}}
+
+
+parse_args()
+{ #{{
+ i=1 # because we start from "$1", not from "$0"
+ while [ $i -le $# ]
+ do
+ #### [START] Convert GNU longopts to POSIX equivalents ####
+ if [ "$1" = "--${1##--}" ] # check if $1 is a longopt
+ then
+ # Catch invalid options
+ case "$1" in
+ (--opacity=|--name=|--window=)
+ echo "$EXE_NAME: option ${1%=} needs a value" >&2
+ exit 1;;
+ (--opacity|--name|--window)
+ test $i -eq $# \
+ && echo "$EXE_NAME: option $1 needs a value" >&2 \
+ && exit 1;;
+ esac
+
+ # Separate "--ARG=VAL" into "--ARG" "VAL"
+ case "$1" in
+ (--opacity=*|--name=*|--window=*)
+ ARG="$(echo "$1" | sed -E 's/(--[^=]+)=.*$/\1/')"
+ VAL="${1##${ARG}=}"
+ shift && set -- "$ARG" "$VAL" "$@"
+ esac
+
+ # Turn into short form
+ case "$1" in
+ (--help|--opacity|--get|--delete|--toggle|--reset|--select|--current|--name|--window)
+ ARG=${1#-} # remove one '-' from prefix
+ ARG="$(echo "$ARG" | cut -c -2)" # get first two characters
+ shift && set -- "$ARG" "$@"
+ esac
+
+ # If the argument still starts with --, it is an invalid argument
+ case "$1" in
+ (--*)
+ echo "$EXE_NAME: illegal option $1" >&2
+ exit 1
+ esac
+ fi
+ #### [END] Convert GNU longopts to POSIX equivalents ####
+
+
+ #### [START] Prepend '-o' to standalone opacity values ####
+ # Iterate over every argument and check if it is an opacity without the -o
+ # option in the previous argument. If so, then prepend the -o option.
+ # e.g. Turn this -
+ # picom-trans -c +10 -s
+ # into this -
+ # picom-trans -c -o +10 -s
+ #
+ # NOTE: Don't touch arguments that are preceded by -o, -w, or -n (i.e. the
+ # options that take a value.)
+ # e.g. This -
+ # picom-trans -w 75 -o 90
+ # should NOT be turned into this -
+ # picom-trans -w -o 75 -o 90
+ # We ensure this by checking the "$#"th (i.e. the last) argument. If
+ # argument is an option that needs a value, we don't do anything to $1.
+ #
+ # NOTE: we are using printf because most echo implementations aren't
+ # POSIX-compliant. For example, according to POSIX.1-2017, echo doesn't
+ # support any options, so,
+ # $ echo "-n"
+ # should output -
+ # -n
+ # But it doesn't. It instead interprets the "-n" as the option -n, which,
+ # in most implementations, means that the trailing newline should not be
+ # printed.
+ if echo "$1" | grep -qE '^[+-]?[[:digit:]]+%?$' && \
+ ! eval "printf '%s' \"\${$#}\"" | grep -q '^-[hdtrgsc]*[own]$'
+ # NOTE: eval "printf '%s' \"\${$#}\"" means 'print the last argument'
+ # NOTE: The letters inside the first square brackets (ie. hdtrgsc) are
+ # the same as those in the getopts argument, minus those that are
+ # followed by a ':'
+ # NOTE: The letters inside the second square brackets (ie. own) are
+ # the same as those in the getopts argument, minus those that are
+ # NOT followed by a ':'
+ then
+ set -- "$@" "-o"
+ i=$(( i + 1 ))
+ fi
+ #### [END] Prepend '-o' to standalone opacity values ####
+
+
+ # Prepare for next iteration
+ ARG="$1"
+ shift && set -- "$@" "$ARG"
+ i=$(( i + 1 ))
+ done
+
+
+ # NOTE: DO NOT ATTEMPT TO USE "$OPTIND" INSIDE THE getopts LOOP
+ # - https://github.com/yshui/picom/pull/634#discussion_r654571535
+ # - https://www.mail-archive.com/austin-group-l%40opengroup.org/msg04112.html
+ OPTIND=1
+ while getopts 'ho:dtrgsn:w:c' OPTION
+ do
+ case "$OPTION" in
+ (h) print_usage; exit 0;;
+ (o) target_opacity="$OPTARG";;
+ (d) action=delete;;
+ (t) action=toggle;;
+ (r) action=reset;;
+ (g) action=get;;
+ (s) winidtype=; winid=;;
+ (n) winidtype=-name; winid="$OPTARG";;
+ (w) winidtype=-id; winid="$OPTARG";;
+ (c) winidtype=-id; winid="$(get_focused_window_id)";;
+ (\?) exit 1
+ esac
+ done
+} #}}
+
+
+get_target_window_id()
+{ #{{
+
+ # Get the output of xwininfo
+ if test -z "$winidtype"
+ then xwininfo_output="$(xwininfo -children -frame)"
+ elif test "$winidtype" = "-name"
+ then xwininfo_output="$(xwininfo -children -name "$winid")"
+ elif test "$winidtype" = "-id"
+ then
+ # First, check if supplied window id is valid
+ if ! echo "$winid" | grep -Eiq '^[[:space:]]*(0x[[:xdigit:]]+|[[:digit:]]+)[[:space:]]*$'
+ then
+ echo "Bad window ID" >&2
+ exit 1
+ fi
+ xwininfo_output="$(xwininfo -children -id "$winid")"
+ fi
+
+ # Extract window id from xwininfo output
+ winid="$(echo "$xwininfo_output" | sed -n 's/^xwininfo:.*: \(0x[[:xdigit:]]*\).*$/\1/p')"
+ if test -z "$winid"
+ then
+ echo "Failed to find window" >&2
+ exit 1
+ fi
+
+ # Make sure it's not root window
+ if echo "$xwininfo_output" | grep -Fq "Parent window id: 0x0"
+ then
+ echo "Cannot set opacity on root window" >&2
+ exit 1
+ fi
+
+ # If it's not the topmost window, get the topmost window
+ if ! echo "$xwininfo_output" | grep -q 'Parent window id: 0x[[:xdigit:]]* (the root window)'
+ then
+ window_tree="$(xwininfo -root -tree)"
+ if test -z "$window_tree"
+ then
+ echo "Failed to get root window tree" >&2
+ exit 1
+ fi
+
+ # Find the highest ancestor of the target window
+ winid="$(echo "$window_tree" \
+ | sed -n "/^\s*$winid/q;s/^ \(0x[[:xdigit:]]*\).*/\1/p" \
+ | tail -n 1)"
+ if test -z "$winid"
+ then
+ echo "Failed to find window in window tree" >&2
+ exit 1
+ fi
+ fi
+ if test -z "$winid"
+ then
+ echo "Failed to find the highest parent window below root of the selected window" >&2
+ exit 1
+ fi
+
+ echo "$winid"
+} #}}
+
+get_focused_window_id()
+{ #{{
+ id="$(xprop -root -notype -f _NET_ACTIVE_WINDOW 32x '$0' _NET_ACTIVE_WINDOW)"
+ echo "${id#_NET_ACTIVE_WINDOW}"
+} #}}
+
+get_current_opacity()
+{ #{{
+ # Gets current opacity in the range 0-100
+ # Doesn't output anything if opacity isn't set
+ cur="$(xprop -id "$winid" -notype -f _NET_WM_WINDOW_OPACITY 32c '$0' _NET_WM_WINDOW_OPACITY)"
+ cur="${cur#_NET_WM_WINDOW_OPACITY}"
+ cur="${cur%:*}"
+ test -n "$cur" &&
+ cur=$(( cur * 100 / 0xffffffff ))
+ echo "$cur"
+} #}}
+
+
+get_opacity()
+{ #{{
+ cur="$(get_current_opacity)"
+ test -z "$cur" && cur=100 # Unset opacity means fully opaque
+ echo "$cur"
+ exit 0
+} #}}
+
+delete_opacity()
+{ #{{
+ xprop -id "$winid" -remove _NET_WM_WINDOW_OPACITY
+ exit 0
+} #}}
+
+reset_opacity() # Reset opacity of all windows
+{ #{{
+ for winid in $(xwininfo -root -tree | sed -n 's/^ \(0x[[:xdigit:]]*\).*/\1/p')
+ do xprop -id "$winid" -remove _NET_WM_WINDOW_OPACITY 2>/dev/null
+ done
+ exit 0
+} #}}
+
+set_opacity()
+{ #{{
+ if ! echo "$target_opacity" | grep -qE '^[+-]?[[:digit:]]+%?$'
+ then
+ if test -z "$target_opacity"
+ then echo "No opacity specified" >&2
+ else echo "Invalid opacity specified: $target_opacity" >&2
+ fi
+ exit 1
+ fi
+
+ # strip trailing '%' sign, if any
+ target_opacity="${target_opacity%%%}"
+
+ if echo "$target_opacity" | grep -q '^[+-]'
+ then
+ current_opacity="$(get_current_opacity)"
+ test -z "$current_opacity" && current_opacity=100
+ target_opacity=$(( current_opacity + target_opacity ))
+ fi
+
+ test $target_opacity -lt 0 && target_opacity=0
+ test $target_opacity -gt 100 && target_opacity=100
+
+ target_opacity=$(( target_opacity * 0xffffffff / 100 ))
+ xprop -id "$winid" -f _NET_WM_WINDOW_OPACITY 32c \
+ -set _NET_WM_WINDOW_OPACITY "$target_opacity"
+
+ exit $?
+} #}}
+
+toggle_opacity()
+{ #{{
+ # If opacity is currently set, unset it.
+ # If opacity is currently unset, set opacity to the supplied value. If no
+ # value is supplied, we default to 100%.
+ if test -z "$(get_current_opacity)"
+ then
+ test -n "$target_opacity" || target_opacity=100
+ set_opacity
+ else
+ delete_opacity
+ fi
+} #}}
+
+
+# Warn about rename of compton to picom
+case "$0" in
+ *compton-trans*) echo "Warning: compton has been renamed, please use picom-trans instead" >&2;;
+esac
+
+
+# Check if both xwininfo and xprop are available
+if ! command -v xprop >/dev/null || ! command -v xwininfo >/dev/null
+then
+ echo "The command xwininfo or xprop is not available. They might reside in a package named xwininfo, xprop, x11-utils, xorg-xprop, or xorg-xwininfo" >&2
+ exit 1
+fi
+
+
+# No arguments given. Show help.
+if test $# -eq 0
+then
+ print_usage >&2
+ exit 1
+fi
+
+
+# Variables
+# action is set to 'set' by default
+action=set
+winid=
+winidtype=
+target_opacity=
+
+# If there's only one argument, and it's a valid opacity
+# then take it as target_opacity. Else, parse all arguments.
+if test $# -eq 1 && echo "$1" | grep -qE '^[+-]?[[:digit:]]+%?$'
+then
+ target_opacity=$1
+ shift
+else
+ parse_args "$@"
+fi
+
+
+# reset_opacity doesn't need $winid
+case $action in
+ (reset) reset_opacity;;
+esac
+
+# Any other action needs $winid
+#
+# NOTE: Do NOT change the order of winid= and winidtype= below
+# the output of get_target_window_id depends on $winidtype
+#
+# NOTE: If get_target_window_id returns with a non-zero $?
+# that must mean that some error occured. So, exit with that same $?
+#
+winid=$(get_target_window_id) || exit $?
+winidtype=-id
+case $action in
+ (set) set_opacity;;
+ (get) get_opacity;;
+ (delete) delete_opacity;;
+ (toggle) toggle_opacity;;
+esac
+
+
+# We should never reach this part of the file
+echo "This sentence shouldn't have been printed. Please file a bug report." >&2
+exit 128
+
+
+# vim:ft=sh:ts=4:sts=4:sw=2:et:fdm=marker:fmr=#{{,#}}:nowrap
diff --git a/dwm/picom/compton-default-fshader-win.glsl b/dwm/picom/compton-default-fshader-win.glsl
new file mode 100644
index 0000000..e319523
--- /dev/null
+++ b/dwm/picom/compton-default-fshader-win.glsl
@@ -0,0 +1,11 @@
+uniform float opacity;
+uniform bool invert_color;
+uniform sampler2D tex;
+
+void main() {
+ vec4 c = texture2D(tex, gl_TexCoord[0]);
+ if (invert_color)
+ c = vec4(vec3(c.a, c.a, c.a) - vec3(c), c.a);
+ c *= opacity;
+ gl_FragColor = c;
+}
diff --git a/dwm/picom/compton-fake-transparency-fshader-win.glsl b/dwm/picom/compton-fake-transparency-fshader-win.glsl
new file mode 100644
index 0000000..88e3653
--- /dev/null
+++ b/dwm/picom/compton-fake-transparency-fshader-win.glsl
@@ -0,0 +1,19 @@
+uniform float opacity;
+uniform bool invert_color;
+uniform sampler2D tex;
+
+void main() {
+ vec4 c = texture2D(tex, gl_TexCoord[0]);
+ {
+ // Change vec4(1.0, 1.0, 1.0, 1.0) to your desired color
+ vec4 vdiff = abs(vec4(1.0, 1.0, 1.0, 1.0) - c);
+ float diff = max(max(max(vdiff.r, vdiff.g), vdiff.b), vdiff.a);
+ // Change 0.8 to your desired opacity
+ if (diff < 0.001)
+ c *= 0.8;
+ }
+ if (invert_color)
+ c = vec4(vec3(c.a, c.a, c.a) - vec3(c), c.a);
+ c *= opacity;
+ gl_FragColor = c;
+}
diff --git a/dwm/picom/compton.desktop b/dwm/picom/compton.desktop
new file mode 100644
index 0000000..77734f1
--- /dev/null
+++ b/dwm/picom/compton.desktop
@@ -0,0 +1,13 @@
+[Desktop Entry]
+Version=1.0
+Type=Application
+NoDisplay=true
+Name=compton
+GenericName=X compositor
+Comment=An X compositor
+Categories=Utility;
+Keywords=compositor;composite manager;window effects;transparency;opacity;
+TryExec=compton
+Exec=compton
+Icon=compton
+# Thanks to quequotion for providing this file!
diff --git a/dwm/picom/dbus-examples/cdbus-driver.sh b/dwm/picom/dbus-examples/cdbus-driver.sh
new file mode 100755
index 0000000..31a9b2f
--- /dev/null
+++ b/dwm/picom/dbus-examples/cdbus-driver.sh
@@ -0,0 +1,54 @@
+#!/bin/sh
+
+if [ -z "$SED" ]; then
+ SED="sed"
+ command -v gsed > /dev/null && SED="gsed"
+fi
+
+# === Get connection parameters ===
+
+dpy=$(echo -n "$DISPLAY" | tr -c '[:alnum:]' _)
+
+if [ -z "$dpy" ]; then
+ echo "Cannot find display."
+ exit 1
+fi
+
+service="com.github.chjj.compton.${dpy}"
+interface='com.github.chjj.compton'
+object='/com/github/chjj/compton'
+type_win='uint32'
+type_enum='uint32'
+
+# === DBus methods ===
+
+# List all window ID compton manages (except destroyed ones)
+dbus-send --print-reply --dest="$service" "$object" "${interface}.list_win"
+
+# Get window ID of currently focused window
+focused=$(dbus-send --print-reply --dest="$service" "$object" "${interface}.find_win" string:focused | $SED -n 's/^[[:space:]]*'${type_win}'[[:space:]]*\([[:digit:]]*\).*/\1/p')
+
+if [ -n "$focused" ]; then
+ # Get invert_color_force property of the window
+ dbus-send --print-reply --dest="$service" "$object" "${interface}.win_get" "${type_win}:${focused}" string:invert_color_force
+
+ # Set the window to have inverted color
+ dbus-send --print-reply --dest="$service" "$object" "${interface}.win_set" "${type_win}:${focused}" string:invert_color_force "${type_enum}:1"
+else
+ echo "Cannot find focused window."
+fi
+
+# Reset compton
+sleep 3
+dbus-send --print-reply --dest="$service" "$object" "${interface}.reset"
+
+# Undirect window
+sleep 3
+dbus-send --print-reply --dest="$service" "$object" "${interface}.opts_set" string:redirected_force "${type_enum}:0"
+
+# Revert back to auto
+sleep 3
+dbus-send --print-reply --dest="$service" "$object" "${interface}.opts_set" string:redirected_force "${type_enum}:2"
+
+# Force repaint
+dbus-send --print-reply --dest="$service" "$object" "${interface}.repaint"
diff --git a/dwm/picom/dbus-examples/inverter.sh b/dwm/picom/dbus-examples/inverter.sh
new file mode 100755
index 0000000..e13cb2d
--- /dev/null
+++ b/dwm/picom/dbus-examples/inverter.sh
@@ -0,0 +1,69 @@
+#!/bin/sh
+
+# == Declare stderr function ===
+
+stderr() {
+ printf "\033[1;31m%s\n\033[0m" "$@" >&2
+}
+
+# === Verify `picom --dbus` status ===
+
+if [ -z "$(dbus-send --session --dest=org.freedesktop.DBus --type=method_call --print-reply /org/freedesktop/DBus org.freedesktop.DBus.ListNames | grep compton)" ]; then
+ stderr "picom DBus interface unavailable"
+ if [ -n "$(pgrep picom)" ]; then
+ stderr "picom running without dbus interface"
+ #killall picom & # Causes all windows to flicker away and come back ugly.
+ #picom --dbus & # Causes all windows to flicker away and come back beautiful
+ else
+ stderr "picom not running"
+ fi
+ exit 1
+fi
+
+# === Setup sed ===
+
+SED="${SED:-$(command -v gsed || printf 'sed')}"
+
+# === Get connection parameters ===
+
+dpy=$(printf "$DISPLAY" | tr -c '[:alnum:]' _)
+
+if [ -z "$dpy" ]; then
+ stderr "Cannot find display."
+ exit 1
+fi
+
+service="com.github.chjj.compton.${dpy}"
+interface="com.github.chjj.compton"
+picom_dbus="dbus-send --print-reply --dest="${service}" / "${interface}"."
+type_win='uint32'
+type_enum='uint32'
+
+# === Color Inversion ===
+
+# Get window ID of window to invert
+if [ -z "$1" -o "$1" = "selected" ]; then
+ window=$(xwininfo -frame | sed -n 's/^xwininfo: Window id: \(0x[[:xdigit:]][[:xdigit:]]*\).*/\1/p') # Select window by mouse
+elif [ "$1" = "focused" ]; then
+ # Ensure we are tracking focus
+ window=$(${picom_dbus}find_win string:focused | $SED -n 's/^[[:space:]]*'${type_win}'[[:space:]]*\([[:digit:]]*\).*/\1/p') # Query picom for the active window
+elif echo "$1" | grep -Eiq '^([[:digit:]][[:digit:]]*|0x[[:xdigit:]][[:xdigit:]]*)$'; then
+ window="$1" # Accept user-specified window-id if the format is correct
+else
+ echo "$0" "[ selected | focused | window-id ]"
+fi
+
+# Color invert the selected or focused window
+if [ -n "$window" ]; then
+ invert_status="$(${picom_dbus}win_get "${type_win}:${window}" string:invert_color | $SED -n 's/^[[:space:]]*boolean[[:space:]]*\([[:alpha:]]*\).*/\1/p')"
+ if [ "$invert_status" = true ]; then
+ invert=0 # Set the window to have normal color
+ else
+ invert=1 # Set the window to have inverted color
+ fi
+ ${picom_dbus}win_set "${type_win}:${window}" string:invert_color_force "${type_enum}:${invert}" &
+else
+ stderr "Cannot find $1 window."
+ exit 1
+fi
+exit 0
diff --git a/dwm/picom/desc.txt b/dwm/picom/desc.txt
new file mode 100644
index 0000000..eadc037
--- /dev/null
+++ b/dwm/picom/desc.txt
@@ -0,0 +1 @@
+Compton is a X compositing window manager, fork of xcompmgr-dana.
diff --git a/dwm/picom/man/meson.build b/dwm/picom/man/meson.build
new file mode 100644
index 0000000..6324830
--- /dev/null
+++ b/dwm/picom/man/meson.build
@@ -0,0 +1,13 @@
+mans = ['picom.1', 'picom-trans.1']
+if get_option('with_docs')
+ a2x = find_program('a2x')
+ foreach m : mans
+ custom_target(m, output: [m], input: [m+'.asciidoc'],
+ command: [a2x, '-a',
+ 'picom-version='+version,
+ '--format', 'manpage', '@INPUT@', '-D',
+ meson.current_build_dir()],
+ install: true,
+ install_dir: join_paths(get_option('mandir'), 'man1'))
+ endforeach
+endif
diff --git a/dwm/picom/man/picom-trans.1.asciidoc b/dwm/picom/man/picom-trans.1.asciidoc
new file mode 100644
index 0000000..22b1dd2
--- /dev/null
+++ b/dwm/picom/man/picom-trans.1.asciidoc
@@ -0,0 +1,114 @@
+picom-trans(1)
+================
+:doctype: manpage
+:man source: picom
+:man version: {picom-version}
+:man manual: User Commands
+
+NAME
+----
+picom-trans - an opacity setter tool
+
+SYNOPSIS
+--------
+
+*picom-trans* [-w 'WINDOW_ID'] [-n 'WINDOW_NAME'] [-c] [-s] 'OPACITY'
+
+DESCRIPTION
+-----------
+
+*picom-trans* is a bash script that sets '_NET_WM_WINDOW_OPACITY' attribute of a window using standard X11 command-line utilities, including *xprop*(1) and *xwininfo*(1). It is similar to *transset*(1) or *transset-df*(1).
+
+OPTIONS
+-------
+*-w*, *--window*='WINDOW_ID'::
+Specify the window id of the target window.
+
+*-n*, *--name*='WINDOW_NAME'::
+Specify and try to match a window name.
+
+*-c*, *--current*::
+Specify the currently active window as target. Only works if EWMH '_NET_ACTIVE_WINDOW' property exists on root window.
+
+*-s*, *--select*::
+Select target window with mouse cursor. This is the default if no window has been specified.
+
+*-o*, *--opacity*='OPACITY'::
+Specify the new opacity value for the window. This value can be anywhere from 1-100. If it is prefixed with a plus or minus (+/-), this will increment or decrement from the target window's current opacity instead.
+
+*-g*, *--get*::
+Print the target window's opacity instead of setting it.
+
+*-d*, *--delete*::
+Delete opacity of the target window instead of setting it.
+
+*-t*, *--toggle*::
+Toggle the target window's opacity: Set opacity if not already set, and delete if already set.
+
+*-r*, *--reset*::
+Reset opacity for all windows instead of setting it.
+
+EXAMPLES
+--------
+
+* Set the opacity of the window with specific window ID to 75%:
++
+------------
+picom-trans -w "$WINDOWID" 75
+------------
+
+* Set the opacity of the window with the name "urxvt" to 75%:
++
+------------
+picom-trans -n "urxvt" 75
+------------
+
+* Set current window to opacity of 75%:
++
+------------
+picom-trans -c 75
+------------
+
+* Select target window and set opacity to 75%:
++
+------------
+picom-trans -s 75
+------------
+
+* Increment opacity of current active window by 5%:
++
+------------
+picom-trans -c +5
+------------
+
+* Decrement opacity of current active window by 5%:
++
+------------
+picom-trans -c -- -5
+------------
+
+* Delete current window's opacity:
++
+------------
+picom-trans -c --delete
+------------
+
+* Toggle current window's opacity between 90 and unset
++
+------------
+picom-trans -c --toggle 90
+------------
+
+* Reset all windows:
++
+------------
+picom-trans --reset
+------------
+
+BUGS
+----
+Please submit bug reports to .
+
+SEE ALSO
+--------
+link:picom.1.html[*picom*(1)], *xprop*(1), *xwininfo*(1)
diff --git a/dwm/picom/man/picom.1.asciidoc b/dwm/picom/man/picom.1.asciidoc
new file mode 100644
index 0000000..ccd7e43
--- /dev/null
+++ b/dwm/picom/man/picom.1.asciidoc
@@ -0,0 +1,509 @@
+picom(1)
+========
+:doctype: manpage
+:man source: picom
+:man version: {picom-version}
+:man manual: User Commands
+
+NAME
+----
+picom - a compositor for X11
+
+SYNOPSIS
+--------
+*picom* ['OPTIONS']
+
+DESCRIPTION
+-----------
+picom is a compositor based on Dana Jansens' version of xcompmgr (which itself was written by Keith Packard). It includes some improvements over the original xcompmgr, like window frame opacity and inactive window transparency.
+
+OPTIONS
+-------
+*-h*, *--help*::
+ Get the usage text embedded in program code, which may be more up-to-date than this man page.
+
+*-r*, *--shadow-radius*='RADIUS'::
+ The blur radius for shadows, in pixels. (defaults to 12)
+
+*-o*, *--shadow-opacity*='OPACITY'::
+ The opacity of shadows. (0.0 - 1.0, defaults to 0.75)
+
+*-l*, *--shadow-offset-x*='OFFSET'::
+ The left offset for shadows, in pixels. (defaults to -15)
+
+*-t*, *--shadow-offset-y*='OFFSET'::
+ The top offset for shadows, in pixels. (defaults to -15)
+
+*-I*, *--fade-in-step*='OPACITY_STEP'::
+ Opacity change between steps while fading in. (0.01 - 1.0, defaults to 0.028)
+
+*-O*, *--fade-out-step*='OPACITY_STEP'::
+ Opacity change between steps while fading out. (0.01 - 1.0, defaults to 0.03)
+
+*-D*, *--fade-delta*='MILLISECONDS'::
+ The time between steps in fade step, in milliseconds. (> 0, defaults to 10)
+
+*-c*, *--shadow*::
+ Enabled client-side shadows on windows. Note desktop windows (windows with '_NET_WM_WINDOW_TYPE_DESKTOP') never get shadow, unless explicitly requested using the wintypes option.
+
+*-f*, *--fading*::
+ Fade windows in/out when opening/closing and when opacity changes, unless *--no-fading-openclose* is used.
+
+*-F*::
+ Equals to *-f*. Deprecated.
+
+*--animations*::
+ Run animations for window geometry changes (movement and scaling).
+ We use spring-based animations, which are parametrized by *--animation-stiffness*, *--animation-dampening*, *--animation-window-mass* and *--animation-clamp*. +
+ A useful resource for selecting animation parameters is https://react-spring-visualizer.com/, which allows you to interactively try out various parameters and see the resulting animation curve. Or you can just edit the values in the config file, which is automatically reloaded.
+
+*--animation-for-open-window*::
+ Which animation to run when opening a window. Must be one of `none`, `fly-in`, `zoom` (default: `none`).
+
+*--animation-stiffness*::
+ Stiffness (a.k.a. tension) parameter for spring-based animation (default: 200.0).
+
+*--animation-dampening*::
+ Dampening (a.k.a. friction) parameter for spring-based animation (default: 25.0).
+
+*--animation-window-mass*::
+ Mass parameter for spring-based animation (default: 1.0).
+
+*--animation-clamping*::
+ Whether to clamp animations (default: true).
+
+ **NOTE:** With clamping disabled, on very low performance conditions (e.g., over 100ms to render an animation frame), windows may diverge. If this is your case, it is strongly advised to keep clamping on, as it protects against that.
+
+*-i*, *--inactive-opacity*='OPACITY'::
+ Opacity of inactive windows. (0.1 - 1.0, defaults to 1.0)
+
+*-e*, *--frame-opacity*='OPACITY'::
+ Opacity of window titlebars and borders. (0.1 - 1.0, disabled by default)
+
+*-b*, *--daemon*::
+ Daemonize process. Fork to background after initialization. This option can only be set from the command line, setting this in the configuration file will have no effect.
+
+*--log-level*::
+ Set the log level. Possible values are "TRACE", "DEBUG", "INFO", "WARN", "ERROR", in increasing level of importance. Case doesn't matter. If using the "TRACE" log level, it's better to log into a file using *--log-file*, since it can generate a huge stream of logs.
+
+*--log-file*::
+ Set the log file. If *--log-file* is never specified, logs will be written to stderr. Otherwise, logs will to written to the given file, though some of the early logs might still be written to the stderr. When setting this option from the config file, it is recommended to use an absolute path.
+
+*--experimental-backends*::
+ Use the new, reimplemented version of the backends. The new backends are HIGHLY UNSTABLE at this point, you have been warned. This option is not available in the config file.
+
+*--show-all-xerrors*::
+ Show all X errors (for debugging).
+
+*--config* 'PATH'::
+ Look for configuration file at the path. See *CONFIGURATION FILES* section below for where picom looks for a configuration file by default. Use `/dev/null` to avoid loading configuration file.
+
+*--write-pid-path* 'PATH'::
+ Write process ID to a file. it is recommended to use an absolute path.
+
+*--shadow-color* 'STRING'::
+ Color of shadow, as a hex string ('#000000')
+
+*--shadow-red* 'VALUE'::
+ Red color value of shadow (0.0 - 1.0, defaults to 0).
+
+*--shadow-green* 'VALUE'::
+ Green color value of shadow (0.0 - 1.0, defaults to 0).
+
+*--shadow-blue* 'VALUE'::
+ Blue color value of shadow (0.0 - 1.0, defaults to 0).
+
+*--inactive-opacity-override*::
+ Let inactive opacity set by *-i* override the '_NET_WM_WINDOW_OPACITY' values of windows.
+
+*--active-opacity* 'OPACITY'::
+ Default opacity for active windows. (0.0 - 1.0, defaults to 1.0)
+
+*--inactive-dim* 'VALUE'::
+ Dim inactive windows. (0.0 - 1.0, defaults to 0.0)
+
+*--corner-radius* 'VALUE'::
+ Sets the radius of rounded window corners. When > 0, the compositor will round the corners of windows. Does not interact well with *--transparent-clipping*. (defaults to 0).
+
+*--rounded-corners-exclude* 'CONDITION'::
+ Exclude conditions for rounded corners.
+
+*--mark-wmwin-focused*::
+ Try to detect WM windows (a non-override-redirect window with no child that has 'WM_STATE') and mark them as active.
+
+*--mark-ovredir-focused*::
+ Mark override-redirect windows that doesn't have a child window with 'WM_STATE' focused.
+
+*--no-fading-openclose*::
+ Do not fade on window open/close.
+
+*--no-fading-destroyed-argb*::
+ Do not fade destroyed ARGB windows with WM frame. Workaround of bugs in Openbox, Fluxbox, etc.
+
+*--shadow-ignore-shaped*::
+ Do not paint shadows on shaped windows. Note shaped windows here means windows setting its shape through X Shape extension. Those using ARGB background is beyond our control. Deprecated, use `--shadow-exclude 'bounding_shaped'` or `--shadow-exclude 'bounding_shaped && !rounded_corners'` instead.
+
+*--detect-rounded-corners*::
+ Try to detect windows with rounded corners and don't consider them shaped windows. The accuracy is not very high, unfortunately.
+
+*--detect-client-opacity*::
+ Detect '_NET_WM_WINDOW_OPACITY' on client windows, useful for window managers not passing '_NET_WM_WINDOW_OPACITY' of client windows to frame windows.
+
+*--vsync*, *--no-vsync*::
+ Enable/disable VSync.
+
+*--use-ewmh-active-win*::
+ Use EWMH '_NET_ACTIVE_WINDOW' to determine currently focused window, rather than listening to 'FocusIn'/'FocusOut' event. Might have more accuracy, provided that the WM supports it.
+
+*--unredir-if-possible*::
+ Unredirect all windows if a full-screen opaque window is detected, to maximize performance for full-screen windows. Known to cause flickering when redirecting/unredirecting windows.
+
+*--unredir-if-possible-delay* 'MILLISECONDS'::
+ Delay before unredirecting the window, in milliseconds. Defaults to 0.
+
+*--unredir-if-possible-exclude* 'CONDITION'::
+ Conditions of windows that shouldn't be considered full-screen for unredirecting screen.
+
+*--shadow-exclude* 'CONDITION'::
+ Specify a list of conditions of windows that should have no shadow.
+
+*--clip-shadow-above* 'CONDITION'::
+ Specify a list of conditions of windows that should have no shadow painted over, such as a dock window.
+
+*--fade-exclude* 'CONDITION'::
+ Specify a list of conditions of windows that should not be faded.
+
+*--focus-exclude* 'CONDITION'::
+ Specify a list of conditions of windows that should always be considered focused.
+
+*--inactive-dim-fixed*::
+ Use fixed inactive dim value, instead of adjusting according to window opacity.
+
+*--detect-transient*::
+ Use 'WM_TRANSIENT_FOR' to group windows, and consider windows in the same group focused at the same time.
+
+*--detect-client-leader*::
+ Use 'WM_CLIENT_LEADER' to group windows, and consider windows in the same group focused at the same time. This usually means windows from the same application will be considered focused or unfocused at the same time.'WM_TRANSIENT_FOR' has higher priority if *--detect-transient* is enabled, too.
+
+*--blur-method*, *--blur-size*, *--blur-deviation*, *--blur-strength*::
+ Parameters for background blurring, see the *BLUR* section for more information.
+
+*--blur-background*::
+ Blur background of semi-transparent / ARGB windows. Bad in performance, with driver-dependent behavior. The name of the switch may change without prior notifications.
+
+*--blur-background-frame*::
+ Blur background of windows when the window frame is not opaque. Implies *--blur-background*. Bad in performance, with driver-dependent behavior. The name may change.
+
+*--blur-background-fixed*::
+ Use fixed blur strength rather than adjusting according to window opacity.
+
+*--blur-kern* 'MATRIX'::
+ Specify the blur convolution kernel, with the following format:
++
+----
+WIDTH,HEIGHT,ELE1,ELE2,ELE3,ELE4,ELE5...
+----
++
+In other words, the matrix is formatted as a list of comma separated numbers. The first two numbers must be integers, which specify the width and height of the matrix. They must be odd numbers. Then, the following 'width * height - 1' numbers specifies the numbers in the matrix, row by row, excluding the center element.
++
+The elements are finite floating point numbers. The decimal pointer has to be '.' (a period), scientific notation is not supported.
++
+The element in the center will either be 1.0 or varying based on opacity, depending on whether you have *--blur-background-fixed*. Yet the automatic adjustment of blur factor may not work well with a custom blur kernel.
++
+A 7x7 Gaussian blur kernel (sigma = 0.84089642) looks like:
++
+----
+--blur-kern '7,7,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000102,0.003494,0.029143,0.059106,0.029143,0.003494,0.000102,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.001723,0.059106,0.493069,0.493069,0.059106,0.001723,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000102,0.003494,0.029143,0.059106,0.029143,0.003494,0.000102,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003'
+----
++
+May also be one of the predefined kernels: `3x3box` (default), `5x5box`, `7x7box`, `3x3gaussian`, `5x5gaussian`, `7x7gaussian`, `9x9gaussian`, `11x11gaussian`. All Gaussian kernels are generated with sigma = 0.84089642 . If you find yourself needing to generate custom blur kernels, you might want to try the new blur configuration supported by the experimental backends (See *BLUR* and *--experimental-backends*).
+
+*--blur-background-exclude* 'CONDITION'::
+ Exclude conditions for background blur.
+
+*--resize-damage* 'INTEGER'::
+ Resize damaged region by a specific number of pixels. A positive value enlarges it while a negative one shrinks it. If the value is positive, those additional pixels will not be actually painted to screen, only used in blur calculation, and such. (Due to technical limitations, with *--use-damage*, those pixels will still be incorrectly painted to screen.) Primarily used to fix the line corruption issues of blur, in which case you should use the blur radius value here (e.g. with a 3x3 kernel, you should use `--resize-damage 1`, with a 5x5 one you use `--resize-damage 2`, and so on). May or may not work with *--glx-no-stencil*. Shrinking doesn't function correctly.
+
+*--invert-color-include* 'CONDITION'::
+ Specify a list of conditions of windows that should be painted with inverted color. Resource-hogging, and is not well tested.
+
+*--opacity-rule* 'OPACITY':'CONDITION'::
+ Specify a list of opacity rules, in the format `PERCENT:PATTERN`, like `50:name *= "Firefox"`. picom-trans is recommended over this. Note we don't make any guarantee about possible conflicts with other programs that set '_NET_WM_WINDOW_OPACITY' on frame or client windows.
+
+*--shadow-exclude-reg* 'GEOMETRY'::
+ Specify a X geometry that describes the region in which shadow should not be painted in, such as a dock window region. Use `--shadow-exclude-reg x10+0-0`, for example, if the 10 pixels on the bottom of the screen should not have shadows painted on.
+
+*--xinerama-shadow-crop*::
+ Crop shadow of a window fully on a particular Xinerama screen to the screen.
+
+*--backend* 'BACKEND'::
+ Specify the backend to use: `xrender`, `glx`, or `xr_glx_hybrid`. `xrender` is the default one.
++
+--
+* `xrender` backend performs all rendering operations with X Render extension. It is what `xcompmgr` uses, and is generally a safe fallback when you encounter rendering artifacts or instability.
+* `glx` (OpenGL) backend performs all rendering operations with OpenGL. It is more friendly to some VSync methods, and has significantly superior performance on color inversion (*--invert-color-include*) or blur (*--blur-background*). It requires proper OpenGL 2.0 support from your driver and hardware. You may wish to look at the GLX performance optimization options below. *--xrender-sync-fence* might be needed on some systems to avoid delay in changes of screen contents.
+* `xr_glx_hybrid` backend renders the updated screen contents with X Render and presents it on the screen with GLX. It attempts to address the rendering issues some users encountered with GLX backend and enables the better VSync of GLX backends. *--vsync-use-glfinish* might fix some rendering issues with this backend.
+--
+
+*--glx-no-stencil*::
+ GLX backend: Avoid using stencil buffer, useful if you don't have a stencil buffer. Might cause incorrect opacity when rendering transparent content (but never practically happened) and may not work with *--blur-background*. My tests show a 15% performance boost. Recommended.
+
+*--glx-no-rebind-pixmap*::
+ GLX backend: Avoid rebinding pixmap on window damage. Probably could improve performance on rapid window content changes, but is known to break things on some drivers (LLVMpipe, xf86-video-intel, etc.). Recommended if it works.
+
+*--no-use-damage*::
+ Disable the use of damage information. This cause the whole screen to be redrawn everytime, instead of the part of the screen has actually changed. Potentially degrades the performance, but might fix some artifacts.
+
+*--xrender-sync-fence*::
+ Use X Sync fence to sync clients' draw calls, to make sure all draw calls are finished before picom starts drawing. Needed on nvidia-drivers with GLX backend for some users.
+
+*--glx-fshader-win* 'SHADER'::
+ GLX backend: Use specified GLSL fragment shader for rendering window contents. See `compton-default-fshader-win.glsl` and `compton-fake-transparency-fshader-win.glsl` in the source tree for examples.
+
+*--force-win-blend*::
+ Force all windows to be painted with blending. Useful if you have a *--glx-fshader-win* that could turn opaque pixels transparent.
+
+*--dbus*::
+ Enable remote control via D-Bus. See the *D-BUS API* section below for more details.
+
+*--benchmark* 'CYCLES'::
+ Benchmark mode. Repeatedly paint until reaching the specified cycles.
+
+*--benchmark-wid* 'WINDOW_ID'::
+ Specify window ID to repaint in benchmark mode. If omitted or is 0, the whole screen is repainted.
+
+*--no-ewmh-fullscreen*::
+ Do not use EWMH to detect fullscreen windows. Reverts to checking if a window is fullscreen based only on its size and coordinates.
+
+*--max-brightness*::
+ Dimming bright windows so their brightness doesn't exceed this set value. Brightness of a window is estimated by averaging all pixels in the window, so this could comes with a performance hit. Setting this to 1.0 disables this behaviour. Requires *--use-damage* to be disabled. (default: 1.0)
+
+*--transparent-clipping*::
+ Make transparent windows clip other windows like non-transparent windows do, instead of blending on top of them.
+
+FORMAT OF CONDITIONS
+--------------------
+Some options accept a condition string to match certain windows. A condition string is formed by one or more conditions, joined by logical operators.
+
+A condition with "exists" operator looks like this:
+
+ [] :
+
+With equals operator it looks like:
+
+ [] : =
+
+With greater-than/less-than operators it looks like:
+
+ [] :
+
+'NEGATION' (optional) is one or more exclamation marks;
+
+'TARGET' is either a predefined target name, or the name of a window property to match. Supported predefined targets are `id`, `x`, `y`, `x2` (`x` + `widthb`), `y2` (like `x2`), `width`, `height`, `widthb` (`width` + 2 * `border_width`), `heightb` (like `widthb`), `border_width`, `fullscreen`, `override_redirect`, `argb` (whether the window has an ARGB visual), `focused`, `wmwin` (whether the window looks like a WM window, i.e. has no child window with `WM_STATE` and is not override-redirected), `bounding_shaped`, `rounded_corners` (requires *--detect-rounded-corners*), `client` (ID of client window), `window_type` (window type in string), `leader` (ID of window leader), `name`, `class_g` (= `WM_CLASS[1]`), `class_i` (= `WM_CLASS[0]`), and `role`.
+
+'CLIENT/FRAME' is a single `@` if the window attribute should be be looked up on client window, nothing if on frame window;
+
+'INDEX' (optional) is the index number of the property to look up. For example, `[2]` means look at the third value in the property. If not specified, the first value (index `[0]`) is used implicitly. Use the special value `[*]` to perform matching against all available property values using logical OR. Do not specify it for predefined targets.
+
+'FORMAT' (optional) specifies the format of the property, 8, 16, or 32. On absence we use format X reports. Do not specify it for predefined or string targets.
+
+'TYPE' is a single character representing the type of the property to match for: `c` for 'CARDINAL', `a` for 'ATOM', `w` for 'WINDOW', `d` for 'DRAWABLE', `s` for 'STRING' (and any other string types, such as 'UTF8_STRING'). Do not specify it for predefined targets.
+
+'OP QUALIFIER' (optional), applicable only for equals operator, could be `?` (ignore-case).
+
+'MATCH TYPE' (optional), applicable only for equals operator, could be nothing (exact match), `*` (match anywhere), `^` (match from start), `%` (wildcard), or `~` (PCRE regular expression).
+
+'OPERATOR' is one of `=` (equals), `<`, `>`, `<=`, `=>`, or nothing (exists). Exists operator checks whether a property exists on a window (but for predefined targets, exists means != 0 then).
+
+'PATTERN' is either an integer or a string enclosed by single or double quotes. Python-3-style escape sequences and raw string are supported in the string format.
+
+Supported logical operators are `&&` (and) and `||` (or). `&&` has higher precedence than `||`, left-to-right associativity. Use parentheses to change precedence.
+
+Examples:
+
+ # If the window is focused
+ focused
+ focused = 1
+ # If the window is not override-redirected
+ !override_redirect
+ override_redirect = false
+ override_redirect != true
+ override_redirect != 1
+ # If the window is a menu
+ window_type *= "menu"
+ _NET_WM_WINDOW_TYPE@:a *= "MENU"
+ # If the window is marked hidden: _NET_WM_STATE contains _NET_WM_STATE_HIDDEN
+ _NET_WM_STATE@[*]:a = "_NET_WM_STATE_HIDDEN"
+ # If the window is marked sticky: _NET_WM_STATE contains an atom that contains
+ # "sticky", ignore case
+ _NET_WM_STATE@[*]:a *?= "sticky"
+ # If the window name contains "Firefox", ignore case
+ name *?= "Firefox"
+ _NET_WM_NAME@:s *?= "Firefox"
+ # If the window name ends with "Firefox"
+ name %= "*Firefox"
+ name ~= "Firefox$"
+ # If the window has a property _COMPTON_SHADOW with value 0, type CARDINAL,
+ # format 32, value 0, on its frame window
+ _COMPTON_SHADOW:32c = 0
+ # If the third value of _NET_FRAME_EXTENTS is less than 20, or there's no
+ # _NET_FRAME_EXTENTS property on client window
+ _NET_FRAME_EXTENTS@[2]:32c < 20 || !_NET_FRAME_EXTENTS@:32c
+ # The pattern here will be parsed as "dd4"
+ name = "\x64\x64\o64"
+ # The pattern here will be parsed as "\x64\x64\x64"
+ name = r"\x64\x64\o64"
+
+
+LEGACY FORMAT OF CONDITIONS
+---------------------------
+
+This is the old condition format we once used. Support of this format might be removed in the future.
+
+ condition = TARGET:TYPE[FLAGS]:PATTERN
+
+'TARGET' is one of "n" (window name), "i" (window class instance), "g" (window general class), and "r" (window role).
+
+'TYPE' is one of "e" (exact match), "a" (match anywhere), "s" (match from start), "w" (wildcard), and "p" (PCRE regular expressions, if compiled with the support).
+
+'FLAGS' could be a series of flags. Currently the only defined flag is "i" (ignore case).
+
+'PATTERN' is the actual pattern string.
+
+CONFIGURATION FILES
+-------------------
+picom could read from a configuration file if libconfig support is compiled in. If *--config* is not used, picom will seek for a configuration file in `$XDG_CONFIG_HOME/picom.conf` (`~/.config/picom.conf`, usually), then `$XDG_CONFIG_HOME/picom/picom.conf`, then `$XDG_CONFIG_DIRS/picom.conf` (often `/etc/xdg/picom.conf`), then `$XDG_CONFIG_DIRS/picom/picom.conf`.
+
+picom uses general libconfig configuration file format. A sample configuration file is available as `picom.sample.conf` in the source tree. Most of commandline switches can be used as options in configuration file as well. For example, *--vsync* option documented above can be set in the configuration file using `vsync = `. Command line options will always overwrite the settings in the configuration file.
+
+Window-type-specific settings are exposed only in configuration file and has the following format:
+
+------------
+wintypes:
+{
+ WINDOW_TYPE = { fade = BOOL; shadow = BOOL; opacity = FLOAT; focus = BOOL; blur-background = BOOL; full-shadow = BOOL; clip-shadow-above = BOOL; redir-ignore = BOOL; };
+};
+------------
+
+'WINDOW_TYPE' is one of the 15 window types defined in EWMH standard: "unknown", "desktop", "dock", "toolbar", "menu", "utility", "splash", "dialog", "normal", "dropdown_menu", "popup_menu", "tooltip", "notification", "combo", and "dnd".
+
+Following per window-type options are available: ::
+
+ fade, shadow:::
+ Controls window-type-specific shadow and fade settings.
+
+ opacity:::
+ Controls default opacity of the window type.
+
+ focus:::
+ Controls whether the window of this type is to be always considered focused. (By default, all window types except "normal" and "dialog" has this on.)
+
+ blur-background:::
+ Controls wether the window of this type will have its transparent background blurred.
+
+ full-shadow:::
+ Controls whether shadow is drawn under the parts of the window that you normally won't be able to see. Useful when the window has parts of it transparent, and you want shadows in those areas.
+
+ clip-shadow-above:::
+ Controls wether shadows that would have been drawn above the window should be clipped. Useful for dock windows that should have no shadow painted on top.
+
+ redir-ignore:::
+ Controls whether this type of windows should cause screen to become redirected again after been unredirected. If you have *--unredir-if-possible* set, and doesn't want certain window to cause unnecessary screen redirection, you can set this to `true`.
+
+BLUR
+----
+You can configure how the window background is blurred using a 'blur' section in your configuration file. Here is an example:
+
+--------
+blur:
+{
+ method = "gaussian";
+ size = 10;
+ deviation = 5.0;
+};
+--------
+
+Available options of the 'blur' section are: ::
+
+ *method*:::
+ A string. Controls the blur method. Corresponds to the *--blur-method* command line option. Available choices are:
+ 'none' to disable blurring; 'gaussian' for gaussian blur; 'box' for box blur; 'kernel' for convolution blur with a custom kernel; 'dual_kawase' for dual-filter kawase blur.
+ Note: 'gaussian', 'box' and 'dual_kawase' blur methods are only supported by the experimental backends.
+ (default: none)
+
+ *size*:::
+ An integer. The size of the blur kernel, required by 'gaussian' and 'box' blur methods. For the 'kernel' method, the size is included in the kernel. Corresponds to the *--blur-size* command line option (default: 3).
+
+ *deviation*:::
+ A floating point number. The standard deviation for the 'gaussian' blur method. Corresponds to the *--blur-deviation* command line option (default: 0.84089642).
+
+ *strength*:::
+ An integer in the range 0-20. The strength of the 'dual_kawase' blur method. Corresponds to the *--blur-strength* command line option. If set to zero, the value requested by *--blur-size* is approximated (default: 5).
+
+ *kernel*:::
+ A string. The kernel to use for the 'kernel' blur method, specified in the same format as the *--blur-kerns* option. Corresponds to the *--blur-kerns* command line option.
+
+SIGNALS
+-------
+
+* picom reinitializes itself upon receiving `SIGUSR1`.
+
+D-BUS API
+---------
+
+It's possible to control picom via D-Bus messages, by running picom with *--dbus* and send messages to `com.github.chjj.compton.`. `` is the display used by picom, with all non-alphanumeric characters transformed to underscores. For `DISPLAY=:0.0` you should use `com.github.chjj.compton._0_0`, for example.
+
+The D-Bus methods and signals are not yet stable, thus undocumented right now.
+
+EXAMPLES
+--------
+
+* Disable configuration file parsing:
++
+------------
+$ picom --config /dev/null
+------------
+
+* Run picom with client-side shadow and fading:
++
+------------
+$ picom -cf
+------------
+
+* Same thing as above, plus making inactive windows 80% transparent, making frame 80% transparent, don't fade on window open/close, and fork to background:
++
+------------
+$ picom -bcf -i 0.8 -e 0.8 --no-fading-openclose
+------------
+
+* Draw white shadows:
++
+------------
+$ picom -c --shadow-red 1 --shadow-green 1 --shadow-blue 1
+------------
+
+* Avoid drawing shadows on wbar window:
++
+------------
+$ picom -c --shadow-exclude 'class_g = "wbar"'
+------------
+
+* Enable VSync with GLX backend:
++
+------------
+$ picom --backend glx --vsync
+------------
+
+BUGS
+----
+Please submit bug reports to .
+
+Out dated information in this man page is considered a bug.
+
+RESOURCES
+---------
+Homepage:
+
+SEE ALSO
+--------
+*xcompmgr*(1), link:picom-trans.html[*picom-trans*(1)]
diff --git a/dwm/picom/media/compton.svg b/dwm/picom/media/compton.svg
new file mode 100644
index 0000000..cfe1842
--- /dev/null
+++ b/dwm/picom/media/compton.svg
@@ -0,0 +1,76 @@
+
+
+
diff --git a/dwm/picom/media/icons/48x48/compton.png b/dwm/picom/media/icons/48x48/compton.png
new file mode 100644
index 0000000..8eb6320
Binary files /dev/null and b/dwm/picom/media/icons/48x48/compton.png differ
diff --git a/dwm/picom/meson.build b/dwm/picom/meson.build
new file mode 100644
index 0000000..505dba2
--- /dev/null
+++ b/dwm/picom/meson.build
@@ -0,0 +1,83 @@
+project('picom', 'c', version: '9',
+ default_options: ['c_std=c11'])
+
+cc = meson.get_compiler('c')
+
+# use project version by default
+version = 'v'+meson.project_version()
+
+# use git describe if that's available
+git = find_program('git', required: false)
+if git.found()
+ gitv = run_command('git', 'rev-parse', '--short=5', 'HEAD')
+ if gitv.returncode() == 0
+ version = 'vgit-'+gitv.stdout().strip()
+ endif
+endif
+
+add_global_arguments('-DCOMPTON_VERSION="'+version+'"', language: 'c')
+
+if get_option('buildtype') == 'release'
+ add_global_arguments('-DNDEBUG', language: 'c')
+endif
+
+if get_option('sanitize')
+ sanitizers = ['address', 'undefined']
+ if cc.has_argument('-fsanitize=integer')
+ sanitizers += ['integer']
+ endif
+ if cc.has_argument('-fsanitize=nullability')
+ sanitizers += ['nullability']
+ endif
+ add_global_arguments('-fsanitize='+','.join(sanitizers), language: 'c')
+ add_global_link_arguments('-fsanitize='+','.join(sanitizers), language: 'c')
+ if cc.has_argument('-fno-sanitize=unsigned-integer-overflow')
+ add_global_arguments('-fno-sanitize=unsigned-integer-overflow', language: 'c')
+ endif
+endif
+
+if get_option('modularize')
+ if not cc.has_argument('-fmodules')
+ error('option \'modularize\' requires clang')
+ endif
+ add_global_arguments(['-fmodules',
+ '-fmodule-map-file='+
+ meson.current_source_dir()+
+ '/src/picom.modulemap'],
+ language: 'c')
+endif
+
+add_global_arguments('-D_GNU_SOURCE', language: 'c')
+
+if cc.has_header('stdc-predef.h')
+ add_global_arguments('-DHAS_STDC_PREDEF_H', language: 'c')
+endif
+
+warns = [ 'all', 'cast-function-type', 'ignored-qualifiers', 'missing-parameter-type',
+ 'nonnull', 'shadow', 'no-type-limits', 'old-style-declaration', 'override-init',
+ 'sign-compare', 'type-limits', 'uninitialized', 'shift-negative-value',
+ 'unused-but-set-parameter', 'unused-parameter', 'implicit-fallthrough',
+ 'no-unknown-warning-option', 'no-missing-braces', 'conversion', 'empty-body' ]
+foreach w : warns
+ if cc.has_argument('-W'+w)
+ add_global_arguments('-W'+w, language: 'c')
+ endif
+endforeach
+
+test_h_dep = subproject('test.h').get_variable('test_h_dep')
+
+subdir('src')
+subdir('man')
+
+install_data('bin/picom-trans', install_dir: get_option('bindir'))
+install_data('picom.desktop', install_dir: 'share/applications')
+
+if get_option('compton')
+ install_data('compton.desktop', install_dir: 'share/applications')
+ install_data('media/icons/48x48/compton.png',
+ install_dir: 'share/icons/hicolor/48x48/apps')
+ install_data('media/compton.svg',
+ install_dir: 'share/icons/hicolor/scalable/apps')
+
+ meson.add_install_script('meson/install.sh')
+endif
diff --git a/dwm/picom/meson/install.sh b/dwm/picom/meson/install.sh
new file mode 100755
index 0000000..a591c39
--- /dev/null
+++ b/dwm/picom/meson/install.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+if [ ! -e "${MESON_INSTALL_DESTDIR_PREFIX}/bin/compton" ]; then
+ echo "Linking picom to ${MESON_INSTALL_DESTDIR_PREFIX}/bin/compton"
+ ln -s picom "${MESON_INSTALL_DESTDIR_PREFIX}/bin/compton"
+fi
+
+if [ ! -e "${MESON_INSTALL_DESTDIR_PREFIX}/bin/compton-trans" ]; then
+ echo "Linking picom-trans to ${MESON_INSTALL_DESTDIR_PREFIX}/bin/compton-trans"
+ ln -s picom-trans "${MESON_INSTALL_DESTDIR_PREFIX}/bin/compton-trans"
+fi
diff --git a/dwm/picom/meson_options.txt b/dwm/picom/meson_options.txt
new file mode 100644
index 0000000..9c3b0da
--- /dev/null
+++ b/dwm/picom/meson_options.txt
@@ -0,0 +1,18 @@
+option('sanitize', type: 'boolean', value: false, description: 'Build with sanitizers enabled (deprecated)')
+option('config_file', type: 'boolean', value: true, description: 'Enable config file support')
+option('regex', type: 'boolean', value: true, description: 'Enable regex support in window conditions')
+
+option('vsync_drm', type: 'boolean', value: false, description: 'Enable support for using drm for vsync')
+
+option('opengl', type: 'boolean', value: true, description: 'Enable features that require opengl (opengl backend, and opengl vsync methods)')
+option('dbus', type: 'boolean', value: true, description: 'Enable support for D-Bus remote control')
+
+option('xrescheck', type: 'boolean', value: false, description: 'Enable X resource leak checker (for debug only)')
+
+option('compton', type: 'boolean', value: true, description: 'Install backwards compat with compton')
+
+option('with_docs', type: 'boolean', value: false, description: 'Build documentation and man pages')
+
+option('modularize', type: 'boolean', value: false, description: 'Build with clang\'s module system')
+
+option('unittest', type: 'boolean', value: false, description: 'Enable unittests in the code')
diff --git a/dwm/picom/picom-dbus.desktop b/dwm/picom/picom-dbus.desktop
new file mode 100644
index 0000000..5f35c8e
--- /dev/null
+++ b/dwm/picom/picom-dbus.desktop
@@ -0,0 +1,11 @@
+[Desktop Entry]
+Version=1.0
+Type=Application
+NoDisplay=true
+Name=picom (dbus)
+GenericName=X compositor (dbus)
+Comment=An X compositor with dbus backend enabled
+Categories=Utility;
+Keywords=compositor;composite manager;window effects;transparency;opacity;
+TryExec=picom
+Exec=picom --dbus
diff --git a/dwm/picom/picom.desktop b/dwm/picom/picom.desktop
new file mode 100644
index 0000000..9d21f6d
--- /dev/null
+++ b/dwm/picom/picom.desktop
@@ -0,0 +1,13 @@
+[Desktop Entry]
+Version=1.0
+Type=Application
+NoDisplay=false
+Name=picom
+GenericName=X compositor
+Comment=An X compositor
+Categories=Utility;
+Keywords=compositor;composite manager;window effects;transparency;opacity;
+TryExec=picom
+Exec=picom
+# Thanks to quequotion for providing this file!
+Icon=picom
diff --git a/dwm/picom/picom.sample.conf b/dwm/picom/picom.sample.conf
new file mode 100644
index 0000000..efc04a4
--- /dev/null
+++ b/dwm/picom/picom.sample.conf
@@ -0,0 +1,455 @@
+#################################
+# Shadows #
+#################################
+
+
+# Enabled client-side shadows on windows. Note desktop windows
+# (windows with '_NET_WM_WINDOW_TYPE_DESKTOP') never get shadow,
+# unless explicitly requested using the wintypes option.
+#
+# shadow = false
+shadow = true;
+
+# The blur radius for shadows, in pixels. (defaults to 12)
+# shadow-radius = 12
+shadow-radius = 7;
+
+# The opacity of shadows. (0.0 - 1.0, defaults to 0.75)
+# shadow-opacity = .75
+
+# The left offset for shadows, in pixels. (defaults to -15)
+# shadow-offset-x = -15
+shadow-offset-x = -7;
+
+# The top offset for shadows, in pixels. (defaults to -15)
+# shadow-offset-y = -15
+shadow-offset-y = -7;
+
+# Red color value of shadow (0.0 - 1.0, defaults to 0).
+# shadow-red = 0
+
+# Green color value of shadow (0.0 - 1.0, defaults to 0).
+# shadow-green = 0
+
+# Blue color value of shadow (0.0 - 1.0, defaults to 0).
+# shadow-blue = 0
+
+# Hex string color value of shadow (#000000 - #FFFFFF, defaults to #000000). This option will override options set shadow-(red/green/blue)
+# shadow-color = "#000000"
+
+# Specify a list of conditions of windows that should have no shadow.
+#
+# examples:
+# shadow-exclude = "n:e:Notification";
+#
+# shadow-exclude = []
+shadow-exclude = [
+ "name = 'Notification'",
+ "class_g = 'Conky'",
+ "class_g ?= 'Notify-osd'",
+ "class_g = 'Cairo-clock'",
+ "_GTK_FRAME_EXTENTS@:c"
+];
+
+# Specify a list of conditions of windows that should have no shadow painted over, such as a dock window.
+# clip-shadow-above = []
+
+# Specify a X geometry that describes the region in which shadow should not
+# be painted in, such as a dock window region. Use
+# shadow-exclude-reg = "x10+0+0"
+# for example, if the 10 pixels on the bottom of the screen should not have shadows painted on.
+#
+# shadow-exclude-reg = ""
+
+# Crop shadow of a window fully on a particular Xinerama screen to the screen.
+# xinerama-shadow-crop = false
+
+
+#################################
+# Fading #
+#################################
+
+
+# Fade windows in/out when opening/closing and when opacity changes,
+# unless no-fading-openclose is used.
+# fading = false
+fading = true;
+
+# Opacity change between steps while fading in. (0.01 - 1.0, defaults to 0.028)
+# fade-in-step = 0.028
+fade-in-step = 0.03;
+
+# Opacity change between steps while fading out. (0.01 - 1.0, defaults to 0.03)
+# fade-out-step = 0.03
+fade-out-step = 0.03;
+
+# The time between steps in fade step, in milliseconds. (> 0, defaults to 10)
+# fade-delta = 10
+
+# Specify a list of conditions of windows that should not be faded.
+# fade-exclude = []
+
+# Do not fade on window open/close.
+# no-fading-openclose = false
+
+# Do not fade destroyed ARGB windows with WM frame. Workaround of bugs in Openbox, Fluxbox, etc.
+# no-fading-destroyed-argb = false
+
+
+#################################
+# Transparency / Opacity #
+#################################
+
+
+# Opacity of inactive windows. (0.1 - 1.0, defaults to 1.0)
+# inactive-opacity = 1
+inactive-opacity = 0.8;
+
+# Opacity of window titlebars and borders. (0.1 - 1.0, disabled by default)
+# frame-opacity = 1.0
+frame-opacity = 0.7;
+
+# Let inactive opacity set by -i override the '_NET_WM_WINDOW_OPACITY' values of windows.
+# inactive-opacity-override = true
+inactive-opacity-override = false;
+
+# Default opacity for active windows. (0.0 - 1.0, defaults to 1.0)
+# active-opacity = 1.0
+
+# Dim inactive windows. (0.0 - 1.0, defaults to 0.0)
+# inactive-dim = 0.0
+
+# Specify a list of conditions of windows that should never be considered focused.
+# focus-exclude = []
+focus-exclude = [ "class_g = 'Cairo-clock'" ];
+
+# Use fixed inactive dim value, instead of adjusting according to window opacity.
+# inactive-dim-fixed = 1.0
+
+# Specify a list of opacity rules, in the format `PERCENT:PATTERN`,
+# like `50:name *= "Firefox"`. picom-trans is recommended over this.
+# Note we don't make any guarantee about possible conflicts with other
+# programs that set '_NET_WM_WINDOW_OPACITY' on frame or client windows.
+# example:
+# opacity-rule = [ "80:class_g = 'URxvt'" ];
+#
+# opacity-rule = []
+
+
+#################################
+# Corners #
+#################################
+
+# Sets the radius of rounded window corners. When > 0, the compositor will
+# round the corners of windows. Does not interact well with
+# `transparent-clipping`.
+corner-radius = 0
+
+# Exclude conditions for rounded corners.
+rounded-corners-exclude = [
+ "window_type = 'dock'",
+ "window_type = 'desktop'"
+];
+
+
+#################################
+# Background-Blurring #
+#################################
+
+
+# Parameters for background blurring, see the *BLUR* section for more information.
+# blur-method =
+# blur-size = 12
+#
+# blur-deviation = false
+#
+# blur-strength = 5
+
+# Blur background of semi-transparent / ARGB windows.
+# Bad in performance, with driver-dependent behavior.
+# The name of the switch may change without prior notifications.
+#
+# blur-background = false
+
+# Blur background of windows when the window frame is not opaque.
+# Implies:
+# blur-background
+# Bad in performance, with driver-dependent behavior. The name may change.
+#
+# blur-background-frame = false
+
+
+# Use fixed blur strength rather than adjusting according to window opacity.
+# blur-background-fixed = false
+
+
+# Specify the blur convolution kernel, with the following format:
+# example:
+# blur-kern = "5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1";
+#
+# blur-kern = ""
+blur-kern = "3x3box";
+
+
+# Exclude conditions for background blur.
+# blur-background-exclude = []
+blur-background-exclude = [
+ "window_type = 'dock'",
+ "window_type = 'desktop'",
+ "_GTK_FRAME_EXTENTS@:c"
+];
+
+#################################
+# General Settings #
+#################################
+
+# Enable remote control via D-Bus. See the man page for more details.
+# dbus = true
+
+# Daemonize process. Fork to background after initialization. Causes issues with certain (badly-written) drivers.
+# daemon = false
+
+# Specify the backend to use: `xrender`, `glx`, or `xr_glx_hybrid`.
+# `xrender` is the default one.
+#
+# backend = "glx"
+backend = "xrender";
+
+# Enable/disable VSync.
+# vsync = false
+vsync = true;
+
+# Enable remote control via D-Bus. See the *D-BUS API* section below for more details.
+# dbus = false
+
+# Try to detect WM windows (a non-override-redirect window with no
+# child that has 'WM_STATE') and mark them as active.
+#
+# mark-wmwin-focused = false
+mark-wmwin-focused = true;
+
+# Mark override-redirect windows that doesn't have a child window with 'WM_STATE' focused.
+# mark-ovredir-focused = false
+mark-ovredir-focused = true;
+
+# Try to detect windows with rounded corners and don't consider them
+# shaped windows. The accuracy is not very high, unfortunately.
+#
+# detect-rounded-corners = false
+detect-rounded-corners = true;
+
+# Detect '_NET_WM_WINDOW_OPACITY' on client windows, useful for window managers
+# not passing '_NET_WM_WINDOW_OPACITY' of client windows to frame windows.
+#
+# detect-client-opacity = false
+detect-client-opacity = true;
+
+# Use EWMH '_NET_ACTIVE_WINDOW' to determine currently focused window,
+# rather than listening to 'FocusIn'/'FocusOut' event. Might have more accuracy,
+# provided that the WM supports it.
+#
+# use-ewmh-active-win = false
+
+# Unredirect all windows if a full-screen opaque window is detected,
+# to maximize performance for full-screen windows. Known to cause flickering
+# when redirecting/unredirecting windows.
+#
+# unredir-if-possible = false
+
+# Delay before unredirecting the window, in milliseconds. Defaults to 0.
+# unredir-if-possible-delay = 0
+
+# Conditions of windows that shouldn't be considered full-screen for unredirecting screen.
+# unredir-if-possible-exclude = []
+
+# Use 'WM_TRANSIENT_FOR' to group windows, and consider windows
+# in the same group focused at the same time.
+#
+# detect-transient = false
+detect-transient = true;
+
+# Use 'WM_CLIENT_LEADER' to group windows, and consider windows in the same
+# group focused at the same time. This usually means windows from the same application
+# will be considered focused or unfocused at the same time.
+# 'WM_TRANSIENT_FOR' has higher priority if detect-transient is enabled, too.
+#
+# detect-client-leader = false
+
+# Resize damaged region by a specific number of pixels.
+# A positive value enlarges it while a negative one shrinks it.
+# If the value is positive, those additional pixels will not be actually painted
+# to screen, only used in blur calculation, and such. (Due to technical limitations,
+# with use-damage, those pixels will still be incorrectly painted to screen.)
+# Primarily used to fix the line corruption issues of blur,
+# in which case you should use the blur radius value here
+# (e.g. with a 3x3 kernel, you should use `--resize-damage 1`,
+# with a 5x5 one you use `--resize-damage 2`, and so on).
+# May or may not work with *--glx-no-stencil*. Shrinking doesn't function correctly.
+#
+# resize-damage = 1
+
+# Specify a list of conditions of windows that should be painted with inverted color.
+# Resource-hogging, and is not well tested.
+#
+# invert-color-include = []
+
+# GLX backend: Avoid using stencil buffer, useful if you don't have a stencil buffer.
+# Might cause incorrect opacity when rendering transparent content (but never
+# practically happened) and may not work with blur-background.
+# My tests show a 15% performance boost. Recommended.
+#
+# glx-no-stencil = false
+
+# GLX backend: Avoid rebinding pixmap on window damage.
+# Probably could improve performance on rapid window content changes,
+# but is known to break things on some drivers (LLVMpipe, xf86-video-intel, etc.).
+# Recommended if it works.
+#
+# glx-no-rebind-pixmap = false
+
+# Disable the use of damage information.
+# This cause the whole screen to be redrawn everytime, instead of the part of the screen
+# has actually changed. Potentially degrades the performance, but might fix some artifacts.
+# The opposing option is use-damage
+#
+# no-use-damage = false
+use-damage = true;
+
+# Use X Sync fence to sync clients' draw calls, to make sure all draw
+# calls are finished before picom starts drawing. Needed on nvidia-drivers
+# with GLX backend for some users.
+#
+# xrender-sync-fence = false
+
+# GLX backend: Use specified GLSL fragment shader for rendering window contents.
+# See `compton-default-fshader-win.glsl` and `compton-fake-transparency-fshader-win.glsl`
+# in the source tree for examples.
+#
+# glx-fshader-win = ""
+
+# Force all windows to be painted with blending. Useful if you
+# have a glx-fshader-win that could turn opaque pixels transparent.
+#
+# force-win-blend = false
+
+# Do not use EWMH to detect fullscreen windows.
+# Reverts to checking if a window is fullscreen based only on its size and coordinates.
+#
+# no-ewmh-fullscreen = false
+
+# Dimming bright windows so their brightness doesn't exceed this set value.
+# Brightness of a window is estimated by averaging all pixels in the window,
+# so this could comes with a performance hit.
+# Setting this to 1.0 disables this behaviour. Requires --use-damage to be disabled. (default: 1.0)
+#
+# max-brightness = 1.0
+
+# Make transparent windows clip other windows like non-transparent windows do,
+# instead of blending on top of them.
+#
+# transparent-clipping = false
+
+# Set the log level. Possible values are:
+# "trace", "debug", "info", "warn", "error"
+# in increasing level of importance. Case doesn't matter.
+# If using the "TRACE" log level, it's better to log into a file
+# using *--log-file*, since it can generate a huge stream of logs.
+#
+# log-level = "debug"
+log-level = "warn";
+
+# Set the log file.
+# If *--log-file* is never specified, logs will be written to stderr.
+# Otherwise, logs will to written to the given file, though some of the early
+# logs might still be written to the stderr.
+# When setting this option from the config file, it is recommended to use an absolute path.
+#
+# log-file = "/path/to/your/log/file"
+
+# Show all X errors (for debugging)
+# show-all-xerrors = false
+
+# Write process ID to a file.
+# write-pid-path = "/path/to/your/log/file"
+
+# Window type settings
+#
+# 'WINDOW_TYPE' is one of the 15 window types defined in EWMH standard:
+# "unknown", "desktop", "dock", "toolbar", "menu", "utility",
+# "splash", "dialog", "normal", "dropdown_menu", "popup_menu",
+# "tooltip", "notification", "combo", and "dnd".
+#
+# Following per window-type options are available: ::
+#
+# fade, shadow:::
+# Controls window-type-specific shadow and fade settings.
+#
+# opacity:::
+# Controls default opacity of the window type.
+#
+# focus:::
+# Controls whether the window of this type is to be always considered focused.
+# (By default, all window types except "normal" and "dialog" has this on.)
+#
+# full-shadow:::
+# Controls whether shadow is drawn under the parts of the window that you
+# normally won't be able to see. Useful when the window has parts of it
+# transparent, and you want shadows in those areas.
+#
+# clip-shadow-above:::
+# Controls wether shadows that would have been drawn above the window should
+# be clipped. Useful for dock windows that should have no shadow painted on top.
+#
+# redir-ignore:::
+# Controls whether this type of windows should cause screen to become
+# redirected again after been unredirected. If you have unredir-if-possible
+# set, and doesn't want certain window to cause unnecessary screen redirection,
+# you can set this to `true`.
+#
+wintypes:
+{
+ tooltip = { fade = true; shadow = true; opacity = 0.75; focus = true; full-shadow = false; };
+ dock = { shadow = false; clip-shadow-above = true; }
+ dnd = { shadow = false; }
+ menu = { animation = "slide-down"; }
+ popup_menu = { animation = "slide-down"; opacity = 0.8; }
+ dropdown_menu = { animation = "slide-down"; opacity = 0.8; }
+ toolbar = { animation = "none"; }
+};
+
+#################################
+# Animation Settings #
+#################################
+
+animations = true;
+
+# Values can be none, auto, fly-in, zoom, squeeze, slide-up, slide-down, slide-left, slide-right
+animation-for-open-window = "squeeze";
+animation-for-transient-window = "slide-down";
+animation-for-unmap-window = "auto";
+animation-for-workspace-switch-in = "auto";
+animation-for-workspace-switch-out = "auto";
+
+# Stiffness (a.k.a. tension) parameter for spring-based animation (default: 200.0).
+animation-stiffness = 1000;
+
+# Dampening (a.k.a. friction) parameter for spring-based animation (default: 25.0).
+animation-dampening = 50;
+
+# Mass parameter for spring-based animation (default: 1.0).
+animation-window-mass = 1;
+
+# The time between steps in animation, in milliseconds. (> 0, defaults to 10).
+animation-delta = 7;
+
+# Force animations to go step by step even if cpu usage is high
+animation-force-steps = true;
+
+# Whether to clamp animations (default: true).
+#animation-clamping = false;
+
+# Specify a list of conditions of windows that should have no animations.
+animation-exclude = [
+ "class_g *= 'flameshot'",
+ "class_g *= 'i3lock'"
+];
diff --git a/dwm/picom/src/atom.c b/dwm/picom/src/atom.c
new file mode 100644
index 0000000..0272dc8
--- /dev/null
+++ b/dwm/picom/src/atom.c
@@ -0,0 +1,37 @@
+#include
+#include
+
+#include "atom.h"
+#include "common.h"
+#include "utils.h"
+#include "log.h"
+
+static inline void *atom_getter(void *ud, const char *atom_name, int *err) {
+ xcb_connection_t *c = ud;
+ xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(
+ c, xcb_intern_atom(c, 0, to_u16_checked(strlen(atom_name)), atom_name), NULL);
+
+ xcb_atom_t atom = XCB_NONE;
+ if (reply) {
+ log_debug("Atom %s is %d", atom_name, reply->atom);
+ atom = reply->atom;
+ free(reply);
+ } else {
+ log_error("Failed to intern atoms");
+ *err = 1;
+ }
+ return (void *)(intptr_t)atom;
+}
+
+/**
+ * Create a new atom structure and fetch all predefined atoms
+ */
+struct atom *init_atoms(xcb_connection_t *c) {
+ auto atoms = ccalloc(1, struct atom);
+ atoms->c = new_cache((void *)c, atom_getter, NULL);
+#define ATOM_GET(x) atoms->a##x = (xcb_atom_t)(intptr_t)cache_get(atoms->c, #x, NULL)
+ LIST_APPLY(ATOM_GET, SEP_COLON, ATOM_LIST1);
+ LIST_APPLY(ATOM_GET, SEP_COLON, ATOM_LIST2);
+#undef ATOM_GET
+ return atoms;
+}
diff --git a/dwm/picom/src/atom.h b/dwm/picom/src/atom.h
new file mode 100644
index 0000000..baf3360
--- /dev/null
+++ b/dwm/picom/src/atom.h
@@ -0,0 +1,68 @@
+#pragma once
+#include
+
+#include
+
+#include "meta.h"
+#include "cache.h"
+
+// clang-format off
+// Splitted into 2 lists because of the limitation of our macros
+#define ATOM_LIST1 \
+ _NET_WM_WINDOW_OPACITY, \
+ _NET_FRAME_EXTENTS, \
+ WM_STATE, \
+ _NET_WM_NAME, \
+ _NET_WM_PID, \
+ WM_NAME, \
+ WM_CLASS, \
+ WM_ICON_NAME, \
+ WM_TRANSIENT_FOR, \
+ WM_WINDOW_ROLE, \
+ WM_CLIENT_LEADER, \
+ WM_CLIENT_MACHINE, \
+ _NET_ACTIVE_WINDOW, \
+ _COMPTON_SHADOW, \
+ _NET_WM_WINDOW_TYPE, \
+ _NET_CURRENT_DESKTOP
+
+#define ATOM_LIST2 \
+ _NET_WM_WINDOW_TYPE_DESKTOP, \
+ _NET_WM_WINDOW_TYPE_DOCK, \
+ _NET_WM_WINDOW_TYPE_TOOLBAR, \
+ _NET_WM_WINDOW_TYPE_MENU, \
+ _NET_WM_WINDOW_TYPE_UTILITY, \
+ _NET_WM_WINDOW_TYPE_SPLASH, \
+ _NET_WM_WINDOW_TYPE_DIALOG, \
+ _NET_WM_WINDOW_TYPE_NORMAL, \
+ _NET_WM_WINDOW_TYPE_DROPDOWN_MENU, \
+ _NET_WM_WINDOW_TYPE_POPUP_MENU, \
+ _NET_WM_WINDOW_TYPE_TOOLTIP, \
+ _NET_WM_WINDOW_TYPE_NOTIFICATION, \
+ _NET_WM_WINDOW_TYPE_COMBO, \
+ _NET_WM_WINDOW_TYPE_DND, \
+ _NET_WM_STATE, \
+ _NET_WM_STATE_FULLSCREEN, \
+ _NET_WM_BYPASS_COMPOSITOR, \
+ UTF8_STRING, \
+ C_STRING
+// clang-format on
+
+#define ATOM_DEF(x) xcb_atom_t a##x
+
+struct atom {
+ struct cache *c;
+ LIST_APPLY(ATOM_DEF, SEP_COLON, ATOM_LIST1);
+ LIST_APPLY(ATOM_DEF, SEP_COLON, ATOM_LIST2);
+};
+
+struct atom *init_atoms(xcb_connection_t *);
+
+static inline xcb_atom_t get_atom(struct atom *a, const char *key) {
+ return (xcb_atom_t)(intptr_t)cache_get(a->c, key, NULL);
+}
+
+static inline void destroy_atoms(struct atom *a) {
+ cache_free(a->c);
+ free(a);
+}
diff --git a/dwm/picom/src/backend/backend.c b/dwm/picom/src/backend/backend.c
new file mode 100644
index 0000000..2ef5f03
--- /dev/null
+++ b/dwm/picom/src/backend/backend.c
@@ -0,0 +1,540 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#include
+#include
+
+#include "backend/backend.h"
+#include "common.h"
+#include "compiler.h"
+#include "config.h"
+#include "log.h"
+#include "region.h"
+#include "types.h"
+#include "win.h"
+#include "x.h"
+
+extern struct backend_operations xrender_ops, dummy_ops;
+#ifdef CONFIG_OPENGL
+extern struct backend_operations glx_ops;
+#endif
+
+struct backend_operations *backend_list[NUM_BKEND] = {
+ [BKEND_XRENDER] = &xrender_ops,
+ [BKEND_DUMMY] = &dummy_ops,
+#ifdef CONFIG_OPENGL
+ [BKEND_GLX] = &glx_ops,
+#endif
+};
+
+/**
+ * @param all_damage if true ignore damage and repaint the whole screen
+ */
+region_t get_damage(session_t *ps, bool all_damage) {
+ region_t region;
+ auto buffer_age_fn = ps->backend_data->ops->buffer_age;
+ int buffer_age = buffer_age_fn ? buffer_age_fn(ps->backend_data) : -1;
+
+ if (all_damage) {
+ buffer_age = -1;
+ }
+
+ pixman_region32_init(®ion);
+ if (buffer_age == -1 || buffer_age > ps->ndamage) {
+ pixman_region32_copy(®ion, &ps->screen_reg);
+ } else {
+ for (int i = 0; i < buffer_age; i++) {
+ auto curr = ((ps->damage - ps->damage_ring) + i) % ps->ndamage;
+ log_trace("damage index: %d, damage ring offset: %td", i, curr);
+ dump_region(&ps->damage_ring[curr]);
+ pixman_region32_union(®ion, ®ion, &ps->damage_ring[curr]);
+ }
+ pixman_region32_intersect(®ion, ®ion, &ps->screen_reg);
+ }
+ return region;
+}
+
+static void process_window_for_painting(session_t *ps, struct managed_win *w,
+ void *win_image, double additional_alpha,
+ region_t *reg_bound, region_t *reg_visible,
+ region_t *reg_paint, region_t *reg_paint_in_bound) {
+ // For window image processing, we don't have to limit the process
+ // region to damage for correctness. (see for
+ // details)
+
+ // The visible region, in window local coordinates Although we
+ // don't limit process region to damage, we provide that info in
+ // reg_visible as a hint. Since window image data outside of the
+ // damage region won't be painted onto target
+ region_t reg_visible_local;
+ {
+ // The bounding shape, in window local coordinates
+ region_t reg_bound_local;
+ pixman_region32_init(®_bound_local);
+ pixman_region32_copy(®_bound_local, reg_bound);
+ pixman_region32_translate(®_bound_local, -w->g.x, -w->g.y);
+
+ pixman_region32_init(®_visible_local);
+ pixman_region32_intersect(®_visible_local, reg_visible, reg_paint);
+ pixman_region32_translate(®_visible_local, -w->g.x, -w->g.y);
+ // Data outside of the bounding shape won't be visible,
+ // but it is not necessary to limit the image operations
+ // to the bounding shape yet. So pass that as the visible
+ // region, not the clip region.
+ pixman_region32_intersect(®_visible_local, ®_visible_local,
+ ®_bound_local);
+ pixman_region32_fini(®_bound_local);
+ }
+
+ auto new_img = ps->backend_data->ops->clone_image(ps->backend_data, win_image,
+ ®_visible_local);
+ auto reg_frame = win_get_region_frame_local_by_val(w);
+ double alpha = additional_alpha * w->opacity;
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_OPACITY, new_img, &alpha);
+ ps->backend_data->ops->image_op(ps->backend_data, IMAGE_OP_APPLY_ALPHA, new_img,
+ ®_frame, ®_visible_local,
+ (double[]){w->frame_opacity});
+ pixman_region32_fini(®_frame);
+ ps->backend_data->ops->compose(ps->backend_data, new_img, w->g.x, w->g.y,
+ w->g.x + w->widthb, w->g.y + w->heightb,
+ reg_paint_in_bound, reg_visible);
+ ps->backend_data->ops->release_image(ps->backend_data, new_img);
+ pixman_region32_fini(®_visible_local);
+}
+
+void handle_device_reset(session_t *ps) {
+ log_error("Device reset detected");
+ // Wait for reset to complete
+ // Although ideally the backend should return DEVICE_STATUS_NORMAL after a reset
+ // is completed, it's not always possible.
+ //
+ // According to ARB_robustness (emphasis mine):
+ //
+ // "If a reset status other than NO_ERROR is returned and subsequent
+ // calls return NO_ERROR, the context reset was encountered and
+ // completed. If a reset status is repeatedly returned, the context **may**
+ // be in the process of resetting."
+ //
+ // Which means it may also not be in the process of resetting. For example on
+ // AMDGPU devices, Mesa OpenGL always return CONTEXT_RESET after a reset has
+ // started, completed or not.
+ //
+ // So here we blindly wait 5 seconds and hope ourselves best of the luck.
+ sleep(5);
+
+ // Reset picom
+ log_info("Resetting picom after device reset");
+ ev_break(ps->loop, EVBREAK_ALL);
+}
+
+/// paint all windows
+void paint_all_new(session_t *ps, struct managed_win *t, bool ignore_damage) {
+ if (ps->backend_data->ops->device_status &&
+ ps->backend_data->ops->device_status(ps->backend_data) != DEVICE_STATUS_NORMAL) {
+ return handle_device_reset(ps);
+ }
+ if (ps->o.xrender_sync_fence) {
+ if (ps->xsync_exists && !x_fence_sync(ps->c, ps->sync_fence)) {
+ log_error("x_fence_sync failed, xrender-sync-fence will be "
+ "disabled from now on.");
+ xcb_sync_destroy_fence(ps->c, ps->sync_fence);
+ ps->sync_fence = XCB_NONE;
+ ps->o.xrender_sync_fence = false;
+ ps->xsync_exists = false;
+ }
+ }
+ // All painting will be limited to the damage, if _some_ of
+ // the paints bleed out of the damage region, it will destroy
+ // part of the image we want to reuse
+ region_t reg_damage;
+ if (!ignore_damage) {
+ reg_damage = get_damage(ps, ps->o.monitor_repaint || !ps->o.use_damage);
+ } else {
+ pixman_region32_init(®_damage);
+ pixman_region32_copy(®_damage, &ps->screen_reg);
+ }
+
+ if (!pixman_region32_not_empty(®_damage)) {
+ pixman_region32_fini(®_damage);
+ return;
+ }
+
+#ifdef DEBUG_REPAINT
+ static struct timespec last_paint = {0};
+#endif
+
+ //
+ // If use_damage is enabled, we MUST make sure only the damaged regions of the
+ // screen are ever touched by the compositor. The reason is that at the beginning
+ // of each render, we clear the damaged regions with the wallpaper, and nothing
+ // else. If later during the render we changed anything outside the damaged
+ // region, that won't be cleared by the next render, and will thus accumulate.
+ // (e.g. if shadow is drawn outside the damaged region, it will become thicker and
+ // thicker over time.)
+
+ /// The adjusted damaged regions
+ region_t reg_paint;
+ assert(ps->o.blur_method != BLUR_METHOD_INVALID);
+ if (ps->o.blur_method != BLUR_METHOD_NONE && ps->backend_data->ops->get_blur_size) {
+ int blur_width, blur_height;
+ ps->backend_data->ops->get_blur_size(ps->backend_blur_context,
+ &blur_width, &blur_height);
+
+ // The region of screen a given window influences will be smeared
+ // out by blur. With more windows on top of the given window, the
+ // influences region will be smeared out more.
+ //
+ // Also, blurring requires data slightly outside the area that needs
+ // to be blurred. The more semi-transparent windows are stacked on top
+ // of each other, the larger the area will be.
+ //
+ // Instead of accurately calculate how much bigger the damage
+ // region will be because of blur, we assume the worst case here.
+ // That is, the damaged window is at the bottom of the stack, and
+ // all other windows have semi-transparent background
+ int resize_factor = 1;
+ if (t) {
+ resize_factor = t->stacking_rank;
+ }
+ resize_region_in_place(®_damage, blur_width * resize_factor,
+ blur_height * resize_factor);
+ reg_paint = resize_region(®_damage, blur_width * resize_factor,
+ blur_height * resize_factor);
+ pixman_region32_intersect(®_paint, ®_paint, &ps->screen_reg);
+ pixman_region32_intersect(®_damage, ®_damage, &ps->screen_reg);
+ } else {
+ pixman_region32_init(®_paint);
+ pixman_region32_copy(®_paint, ®_damage);
+ }
+
+ // A hint to backend, the region that will be visible on screen
+ // backend can optimize based on this info
+ region_t reg_visible;
+ pixman_region32_init(®_visible);
+ pixman_region32_copy(®_visible, &ps->screen_reg);
+ if (t && !ps->o.transparent_clipping) {
+ // Calculate the region upon which the root window (wallpaper) is to be
+ // painted based on the ignore region of the lowest window, if available
+ //
+ // NOTE If transparent_clipping is enabled, transparent windows are
+ // included in the reg_ignore, but we still want to have the wallpaper
+ // beneath them, so we don't use reg_ignore for wallpaper in that case.
+ pixman_region32_subtract(®_visible, ®_visible, t->reg_ignore);
+ }
+
+ // Region on screen we don't want any shadows on
+ region_t reg_shadow_clip;
+ pixman_region32_init(®_shadow_clip);
+
+ if (ps->backend_data->ops->prepare) {
+ ps->backend_data->ops->prepare(ps->backend_data, ®_paint);
+ }
+
+ if (ps->root_image) {
+ ps->backend_data->ops->compose(ps->backend_data, ps->root_image, 0, 0,
+ ps->root_width, ps->root_height,
+ ®_paint, ®_visible);
+ } else {
+ ps->backend_data->ops->fill(ps->backend_data, (struct color){0, 0, 0, 1},
+ ®_paint);
+ }
+
+ // Windows are sorted from bottom to top
+ // Each window has a reg_ignore, which is the region obscured by all the windows
+ // on top of that window. This is used to reduce the number of pixels painted.
+ //
+ // Whether this is beneficial is to be determined XXX
+ for (auto w = t; w; w = w->prev_trans) {
+ pixman_region32_subtract(®_visible, &ps->screen_reg, w->reg_ignore);
+ assert(!(w->flags & WIN_FLAGS_IMAGE_ERROR));
+ assert(!(w->flags & WIN_FLAGS_PIXMAP_STALE));
+ assert(!(w->flags & WIN_FLAGS_PIXMAP_NONE));
+
+ // The bounding shape of the window, in global/target coordinates
+ // reminder: bounding shape contains the WM frame
+ auto reg_bound = win_get_bounding_shape_global_by_val(w);
+ auto reg_bound_no_corner =
+ win_get_bounding_shape_global_without_corners_by_val(w);
+
+ // The clip region for the current window, in global/target coordinates
+ // reg_paint_in_bound \in reg_paint
+ region_t reg_paint_in_bound;
+ pixman_region32_init(®_paint_in_bound);
+ pixman_region32_intersect(®_paint_in_bound, ®_bound, ®_paint);
+ if (ps->o.transparent_clipping) {
+ //
+ // If transparent_clipping is enabled, we need to be SURE that
+ // things are not drawn inside reg_ignore, because otherwise they
+ // will appear underneath transparent windows.
+ // So here we have make sure reg_paint_in_bound \in reg_visible
+ // There are a few other places below where this is needed as
+ // well.
+ pixman_region32_intersect(®_paint_in_bound,
+ ®_paint_in_bound, ®_visible);
+ }
+
+ // Blur window background
+ /* TODO(yshui) since the backend might change the content of the window
+ * (e.g. with shaders), we should consult the backend whether the window
+ * is transparent or not. for now we will just rely on the force_win_blend
+ * option */
+ auto real_win_mode = w->mode;
+
+ if (w->blur_background &&
+ (ps->o.force_win_blend || real_win_mode == WMODE_TRANS ||
+ (ps->o.blur_background_frame && real_win_mode == WMODE_FRAME_TRANS))) {
+ // Minimize the region we try to blur, if the window
+ // itself is not opaque, only the frame is.
+
+ double blur_opacity = 1;
+ if (w->opacity < (1.0 / MAX_ALPHA)) {
+ // Hide blur for fully transparent windows.
+ blur_opacity = 0;
+ } else if (w->state == WSTATE_MAPPING) {
+ // Gradually increase the blur intensity during
+ // fading in.
+ assert(w->opacity <= w->opacity_target);
+ blur_opacity = w->opacity / w->opacity_target;
+ } else if (w->state == WSTATE_UNMAPPING ||
+ w->state == WSTATE_DESTROYING) {
+ // Gradually decrease the blur intensity during
+ // fading out.
+ assert(w->opacity <= w->opacity_target_old);
+ blur_opacity = w->opacity / w->opacity_target_old;
+ } else if (w->state == WSTATE_FADING) {
+ if (w->opacity < w->opacity_target &&
+ w->opacity_target_old < (1.0 / MAX_ALPHA)) {
+ // Gradually increase the blur intensity during
+ // fading in.
+ assert(w->opacity <= w->opacity_target);
+ blur_opacity = w->opacity / w->opacity_target;
+ } else if (w->opacity > w->opacity_target &&
+ w->opacity_target < (1.0 / MAX_ALPHA)) {
+ // Gradually decrease the blur intensity during
+ // fading out.
+ assert(w->opacity <= w->opacity_target_old);
+ blur_opacity = w->opacity / w->opacity_target_old;
+ }
+ }
+ assert(blur_opacity >= 0 && blur_opacity <= 1);
+
+ if (real_win_mode == WMODE_TRANS || ps->o.force_win_blend) {
+ // We need to blur the bounding shape of the window
+ // (reg_paint_in_bound = reg_bound \cap reg_paint)
+ ps->backend_data->ops->blur(
+ ps->backend_data, blur_opacity, ps->backend_blur_context,
+ ®_paint_in_bound, ®_visible);
+ } else {
+ // Window itself is solid, we only need to blur the frame
+ // region
+
+ // Readability assertions
+ assert(ps->o.blur_background_frame);
+ assert(real_win_mode == WMODE_FRAME_TRANS);
+
+ auto reg_blur = win_get_region_frame_local_by_val(w);
+ pixman_region32_translate(®_blur, w->g.x, w->g.y);
+ // make sure reg_blur \in reg_paint
+ pixman_region32_intersect(®_blur, ®_blur, ®_paint);
+ if (ps->o.transparent_clipping) {
+ // ref:
+ pixman_region32_intersect(®_blur, ®_blur,
+ ®_visible);
+ }
+ ps->backend_data->ops->blur(ps->backend_data, blur_opacity,
+ ps->backend_blur_context,
+ ®_blur, ®_visible);
+ pixman_region32_fini(®_blur);
+ }
+ }
+
+ // Draw shadow on target
+ if (w->shadow) {
+ assert(!(w->flags & WIN_FLAGS_SHADOW_NONE));
+ // Clip region for the shadow
+ // reg_shadow \in reg_paint
+ auto reg_shadow = win_extents_by_val(w);
+ pixman_region32_intersect(®_shadow, ®_shadow, ®_paint);
+ if (!ps->o.wintype_option[w->window_type].full_shadow) {
+ pixman_region32_subtract(®_shadow, ®_shadow,
+ ®_bound_no_corner);
+ }
+
+ // Mask out the region we don't want shadow on
+ if (pixman_region32_not_empty(&ps->shadow_exclude_reg)) {
+ pixman_region32_subtract(®_shadow, ®_shadow,
+ &ps->shadow_exclude_reg);
+ }
+ if (pixman_region32_not_empty(®_shadow_clip)) {
+ pixman_region32_subtract(®_shadow, ®_shadow,
+ ®_shadow_clip);
+ }
+
+ if (ps->o.xinerama_shadow_crop && w->xinerama_scr >= 0 &&
+ w->xinerama_scr < ps->xinerama_nscrs) {
+ // There can be a window where number of screens is
+ // updated, but the screen number attached to the windows
+ // have not.
+ //
+ // Window screen number will be updated eventually, so
+ // here we just check to make sure we don't access out of
+ // bounds.
+ pixman_region32_intersect(
+ ®_shadow, ®_shadow,
+ &ps->xinerama_scr_regs[w->xinerama_scr]);
+ }
+
+ if (ps->o.transparent_clipping) {
+ // ref:
+ pixman_region32_intersect(®_shadow, ®_shadow,
+ ®_visible);
+ }
+
+ assert(w->shadow_image);
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_OPACITY, w->shadow_image,
+ &w->opacity);
+
+ ps->backend_data->ops->compose(
+ ps->backend_data, w->shadow_image, w->g.x + w->shadow_dx,
+ w->g.y + w->shadow_dy, w->g.x + w->shadow_dx + w->shadow_width,
+ w->g.y + w->shadow_dy + w->shadow_height, ®_shadow,
+ ®_visible);
+ pixman_region32_fini(®_shadow);
+ }
+
+ // Update image properties
+ {
+ double dim_opacity = 0.0;
+ if (w->dim) {
+ dim_opacity = ps->o.inactive_dim;
+ if (!ps->o.inactive_dim_fixed) {
+ dim_opacity *= w->opacity;
+ }
+ }
+
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_MAX_BRIGHTNESS, w->win_image,
+ &ps->o.max_brightness);
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_INVERTED, w->win_image,
+ &w->invert_color);
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_DIM_LEVEL, w->win_image,
+ &dim_opacity);
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_OPACITY, w->win_image, &w->opacity);
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_CORNER_RADIUS, w->win_image,
+ (double[]){w->corner_radius});
+ if (w->corner_radius) {
+ int border_width = w->g.border_width;
+ if (border_width == 0) {
+ // Some WM has borders implemented as WM frames
+ border_width = min3(w->frame_extents.left,
+ w->frame_extents.right,
+ w->frame_extents.bottom);
+ }
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_BORDER_WIDTH,
+ w->win_image, &border_width);
+ if (w->old_win_image) {
+ // TODO(dccsillag): explain why the following is
+ // "necessary"
+ double zero = 0.0;
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_BORDER_WIDTH,
+ w->old_win_image, &zero);
+ ps->backend_data->ops->set_image_property(
+ ps->backend_data, IMAGE_PROPERTY_CORNER_RADIUS,
+ w->old_win_image, &zero);
+ }
+ }
+ }
+
+ if (w->opacity * MAX_ALPHA < 1) {
+ // We don't need to paint the window body itself if it's
+ // completely transparent.
+ goto skip;
+ }
+
+ if (w->clip_shadow_above) {
+ // Add window bounds to shadow-clip region
+ pixman_region32_union(®_shadow_clip, ®_shadow_clip, ®_bound);
+ } else {
+ // Remove overlapping window bounds from shadow-clip region
+ pixman_region32_subtract(®_shadow_clip, ®_shadow_clip, ®_bound);
+ }
+
+ // Draw window on target
+ bool is_animating = 0 <= w->animation_progress && w->animation_progress < 1.0;
+ if (w->frame_opacity == 1 && !is_animating) {
+ ps->backend_data->ops->compose(ps->backend_data, w->win_image,
+ w->g.x, w->g.y,
+ w->g.x + w->widthb, w->g.y + w->heightb,
+ ®_paint_in_bound, ®_visible);
+ } else {
+ process_window_for_painting(
+ ps, w, w->win_image, 1.0, ®_bound, ®_visible,
+ ®_paint, ®_paint_in_bound);
+
+ if (w->old_win_image) {
+ bool resizing =
+ w->g.width != w->pending_g.width ||
+ w->g.height != w->pending_g.height;
+
+ // Only do this if size changes as otherwise moving
+ // transparent windows will flicker
+ if (resizing) {
+ assert(w->old_win_image);
+
+ process_window_for_painting(ps, w, w->old_win_image,
+ 1.0 - w->animation_progress,
+ ®_bound, ®_visible,
+ ®_paint, ®_paint_in_bound);
+ }
+ }
+ }
+ skip:
+ pixman_region32_fini(®_bound);
+ pixman_region32_fini(®_bound_no_corner);
+ pixman_region32_fini(®_paint_in_bound);
+ }
+ pixman_region32_fini(®_paint);
+ pixman_region32_fini(®_shadow_clip);
+
+ if (ps->o.monitor_repaint) {
+ const struct color DEBUG_COLOR = {0.5, 0, 0, 0.5};
+ auto reg_damage_debug = get_damage(ps, false);
+ ps->backend_data->ops->fill(ps->backend_data, DEBUG_COLOR, ®_damage_debug);
+ pixman_region32_fini(®_damage_debug);
+ }
+
+ // Move the head of the damage ring
+ ps->damage = ps->damage - 1;
+ if (ps->damage < ps->damage_ring) {
+ ps->damage = ps->damage_ring + ps->ndamage - 1;
+ }
+ pixman_region32_clear(ps->damage);
+
+ if (ps->backend_data->ops->present) {
+ // Present the rendered scene
+ // Vsync is done here
+ ps->backend_data->ops->present(ps->backend_data, ®_damage);
+ }
+
+ pixman_region32_fini(®_damage);
+
+#ifdef DEBUG_REPAINT
+ struct timespec now = get_time_timespec();
+ struct timespec diff = {0};
+ timespec_subtract(&diff, &now, &last_paint);
+ log_trace("[ %5ld:%09ld ] ", diff.tv_sec, diff.tv_nsec);
+ last_paint = now;
+ log_trace("paint:");
+ for (win *w = t; w; w = w->prev_trans)
+ log_trace(" %#010lx", w->id);
+#endif
+}
+
+// vim: set noet sw=8 ts=8 :
diff --git a/dwm/picom/src/backend/backend.h b/dwm/picom/src/backend/backend.h
new file mode 100644
index 0000000..5652a36
--- /dev/null
+++ b/dwm/picom/src/backend/backend.h
@@ -0,0 +1,294 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) 2018, Yuxuan Shui
+
+#pragma once
+
+#include
+
+#include "compiler.h"
+#include "config.h"
+#include "driver.h"
+#include "kernel.h"
+#include "region.h"
+#include "types.h"
+#include "x.h"
+
+typedef struct session session_t;
+struct managed_win;
+
+struct ev_loop;
+struct backend_operations;
+
+typedef struct backend_base {
+ struct backend_operations *ops;
+ xcb_connection_t *c;
+ xcb_window_t root;
+ struct ev_loop *loop;
+
+ /// Whether the backend can accept new render request at the moment
+ bool busy;
+ // ...
+} backend_t;
+
+typedef void (*backend_ready_callback_t)(void *);
+
+// This mimics OpenGL's ARB_robustness extension, which enables detection of GPU context
+// resets.
+// See: https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_robustness.txt, section
+// 2.6 "Graphics Reset Recovery".
+enum device_status {
+ DEVICE_STATUS_NORMAL,
+ DEVICE_STATUS_RESETTING,
+};
+
+// When image properties are actually applied to the image, they are applied in a
+// particular order:
+//
+// Color inversion -> Dimming -> Opacity multiply -> Limit maximum brightness
+// (Corner radius could be applied in any order)
+enum image_properties {
+ // Whether the color of the image is inverted
+ // 1 boolean, default: false
+ IMAGE_PROPERTY_INVERTED,
+ // How much the image is dimmed
+ // 1 double, default: 0
+ IMAGE_PROPERTY_DIM_LEVEL,
+ // Image opacity, i.e. an alpha value multiplied to the alpha channel
+ // 1 double, default: 1
+ IMAGE_PROPERTY_OPACITY,
+ // The effective size of the image, the image will be tiled to fit.
+ // 2 int, default: the actual size of the image
+ IMAGE_PROPERTY_EFFECTIVE_SIZE,
+ // Limit how bright image can be. The image brightness is estimated by averaging
+ // the pixels in the image, and dimming will be applied to scale the average
+ // brightness down to the max brightness value.
+ // 1 double, default: 1
+ IMAGE_PROPERTY_MAX_BRIGHTNESS,
+ // Gives the image a rounded corner.
+ // 1 double, default: 0
+ IMAGE_PROPERTY_CORNER_RADIUS,
+ // Border width
+ // 1 int, default: 0
+ IMAGE_PROPERTY_BORDER_WIDTH,
+};
+
+enum image_operations {
+ // Multiply the alpha channel by the argument
+ IMAGE_OP_APPLY_ALPHA,
+};
+
+struct gaussian_blur_args {
+ int size;
+ double deviation;
+};
+
+struct box_blur_args {
+ int size;
+};
+
+struct kernel_blur_args {
+ struct conv **kernels;
+ int kernel_count;
+};
+
+struct dual_kawase_blur_args {
+ int size;
+ int strength;
+};
+
+struct backend_operations {
+ // =========== Initialization ===========
+
+ /// Initialize the backend, prepare for rendering to the target window.
+ /// Here is how you should choose target window:
+ /// 1) if ps->overlay is not XCB_NONE, use that
+ /// 2) use ps->root otherwise
+ // TODO(yshui) make the target window a parameter
+ backend_t *(*init)(session_t *)attr_nonnull(1);
+ void (*deinit)(backend_t *backend_data) attr_nonnull(1);
+
+ /// Called when rendering will be stopped for an unknown amount of
+ /// time (e.g. when screen is unredirected). Free some resources.
+ ///
+ /// Optional, not yet used
+ void (*pause)(backend_t *backend_data, session_t *ps);
+
+ /// Called before rendering is resumed
+ ///
+ /// Optional, not yet used
+ void (*resume)(backend_t *backend_data, session_t *ps);
+
+ /// Called when root property changed, returns the new
+ /// backend_data. Even if the backend_data changed, all
+ /// the existing image data returned by this backend should
+ /// remain valid.
+ ///
+ /// Optional
+ void *(*root_change)(backend_t *backend_data, session_t *ps);
+
+ // =========== Rendering ============
+
+ // NOTE: general idea about reg_paint/reg_op vs reg_visible is that reg_visible is
+ // merely a hint. Ignoring reg_visible entirely don't affect the correctness of
+ // the operation performed. OTOH reg_paint/reg_op is part of the parameters of the
+ // operation, and must be honored in order to complete the operation correctly.
+
+ // NOTE: due to complications introduced by use-damage and blur, the rendering API
+ // is a bit weird. The idea is, `compose` and `blur` have to update a temporary
+ // buffer, because `blur` requires data from an area slightly larger than the area
+ // that will be visible. So the area outside the visible area has to be rendered,
+ // but we have to discard the result (because the result of blurring that area
+ // will be wrong). That's why we cannot render into the back buffer directly.
+ // After rendering is done, `present` is called to update a portion of the actual
+ // back buffer, then present it to the target (or update the target directly,
+ // if not back buffered).
+
+ /// Called before when a new frame starts.
+ ///
+ /// Optional
+ void (*prepare)(backend_t *backend_data, const region_t *reg_damage);
+
+ /**
+ * Paint the content of an image onto the rendering buffer
+ *
+ * @param backend_data the backend data
+ * @param image_data the image to paint
+ * @param dst_x1, dst_y1 the top left corner of the image in the target
+ * @param dst_x2, dst_y2 the top right corner of the image in the target
+ * @param reg_paint the clip region, in target coordinates
+ * @param reg_visible the visible region, in target coordinates
+ */
+ void (*compose)(backend_t *backend_data, void *image_data,
+ int dst_x1, int dst_y1, int dst_x2, int dst_y2,
+ const region_t *reg_paint, const region_t *reg_visible);
+
+ /// Fill rectangle of the rendering buffer, mostly for debug purposes, optional.
+ void (*fill)(backend_t *backend_data, struct color, const region_t *clip);
+
+ /// Blur a given region of the rendering buffer.
+ bool (*blur)(backend_t *backend_data, double opacity, void *blur_ctx,
+ const region_t *reg_blur, const region_t *reg_visible)
+ attr_nonnull(1, 3, 4, 5);
+
+ /// Update part of the back buffer with the rendering buffer, then present the
+ /// back buffer onto the target window (if not back buffered, update part of the
+ /// target window directly).
+ ///
+ /// Optional, if NULL, indicates the backend doesn't have render output
+ ///
+ /// @param region part of the target that should be updated
+ void (*present)(backend_t *backend_data, const region_t *region) attr_nonnull(1, 2);
+
+ /**
+ * Bind a X pixmap to the backend's internal image data structure.
+ *
+ * @param backend_data backend data
+ * @param pixmap X pixmap to bind
+ * @param fmt information of the pixmap's visual
+ * @param owned whether the ownership of the pixmap is transfered to the backend
+ * @return backend internal data structure bound with this pixmap
+ */
+ void *(*bind_pixmap)(backend_t *backend_data, xcb_pixmap_t pixmap,
+ struct xvisual_info fmt, bool owned);
+
+ /// Create a shadow image based on the parameters
+ /// Default implementation: default_backend_render_shadow
+ void *(*render_shadow)(backend_t *backend_data, int width, int height,
+ const conv *kernel, double r, double g, double b, double a);
+
+ // ============ Resource management ===========
+
+ /// Free resources associated with an image data structure
+ void (*release_image)(backend_t *backend_data, void *img_data) attr_nonnull(1, 2);
+
+ // =========== Query ===========
+
+ /// Return if image is not completely opaque.
+ ///
+ /// This function is needed because some backend might change the content of the
+ /// window (e.g. when using a custom shader with the glx backend), so only the
+ /// backend knows if an image is transparent.
+ bool (*is_image_transparent)(backend_t *backend_data, void *image_data)
+ attr_nonnull(1, 2);
+
+ /// Get the age of the buffer content we are currently rendering ontop
+ /// of. The buffer that has just been `present`ed has a buffer age of 1.
+ /// Everytime `present` is called, buffers get older. Return -1 if the
+ /// buffer is empty.
+ ///
+ /// Optional
+ int (*buffer_age)(backend_t *backend_data);
+
+ /// The maximum number buffer_age might return.
+ int max_buffer_age;
+
+ // =========== Post-processing ============
+
+ /* TODO(yshui) Consider preserving the order of image ops.
+ * Currently in both backends, the image ops are applied lazily when needed.
+ * However neither backends preserve the order of image ops, they just applied all
+ * pending lazy ops in a pre-determined fixed order, regardless in which order
+ * they were originally applied. This might lead to inconsistencies.*/
+
+ /**
+ * Change image properties
+ *
+ * @param backend_data backend data
+ * @param prop the property to change
+ * @param image_data an image data structure returned by the backend
+ * @param args property value
+ * @return whether the operation is successful
+ */
+ bool (*set_image_property)(backend_t *backend_data, enum image_properties prop,
+ void *image_data, void *args);
+
+ /**
+ * Manipulate an image. Image properties are untouched.
+ *
+ * @param backend_data backend data
+ * @param op the operation to perform
+ * @param image_data an image data structure returned by the backend
+ * @param reg_op the clip region, define the part of the image to be
+ * operated on.
+ * @param reg_visible define the part of the image that will eventually
+ * be visible on target. this is a hint to the backend
+ * for optimization purposes.
+ * @param args extra arguments, operation specific
+ * @return whether the operation is successful
+ */
+ bool (*image_op)(backend_t *backend_data, enum image_operations op, void *image_data,
+ const region_t *reg_op, const region_t *reg_visible, void *args);
+
+ /// Create another instance of the `image_data`. All `image_op` and
+ /// `set_image_property` calls on the returned image should not affect the
+ /// original image
+ void *(*clone_image)(backend_t *base, const void *image_data,
+ const region_t *reg_visible);
+
+ /// Create a blur context that can be used to call `blur`
+ void *(*create_blur_context)(backend_t *base, enum blur_method, void *args);
+ /// Destroy a blur context
+ void (*destroy_blur_context)(backend_t *base, void *ctx);
+ /// Get how many pixels outside of the blur area is needed for blur
+ void (*get_blur_size)(void *blur_context, int *width, int *height);
+
+ // =========== Hooks ============
+ /// Let the backend hook into the event handling queue
+ /// Not implemented yet
+ void (*set_ready_callback)(backend_t *, backend_ready_callback_t cb);
+ /// Called right after the core has handled its events.
+ /// Not implemented yet
+ void (*handle_events)(backend_t *);
+ // =========== Misc ============
+ /// Return the driver that is been used by the backend
+ enum driver (*detect_driver)(backend_t *backend_data);
+
+ void (*diagnostics)(backend_t *backend_data);
+
+ enum device_status (*device_status)(backend_t *backend_data);
+};
+
+extern struct backend_operations *backend_list[];
+
+void paint_all_new(session_t *ps, struct managed_win *const t, bool ignore_damage)
+ attr_nonnull(1);
diff --git a/dwm/picom/src/backend/backend_common.c b/dwm/picom/src/backend/backend_common.c
new file mode 100644
index 0000000..5bd75e2
--- /dev/null
+++ b/dwm/picom/src/backend/backend_common.c
@@ -0,0 +1,483 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#include
+#include
+#include
+#include
+#include
+
+#include "backend/backend.h"
+#include "backend/backend_common.h"
+#include "common.h"
+#include "config.h"
+#include "kernel.h"
+#include "log.h"
+#include "utils.h"
+#include "win.h"
+#include "x.h"
+
+/**
+ * Generate a 1x1 Picture of a particular color.
+ */
+xcb_render_picture_t solid_picture(xcb_connection_t *c, xcb_drawable_t d, bool argb,
+ double a, double r, double g, double b) {
+ xcb_pixmap_t pixmap;
+ xcb_render_picture_t picture;
+ xcb_render_create_picture_value_list_t pa;
+ xcb_render_color_t col;
+ xcb_rectangle_t rect;
+
+ pixmap = x_create_pixmap(c, argb ? 32 : 8, d, 1, 1);
+ if (!pixmap)
+ return XCB_NONE;
+
+ pa.repeat = 1;
+ picture = x_create_picture_with_standard_and_pixmap(
+ c, argb ? XCB_PICT_STANDARD_ARGB_32 : XCB_PICT_STANDARD_A_8, pixmap,
+ XCB_RENDER_CP_REPEAT, &pa);
+
+ if (!picture) {
+ xcb_free_pixmap(c, pixmap);
+ return XCB_NONE;
+ }
+
+ col.alpha = (uint16_t)(a * 0xffff);
+ col.red = (uint16_t)(r * 0xffff);
+ col.green = (uint16_t)(g * 0xffff);
+ col.blue = (uint16_t)(b * 0xffff);
+
+ rect.x = 0;
+ rect.y = 0;
+ rect.width = 1;
+ rect.height = 1;
+
+ xcb_render_fill_rectangles(c, XCB_RENDER_PICT_OP_SRC, picture, col, 1, &rect);
+ xcb_free_pixmap(c, pixmap);
+
+ return picture;
+}
+
+xcb_image_t *
+make_shadow(xcb_connection_t *c, const conv *kernel, double opacity, int width, int height) {
+ /*
+ * We classify shadows into 4 kinds of regions
+ * r = shadow radius
+ * (0, 0) is the top left of the window itself
+ * -r r width-r width+r
+ * -r +-----+---------+-----+
+ * | 1 | 2 | 1 |
+ * r +-----+---------+-----+
+ * | 2 | 3 | 2 |
+ * height-r +-----+---------+-----+
+ * | 1 | 2 | 1 |
+ * height+r +-----+---------+-----+
+ */
+ xcb_image_t *ximage;
+ const double *shadow_sum = kernel->rsum;
+ assert(shadow_sum);
+ // We only support square kernels for shadow
+ assert(kernel->w == kernel->h);
+ int d = kernel->w;
+ int r = d / 2;
+ int swidth = width + r * 2, sheight = height + r * 2;
+
+ assert(d % 2 == 1);
+ assert(d > 0);
+
+ ximage = xcb_image_create_native(c, to_u16_checked(swidth), to_u16_checked(sheight),
+ XCB_IMAGE_FORMAT_Z_PIXMAP, 8, 0, 0, NULL);
+ if (!ximage) {
+ log_error("failed to create an X image");
+ return 0;
+ }
+
+ unsigned char *data = ximage->data;
+ long long sstride = ximage->stride;
+
+ // If the window body is smaller than the kernel, we do convolution directly
+ if (width < r * 2 && height < r * 2) {
+ for (int y = 0; y < sheight; y++) {
+ for (int x = 0; x < swidth; x++) {
+ double sum = sum_kernel_normalized(
+ kernel, d - x - 1, d - y - 1, width, height);
+ data[y * sstride + x] = (uint8_t)(sum * 255.0 * opacity);
+ }
+ }
+ return ximage;
+ }
+
+ if (height < r * 2) {
+ // Implies width >= r * 2
+ // If the window height is smaller than the kernel, we divide
+ // the window like this:
+ // -r r width-r width+r
+ // +------+-------------+------+
+ // | | | |
+ // +------+-------------+------+
+ for (int y = 0; y < sheight; y++) {
+ for (int x = 0; x < r * 2; x++) {
+ double sum = sum_kernel_normalized(kernel, d - x - 1,
+ d - y - 1, d, height) *
+ 255.0 * opacity;
+ data[y * sstride + x] = (uint8_t)sum;
+ data[y * sstride + swidth - x - 1] = (uint8_t)sum;
+ }
+ }
+ for (int y = 0; y < sheight; y++) {
+ double sum = sum_kernel_normalized(kernel, 0, d - y - 1, d, height) *
+ 255.0 * opacity;
+ memset(&data[y * sstride + r * 2], (uint8_t)sum,
+ (size_t)(width - 2 * r));
+ }
+ return ximage;
+ }
+ if (width < r * 2) {
+ // Similarly, for width smaller than kernel
+ for (int y = 0; y < r * 2; y++) {
+ for (int x = 0; x < swidth; x++) {
+ double sum = sum_kernel_normalized(kernel, d - x - 1,
+ d - y - 1, width, d) *
+ 255.0 * opacity;
+ data[y * sstride + x] = (uint8_t)sum;
+ data[(sheight - y - 1) * sstride + x] = (uint8_t)sum;
+ }
+ }
+ for (int x = 0; x < swidth; x++) {
+ double sum = sum_kernel_normalized(kernel, d - x - 1, 0, width, d) *
+ 255.0 * opacity;
+ for (int y = r * 2; y < height; y++) {
+ data[y * sstride + x] = (uint8_t)sum;
+ }
+ }
+ return ximage;
+ }
+
+ // Implies: width >= r * 2 && height >= r * 2
+
+ // Fill part 3
+ for (int y = r; y < height + r; y++) {
+ memset(data + sstride * y + r, (uint8_t)(255 * opacity), (size_t)width);
+ }
+
+ // Part 1
+ for (int y = 0; y < r * 2; y++) {
+ for (int x = 0; x < r * 2; x++) {
+ double tmpsum = shadow_sum[y * d + x] * opacity * 255.0;
+ data[y * sstride + x] = (uint8_t)tmpsum;
+ data[(sheight - y - 1) * sstride + x] = (uint8_t)tmpsum;
+ data[(sheight - y - 1) * sstride + (swidth - x - 1)] = (uint8_t)tmpsum;
+ data[y * sstride + (swidth - x - 1)] = (uint8_t)tmpsum;
+ }
+ }
+
+ // Part 2, top/bottom
+ for (int y = 0; y < r * 2; y++) {
+ double tmpsum = shadow_sum[d * y + d - 1] * opacity * 255.0;
+ memset(&data[y * sstride + r * 2], (uint8_t)tmpsum, (size_t)(width - r * 2));
+ memset(&data[(sheight - y - 1) * sstride + r * 2], (uint8_t)tmpsum,
+ (size_t)(width - r * 2));
+ }
+
+ // Part 2, left/right
+ for (int x = 0; x < r * 2; x++) {
+ double tmpsum = shadow_sum[d * (d - 1) + x] * opacity * 255.0;
+ for (int y = r * 2; y < height; y++) {
+ data[y * sstride + x] = (uint8_t)tmpsum;
+ data[y * sstride + (swidth - x - 1)] = (uint8_t)tmpsum;
+ }
+ }
+
+ return ximage;
+}
+
+/**
+ * Generate shadow Picture for a window.
+ */
+bool build_shadow(xcb_connection_t *c, xcb_drawable_t d, double opacity, const int width,
+ const int height, const conv *kernel, xcb_render_picture_t shadow_pixel,
+ xcb_pixmap_t *pixmap, xcb_render_picture_t *pict) {
+ xcb_image_t *shadow_image = NULL;
+ xcb_pixmap_t shadow_pixmap = XCB_NONE, shadow_pixmap_argb = XCB_NONE;
+ xcb_render_picture_t shadow_picture = XCB_NONE, shadow_picture_argb = XCB_NONE;
+ xcb_gcontext_t gc = XCB_NONE;
+
+ shadow_image = make_shadow(c, kernel, opacity, width, height);
+ if (!shadow_image) {
+ log_error("Failed to make shadow");
+ return false;
+ }
+
+ shadow_pixmap = x_create_pixmap(c, 8, d, shadow_image->width, shadow_image->height);
+ shadow_pixmap_argb =
+ x_create_pixmap(c, 32, d, shadow_image->width, shadow_image->height);
+
+ if (!shadow_pixmap || !shadow_pixmap_argb) {
+ log_error("Failed to create shadow pixmaps");
+ goto shadow_picture_err;
+ }
+
+ shadow_picture = x_create_picture_with_standard_and_pixmap(
+ c, XCB_PICT_STANDARD_A_8, shadow_pixmap, 0, NULL);
+ shadow_picture_argb = x_create_picture_with_standard_and_pixmap(
+ c, XCB_PICT_STANDARD_ARGB_32, shadow_pixmap_argb, 0, NULL);
+ if (!shadow_picture || !shadow_picture_argb) {
+ goto shadow_picture_err;
+ }
+
+ gc = x_new_id(c);
+ xcb_create_gc(c, gc, shadow_pixmap, 0, NULL);
+
+ // We need to make room for protocol metadata in the request. The metadata should
+ // be 24 bytes plus padding, let's be generous and give it 1kb
+ auto maximum_image_size = xcb_get_maximum_request_length(c) * 4 - 1024;
+ auto maximum_row =
+ to_u16_checked(clamp(maximum_image_size / shadow_image->stride, 0, UINT16_MAX));
+ if (maximum_row <= 0) {
+ // TODO(yshui) Upload image with XShm
+ log_error("X server request size limit is too restrictive, or the shadow "
+ "image is too wide for us to send a single row of the shadow "
+ "image. Shadow size: %dx%d",
+ width, height);
+ goto shadow_picture_err;
+ }
+
+ for (uint32_t row = 0; row < shadow_image->height; row += maximum_row) {
+ auto batch_height = maximum_row;
+ if (batch_height > shadow_image->height - row) {
+ batch_height = to_u16_checked(shadow_image->height - row);
+ }
+
+ uint32_t offset = row * shadow_image->stride / sizeof(*shadow_image->data);
+ xcb_put_image(c, (uint8_t)shadow_image->format, shadow_pixmap, gc,
+ shadow_image->width, batch_height, 0, to_i16_checked(row),
+ 0, shadow_image->depth, shadow_image->stride * batch_height,
+ shadow_image->data + offset);
+ }
+
+ xcb_render_composite(c, XCB_RENDER_PICT_OP_SRC, shadow_pixel, shadow_picture,
+ shadow_picture_argb, 0, 0, 0, 0, 0, 0, shadow_image->width,
+ shadow_image->height);
+
+ *pixmap = shadow_pixmap_argb;
+ *pict = shadow_picture_argb;
+
+ xcb_free_gc(c, gc);
+ xcb_image_destroy(shadow_image);
+ xcb_free_pixmap(c, shadow_pixmap);
+ xcb_render_free_picture(c, shadow_picture);
+
+ return true;
+
+shadow_picture_err:
+ if (shadow_image) {
+ xcb_image_destroy(shadow_image);
+ }
+ if (shadow_pixmap) {
+ xcb_free_pixmap(c, shadow_pixmap);
+ }
+ if (shadow_pixmap_argb) {
+ xcb_free_pixmap(c, shadow_pixmap_argb);
+ }
+ if (shadow_picture) {
+ xcb_render_free_picture(c, shadow_picture);
+ }
+ if (shadow_picture_argb) {
+ xcb_render_free_picture(c, shadow_picture_argb);
+ }
+ if (gc) {
+ xcb_free_gc(c, gc);
+ }
+
+ return false;
+}
+
+void *
+default_backend_render_shadow(backend_t *backend_data, int width, int height,
+ const conv *kernel, double r, double g, double b, double a) {
+ xcb_pixmap_t shadow_pixel = solid_picture(backend_data->c, backend_data->root,
+ true, 1, r, g, b),
+ shadow = XCB_NONE;
+ xcb_render_picture_t pict = XCB_NONE;
+
+ if (!build_shadow(backend_data->c, backend_data->root, a, width, height, kernel,
+ shadow_pixel, &shadow, &pict)) {
+ return NULL;
+ }
+
+ auto visual = x_get_visual_for_standard(backend_data->c, XCB_PICT_STANDARD_ARGB_32);
+ void *ret = backend_data->ops->bind_pixmap(
+ backend_data, shadow, x_get_visual_info(backend_data->c, visual), true);
+ xcb_render_free_picture(backend_data->c, pict);
+ return ret;
+}
+
+static struct conv **generate_box_blur_kernel(struct box_blur_args *args, int *kernel_count) {
+ int r = args->size * 2 + 1;
+ assert(r > 0);
+ auto ret = ccalloc(2, struct conv *);
+ ret[0] = cvalloc(sizeof(struct conv) + sizeof(double) * (size_t)r);
+ ret[1] = cvalloc(sizeof(struct conv) + sizeof(double) * (size_t)r);
+ ret[0]->w = r;
+ ret[0]->h = 1;
+ ret[1]->w = 1;
+ ret[1]->h = r;
+ for (int i = 0; i < r; i++) {
+ ret[0]->data[i] = 1;
+ ret[1]->data[i] = 1;
+ }
+ *kernel_count = 2;
+ return ret;
+}
+
+static struct conv **
+generate_gaussian_blur_kernel(struct gaussian_blur_args *args, int *kernel_count) {
+ int r = args->size * 2 + 1;
+ assert(r > 0);
+ auto ret = ccalloc(2, struct conv *);
+ ret[0] = cvalloc(sizeof(struct conv) + sizeof(double) * (size_t)r);
+ ret[1] = cvalloc(sizeof(struct conv) + sizeof(double) * (size_t)r);
+ ret[0]->w = r;
+ ret[0]->h = 1;
+ ret[1]->w = 1;
+ ret[1]->h = r;
+ for (int i = 0; i <= args->size; i++) {
+ ret[0]->data[i] = ret[0]->data[r - i - 1] =
+ 1.0 / (sqrt(2.0 * M_PI) * args->deviation) *
+ exp(-(args->size - i) * (args->size - i) /
+ (2 * args->deviation * args->deviation));
+ ret[1]->data[i] = ret[1]->data[r - i - 1] = ret[0]->data[i];
+ }
+ *kernel_count = 2;
+ return ret;
+}
+
+/// Generate blur kernels for gaussian and box blur methods. Generated kernel is not
+/// normalized, and the center element will always be 1.
+struct conv **generate_blur_kernel(enum blur_method method, void *args, int *kernel_count) {
+ switch (method) {
+ case BLUR_METHOD_BOX: return generate_box_blur_kernel(args, kernel_count);
+ case BLUR_METHOD_GAUSSIAN:
+ return generate_gaussian_blur_kernel(args, kernel_count);
+ default: break;
+ }
+ return NULL;
+}
+
+/// Generate kernel parameters for dual-kawase blur method. Falls back on approximating
+/// standard gauss radius if strength is zero or below.
+struct dual_kawase_params *generate_dual_kawase_params(void *args) {
+ struct dual_kawase_blur_args *blur_args = args;
+ static const struct {
+ int iterations; /// Number of down- and upsample iterations
+ float offset; /// Sample offset in half-pixels
+ int min_radius; /// Approximate gauss-blur with at least this
+ /// radius and std-deviation
+ } strength_levels[20] = {
+ {.iterations = 1, .offset = 1.25f, .min_radius = 1}, // LVL 1
+ {.iterations = 1, .offset = 2.25f, .min_radius = 6}, // LVL 2
+ {.iterations = 2, .offset = 2.00f, .min_radius = 11}, // LVL 3
+ {.iterations = 2, .offset = 3.00f, .min_radius = 17}, // LVL 4
+ {.iterations = 2, .offset = 4.25f, .min_radius = 24}, // LVL 5
+ {.iterations = 3, .offset = 2.50f, .min_radius = 32}, // LVL 6
+ {.iterations = 3, .offset = 3.25f, .min_radius = 40}, // LVL 7
+ {.iterations = 3, .offset = 4.25f, .min_radius = 51}, // LVL 8
+ {.iterations = 3, .offset = 5.50f, .min_radius = 67}, // LVL 9
+ {.iterations = 4, .offset = 3.25f, .min_radius = 83}, // LVL 10
+ {.iterations = 4, .offset = 4.00f, .min_radius = 101}, // LVL 11
+ {.iterations = 4, .offset = 5.00f, .min_radius = 123}, // LVL 12
+ {.iterations = 4, .offset = 6.00f, .min_radius = 148}, // LVL 13
+ {.iterations = 4, .offset = 7.25f, .min_radius = 178}, // LVL 14
+ {.iterations = 4, .offset = 8.25f, .min_radius = 208}, // LVL 15
+ {.iterations = 5, .offset = 4.50f, .min_radius = 236}, // LVL 16
+ {.iterations = 5, .offset = 5.25f, .min_radius = 269}, // LVL 17
+ {.iterations = 5, .offset = 6.25f, .min_radius = 309}, // LVL 18
+ {.iterations = 5, .offset = 7.25f, .min_radius = 357}, // LVL 19
+ {.iterations = 5, .offset = 8.50f, .min_radius = 417}, // LVL 20
+ };
+
+ auto params = ccalloc(1, struct dual_kawase_params);
+ params->iterations = 0;
+ params->offset = 1.0f;
+
+ if (blur_args->strength <= 0 && blur_args->size) {
+ // find highest level that approximates blur-strength with the selected
+ // gaussian blur-radius
+ int lvl = 1;
+ while (strength_levels[lvl - 1].min_radius < blur_args->size && lvl < 20) {
+ ++lvl;
+ }
+ blur_args->strength = lvl;
+ }
+ if (blur_args->strength <= 0) {
+ // default value
+ blur_args->strength = 5;
+ }
+
+ assert(blur_args->strength > 0 && blur_args->strength <= 20);
+ params->iterations = strength_levels[blur_args->strength - 1].iterations;
+ params->offset = strength_levels[blur_args->strength - 1].offset;
+
+ // Expand sample area to cover the smallest texture / highest selected iteration:
+ // - Smallest texture dimensions are halved `iterations`-times
+ // - Upsample needs pixels two-times `offset` away from the border
+ // - Plus one for interpolation differences
+ params->expand = (1 << params->iterations) * 2 * (int)ceil(params->offset) + 1;
+
+ return params;
+}
+
+void *default_clone_image(backend_t *base attr_unused, const void *image_data,
+ const region_t *reg_visible attr_unused) {
+ auto new_img = ccalloc(1, struct backend_image);
+ *new_img = *(struct backend_image *)image_data;
+ new_img->inner->refcount++;
+ return new_img;
+}
+
+bool default_set_image_property(backend_t *base attr_unused, enum image_properties op,
+ void *image_data, void *arg) {
+ struct backend_image *tex = image_data;
+ int *iargs = arg;
+ bool *bargs = arg;
+ double *dargs = arg;
+ switch (op) {
+ case IMAGE_PROPERTY_INVERTED: tex->color_inverted = bargs[0]; break;
+ case IMAGE_PROPERTY_DIM_LEVEL: tex->dim = dargs[0]; break;
+ case IMAGE_PROPERTY_OPACITY: tex->opacity = dargs[0]; break;
+ case IMAGE_PROPERTY_EFFECTIVE_SIZE:
+ // texture is already set to repeat, so nothing else we need to do
+ tex->ewidth = iargs[0];
+ tex->eheight = iargs[1];
+ break;
+ case IMAGE_PROPERTY_CORNER_RADIUS: tex->corner_radius = dargs[0]; break;
+ case IMAGE_PROPERTY_MAX_BRIGHTNESS: tex->max_brightness = dargs[0]; break;
+ case IMAGE_PROPERTY_BORDER_WIDTH: tex->border_width = *(int *)arg; break;
+ }
+
+ return true;
+}
+
+bool default_is_image_transparent(backend_t *base attr_unused, void *image_data) {
+ struct backend_image *img = image_data;
+ return img->opacity < 1 || img->inner->has_alpha;
+}
+
+struct backend_image *default_new_backend_image(int w, int h) {
+ auto ret = ccalloc(1, struct backend_image);
+ ret->opacity = 1;
+ ret->dim = 0;
+ ret->max_brightness = 1;
+ ret->eheight = h;
+ ret->ewidth = w;
+ ret->color_inverted = false;
+ ret->corner_radius = 0;
+ return ret;
+}
+
+void init_backend_base(struct backend_base *base, session_t *ps) {
+ base->c = ps->c;
+ base->loop = ps->loop;
+ base->root = ps->root;
+ base->busy = false;
+ base->ops = NULL;
+}
diff --git a/dwm/picom/src/backend/backend_common.h b/dwm/picom/src/backend/backend_common.h
new file mode 100644
index 0000000..53b4a26
--- /dev/null
+++ b/dwm/picom/src/backend/backend_common.h
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#pragma once
+
+#include
+#include
+
+#include
+
+#include "backend.h"
+#include "config.h"
+#include "region.h"
+
+typedef struct session session_t;
+typedef struct win win;
+typedef struct conv conv;
+typedef struct backend_base backend_t;
+struct backend_operations;
+
+struct dual_kawase_params {
+ /// Number of downsample passes
+ int iterations;
+ /// Pixel offset for down- and upsample
+ float offset;
+ /// Save area around blur target (@ref resize_width, @ref resize_height)
+ int expand;
+};
+
+struct backend_image_inner_base {
+ int refcount;
+ bool has_alpha;
+};
+
+struct backend_image {
+ // Backend dependent inner image data
+ struct backend_image_inner_base *inner;
+ double opacity;
+ double dim;
+ double max_brightness;
+ double corner_radius;
+ // Effective size of the image
+ int ewidth, eheight;
+ bool color_inverted;
+ int border_width;
+};
+
+bool build_shadow(xcb_connection_t *, xcb_drawable_t, double opacity, int width,
+ int height, const conv *kernel, xcb_render_picture_t shadow_pixel,
+ xcb_pixmap_t *pixmap, xcb_render_picture_t *pict);
+
+xcb_render_picture_t solid_picture(xcb_connection_t *, xcb_drawable_t, bool argb,
+ double a, double r, double g, double b);
+
+xcb_image_t *
+make_shadow(xcb_connection_t *c, const conv *kernel, double opacity, int width, int height);
+
+/// The default implementation of `is_win_transparent`, it simply looks at win::mode. So
+/// this is not suitable for backends that alter the content of windows
+bool default_is_win_transparent(void *, win *, void *);
+
+/// The default implementation of `is_frame_transparent`, it uses win::frame_opacity. Same
+/// caveat as `default_is_win_transparent` applies.
+bool default_is_frame_transparent(void *, win *, void *);
+
+void *
+default_backend_render_shadow(backend_t *backend_data, int width, int height,
+ const conv *kernel, double r, double g, double b, double a);
+
+void init_backend_base(struct backend_base *base, session_t *ps);
+
+struct conv **generate_blur_kernel(enum blur_method method, void *args, int *kernel_count);
+struct dual_kawase_params *generate_dual_kawase_params(void *args);
+
+void *default_clone_image(backend_t *base, const void *image_data, const region_t *reg);
+void *default_resize_image(backend_t *base, const void *image_data, uint16_t desired_width,
+ uint16_t desired_height, const region_t *reg);
+bool default_is_image_transparent(backend_t *base attr_unused, void *image_data);
+bool default_set_image_property(backend_t *base attr_unused, enum image_properties op,
+ void *image_data, void *arg);
+struct backend_image *default_new_backend_image(int w, int h);
diff --git a/dwm/picom/src/backend/driver.c b/dwm/picom/src/backend/driver.c
new file mode 100644
index 0000000..a41d2fd
--- /dev/null
+++ b/dwm/picom/src/backend/driver.c
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#include
+#include
+
+#include
+#include
+
+#include "backend/backend.h"
+#include "backend/driver.h"
+#include "common.h"
+#include "compiler.h"
+#include "log.h"
+
+/// Apply driver specified global workarounds. It's safe to call this multiple times.
+void apply_driver_workarounds(struct session *ps, enum driver driver) {
+ if (driver & DRIVER_NVIDIA) {
+ // setenv("__GL_YIELD", "usleep", true);
+ setenv("__GL_MaxFramesAllowed", "1", true);
+ ps->o.xrender_sync_fence = true;
+ }
+}
+
+enum driver detect_driver(xcb_connection_t *c, backend_t *backend_data, xcb_window_t window) {
+ enum driver ret = 0;
+ // First we try doing backend agnostic detection using RANDR
+ // There's no way to query the X server about what driver is loaded, so RANDR is
+ // our best shot.
+ auto randr_version = xcb_randr_query_version_reply(
+ c, xcb_randr_query_version(c, XCB_RANDR_MAJOR_VERSION, XCB_RANDR_MINOR_VERSION),
+ NULL);
+ if (randr_version &&
+ (randr_version->major_version > 1 || randr_version->minor_version >= 4)) {
+ auto r = xcb_randr_get_providers_reply(
+ c, xcb_randr_get_providers(c, window), NULL);
+ if (r == NULL) {
+ log_warn("Failed to get RANDR providers");
+ free(randr_version);
+ return 0;
+ }
+
+ auto providers = xcb_randr_get_providers_providers(r);
+ for (auto i = 0; i < xcb_randr_get_providers_providers_length(r); i++) {
+ auto r2 = xcb_randr_get_provider_info_reply(
+ c, xcb_randr_get_provider_info(c, providers[i], r->timestamp), NULL);
+ if (r2 == NULL) {
+ continue;
+ }
+ if (r2->num_outputs == 0) {
+ free(r2);
+ continue;
+ }
+
+ auto name_len = xcb_randr_get_provider_info_name_length(r2);
+ assert(name_len >= 0);
+ auto name =
+ strndup(xcb_randr_get_provider_info_name(r2), (size_t)name_len);
+ if (strcasestr(name, "modesetting") != NULL) {
+ ret |= DRIVER_MODESETTING;
+ } else if (strcasestr(name, "Radeon") != NULL) {
+ // Be conservative, add both radeon drivers
+ ret |= DRIVER_AMDGPU | DRIVER_RADEON;
+ } else if (strcasestr(name, "NVIDIA") != NULL) {
+ ret |= DRIVER_NVIDIA;
+ } else if (strcasestr(name, "nouveau") != NULL) {
+ ret |= DRIVER_NOUVEAU;
+ } else if (strcasestr(name, "Intel") != NULL) {
+ ret |= DRIVER_INTEL;
+ }
+ free(name);
+ free(r2);
+ }
+ free(r);
+ }
+ free(randr_version);
+
+ // If the backend supports driver detection, use that as well
+ if (backend_data && backend_data->ops->detect_driver) {
+ ret |= backend_data->ops->detect_driver(backend_data);
+ }
+ return ret;
+}
diff --git a/dwm/picom/src/backend/driver.h b/dwm/picom/src/backend/driver.h
new file mode 100644
index 0000000..a37cda3
--- /dev/null
+++ b/dwm/picom/src/backend/driver.h
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+
+#pragma once
+
+#include
+#include
+#include
+
+#include "utils.h"
+
+struct session;
+struct backend_base;
+
+// A list of known driver quirks:
+// * NVIDIA driver doesn't like seeing the same pixmap under different
+// ids, so avoid naming the pixmap again when it didn't actually change.
+
+/// A list of possible drivers.
+/// The driver situation is a bit complicated. There are two drivers we care about: the
+/// DDX, and the OpenGL driver. They are usually paired, but not always, since there is
+/// also the generic modesetting driver.
+/// This enum represents _both_ drivers.
+enum driver {
+ DRIVER_AMDGPU = 1, // AMDGPU for DDX, radeonsi for OpenGL
+ DRIVER_RADEON = 2, // ATI for DDX, mesa r600 for OpenGL
+ DRIVER_FGLRX = 4,
+ DRIVER_NVIDIA = 8,
+ DRIVER_NOUVEAU = 16,
+ DRIVER_INTEL = 32,
+ DRIVER_MODESETTING = 64,
+};
+
+static const char *driver_names[] = {
+ "AMDGPU", "Radeon", "fglrx", "NVIDIA", "nouveau", "Intel", "modesetting",
+};
+
+/// Return a list of all drivers currently in use by the X server.
+/// Note, this is a best-effort test, so no guarantee all drivers will be detected.
+enum driver detect_driver(xcb_connection_t *, struct backend_base *, xcb_window_t);
+
+/// Apply driver specified global workarounds. It's safe to call this multiple times.
+void apply_driver_workarounds(struct session *ps, enum driver);
+
+// Print driver names to stdout, for diagnostics
+static inline void print_drivers(enum driver drivers) {
+ const char *seen_drivers[ARR_SIZE(driver_names)];
+ int driver_count = 0;
+ for (size_t i = 0; i < ARR_SIZE(driver_names); i++) {
+ if (drivers & (1ul << i)) {
+ seen_drivers[driver_count++] = driver_names[i];
+ }
+ }
+
+ if (driver_count > 0) {
+ printf("%s", seen_drivers[0]);
+ for (int i = 1; i < driver_count; i++) {
+ printf(", %s", seen_drivers[i]);
+ }
+ }
+ printf("\n");
+}
diff --git a/dwm/picom/src/backend/dummy/dummy.c b/dwm/picom/src/backend/dummy/dummy.c
new file mode 100644
index 0000000..a057b97
--- /dev/null
+++ b/dwm/picom/src/backend/dummy/dummy.c
@@ -0,0 +1,174 @@
+#include
+#include
+
+#include "backend/backend.h"
+#include "backend/backend_common.h"
+#include "common.h"
+#include "compiler.h"
+#include "config.h"
+#include "log.h"
+#include "region.h"
+#include "types.h"
+#include "uthash_extra.h"
+#include "utils.h"
+#include "x.h"
+
+struct dummy_image {
+ xcb_pixmap_t pixmap;
+ bool transparent;
+ int *refcount;
+ UT_hash_handle hh;
+};
+
+struct dummy_data {
+ struct backend_base base;
+ struct dummy_image *images;
+};
+
+struct backend_base *dummy_init(struct session *ps attr_unused) {
+ auto ret = (struct backend_base *)ccalloc(1, struct dummy_data);
+ ret->c = ps->c;
+ ret->loop = ps->loop;
+ ret->root = ps->root;
+ ret->busy = false;
+ return ret;
+}
+
+void dummy_deinit(struct backend_base *data) {
+ auto dummy = (struct dummy_data *)data;
+ HASH_ITER2(dummy->images, img) {
+ log_warn("Backend image for pixmap %#010x is not freed", img->pixmap);
+ HASH_DEL(dummy->images, img);
+ free(img->refcount);
+ free(img);
+ }
+ free(dummy);
+}
+
+static void dummy_check_image(struct backend_base *base, const struct dummy_image *img) {
+ auto dummy = (struct dummy_data *)base;
+ struct dummy_image *tmp = NULL;
+ HASH_FIND_INT(dummy->images, &img->pixmap, tmp);
+ if (!tmp) {
+ log_warn("Using an invalid (possibly freed) image");
+ assert(false);
+ }
+ assert(*tmp->refcount > 0);
+}
+
+void dummy_compose(struct backend_base *base, void *image, int dst_x1 attr_unused,
+ int dst_y1 attr_unused, int dst_x2 attr_unused, int dst_y2 attr_unused,
+ const region_t *reg_paint attr_unused, const region_t *reg_visible attr_unused) {
+ dummy_check_image(base, image);
+}
+
+void dummy_fill(struct backend_base *backend_data attr_unused, struct color c attr_unused,
+ const region_t *clip attr_unused) {
+}
+
+bool dummy_blur(struct backend_base *backend_data attr_unused, double opacity attr_unused,
+ void *blur_ctx attr_unused, const region_t *reg_blur attr_unused,
+ const region_t *reg_visible attr_unused) {
+ return true;
+}
+
+void *dummy_bind_pixmap(struct backend_base *base, xcb_pixmap_t pixmap,
+ struct xvisual_info fmt, bool owned attr_unused) {
+ auto dummy = (struct dummy_data *)base;
+ struct dummy_image *img = NULL;
+ HASH_FIND_INT(dummy->images, &pixmap, img);
+ if (img) {
+ (*img->refcount)++;
+ return img;
+ }
+
+ img = ccalloc(1, struct dummy_image);
+ img->pixmap = pixmap;
+ img->transparent = fmt.alpha_size != 0;
+ img->refcount = ccalloc(1, int);
+ *img->refcount = 1;
+
+ HASH_ADD_INT(dummy->images, pixmap, img);
+ return (void *)img;
+}
+
+void dummy_release_image(backend_t *base, void *image) {
+ auto dummy = (struct dummy_data *)base;
+ auto img = (struct dummy_image *)image;
+ assert(*img->refcount > 0);
+ (*img->refcount)--;
+ if (*img->refcount == 0) {
+ HASH_DEL(dummy->images, img);
+ free(img->refcount);
+ free(img);
+ }
+}
+
+bool dummy_is_image_transparent(struct backend_base *base, void *image) {
+ auto img = (struct dummy_image *)image;
+ dummy_check_image(base, img);
+ return img->transparent;
+}
+
+int dummy_buffer_age(struct backend_base *base attr_unused) {
+ return 2;
+}
+
+bool dummy_image_op(struct backend_base *base, enum image_operations op attr_unused,
+ void *image, const region_t *reg_op attr_unused,
+ const region_t *reg_visible attr_unused, void *args attr_unused) {
+ dummy_check_image(base, image);
+ return true;
+}
+
+bool dummy_set_image_property(struct backend_base *base, enum image_properties prop attr_unused,
+ void *image, void *arg attr_unused) {
+ dummy_check_image(base, image);
+ return true;
+}
+
+void *dummy_clone_image(struct backend_base *base, const void *image,
+ const region_t *reg_visible attr_unused) {
+ auto img = (const struct dummy_image *)image;
+ dummy_check_image(base, img);
+ (*img->refcount)++;
+ return (void *)img;
+}
+
+void *dummy_create_blur_context(struct backend_base *base attr_unused,
+ enum blur_method method attr_unused, void *args attr_unused) {
+ static int dummy_context;
+ return &dummy_context;
+}
+
+void dummy_destroy_blur_context(struct backend_base *base attr_unused, void *ctx attr_unused) {
+}
+
+void dummy_get_blur_size(void *ctx attr_unused, int *width, int *height) {
+ // These numbers are arbitrary, to make sure the reisze_region code path is
+ // covered.
+ *width = 5;
+ *height = 5;
+}
+
+struct backend_operations dummy_ops = {
+ .init = dummy_init,
+ .deinit = dummy_deinit,
+ .compose = dummy_compose,
+ .fill = dummy_fill,
+ .blur = dummy_blur,
+ .bind_pixmap = dummy_bind_pixmap,
+ .render_shadow = default_backend_render_shadow,
+ .release_image = dummy_release_image,
+ .is_image_transparent = dummy_is_image_transparent,
+ .buffer_age = dummy_buffer_age,
+ .max_buffer_age = 5,
+
+ .image_op = dummy_image_op,
+ .clone_image = dummy_clone_image,
+ .set_image_property = dummy_set_image_property,
+ .create_blur_context = dummy_create_blur_context,
+ .destroy_blur_context = dummy_destroy_blur_context,
+ .get_blur_size = dummy_get_blur_size,
+
+};
diff --git a/dwm/picom/src/backend/gl/gl_common.c b/dwm/picom/src/backend/gl/gl_common.c
new file mode 100644
index 0000000..bf00e74
--- /dev/null
+++ b/dwm/picom/src/backend/gl/gl_common.c
@@ -0,0 +1,1946 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#include
+#include
+#include
+#include
+#include
+#include
+#include // for xcb_render_fixed_t, XXX
+
+#include "backend/backend.h"
+#include "common.h"
+#include "compiler.h"
+#include "config.h"
+#include "kernel.h"
+#include "log.h"
+#include "region.h"
+#include "string_utils.h"
+#include "types.h"
+#include "utils.h"
+
+#include "backend/backend_common.h"
+#include "backend/gl/gl_common.h"
+
+#define GLSL(version, ...) "#version " #version "\n" #__VA_ARGS__
+#define QUOTE(...) #__VA_ARGS__
+
+static const GLuint vert_coord_loc = 0;
+static const GLuint vert_in_texcoord_loc = 1;
+
+struct gl_blur_context {
+ enum blur_method method;
+ gl_blur_shader_t *blur_shader;
+
+ /// Temporary textures used for blurring
+ GLuint *blur_textures;
+ int blur_texture_count;
+ /// Temporary fbos used for blurring
+ GLuint *blur_fbos;
+ int blur_fbo_count;
+
+ /// Cached dimensions of each blur_texture. They are the same size as the target,
+ /// so they are always big enough without resizing.
+ /// Turns out calling glTexImage to resize is expensive, so we avoid that.
+ struct texture_size {
+ int width;
+ int height;
+ } * texture_sizes;
+
+ /// Cached dimensions of the offscreen framebuffer. It's the same size as the
+ /// target but is expanded in either direction by resize_width / resize_height.
+ int fb_width, fb_height;
+
+ /// How much do we need to resize the damaged region for blurring.
+ int resize_width, resize_height;
+
+ int npasses;
+};
+
+GLuint gl_create_shader(GLenum shader_type, const char *shader_str) {
+ log_trace("===\n%s\n===", shader_str);
+
+ bool success = false;
+ GLuint shader = glCreateShader(shader_type);
+ if (!shader) {
+ log_error("Failed to create shader with type %#x.", shader_type);
+ goto end;
+ }
+ glShaderSource(shader, 1, &shader_str, NULL);
+ glCompileShader(shader);
+
+ // Get shader status
+ {
+ GLint status = GL_FALSE;
+ glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
+ if (GL_FALSE == status) {
+ GLint log_len = 0;
+ glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
+ if (log_len) {
+ char log[log_len + 1];
+ glGetShaderInfoLog(shader, log_len, NULL, log);
+ log_error("Failed to compile shader with type %d: %s",
+ shader_type, log);
+ }
+ goto end;
+ }
+ }
+
+ success = true;
+
+end:
+ if (shader && !success) {
+ glDeleteShader(shader);
+ shader = 0;
+ }
+
+ return shader;
+}
+
+GLuint gl_create_program(const GLuint *const shaders, int nshaders) {
+ bool success = false;
+ GLuint program = glCreateProgram();
+ if (!program) {
+ log_error("Failed to create program.");
+ goto end;
+ }
+
+ for (int i = 0; i < nshaders; ++i)
+ glAttachShader(program, shaders[i]);
+ glLinkProgram(program);
+
+ // Get program status
+ {
+ GLint status = GL_FALSE;
+ glGetProgramiv(program, GL_LINK_STATUS, &status);
+ if (GL_FALSE == status) {
+ GLint log_len = 0;
+ glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_len);
+ if (log_len) {
+ char log[log_len + 1];
+ glGetProgramInfoLog(program, log_len, NULL, log);
+ log_error("Failed to link program: %s", log);
+ }
+ goto end;
+ }
+ }
+ success = true;
+
+end:
+ if (program) {
+ for (int i = 0; i < nshaders; ++i)
+ glDetachShader(program, shaders[i]);
+ }
+ if (program && !success) {
+ glDeleteProgram(program);
+ program = 0;
+ }
+
+ return program;
+}
+
+/**
+ * @brief Create a program from vertex and fragment shader strings.
+ */
+GLuint gl_create_program_from_str(const char *vert_shader_str, const char *frag_shader_str) {
+ GLuint vert_shader = 0;
+ GLuint frag_shader = 0;
+ GLuint prog = 0;
+
+ if (vert_shader_str)
+ vert_shader = gl_create_shader(GL_VERTEX_SHADER, vert_shader_str);
+ if (frag_shader_str)
+ frag_shader = gl_create_shader(GL_FRAGMENT_SHADER, frag_shader_str);
+
+ {
+ GLuint shaders[2];
+ int count = 0;
+ if (vert_shader) {
+ shaders[count++] = vert_shader;
+ }
+ if (frag_shader) {
+ shaders[count++] = frag_shader;
+ }
+ if (count) {
+ prog = gl_create_program(shaders, count);
+ }
+ }
+
+ if (vert_shader)
+ glDeleteShader(vert_shader);
+ if (frag_shader)
+ glDeleteShader(frag_shader);
+
+ return prog;
+}
+
+static void gl_free_prog_main(gl_win_shader_t *pprogram) {
+ if (!pprogram)
+ return;
+ if (pprogram->prog) {
+ glDeleteProgram(pprogram->prog);
+ pprogram->prog = 0;
+ }
+}
+
+/*
+ * @brief Implements recursive part of gl_average_texture_color.
+ *
+ * @note In order to reduce number of textures which needs to be
+ * allocated and deleted during this recursive render
+ * we reuse the same two textures for render source and
+ * destination simply by alterating between them.
+ * Unfortunately on first iteration source_texture might
+ * be read-only. In this case we will select auxiliary_texture as
+ * destination_texture in order not to touch that read-only source
+ * texture in following render iteration.
+ * Otherwise we simply will switch source and destination textures
+ * between each other on each render iteration.
+ */
+static GLuint
+_gl_average_texture_color(backend_t *base, GLuint source_texture, GLuint destination_texture,
+ GLuint auxiliary_texture, GLuint fbo, int width, int height) {
+ const int max_width = 1;
+ const int max_height = 1;
+ const int from_width = next_power_of_two(width);
+ const int from_height = next_power_of_two(height);
+ const int to_width = from_width > max_width ? from_width / 2 : from_width;
+ const int to_height = from_height > max_height ? from_height / 2 : from_height;
+
+ // Prepare coordinates
+ GLint coord[] = {
+ // top left
+ 0, 0, // vertex coord
+ 0, 0, // texture coord
+
+ // top right
+ to_width, 0, // vertex coord
+ width, 0, // texture coord
+
+ // bottom right
+ to_width, to_height, // vertex coord
+ width, height, // texture coord
+
+ // bottom left
+ 0, to_height, // vertex coord
+ 0, height, // texture coord
+ };
+ glBufferSubData(GL_ARRAY_BUFFER, 0, (long)sizeof(*coord) * 16, coord);
+
+ // Prepare framebuffer for new render iteration
+ glBindTexture(GL_TEXTURE_2D, destination_texture);
+ glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ destination_texture, 0);
+ gl_check_fb_complete(GL_FRAMEBUFFER);
+
+ // Bind source texture as downscaling shader uniform input
+ glBindTexture(GL_TEXTURE_2D, source_texture);
+
+ // Render into framebuffer
+ glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);
+
+ // Have we downscaled enough?
+ GLuint result;
+ if (to_width > max_width || to_height > max_height) {
+ GLuint new_source_texture = destination_texture;
+ GLuint new_destination_texture =
+ auxiliary_texture != 0 ? auxiliary_texture : source_texture;
+ result = _gl_average_texture_color(base, new_source_texture,
+ new_destination_texture, 0, fbo,
+ to_width, to_height);
+ } else {
+ result = destination_texture;
+ }
+
+ return result;
+}
+
+/*
+ * @brief Builds a 1x1 texture which has color corresponding to the average of all
+ * pixels of img by recursively rendering into texture of quorter the size (half
+ * width and half height).
+ * Returned texture must not be deleted, since it's owned by the gl_image. It will be
+ * deleted when the gl_image is released.
+ */
+static GLuint gl_average_texture_color(backend_t *base, struct backend_image *img) {
+ auto gd = (struct gl_data *)base;
+ auto inner = (struct gl_texture *)img->inner;
+
+ // Prepare textures which will be used for destination and source of rendering
+ // during downscaling.
+ const int texture_count = ARR_SIZE(inner->auxiliary_texture);
+ if (!inner->auxiliary_texture[0]) {
+ assert(!inner->auxiliary_texture[1]);
+ glGenTextures(texture_count, inner->auxiliary_texture);
+ glActiveTexture(GL_TEXTURE0);
+ for (int i = 0; i < texture_count; i++) {
+ glBindTexture(GL_TEXTURE_2D, inner->auxiliary_texture[i]);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
+ glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR,
+ (GLint[]){0, 0, 0, 0});
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, inner->width,
+ inner->height, 0, GL_BGR, GL_UNSIGNED_BYTE, NULL);
+ }
+ }
+
+ // Prepare framebuffer used for rendering and bind it
+ GLuint fbo;
+ glGenFramebuffers(1, &fbo);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
+ glDrawBuffer(GL_COLOR_ATTACHMENT0);
+
+ // Enable shaders
+ glUseProgram(gd->brightness_shader.prog);
+ glUniform2f(glGetUniformLocationChecked(gd->brightness_shader.prog, "texsize"),
+ (GLfloat)inner->width, (GLfloat)inner->height);
+
+ // Prepare vertex attributes
+ GLuint vao;
+ glGenVertexArrays(1, &vao);
+ glBindVertexArray(vao);
+ GLuint bo[2];
+ glGenBuffers(2, bo);
+ glBindBuffer(GL_ARRAY_BUFFER, bo[0]);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bo[1]);
+ glEnableVertexAttribArray(vert_coord_loc);
+ glEnableVertexAttribArray(vert_in_texcoord_loc);
+ glVertexAttribPointer(vert_coord_loc, 2, GL_INT, GL_FALSE, sizeof(GLint) * 4, NULL);
+ glVertexAttribPointer(vert_in_texcoord_loc, 2, GL_INT, GL_FALSE,
+ sizeof(GLint) * 4, (void *)(sizeof(GLint) * 2));
+
+ // Allocate buffers for render input
+ GLint coord[16] = {0};
+ GLuint indices[] = {0, 1, 2, 2, 3, 0};
+ glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord) * 16, coord, GL_DYNAMIC_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)sizeof(*indices) * 6, indices,
+ GL_STATIC_DRAW);
+
+ // Do actual recursive render to 1x1 texture
+ GLuint result_texture = _gl_average_texture_color(
+ base, inner->texture, inner->auxiliary_texture[0],
+ inner->auxiliary_texture[1], fbo, inner->width, inner->height);
+
+ // Cleanup vertex attributes
+ glDisableVertexAttribArray(vert_coord_loc);
+ glDisableVertexAttribArray(vert_in_texcoord_loc);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glDeleteBuffers(2, bo);
+ glBindVertexArray(0);
+ glDeleteVertexArrays(1, &vao);
+
+ // Cleanup shaders
+ glUseProgram(0);
+
+ // Cleanup framebuffers
+ glDeleteFramebuffers(1, &fbo);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+ glDrawBuffer(GL_BACK);
+
+ // Cleanup render textures
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ gl_check_err();
+
+ return result_texture;
+}
+
+/**
+ * Render a region with texture data.
+ *
+ * @param ptex the texture
+ * @param target the framebuffer to render into
+ * @param dst_x,dst_y the top left corner of region where this texture
+ * should go. In OpenGL coordinate system (important!).
+ * @param reg_tgt the clip region, in Xorg coordinate system
+ * @param reg_visible ignored
+ */
+static void _gl_compose(backend_t *base, struct backend_image *img, GLuint target,
+ GLint *coord, GLuint *indices, int nrects) {
+ auto gd = (struct gl_data *)base;
+ auto inner = (struct gl_texture *)img->inner;
+ if (!img || !inner->texture) {
+ log_error("Missing texture.");
+ return;
+ }
+
+ GLuint brightness = 0;
+ if (img->max_brightness < 1.0) {
+ brightness = gl_average_texture_color(base, img);
+ }
+
+ assert(gd->win_shader.prog);
+ glUseProgram(gd->win_shader.prog);
+ if (gd->win_shader.uniform_opacity >= 0) {
+ glUniform1f(gd->win_shader.uniform_opacity, (float)img->opacity);
+ }
+ if (gd->win_shader.uniform_invert_color >= 0) {
+ glUniform1i(gd->win_shader.uniform_invert_color, img->color_inverted);
+ }
+ if (gd->win_shader.uniform_tex >= 0) {
+ glUniform1i(gd->win_shader.uniform_tex, 0);
+ }
+ if (gd->win_shader.uniform_dim >= 0) {
+ glUniform1f(gd->win_shader.uniform_dim, (float)img->dim);
+ }
+ if (gd->win_shader.uniform_brightness >= 0) {
+ glUniform1i(gd->win_shader.uniform_brightness, 1);
+ }
+ if (gd->win_shader.uniform_max_brightness >= 0) {
+ glUniform1f(gd->win_shader.uniform_max_brightness, (float)img->max_brightness);
+ }
+ if (gd->win_shader.uniform_corner_radius >= 0) {
+ glUniform1f(gd->win_shader.uniform_corner_radius, (float)img->corner_radius);
+ }
+ if (gd->win_shader.uniform_border_width >= 0) {
+ auto border_width = img->border_width;
+ if (border_width > img->corner_radius) {
+ border_width = 0;
+ }
+ glUniform1f(gd->win_shader.uniform_border_width, (float)border_width);
+ }
+
+ // log_trace("Draw: %d, %d, %d, %d -> %d, %d (%d, %d) z %d\n",
+ // x, y, width, height, dx, dy, ptex->width, ptex->height, z);
+
+ // Bind texture
+ glActiveTexture(GL_TEXTURE1);
+ glBindTexture(GL_TEXTURE_2D, brightness);
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, inner->texture);
+
+ GLuint vao;
+ glGenVertexArrays(1, &vao);
+ glBindVertexArray(vao);
+
+ GLuint bo[2];
+ glGenBuffers(2, bo);
+ glBindBuffer(GL_ARRAY_BUFFER, bo[0]);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bo[1]);
+ glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord) * nrects * 16, coord, GL_STATIC_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)sizeof(*indices) * nrects * 6,
+ indices, GL_STATIC_DRAW);
+
+ glEnableVertexAttribArray(vert_coord_loc);
+ glEnableVertexAttribArray(vert_in_texcoord_loc);
+ glVertexAttribPointer(vert_coord_loc, 2, GL_INT, GL_FALSE, sizeof(GLint) * 4, NULL);
+ glVertexAttribPointer(vert_in_texcoord_loc, 2, GL_INT, GL_FALSE,
+ sizeof(GLint) * 4, (void *)(sizeof(GLint) * 2));
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target);
+ glDrawElements(GL_TRIANGLES, nrects * 6, GL_UNSIGNED_INT, NULL);
+
+ glDisableVertexAttribArray(vert_coord_loc);
+ glDisableVertexAttribArray(vert_in_texcoord_loc);
+ glBindVertexArray(0);
+ glDeleteVertexArrays(1, &vao);
+
+ // Cleanup
+ glBindTexture(GL_TEXTURE_2D, 0);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+ glDrawBuffer(GL_BACK);
+
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glDeleteBuffers(2, bo);
+
+ glUseProgram(0);
+
+ gl_check_err();
+
+ return;
+}
+
+/// Convert rectangles in X coordinates to OpenGL vertex and texture coordinates
+/// @param[in] nrects, rects rectangles
+/// @param[in] dst_x, dst_y origin of the OpenGL texture, affect the calculated texture
+/// coordinates
+/// @param[in] texture_height height of the OpenGL texture
+/// @param[in] root_height height of the back buffer
+/// @param[in] y_inverted whether the texture is y inverted
+/// @param[out] coord, indices output
+static void
+x_rect_to_coords(int nrects, const rect_t *rects, int dst_x, int dst_y, int texture_height,
+ int root_height, bool y_inverted, GLint *coord, GLuint *indices) {
+ dst_y = root_height - dst_y;
+ if (y_inverted) {
+ dst_y -= texture_height;
+ }
+
+ for (int i = 0; i < nrects; i++) {
+ // Y-flip. Note after this, crect.y1 > crect.y2
+ rect_t crect = rects[i];
+ crect.y1 = root_height - crect.y1;
+ crect.y2 = root_height - crect.y2;
+
+ // Calculate texture coordinates
+ // (texture_x1, texture_y1), texture coord for the _bottom left_ corner
+ GLint texture_x1 = crect.x1 - dst_x, texture_y1 = crect.y2 - dst_y,
+ texture_x2 = texture_x1 + (crect.x2 - crect.x1),
+ texture_y2 = texture_y1 + (crect.y1 - crect.y2);
+
+ // X pixmaps might be Y inverted, invert the texture coordinates
+ if (y_inverted) {
+ texture_y1 = texture_height - texture_y1;
+ texture_y2 = texture_height - texture_y2;
+ }
+
+ // Vertex coordinates
+ auto vx1 = crect.x1;
+ auto vy1 = crect.y2;
+ auto vx2 = crect.x2;
+ auto vy2 = crect.y1;
+
+ // log_trace("Rect %d: %f, %f, %f, %f -> %d, %d, %d, %d",
+ // ri, rx, ry, rxe, rye, rdx, rdy, rdxe, rdye);
+
+ memcpy(&coord[i * 16],
+ ((GLint[][2]){
+ {vx1, vy1},
+ {texture_x1, texture_y1},
+ {vx2, vy1},
+ {texture_x2, texture_y1},
+ {vx2, vy2},
+ {texture_x2, texture_y2},
+ {vx1, vy2},
+ {texture_x1, texture_y2},
+ }),
+ sizeof(GLint[2]) * 8);
+
+ GLuint u = (GLuint)(i * 4);
+ memcpy(&indices[i * 6],
+ ((GLuint[]){u + 0, u + 1, u + 2, u + 2, u + 3, u + 0}),
+ sizeof(GLuint) * 6);
+ }
+}
+
+// TODO(yshui) make use of reg_visible
+void gl_compose(backend_t *base, void *image_data,
+ int dst_x1, int dst_y1, int dst_x2, int dst_y2,
+ const region_t *reg_tgt, const region_t *reg_visible attr_unused) {
+ auto gd = (struct gl_data *)base;
+ struct backend_image *img = image_data;
+ auto inner = (struct gl_texture *)img->inner;
+
+ // Painting
+ int nrects;
+ const rect_t *rects;
+ rects = pixman_region32_rectangles((region_t *)reg_tgt, &nrects);
+ if (!nrects) {
+ // Nothing to paint
+ return;
+ }
+
+ // Until we start to use glClipControl, reg_tgt, dst_x and dst_y and
+ // in a different coordinate system than the one OpenGL uses.
+ // OpenGL window coordinate (or NDC) has the origin at the lower left of the
+ // screen, with y axis pointing up; Xorg has the origin at the upper left of the
+ // screen, with y axis pointing down. We have to do some coordinate conversion in
+ // this function
+
+ auto coord = ccalloc(nrects * 16, GLint);
+ auto indices = ccalloc(nrects * 6, GLuint);
+ x_rect_to_coords(nrects, rects, dst_x1, dst_y1, inner->height, gd->height,
+ inner->y_inverted, coord, indices);
+
+ // Interpolate the texture coordinates into the specified range
+ for (unsigned int i = 2; i < 16; i+=4) {
+ coord[i+0] = lerp_range(0, dst_x2 - dst_x1, 0, inner->width, coord[i+0]);
+ coord[i+1] = lerp_range(0, dst_y2 - dst_y1, 0, inner->height, coord[i+1]);
+ }
+
+ _gl_compose(base, img, gd->back_fbo, coord, indices, nrects);
+
+ free(indices);
+ free(coord);
+}
+
+/**
+ * Blur contents in a particular region.
+ */
+bool gl_kernel_blur(backend_t *base, double opacity, void *ctx, const rect_t *extent,
+ const GLuint vao[2], const int vao_nelems[2]) {
+ auto bctx = (struct gl_blur_context *)ctx;
+ auto gd = (struct gl_data *)base;
+
+ int dst_y_fb_coord = bctx->fb_height - extent->y2;
+
+ int curr = 0;
+ for (int i = 0; i < bctx->npasses; ++i) {
+ const gl_blur_shader_t *p = &bctx->blur_shader[i];
+ assert(p->prog);
+
+ assert(bctx->blur_textures[curr]);
+
+ // The origin to use when sampling from the source texture
+ GLint texorig_x = extent->x1, texorig_y = dst_y_fb_coord;
+ GLint tex_width, tex_height;
+ GLuint src_texture;
+
+ if (i == 0) {
+ src_texture = gd->back_texture;
+ tex_width = gd->width;
+ tex_height = gd->height;
+ } else {
+ src_texture = bctx->blur_textures[curr];
+ auto src_size = bctx->texture_sizes[curr];
+ tex_width = src_size.width;
+ tex_height = src_size.height;
+ }
+
+ glBindTexture(GL_TEXTURE_2D, src_texture);
+ glUseProgram(p->prog);
+ glUniform2f(p->uniform_pixel_norm, 1.0f / (GLfloat)tex_width,
+ 1.0f / (GLfloat)tex_height);
+
+ // The number of indices in the selected vertex array
+ GLsizei nelems;
+
+ if (i < bctx->npasses - 1) {
+ assert(bctx->blur_fbos[0]);
+ assert(bctx->blur_textures[!curr]);
+
+ // not last pass, draw into framebuffer, with resized regions
+ glBindVertexArray(vao[1]);
+ nelems = vao_nelems[1];
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[0]);
+
+ glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
+ GL_TEXTURE_2D, bctx->blur_textures[!curr], 0);
+ glDrawBuffer(GL_COLOR_ATTACHMENT0);
+ if (!gl_check_fb_complete(GL_FRAMEBUFFER)) {
+ return false;
+ }
+
+ glUniform1f(p->uniform_opacity, 1.0);
+ } else {
+ // last pass, draw directly into the back buffer, with origin
+ // regions
+ glBindVertexArray(vao[0]);
+ nelems = vao_nelems[0];
+ glBindFramebuffer(GL_FRAMEBUFFER, gd->back_fbo);
+
+ glUniform1f(p->uniform_opacity, (float)opacity);
+ }
+
+ glUniform2f(p->texorig_loc, (GLfloat)texorig_x, (GLfloat)texorig_y);
+ glDrawElements(GL_TRIANGLES, nelems, GL_UNSIGNED_INT, NULL);
+
+ // XXX use multiple draw calls is probably going to be slow than
+ // just simply blur the whole area.
+
+ curr = !curr;
+ }
+
+ return true;
+}
+
+bool gl_dual_kawase_blur(backend_t *base, double opacity, void *ctx, const rect_t *extent,
+ const GLuint vao[2], const int vao_nelems[2]) {
+ auto bctx = (struct gl_blur_context *)ctx;
+ auto gd = (struct gl_data *)base;
+
+ int dst_y_fb_coord = bctx->fb_height - extent->y2;
+
+ int iterations = bctx->blur_texture_count;
+ int scale_factor = 1;
+
+ // Kawase downsample pass
+ const gl_blur_shader_t *down_pass = &bctx->blur_shader[0];
+ assert(down_pass->prog);
+ glUseProgram(down_pass->prog);
+
+ glUniform2f(down_pass->texorig_loc, (GLfloat)extent->x1, (GLfloat)dst_y_fb_coord);
+
+ for (int i = 0; i < iterations; ++i) {
+ // Scale output width / height by half in each iteration
+ scale_factor <<= 1;
+
+ GLuint src_texture;
+ int tex_width, tex_height;
+
+ if (i == 0) {
+ // first pass: copy from back buffer
+ src_texture = gd->back_texture;
+ tex_width = gd->width;
+ tex_height = gd->height;
+ } else {
+ // copy from previous pass
+ src_texture = bctx->blur_textures[i - 1];
+ auto src_size = bctx->texture_sizes[i - 1];
+ tex_width = src_size.width;
+ tex_height = src_size.height;
+ }
+
+ assert(src_texture);
+ assert(bctx->blur_fbos[i]);
+
+ glBindTexture(GL_TEXTURE_2D, src_texture);
+ glBindVertexArray(vao[1]);
+ auto nelems = vao_nelems[1];
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[i]);
+ glDrawBuffer(GL_COLOR_ATTACHMENT0);
+
+ glUniform1f(down_pass->scale_loc, (GLfloat)scale_factor);
+
+ glUniform2f(down_pass->uniform_pixel_norm, 1.0f / (GLfloat)tex_width,
+ 1.0f / (GLfloat)tex_height);
+
+ glDrawElements(GL_TRIANGLES, nelems, GL_UNSIGNED_INT, NULL);
+ }
+
+ // Kawase upsample pass
+ const gl_blur_shader_t *up_pass = &bctx->blur_shader[1];
+ assert(up_pass->prog);
+ glUseProgram(up_pass->prog);
+
+ glUniform2f(up_pass->texorig_loc, (GLfloat)extent->x1, (GLfloat)dst_y_fb_coord);
+
+ for (int i = iterations - 1; i >= 0; --i) {
+ // Scale output width / height back by two in each iteration
+ scale_factor >>= 1;
+
+ const GLuint src_texture = bctx->blur_textures[i];
+ assert(src_texture);
+
+ // Calculate normalized half-width/-height of a src pixel
+ auto src_size = bctx->texture_sizes[i];
+ int tex_width = src_size.width;
+ int tex_height = src_size.height;
+
+ // The number of indices in the selected vertex array
+ GLsizei nelems;
+
+ glBindTexture(GL_TEXTURE_2D, src_texture);
+ if (i > 0) {
+ assert(bctx->blur_fbos[i - 1]);
+
+ // not last pass, draw into next framebuffer
+ glBindVertexArray(vao[1]);
+ nelems = vao_nelems[1];
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[i - 1]);
+ glDrawBuffer(GL_COLOR_ATTACHMENT0);
+
+ glUniform1f(up_pass->uniform_opacity, (GLfloat)1);
+ } else {
+ // last pass, draw directly into the back buffer
+ glBindVertexArray(vao[0]);
+ nelems = vao_nelems[0];
+ glBindFramebuffer(GL_FRAMEBUFFER, gd->back_fbo);
+
+ glUniform1f(up_pass->uniform_opacity, (GLfloat)opacity);
+ }
+
+ glUniform1f(up_pass->scale_loc, (GLfloat)scale_factor);
+ glUniform2f(up_pass->uniform_pixel_norm, 1.0f / (GLfloat)tex_width,
+ 1.0f / (GLfloat)tex_height);
+
+ glDrawElements(GL_TRIANGLES, nelems, GL_UNSIGNED_INT, NULL);
+ }
+
+ return true;
+}
+
+bool gl_blur(backend_t *base, double opacity, void *ctx, const region_t *reg_blur,
+ const region_t *reg_visible attr_unused) {
+ auto bctx = (struct gl_blur_context *)ctx;
+ auto gd = (struct gl_data *)base;
+
+ bool ret = false;
+
+ if (gd->width != bctx->fb_width || gd->height != bctx->fb_height) {
+ // Resize the temporary textures used for blur in case the root
+ // size changed
+ bctx->fb_width = gd->width;
+ bctx->fb_height = gd->height;
+
+ for (int i = 0; i < bctx->blur_texture_count; ++i) {
+ auto tex_size = bctx->texture_sizes + i;
+ if (bctx->method == BLUR_METHOD_DUAL_KAWASE) {
+ // Use smaller textures for each iteration (quarter of the
+ // previous texture)
+ tex_size->width = 1 + ((bctx->fb_width - 1) >> (i + 1));
+ tex_size->height = 1 + ((bctx->fb_height - 1) >> (i + 1));
+ } else {
+ tex_size->width = bctx->fb_width;
+ tex_size->height = bctx->fb_height;
+ }
+
+ glBindTexture(GL_TEXTURE_2D, bctx->blur_textures[i]);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, tex_size->width,
+ tex_size->height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
+
+ if (bctx->method == BLUR_METHOD_DUAL_KAWASE) {
+ // Attach texture to FBO target
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[i]);
+ glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
+ GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ bctx->blur_textures[i], 0);
+ if (!gl_check_fb_complete(GL_FRAMEBUFFER)) {
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ return false;
+ }
+ }
+ }
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+ }
+
+ // Remainder: regions are in Xorg coordinates
+ auto reg_blur_resized =
+ resize_region(reg_blur, bctx->resize_width, bctx->resize_height);
+ const rect_t *extent = pixman_region32_extents((region_t *)reg_blur),
+ *extent_resized = pixman_region32_extents(®_blur_resized);
+ int width = extent->x2 - extent->x1, height = extent->y2 - extent->y1;
+ if (width == 0 || height == 0) {
+ return true;
+ }
+
+ int nrects, nrects_resized;
+ const rect_t *rects = pixman_region32_rectangles((region_t *)reg_blur, &nrects),
+ *rects_resized =
+ pixman_region32_rectangles(®_blur_resized, &nrects_resized);
+ if (!nrects || !nrects_resized) {
+ return true;
+ }
+
+ auto coord = ccalloc(nrects * 16, GLint);
+ auto indices = ccalloc(nrects * 6, GLuint);
+ x_rect_to_coords(nrects, rects, extent_resized->x1, extent_resized->y2,
+ bctx->fb_height, gd->height, false, coord, indices);
+
+ auto coord_resized = ccalloc(nrects_resized * 16, GLint);
+ auto indices_resized = ccalloc(nrects_resized * 6, GLuint);
+ x_rect_to_coords(nrects_resized, rects_resized, extent_resized->x1,
+ extent_resized->y2, bctx->fb_height, bctx->fb_height, false,
+ coord_resized, indices_resized);
+ pixman_region32_fini(®_blur_resized);
+
+ GLuint vao[2];
+ glGenVertexArrays(2, vao);
+ GLuint bo[4];
+ glGenBuffers(4, bo);
+
+ glBindVertexArray(vao[0]);
+ glBindBuffer(GL_ARRAY_BUFFER, bo[0]);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bo[1]);
+ glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord) * nrects * 16, coord, GL_STATIC_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)sizeof(*indices) * nrects * 6,
+ indices, GL_STATIC_DRAW);
+ glEnableVertexAttribArray(vert_coord_loc);
+ glEnableVertexAttribArray(vert_in_texcoord_loc);
+ glVertexAttribPointer(vert_coord_loc, 2, GL_INT, GL_FALSE, sizeof(GLint) * 4, NULL);
+ glVertexAttribPointer(vert_in_texcoord_loc, 2, GL_INT, GL_FALSE,
+ sizeof(GLint) * 4, (void *)(sizeof(GLint) * 2));
+
+ glBindVertexArray(vao[1]);
+ glBindBuffer(GL_ARRAY_BUFFER, bo[2]);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bo[3]);
+ glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord_resized) * nrects_resized * 16,
+ coord_resized, GL_STATIC_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER,
+ (long)sizeof(*indices_resized) * nrects_resized * 6, indices_resized,
+ GL_STATIC_DRAW);
+ glEnableVertexAttribArray(vert_coord_loc);
+ glEnableVertexAttribArray(vert_in_texcoord_loc);
+ glVertexAttribPointer(vert_coord_loc, 2, GL_INT, GL_FALSE, sizeof(GLint) * 4, NULL);
+ glVertexAttribPointer(vert_in_texcoord_loc, 2, GL_INT, GL_FALSE,
+ sizeof(GLint) * 4, (void *)(sizeof(GLint) * 2));
+
+ int vao_nelems[2] = {nrects * 6, nrects_resized * 6};
+
+ if (bctx->method == BLUR_METHOD_DUAL_KAWASE) {
+ ret = gl_dual_kawase_blur(base, opacity, ctx, extent_resized, vao, vao_nelems);
+ } else {
+ ret = gl_kernel_blur(base, opacity, ctx, extent_resized, vao, vao_nelems);
+ }
+
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ glBindTexture(GL_TEXTURE_2D, 0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glDeleteBuffers(4, bo);
+ glBindVertexArray(0);
+ glDeleteVertexArrays(2, vao);
+ glUseProgram(0);
+
+ free(indices);
+ free(coord);
+ free(indices_resized);
+ free(coord_resized);
+
+ gl_check_err();
+ return ret;
+}
+
+// clang-format off
+const char *vertex_shader = GLSL(330,
+ uniform mat4 projection;
+ uniform float scale = 1.0;
+ uniform vec2 texorig;
+ layout(location = 0) in vec2 coord;
+ layout(location = 1) in vec2 in_texcoord;
+ out vec2 texcoord;
+ void main() {
+ gl_Position = projection * vec4(coord, 0, scale);
+ texcoord = in_texcoord + texorig;
+ }
+);
+// clang-format on
+
+/**
+ * Load a GLSL main program from shader strings.
+ */
+static int gl_win_shader_from_string(const char *vshader_str, const char *fshader_str,
+ gl_win_shader_t *ret) {
+ // Build program
+ ret->prog = gl_create_program_from_str(vshader_str, fshader_str);
+ if (!ret->prog) {
+ log_error("Failed to create GLSL program.");
+ return -1;
+ }
+
+ // Get uniform addresses
+ bind_uniform(ret, opacity);
+ bind_uniform(ret, invert_color);
+ bind_uniform(ret, tex);
+ bind_uniform(ret, dim);
+ bind_uniform(ret, brightness);
+ bind_uniform(ret, max_brightness);
+ bind_uniform(ret, corner_radius);
+ bind_uniform(ret, border_width);
+
+ gl_check_err();
+
+ return true;
+}
+
+/**
+ * Callback to run on root window size change.
+ */
+void gl_resize(struct gl_data *gd, int width, int height) {
+ GLint viewport_dimensions[2];
+ glGetIntegerv(GL_MAX_VIEWPORT_DIMS, viewport_dimensions);
+
+ gd->height = height;
+ gd->width = width;
+
+ assert(viewport_dimensions[0] >= gd->width);
+ assert(viewport_dimensions[1] >= gd->height);
+
+ glBindTexture(GL_TEXTURE_2D, gd->back_texture);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_BGR,
+ GL_UNSIGNED_BYTE, NULL);
+
+ gl_check_err();
+}
+
+// clang-format off
+static const char dummy_frag[] = GLSL(330,
+ uniform sampler2D tex;
+ in vec2 texcoord;
+ void main() {
+ gl_FragColor = texelFetch(tex, ivec2(texcoord.xy), 0);
+ }
+);
+
+static const char fill_frag[] = GLSL(330,
+ uniform vec4 color;
+ void main() {
+ gl_FragColor = color;
+ }
+);
+
+static const char fill_vert[] = GLSL(330,
+ layout(location = 0) in vec2 in_coord;
+ uniform mat4 projection;
+ void main() {
+ gl_Position = projection * vec4(in_coord, 0, 1);
+ }
+);
+
+static const char interpolating_frag[] = GLSL(330,
+ uniform sampler2D tex;
+ in vec2 texcoord;
+ void main() {
+ gl_FragColor = vec4(texture2D(tex, vec2(texcoord.xy), 0).rgb, 1);
+ }
+);
+
+static const char interpolating_vert[] = GLSL(330,
+ uniform mat4 projection;
+ uniform vec2 texsize;
+ layout(location = 0) in vec2 in_coord;
+ layout(location = 1) in vec2 in_texcoord;
+ out vec2 texcoord;
+ void main() {
+ gl_Position = projection * vec4(in_coord, 0, 1);
+ texcoord = in_texcoord / texsize;
+ }
+);
+// clang-format on
+
+/// Fill a given region in bound framebuffer.
+/// @param[in] y_inverted whether the y coordinates in `clip` should be inverted
+static void _gl_fill(backend_t *base, struct color c, const region_t *clip, GLuint target,
+ int height, bool y_inverted) {
+ static const GLuint fill_vert_in_coord_loc = 0;
+ int nrects;
+ const rect_t *rect = pixman_region32_rectangles((region_t *)clip, &nrects);
+ auto gd = (struct gl_data *)base;
+
+ GLuint vao;
+ glGenVertexArrays(1, &vao);
+ glBindVertexArray(vao);
+
+ GLuint bo[2];
+ glGenBuffers(2, bo);
+ glUseProgram(gd->fill_shader.prog);
+ glUniform4f(gd->fill_shader.color_loc, (GLfloat)c.red, (GLfloat)c.green,
+ (GLfloat)c.blue, (GLfloat)c.alpha);
+ glEnableVertexAttribArray(fill_vert_in_coord_loc);
+ glBindBuffer(GL_ARRAY_BUFFER, bo[0]);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bo[1]);
+
+ auto coord = ccalloc(nrects * 8, GLint);
+ auto indices = ccalloc(nrects * 6, GLuint);
+ for (int i = 0; i < nrects; i++) {
+ GLint y1 = y_inverted ? height - rect[i].y2 : rect[i].y1,
+ y2 = y_inverted ? height - rect[i].y1 : rect[i].y2;
+ // clang-format off
+ memcpy(&coord[i * 8],
+ ((GLint[][2]){
+ {rect[i].x1, y1}, {rect[i].x2, y1},
+ {rect[i].x2, y2}, {rect[i].x1, y2}}),
+ sizeof(GLint[2]) * 4);
+ // clang-format on
+ indices[i * 6 + 0] = (GLuint)i * 4 + 0;
+ indices[i * 6 + 1] = (GLuint)i * 4 + 1;
+ indices[i * 6 + 2] = (GLuint)i * 4 + 2;
+ indices[i * 6 + 3] = (GLuint)i * 4 + 2;
+ indices[i * 6 + 4] = (GLuint)i * 4 + 3;
+ indices[i * 6 + 5] = (GLuint)i * 4 + 0;
+ }
+ glBufferData(GL_ARRAY_BUFFER, nrects * 8 * (long)sizeof(*coord), coord, GL_STREAM_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, nrects * 6 * (long)sizeof(*indices),
+ indices, GL_STREAM_DRAW);
+
+ glVertexAttribPointer(fill_vert_in_coord_loc, 2, GL_INT, GL_FALSE,
+ sizeof(*coord) * 2, (void *)0);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target);
+ glDrawElements(GL_TRIANGLES, nrects * 6, GL_UNSIGNED_INT, NULL);
+
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glDisableVertexAttribArray(fill_vert_in_coord_loc);
+ glBindVertexArray(0);
+ glDeleteVertexArrays(1, &vao);
+
+ glDeleteBuffers(2, bo);
+ free(indices);
+ free(coord);
+
+ gl_check_err();
+}
+
+void gl_fill(backend_t *base, struct color c, const region_t *clip) {
+ auto gd = (struct gl_data *)base;
+ return _gl_fill(base, c, clip, gd->back_fbo, gd->height, true);
+}
+
+static void gl_release_image_inner(backend_t *base, struct gl_texture *inner) {
+ auto gd = (struct gl_data *)base;
+ if (inner->user_data) {
+ gd->release_user_data(base, inner);
+ }
+ assert(inner->user_data == NULL);
+
+ glDeleteTextures(1, &inner->texture);
+ glDeleteTextures(2, inner->auxiliary_texture);
+ free(inner);
+ gl_check_err();
+}
+
+void gl_release_image(backend_t *base, void *image_data) {
+ struct backend_image *wd = image_data;
+ auto inner = (struct gl_texture *)wd->inner;
+ inner->refcount--;
+ assert(inner->refcount >= 0);
+ if (inner->refcount == 0) {
+ gl_release_image_inner(base, inner);
+ }
+ free(wd);
+}
+
+static inline void gl_free_blur_shader(gl_blur_shader_t *shader) {
+ if (shader->prog) {
+ glDeleteProgram(shader->prog);
+ }
+
+ shader->prog = 0;
+}
+
+void gl_destroy_blur_context(backend_t *base attr_unused, void *ctx) {
+ auto bctx = (struct gl_blur_context *)ctx;
+ // Free GLSL shaders/programs
+ for (int i = 0; i < bctx->npasses; ++i) {
+ gl_free_blur_shader(&bctx->blur_shader[i]);
+ }
+ free(bctx->blur_shader);
+
+ if (bctx->blur_texture_count && bctx->blur_textures) {
+ glDeleteTextures(bctx->blur_texture_count, bctx->blur_textures);
+ free(bctx->blur_textures);
+ }
+ if (bctx->blur_texture_count && bctx->texture_sizes) {
+ free(bctx->texture_sizes);
+ }
+ if (bctx->blur_fbo_count && bctx->blur_fbos) {
+ glDeleteFramebuffers(bctx->blur_fbo_count, bctx->blur_fbos);
+ free(bctx->blur_fbos);
+ }
+
+ bctx->blur_texture_count = 0;
+ bctx->blur_fbo_count = 0;
+
+ free(bctx);
+
+ gl_check_err();
+}
+
+/**
+ * Initialize GL blur filters.
+ */
+bool gl_create_kernel_blur_context(void *blur_context, GLfloat *projection,
+ enum blur_method method, void *args) {
+ bool success = false;
+ auto ctx = (struct gl_blur_context *)blur_context;
+
+ struct conv **kernels;
+
+ int nkernels;
+ ctx->method = BLUR_METHOD_KERNEL;
+ if (method == BLUR_METHOD_KERNEL) {
+ nkernels = ((struct kernel_blur_args *)args)->kernel_count;
+ kernels = ((struct kernel_blur_args *)args)->kernels;
+ } else {
+ kernels = generate_blur_kernel(method, args, &nkernels);
+ }
+
+ if (!nkernels) {
+ ctx->method = BLUR_METHOD_NONE;
+ return true;
+ }
+
+ // Specify required textures and FBOs
+ ctx->blur_texture_count = 2;
+ ctx->blur_fbo_count = 1;
+
+ ctx->blur_shader = ccalloc(max2(2, nkernels), gl_blur_shader_t);
+
+ char *lc_numeric_old = strdup(setlocale(LC_NUMERIC, NULL));
+ // Enforce LC_NUMERIC locale "C" here to make sure decimal point is sane
+ // Thanks to hiciu for reporting.
+ setlocale(LC_NUMERIC, "C");
+
+ // clang-format off
+ static const char *FRAG_SHADER_BLUR = GLSL(330,
+ %s\n // other extension pragmas
+ uniform sampler2D tex_src;
+ uniform vec2 pixel_norm;
+ uniform float opacity;
+ in vec2 texcoord;
+ out vec4 out_color;
+ void main() {
+ vec2 uv = texcoord * pixel_norm;
+ vec4 sum = vec4(0.0, 0.0, 0.0, 0.0);
+ %s //body of the convolution
+ out_color = sum / float(%.7g) * opacity;
+ }
+ );
+ static const char *FRAG_SHADER_BLUR_ADD = QUOTE(
+ sum += float(%.7g) * texture2D(tex_src, uv + pixel_norm * vec2(%.7g, %.7g));
+ );
+ // clang-format on
+
+ const char *shader_add = FRAG_SHADER_BLUR_ADD;
+ char *extension = strdup("");
+
+ for (int i = 0; i < nkernels; i++) {
+ auto kern = kernels[i];
+ // Build shader
+ int width = kern->w, height = kern->h;
+ int nele = width * height;
+ // '%.7g' is at most 14 characters, inserted 3 times
+ size_t body_len = (strlen(shader_add) + 42) * (uint)nele;
+ char *shader_body = ccalloc(body_len, char);
+ char *pc = shader_body;
+
+ // Make use of the linear interpolation hardware by sampling 2 pixels with
+ // one texture access by sampling between both pixels based on their
+ // relative weight. Easiest done in a single dimension as 2D bilinear
+ // filtering would raise additional constraints on the kernels. Therefore
+ // only use interpolation along the larger dimension.
+ double sum = 0.0;
+ if (width > height) {
+ // use interpolation in x dimension (width)
+ for (int j = 0; j < height; ++j) {
+ for (int k = 0; k < width; k += 2) {
+ double val1, val2;
+ val1 = kern->data[j * width + k];
+ val2 = (k + 1 < width)
+ ? kern->data[j * width + k + 1]
+ : 0;
+
+ double combined_weight = val1 + val2;
+ if (combined_weight == 0) {
+ continue;
+ }
+ sum += combined_weight;
+
+ double offset_x =
+ k + (val2 / combined_weight) - (width / 2);
+ double offset_y = j - (height / 2);
+ pc += snprintf(
+ pc, body_len - (ulong)(pc - shader_body),
+ shader_add, combined_weight, offset_x, offset_y);
+ assert(pc < shader_body + body_len);
+ }
+ }
+ } else {
+ // use interpolation in y dimension (height)
+ for (int j = 0; j < height; j += 2) {
+ for (int k = 0; k < width; ++k) {
+ double val1, val2;
+ val1 = kern->data[j * width + k];
+ val2 = (j + 1 < height)
+ ? kern->data[(j + 1) * width + k]
+ : 0;
+
+ double combined_weight = val1 + val2;
+ if (combined_weight == 0) {
+ continue;
+ }
+ sum += combined_weight;
+
+ double offset_x = k - (width / 2);
+ double offset_y =
+ j + (val2 / combined_weight) - (height / 2);
+ pc += snprintf(
+ pc, body_len - (ulong)(pc - shader_body),
+ shader_add, combined_weight, offset_x, offset_y);
+ assert(pc < shader_body + body_len);
+ }
+ }
+ }
+
+ auto pass = ctx->blur_shader + i;
+ size_t shader_len = strlen(FRAG_SHADER_BLUR) + strlen(extension) +
+ strlen(shader_body) + 10 /* sum */ +
+ 1 /* null terminator */;
+ char *shader_str = ccalloc(shader_len, char);
+ auto real_shader_len = snprintf(shader_str, shader_len, FRAG_SHADER_BLUR,
+ extension, shader_body, sum);
+ CHECK(real_shader_len >= 0);
+ CHECK((size_t)real_shader_len < shader_len);
+ free(shader_body);
+
+ // Build program
+ pass->prog = gl_create_program_from_str(vertex_shader, shader_str);
+ free(shader_str);
+ if (!pass->prog) {
+ log_error("Failed to create GLSL program.");
+ success = false;
+ goto out;
+ }
+ glBindFragDataLocation(pass->prog, 0, "out_color");
+
+ // Get uniform addresses
+ bind_uniform(pass, pixel_norm);
+ bind_uniform(pass, opacity);
+ pass->texorig_loc = glGetUniformLocationChecked(pass->prog, "texorig");
+
+ // Setup projection matrix
+ glUseProgram(pass->prog);
+ int pml = glGetUniformLocationChecked(pass->prog, "projection");
+ glUniformMatrix4fv(pml, 1, false, projection);
+ glUseProgram(0);
+
+ ctx->resize_width += kern->w / 2;
+ ctx->resize_height += kern->h / 2;
+ }
+
+ if (nkernels == 1) {
+ // Generate an extra null pass so we don't need special code path for
+ // the single pass case
+ auto pass = &ctx->blur_shader[1];
+ pass->prog = gl_create_program_from_str(vertex_shader, dummy_frag);
+ pass->uniform_pixel_norm = -1;
+ pass->uniform_opacity = -1;
+ pass->texorig_loc = glGetUniformLocationChecked(pass->prog, "texorig");
+
+ // Setup projection matrix
+ glUseProgram(pass->prog);
+ int pml = glGetUniformLocationChecked(pass->prog, "projection");
+ glUniformMatrix4fv(pml, 1, false, projection);
+ glUseProgram(0);
+
+ ctx->npasses = 2;
+ } else {
+ ctx->npasses = nkernels;
+ }
+
+ success = true;
+out:
+ if (method != BLUR_METHOD_KERNEL) {
+ // We generated the blur kernels, so we need to free them
+ for (int i = 0; i < nkernels; i++) {
+ free(kernels[i]);
+ }
+ free(kernels);
+ }
+
+ free(extension);
+ // Restore LC_NUMERIC
+ setlocale(LC_NUMERIC, lc_numeric_old);
+ free(lc_numeric_old);
+
+ return success;
+}
+
+bool gl_create_dual_kawase_blur_context(void *blur_context, GLfloat *projection,
+ enum blur_method method, void *args) {
+ bool success = false;
+ auto ctx = (struct gl_blur_context *)blur_context;
+
+ ctx->method = method;
+
+ auto blur_params = generate_dual_kawase_params(args);
+
+ // Specify required textures and FBOs
+ ctx->blur_texture_count = blur_params->iterations;
+ ctx->blur_fbo_count = blur_params->iterations;
+
+ ctx->resize_width += blur_params->expand;
+ ctx->resize_height += blur_params->expand;
+
+ ctx->npasses = 2;
+ ctx->blur_shader = ccalloc(ctx->npasses, gl_blur_shader_t);
+
+ char *lc_numeric_old = strdup(setlocale(LC_NUMERIC, NULL));
+ // Enforce LC_NUMERIC locale "C" here to make sure decimal point is sane
+ // Thanks to hiciu for reporting.
+ setlocale(LC_NUMERIC, "C");
+
+ // Dual-kawase downsample shader / program
+ auto down_pass = ctx->blur_shader;
+ {
+ // clang-format off
+ static const char *FRAG_SHADER_DOWN = GLSL(330,
+ uniform sampler2D tex_src;
+ uniform float scale = 1.0;
+ uniform vec2 pixel_norm;
+ in vec2 texcoord;
+ out vec4 out_color;
+ void main() {
+ vec2 offset = %.7g * pixel_norm;
+ vec2 uv = texcoord * pixel_norm * (2.0 / scale);
+ vec4 sum = texture2D(tex_src, uv) * 4.0;
+ sum += texture2D(tex_src, uv - vec2(0.5, 0.5) * offset);
+ sum += texture2D(tex_src, uv + vec2(0.5, 0.5) * offset);
+ sum += texture2D(tex_src, uv + vec2(0.5, -0.5) * offset);
+ sum += texture2D(tex_src, uv - vec2(0.5, -0.5) * offset);
+ out_color = sum / 8.0;
+ }
+ );
+ // clang-format on
+
+ // Build shader
+ size_t shader_len =
+ strlen(FRAG_SHADER_DOWN) + 10 /* offset */ + 1 /* null terminator */;
+ char *shader_str = ccalloc(shader_len, char);
+ auto real_shader_len =
+ snprintf(shader_str, shader_len, FRAG_SHADER_DOWN, blur_params->offset);
+ CHECK(real_shader_len >= 0);
+ CHECK((size_t)real_shader_len < shader_len);
+
+ // Build program
+ down_pass->prog = gl_create_program_from_str(vertex_shader, shader_str);
+ free(shader_str);
+ if (!down_pass->prog) {
+ log_error("Failed to create GLSL program.");
+ success = false;
+ goto out;
+ }
+ glBindFragDataLocation(down_pass->prog, 0, "out_color");
+
+ // Get uniform addresses
+ bind_uniform(down_pass, pixel_norm);
+ down_pass->texorig_loc =
+ glGetUniformLocationChecked(down_pass->prog, "texorig");
+ down_pass->scale_loc =
+ glGetUniformLocationChecked(down_pass->prog, "scale");
+
+ // Setup projection matrix
+ glUseProgram(down_pass->prog);
+ int pml = glGetUniformLocationChecked(down_pass->prog, "projection");
+ glUniformMatrix4fv(pml, 1, false, projection);
+ glUseProgram(0);
+ }
+
+ // Dual-kawase upsample shader / program
+ auto up_pass = ctx->blur_shader + 1;
+ {
+ // clang-format off
+ static const char *FRAG_SHADER_UP = GLSL(330,
+ uniform sampler2D tex_src;
+ uniform float scale = 1.0;
+ uniform vec2 pixel_norm;
+ uniform float opacity;
+ in vec2 texcoord;
+ out vec4 out_color;
+ void main() {
+ vec2 offset = %.7g * pixel_norm;
+ vec2 uv = texcoord * pixel_norm / (2 * scale);
+ vec4 sum = texture2D(tex_src, uv + vec2(-1.0, 0.0) * offset);
+ sum += texture2D(tex_src, uv + vec2(-0.5, 0.5) * offset) * 2.0;
+ sum += texture2D(tex_src, uv + vec2(0.0, 1.0) * offset);
+ sum += texture2D(tex_src, uv + vec2(0.5, 0.5) * offset) * 2.0;
+ sum += texture2D(tex_src, uv + vec2(1.0, 0.0) * offset);
+ sum += texture2D(tex_src, uv + vec2(0.5, -0.5) * offset) * 2.0;
+ sum += texture2D(tex_src, uv + vec2(0.0, -1.0) * offset);
+ sum += texture2D(tex_src, uv + vec2(-0.5, -0.5) * offset) * 2.0;
+ out_color = sum / 12.0 * opacity;
+ }
+ );
+ // clang-format on
+
+ // Build shader
+ size_t shader_len =
+ strlen(FRAG_SHADER_UP) + 10 /* offset */ + 1 /* null terminator */;
+ char *shader_str = ccalloc(shader_len, char);
+ auto real_shader_len =
+ snprintf(shader_str, shader_len, FRAG_SHADER_UP, blur_params->offset);
+ CHECK(real_shader_len >= 0);
+ CHECK((size_t)real_shader_len < shader_len);
+
+ // Build program
+ up_pass->prog = gl_create_program_from_str(vertex_shader, shader_str);
+ free(shader_str);
+ if (!up_pass->prog) {
+ log_error("Failed to create GLSL program.");
+ success = false;
+ goto out;
+ }
+ glBindFragDataLocation(up_pass->prog, 0, "out_color");
+
+ // Get uniform addresses
+ bind_uniform(up_pass, pixel_norm);
+ bind_uniform(up_pass, opacity);
+ up_pass->texorig_loc =
+ glGetUniformLocationChecked(up_pass->prog, "texorig");
+ up_pass->scale_loc = glGetUniformLocationChecked(up_pass->prog, "scale");
+
+ // Setup projection matrix
+ glUseProgram(up_pass->prog);
+ int pml = glGetUniformLocationChecked(up_pass->prog, "projection");
+ glUniformMatrix4fv(pml, 1, false, projection);
+ glUseProgram(0);
+ }
+
+ success = true;
+out:
+ free(blur_params);
+
+ if (!success) {
+ ctx = NULL;
+ }
+
+ // Restore LC_NUMERIC
+ setlocale(LC_NUMERIC, lc_numeric_old);
+ free(lc_numeric_old);
+
+ return success;
+}
+
+void *gl_create_blur_context(backend_t *base, enum blur_method method, void *args) {
+ bool success;
+ auto gd = (struct gl_data *)base;
+
+ auto ctx = ccalloc(1, struct gl_blur_context);
+
+ if (!method || method >= BLUR_METHOD_INVALID) {
+ ctx->method = BLUR_METHOD_NONE;
+ return ctx;
+ }
+
+ // Set projection matrix to gl viewport dimensions so we can use screen
+ // coordinates for all vertices
+ // Note: OpenGL matrices are column major
+ GLint viewport_dimensions[2];
+ glGetIntegerv(GL_MAX_VIEWPORT_DIMS, viewport_dimensions);
+ GLfloat projection_matrix[4][4] = {{2.0f / (GLfloat)viewport_dimensions[0], 0, 0, 0},
+ {0, 2.0f / (GLfloat)viewport_dimensions[1], 0, 0},
+ {0, 0, 0, 0},
+ {-1, -1, 0, 1}};
+
+ if (method == BLUR_METHOD_DUAL_KAWASE) {
+ success = gl_create_dual_kawase_blur_context(ctx, projection_matrix[0],
+ method, args);
+ } else {
+ success =
+ gl_create_kernel_blur_context(ctx, projection_matrix[0], method, args);
+ }
+ if (!success || ctx->method == BLUR_METHOD_NONE) {
+ goto out;
+ }
+
+ // Texture size will be defined by gl_blur
+ ctx->blur_textures = ccalloc(ctx->blur_texture_count, GLuint);
+ ctx->texture_sizes = ccalloc(ctx->blur_texture_count, struct texture_size);
+ glGenTextures(ctx->blur_texture_count, ctx->blur_textures);
+
+ for (int i = 0; i < ctx->blur_texture_count; ++i) {
+ glBindTexture(GL_TEXTURE_2D, ctx->blur_textures[i]);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ }
+
+ // Generate FBO and textures when needed
+ ctx->blur_fbos = ccalloc(ctx->blur_fbo_count, GLuint);
+ glGenFramebuffers(ctx->blur_fbo_count, ctx->blur_fbos);
+
+ for (int i = 0; i < ctx->blur_fbo_count; ++i) {
+ if (!ctx->blur_fbos[i]) {
+ log_error("Failed to generate framebuffer objects for blur");
+ success = false;
+ goto out;
+ }
+ }
+
+out:
+ if (!success) {
+ gl_destroy_blur_context(&gd->base, ctx);
+ ctx = NULL;
+ }
+
+ gl_check_err();
+ return ctx;
+}
+
+void gl_get_blur_size(void *blur_context, int *width, int *height) {
+ auto ctx = (struct gl_blur_context *)blur_context;
+ *width = ctx->resize_width;
+ *height = ctx->resize_height;
+}
+
+// clang-format off
+const char *win_shader_glsl = GLSL(330,
+ uniform float opacity;
+ uniform float dim;
+ uniform float corner_radius;
+ uniform float border_width;
+ uniform bool invert_color;
+ in vec2 texcoord;
+ uniform sampler2D tex;
+ uniform sampler2D brightness;
+ uniform float max_brightness;
+ // Signed distance field for rectangle center at (0, 0), with size of
+ // half_size * 2
+ float rectangle_sdf(vec2 point, vec2 half_size) {
+ vec2 d = abs(point) - half_size;
+ return length(max(d, 0.0));
+ }
+
+ void main() {
+ vec4 c = texelFetch(tex, ivec2(texcoord), 0);
+ vec4 border_color = texture(tex, vec2(0.0, 0.5));
+ if (invert_color) {
+ c = vec4(c.aaa - c.rgb, c.a);
+ border_color = vec4(border_color.aaa - border_color.rgb, border_color.a);
+ }
+ c = vec4(c.rgb * (1.0 - dim), c.a) * opacity;
+ border_color = vec4(border_color.rgb * (1.0 - dim), border_color.a) * opacity;
+
+ vec3 rgb_brightness = texelFetch(brightness, ivec2(0, 0), 0).rgb;
+ // Ref: https://en.wikipedia.org/wiki/Relative_luminance
+ float brightness = rgb_brightness.r * 0.21 +
+ rgb_brightness.g * 0.72 +
+ rgb_brightness.b * 0.07;
+ if (brightness > max_brightness) {
+ c.rgb = c.rgb * (max_brightness / brightness);
+ border_color.rgb = border_color.rgb * (max_brightness / brightness);
+ }
+
+ // Rim color is the color of the outer rim of the window, if there is no
+ // border, it's the color of the window itself, otherwise it's the border.
+ // Using mix() to avoid a branch here.
+ vec4 rim_color = mix(c, border_color, clamp(border_width, 0.0f, 1.0f));
+
+ vec2 outer_size = vec2(textureSize(tex, 0));
+ vec2 inner_size = outer_size - vec2(corner_radius) * 2.0f - 1;
+ float rect_distance = rectangle_sdf(texcoord - outer_size / 2.0f,
+ inner_size / 2.0f) - corner_radius;
+ if (rect_distance > 0.0f) {
+ c = (1.0f - clamp(rect_distance, 0.0f, 1.0f)) * rim_color;
+ } else {
+ float factor = clamp(rect_distance + border_width, 0.0f, 1.0f);
+ c = (1.0f - factor) * c + factor * border_color;
+ }
+
+ gl_FragColor = c;
+ }
+);
+
+const char *present_vertex_shader = GLSL(330,
+ uniform mat4 projection;
+ layout(location = 0) in vec2 coord;
+ out vec2 texcoord;
+ void main() {
+ gl_Position = projection * vec4(coord, 0, 1);
+ texcoord = coord;
+ }
+);
+// clang-format on
+
+bool gl_init(struct gl_data *gd, session_t *ps) {
+ // Initialize GLX data structure
+ glDisable(GL_DEPTH_TEST);
+ glDepthMask(GL_FALSE);
+
+ glEnable(GL_BLEND);
+ // X pixmap is in premultiplied alpha, so we might just as well use it too.
+ // Thanks to derhass for help.
+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+
+ // Initialize stencil buffer
+ glDisable(GL_STENCIL_TEST);
+ glStencilMask(0x1);
+ glStencilFunc(GL_EQUAL, 0x1, 0x1);
+
+ // Set gl viewport to the maximum supported size so we won't have to worry about
+ // it later on when the screen is resized. The corresponding projection matrix can
+ // be set now and won't have to be updated. Since fragments outside the target
+ // buffer are skipped anyways, this should have no impact on performance.
+ GLint viewport_dimensions[2];
+ glGetIntegerv(GL_MAX_VIEWPORT_DIMS, viewport_dimensions);
+ glViewport(0, 0, viewport_dimensions[0], viewport_dimensions[1]);
+
+ // Clear screen
+ glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+ glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
+
+ glGenFramebuffers(1, &gd->back_fbo);
+ glGenTextures(1, &gd->back_texture);
+ if (!gd->back_fbo || !gd->back_texture) {
+ log_error("Failed to generate a framebuffer object");
+ return false;
+ }
+
+ glBindTexture(GL_TEXTURE_2D, gd->back_texture);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ // Set projection matrix to gl viewport dimensions so we can use screen
+ // coordinates for all vertices
+ // Note: OpenGL matrices are column major
+ GLfloat projection_matrix[4][4] = {{2.0f / (GLfloat)viewport_dimensions[0], 0, 0, 0},
+ {0, 2.0f / (GLfloat)viewport_dimensions[1], 0, 0},
+ {0, 0, 0, 0},
+ {-1, -1, 0, 1}};
+
+ // Initialize shaders
+ gl_win_shader_from_string(vertex_shader, win_shader_glsl, &gd->win_shader);
+ int pml = glGetUniformLocationChecked(gd->win_shader.prog, "projection");
+ glUseProgram(gd->win_shader.prog);
+ glUniformMatrix4fv(pml, 1, false, projection_matrix[0]);
+ glUseProgram(0);
+
+ gd->fill_shader.prog = gl_create_program_from_str(fill_vert, fill_frag);
+ gd->fill_shader.color_loc = glGetUniformLocation(gd->fill_shader.prog, "color");
+ pml = glGetUniformLocationChecked(gd->fill_shader.prog, "projection");
+ glUseProgram(gd->fill_shader.prog);
+ glUniformMatrix4fv(pml, 1, false, projection_matrix[0]);
+ glUseProgram(0);
+
+ gd->present_prog = gl_create_program_from_str(present_vertex_shader, dummy_frag);
+ if (!gd->present_prog) {
+ log_error("Failed to create the present shader");
+ return false;
+ }
+ pml = glGetUniformLocationChecked(gd->present_prog, "projection");
+ glUseProgram(gd->present_prog);
+ glUniform1i(glGetUniformLocationChecked(gd->present_prog, "tex"), 0);
+ glUniformMatrix4fv(pml, 1, false, projection_matrix[0]);
+ glUseProgram(0);
+
+ gd->brightness_shader.prog =
+ gl_create_program_from_str(interpolating_vert, interpolating_frag);
+ if (!gd->brightness_shader.prog) {
+ log_error("Failed to create the brightness shader");
+ return false;
+ }
+ pml = glGetUniformLocationChecked(gd->brightness_shader.prog, "projection");
+ glUseProgram(gd->brightness_shader.prog);
+ glUniform1i(glGetUniformLocationChecked(gd->brightness_shader.prog, "tex"), 0);
+ glUniformMatrix4fv(pml, 1, false, projection_matrix[0]);
+ glUseProgram(0);
+
+ // Set up the size of the back texture
+ gl_resize(gd, ps->root_width, ps->root_height);
+
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gd->back_fbo);
+ glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ gd->back_texture, 0);
+ glDrawBuffer(GL_COLOR_ATTACHMENT0);
+ if (!gl_check_fb_complete(GL_FRAMEBUFFER)) {
+ return false;
+ }
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+
+ gd->logger = gl_string_marker_logger_new();
+ if (gd->logger) {
+ log_add_target_tls(gd->logger);
+ }
+
+ const char *vendor = (const char *)glGetString(GL_VENDOR);
+ log_debug("GL_VENDOR = %s", vendor);
+ if (strcmp(vendor, "NVIDIA Corporation") == 0) {
+ log_info("GL vendor is NVIDIA, don't use glFinish");
+ gd->is_nvidia = true;
+ } else {
+ gd->is_nvidia = false;
+ }
+ gd->has_robustness = gl_has_extension("GL_ARB_robustness");
+
+ return true;
+}
+
+void gl_deinit(struct gl_data *gd) {
+ gl_free_prog_main(&gd->win_shader);
+
+ if (gd->logger) {
+ log_remove_target_tls(gd->logger);
+ gd->logger = NULL;
+ }
+
+ gl_check_err();
+}
+
+GLuint gl_new_texture(GLenum target) {
+ GLuint texture;
+ glGenTextures(1, &texture);
+ if (!texture) {
+ log_error("Failed to generate texture");
+ return 0;
+ }
+
+ glBindTexture(target, texture);
+ glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ glBindTexture(target, 0);
+
+ return texture;
+}
+
+/// Actually duplicate a texture into a new one, if this texture is shared
+static inline void gl_image_decouple(backend_t *base, struct backend_image *img) {
+ if (img->inner->refcount == 1) {
+ return;
+ }
+ auto gd = (struct gl_data *)base;
+ auto inner = (struct gl_texture *)img->inner;
+ auto new_tex = ccalloc(1, struct gl_texture);
+
+ new_tex->texture = gl_new_texture(GL_TEXTURE_2D);
+ new_tex->y_inverted = true;
+ new_tex->height = inner->height;
+ new_tex->width = inner->width;
+ new_tex->refcount = 1;
+ new_tex->user_data = gd->decouple_texture_user_data(base, inner->user_data);
+
+ glBindTexture(GL_TEXTURE_2D, new_tex->texture);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, new_tex->width, new_tex->height, 0,
+ GL_BGRA, GL_UNSIGNED_BYTE, NULL);
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ assert(gd->present_prog);
+ glUseProgram(gd->present_prog);
+ glBindTexture(GL_TEXTURE_2D, inner->texture);
+
+ GLuint fbo;
+ glGenFramebuffers(1, &fbo);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
+ glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ new_tex->texture, 0);
+ glDrawBuffer(GL_COLOR_ATTACHMENT0);
+ gl_check_fb_complete(GL_DRAW_FRAMEBUFFER);
+
+ glClearColor(0, 0, 0, 0);
+ glClear(GL_COLOR_BUFFER_BIT);
+
+ // clang-format off
+ GLint coord[] = {
+ // top left
+ 0, 0, // vertex coord
+ 0, 0, // texture coord
+
+ // top right
+ new_tex->width, 0, // vertex coord
+ new_tex->width, 0, // texture coord
+
+ // bottom right
+ new_tex->width, new_tex->height,
+ new_tex->width, new_tex->height,
+
+ // bottom left
+ 0, new_tex->height,
+ 0, new_tex->height,
+ };
+ // clang-format on
+ GLuint indices[] = {0, 1, 2, 2, 3, 0};
+
+ GLuint vao;
+ glGenVertexArrays(1, &vao);
+ glBindVertexArray(vao);
+
+ GLuint bo[2];
+ glGenBuffers(2, bo);
+ glBindBuffer(GL_ARRAY_BUFFER, bo[0]);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bo[1]);
+ glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord) * 16, coord, GL_STATIC_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)sizeof(*indices) * 6, indices,
+ GL_STATIC_DRAW);
+
+ glEnableVertexAttribArray(vert_coord_loc);
+ glEnableVertexAttribArray(vert_in_texcoord_loc);
+ glVertexAttribPointer(vert_coord_loc, 2, GL_INT, GL_FALSE, sizeof(GLint) * 4, NULL);
+ glVertexAttribPointer(vert_in_texcoord_loc, 2, GL_INT, GL_FALSE,
+ sizeof(GLint) * 4, (void *)(sizeof(GLint) * 2));
+
+ glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);
+
+ glDisableVertexAttribArray(vert_coord_loc);
+ glDisableVertexAttribArray(vert_in_texcoord_loc);
+ glBindVertexArray(0);
+ glDeleteVertexArrays(1, &vao);
+
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glDeleteBuffers(2, bo);
+
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+ glDeleteFramebuffers(1, &fbo);
+
+ glBindTexture(GL_TEXTURE_2D, 0);
+ glUseProgram(0);
+
+ gl_check_err();
+
+ img->inner = (struct backend_image_inner_base *)new_tex;
+ inner->refcount--;
+}
+
+static void gl_image_apply_alpha(backend_t *base, struct backend_image *img,
+ const region_t *reg_op, double alpha) {
+ // Result color = 0 (GL_ZERO) + alpha (GL_CONSTANT_ALPHA) * original color
+ auto inner = (struct gl_texture *)img->inner;
+ glBlendFunc(GL_ZERO, GL_CONSTANT_ALPHA);
+ glBlendColor(0, 0, 0, (GLclampf)alpha);
+ GLuint fbo;
+ glGenFramebuffers(1, &fbo);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
+ glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ inner->texture, 0);
+ glDrawBuffer(GL_COLOR_ATTACHMENT0);
+ _gl_fill(base, (struct color){0, 0, 0, 0}, reg_op, fbo, 0, false);
+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+ glDeleteFramebuffers(1, &fbo);
+}
+
+void gl_present(backend_t *base, const region_t *region) {
+ auto gd = (struct gl_data *)base;
+
+ int nrects;
+ const rect_t *rect = pixman_region32_rectangles((region_t *)region, &nrects);
+ auto coord = ccalloc(nrects * 8, GLint);
+ auto indices = ccalloc(nrects * 6, GLuint);
+ for (int i = 0; i < nrects; i++) {
+ // clang-format off
+ memcpy(&coord[i * 8],
+ ((GLint[]){rect[i].x1, gd->height - rect[i].y2,
+ rect[i].x2, gd->height - rect[i].y2,
+ rect[i].x2, gd->height - rect[i].y1,
+ rect[i].x1, gd->height - rect[i].y1}),
+ sizeof(GLint) * 8);
+ // clang-format on
+
+ GLuint u = (GLuint)(i * 4);
+ memcpy(&indices[i * 6],
+ ((GLuint[]){u + 0, u + 1, u + 2, u + 2, u + 3, u + 0}),
+ sizeof(GLuint) * 6);
+ }
+
+ glUseProgram(gd->present_prog);
+ glBindTexture(GL_TEXTURE_2D, gd->back_texture);
+
+ GLuint vao;
+ glGenVertexArrays(1, &vao);
+ glBindVertexArray(vao);
+
+ GLuint bo[2];
+ glGenBuffers(2, bo);
+ glEnableVertexAttribArray(vert_coord_loc);
+ glBindBuffer(GL_ARRAY_BUFFER, bo[0]);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bo[1]);
+ glBufferData(GL_ARRAY_BUFFER, (long)sizeof(GLint) * nrects * 8, coord, GL_STREAM_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)sizeof(GLuint) * nrects * 6, indices,
+ GL_STREAM_DRAW);
+
+ glVertexAttribPointer(vert_coord_loc, 2, GL_INT, GL_FALSE, sizeof(GLint) * 2, NULL);
+ glDrawElements(GL_TRIANGLES, nrects * 6, GL_UNSIGNED_INT, NULL);
+
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glBindVertexArray(0);
+ glDeleteBuffers(2, bo);
+ glDeleteVertexArrays(1, &vao);
+
+ free(coord);
+ free(indices);
+}
+
+bool gl_image_op(backend_t *base, enum image_operations op, void *image_data,
+ const region_t *reg_op, const region_t *reg_visible attr_unused, void *arg) {
+ struct backend_image *tex = image_data;
+ switch (op) {
+ case IMAGE_OP_APPLY_ALPHA:
+ gl_image_decouple(base, tex);
+ assert(tex->inner->refcount == 1);
+ gl_image_apply_alpha(base, tex, reg_op, *(double *)arg);
+ break;
+ }
+
+ return true;
+}
+
+enum device_status gl_device_status(backend_t *base) {
+ auto gd = (struct gl_data *)base;
+ if (!gd->has_robustness) {
+ return DEVICE_STATUS_NORMAL;
+ }
+ if (glGetGraphicsResetStatusARB() == GL_NO_ERROR) {
+ return DEVICE_STATUS_NORMAL;
+ } else {
+ return DEVICE_STATUS_RESETTING;
+ }
+}
diff --git a/dwm/picom/src/backend/gl/gl_common.h b/dwm/picom/src/backend/gl/gl_common.h
new file mode 100644
index 0000000..8bbbabb
--- /dev/null
+++ b/dwm/picom/src/backend/gl/gl_common.h
@@ -0,0 +1,238 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#pragma once
+#include
+#include
+#include
+#include
+
+#include "backend/backend.h"
+#include "log.h"
+#include "region.h"
+
+#define CASESTRRET(s) \
+ case s: return #s
+
+static inline GLint glGetUniformLocationChecked(GLuint p, const char *name) {
+ auto ret = glGetUniformLocation(p, name);
+ if (ret < 0) {
+ log_info("Failed to get location of uniform '%s'. This is normal when "
+ "using custom shaders.",
+ name);
+ }
+ return ret;
+}
+
+#define bind_uniform(shader, uniform) \
+ (shader)->uniform_##uniform = glGetUniformLocationChecked((shader)->prog, #uniform)
+
+// Program and uniforms for window shader
+typedef struct {
+ GLuint prog;
+ GLint uniform_opacity;
+ GLint uniform_invert_color;
+ GLint uniform_tex;
+ GLint uniform_dim;
+ GLint uniform_brightness;
+ GLint uniform_max_brightness;
+ GLint uniform_corner_radius;
+ GLint uniform_border_width;
+} gl_win_shader_t;
+
+// Program and uniforms for brightness shader
+typedef struct {
+ GLuint prog;
+} gl_brightness_shader_t;
+
+// Program and uniforms for blur shader
+typedef struct {
+ GLuint prog;
+ GLint uniform_pixel_norm;
+ GLint uniform_opacity;
+ GLint texorig_loc;
+ GLint scale_loc;
+} gl_blur_shader_t;
+
+typedef struct {
+ GLuint prog;
+ GLint color_loc;
+} gl_fill_shader_t;
+
+/// @brief Wrapper of a binded GLX texture.
+struct gl_texture {
+ int refcount;
+ bool has_alpha;
+ GLuint texture;
+ int width, height;
+ bool y_inverted;
+
+ // Textures for auxiliary uses.
+ GLuint auxiliary_texture[2];
+ void *user_data;
+};
+
+struct gl_data {
+ backend_t base;
+ // If we are using proprietary NVIDIA driver
+ bool is_nvidia;
+ // If ARB_robustness extension is present
+ bool has_robustness;
+ // Height and width of the root window
+ int height, width;
+ gl_win_shader_t win_shader;
+ gl_brightness_shader_t brightness_shader;
+ gl_fill_shader_t fill_shader;
+ GLuint back_texture, back_fbo;
+ GLuint present_prog;
+
+ /// Called when an gl_texture is decoupled from the texture it refers. Returns
+ /// the decoupled user_data
+ void *(*decouple_texture_user_data)(backend_t *base, void *user_data);
+
+ /// Release the user data attached to a gl_texture
+ void (*release_user_data)(backend_t *base, struct gl_texture *);
+
+ struct log_target *logger;
+};
+
+typedef struct session session_t;
+
+#define GL_PROG_MAIN_INIT \
+ { .prog = 0, .unifm_opacity = -1, .unifm_invert_color = -1, .unifm_tex = -1, }
+
+GLuint gl_create_shader(GLenum shader_type, const char *shader_str);
+GLuint gl_create_program(const GLuint *const shaders, int nshaders);
+GLuint gl_create_program_from_str(const char *vert_shader_str, const char *frag_shader_str);
+
+/**
+ * @brief Render a region with texture data.
+ */
+void gl_compose(backend_t *, void *ptex,
+ int dst_x1, int dst_y1, int dst_x2, int dst_y2,
+ const region_t *reg_tgt, const region_t *reg_visible);
+
+void gl_resize(struct gl_data *, int width, int height);
+
+bool gl_init(struct gl_data *gd, session_t *);
+void gl_deinit(struct gl_data *gd);
+
+GLuint gl_new_texture(GLenum target);
+
+bool gl_image_op(backend_t *base, enum image_operations op, void *image_data,
+ const region_t *reg_op, const region_t *reg_visible, void *arg);
+
+void gl_release_image(backend_t *base, void *image_data);
+
+void *gl_clone(backend_t *base, const void *image_data, const region_t *reg_visible);
+
+bool gl_blur(backend_t *base, double opacity, void *, const region_t *reg_blur,
+ const region_t *reg_visible);
+void *gl_create_blur_context(backend_t *base, enum blur_method, void *args);
+void gl_destroy_blur_context(backend_t *base, void *ctx);
+void gl_get_blur_size(void *blur_context, int *width, int *height);
+
+void gl_fill(backend_t *base, struct color, const region_t *clip);
+
+void gl_present(backend_t *base, const region_t *);
+bool gl_read_pixel(backend_t *base, void *image_data, int x, int y, struct color *output);
+enum device_status gl_device_status(backend_t *base);
+
+static inline void gl_delete_texture(GLuint texture) {
+ glDeleteTextures(1, &texture);
+}
+
+/**
+ * Get a textual representation of an OpenGL error.
+ */
+static inline const char *gl_get_err_str(GLenum err) {
+ switch (err) {
+ CASESTRRET(GL_NO_ERROR);
+ CASESTRRET(GL_INVALID_ENUM);
+ CASESTRRET(GL_INVALID_VALUE);
+ CASESTRRET(GL_INVALID_OPERATION);
+ CASESTRRET(GL_INVALID_FRAMEBUFFER_OPERATION);
+ CASESTRRET(GL_OUT_OF_MEMORY);
+ CASESTRRET(GL_STACK_UNDERFLOW);
+ CASESTRRET(GL_STACK_OVERFLOW);
+ CASESTRRET(GL_FRAMEBUFFER_UNDEFINED);
+ CASESTRRET(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
+ CASESTRRET(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
+ CASESTRRET(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
+ CASESTRRET(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
+ CASESTRRET(GL_FRAMEBUFFER_UNSUPPORTED);
+ CASESTRRET(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE);
+ CASESTRRET(GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS);
+ }
+ return NULL;
+}
+
+/**
+ * Check for GLX error.
+ *
+ * http://blog.nobel-joergensen.com/2013/01/29/debugging-opengl-using-glgeterror/
+ */
+static inline void gl_check_err_(const char *func, int line) {
+ GLenum err = GL_NO_ERROR;
+
+ while (GL_NO_ERROR != (err = glGetError())) {
+ const char *errtext = gl_get_err_str(err);
+ if (errtext) {
+ log_printf(tls_logger, LOG_LEVEL_ERROR, func,
+ "GLX error at line %d: %s", line, errtext);
+ } else {
+ log_printf(tls_logger, LOG_LEVEL_ERROR, func,
+ "GLX error at line %d: %d", line, err);
+ }
+ }
+}
+
+static inline void gl_clear_err(void) {
+ while (glGetError() != GL_NO_ERROR)
+ ;
+}
+
+#define gl_check_err() gl_check_err_(__func__, __LINE__)
+
+/**
+ * Check for GL framebuffer completeness.
+ */
+static inline bool gl_check_fb_complete_(const char *func, int line, GLenum fb) {
+ GLenum status = glCheckFramebufferStatus(fb);
+
+ if (status == GL_FRAMEBUFFER_COMPLETE) {
+ return true;
+ }
+
+ const char *stattext = gl_get_err_str(status);
+ if (stattext) {
+ log_printf(tls_logger, LOG_LEVEL_ERROR, func,
+ "Framebuffer attachment failed at line %d: %s", line, stattext);
+ } else {
+ log_printf(tls_logger, LOG_LEVEL_ERROR, func,
+ "Framebuffer attachment failed at line %d: %d", line, status);
+ }
+
+ return false;
+}
+
+#define gl_check_fb_complete(fb) gl_check_fb_complete_(__func__, __LINE__, (fb))
+
+/**
+ * Check if a GLX extension exists.
+ */
+static inline bool gl_has_extension(const char *ext) {
+ int nexts = 0;
+ glGetIntegerv(GL_NUM_EXTENSIONS, &nexts);
+ for (int i = 0; i < nexts || !nexts; i++) {
+ const char *exti = (const char *)glGetStringi(GL_EXTENSIONS, (GLuint)i);
+ if (exti == NULL) {
+ break;
+ }
+ if (strcmp(ext, exti) == 0) {
+ return true;
+ }
+ }
+ gl_clear_err();
+ log_info("Missing GL extension %s.", ext);
+ return false;
+}
diff --git a/dwm/picom/src/backend/gl/glx.c b/dwm/picom/src/backend/gl/glx.c
new file mode 100644
index 0000000..3af7c1b
--- /dev/null
+++ b/dwm/picom/src/backend/gl/glx.c
@@ -0,0 +1,654 @@
+// SPDX-License-Identifier: MIT
+/*
+ * Compton - a compositor for X11
+ *
+ * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
+ *
+ * Copyright (c) 2011-2013, Christopher Jeffrey
+ * Copyright (c) 2019 Yuxuan Shui
+ * See LICENSE-mit for more information.
+ *
+ */
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "backend/backend.h"
+#include "backend/backend_common.h"
+#include "backend/gl/gl_common.h"
+#include "backend/gl/glx.h"
+#include "common.h"
+#include "compiler.h"
+#include "config.h"
+#include "log.h"
+#include "picom.h"
+#include "region.h"
+#include "utils.h"
+#include "win.h"
+#include "x.h"
+
+struct _glx_pixmap {
+ GLXPixmap glpixmap;
+ xcb_pixmap_t pixmap;
+ bool owned;
+};
+
+struct _glx_data {
+ struct gl_data gl;
+ Display *display;
+ int screen;
+ xcb_window_t target_win;
+ GLXContext ctx;
+};
+
+#define glXGetFBConfigAttribChecked(a, b, attr, c) \
+ do { \
+ if (glXGetFBConfigAttrib(a, b, attr, c)) { \
+ log_info("Cannot get FBConfig attribute " #attr); \
+ continue; \
+ } \
+ } while (0)
+
+struct glx_fbconfig_info *glx_find_fbconfig(Display *dpy, int screen, struct xvisual_info m) {
+ log_debug("Looking for FBConfig for RGBA%d%d%d%d, depth %d", m.red_size,
+ m.blue_size, m.green_size, m.alpha_size, m.visual_depth);
+
+ int ncfg;
+ // clang-format off
+ GLXFBConfig *cfg =
+ glXChooseFBConfig(dpy, screen, (int[]){
+ GLX_RENDER_TYPE, GLX_RGBA_BIT,
+ GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
+ GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
+ GLX_X_RENDERABLE, true,
+ GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, (GLint)GLX_DONT_CARE,
+ GLX_BUFFER_SIZE, m.red_size + m.green_size +
+ m.blue_size + m.alpha_size,
+ GLX_RED_SIZE, m.red_size,
+ GLX_BLUE_SIZE, m.blue_size,
+ GLX_GREEN_SIZE, m.green_size,
+ GLX_ALPHA_SIZE, m.alpha_size,
+ GLX_STENCIL_SIZE, 0,
+ GLX_DEPTH_SIZE, 0,
+ 0
+ }, &ncfg);
+ // clang-format on
+
+ int texture_tgts, y_inverted, texture_fmt;
+ bool found = false;
+ int min_cost = INT_MAX;
+ GLXFBConfig ret;
+ for (int i = 0; i < ncfg; i++) {
+ int depthbuf, stencil, doublebuf, bufsize;
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_BUFFER_SIZE, &bufsize);
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_DEPTH_SIZE, &depthbuf);
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_STENCIL_SIZE, &stencil);
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_DOUBLEBUFFER, &doublebuf);
+ if (depthbuf + stencil + bufsize * (doublebuf + 1) >= min_cost) {
+ continue;
+ }
+ int red, green, blue;
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_RED_SIZE, &red);
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_BLUE_SIZE, &blue);
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_GREEN_SIZE, &green);
+ if (red != m.red_size || green != m.green_size || blue != m.blue_size) {
+ // Color size doesn't match, this cannot work
+ continue;
+ }
+
+ int rgb, rgba;
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_BIND_TO_TEXTURE_RGB_EXT, &rgb);
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &rgba);
+ if (!rgb && !rgba) {
+ log_info("FBConfig is neither RGBA nor RGB, we cannot "
+ "handle this setup.");
+ continue;
+ }
+
+ int visual;
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_VISUAL_ID, &visual);
+ if (m.visual_depth != -1 &&
+ x_get_visual_depth(XGetXCBConnection(dpy), (xcb_visualid_t)visual) !=
+ m.visual_depth) {
+ // FBConfig and the correspondent X Visual might not have the same
+ // depth. (e.g. 32 bit FBConfig with a 24 bit Visual). This is
+ // quite common, seen in both open source and proprietary drivers.
+ //
+ // If the FBConfig has a matching depth but its visual doesn't, we
+ // still cannot use it.
+ continue;
+ }
+
+ // All check passed, we are using this one.
+ found = true;
+ ret = cfg[i];
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_BIND_TO_TEXTURE_TARGETS_EXT,
+ &texture_tgts);
+ glXGetFBConfigAttribChecked(dpy, cfg[i], GLX_Y_INVERTED_EXT, &y_inverted);
+
+ // Prefer the texture format with matching alpha, with the other one as
+ // fallback
+ if (m.alpha_size) {
+ texture_fmt = rgba ? GLX_TEXTURE_FORMAT_RGBA_EXT
+ : GLX_TEXTURE_FORMAT_RGB_EXT;
+ } else {
+ texture_fmt =
+ rgb ? GLX_TEXTURE_FORMAT_RGB_EXT : GLX_TEXTURE_FORMAT_RGBA_EXT;
+ }
+ min_cost = depthbuf + stencil + bufsize * (doublebuf + 1);
+ }
+ free(cfg);
+ if (!found) {
+ return NULL;
+ }
+
+ auto info = cmalloc(struct glx_fbconfig_info);
+ info->cfg = ret;
+ info->texture_tgts = texture_tgts;
+ info->texture_fmt = texture_fmt;
+ info->y_inverted = y_inverted;
+ return info;
+}
+
+/**
+ * Free a glx_texture_t.
+ */
+static void glx_release_image(backend_t *base, struct gl_texture *tex) {
+ struct _glx_data *gd = (void *)base;
+
+ struct _glx_pixmap *p = tex->user_data;
+ // Release binding
+ if (p->glpixmap && tex->texture) {
+ glBindTexture(GL_TEXTURE_2D, tex->texture);
+ glXReleaseTexImageEXT(gd->display, p->glpixmap, GLX_FRONT_LEFT_EXT);
+ glBindTexture(GL_TEXTURE_2D, 0);
+ }
+
+ // Free GLX Pixmap
+ if (p->glpixmap) {
+ glXDestroyPixmap(gd->display, p->glpixmap);
+ p->glpixmap = 0;
+ }
+
+ if (p->owned) {
+ xcb_free_pixmap(base->c, p->pixmap);
+ p->pixmap = XCB_NONE;
+ }
+
+ free(p);
+ tex->user_data = NULL;
+}
+
+/**
+ * Destroy GLX related resources.
+ */
+void glx_deinit(backend_t *base) {
+ struct _glx_data *gd = (void *)base;
+
+ gl_deinit(&gd->gl);
+
+ // Destroy GLX context
+ if (gd->ctx) {
+ glXMakeCurrent(gd->display, None, NULL);
+ glXDestroyContext(gd->display, gd->ctx);
+ gd->ctx = 0;
+ }
+
+ free(gd);
+}
+
+static void *glx_decouple_user_data(backend_t *base attr_unused, void *ud attr_unused) {
+ auto ret = cmalloc(struct _glx_pixmap);
+ ret->owned = false;
+ ret->glpixmap = 0;
+ ret->pixmap = 0;
+ return ret;
+}
+
+static bool glx_set_swap_interval(int interval, Display *dpy, GLXDrawable drawable) {
+ bool vsync_enabled = false;
+ if (glxext.has_GLX_MESA_swap_control) {
+ vsync_enabled = (glXSwapIntervalMESA((uint)interval) == 0);
+ }
+ if (!vsync_enabled && glxext.has_GLX_SGI_swap_control) {
+ vsync_enabled = (glXSwapIntervalSGI(interval) == 0);
+ }
+ if (!vsync_enabled && glxext.has_GLX_EXT_swap_control) {
+ // glXSwapIntervalEXT doesn't return if it's successful
+ glXSwapIntervalEXT(dpy, drawable, interval);
+ vsync_enabled = true;
+ }
+ return vsync_enabled;
+}
+
+/**
+ * Initialize OpenGL.
+ */
+static backend_t *glx_init(session_t *ps) {
+ bool success = false;
+ glxext_init(ps->dpy, ps->scr);
+ auto gd = ccalloc(1, struct _glx_data);
+ init_backend_base(&gd->gl.base, ps);
+
+ gd->display = ps->dpy;
+ gd->screen = ps->scr;
+ gd->target_win = session_get_target_window(ps);
+
+ XVisualInfo *pvis = NULL;
+
+ // Check for GLX extension
+ if (!ps->glx_exists) {
+ log_error("No GLX extension.");
+ goto end;
+ }
+
+ // Get XVisualInfo
+ int nitems = 0;
+ XVisualInfo vreq = {.visualid = ps->vis};
+ pvis = XGetVisualInfo(ps->dpy, VisualIDMask, &vreq, &nitems);
+ if (!pvis) {
+ log_error("Failed to acquire XVisualInfo for current visual.");
+ goto end;
+ }
+
+ // Ensure the visual is double-buffered
+ int value = 0;
+ if (glXGetConfig(ps->dpy, pvis, GLX_USE_GL, &value) || !value) {
+ log_error("Root visual is not a GL visual.");
+ goto end;
+ }
+
+ if (glXGetConfig(ps->dpy, pvis, GLX_STENCIL_SIZE, &value) || !value) {
+ log_error("Root visual lacks stencil buffer.");
+ goto end;
+ }
+
+ if (glXGetConfig(ps->dpy, pvis, GLX_DOUBLEBUFFER, &value) || !value) {
+ log_error("Root visual is not a double buffered GL visual.");
+ goto end;
+ }
+
+ if (glXGetConfig(ps->dpy, pvis, GLX_RGBA, &value) || !value) {
+ log_error("Root visual is a color index visual, not supported");
+ goto end;
+ }
+
+ if (!glxext.has_GLX_EXT_texture_from_pixmap) {
+ log_error("GLX_EXT_texture_from_pixmap is not supported by your driver");
+ goto end;
+ }
+
+ if (!glxext.has_GLX_ARB_create_context) {
+ log_error("GLX_ARB_create_context is not supported by your driver");
+ goto end;
+ }
+
+ // Find a fbconfig with visualid matching the one from the target win, so we can
+ // be sure that the fbconfig is compatible with our target window.
+ int ncfgs;
+ GLXFBConfig *cfg = glXGetFBConfigs(gd->display, gd->screen, &ncfgs);
+ bool found = false;
+ for (int i = 0; i < ncfgs; i++) {
+ int visualid;
+ glXGetFBConfigAttribChecked(gd->display, cfg[i], GLX_VISUAL_ID, &visualid);
+ if ((VisualID)visualid != pvis->visualid) {
+ continue;
+ }
+
+ int *attributes = (int[]){GLX_CONTEXT_MAJOR_VERSION_ARB,
+ 3,
+ GLX_CONTEXT_MINOR_VERSION_ARB,
+ 3,
+ GLX_CONTEXT_PROFILE_MASK_ARB,
+ GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
+ 0,
+ 0,
+ 0};
+ if (glxext.has_GLX_ARB_create_context_robustness) {
+ attributes[6] = GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB;
+ attributes[7] = GLX_LOSE_CONTEXT_ON_RESET_ARB;
+ }
+
+ gd->ctx = glXCreateContextAttribsARB(ps->dpy, cfg[i], 0, true, attributes);
+ free(cfg);
+
+ if (!gd->ctx) {
+ log_error("Failed to get GLX context.");
+ goto end;
+ }
+ found = true;
+ break;
+ }
+
+ if (!found) {
+ log_error("Couldn't find a suitable fbconfig for the target window");
+ goto end;
+ }
+
+ // Attach GLX context
+ GLXDrawable tgt = gd->target_win;
+ if (!glXMakeCurrent(ps->dpy, tgt, gd->ctx)) {
+ log_error("Failed to attach GLX context.");
+ goto end;
+ }
+
+ if (!gl_init(&gd->gl, ps)) {
+ log_error("Failed to setup OpenGL");
+ goto end;
+ }
+
+ gd->gl.decouple_texture_user_data = glx_decouple_user_data;
+ gd->gl.release_user_data = glx_release_image;
+
+ if (ps->o.vsync) {
+ if (!glx_set_swap_interval(1, ps->dpy, tgt)) {
+ log_error("Failed to enable vsync.");
+ }
+ } else {
+ glx_set_swap_interval(0, ps->dpy, tgt);
+ }
+
+ success = true;
+
+end:
+ if (pvis) {
+ XFree(pvis);
+ }
+
+ if (!success) {
+ glx_deinit(&gd->gl.base);
+ return NULL;
+ }
+
+ return &gd->gl.base;
+}
+
+static void *
+glx_bind_pixmap(backend_t *base, xcb_pixmap_t pixmap, struct xvisual_info fmt, bool owned) {
+ struct _glx_data *gd = (void *)base;
+ struct _glx_pixmap *glxpixmap = NULL;
+ // Retrieve pixmap parameters, if they aren't provided
+ if (fmt.visual_depth > OPENGL_MAX_DEPTH) {
+ log_error("Requested depth %d higher than max possible depth %d.",
+ fmt.visual_depth, OPENGL_MAX_DEPTH);
+ return false;
+ }
+
+ if (fmt.visual_depth < 0) {
+ log_error("Pixmap %#010x with invalid depth %d", pixmap, fmt.visual_depth);
+ return false;
+ }
+
+ auto r = xcb_get_geometry_reply(base->c, xcb_get_geometry(base->c, pixmap), NULL);
+ if (!r) {
+ log_error("Invalid pixmap %#010x", pixmap);
+ return NULL;
+ }
+
+ log_trace("Binding pixmap %#010x", pixmap);
+ auto wd = ccalloc(1, struct backend_image);
+ wd->max_brightness = 1;
+ auto inner = ccalloc(1, struct gl_texture);
+ inner->width = wd->ewidth = r->width;
+ inner->height = wd->eheight = r->height;
+ wd->inner = (struct backend_image_inner_base *)inner;
+ free(r);
+
+ auto fbcfg = glx_find_fbconfig(gd->display, gd->screen, fmt);
+ if (!fbcfg) {
+ log_error("Couldn't find FBConfig with requested visual %x", fmt.visual);
+ goto err;
+ }
+
+ // Choose a suitable texture target for our pixmap.
+ // Refer to GLX_EXT_texture_om_pixmap spec to see what are the mean
+ // of the bits in texture_tgts
+ if (!(fbcfg->texture_tgts & GLX_TEXTURE_2D_BIT_EXT)) {
+ log_error("Cannot bind pixmap to GL_TEXTURE_2D, giving up");
+ goto err;
+ }
+
+ log_debug("depth %d, rgba %d", fmt.visual_depth,
+ (fbcfg->texture_fmt == GLX_TEXTURE_FORMAT_RGBA_EXT));
+
+ GLint attrs[] = {
+ GLX_TEXTURE_FORMAT_EXT,
+ fbcfg->texture_fmt,
+ GLX_TEXTURE_TARGET_EXT,
+ GLX_TEXTURE_2D_EXT,
+ 0,
+ };
+
+ inner->y_inverted = fbcfg->y_inverted;
+
+ glxpixmap = cmalloc(struct _glx_pixmap);
+ glxpixmap->pixmap = pixmap;
+ glxpixmap->glpixmap = glXCreatePixmap(gd->display, fbcfg->cfg, pixmap, attrs);
+ glxpixmap->owned = owned;
+ free(fbcfg);
+
+ if (!glxpixmap->glpixmap) {
+ log_error("Failed to create glpixmap for pixmap %#010x", pixmap);
+ goto err;
+ }
+
+ log_trace("GLXPixmap %#010lx", glxpixmap->glpixmap);
+
+ // Create texture
+ inner->user_data = glxpixmap;
+ inner->texture = gl_new_texture(GL_TEXTURE_2D);
+ inner->has_alpha = fmt.alpha_size != 0;
+ wd->opacity = 1;
+ wd->color_inverted = false;
+ wd->dim = 0;
+ wd->inner->refcount = 1;
+ glBindTexture(GL_TEXTURE_2D, inner->texture);
+ glXBindTexImageEXT(gd->display, glxpixmap->glpixmap, GLX_FRONT_LEFT_EXT, NULL);
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ gl_check_err();
+ return wd;
+err:
+ if (glxpixmap && glxpixmap->glpixmap) {
+ glXDestroyPixmap(gd->display, glxpixmap->glpixmap);
+ }
+ free(glxpixmap);
+
+ if (owned) {
+ xcb_free_pixmap(base->c, pixmap);
+ }
+ free(wd);
+ return NULL;
+}
+
+static void glx_present(backend_t *base, const region_t *region attr_unused) {
+ struct _glx_data *gd = (void *)base;
+ gl_present(base, region);
+ glXSwapBuffers(gd->display, gd->target_win);
+ if (!gd->gl.is_nvidia) {
+ glFinish();
+ }
+}
+
+static int glx_buffer_age(backend_t *base) {
+ if (!glxext.has_GLX_EXT_buffer_age) {
+ return -1;
+ }
+
+ struct _glx_data *gd = (void *)base;
+ unsigned int val;
+ glXQueryDrawable(gd->display, gd->target_win, GLX_BACK_BUFFER_AGE_EXT, &val);
+ return (int)val ?: -1;
+}
+
+static void glx_diagnostics(backend_t *base) {
+ struct _glx_data *gd = (void *)base;
+ bool warn_software_rendering = false;
+ const char *software_renderer_names[] = {"llvmpipe", "SWR", "softpipe"};
+ auto glx_vendor = glXGetClientString(gd->display, GLX_VENDOR);
+ printf("* Driver vendors:\n");
+ printf(" * GLX: %s\n", glx_vendor);
+ printf(" * GL: %s\n", glGetString(GL_VENDOR));
+
+ auto gl_renderer = (const char *)glGetString(GL_RENDERER);
+ printf("* GL renderer: %s\n", gl_renderer);
+ if (strcmp(glx_vendor, "Mesa Project and SGI")) {
+ for (size_t i = 0; i < ARR_SIZE(software_renderer_names); i++) {
+ if (strstr(gl_renderer, software_renderer_names[i]) != NULL) {
+ warn_software_rendering = true;
+ break;
+ }
+ }
+ }
+
+#ifdef GLX_MESA_query_renderer
+ if (glxext.has_GLX_MESA_query_renderer) {
+ unsigned int accelerated = 0;
+ glXQueryCurrentRendererIntegerMESA(GLX_RENDERER_ACCELERATED_MESA, &accelerated);
+ printf("* Accelerated: %d\n", accelerated);
+
+ // Trust GLX_MESA_query_renderer when it's available
+ warn_software_rendering = (accelerated == 0);
+ }
+#endif
+
+ if (warn_software_rendering) {
+ printf("\n(You are using a software renderer. Unless you are doing this\n"
+ "intentionally, this means you don't have a graphics driver\n"
+ "properly installed. Performance will suffer. Please fix this\n"
+ "before reporting your issue.)\n");
+ }
+}
+
+struct backend_operations glx_ops = {
+ .init = glx_init,
+ .deinit = glx_deinit,
+ .bind_pixmap = glx_bind_pixmap,
+ .release_image = gl_release_image,
+ .compose = gl_compose,
+ .image_op = gl_image_op,
+ .set_image_property = default_set_image_property,
+ .clone_image = default_clone_image,
+ .blur = gl_blur,
+ .is_image_transparent = default_is_image_transparent,
+ .present = glx_present,
+ .buffer_age = glx_buffer_age,
+ .render_shadow = default_backend_render_shadow,
+ .fill = gl_fill,
+ .create_blur_context = gl_create_blur_context,
+ .destroy_blur_context = gl_destroy_blur_context,
+ .get_blur_size = gl_get_blur_size,
+ .diagnostics = glx_diagnostics,
+ .device_status = gl_device_status,
+ .max_buffer_age = 5, // Why?
+};
+
+/**
+ * Check if a GLX extension exists.
+ */
+static inline bool glx_has_extension(Display *dpy, int screen, const char *ext) {
+ const char *glx_exts = glXQueryExtensionsString(dpy, screen);
+ if (!glx_exts) {
+ log_error("Failed get GLX extension list.");
+ return false;
+ }
+
+ auto inlen = strlen(ext);
+ const char *curr = glx_exts;
+ bool match = false;
+ while (curr && !match) {
+ const char *end = strchr(curr, ' ');
+ if (!end) {
+ // Last extension string
+ match = strcmp(ext, curr) == 0;
+ } else if (curr + inlen == end) {
+ // Length match, do match string
+ match = strncmp(ext, curr, (unsigned long)(end - curr)) == 0;
+ }
+ curr = end ? end + 1 : NULL;
+ }
+
+ if (!match) {
+ log_info("Missing GLX extension %s.", ext);
+ } else {
+ log_info("Found GLX extension %s.", ext);
+ }
+
+ return match;
+}
+
+struct glxext_info glxext = {0};
+PFNGLXGETVIDEOSYNCSGIPROC glXGetVideoSyncSGI;
+PFNGLXWAITVIDEOSYNCSGIPROC glXWaitVideoSyncSGI;
+PFNGLXGETSYNCVALUESOMLPROC glXGetSyncValuesOML;
+PFNGLXWAITFORMSCOMLPROC glXWaitForMscOML;
+PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
+PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI;
+PFNGLXSWAPINTERVALMESAPROC glXSwapIntervalMESA;
+PFNGLXBINDTEXIMAGEEXTPROC glXBindTexImageEXT;
+PFNGLXRELEASETEXIMAGEEXTPROC glXReleaseTexImageEXT;
+PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB;
+
+#ifdef GLX_MESA_query_renderer
+PFNGLXQUERYCURRENTRENDERERINTEGERMESAPROC glXQueryCurrentRendererIntegerMESA;
+#endif
+
+void glxext_init(Display *dpy, int screen) {
+ if (glxext.initialized) {
+ return;
+ }
+ glxext.initialized = true;
+#define check_ext(name) glxext.has_##name = glx_has_extension(dpy, screen, #name)
+ check_ext(GLX_SGI_video_sync);
+ check_ext(GLX_SGI_swap_control);
+ check_ext(GLX_OML_sync_control);
+ check_ext(GLX_MESA_swap_control);
+ check_ext(GLX_EXT_swap_control);
+ check_ext(GLX_EXT_texture_from_pixmap);
+ check_ext(GLX_ARB_create_context);
+ check_ext(GLX_EXT_buffer_age);
+ check_ext(GLX_ARB_create_context_robustness);
+#ifdef GLX_MESA_query_renderer
+ check_ext(GLX_MESA_query_renderer);
+#endif
+#undef check_ext
+
+#define lookup(name) (name = (__typeof__(name))glXGetProcAddress((GLubyte *)#name))
+ // Checking if the returned function pointer is NULL is not really necessary,
+ // or maybe not even useful, since glXGetProcAddress might always return
+ // something. We are doing it just for completeness' sake.
+ if (!lookup(glXGetVideoSyncSGI) || !lookup(glXWaitVideoSyncSGI)) {
+ glxext.has_GLX_SGI_video_sync = false;
+ }
+ if (!lookup(glXSwapIntervalEXT)) {
+ glxext.has_GLX_EXT_swap_control = false;
+ }
+ if (!lookup(glXSwapIntervalMESA)) {
+ glxext.has_GLX_MESA_swap_control = false;
+ }
+ if (!lookup(glXSwapIntervalSGI)) {
+ glxext.has_GLX_SGI_swap_control = false;
+ }
+ if (!lookup(glXWaitForMscOML) || !lookup(glXGetSyncValuesOML)) {
+ glxext.has_GLX_OML_sync_control = false;
+ }
+ if (!lookup(glXBindTexImageEXT) || !lookup(glXReleaseTexImageEXT)) {
+ glxext.has_GLX_EXT_texture_from_pixmap = false;
+ }
+ if (!lookup(glXCreateContextAttribsARB)) {
+ glxext.has_GLX_ARB_create_context = false;
+ }
+#ifdef GLX_MESA_query_renderer
+ if (!lookup(glXQueryCurrentRendererIntegerMESA)) {
+ glxext.has_GLX_MESA_query_renderer = false;
+ }
+#endif
+#undef lookup
+}
diff --git a/dwm/picom/src/backend/gl/glx.h b/dwm/picom/src/backend/gl/glx.h
new file mode 100644
index 0000000..44b4da0
--- /dev/null
+++ b/dwm/picom/src/backend/gl/glx.h
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#pragma once
+#include
+// Older version of glx.h defines function prototypes for these extensions...
+// Rename them to avoid conflicts
+#define glXSwapIntervalMESA glXSwapIntervalMESA_
+#define glXBindTexImageEXT glXBindTexImageEXT_
+#define glXReleaseTexImageEXT glXReleaseTexImageEXT
+#include
+#undef glXSwapIntervalMESA
+#undef glXBindTexImageEXT
+#undef glXReleaseTexImageEXT
+#include
+#include
+#include
+
+#include "log.h"
+#include "compiler.h"
+#include "utils.h"
+#include "x.h"
+
+struct glx_fbconfig_info {
+ GLXFBConfig cfg;
+ int texture_tgts;
+ int texture_fmt;
+ int y_inverted;
+};
+
+/// The search criteria for glx_find_fbconfig
+struct glx_fbconfig_criteria {
+ /// Bit width of the red component
+ int red_size;
+ /// Bit width of the green component
+ int green_size;
+ /// Bit width of the blue component
+ int blue_size;
+ /// Bit width of the alpha component
+ int alpha_size;
+ /// The depth of X visual
+ int visual_depth;
+};
+
+struct glx_fbconfig_info *glx_find_fbconfig(Display *, int screen, struct xvisual_info);
+
+
+struct glxext_info {
+ bool initialized;
+ bool has_GLX_SGI_video_sync;
+ bool has_GLX_SGI_swap_control;
+ bool has_GLX_OML_sync_control;
+ bool has_GLX_MESA_swap_control;
+ bool has_GLX_EXT_swap_control;
+ bool has_GLX_EXT_texture_from_pixmap;
+ bool has_GLX_ARB_create_context;
+ bool has_GLX_EXT_buffer_age;
+ bool has_GLX_MESA_query_renderer;
+ bool has_GLX_ARB_create_context_robustness;
+};
+
+extern struct glxext_info glxext;
+
+extern PFNGLXGETVIDEOSYNCSGIPROC glXGetVideoSyncSGI;
+extern PFNGLXWAITVIDEOSYNCSGIPROC glXWaitVideoSyncSGI;
+extern PFNGLXGETSYNCVALUESOMLPROC glXGetSyncValuesOML;
+extern PFNGLXWAITFORMSCOMLPROC glXWaitForMscOML;
+extern PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
+extern PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI;
+extern PFNGLXSWAPINTERVALMESAPROC glXSwapIntervalMESA;
+extern PFNGLXBINDTEXIMAGEEXTPROC glXBindTexImageEXT;
+extern PFNGLXRELEASETEXIMAGEEXTPROC glXReleaseTexImageEXT;
+extern PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB;
+
+#ifdef GLX_MESA_query_renderer
+extern PFNGLXQUERYCURRENTRENDERERINTEGERMESAPROC glXQueryCurrentRendererIntegerMESA;
+#endif
+
+void glxext_init(Display *, int screen);
diff --git a/dwm/picom/src/backend/meson.build b/dwm/picom/src/backend/meson.build
new file mode 100644
index 0000000..b8f0ad9
--- /dev/null
+++ b/dwm/picom/src/backend/meson.build
@@ -0,0 +1,7 @@
+# enable xrender
+srcs += [ files('backend_common.c', 'xrender/xrender.c', 'dummy/dummy.c', 'backend.c', 'driver.c') ]
+
+# enable opengl
+if get_option('opengl')
+ srcs += [ files('gl/gl_common.c', 'gl/glx.c') ]
+endif
diff --git a/dwm/picom/src/backend/xrender/xrender.c b/dwm/picom/src/backend/xrender/xrender.c
new file mode 100644
index 0000000..6e661e8
--- /dev/null
+++ b/dwm/picom/src/backend/xrender/xrender.c
@@ -0,0 +1,889 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) Yuxuan Shui
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+
+#include "backend/backend.h"
+#include "backend/backend_common.h"
+#include "common.h"
+#include "config.h"
+#include "kernel.h"
+#include "log.h"
+#include "picom.h"
+#include "region.h"
+#include "types.h"
+#include "utils.h"
+#include "win.h"
+#include "x.h"
+
+typedef struct _xrender_data {
+ backend_t base;
+ /// If vsync is enabled and supported by the current system
+ bool vsync;
+ xcb_visualid_t default_visual;
+ /// Target window
+ xcb_window_t target_win;
+ /// Painting target, it is either the root or the overlay
+ xcb_render_picture_t target;
+ /// Back buffers. Double buffer, with 1 for temporary render use
+ xcb_render_picture_t back[3];
+ /// The back buffer that is for temporary use
+ /// Age of each back buffer.
+ int buffer_age[3];
+ /// The back buffer we should be painting into
+ int curr_back;
+ /// The corresponding pixmap to the back buffer
+ xcb_pixmap_t back_pixmap[3];
+ /// Pictures of pixel of different alpha value, used as a mask to
+ /// paint transparent images
+ xcb_render_picture_t alpha_pict[256];
+
+ // XXX don't know if these are really needed
+
+ /// 1x1 white picture
+ xcb_render_picture_t white_pixel;
+ /// 1x1 black picture
+ xcb_render_picture_t black_pixel;
+
+ /// Width and height of the target pixmap
+ int target_width, target_height;
+
+ xcb_special_event_t *present_event;
+} xrender_data;
+
+struct _xrender_blur_context {
+ enum blur_method method;
+ /// Blur kernels converted to X format
+ struct x_convolution_kernel **x_blur_kernel;
+
+ int resize_width, resize_height;
+
+ /// Number of blur kernels
+ int x_blur_kernel_count;
+};
+
+struct _xrender_image_data_inner {
+ // struct backend_image_inner_base
+ int refcount;
+ bool has_alpha;
+
+ // Pixmap that the client window draws to,
+ // it will contain the content of client window.
+ xcb_pixmap_t pixmap;
+ // A Picture links to the Pixmap
+ xcb_render_picture_t pict;
+ int width, height;
+ xcb_visualid_t visual;
+ uint8_t depth;
+ // Whether we own this image, e.g. we allocated it;
+ // or not, e.g. this is a named pixmap of a X window.
+ bool owned;
+};
+
+struct xrender_rounded_rectangle_cache {
+ int refcount;
+ // A cached picture of a rounded rectangle. Xorg rasterizes shapes on CPU so it's
+ // exceedingly slow.
+ xcb_render_picture_t p;
+};
+
+struct xrender_image {
+ struct backend_image base;
+
+ struct xrender_rounded_rectangle_cache *rounded_rectangle;
+};
+
+/// Make a picture of size width x height, which has a rounded rectangle of corner_radius
+/// rendered in it.
+struct xrender_rounded_rectangle_cache *
+make_rounded_corner_cache(xcb_connection_t *c, xcb_render_picture_t src,
+ xcb_drawable_t root, int width, int height, int corner_radius) {
+ auto picture = x_create_picture_with_standard(c, root, width, height,
+ XCB_PICT_STANDARD_ARGB_32, 0, NULL);
+ if (picture == XCB_NONE) {
+ return NULL;
+ }
+
+ int inner_height = height - 2 * corner_radius;
+ int cap_height = corner_radius;
+ if (inner_height < 0) {
+ cap_height = height / 2;
+ inner_height = 0;
+ }
+ auto points = ccalloc(cap_height * 4 + 4, xcb_render_pointfix_t);
+ int point_count = 0;
+
+#define ADD_POINT(px, py) \
+ assert(point_count < cap_height * 4 + 4); \
+ points[point_count].x = DOUBLE_TO_XFIXED(px); \
+ points[point_count].y = DOUBLE_TO_XFIXED(py); \
+ point_count += 1;
+
+ // The top cap
+ for (int i = 0; i <= cap_height; i++) {
+ double y = corner_radius - i;
+ double delta = sqrt(corner_radius * corner_radius - y * y);
+ double left = corner_radius - delta;
+ double right = width - corner_radius + delta;
+ if (left >= right) {
+ continue;
+ }
+ ADD_POINT(left, i);
+ ADD_POINT(right, i);
+ }
+
+ // The middle rectangle
+ if (inner_height > 0) {
+ ADD_POINT(0, cap_height + inner_height);
+ ADD_POINT(width, cap_height + inner_height);
+ }
+
+ // The bottom cap
+ for (int i = cap_height + inner_height + 1; i <= height; i++) {
+ double y = corner_radius - (height - i);
+ double delta = sqrt(corner_radius * corner_radius - y * y);
+ double left = corner_radius - delta;
+ double right = width - corner_radius + delta;
+ if (left >= right) {
+ break;
+ }
+ ADD_POINT(left, i);
+ ADD_POINT(right, i);
+ }
+#undef ADD_POINT
+
+ XCB_AWAIT_VOID(xcb_render_tri_strip, c, XCB_RENDER_PICT_OP_SRC, src, picture,
+ x_get_pictfmt_for_standard(c, XCB_PICT_STANDARD_A_8), 0, 0,
+ (uint32_t)point_count, points);
+ free(points);
+ auto ret = ccalloc(1, struct xrender_rounded_rectangle_cache);
+ ret->p = picture;
+ ret->refcount = 1;
+ return ret;
+}
+
+static void compose_impl(struct _xrender_data *xd, struct xrender_image *xrimg,
+ int dst_x1, int dst_y1, int dst_x2, int dst_y2,
+ const region_t *reg_paint, const region_t *reg_visible,
+ xcb_render_picture_t result) {
+ const struct backend_image *img = &xrimg->base;
+ auto alpha_pict = xd->alpha_pict[(int)(img->opacity * MAX_ALPHA)];
+ auto inner = (struct _xrender_image_data_inner *)img->inner;
+ region_t reg;
+
+ bool has_alpha = inner->has_alpha || img->opacity != 1;
+ const auto tmpw = to_u16_checked(dst_x2 - dst_x1);
+ const auto tmph = to_u16_checked(dst_y2 - dst_y1);
+ const auto tmpew = to_u16_checked(dst_x2 - dst_x1);
+ const auto tmpeh = to_u16_checked(dst_y2 - dst_y1);
+ const xcb_render_color_t dim_color = {
+ .red = 0, .green = 0, .blue = 0, .alpha = (uint16_t)(0xffff * img->dim)};
+
+ // Clip region of rendered_pict might be set during rendering, clear it to
+ // make sure we get everything into the buffer
+ x_clear_picture_clip_region(xd->base.c, inner->pict);
+
+ pixman_region32_init(®);
+ pixman_region32_intersect(®, (region_t *)reg_paint, (region_t *)reg_visible);
+ x_set_picture_clip_region(xd->base.c, result, 0, 0, ®);
+#define DOUBLE_TO_XFIXED(value) ((xcb_render_fixed_t)(((double)(value)) * 65536))
+ {
+ const xcb_render_transform_t transform = {
+ DOUBLE_TO_XFIXED((double)img->ewidth / (double)tmpew), DOUBLE_TO_XFIXED(0.0), DOUBLE_TO_XFIXED(0.0),
+ DOUBLE_TO_XFIXED(0.0), DOUBLE_TO_XFIXED((double)img->eheight / (double)tmpeh), DOUBLE_TO_XFIXED(0.0),
+ DOUBLE_TO_XFIXED(0.0), DOUBLE_TO_XFIXED(0.0), DOUBLE_TO_XFIXED(1.0),
+ };
+ xcb_render_set_picture_transform(xd->base.c, inner->pict, transform);
+ xcb_render_set_picture_filter(xd->base.c, inner->pict, 7, "nearest", 0, NULL);
+ }
+#undef DOUBLE_TO_XFIXED
+
+ if (img->corner_radius != 0 && xrimg->rounded_rectangle == NULL) {
+ xrimg->rounded_rectangle = make_rounded_corner_cache(
+ xd->base.c, xd->white_pixel, xd->base.root, inner->width,
+ inner->height, (int)img->corner_radius);
+ }
+ if (((img->color_inverted || img->dim != 0) && has_alpha) || img->corner_radius != 0) {
+ // Apply image properties using a temporary image, because the source
+ // image is transparent. Otherwise the properties can be applied directly
+ // on the target image.
+ auto tmp_pict =
+ x_create_picture_with_visual(xd->base.c, xd->base.root, inner->width,
+ inner->height, inner->visual, 0, NULL);
+
+ // Set clip region translated to source coordinate
+ x_set_picture_clip_region(xd->base.c, tmp_pict, to_i16_checked(-dst_x1),
+ to_i16_checked(-dst_y1), ®);
+ // Copy source -> tmp
+ xcb_render_composite(xd->base.c, XCB_RENDER_PICT_OP_OVER, inner->pict,
+ XCB_NONE, tmp_pict, 0, 0, 0, 0, 0, 0, tmpw, tmph);
+ if (img->color_inverted) {
+ if (inner->has_alpha) {
+ auto tmp_pict2 = x_create_picture_with_visual(
+ xd->base.c, xd->base.root, tmpw, tmph, inner->visual,
+ 0, NULL);
+ xcb_render_composite(xd->base.c, XCB_RENDER_PICT_OP_OVER,
+ tmp_pict, XCB_NONE, tmp_pict2, 0, 0,
+ 0, 0, 0, 0, tmpw, tmph);
+
+ xcb_render_composite(xd->base.c, XCB_RENDER_PICT_OP_DIFFERENCE,
+ xd->white_pixel, XCB_NONE, tmp_pict,
+ 0, 0, 0, 0, 0, 0, tmpw, tmph);
+ xcb_render_composite(
+ xd->base.c, XCB_RENDER_PICT_OP_IN_REVERSE, tmp_pict2,
+ XCB_NONE, tmp_pict, 0, 0, 0, 0, 0, 0, tmpw, tmph);
+ xcb_render_free_picture(xd->base.c, tmp_pict2);
+ } else {
+ xcb_render_composite(xd->base.c, XCB_RENDER_PICT_OP_DIFFERENCE,
+ xd->white_pixel, XCB_NONE, tmp_pict,
+ 0, 0, 0, 0, 0, 0, tmpw, tmph);
+ }
+ }
+ if (img->dim != 0) {
+ // Dim the actually content of window
+ xcb_rectangle_t rect = {
+ .x = 0,
+ .y = 0,
+ .width = tmpw,
+ .height = tmph,
+ };
+
+ xcb_render_fill_rectangles(xd->base.c, XCB_RENDER_PICT_OP_OVER,
+ tmp_pict, dim_color, 1, &rect);
+ }
+
+ if (img->corner_radius != 0 && xrimg->rounded_rectangle != NULL) {
+ // Clip tmp_pict with a rounded rectangle
+ xcb_render_composite(xd->base.c, XCB_RENDER_PICT_OP_IN_REVERSE,
+ xrimg->rounded_rectangle->p, XCB_NONE,
+ tmp_pict, 0, 0, 0, 0, 0, 0, tmpw, tmph);
+ }
+
+ xcb_render_composite(xd->base.c, XCB_RENDER_PICT_OP_OVER, tmp_pict,
+ alpha_pict, result, 0, 0, 0, 0, to_i16_checked(dst_x1),
+ to_i16_checked(dst_y1), tmpew, tmpeh);
+ xcb_render_free_picture(xd->base.c, tmp_pict);
+ } else {
+ uint8_t op = (has_alpha ? XCB_RENDER_PICT_OP_OVER : XCB_RENDER_PICT_OP_SRC);
+
+ xcb_render_composite(xd->base.c, op, inner->pict, alpha_pict, result, 0,
+ 0, 0, 0, to_i16_checked(dst_x1),
+ to_i16_checked(dst_y1), tmpew, tmpeh);
+ if (img->dim != 0 || img->color_inverted) {
+ // Apply properties, if we reach here, then has_alpha == false
+ assert(!has_alpha);
+ if (img->color_inverted) {
+ xcb_render_composite(xd->base.c, XCB_RENDER_PICT_OP_DIFFERENCE,
+ xd->white_pixel, XCB_NONE, result, 0,
+ 0, 0, 0, to_i16_checked(dst_x1),
+ to_i16_checked(dst_y1), tmpew, tmpeh);
+ }
+
+ if (img->dim != 0) {
+ // Dim the actually content of window
+ xcb_rectangle_t rect = {
+ .x = to_i16_checked(dst_x1),
+ .y = to_i16_checked(dst_y1),
+ .width = tmpew,
+ .height = tmpeh,
+ };
+
+ xcb_render_fill_rectangles(xd->base.c, XCB_RENDER_PICT_OP_OVER,
+ result, dim_color, 1, &rect);
+ }
+ }
+ }
+ pixman_region32_fini(®);
+}
+
+static void compose(backend_t *base, void *img_data,
+ int dst_x1, int dst_y1, int dst_x2, int dst_y2,
+ const region_t *reg_paint, const region_t *reg_visible) {
+ // TODO(dccsillag): use dst_{x,y}2
+ struct _xrender_data *xd = (void *)base;
+ return compose_impl(xd, img_data, dst_x1, dst_y1, dst_x2, dst_y2, reg_paint, reg_visible, xd->back[2]);
+}
+
+static void fill(backend_t *base, struct color c, const region_t *clip) {
+ struct _xrender_data *xd = (void *)base;
+ const rect_t *extent = pixman_region32_extents((region_t *)clip);
+ x_set_picture_clip_region(base->c, xd->back[2], 0, 0, clip);
+ // color is in X fixed point representation
+ xcb_render_fill_rectangles(
+ base->c, XCB_RENDER_PICT_OP_OVER, xd->back[2],
+ (xcb_render_color_t){.red = (uint16_t)(c.red * 0xffff),
+ .green = (uint16_t)(c.green * 0xffff),
+ .blue = (uint16_t)(c.blue * 0xffff),
+ .alpha = (uint16_t)(c.alpha * 0xffff)},
+ 1,
+ (xcb_rectangle_t[]){{.x = to_i16_checked(extent->x1),
+ .y = to_i16_checked(extent->y1),
+ .width = to_u16_checked(extent->x2 - extent->x1),
+ .height = to_u16_checked(extent->y2 - extent->y1)}});
+}
+
+static bool blur(backend_t *backend_data, double opacity, void *ctx_,
+ const region_t *reg_blur, const region_t *reg_visible) {
+ struct _xrender_blur_context *bctx = ctx_;
+ if (bctx->method == BLUR_METHOD_NONE) {
+ return true;
+ }
+
+ struct _xrender_data *xd = (void *)backend_data;
+ xcb_connection_t *c = xd->base.c;
+ region_t reg_op;
+ pixman_region32_init(®_op);
+ pixman_region32_intersect(®_op, (region_t *)reg_blur, (region_t *)reg_visible);
+ if (!pixman_region32_not_empty(®_op)) {
+ pixman_region32_fini(®_op);
+ return true;
+ }
+
+ region_t reg_op_resized =
+ resize_region(®_op, bctx->resize_width, bctx->resize_height);
+
+ const pixman_box32_t *extent_resized = pixman_region32_extents(®_op_resized);
+ const auto height_resized = to_u16_checked(extent_resized->y2 - extent_resized->y1);
+ const auto width_resized = to_u16_checked(extent_resized->x2 - extent_resized->x1);
+ static const char *filter0 = "Nearest"; // The "null" filter
+ static const char *filter = "convolution";
+
+ // Create a buffer for storing blurred picture, make it just big enough
+ // for the blur region
+ const uint32_t pic_attrs_mask = XCB_RENDER_CP_REPEAT;
+ const xcb_render_create_picture_value_list_t pic_attrs = {.repeat = XCB_RENDER_REPEAT_PAD};
+ xcb_render_picture_t tmp_picture[2] = {
+ x_create_picture_with_visual(xd->base.c, xd->base.root, width_resized, height_resized,
+ xd->default_visual, pic_attrs_mask, &pic_attrs),
+ x_create_picture_with_visual(xd->base.c, xd->base.root, width_resized, height_resized,
+ xd->default_visual, pic_attrs_mask, &pic_attrs)};
+
+ if (!tmp_picture[0] || !tmp_picture[1]) {
+ log_error("Failed to build intermediate Picture.");
+ pixman_region32_fini(®_op);
+ pixman_region32_fini(®_op_resized);
+ return false;
+ }
+
+ region_t clip;
+ pixman_region32_init(&clip);
+ pixman_region32_copy(&clip, ®_op_resized);
+ pixman_region32_translate(&clip, -extent_resized->x1, -extent_resized->y1);
+ x_set_picture_clip_region(c, tmp_picture[0], 0, 0, &clip);
+ x_set_picture_clip_region(c, tmp_picture[1], 0, 0, &clip);
+ pixman_region32_fini(&clip);
+
+ xcb_render_picture_t src_pict = xd->back[2], dst_pict = tmp_picture[0];
+ auto alpha_pict = xd->alpha_pict[(int)(opacity * MAX_ALPHA)];
+ int current = 0;
+ x_set_picture_clip_region(c, src_pict, 0, 0, ®_op_resized);
+
+ // For more than 1 pass, we do:
+ // back -(pass 1)-> tmp0 -(pass 2)-> tmp1 ...
+ // -(pass n-1)-> tmp0 or tmp1 -(pass n)-> back
+ // For 1 pass, we do
+ // back -(pass 1)-> tmp0 -(copy)-> target_buffer
+ int i;
+ for (i = 0; i < bctx->x_blur_kernel_count; i++) {
+ // Copy from source picture to destination. The filter must
+ // be applied on source picture, to get the nearby pixels outside the
+ // window.
+ xcb_render_set_picture_filter(c, src_pict, to_u16_checked(strlen(filter)),
+ filter,
+ to_u32_checked(bctx->x_blur_kernel[i]->size),
+ bctx->x_blur_kernel[i]->kernel);
+
+ if (i == 0) {
+ // First pass, back buffer -> tmp picture
+ // (we do this even if this is also the last pass, because we
+ // cannot do back buffer -> back buffer)
+ xcb_render_composite(c, XCB_RENDER_PICT_OP_SRC, src_pict, XCB_NONE,
+ dst_pict, to_i16_checked(extent_resized->x1),
+ to_i16_checked(extent_resized->y1), 0, 0, 0,
+ 0, width_resized, height_resized);
+ } else if (i < bctx->x_blur_kernel_count - 1) {
+ // This is not the last pass or the first pass,
+ // tmp picture 1 -> tmp picture 2
+ xcb_render_composite(c, XCB_RENDER_PICT_OP_SRC, src_pict,
+ XCB_NONE, dst_pict, 0, 0, 0, 0, 0, 0,
+ width_resized, height_resized);
+ } else {
+ x_set_picture_clip_region(c, xd->back[2], 0, 0, ®_op);
+ // This is the last pass, and we are doing more than 1 pass
+ xcb_render_composite(c, XCB_RENDER_PICT_OP_OVER, src_pict,
+ alpha_pict, xd->back[2], 0, 0, 0, 0,
+ to_i16_checked(extent_resized->x1),
+ to_i16_checked(extent_resized->y1),
+ width_resized, height_resized);
+ }
+
+ // reset filter
+ xcb_render_set_picture_filter(
+ c, src_pict, to_u16_checked(strlen(filter0)), filter0, 0, NULL);
+
+ src_pict = tmp_picture[current];
+ dst_pict = tmp_picture[!current];
+ current = !current;
+ }
+
+ // There is only 1 pass
+ if (i == 1) {
+ x_set_picture_clip_region(c, xd->back[2], 0, 0, ®_op);
+ xcb_render_composite(
+ c, XCB_RENDER_PICT_OP_OVER, src_pict, alpha_pict, xd->back[2], 0, 0,
+ 0, 0, to_i16_checked(extent_resized->x1),
+ to_i16_checked(extent_resized->y1), width_resized, height_resized);
+ }
+
+ xcb_render_free_picture(c, tmp_picture[0]);
+ xcb_render_free_picture(c, tmp_picture[1]);
+ pixman_region32_fini(®_op);
+ pixman_region32_fini(®_op_resized);
+ return true;
+}
+
+static void *
+bind_pixmap(backend_t *base, xcb_pixmap_t pixmap, struct xvisual_info fmt, bool owned) {
+ xcb_generic_error_t *e;
+ auto r = xcb_get_geometry_reply(base->c, xcb_get_geometry(base->c, pixmap), &e);
+ if (!r) {
+ log_error("Invalid pixmap: %#010x", pixmap);
+ x_print_error(e->full_sequence, e->major_code, e->minor_code, e->error_code);
+ return NULL;
+ }
+
+ auto img = ccalloc(1, struct xrender_image);
+ auto inner = ccalloc(1, struct _xrender_image_data_inner);
+ inner->depth = (uint8_t)fmt.visual_depth;
+ inner->width = img->base.ewidth = r->width;
+ inner->height = img->base.eheight = r->height;
+ inner->pixmap = pixmap;
+ inner->has_alpha = fmt.alpha_size != 0;
+ inner->pict =
+ x_create_picture_with_visual_and_pixmap(base->c, fmt.visual, pixmap, 0, NULL);
+ inner->owned = owned;
+ inner->visual = fmt.visual;
+ inner->refcount = 1;
+
+ img->base.inner = (struct backend_image_inner_base *)inner;
+ img->base.opacity = 1;
+ img->rounded_rectangle = NULL;
+ free(r);
+
+ if (inner->pict == XCB_NONE) {
+ free(inner);
+ free(img);
+ return NULL;
+ }
+ return img;
+}
+static void release_image_inner(backend_t *base, struct _xrender_image_data_inner *inner) {
+ xcb_render_free_picture(base->c, inner->pict);
+ if (inner->owned) {
+ xcb_free_pixmap(base->c, inner->pixmap);
+ }
+ free(inner);
+}
+
+static void
+release_rounded_corner_cache(backend_t *base, struct xrender_rounded_rectangle_cache *cache) {
+ if (!cache) {
+ return;
+ }
+
+ assert(cache->refcount > 0);
+ cache->refcount--;
+ if (cache->refcount == 0) {
+ xcb_free_pixmap(base->c, cache->p);
+ free(cache);
+ }
+}
+
+static void release_image(backend_t *base, void *image) {
+ struct xrender_image *img = image;
+ release_rounded_corner_cache(base, img->rounded_rectangle);
+ img->rounded_rectangle = NULL;
+ img->base.inner->refcount -= 1;
+ if (img->base.inner->refcount == 0) {
+ release_image_inner(base, (void *)img->base.inner);
+ }
+ free(img);
+}
+
+static void deinit(backend_t *backend_data) {
+ struct _xrender_data *xd = (void *)backend_data;
+ for (int i = 0; i < 256; i++) {
+ xcb_render_free_picture(xd->base.c, xd->alpha_pict[i]);
+ }
+ xcb_render_free_picture(xd->base.c, xd->target);
+ for (int i = 0; i < 2; i++) {
+ xcb_render_free_picture(xd->base.c, xd->back[i]);
+ xcb_free_pixmap(xd->base.c, xd->back_pixmap[i]);
+ }
+ if (xd->present_event) {
+ xcb_unregister_for_special_event(xd->base.c, xd->present_event);
+ }
+ xcb_render_free_picture(xd->base.c, xd->white_pixel);
+ xcb_render_free_picture(xd->base.c, xd->black_pixel);
+ free(xd);
+}
+
+static void present(backend_t *base, const region_t *region) {
+ struct _xrender_data *xd = (void *)base;
+ const rect_t *extent = pixman_region32_extents((region_t *)region);
+ int16_t orig_x = to_i16_checked(extent->x1), orig_y = to_i16_checked(extent->y1);
+ uint16_t region_width = to_u16_checked(extent->x2 - extent->x1),
+ region_height = to_u16_checked(extent->y2 - extent->y1);
+
+ // compose() sets clip region on the back buffer, so clear it first
+ x_clear_picture_clip_region(base->c, xd->back[xd->curr_back]);
+
+ // limit the region of update
+ x_set_picture_clip_region(base->c, xd->back[2], 0, 0, region);
+
+ if (xd->vsync) {
+ // Update the back buffer first, then present
+ xcb_render_composite(base->c, XCB_RENDER_PICT_OP_SRC, xd->back[2],
+ XCB_NONE, xd->back[xd->curr_back], orig_x, orig_y, 0,
+ 0, orig_x, orig_y, region_width, region_height);
+
+ // Make sure we got reply from PresentPixmap before waiting for events,
+ // to avoid deadlock
+ auto e = xcb_request_check(
+ base->c, xcb_present_pixmap_checked(
+ xd->base.c, xd->target_win,
+ xd->back_pixmap[xd->curr_back], 0, XCB_NONE, XCB_NONE, 0,
+ 0, XCB_NONE, XCB_NONE, XCB_NONE, 0, 0, 0, 0, 0, NULL));
+ if (e) {
+ log_error("Failed to present pixmap");
+ free(e);
+ return;
+ }
+ // TODO(yshui) don't block wait for present completion
+ xcb_present_generic_event_t *pev =
+ (void *)xcb_wait_for_special_event(base->c, xd->present_event);
+ if (!pev) {
+ // We don't know what happened, maybe X died
+ // But reset buffer age, so in case we do recover, we will
+ // render correctly.
+ xd->buffer_age[0] = xd->buffer_age[1] = -1;
+ return;
+ }
+ assert(pev->evtype == XCB_PRESENT_COMPLETE_NOTIFY);
+ xcb_present_complete_notify_event_t *pcev = (void *)pev;
+ // log_trace("Present complete: %d %ld", pcev->mode, pcev->msc);
+ xd->buffer_age[xd->curr_back] = 1;
+
+ // buffer_age < 0 means that back buffer is empty
+ if (xd->buffer_age[1 - xd->curr_back] > 0) {
+ xd->buffer_age[1 - xd->curr_back]++;
+ }
+ if (pcev->mode == XCB_PRESENT_COMPLETE_MODE_FLIP) {
+ // We cannot use the pixmap we used anymore
+ xd->curr_back = 1 - xd->curr_back;
+ }
+ free(pev);
+ } else {
+ // No vsync needed, draw into the target picture directly
+ xcb_render_composite(base->c, XCB_RENDER_PICT_OP_SRC, xd->back[2],
+ XCB_NONE, xd->target, orig_x, orig_y, 0, 0, orig_x,
+ orig_y, region_width, region_height);
+ }
+}
+
+static int buffer_age(backend_t *backend_data) {
+ struct _xrender_data *xd = (void *)backend_data;
+ if (!xd->vsync) {
+ // Only the target picture really holds the screen content, and its
+ // content is always up to date. So buffer age is always 1.
+ return 1;
+ }
+ return xd->buffer_age[xd->curr_back];
+}
+
+static struct _xrender_image_data_inner *
+new_inner(backend_t *base, int w, int h, xcb_visualid_t visual, uint8_t depth) {
+ auto new_inner = ccalloc(1, struct _xrender_image_data_inner);
+ new_inner->pixmap = x_create_pixmap(base->c, depth, base->root, w, h);
+ if (new_inner->pixmap == XCB_NONE) {
+ log_error("Failed to create pixmap for copy");
+ free(new_inner);
+ return NULL;
+ }
+ new_inner->pict = x_create_picture_with_visual_and_pixmap(
+ base->c, visual, new_inner->pixmap, 0, NULL);
+ if (new_inner->pict == XCB_NONE) {
+ log_error("Failed to create picture for copy");
+ xcb_free_pixmap(base->c, new_inner->pixmap);
+ free(new_inner);
+ return NULL;
+ }
+ new_inner->width = w;
+ new_inner->height = h;
+ new_inner->visual = visual;
+ new_inner->depth = depth;
+ new_inner->refcount = 1;
+ new_inner->owned = true;
+ return new_inner;
+}
+
+static bool decouple_image(backend_t *base, struct backend_image *img, const region_t *reg) {
+ if (img->inner->refcount == 1) {
+ return true;
+ }
+ auto inner = (struct _xrender_image_data_inner *)img->inner;
+ // Force new pixmap to a 32-bit ARGB visual to allow for transparent frames around
+ // non-transparent windows
+ auto visual = (inner->depth == 32)
+ ? inner->visual
+ : x_get_visual_for_standard(base->c, XCB_PICT_STANDARD_ARGB_32);
+ auto inner2 = new_inner(base, inner->width, inner->height, visual, 32);
+ if (!inner2) {
+ return false;
+ }
+
+ x_set_picture_clip_region(base->c, inner->pict, 0, 0, reg);
+ xcb_render_composite(base->c, XCB_RENDER_PICT_OP_SRC, inner->pict, XCB_NONE,
+ inner2->pict, 0, 0, 0, 0, 0, 0, to_u16_checked(inner->width),
+ to_u16_checked(inner->height));
+
+ img->inner = (struct backend_image_inner_base *)inner2;
+ inner->refcount--;
+ return true;
+}
+
+static bool image_op(backend_t *base, enum image_operations op, void *image,
+ const region_t *reg_op, const region_t *reg_visible, void *arg) {
+ struct _xrender_data *xd = (void *)base;
+ struct backend_image *img = image;
+ region_t reg;
+ double *dargs = arg;
+
+ pixman_region32_init(®);
+ pixman_region32_intersect(®, (region_t *)reg_op, (region_t *)reg_visible);
+
+ switch (op) {
+ case IMAGE_OP_APPLY_ALPHA:
+ assert(reg_op);
+
+ if (!pixman_region32_not_empty(®)) {
+ break;
+ }
+
+ if (dargs[0] == 1) {
+ break;
+ }
+
+ if (!decouple_image(base, img, reg_visible)) {
+ pixman_region32_fini(®);
+ return false;
+ }
+
+ auto inner = (struct _xrender_image_data_inner *)img->inner;
+ auto alpha_pict = xd->alpha_pict[(int)((1 - dargs[0]) * MAX_ALPHA)];
+ x_set_picture_clip_region(base->c, inner->pict, 0, 0, ®);
+ xcb_render_composite(base->c, XCB_RENDER_PICT_OP_OUT_REVERSE, alpha_pict,
+ XCB_NONE, inner->pict, 0, 0, 0, 0, 0, 0,
+ to_u16_checked(inner->width),
+ to_u16_checked(inner->height));
+ inner->has_alpha = true;
+ break;
+ }
+ pixman_region32_fini(®);
+ return true;
+}
+
+static void *
+create_blur_context(backend_t *base attr_unused, enum blur_method method, void *args) {
+ auto ret = ccalloc(1, struct _xrender_blur_context);
+ if (!method || method >= BLUR_METHOD_INVALID) {
+ ret->method = BLUR_METHOD_NONE;
+ return ret;
+ }
+ if (method == BLUR_METHOD_DUAL_KAWASE) {
+ log_warn("Blur method 'dual_kawase' is not compatible with the 'xrender' "
+ "backend.");
+ ret->method = BLUR_METHOD_NONE;
+ return ret;
+ }
+
+ ret->method = BLUR_METHOD_KERNEL;
+ struct conv **kernels;
+ int kernel_count;
+ if (method == BLUR_METHOD_KERNEL) {
+ kernels = ((struct kernel_blur_args *)args)->kernels;
+ kernel_count = ((struct kernel_blur_args *)args)->kernel_count;
+ } else {
+ kernels = generate_blur_kernel(method, args, &kernel_count);
+ }
+
+ ret->x_blur_kernel = ccalloc(kernel_count, struct x_convolution_kernel *);
+ for (int i = 0; i < kernel_count; i++) {
+ int center = kernels[i]->h * kernels[i]->w / 2;
+ x_create_convolution_kernel(kernels[i], kernels[i]->data[center],
+ &ret->x_blur_kernel[i]);
+ ret->resize_width += kernels[i]->w / 2;
+ ret->resize_height += kernels[i]->h / 2;
+ }
+ ret->x_blur_kernel_count = kernel_count;
+
+ if (method != BLUR_METHOD_KERNEL) {
+ // Kernels generated by generate_blur_kernel, so we need to free them.
+ for (int i = 0; i < kernel_count; i++) {
+ free(kernels[i]);
+ }
+ free(kernels);
+ }
+ return ret;
+}
+
+static void destroy_blur_context(backend_t *base attr_unused, void *ctx_) {
+ struct _xrender_blur_context *ctx = ctx_;
+ for (int i = 0; i < ctx->x_blur_kernel_count; i++) {
+ free(ctx->x_blur_kernel[i]);
+ }
+ free(ctx->x_blur_kernel);
+ free(ctx);
+}
+
+static void get_blur_size(void *blur_context, int *width, int *height) {
+ struct _xrender_blur_context *ctx = blur_context;
+ *width = ctx->resize_width;
+ *height = ctx->resize_height;
+}
+
+static backend_t *backend_xrender_init(session_t *ps) {
+ auto xd = ccalloc(1, struct _xrender_data);
+ init_backend_base(&xd->base, ps);
+
+ for (int i = 0; i <= MAX_ALPHA; ++i) {
+ double o = (double)i / (double)MAX_ALPHA;
+ xd->alpha_pict[i] = solid_picture(ps->c, ps->root, false, o, 0, 0, 0);
+ assert(xd->alpha_pict[i] != XCB_NONE);
+ }
+
+ xd->target_width = ps->root_width;
+ xd->target_height = ps->root_height;
+ xd->default_visual = ps->vis;
+ xd->black_pixel = solid_picture(ps->c, ps->root, true, 1, 0, 0, 0);
+ xd->white_pixel = solid_picture(ps->c, ps->root, true, 1, 1, 1, 1);
+
+ xd->target_win = session_get_target_window(ps);
+ xcb_render_create_picture_value_list_t pa = {
+ .subwindowmode = XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS,
+ };
+ xd->target = x_create_picture_with_visual_and_pixmap(
+ ps->c, ps->vis, xd->target_win, XCB_RENDER_CP_SUBWINDOW_MODE, &pa);
+
+ auto pictfmt = x_get_pictform_for_visual(ps->c, ps->vis);
+ if (!pictfmt) {
+ log_fatal("Default visual is invalid");
+ abort();
+ }
+
+ xd->vsync = ps->o.vsync;
+ if (ps->present_exists) {
+ auto eid = x_new_id(ps->c);
+ auto e =
+ xcb_request_check(ps->c, xcb_present_select_input_checked(
+ ps->c, eid, xd->target_win,
+ XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY));
+ if (e) {
+ log_error("Cannot select present input, vsync will be disabled");
+ xd->vsync = false;
+ free(e);
+ }
+
+ xd->present_event =
+ xcb_register_for_special_xge(ps->c, &xcb_present_id, eid, NULL);
+ if (!xd->present_event) {
+ log_error("Cannot register for special XGE, vsync will be "
+ "disabled");
+ xd->vsync = false;
+ }
+ } else {
+ xd->vsync = false;
+ }
+
+ // We might need to do double buffering for vsync, and buffer 0 and 1 are for
+ // double buffering.
+ int first_buffer_index = xd->vsync ? 0 : 2;
+ for (int i = first_buffer_index; i < 3; i++) {
+ xd->back_pixmap[i] = x_create_pixmap(ps->c, pictfmt->depth, ps->root,
+ to_u16_checked(ps->root_width),
+ to_u16_checked(ps->root_height));
+ const uint32_t pic_attrs_mask = XCB_RENDER_CP_REPEAT;
+ const xcb_render_create_picture_value_list_t pic_attrs = {
+ .repeat = XCB_RENDER_REPEAT_PAD};
+ xd->back[i] = x_create_picture_with_pictfmt_and_pixmap(
+ ps->c, pictfmt, xd->back_pixmap[i], pic_attrs_mask, &pic_attrs);
+ xd->buffer_age[i] = -1;
+ if (xd->back_pixmap[i] == XCB_NONE || xd->back[i] == XCB_NONE) {
+ log_error("Cannot create pixmap for rendering");
+ goto err;
+ }
+ }
+ xd->curr_back = 0;
+
+ return &xd->base;
+err:
+ deinit(&xd->base);
+ return NULL;
+}
+
+void *clone_image(backend_t *base attr_unused, const void *image_data,
+ const region_t *reg_visible attr_unused) {
+ auto new_img = ccalloc(1, struct xrender_image);
+ *new_img = *(struct xrender_image *)image_data;
+ new_img->base.inner->refcount++;
+ if (new_img->rounded_rectangle) {
+ new_img->rounded_rectangle->refcount++;
+ }
+ return new_img;
+}
+
+static bool
+set_image_property(backend_t *base, enum image_properties op, void *image, void *args) {
+ auto xrimg = (struct xrender_image *)image;
+ if (op == IMAGE_PROPERTY_CORNER_RADIUS &&
+ ((double *)args)[0] != xrimg->base.corner_radius) {
+ // Free cached rounded rectangle if corner radius changed
+ release_rounded_corner_cache(base, xrimg->rounded_rectangle);
+ xrimg->rounded_rectangle = NULL;
+ }
+ return default_set_image_property(base, op, image, args);
+}
+
+struct backend_operations xrender_ops = {
+ .init = backend_xrender_init,
+ .deinit = deinit,
+ .blur = blur,
+ .present = present,
+ .compose = compose,
+ .fill = fill,
+ .bind_pixmap = bind_pixmap,
+ .release_image = release_image,
+ .render_shadow = default_backend_render_shadow,
+ //.prepare_win = prepare_win,
+ //.release_win = release_win,
+ .is_image_transparent = default_is_image_transparent,
+ .buffer_age = buffer_age,
+ .max_buffer_age = 2,
+
+ .image_op = image_op,
+ .clone_image = clone_image,
+ .set_image_property = set_image_property,
+ .create_blur_context = create_blur_context,
+ .destroy_blur_context = destroy_blur_context,
+ .get_blur_size = get_blur_size,
+};
+
+// vim: set noet sw=8 ts=8:
diff --git a/dwm/picom/src/c2.c b/dwm/picom/src/c2.c
new file mode 100644
index 0000000..d0c1aeb
--- /dev/null
+++ b/dwm/picom/src/c2.c
@@ -0,0 +1,1674 @@
+// SPDX-License-Identifier: MIT
+
+/*
+ * Compton - a compositor for X11
+ *
+ * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
+ *
+ * Copyright (c) 2011-2013, Christopher Jeffrey
+ * See LICENSE-mit for more information.
+ *
+ */
+
+#include
+#include
+#include
+#include
+
+// libpcre
+#ifdef CONFIG_REGEX_PCRE
+#include
+
+// For compatibility with
+#include
+
+#include "atom.h"
+#include "common.h"
+#include "compiler.h"
+#include "config.h"
+#include "log.h"
+#include "string_utils.h"
+#include "utils.h"
+#include "win.h"
+#include "x.h"
+
+#include "c2.h"
+
+#pragma GCC diagnostic error "-Wunused-parameter"
+
+#define C2_MAX_LEVELS 10
+
+typedef struct _c2_b c2_b_t;
+typedef struct _c2_l c2_l_t;
+
+/// Pointer to a condition tree.
+typedef struct {
+ bool isbranch : 1;
+ union {
+ c2_b_t *b;
+ c2_l_t *l;
+ };
+} c2_ptr_t;
+
+/// Initializer for c2_ptr_t.
+#define C2_PTR_INIT \
+ { .isbranch = false, .l = NULL, }
+
+static const c2_ptr_t C2_PTR_NULL = C2_PTR_INIT;
+
+/// Operator of a branch element.
+typedef enum {
+ C2_B_OUNDEFINED,
+ C2_B_OAND,
+ C2_B_OOR,
+ C2_B_OXOR,
+} c2_b_op_t;
+
+/// Structure for branch element in a window condition
+struct _c2_b {
+ bool neg : 1;
+ c2_b_op_t op;
+ c2_ptr_t opr1;
+ c2_ptr_t opr2;
+};
+
+/// Initializer for c2_b_t.
+#define C2_B_INIT \
+ { .neg = false, .op = C2_B_OUNDEFINED, .opr1 = C2_PTR_INIT, .opr2 = C2_PTR_INIT, }
+
+/// Structure for leaf element in a window condition
+struct _c2_l {
+ bool neg : 1;
+ enum { C2_L_OEXISTS,
+ C2_L_OEQ,
+ C2_L_OGT,
+ C2_L_OGTEQ,
+ C2_L_OLT,
+ C2_L_OLTEQ,
+ } op : 3;
+ enum { C2_L_MEXACT,
+ C2_L_MSTART,
+ C2_L_MCONTAINS,
+ C2_L_MWILDCARD,
+ C2_L_MPCRE,
+ } match : 3;
+ bool match_ignorecase : 1;
+ char *tgt;
+ xcb_atom_t tgtatom;
+ bool tgt_onframe;
+ int index;
+ enum { C2_L_PUNDEFINED = -1,
+ C2_L_PID = 0,
+ C2_L_PX,
+ C2_L_PY,
+ C2_L_PX2,
+ C2_L_PY2,
+ C2_L_PWIDTH,
+ C2_L_PHEIGHT,
+ C2_L_PWIDTHB,
+ C2_L_PHEIGHTB,
+ C2_L_PBDW,
+ C2_L_PFULLSCREEN,
+ C2_L_POVREDIR,
+ C2_L_PARGB,
+ C2_L_PFOCUSED,
+ C2_L_PWMWIN,
+ C2_L_PBSHAPED,
+ C2_L_PROUNDED,
+ C2_L_PCLIENT,
+ C2_L_PWINDOWTYPE,
+ C2_L_PLEADER,
+ C2_L_PNAME,
+ C2_L_PCLASSG,
+ C2_L_PCLASSI,
+ C2_L_PROLE,
+ } predef;
+ enum c2_l_type {
+ C2_L_TUNDEFINED,
+ C2_L_TSTRING,
+ C2_L_TCARDINAL,
+ C2_L_TWINDOW,
+ C2_L_TATOM,
+ C2_L_TDRAWABLE,
+ } type;
+ int format;
+ enum { C2_L_PTUNDEFINED,
+ C2_L_PTSTRING,
+ C2_L_PTINT,
+ } ptntype;
+ char *ptnstr;
+ long ptnint;
+#ifdef CONFIG_REGEX_PCRE
+ pcre *regex_pcre;
+ pcre_extra *regex_pcre_extra;
+#endif
+};
+
+/// Initializer for c2_l_t.
+#define C2_L_INIT \
+ { \
+ .neg = false, .op = C2_L_OEXISTS, .match = C2_L_MEXACT, \
+ .match_ignorecase = false, .tgt = NULL, .tgtatom = 0, .tgt_onframe = false, \
+ .predef = C2_L_PUNDEFINED, .index = 0, .type = C2_L_TUNDEFINED, \
+ .format = 0, .ptntype = C2_L_PTUNDEFINED, .ptnstr = NULL, .ptnint = 0, \
+ }
+
+static const c2_l_t leaf_def = C2_L_INIT;
+
+/// Linked list type of conditions.
+struct _c2_lptr {
+ c2_ptr_t ptr;
+ void *data;
+ struct _c2_lptr *next;
+};
+
+/// Initializer for c2_lptr_t.
+#define C2_LPTR_INIT \
+ { .ptr = C2_PTR_INIT, .data = NULL, .next = NULL, }
+
+/// Structure representing a predefined target.
+typedef struct {
+ const char *name;
+ enum c2_l_type type;
+ int format;
+} c2_predef_t;
+
+// Predefined targets.
+static const c2_predef_t C2_PREDEFS[] = {
+ [C2_L_PID] = {"id", C2_L_TCARDINAL, 0},
+ [C2_L_PX] = {"x", C2_L_TCARDINAL, 0},
+ [C2_L_PY] = {"y", C2_L_TCARDINAL, 0},
+ [C2_L_PX2] = {"x2", C2_L_TCARDINAL, 0},
+ [C2_L_PY2] = {"y2", C2_L_TCARDINAL, 0},
+ [C2_L_PWIDTH] = {"width", C2_L_TCARDINAL, 0},
+ [C2_L_PHEIGHT] = {"height", C2_L_TCARDINAL, 0},
+ [C2_L_PWIDTHB] = {"widthb", C2_L_TCARDINAL, 0},
+ [C2_L_PHEIGHTB] = {"heightb", C2_L_TCARDINAL, 0},
+ [C2_L_PBDW] = {"border_width", C2_L_TCARDINAL, 0},
+ [C2_L_PFULLSCREEN] = {"fullscreen", C2_L_TCARDINAL, 0},
+ [C2_L_POVREDIR] = {"override_redirect", C2_L_TCARDINAL, 0},
+ [C2_L_PARGB] = {"argb", C2_L_TCARDINAL, 0},
+ [C2_L_PFOCUSED] = {"focused", C2_L_TCARDINAL, 0},
+ [C2_L_PWMWIN] = {"wmwin", C2_L_TCARDINAL, 0},
+ [C2_L_PBSHAPED] = {"bounding_shaped", C2_L_TCARDINAL, 0},
+ [C2_L_PROUNDED] = {"rounded_corners", C2_L_TCARDINAL, 0},
+ [C2_L_PCLIENT] = {"client", C2_L_TWINDOW, 0},
+ [C2_L_PWINDOWTYPE] = {"window_type", C2_L_TSTRING, 0},
+ [C2_L_PLEADER] = {"leader", C2_L_TWINDOW, 0},
+ [C2_L_PNAME] = {"name", C2_L_TSTRING, 0},
+ [C2_L_PCLASSG] = {"class_g", C2_L_TSTRING, 0},
+ [C2_L_PCLASSI] = {"class_i", C2_L_TSTRING, 0},
+ [C2_L_PROLE] = {"role", C2_L_TSTRING, 0},
+};
+
+/**
+ * Get the numeric property value from a win_prop_t.
+ */
+static inline long winprop_get_int(winprop_t prop, size_t index) {
+ long tgt = 0;
+
+ if (!prop.nitems || index >= prop.nitems) {
+ return 0;
+ }
+
+ switch (prop.format) {
+ case 8: tgt = *(prop.p8 + index); break;
+ case 16: tgt = *(prop.p16 + index); break;
+ case 32: tgt = *(prop.p32 + index); break;
+ default: assert(0); break;
+ }
+
+ return tgt;
+}
+
+/**
+ * Compare next word in a string with another string.
+ */
+static inline int strcmp_wd(const char *needle, const char *src) {
+ int ret = mstrncmp(needle, src);
+ if (ret)
+ return ret;
+
+ char c = src[strlen(needle)];
+ if (isalnum((unsigned char)c) || '_' == c)
+ return 1;
+ else
+ return 0;
+}
+
+/**
+ * Return whether a c2_ptr_t is empty.
+ */
+static inline attr_unused bool c2_ptr_isempty(const c2_ptr_t p) {
+ return !(p.isbranch ? (bool)p.b : (bool)p.l);
+}
+
+/**
+ * Reset a c2_ptr_t.
+ */
+static inline void c2_ptr_reset(c2_ptr_t *pp) {
+ if (pp)
+ memcpy(pp, &C2_PTR_NULL, sizeof(c2_ptr_t));
+}
+
+/**
+ * Combine two condition trees.
+ */
+static inline c2_ptr_t c2h_comb_tree(c2_b_op_t op, c2_ptr_t p1, c2_ptr_t p2) {
+ c2_ptr_t p = {.isbranch = true, .b = NULL};
+ p.b = cmalloc(c2_b_t);
+
+ p.b->neg = false;
+ p.b->op = op;
+ p.b->opr1 = p1;
+ p.b->opr2 = p2;
+
+ return p;
+}
+
+/**
+ * Get the precedence value of a condition branch operator.
+ */
+static inline int c2h_b_opp(c2_b_op_t op) {
+ switch (op) {
+ case C2_B_OAND: return 2;
+ case C2_B_OOR: return 1;
+ case C2_B_OXOR: return 1;
+ default: break;
+ }
+
+ assert(0);
+ return 0;
+}
+
+/**
+ * Compare precedence of two condition branch operators.
+ *
+ * Associativity is left-to-right, forever.
+ *
+ * @return positive number if op1 > op2, 0 if op1 == op2 in precedence,
+ * negative number otherwise
+ */
+static inline int c2h_b_opcmp(c2_b_op_t op1, c2_b_op_t op2) {
+ return c2h_b_opp(op1) - c2h_b_opp(op2);
+}
+
+static int c2_parse_grp(const char *pattern, int offset, c2_ptr_t *presult, int level);
+
+static int c2_parse_target(const char *pattern, int offset, c2_ptr_t *presult);
+
+static int c2_parse_op(const char *pattern, int offset, c2_ptr_t *presult);
+
+static int c2_parse_pattern(const char *pattern, int offset, c2_ptr_t *presult);
+
+static int c2_parse_legacy(const char *pattern, int offset, c2_ptr_t *presult);
+
+static void c2_free(c2_ptr_t p);
+
+/**
+ * Wrapper of c2_free().
+ */
+static inline void c2_freep(c2_ptr_t *pp) {
+ if (pp) {
+ c2_free(*pp);
+ c2_ptr_reset(pp);
+ }
+}
+
+static const char *c2h_dump_str_tgt(const c2_l_t *pleaf);
+
+static const char *c2h_dump_str_type(const c2_l_t *pleaf);
+
+static void attr_unused c2_dump(c2_ptr_t p);
+
+static xcb_atom_t c2_get_atom_type(const c2_l_t *pleaf);
+
+static bool c2_match_once(session_t *ps, const struct managed_win *w, const c2_ptr_t cond);
+
+/**
+ * Parse a condition string.
+ */
+c2_lptr_t *c2_parse(c2_lptr_t **pcondlst, const char *pattern, void *data) {
+ if (!pattern)
+ return NULL;
+
+ // Parse the pattern
+ c2_ptr_t result = C2_PTR_INIT;
+ int offset = -1;
+
+ if (strlen(pattern) >= 2 && ':' == pattern[1])
+ offset = c2_parse_legacy(pattern, 0, &result);
+ else
+ offset = c2_parse_grp(pattern, 0, &result, 0);
+
+ if (offset < 0) {
+ c2_freep(&result);
+ return NULL;
+ }
+
+ // Insert to pcondlst
+ {
+ static const c2_lptr_t lptr_def = C2_LPTR_INIT;
+ auto plptr = cmalloc(c2_lptr_t);
+ memcpy(plptr, &lptr_def, sizeof(c2_lptr_t));
+ plptr->ptr = result;
+ plptr->data = data;
+ if (pcondlst) {
+ plptr->next = *pcondlst;
+ *pcondlst = plptr;
+ }
+
+#ifdef DEBUG_C2
+ log_trace("(\"%s\"): ", pattern);
+ c2_dump(plptr->ptr);
+ putchar('\n');
+#endif
+
+ return plptr;
+ }
+}
+
+#define c2_error(format, ...) \
+ do { \
+ log_error("Pattern \"%s\" pos %d: " format, pattern, offset, ##__VA_ARGS__); \
+ goto fail; \
+ } while (0)
+
+// TODO(yshui) Not a very good macro, should probably be a function
+#define C2H_SKIP_SPACES() \
+ { \
+ while (isspace((unsigned char)pattern[offset])) \
+ ++offset; \
+ }
+
+/**
+ * Parse a group in condition string.
+ *
+ * @return offset of next character in string
+ */
+static int c2_parse_grp(const char *pattern, int offset, c2_ptr_t *presult, int level) {
+ // Check for recursion levels
+ if (level > C2_MAX_LEVELS)
+ c2_error("Exceeded maximum recursion levels.");
+
+ if (!pattern)
+ return -1;
+
+ // Expected end character
+ const char endchar = (offset ? ')' : '\0');
+
+ // We use a system that a maximum of 2 elements are kept. When we find
+ // the third element, we combine the elements according to operator
+ // precedence. This design limits operators to have at most two-levels
+ // of precedence and fixed left-to-right associativity.
+
+ // For storing branch operators. ops[0] is actually unused
+ c2_b_op_t ops[3] = {};
+ // For storing elements
+ c2_ptr_t eles[2] = {C2_PTR_INIT, C2_PTR_INIT};
+ // Index of next free element slot in eles
+ int elei = 0;
+ // Pointer to the position of next element
+ c2_ptr_t *pele = eles;
+ // Negation flag of next operator
+ bool neg = false;
+ // Whether we are expecting an element immediately, is true at first, or
+ // after encountering a logical operator
+ bool next_expected = true;
+
+ // Parse the pattern character-by-character
+ for (; pattern[offset]; ++offset) {
+ assert(elei <= 2);
+
+ // Jump over spaces
+ if (isspace((unsigned char)pattern[offset]))
+ continue;
+
+ // Handle end of group
+ if (')' == pattern[offset])
+ break;
+
+ // Handle "!"
+ if ('!' == pattern[offset]) {
+ if (!next_expected)
+ c2_error("Unexpected \"!\".");
+
+ neg = !neg;
+ continue;
+ }
+
+ // Handle AND and OR
+ if ('&' == pattern[offset] || '|' == pattern[offset]) {
+ if (next_expected)
+ c2_error("Unexpected logical operator.");
+
+ next_expected = true;
+ if (!mstrncmp("&&", pattern + offset)) {
+ ops[elei] = C2_B_OAND;
+ ++offset;
+ } else if (!mstrncmp("||", pattern + offset)) {
+ ops[elei] = C2_B_OOR;
+ ++offset;
+ } else
+ c2_error("Illegal logical operator.");
+
+ continue;
+ }
+
+ // Parsing an element
+ if (!next_expected)
+ c2_error("Unexpected expression.");
+
+ assert(!elei || ops[elei]);
+
+ // If we are out of space
+ if (2 == elei) {
+ --elei;
+ // If the first operator has higher or equal precedence, combine
+ // the first two elements
+ if (c2h_b_opcmp(ops[1], ops[2]) >= 0) {
+ eles[0] = c2h_comb_tree(ops[1], eles[0], eles[1]);
+ c2_ptr_reset(&eles[1]);
+ pele = &eles[elei];
+ ops[1] = ops[2];
+ }
+ // Otherwise, combine the second and the incoming one
+ else {
+ eles[1] = c2h_comb_tree(ops[2], eles[1], C2_PTR_NULL);
+ assert(eles[1].isbranch);
+ pele = &eles[1].b->opr2;
+ }
+ // The last operator always needs to be reset
+ ops[2] = C2_B_OUNDEFINED;
+ }
+
+ // It's a subgroup if it starts with '('
+ if ('(' == pattern[offset]) {
+ if ((offset = c2_parse_grp(pattern, offset + 1, pele, level + 1)) < 0)
+ goto fail;
+ }
+ // Otherwise it's a leaf
+ else {
+ if ((offset = c2_parse_target(pattern, offset, pele)) < 0)
+ goto fail;
+
+ assert(!pele->isbranch && !c2_ptr_isempty(*pele));
+
+ if ((offset = c2_parse_op(pattern, offset, pele)) < 0)
+ goto fail;
+
+ if ((offset = c2_parse_pattern(pattern, offset, pele)) < 0)
+ goto fail;
+ }
+ // Decrement offset -- we will increment it in loop update
+ --offset;
+
+ // Apply negation
+ if (neg) {
+ neg = false;
+ if (pele->isbranch)
+ pele->b->neg = !pele->b->neg;
+ else
+ pele->l->neg = !pele->l->neg;
+ }
+
+ next_expected = false;
+ ++elei;
+ pele = &eles[elei];
+ }
+
+ // Wrong end character?
+ if (pattern[offset] && !endchar)
+ c2_error("Expected end of string but found '%c'.", pattern[offset]);
+ if (!pattern[offset] && endchar)
+ c2_error("Expected '%c' but found end of string.", endchar);
+
+ // Handle end of group
+ if (!elei) {
+ c2_error("Empty group.");
+ } else if (next_expected) {
+ c2_error("Missing rule before end of group.");
+ } else if (elei > 1) {
+ assert(2 == elei);
+ assert(ops[1]);
+ eles[0] = c2h_comb_tree(ops[1], eles[0], eles[1]);
+ c2_ptr_reset(&eles[1]);
+ }
+
+ *presult = eles[0];
+
+ if (')' == pattern[offset])
+ ++offset;
+
+ return offset;
+
+fail:
+ c2_freep(&eles[0]);
+ c2_freep(&eles[1]);
+
+ return -1;
+}
+
+/**
+ * Parse the target part of a rule.
+ */
+static int c2_parse_target(const char *pattern, int offset, c2_ptr_t *presult) {
+ // Initialize leaf
+ presult->isbranch = false;
+ presult->l = cmalloc(c2_l_t);
+
+ c2_l_t *const pleaf = presult->l;
+ memcpy(pleaf, &leaf_def, sizeof(c2_l_t));
+
+ // Parse negation marks
+ while ('!' == pattern[offset]) {
+ pleaf->neg = !pleaf->neg;
+ ++offset;
+ C2H_SKIP_SPACES();
+ }
+
+ // Copy target name out
+ int tgtlen = 0;
+ for (; pattern[offset] && (isalnum((unsigned char)pattern[offset]) ||
+ '_' == pattern[offset] || '.' == pattern[offset]);
+ ++offset) {
+ ++tgtlen;
+ }
+ if (!tgtlen) {
+ c2_error("Empty target.");
+ }
+ pleaf->tgt = strndup(&pattern[offset - tgtlen], (size_t)tgtlen);
+
+ // Check for predefined targets
+ static const int npredefs = (int)(sizeof(C2_PREDEFS) / sizeof(C2_PREDEFS[0]));
+ for (int i = 0; i < npredefs; ++i) {
+ if (!strcmp(C2_PREDEFS[i].name, pleaf->tgt)) {
+ pleaf->predef = i;
+ pleaf->type = C2_PREDEFS[i].type;
+ pleaf->format = C2_PREDEFS[i].format;
+ break;
+ }
+ }
+
+ C2H_SKIP_SPACES();
+
+ // Parse target-on-frame flag
+ if ('@' == pattern[offset]) {
+ pleaf->tgt_onframe = true;
+ ++offset;
+ C2H_SKIP_SPACES();
+ }
+
+ // Parse index
+ if ('[' == pattern[offset]) {
+ if (pleaf->predef != C2_L_PUNDEFINED) {
+ c2_error("Predefined targets can't have index.");
+ }
+
+ offset++;
+
+ C2H_SKIP_SPACES();
+
+ long index = -1;
+ const char *endptr = NULL;
+
+ if ('*' == pattern[offset]) {
+ index = -1;
+ endptr = pattern + offset + 1;
+ } else {
+ index = strtol(pattern + offset, (char **)&endptr, 0);
+ if (index < 0) {
+ c2_error("Index number invalid.");
+ }
+ }
+
+ if (!endptr || pattern + offset == endptr) {
+ c2_error("No index number found after bracket.");
+ }
+
+ pleaf->index = to_int_checked(index);
+ offset = to_int_checked(endptr - pattern);
+
+ C2H_SKIP_SPACES();
+
+ if (pattern[offset] != ']') {
+ c2_error("Index end marker not found.");
+ }
+
+ ++offset;
+
+ C2H_SKIP_SPACES();
+ }
+
+ // Parse target type and format
+ if (':' == pattern[offset]) {
+ ++offset;
+ C2H_SKIP_SPACES();
+
+ // Look for format
+ bool hasformat = false;
+ long format = 0;
+ {
+ char *endptr = NULL;
+ format = strtol(pattern + offset, &endptr, 0);
+ assert(endptr);
+ if ((hasformat = (endptr && endptr != pattern + offset))) {
+ offset = to_int_checked(endptr - pattern);
+ }
+ C2H_SKIP_SPACES();
+ }
+
+ // Look for type
+ enum c2_l_type type = C2_L_TUNDEFINED;
+ switch (pattern[offset]) {
+ case 'w': type = C2_L_TWINDOW; break;
+ case 'd': type = C2_L_TDRAWABLE; break;
+ case 'c': type = C2_L_TCARDINAL; break;
+ case 's': type = C2_L_TSTRING; break;
+ case 'a': type = C2_L_TATOM; break;
+ default: c2_error("Invalid type character.");
+ }
+
+ if (type) {
+ if (pleaf->predef != C2_L_PUNDEFINED) {
+ log_warn("Type specified for a default target "
+ "will be ignored.");
+ } else {
+ if (pleaf->type && type != pleaf->type) {
+ log_warn("Default type overridden on "
+ "target.");
+ }
+ pleaf->type = type;
+ }
+ }
+
+ offset++;
+ C2H_SKIP_SPACES();
+
+ // Default format
+ if (!pleaf->format) {
+ switch (pleaf->type) {
+ case C2_L_TWINDOW:
+ case C2_L_TDRAWABLE:
+ case C2_L_TATOM: pleaf->format = 32; break;
+ case C2_L_TSTRING: pleaf->format = 8; break;
+ default: break;
+ }
+ }
+
+ // Write format
+ if (hasformat) {
+ if (pleaf->predef != C2_L_PUNDEFINED) {
+ log_warn("Format \"%ld\" specified on a default target "
+ "will be ignored.",
+ format);
+ } else if (pleaf->type == C2_L_TSTRING) {
+ log_warn("Format \"%ld\" specified on a string target "
+ "will be ignored.",
+ format);
+ } else {
+ if (pleaf->format && pleaf->format != format) {
+ log_warn("Default format %d overridden on "
+ "target.",
+ pleaf->format);
+ }
+ pleaf->format = to_int_checked(format);
+ }
+ }
+ }
+
+ if (!pleaf->type) {
+ c2_error("Target type cannot be determined.");
+ }
+
+ // if (!pleaf->predef && !pleaf->format && C2_L_TSTRING != pleaf->type)
+ // c2_error("Target format cannot be determined.");
+
+ if (pleaf->format && 8 != pleaf->format && 16 != pleaf->format && 32 != pleaf->format) {
+ c2_error("Invalid format.");
+ }
+
+ return offset;
+
+fail:
+ return -1;
+}
+
+/**
+ * Parse the operator part of a leaf.
+ */
+static int c2_parse_op(const char *pattern, int offset, c2_ptr_t *presult) {
+ c2_l_t *const pleaf = presult->l;
+
+ // Parse negation marks
+ C2H_SKIP_SPACES();
+ while ('!' == pattern[offset]) {
+ pleaf->neg = !pleaf->neg;
+ ++offset;
+ C2H_SKIP_SPACES();
+ }
+
+ // Parse qualifiers
+ if ('*' == pattern[offset] || '^' == pattern[offset] || '%' == pattern[offset] ||
+ '~' == pattern[offset]) {
+ switch (pattern[offset]) {
+ case '*': pleaf->match = C2_L_MCONTAINS; break;
+ case '^': pleaf->match = C2_L_MSTART; break;
+ case '%': pleaf->match = C2_L_MWILDCARD; break;
+ case '~': pleaf->match = C2_L_MPCRE; break;
+ default: assert(0);
+ }
+ ++offset;
+ C2H_SKIP_SPACES();
+ }
+
+ // Parse flags
+ while ('?' == pattern[offset]) {
+ pleaf->match_ignorecase = true;
+ ++offset;
+ C2H_SKIP_SPACES();
+ }
+
+ // Parse operator
+ while ('=' == pattern[offset] || '>' == pattern[offset] || '<' == pattern[offset]) {
+ if ('=' == pattern[offset] && C2_L_OGT == pleaf->op)
+ pleaf->op = C2_L_OGTEQ;
+ else if ('=' == pattern[offset] && C2_L_OLT == pleaf->op)
+ pleaf->op = C2_L_OLTEQ;
+ else if (pleaf->op) {
+ c2_error("Duplicate operator.");
+ } else {
+ switch (pattern[offset]) {
+ case '=': pleaf->op = C2_L_OEQ; break;
+ case '>': pleaf->op = C2_L_OGT; break;
+ case '<': pleaf->op = C2_L_OLT; break;
+ default: assert(0);
+ }
+ }
+ ++offset;
+ C2H_SKIP_SPACES();
+ }
+
+ // Check for problems
+ if (C2_L_OEQ != pleaf->op && (pleaf->match || pleaf->match_ignorecase))
+ c2_error("Exists/greater-than/less-than operators cannot have a "
+ "qualifier.");
+
+ return offset;
+
+fail:
+ return -1;
+}
+
+/**
+ * Parse the pattern part of a leaf.
+ */
+static int c2_parse_pattern(const char *pattern, int offset, c2_ptr_t *presult) {
+ c2_l_t *const pleaf = presult->l;
+
+ // Exists operator cannot have pattern
+ if (!pleaf->op) {
+ return offset;
+ }
+
+ C2H_SKIP_SPACES();
+
+ char *endptr = NULL;
+ if (!strcmp_wd("true", &pattern[offset])) {
+ pleaf->ptntype = C2_L_PTINT;
+ pleaf->ptnint = true;
+ offset += 4; // length of "true";
+ } else if (!strcmp_wd("false", &pattern[offset])) {
+ pleaf->ptntype = C2_L_PTINT;
+ pleaf->ptnint = false;
+ offset += 5; // length of "false";
+ } else if (pleaf->ptnint = strtol(pattern + offset, &endptr, 0),
+ pattern + offset != endptr) {
+ pleaf->ptntype = C2_L_PTINT;
+ offset = to_int_checked(endptr - pattern);
+ // Make sure we are stopping at the end of a word
+ if (isalnum((unsigned char)pattern[offset])) {
+ c2_error("Trailing characters after a numeric pattern.");
+ }
+ } else {
+ // Parse string patterns
+ bool raw = false;
+ char delim = '\0';
+
+ // String flags
+ if (tolower((unsigned char)pattern[offset]) == 'r') {
+ raw = true;
+ ++offset;
+ C2H_SKIP_SPACES();
+ }
+
+ // Check for delimiters
+ if (pattern[offset] == '\"' || pattern[offset] == '\'') {
+ pleaf->ptntype = C2_L_PTSTRING;
+ delim = pattern[offset];
+ ++offset;
+ }
+
+ if (pleaf->ptntype != C2_L_PTSTRING) {
+ c2_error("Invalid pattern type.");
+ }
+
+ // Parse the string now
+ // We can't determine the length of the pattern, so we use the length
+ // to the end of the pattern string -- currently escape sequences
+ // cannot be converted to a string longer than itself.
+ auto tptnstr = ccalloc((strlen(pattern + offset) + 1), char);
+ char *ptptnstr = tptnstr;
+ pleaf->ptnstr = tptnstr;
+ for (; pattern[offset] && delim != pattern[offset]; ++offset) {
+ // Handle escape sequences if it's not a raw string
+ if ('\\' == pattern[offset] && !raw) {
+ switch (pattern[++offset]) {
+ case '\\': *(ptptnstr++) = '\\'; break;
+ case '\'': *(ptptnstr++) = '\''; break;
+ case '\"': *(ptptnstr++) = '\"'; break;
+ case 'a': *(ptptnstr++) = '\a'; break;
+ case 'b': *(ptptnstr++) = '\b'; break;
+ case 'f': *(ptptnstr++) = '\f'; break;
+ case 'n': *(ptptnstr++) = '\n'; break;
+ case 'r': *(ptptnstr++) = '\r'; break;
+ case 't': *(ptptnstr++) = '\t'; break;
+ case 'v': *(ptptnstr++) = '\v'; break;
+ case 'o':
+ case 'x': {
+ char *tstr = strndup(pattern + offset + 1, 2);
+ char *pstr = NULL;
+ long val = strtol(
+ tstr, &pstr, ('o' == pattern[offset] ? 8 : 16));
+ free(tstr);
+ if (pstr != &tstr[2] || val <= 0)
+ c2_error("Invalid octal/hex escape "
+ "sequence.");
+ *(ptptnstr++) = to_char_checked(val);
+ offset += 2;
+ break;
+ }
+ default: c2_error("Invalid escape sequence.");
+ }
+ } else {
+ *(ptptnstr++) = pattern[offset];
+ }
+ }
+ if (!pattern[offset])
+ c2_error("Premature end of pattern string.");
+ ++offset;
+ *ptptnstr = '\0';
+ pleaf->ptnstr = strdup(tptnstr);
+ free(tptnstr);
+ }
+
+ C2H_SKIP_SPACES();
+
+ if (!pleaf->ptntype)
+ c2_error("Invalid pattern type.");
+
+ // Check if the type is correct
+ if (!(((C2_L_TSTRING == pleaf->type || C2_L_TATOM == pleaf->type) &&
+ C2_L_PTSTRING == pleaf->ptntype) ||
+ ((C2_L_TCARDINAL == pleaf->type || C2_L_TWINDOW == pleaf->type ||
+ C2_L_TDRAWABLE == pleaf->type) &&
+ C2_L_PTINT == pleaf->ptntype)))
+ c2_error("Pattern type incompatible with target type.");
+
+ if (C2_L_PTINT == pleaf->ptntype && pleaf->match)
+ c2_error("Integer/boolean pattern cannot have operator qualifiers.");
+
+ if (C2_L_PTINT == pleaf->ptntype && pleaf->match_ignorecase)
+ c2_error("Integer/boolean pattern cannot have flags.");
+
+ if (C2_L_PTSTRING == pleaf->ptntype &&
+ (C2_L_OGT == pleaf->op || C2_L_OGTEQ == pleaf->op || C2_L_OLT == pleaf->op ||
+ C2_L_OLTEQ == pleaf->op))
+ c2_error("String pattern cannot have an arithmetic operator.");
+
+ return offset;
+
+fail:
+ return -1;
+}
+
+/**
+ * Parse a condition with legacy syntax.
+ */
+static int c2_parse_legacy(const char *pattern, int offset, c2_ptr_t *presult) {
+ if (strlen(pattern + offset) < 4 || pattern[offset + 1] != ':' ||
+ !strchr(pattern + offset + 2, ':')) {
+ c2_error("Legacy parser: Invalid format.");
+ }
+
+ // Allocate memory for new leaf
+ auto pleaf = cmalloc(c2_l_t);
+ presult->isbranch = false;
+ presult->l = pleaf;
+ memcpy(pleaf, &leaf_def, sizeof(c2_l_t));
+ pleaf->type = C2_L_TSTRING;
+ pleaf->op = C2_L_OEQ;
+ pleaf->ptntype = C2_L_PTSTRING;
+
+ // Determine the pattern target
+#define TGTFILL(pdefid) \
+ (pleaf->predef = pdefid, pleaf->type = C2_PREDEFS[pdefid].type, \
+ pleaf->format = C2_PREDEFS[pdefid].format)
+ switch (pattern[offset]) {
+ case 'n': TGTFILL(C2_L_PNAME); break;
+ case 'i': TGTFILL(C2_L_PCLASSI); break;
+ case 'g': TGTFILL(C2_L_PCLASSG); break;
+ case 'r': TGTFILL(C2_L_PROLE); break;
+ default: c2_error("Target \"%c\" invalid.\n", pattern[offset]);
+ }
+#undef TGTFILL
+
+ offset += 2;
+
+ // Determine the match type
+ switch (pattern[offset]) {
+ case 'e': pleaf->match = C2_L_MEXACT; break;
+ case 'a': pleaf->match = C2_L_MCONTAINS; break;
+ case 's': pleaf->match = C2_L_MSTART; break;
+ case 'w': pleaf->match = C2_L_MWILDCARD; break;
+ case 'p': pleaf->match = C2_L_MPCRE; break;
+ default: c2_error("Type \"%c\" invalid.\n", pattern[offset]);
+ }
+ ++offset;
+
+ // Determine the pattern flags
+ while (':' != pattern[offset]) {
+ switch (pattern[offset]) {
+ case 'i': pleaf->match_ignorecase = true; break;
+ default: c2_error("Flag \"%c\" invalid.", pattern[offset]);
+ }
+ ++offset;
+ }
+ ++offset;
+
+ // Copy the pattern
+ pleaf->ptnstr = strdup(pattern + offset);
+
+ return offset;
+
+fail:
+ return -1;
+}
+
+#undef c2_error
+
+/**
+ * Do postprocessing on a condition leaf.
+ */
+static bool c2_l_postprocess(session_t *ps, c2_l_t *pleaf) {
+ // Give a pattern type to a leaf with exists operator, if needed
+ if (C2_L_OEXISTS == pleaf->op && !pleaf->ptntype) {
+ pleaf->ptntype = (C2_L_TSTRING == pleaf->type ? C2_L_PTSTRING : C2_L_PTINT);
+ }
+
+ // Get target atom if it's not a predefined one
+ if (pleaf->predef == C2_L_PUNDEFINED) {
+ pleaf->tgtatom = get_atom(ps->atoms, pleaf->tgt);
+ if (!pleaf->tgtatom) {
+ log_error("Failed to get atom for target \"%s\".", pleaf->tgt);
+ return false;
+ }
+ }
+
+ // Insert target Atom into atom track list
+ if (pleaf->tgtatom) {
+ bool found = false;
+ for (latom_t *platom = ps->track_atom_lst; platom; platom = platom->next) {
+ if (pleaf->tgtatom == platom->atom) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ auto pnew = cmalloc(latom_t);
+ pnew->next = ps->track_atom_lst;
+ pnew->atom = pleaf->tgtatom;
+ ps->track_atom_lst = pnew;
+ }
+ }
+
+ // Warn about lower case characters in target name
+ if (pleaf->predef == C2_L_PUNDEFINED) {
+ for (const char *pc = pleaf->tgt; *pc; ++pc) {
+ if (islower((unsigned char)*pc)) {
+ log_warn("Lowercase character in target name \"%s\".",
+ pleaf->tgt);
+ break;
+ }
+ }
+ }
+
+ // PCRE patterns
+ if (C2_L_PTSTRING == pleaf->ptntype && C2_L_MPCRE == pleaf->match) {
+#ifdef CONFIG_REGEX_PCRE
+ const char *error = NULL;
+ int erroffset = 0;
+ int options = 0;
+
+ // Ignore case flag
+ if (pleaf->match_ignorecase)
+ options |= PCRE_CASELESS;
+
+ // Compile PCRE expression
+ pleaf->regex_pcre =
+ pcre_compile(pleaf->ptnstr, options, &error, &erroffset, NULL);
+ if (!pleaf->regex_pcre) {
+ log_error("Pattern \"%s\": PCRE regular expression parsing "
+ "failed on "
+ "offset %d: %s",
+ pleaf->ptnstr, erroffset, error);
+ return false;
+ }
+#ifdef CONFIG_REGEX_PCRE_JIT
+ pleaf->regex_pcre_extra =
+ pcre_study(pleaf->regex_pcre, PCRE_STUDY_JIT_COMPILE, &error);
+ if (!pleaf->regex_pcre_extra) {
+ printf("Pattern \"%s\": PCRE regular expression study failed: %s",
+ pleaf->ptnstr, error);
+ }
+#endif
+
+ // Free the target string
+ // free(pleaf->tgt);
+ // pleaf->tgt = NULL;
+#else
+ log_error("PCRE regular expression support not compiled in.");
+ return false;
+#endif
+ }
+
+ return true;
+}
+
+static bool c2_tree_postprocess(session_t *ps, c2_ptr_t node) {
+ if (!node.isbranch) {
+ return c2_l_postprocess(ps, node.l);
+ }
+ if (!c2_tree_postprocess(ps, node.b->opr1))
+ return false;
+ return c2_tree_postprocess(ps, node.b->opr2);
+}
+
+bool c2_list_postprocess(session_t *ps, c2_lptr_t *list) {
+ c2_lptr_t *head = list;
+ while (head) {
+ if (!c2_tree_postprocess(ps, head->ptr))
+ return false;
+ head = head->next;
+ }
+ return true;
+}
+/**
+ * Free a condition tree.
+ */
+static void c2_free(c2_ptr_t p) {
+ // For a branch element
+ if (p.isbranch) {
+ c2_b_t *const pbranch = p.b;
+
+ if (!pbranch)
+ return;
+
+ c2_free(pbranch->opr1);
+ c2_free(pbranch->opr2);
+ free(pbranch);
+ }
+ // For a leaf element
+ else {
+ c2_l_t *const pleaf = p.l;
+
+ if (!pleaf)
+ return;
+
+ free(pleaf->tgt);
+ free(pleaf->ptnstr);
+#ifdef CONFIG_REGEX_PCRE
+ pcre_free(pleaf->regex_pcre);
+ LPCRE_FREE_STUDY(pleaf->regex_pcre_extra);
+#endif
+ free(pleaf);
+ }
+}
+
+/**
+ * Free a condition tree in c2_lptr_t.
+ */
+c2_lptr_t *c2_free_lptr(c2_lptr_t *lp) {
+ if (!lp)
+ return NULL;
+
+ c2_lptr_t *pnext = lp->next;
+ c2_free(lp->ptr);
+ free(lp);
+
+ return pnext;
+}
+
+/**
+ * Get a string representation of a rule target.
+ */
+static const char *c2h_dump_str_tgt(const c2_l_t *pleaf) {
+ if (pleaf->predef != C2_L_PUNDEFINED) {
+ return C2_PREDEFS[pleaf->predef].name;
+ } else {
+ return pleaf->tgt;
+ }
+}
+
+/**
+ * Get a string representation of a target.
+ */
+static const char *c2h_dump_str_type(const c2_l_t *pleaf) {
+ switch (pleaf->type) {
+ case C2_L_TWINDOW: return "w";
+ case C2_L_TDRAWABLE: return "d";
+ case C2_L_TCARDINAL: return "c";
+ case C2_L_TSTRING: return "s";
+ case C2_L_TATOM: return "a";
+ case C2_L_TUNDEFINED: break;
+ }
+
+ return NULL;
+}
+
+/**
+ * Dump a condition tree.
+ */
+static void c2_dump(c2_ptr_t p) {
+ // For a branch
+ if (p.isbranch) {
+ const c2_b_t *const pbranch = p.b;
+
+ if (!pbranch) {
+ return;
+ }
+
+ if (pbranch->neg) {
+ putchar('!');
+ }
+
+ printf("(");
+ c2_dump(pbranch->opr1);
+
+ switch (pbranch->op) {
+ case C2_B_OAND: printf(" && "); break;
+ case C2_B_OOR: printf(" || "); break;
+ case C2_B_OXOR: printf(" XOR "); break;
+ default: assert(0); break;
+ }
+
+ c2_dump(pbranch->opr2);
+ printf(") ");
+ }
+ // For a leaf
+ else {
+ const c2_l_t *const pleaf = p.l;
+
+ if (!pleaf) {
+ return;
+ }
+
+ if (C2_L_OEXISTS == pleaf->op && pleaf->neg) {
+ putchar('!');
+ }
+
+ // Print target name, type, and format
+ {
+ printf("%s", c2h_dump_str_tgt(pleaf));
+ if (pleaf->tgt_onframe) {
+ putchar('@');
+ }
+ if (pleaf->predef == C2_L_PUNDEFINED) {
+ if (pleaf->index < 0) {
+ printf("[*]");
+ } else {
+ printf("[%d]", pleaf->index);
+ }
+ }
+ printf(":%d%s", pleaf->format, c2h_dump_str_type(pleaf));
+ }
+
+ // Print operator
+ putchar(' ');
+
+ if (C2_L_OEXISTS != pleaf->op && pleaf->neg) {
+ putchar('!');
+ }
+
+ switch (pleaf->match) {
+ case C2_L_MEXACT: break;
+ case C2_L_MCONTAINS: putchar('*'); break;
+ case C2_L_MSTART: putchar('^'); break;
+ case C2_L_MPCRE: putchar('~'); break;
+ case C2_L_MWILDCARD: putchar('%'); break;
+ }
+
+ if (pleaf->match_ignorecase) {
+ putchar('?');
+ }
+
+ switch (pleaf->op) {
+ case C2_L_OEXISTS: break;
+ case C2_L_OEQ: fputs("=", stdout); break;
+ case C2_L_OGT: fputs(">", stdout); break;
+ case C2_L_OGTEQ: fputs(">=", stdout); break;
+ case C2_L_OLT: fputs("<", stdout); break;
+ case C2_L_OLTEQ: fputs("<=", stdout); break;
+ }
+
+ if (C2_L_OEXISTS == pleaf->op) {
+ return;
+ }
+
+ // Print pattern
+ putchar(' ');
+ switch (pleaf->ptntype) {
+ case C2_L_PTINT: printf("%ld", pleaf->ptnint); break;
+ case C2_L_PTSTRING:
+ // TODO(yshui) Escape string before printing out?
+ printf("\"%s\"", pleaf->ptnstr);
+ break;
+ default: assert(0); break;
+ }
+ }
+}
+
+/**
+ * Get the type atom of a condition.
+ */
+static xcb_atom_t c2_get_atom_type(const c2_l_t *pleaf) {
+ switch (pleaf->type) {
+ case C2_L_TCARDINAL: return XCB_ATOM_CARDINAL;
+ case C2_L_TWINDOW: return XCB_ATOM_WINDOW;
+ case C2_L_TSTRING: return XCB_ATOM_STRING;
+ case C2_L_TATOM: return XCB_ATOM_ATOM;
+ case C2_L_TDRAWABLE: return XCB_ATOM_DRAWABLE;
+ default: assert(0); break;
+ }
+ unreachable;
+}
+
+/**
+ * Match a window against a single leaf window condition.
+ *
+ * For internal use.
+ */
+static inline void c2_match_once_leaf(session_t *ps, const struct managed_win *w,
+ const c2_l_t *pleaf, bool *pres, bool *perr) {
+ assert(pleaf);
+
+ const xcb_window_t wid = (pleaf->tgt_onframe ? w->client_win : w->base.id);
+
+ // Return if wid is missing
+ if (pleaf->predef == C2_L_PUNDEFINED && !wid) {
+ return;
+ }
+
+ const int idx = (pleaf->index < 0 ? 0 : pleaf->index);
+
+ switch (pleaf->ptntype) {
+ // Deal with integer patterns
+ case C2_L_PTINT: {
+ long long *targets = NULL;
+ long long *targets_free = NULL;
+ size_t ntargets = 0;
+
+ // Get the value
+ // A predefined target
+ long long predef_target = 0;
+ if (pleaf->predef != C2_L_PUNDEFINED) {
+ *perr = false;
+ switch (pleaf->predef) {
+ case C2_L_PID: predef_target = wid; break;
+ case C2_L_PX: predef_target = w->g.x; break;
+ case C2_L_PY: predef_target = w->g.y; break;
+ case C2_L_PX2: predef_target = w->g.x + w->widthb; break;
+ case C2_L_PY2: predef_target = w->g.y + w->heightb; break;
+ case C2_L_PWIDTH: predef_target = w->g.width; break;
+ case C2_L_PHEIGHT: predef_target = w->g.height; break;
+ case C2_L_PWIDTHB: predef_target = w->widthb; break;
+ case C2_L_PHEIGHTB: predef_target = w->heightb; break;
+ case C2_L_PBDW: predef_target = w->g.border_width; break;
+ case C2_L_PFULLSCREEN:
+ predef_target = win_is_fullscreen(ps, w);
+ break;
+ case C2_L_POVREDIR: predef_target = w->a.override_redirect; break;
+ case C2_L_PARGB: predef_target = win_has_alpha(w); break;
+ case C2_L_PFOCUSED:
+ predef_target = win_is_focused_raw(ps, w);
+ break;
+ case C2_L_PWMWIN: predef_target = w->wmwin; break;
+ case C2_L_PBSHAPED: predef_target = w->bounding_shaped; break;
+ case C2_L_PROUNDED: predef_target = w->rounded_corners; break;
+ case C2_L_PCLIENT: predef_target = w->client_win; break;
+ case C2_L_PLEADER: predef_target = w->leader; break;
+ default:
+ *perr = true;
+ assert(0);
+ break;
+ }
+ ntargets = 1;
+ targets = &predef_target;
+ }
+ // A raw window property
+ else {
+ int word_count = 1;
+ if (pleaf->index < 0) {
+ // Get length of property in 32-bit multiples
+ auto prop_info = x_get_prop_info(ps->c, wid, pleaf->tgtatom);
+ word_count = to_int_checked((prop_info.length + 4 - 1) / 4);
+ }
+ winprop_t prop = x_get_prop_with_offset(
+ ps->c, wid, pleaf->tgtatom, idx, word_count,
+ c2_get_atom_type(pleaf), pleaf->format);
+
+ ntargets = (pleaf->index < 0 ? prop.nitems : min2(prop.nitems, 1));
+ if (ntargets > 0) {
+ targets = targets_free = ccalloc(ntargets, long long);
+ *perr = false;
+ for (size_t i = 0; i < ntargets; ++i) {
+ targets[i] = winprop_get_int(prop, i);
+ }
+ }
+ free_winprop(&prop);
+ }
+
+ if (*perr) {
+ goto fail_int;
+ }
+
+ // Do comparison
+ bool res = false;
+ for (size_t i = 0; i < ntargets; ++i) {
+ long long tgt = targets[i];
+ switch (pleaf->op) {
+ case C2_L_OEXISTS:
+ res = (pleaf->predef != C2_L_PUNDEFINED ? tgt : true);
+ break;
+ case C2_L_OEQ: res = (tgt == pleaf->ptnint); break;
+ case C2_L_OGT: res = (tgt > pleaf->ptnint); break;
+ case C2_L_OGTEQ: res = (tgt >= pleaf->ptnint); break;
+ case C2_L_OLT: res = (tgt < pleaf->ptnint); break;
+ case C2_L_OLTEQ: res = (tgt <= pleaf->ptnint); break;
+ default: *perr = true; assert(0);
+ }
+ if (res) {
+ break;
+ }
+ }
+ *pres = res;
+
+ fail_int:
+ // Free property values after usage, if necessary
+ if (targets_free) {
+ free(targets_free);
+ }
+ } break;
+ // String patterns
+ case C2_L_PTSTRING: {
+ const char **targets = NULL;
+ const char **targets_free = NULL;
+ const char **targets_free_inner = NULL;
+ size_t ntargets = 0;
+
+ // A predefined target
+ const char *predef_target = NULL;
+ if (pleaf->predef != C2_L_PUNDEFINED) {
+ switch (pleaf->predef) {
+ case C2_L_PWINDOWTYPE:
+ predef_target = WINTYPES[w->window_type];
+ break;
+ case C2_L_PNAME: predef_target = w->name; break;
+ case C2_L_PCLASSG: predef_target = w->class_general; break;
+ case C2_L_PCLASSI: predef_target = w->class_instance; break;
+ case C2_L_PROLE: predef_target = w->role; break;
+ default: assert(0); break;
+ }
+ ntargets = 1;
+ targets = &predef_target;
+ }
+ // An atom type property, convert it to string
+ else if (pleaf->type == C2_L_TATOM) {
+ int word_count = 1;
+ if (pleaf->index < 0) {
+ // Get length of property in 32-bit multiples
+ auto prop_info = x_get_prop_info(ps->c, wid, pleaf->tgtatom);
+ word_count = to_int_checked((prop_info.length + 4 - 1) / 4);
+ }
+ winprop_t prop = x_get_prop_with_offset(
+ ps->c, wid, pleaf->tgtatom, idx, word_count,
+ c2_get_atom_type(pleaf), pleaf->format);
+
+ ntargets = (pleaf->index < 0 ? prop.nitems : min2(prop.nitems, 1));
+ targets = targets_free = (const char **)ccalloc(2 * ntargets, char *);
+ targets_free_inner = targets + ntargets;
+
+ for (size_t i = 0; i < ntargets; ++i) {
+ xcb_atom_t atom = (xcb_atom_t)winprop_get_int(prop, i);
+ if (atom) {
+ xcb_get_atom_name_reply_t *reply = xcb_get_atom_name_reply(
+ ps->c, xcb_get_atom_name(ps->c, atom), NULL);
+ if (reply) {
+ targets[i] = targets_free_inner[i] = strndup(
+ xcb_get_atom_name_name(reply),
+ (size_t)xcb_get_atom_name_name_length(reply));
+ free(reply);
+ }
+ }
+ }
+ free_winprop(&prop);
+ }
+ // Not an atom type, just fetch the string list
+ else {
+ char **strlst = NULL;
+ int nstr = 0;
+ if (wid_get_text_prop(ps, wid, pleaf->tgtatom, &strlst, &nstr)) {
+ if (pleaf->index < 0 && nstr > 0 && strlen(strlst[0]) > 0) {
+ ntargets = to_u32_checked(nstr);
+ targets = (const char **)strlst;
+ } else if (nstr > idx) {
+ ntargets = 1;
+ targets = (const char **)strlst + idx;
+ }
+ }
+ if (strlst) {
+ targets_free = (const char **)strlst;
+ }
+ }
+
+ if (ntargets == 0) {
+ goto fail_str;
+ }
+ for (size_t i = 0; i < ntargets; ++i) {
+ if (!targets[i]) {
+ goto fail_str;
+ }
+ }
+ *perr = false;
+
+ // Actual matching
+ bool res = false;
+ for (size_t i = 0; i < ntargets; ++i) {
+ const char *tgt = targets[i];
+ switch (pleaf->op) {
+ case C2_L_OEXISTS: res = true; break;
+ case C2_L_OEQ:
+ switch (pleaf->match) {
+ case C2_L_MEXACT:
+ if (pleaf->match_ignorecase) {
+ res = !strcasecmp(tgt, pleaf->ptnstr);
+ } else {
+ res = !strcmp(tgt, pleaf->ptnstr);
+ }
+ break;
+ case C2_L_MCONTAINS:
+ if (pleaf->match_ignorecase) {
+ res = strcasestr(tgt, pleaf->ptnstr);
+ } else {
+ res = strstr(tgt, pleaf->ptnstr);
+ }
+ break;
+ case C2_L_MSTART:
+ if (pleaf->match_ignorecase) {
+ res = !strncasecmp(tgt, pleaf->ptnstr,
+ strlen(pleaf->ptnstr));
+ } else {
+ res = !strncmp(tgt, pleaf->ptnstr,
+ strlen(pleaf->ptnstr));
+ }
+ break;
+ case C2_L_MWILDCARD: {
+ int flags = 0;
+ if (pleaf->match_ignorecase) {
+ flags |= FNM_CASEFOLD;
+ }
+ res = !fnmatch(pleaf->ptnstr, tgt, flags);
+ } break;
+ case C2_L_MPCRE:
+#ifdef CONFIG_REGEX_PCRE
+ assert(strlen(tgt) <= INT_MAX);
+ res = (pcre_exec(pleaf->regex_pcre,
+ pleaf->regex_pcre_extra, tgt,
+ (int)strlen(tgt), 0, 0, NULL, 0) >= 0);
+#else
+ assert(0);
+#endif
+ break;
+ }
+ break;
+ default: *perr = true; assert(0);
+ }
+ if (res) {
+ break;
+ }
+ }
+ *pres = res;
+
+ fail_str:
+ // Free the string after usage, if necessary
+ if (targets_free_inner) {
+ for (size_t i = 0; i < ntargets; ++i) {
+ if (targets_free_inner[i]) {
+ free((void *)targets_free_inner[i]);
+ }
+ }
+ }
+ // Free property values after usage, if necessary
+ if (targets_free) {
+ free(targets_free);
+ }
+ } break;
+ default: assert(0); break;
+ }
+}
+
+/**
+ * Match a window against a single window condition.
+ *
+ * @return true if matched, false otherwise.
+ */
+static bool c2_match_once(session_t *ps, const struct managed_win *w, const c2_ptr_t cond) {
+ bool result = false;
+ bool error = true;
+
+ // Handle a branch
+ if (cond.isbranch) {
+ const c2_b_t *pb = cond.b;
+
+ if (!pb)
+ return false;
+
+ error = false;
+
+ switch (pb->op) {
+ case C2_B_OAND:
+ result = (c2_match_once(ps, w, pb->opr1) &&
+ c2_match_once(ps, w, pb->opr2));
+ break;
+ case C2_B_OOR:
+ result = (c2_match_once(ps, w, pb->opr1) ||
+ c2_match_once(ps, w, pb->opr2));
+ break;
+ case C2_B_OXOR:
+ result = (c2_match_once(ps, w, pb->opr1) !=
+ c2_match_once(ps, w, pb->opr2));
+ break;
+ default: error = true; assert(0);
+ }
+
+#ifdef DEBUG_WINMATCH
+ log_trace("(%#010x): branch: result = %d, pattern = ", w->base.id, result);
+ c2_dump(cond);
+ putchar('\n');
+#endif
+ }
+ // Handle a leaf
+ else {
+ const c2_l_t *pleaf = cond.l;
+
+ if (!pleaf)
+ return false;
+
+ c2_match_once_leaf(ps, w, pleaf, &result, &error);
+
+ // For EXISTS operator, no errors are fatal
+ if (C2_L_OEXISTS == pleaf->op && error) {
+ result = false;
+ error = false;
+ }
+
+#ifdef DEBUG_WINMATCH
+ log_trace("(%#010x): leaf: result = %d, error = %d, "
+ "client = %#010x, pattern = ",
+ w->base.id, result, error, w->client_win);
+ c2_dump(cond);
+ putchar('\n');
+#endif
+ }
+
+ // Postprocess the result
+ if (error)
+ result = false;
+
+ if (cond.isbranch ? cond.b->neg : cond.l->neg)
+ result = !result;
+
+ return result;
+}
+
+/**
+ * Match a window against a condition linked list.
+ *
+ * @param cache a place to cache the last matched condition
+ * @param pdata a place to return the data
+ * @return true if matched, false otherwise.
+ */
+bool c2_match(session_t *ps, const struct managed_win *w, const c2_lptr_t *condlst,
+ void **pdata) {
+ assert(ps->server_grabbed);
+ // Then go through the whole linked list
+ for (; condlst; condlst = condlst->next) {
+ if (c2_match_once(ps, w, condlst->ptr)) {
+ if (pdata)
+ *pdata = condlst->data;
+ return true;
+ }
+ }
+
+ return false;
+}
diff --git a/dwm/picom/src/c2.h b/dwm/picom/src/c2.h
new file mode 100644
index 0000000..d6b1d37
--- /dev/null
+++ b/dwm/picom/src/c2.h
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: MIT
+/*
+ * Compton - a compositor for X11
+ *
+ * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
+ *
+ * Copyright (c) 2011-2013, Christopher Jeffrey
+ * See LICENSE-mit for more information.
+ *
+ */
+
+#pragma once
+
+#include
+
+typedef struct _c2_lptr c2_lptr_t;
+typedef struct session session_t;
+struct managed_win;
+
+c2_lptr_t *c2_parse(c2_lptr_t **pcondlst, const char *pattern, void *data);
+
+c2_lptr_t *c2_free_lptr(c2_lptr_t *lp);
+
+bool c2_match(session_t *ps, const struct managed_win *w, const c2_lptr_t *condlst, void **pdata);
+
+bool c2_list_postprocess(session_t *ps, c2_lptr_t *list);
diff --git a/dwm/picom/src/cache.c b/dwm/picom/src/cache.c
new file mode 100644
index 0000000..1ffb31c
--- /dev/null
+++ b/dwm/picom/src/cache.c
@@ -0,0 +1,95 @@
+#include
+
+#include "compiler.h"
+#include "utils.h"
+#include "cache.h"
+
+struct cache_entry {
+ char *key;
+ void *value;
+ UT_hash_handle hh;
+};
+
+struct cache {
+ cache_getter_t getter;
+ cache_free_t free;
+ void *user_data;
+ struct cache_entry *entries;
+};
+
+void cache_set(struct cache *c, const char *key, void *data) {
+ struct cache_entry *e = NULL;
+ HASH_FIND_STR(c->entries, key, e);
+ CHECK(!e);
+
+ e = ccalloc(1, struct cache_entry);
+ e->key = strdup(key);
+ e->value = data;
+ HASH_ADD_STR(c->entries, key, e);
+}
+
+void *cache_get(struct cache *c, const char *key, int *err) {
+ struct cache_entry *e;
+ HASH_FIND_STR(c->entries, key, e);
+ if (e) {
+ return e->value;
+ }
+
+ int tmperr;
+ if (!err) {
+ err = &tmperr;
+ }
+
+ *err = 0;
+ e = ccalloc(1, struct cache_entry);
+ e->key = strdup(key);
+ e->value = c->getter(c->user_data, key, err);
+ if (*err) {
+ free(e->key);
+ free(e);
+ return NULL;
+ }
+
+ HASH_ADD_STR(c->entries, key, e);
+ return e->value;
+}
+
+static inline void _cache_invalidate(struct cache *c, struct cache_entry *e) {
+ if (c->free) {
+ c->free(c->user_data, e->value);
+ }
+ free(e->key);
+ HASH_DEL(c->entries, e);
+ free(e);
+}
+
+void cache_invalidate(struct cache *c, const char *key) {
+ struct cache_entry *e;
+ HASH_FIND_STR(c->entries, key, e);
+
+ if (e) {
+ _cache_invalidate(c, e);
+ }
+}
+
+void cache_invalidate_all(struct cache *c) {
+ struct cache_entry *e, *tmpe;
+ HASH_ITER(hh, c->entries, e, tmpe) {
+ _cache_invalidate(c, e);
+ }
+}
+
+void *cache_free(struct cache *c) {
+ void *ret = c->user_data;
+ cache_invalidate_all(c);
+ free(c);
+ return ret;
+}
+
+struct cache *new_cache(void *ud, cache_getter_t getter, cache_free_t f) {
+ auto c = ccalloc(1, struct cache);
+ c->user_data = ud;
+ c->getter = getter;
+ c->free = f;
+ return c;
+}
diff --git a/dwm/picom/src/cache.h b/dwm/picom/src/cache.h
new file mode 100644
index 0000000..3ca054f
--- /dev/null
+++ b/dwm/picom/src/cache.h
@@ -0,0 +1,32 @@
+#pragma once
+
+struct cache;
+
+typedef void *(*cache_getter_t)(void *user_data, const char *key, int *err);
+typedef void (*cache_free_t)(void *user_data, void *data);
+
+/// Create a cache with `getter`, and a free function `f` which is used to free the cache
+/// value when they are invalidated.
+///
+/// `user_data` will be passed to `getter` and `f` when they are called.
+struct cache *new_cache(void *user_data, cache_getter_t getter, cache_free_t f);
+
+/// Fetch a value from the cache. If the value doesn't present in the cache yet, the
+/// getter will be called, and the returned value will be stored into the cache.
+void *cache_get(struct cache *, const char *key, int *err);
+
+/// Invalidate a value in the cache.
+void cache_invalidate(struct cache *, const char *key);
+
+/// Invalidate all values in the cache.
+void cache_invalidate_all(struct cache *);
+
+/// Invalidate all values in the cache and free it. Returns the user data passed to
+/// `new_cache`
+void *cache_free(struct cache *);
+
+/// Insert a key-value pair into the cache. Only used for internal testing. Takes
+/// ownership of `data`
+///
+/// If `key` already exists in the cache, this function will abort the program.
+void cache_set(struct cache *c, const char *key, void *data);
diff --git a/dwm/picom/src/common.h b/dwm/picom/src/common.h
new file mode 100644
index 0000000..d5dda60
--- /dev/null
+++ b/dwm/picom/src/common.h
@@ -0,0 +1,534 @@
+// SPDX-License-Identifier: MIT
+/*
+ * Compton - a compositor for X11
+ *
+ * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
+ *
+ * Copyright (c) 2011-2013, Christopher Jeffrey
+ * Copyright (c) 2018, Yuxuan Shui
+ *
+ * See LICENSE-mit for more information.
+ *
+ */
+
+#pragma once
+
+// === Options ===
+
+// Debug options, enable them using -D in CFLAGS
+// #define DEBUG_REPAINT 1
+// #define DEBUG_EVENTS 1
+// #define DEBUG_RESTACK 1
+// #define DEBUG_WINMATCH 1
+// #define DEBUG_C2 1
+// #define DEBUG_GLX_DEBUG_CONTEXT 1
+
+#define MAX_ALPHA (255)
+
+// === Includes ===
+
+// For some special functions
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "uthash_extra.h"
+#ifdef CONFIG_OPENGL
+#include "backend/gl/glx.h"
+#endif
+
+// X resource checker
+#ifdef DEBUG_XRC
+#include "xrescheck.h"
+#endif
+
+// FIXME This list of includes should get shorter
+#include "backend/backend.h"
+#include "backend/driver.h"
+#include "compiler.h"
+#include "config.h"
+#include "region.h"
+#include "types.h"
+#include "utils.h"
+#include "list.h"
+#include "render.h"
+#include "win_defs.h"
+#include "x.h"
+
+// === Constants ===0
+
+#define NS_PER_SEC 1000000000L
+#define US_PER_SEC 1000000L
+#define MS_PER_SEC 1000
+
+/// @brief Maximum OpenGL FBConfig depth.
+#define OPENGL_MAX_DEPTH 32
+
+/// @brief Maximum OpenGL buffer age.
+#define CGLX_MAX_BUFFER_AGE 5
+
+// Window flags
+
+// === Types ===
+typedef struct glx_fbconfig glx_fbconfig_t;
+struct glx_session;
+struct atom;
+struct conv;
+
+typedef struct _ignore {
+ struct _ignore *next;
+ unsigned long sequence;
+} ignore_t;
+
+#ifdef CONFIG_OPENGL
+#ifdef DEBUG_GLX_DEBUG_CONTEXT
+typedef GLXContext (*f_glXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config,
+ GLXContext share_context, Bool direct,
+ const int *attrib_list);
+typedef void (*GLDEBUGPROC)(GLenum source, GLenum type, GLuint id, GLenum severity,
+ GLsizei length, const GLchar *message, GLvoid *userParam);
+typedef void (*f_DebugMessageCallback)(GLDEBUGPROC, void *userParam);
+#endif
+
+typedef struct glx_prog_main {
+ /// GLSL program.
+ GLuint prog;
+ /// Location of uniform "opacity" in window GLSL program.
+ GLint unifm_opacity;
+ /// Location of uniform "invert_color" in blur GLSL program.
+ GLint unifm_invert_color;
+ /// Location of uniform "tex" in window GLSL program.
+ GLint unifm_tex;
+ /// Location of uniform "time" in window GLSL program.
+ GLint unifm_time;
+} glx_prog_main_t;
+
+#define GLX_PROG_MAIN_INIT \
+ { \
+ .prog = 0, .unifm_opacity = -1, .unifm_invert_color = -1, \
+ .unifm_tex = -1, .unifm_time = -1 \
+ }
+
+#else
+struct glx_prog_main {};
+#endif
+
+#define PAINT_INIT \
+ { .pixmap = XCB_NONE, .pict = XCB_NONE }
+
+/// Linked list type of atoms.
+typedef struct _latom {
+ xcb_atom_t atom;
+ struct _latom *next;
+} latom_t;
+
+/// Structure containing all necessary data for a session.
+typedef struct session {
+ // === Event handlers ===
+ /// ev_io for X connection
+ ev_io xiow;
+ /// Timeout for delayed unredirection.
+ ev_timer unredir_timer;
+ /// Timer for fading
+ ev_timer fade_timer;
+ /// Timer for animations
+ ev_timer animation_timer;
+ /// Use an ev_idle callback for drawing
+ /// So we only start drawing when events are processed
+ ev_idle draw_idle;
+ /// Called everytime we have timeouts or new data on socket,
+ /// so we can be sure if xcb read from X socket at anytime during event
+ /// handling, we will not left any event unhandled in the queue
+ ev_prepare event_check;
+ /// Signal handler for SIGUSR1
+ ev_signal usr1_signal;
+ /// Signal handler for SIGINT
+ ev_signal int_signal;
+ /// backend data
+ backend_t *backend_data;
+ /// backend blur context
+ void *backend_blur_context;
+ /// graphic drivers used
+ enum driver drivers;
+ /// file watch handle
+ void *file_watch_handle;
+ /// libev mainloop
+ struct ev_loop *loop;
+
+ // === Display related ===
+ /// Whether the X server is grabbed by us
+ bool server_grabbed;
+ /// Display in use.
+ Display *dpy;
+ /// Previous handler of X errors
+ XErrorHandler previous_xerror_handler;
+ /// Default screen.
+ int scr;
+ /// XCB connection.
+ xcb_connection_t *c;
+ /// Default visual.
+ xcb_visualid_t vis;
+ /// Default depth.
+ int depth;
+ /// Root window.
+ xcb_window_t root;
+ /// Height of root window.
+ int root_height;
+ /// Width of root window.
+ int root_width;
+ /// Current desktop number of root window
+ int root_desktop_num;
+ /// Desktop switch direction
+ int root_desktop_switch_direction;
+ // Damage of root window.
+ // Damage root_damage;
+ /// X Composite overlay window.
+ xcb_window_t overlay;
+ /// The target window for debug mode
+ xcb_window_t debug_window;
+ /// Whether the root tile is filled by us.
+ bool root_tile_fill;
+ /// Picture of the root window background.
+ paint_t root_tile_paint;
+ /// The backend data the root pixmap bound to
+ void *root_image;
+ /// A region of the size of the screen.
+ region_t screen_reg;
+ /// Picture of root window. Destination of painting in no-DBE painting
+ /// mode.
+ xcb_render_picture_t root_picture;
+ /// A Picture acting as the painting target.
+ xcb_render_picture_t tgt_picture;
+ /// Temporary buffer to paint to before sending to display.
+ paint_t tgt_buffer;
+ /// Window ID of the window we register as a symbol.
+ xcb_window_t reg_win;
+#ifdef CONFIG_OPENGL
+ /// Pointer to GLX data.
+ struct glx_session *psglx;
+ /// Custom GLX program used for painting window.
+ // XXX should be in struct glx_session
+ glx_prog_main_t glx_prog_win;
+ struct glx_fbconfig_info *argb_fbconfig;
+#endif
+ /// Sync fence to sync draw operations
+ xcb_sync_fence_t sync_fence;
+ /// Whether we are rendering the first frame after screen is redirected
+ bool first_frame;
+
+ // === Operation related ===
+ /// Flags related to the root window
+ uint64_t root_flags;
+ /// Program options.
+ options_t o;
+ /// Whether we have hit unredirection timeout.
+ bool tmout_unredir_hit;
+ /// Whether we need to redraw the screen
+ bool redraw_needed;
+
+ /// Cache a xfixes region so we don't need to allocate it everytime.
+ /// A workaround for yshui/picom#301
+ xcb_xfixes_region_t damaged_region;
+ /// The region needs to painted on next paint.
+ region_t *damage;
+ /// The region damaged on the last paint.
+ region_t *damage_ring;
+ /// Number of damage regions we track
+ int ndamage;
+ /// Whether all windows are currently redirected.
+ bool redirected;
+ /// Pre-generated alpha pictures.
+ xcb_render_picture_t *alpha_picts;
+ /// Time of last fading. In milliseconds.
+ long long fade_time;
+ /// Time of last window animation step. In milliseconds.
+ long animation_time; // TODO(dccsillag) turn into `long long`, like fade_time
+ /// Head pointer of the error ignore linked list.
+ ignore_t *ignore_head;
+ /// Pointer to the next member of tail element of the error
+ /// ignore linked list.
+ ignore_t **ignore_tail;
+ // Cached blur convolution kernels.
+ struct x_convolution_kernel **blur_kerns_cache;
+ /// If we should quit
+ bool quit:1;
+ // TODO(yshui) use separate flags for dfferent kinds of updates so we don't
+ // waste our time.
+ /// Whether there are pending updates, like window creation, etc.
+ bool pending_updates:1;
+
+ // === Expose event related ===
+ /// Pointer to an array of XRectangle-s of exposed region.
+ /// XXX why do we need this array?
+ rect_t *expose_rects;
+ /// Number of XRectangle-s in expose_rects.
+ int size_expose;
+ /// Index of the next free slot in expose_rects.
+ int n_expose;
+
+ // === Window related ===
+ /// A hash table of all windows.
+ struct win *windows;
+ /// Windows in their stacking order
+ struct list_node window_stack;
+ /// Pointer to win of current active window. Used by
+ /// EWMH _NET_ACTIVE_WINDOW focus detection. In theory,
+ /// it's more reliable to store the window ID directly here, just in
+ /// case the WM does something extraordinary, but caching the pointer
+ /// means another layer of complexity.
+ struct managed_win *active_win;
+ /// Window ID of leader window of currently active window. Used for
+ /// subsidiary window detection.
+ xcb_window_t active_leader;
+
+ // === Shadow/dimming related ===
+ /// 1x1 black Picture.
+ xcb_render_picture_t black_picture;
+ /// 1x1 Picture of the shadow color.
+ xcb_render_picture_t cshadow_picture;
+ /// 1x1 white Picture.
+ xcb_render_picture_t white_picture;
+ /// Gaussian map of shadow.
+ struct conv *gaussian_map;
+ // for shadow precomputation
+ /// A region in which shadow is not painted on.
+ region_t shadow_exclude_reg;
+
+ // === Software-optimization-related ===
+ /// Nanosecond offset of the first painting.
+ long paint_tm_offset;
+
+#ifdef CONFIG_VSYNC_DRM
+ // === DRM VSync related ===
+ /// File descriptor of DRI device file. Used for DRM VSync.
+ int drm_fd;
+#endif
+
+ // === X extension related ===
+ /// Event base number for X Fixes extension.
+ int xfixes_event;
+ /// Error base number for X Fixes extension.
+ int xfixes_error;
+ /// Event base number for X Damage extension.
+ int damage_event;
+ /// Error base number for X Damage extension.
+ int damage_error;
+ /// Event base number for X Render extension.
+ int render_event;
+ /// Error base number for X Render extension.
+ int render_error;
+ /// Event base number for X Composite extension.
+ int composite_event;
+ /// Error base number for X Composite extension.
+ int composite_error;
+ /// Major opcode for X Composite extension.
+ int composite_opcode;
+ /// Whether X Shape extension exists.
+ bool shape_exists;
+ /// Event base number for X Shape extension.
+ int shape_event;
+ /// Error base number for X Shape extension.
+ int shape_error;
+ /// Whether X RandR extension exists.
+ bool randr_exists;
+ /// Event base number for X RandR extension.
+ int randr_event;
+ /// Error base number for X RandR extension.
+ int randr_error;
+ /// Whether X Present extension exists.
+ bool present_exists;
+ /// Whether X GLX extension exists.
+ bool glx_exists;
+ /// Event base number for X GLX extension.
+ int glx_event;
+ /// Error base number for X GLX extension.
+ int glx_error;
+ /// Whether X Xinerama extension exists.
+ bool xinerama_exists;
+ /// Xinerama screen regions.
+ region_t *xinerama_scr_regs;
+ /// Number of Xinerama screens.
+ int xinerama_nscrs;
+ /// Whether X Sync extension exists.
+ bool xsync_exists;
+ /// Event base number for X Sync extension.
+ int xsync_event;
+ /// Error base number for X Sync extension.
+ int xsync_error;
+ /// Whether X Render convolution filter exists.
+ bool xrfilter_convolution_exists;
+
+ // === Atoms ===
+ struct atom *atoms;
+ /// Array of atoms of all possible window types.
+ xcb_atom_t atoms_wintypes[NUM_WINTYPES];
+ /// Linked list of additional atoms to track.
+ latom_t *track_atom_lst;
+
+#ifdef CONFIG_DBUS
+ // === DBus related ===
+ void *dbus_data;
+#endif
+
+ int (*vsync_wait)(session_t *);
+} session_t;
+
+/// Enumeration for window event hints.
+typedef enum { WIN_EVMODE_UNKNOWN, WIN_EVMODE_FRAME, WIN_EVMODE_CLIENT } win_evmode_t;
+
+extern const char *const WINTYPES[NUM_WINTYPES];
+extern session_t *ps_g;
+
+void ev_xcb_error(session_t *ps, xcb_generic_error_t *err);
+
+// === Functions ===
+
+/**
+ * Subtracting two struct timespec values.
+ *
+ * Taken from glibc manual.
+ *
+ * Subtract the `struct timespec' values X and Y,
+ * storing the result in RESULT.
+ * Return 1 if the difference is negative, otherwise 0.
+ */
+static inline int
+timespec_subtract(struct timespec *result, struct timespec *x, struct timespec *y) {
+ /* Perform the carry for the later subtraction by updating y. */
+ if (x->tv_nsec < y->tv_nsec) {
+ long nsec = (y->tv_nsec - x->tv_nsec) / NS_PER_SEC + 1;
+ y->tv_nsec -= NS_PER_SEC * nsec;
+ y->tv_sec += nsec;
+ }
+
+ if (x->tv_nsec - y->tv_nsec > NS_PER_SEC) {
+ long nsec = (x->tv_nsec - y->tv_nsec) / NS_PER_SEC;
+ y->tv_nsec += NS_PER_SEC * nsec;
+ y->tv_sec -= nsec;
+ }
+
+ /* Compute the time remaining to wait.
+ tv_nsec is certainly positive. */
+ result->tv_sec = x->tv_sec - y->tv_sec;
+ result->tv_nsec = x->tv_nsec - y->tv_nsec;
+
+ /* Return 1 if result is negative. */
+ return x->tv_sec < y->tv_sec;
+}
+
+/**
+ * Get current time in struct timeval.
+ */
+static inline struct timeval get_time_timeval(void) {
+ struct timeval tv = {0, 0};
+
+ gettimeofday(&tv, NULL);
+
+ // Return a time of all 0 if the call fails
+ return tv;
+}
+
+/**
+ * Get current time in struct timespec.
+ *
+ * Note its starting time is unspecified.
+ */
+static inline struct timespec get_time_timespec(void) {
+ struct timespec tm = {0, 0};
+
+ clock_gettime(CLOCK_MONOTONIC, &tm);
+
+ // Return a time of all 0 if the call fails
+ return tm;
+}
+
+/**
+ * Return the painting target window.
+ */
+static inline xcb_window_t get_tgt_window(session_t *ps) {
+ return ps->overlay != XCB_NONE ? ps->overlay : ps->root;
+}
+
+/**
+ * Check if current backend uses GLX.
+ */
+static inline bool bkend_use_glx(session_t *ps) {
+ return BKEND_GLX == ps->o.backend || BKEND_XR_GLX_HYBRID == ps->o.backend;
+}
+
+static void set_ignore(session_t *ps, unsigned long sequence) {
+ if (ps->o.show_all_xerrors)
+ return;
+
+ auto i = cmalloc(ignore_t);
+ if (!i)
+ return;
+
+ i->sequence = sequence;
+ i->next = 0;
+ *ps->ignore_tail = i;
+ ps->ignore_tail = &i->next;
+}
+
+/**
+ * Ignore X errors caused by given X request.
+ */
+static inline void set_ignore_cookie(session_t *ps, xcb_void_cookie_t cookie) {
+ set_ignore(ps, cookie.sequence);
+}
+
+/**
+ * Determine if a window has a specific property.
+ *
+ * @param ps current session
+ * @param w window to check
+ * @param atom atom of property to check
+ * @return true if it has the attribute, false otherwise
+ */
+static inline bool wid_has_prop(const session_t *ps, xcb_window_t w, xcb_atom_t atom) {
+ auto r = xcb_get_property_reply(
+ ps->c, xcb_get_property(ps->c, 0, w, atom, XCB_GET_PROPERTY_TYPE_ANY, 0, 0), NULL);
+ if (!r) {
+ return false;
+ }
+
+ auto rtype = r->type;
+ free(r);
+
+ if (rtype != XCB_NONE) {
+ return true;
+ }
+ return false;
+}
+
+void force_repaint(session_t *ps);
+
+/** @name DBus handling
+ */
+///@{
+#ifdef CONFIG_DBUS
+/** @name DBus hooks
+ */
+///@{
+void opts_set_no_fading_openclose(session_t *ps, bool newval);
+//!@}
+#endif
+
+/**
+ * Set a bool array of all wintypes to true.
+ */
+static inline void wintype_arr_enable(bool arr[]) {
+ wintype_t i;
+
+ for (i = 0; i < NUM_WINTYPES; ++i) {
+ arr[i] = true;
+ }
+}
diff --git a/dwm/picom/src/compiler.h b/dwm/picom/src/compiler.h
new file mode 100644
index 0000000..f146bd2
--- /dev/null
+++ b/dwm/picom/src/compiler.h
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) 2018 Yuxuan Shui
+#pragma once
+
+#ifdef HAS_STDC_PREDEF_H
+#include
+#endif
+
+// clang-format off
+#define auto __auto_type
+#define likely(x) __builtin_expect(!!(x), 1)
+#define unlikely(x) __builtin_expect(!!(x), 0)
+#define likely_if(x) if (likely(x))
+#define unlikely_if(x) if (unlikely(x))
+
+#ifndef __has_attribute
+# if __GNUC__ >= 4
+# define __has_attribute(x) 1
+# else
+# define __has_attribute(x) 0
+# endif
+#endif
+
+#if __has_attribute(const)
+# define attr_const __attribute__((const))
+#else
+# define attr_const
+#endif
+
+#if __has_attribute(format)
+# define attr_printf(a, b) __attribute__((format(printf, a, b)))
+#else
+# define attr_printf(a, b)
+#endif
+
+#if __has_attribute(pure)
+# define attr_pure __attribute__((pure))
+#else
+# define attr_pure
+#endif
+
+#if __has_attribute(unused)
+# define attr_unused __attribute__((unused))
+#else
+# define attr_unused
+#endif
+
+#if __has_attribute(warn_unused_result)
+# define attr_warn_unused_result __attribute__((warn_unused_result))
+#else
+# define attr_warn_unused_result
+#endif
+// An alias for conveninence
+#define must_use attr_warn_unused_result
+
+#if __has_attribute(nonnull)
+# define attr_nonnull(...) __attribute__((nonnull(__VA_ARGS__)))
+# define attr_nonnull_all __attribute__((nonnull))
+#else
+# define attr_nonnull(...)
+# define attr_nonnull_all
+#endif
+
+#if __has_attribute(returns_nonnull)
+# define attr_ret_nonnull __attribute__((returns_nonnull))
+#else
+# define attr_ret_nonnull
+#endif
+
+#if __has_attribute(deprecated)
+# define attr_deprecated __attribute__((deprecated))
+#else
+# define attr_deprecated
+#endif
+
+#if __has_attribute(malloc)
+# define attr_malloc __attribute__((malloc))
+#else
+# define attr_malloc
+#endif
+
+#if __has_attribute(fallthrough)
+# define fallthrough() __attribute__((fallthrough))
+#else
+# define fallthrough()
+#endif
+
+#if __STDC_VERSION__ >= 201112L
+# define attr_noret _Noreturn
+#else
+# if __has_attribute(noreturn)
+# define attr_noret __attribute__((noreturn))
+# else
+# define attr_noret
+# endif
+#endif
+
+#if defined(__GNUC__) || defined(__clang__)
+# define unreachable __builtin_unreachable()
+#else
+# define unreachable do {} while(0)
+#endif
+
+#ifndef __has_include
+# define __has_include(x) 0
+#endif
+
+#if !defined(__STDC_NO_THREADS__) && __has_include()
+# include
+#elif __STDC_VERSION__ >= 201112L
+# define thread_local _Thread_local
+#elif defined(__GNUC__) || defined(__clang__)
+# define thread_local __thread
+#else
+# define thread_local _Pragma("GCC error \"No thread local storage support\"") __error__
+#endif
+// clang-format on
+
+typedef unsigned long ulong;
+typedef unsigned int uint;
+
+static inline int attr_const popcntul(unsigned long a) {
+ return __builtin_popcountl(a);
+}
diff --git a/dwm/picom/src/config.c b/dwm/picom/src/config.c
new file mode 100644
index 0000000..5b814cc
--- /dev/null
+++ b/dwm/picom/src/config.c
@@ -0,0 +1,651 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2011-2013, Christopher Jeffrey
+// Copyright (c) 2013 Richard Grenville
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include // for xcb_render_fixed_t, XXX
+
+#include "c2.h"
+#include "common.h"
+#include "compiler.h"
+#include "kernel.h"
+#include "log.h"
+#include "region.h"
+#include "string_utils.h"
+#include "types.h"
+#include "utils.h"
+#include "win.h"
+
+#include "config.h"
+
+/**
+ * Parse a long number.
+ */
+bool parse_long(const char *s, long *dest) {
+ const char *endptr = NULL;
+ long val = strtol(s, (char **)&endptr, 0);
+ if (!endptr || endptr == s) {
+ log_error("Invalid number: %s", s);
+ return false;
+ }
+ while (isspace((unsigned char)*endptr))
+ ++endptr;
+ if (*endptr) {
+ log_error("Trailing characters: %s", s);
+ return false;
+ }
+ *dest = val;
+ return true;
+}
+
+/**
+ * Parse an int number.
+ */
+bool parse_int(const char *s, int *dest) {
+ long val;
+ if (!parse_long(s, &val)) {
+ return false;
+ }
+ if (val > INT_MAX || val < INT_MIN) {
+ log_error("Number exceeded int limits: %ld", val);
+ return false;
+ }
+ *dest = (int)val;
+ return true;
+}
+
+/**
+ * Parse a floating-point number in from a string,
+ * also strips the trailing space and comma after the number.
+ *
+ * @param[in] src string to parse
+ * @param[out] dest return the number parsed from the string
+ * @return pointer to the last character parsed
+ */
+const char *parse_readnum(const char *src, double *dest) {
+ const char *pc = NULL;
+ double val = strtod_simple(src, &pc);
+ if (!pc || pc == src) {
+ log_error("No number found: %s", src);
+ return src;
+ }
+ while (*pc && (isspace((unsigned char)*pc) || *pc == ',')) {
+ ++pc;
+ }
+ *dest = val;
+ return pc;
+}
+
+enum blur_method parse_blur_method(const char *src) {
+ if (strcmp(src, "kernel") == 0) {
+ return BLUR_METHOD_KERNEL;
+ } else if (strcmp(src, "box") == 0) {
+ return BLUR_METHOD_BOX;
+ } else if (strcmp(src, "gaussian") == 0) {
+ return BLUR_METHOD_GAUSSIAN;
+ } else if (strcmp(src, "dual_kawase") == 0) {
+ return BLUR_METHOD_DUAL_KAWASE;
+ } else if (strcmp(src, "kawase") == 0) {
+ log_warn("Blur method 'kawase' has been renamed to 'dual_kawase'. "
+ "Interpreted as 'dual_kawase', but this will stop working "
+ "soon.");
+ return BLUR_METHOD_DUAL_KAWASE;
+ } else if (strcmp(src, "none") == 0) {
+ return BLUR_METHOD_NONE;
+ }
+ return BLUR_METHOD_INVALID;
+}
+
+/**
+ * Parse a matrix.
+ *
+ * @param[in] src the blur kernel string
+ * @param[out] endptr return where the end of kernel is in the string
+ * @param[out] hasneg whether the kernel has negative values
+ */
+conv *parse_blur_kern(const char *src, const char **endptr, bool *hasneg) {
+ int width = 0, height = 0;
+ *hasneg = false;
+
+ const char *pc = NULL;
+
+ // Get matrix width and height
+ double val = 0.0;
+ if (src == (pc = parse_readnum(src, &val)))
+ goto err1;
+ src = pc;
+ width = (int)val;
+ if (src == (pc = parse_readnum(src, &val)))
+ goto err1;
+ src = pc;
+ height = (int)val;
+
+ // Validate matrix width and height
+ if (width <= 0 || height <= 0) {
+ log_error("Blue kernel width/height can't be negative.");
+ goto err1;
+ }
+ if (!(width % 2 && height % 2)) {
+ log_error("Blur kernel width/height must be odd.");
+ goto err1;
+ }
+ if (width > 16 || height > 16)
+ log_warn("Blur kernel width/height too large, may slow down"
+ "rendering, and/or consume lots of memory");
+
+ // Allocate memory
+ conv *matrix = cvalloc(sizeof(conv) + (size_t)(width * height) * sizeof(double));
+
+ // Read elements
+ int skip = height / 2 * width + width / 2;
+ for (int i = 0; i < width * height; ++i) {
+ // Ignore the center element
+ if (i == skip) {
+ matrix->data[i] = 1;
+ continue;
+ }
+ if (src == (pc = parse_readnum(src, &val))) {
+ goto err2;
+ }
+ src = pc;
+ if (val < 0) {
+ *hasneg = true;
+ }
+ matrix->data[i] = val;
+ }
+
+ // Detect trailing characters
+ for (; *pc && *pc != ';'; pc++) {
+ if (!isspace((unsigned char)*pc) && *pc != ',') {
+ // TODO(yshui) isspace is locale aware, be careful
+ log_error("Trailing characters in blur kernel string.");
+ goto err2;
+ }
+ }
+
+ // Jump over spaces after ';'
+ if (*pc == ';') {
+ pc++;
+ while (*pc && isspace((unsigned char)*pc)) {
+ ++pc;
+ }
+ }
+
+ // Require an end of string if endptr is not provided, otherwise
+ // copy end pointer to endptr
+ if (endptr) {
+ *endptr = pc;
+ } else if (*pc) {
+ log_error("Only one blur kernel expected.");
+ goto err2;
+ }
+
+ // Fill in width and height
+ matrix->w = width;
+ matrix->h = height;
+ return matrix;
+
+err2:
+ free(matrix);
+err1:
+ return NULL;
+}
+
+/**
+ * Parse a list of convolution kernels.
+ *
+ * @param[in] src string to parse
+ * @param[out] hasneg whether any of the kernels have negative values
+ * @return the kernels
+ */
+struct conv **parse_blur_kern_lst(const char *src, bool *hasneg, int *count) {
+ // TODO(yshui) just return a predefined kernels, not parse predefined strings...
+ static const struct {
+ const char *name;
+ const char *kern_str;
+ } CONV_KERN_PREDEF[] = {
+ {"3x3box", "3,3,1,1,1,1,1,1,1,1,"},
+ {"5x5box", "5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,"},
+ {"7x7box", "7,7,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,"
+ "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,"},
+ {"3x3gaussian", "3,3,0.243117,0.493069,0.243117,0.493069,0.493069,0.243117,0."
+ "493069,0.243117,"},
+ {"5x5gaussian", "5,5,0.003493,0.029143,0.059106,0.029143,0.003493,0.029143,0."
+ "243117,0.493069,0.243117,0.029143,0.059106,0.493069,0."
+ "493069,0.059106,0.029143,0.243117,0.493069,0.243117,0."
+ "029143,0.003493,0.029143,0.059106,0.029143,0.003493,"},
+ {"7x7gaussian", "7,7,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0."
+ "000003,0.000102,0.003493,0.029143,0.059106,0.029143,0."
+ "003493,0.000102,0.000849,0.029143,0.243117,0.493069,0."
+ "243117,0.029143,0.000849,0.001723,0.059106,0.493069,0."
+ "493069,0.059106,0.001723,0.000849,0.029143,0.243117,0."
+ "493069,0.243117,0.029143,0.000849,0.000102,0.003493,0."
+ "029143,0.059106,0.029143,0.003493,0.000102,0.000003,0."
+ "000102,0.000849,0.001723,0.000849,0.000102,0.000003,"},
+ {"9x9gaussian",
+ "9,9,0.000000,0.000000,0.000001,0.000006,0.000012,0.000006,0.000001,0."
+ "000000,0.000000,0.000000,0.000003,0.000102,0.000849,0.001723,0.000849,0."
+ "000102,0.000003,0.000000,0.000001,0.000102,0.003493,0.029143,0.059106,0."
+ "029143,0.003493,0.000102,0.000001,0.000006,0.000849,0.029143,0.243117,0."
+ "493069,0.243117,0.029143,0.000849,0.000006,0.000012,0.001723,0.059106,0."
+ "493069,0.493069,0.059106,0.001723,0.000012,0.000006,0.000849,0.029143,0."
+ "243117,0.493069,0.243117,0.029143,0.000849,0.000006,0.000001,0.000102,0."
+ "003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000001,0.000000,0."
+ "000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000000,0."
+ "000000,0.000000,0.000001,0.000006,0.000012,0.000006,0.000001,0.000000,0."
+ "000000,"},
+ {"11x11gaussian",
+ "11,11,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0."
+ "000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000001,0."
+ "000006,0.000012,0.000006,0.000001,0.000000,0.000000,0.000000,0.000000,0."
+ "000000,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0."
+ "000000,0.000000,0.000000,0.000001,0.000102,0.003493,0.029143,0.059106,0."
+ "029143,0.003493,0.000102,0.000001,0.000000,0.000000,0.000006,0.000849,0."
+ "029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000006,0.000000,0."
+ "000000,0.000012,0.001723,0.059106,0.493069,0.493069,0.059106,0.001723,0."
+ "000012,0.000000,0.000000,0.000006,0.000849,0.029143,0.243117,0.493069,0."
+ "243117,0.029143,0.000849,0.000006,0.000000,0.000000,0.000001,0.000102,0."
+ "003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000001,0.000000,0."
+ "000000,0.000000,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0."
+ "000003,0.000000,0.000000,0.000000,0.000000,0.000000,0.000001,0.000006,0."
+ "000012,0.000006,0.000001,0.000000,0.000000,0.000000,0.000000,0.000000,0."
+ "000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0."
+ "000000,"},
+ };
+
+ *count = 0;
+ *hasneg = false;
+ for (unsigned int i = 0;
+ i < sizeof(CONV_KERN_PREDEF) / sizeof(CONV_KERN_PREDEF[0]); ++i) {
+ if (!strcmp(CONV_KERN_PREDEF[i].name, src))
+ return parse_blur_kern_lst(CONV_KERN_PREDEF[i].kern_str, hasneg, count);
+ }
+
+ int nkernels = 1;
+ for (int i = 0; src[i]; i++) {
+ if (src[i] == ';') {
+ nkernels++;
+ }
+ }
+
+ struct conv **ret = ccalloc(nkernels, struct conv *);
+
+ int i = 0;
+ const char *pc = src;
+
+ // Continue parsing until the end of source string
+ i = 0;
+ while (pc && *pc) {
+ bool tmp_hasneg;
+ assert(i < nkernels);
+ ret[i] = parse_blur_kern(pc, &pc, &tmp_hasneg);
+ if (!ret[i]) {
+ for (int j = 0; j < i; j++) {
+ free(ret[j]);
+ }
+ free(ret);
+ return NULL;
+ }
+ i++;
+ *hasneg |= tmp_hasneg;
+ }
+
+ if (i > 1) {
+ log_warn("You are seeing this message because you are using "
+ "multipass blur. Please report an issue to us so we know "
+ "multipass blur is actually been used. Otherwise it might be "
+ "removed in future releases");
+ }
+
+ *count = i;
+
+ return ret;
+}
+
+/**
+ * Parse a X geometry.
+ *
+ * ps->root_width and ps->root_height must be valid
+ */
+bool parse_geometry(session_t *ps, const char *src, region_t *dest) {
+ pixman_region32_clear(dest);
+ if (!src) {
+ return true;
+ }
+ if (!ps->root_width || !ps->root_height) {
+ return true;
+ }
+
+ long x = 0, y = 0;
+ long width = ps->root_width, height = ps->root_height;
+ long val = 0L;
+ char *endptr = NULL;
+
+ src = skip_space(src);
+ if (!*src) {
+ goto parse_geometry_end;
+ }
+
+ // Parse width
+ // Must be base 10, because "0x0..." may appear
+ if (*src != '+' && *src != '-') {
+ val = strtol(src, &endptr, 10);
+ assert(endptr);
+ if (src != endptr) {
+ if (val < 0) {
+ log_error("Invalid width: %s", src);
+ return false;
+ }
+ width = val;
+ src = endptr;
+ }
+ src = skip_space(src);
+ }
+
+ // Parse height
+ if (*src == 'x') {
+ ++src;
+ val = strtol(src, &endptr, 10);
+ assert(endptr);
+ if (src != endptr) {
+ if (val < 0) {
+ log_error("Invalid height: %s", src);
+ return false;
+ }
+ height = val;
+ src = endptr;
+ }
+ src = skip_space(src);
+ }
+
+ // Parse x
+ if (*src == '+' || *src == '-') {
+ val = strtol(src, &endptr, 10);
+ if (endptr && src != endptr) {
+ x = val;
+ if (*src == '-') {
+ x += ps->root_width - width;
+ }
+ src = endptr;
+ }
+ src = skip_space(src);
+ }
+
+ // Parse y
+ if (*src == '+' || *src == '-') {
+ val = strtol(src, &endptr, 10);
+ if (endptr && src != endptr) {
+ y = val;
+ if (*src == '-') {
+ y += ps->root_height - height;
+ }
+ src = endptr;
+ }
+ src = skip_space(src);
+ }
+
+ if (*src) {
+ log_error("Trailing characters: %s", src);
+ return false;
+ }
+
+parse_geometry_end:
+ if (x < INT_MIN || x > INT_MAX || y < INT_MIN || y > INT_MAX) {
+ log_error("Geometry coordinates exceeded limits: %s", src);
+ return false;
+ }
+ if (width > UINT_MAX || height > UINT_MAX) {
+ // less than 0 is checked for earlier
+ log_error("Geometry size exceeded limits: %s", src);
+ return false;
+ }
+ pixman_region32_union_rect(dest, dest, (int)x, (int)y, (uint)width, (uint)height);
+ return true;
+}
+
+/**
+ * Parse a list of opacity rules.
+ */
+bool parse_rule_opacity(c2_lptr_t **res, const char *src) {
+ // Find opacity value
+ char *endptr = NULL;
+ long val = strtol(src, &endptr, 0);
+ if (!endptr || endptr == src) {
+ log_error("No opacity specified: %s", src);
+ return false;
+ }
+ if (val > 100 || val < 0) {
+ log_error("Opacity %ld invalid: %s", val, src);
+ return false;
+ }
+
+ // Skip over spaces
+ while (*endptr && isspace((unsigned char)*endptr))
+ ++endptr;
+ if (':' != *endptr) {
+ log_error("Opacity terminator not found: %s", src);
+ return false;
+ }
+ ++endptr;
+
+ // Parse pattern
+ // I hope 1-100 is acceptable for (void *)
+ return c2_parse(res, endptr, (void *)val);
+}
+
+/**
+ * Add a pattern to a condition linked list.
+ */
+bool condlst_add(c2_lptr_t **pcondlst, const char *pattern) {
+ if (!pattern)
+ return false;
+
+ if (!c2_parse(pcondlst, pattern, NULL))
+ exit(1);
+
+ return true;
+}
+
+void set_default_winopts(options_t *opt, win_option_mask_t *mask, bool shadow_enable,
+ bool fading_enable, bool blur_enable) {
+ // Apply default wintype options.
+ if (!mask[WINTYPE_DESKTOP].shadow) {
+ // Desktop windows are always drawn without shadow by default.
+ mask[WINTYPE_DESKTOP].shadow = true;
+ opt->wintype_option[WINTYPE_DESKTOP].shadow = false;
+ }
+
+ // Focused/unfocused state only apply to a few window types, all other windows
+ // are always considered focused.
+ const wintype_t nofocus_type[] = {WINTYPE_UNKNOWN, WINTYPE_NORMAL, WINTYPE_UTILITY};
+ for (unsigned long i = 0; i < ARR_SIZE(nofocus_type); i++) {
+ if (!mask[nofocus_type[i]].focus) {
+ mask[nofocus_type[i]].focus = true;
+ opt->wintype_option[nofocus_type[i]].focus = false;
+ }
+ }
+ for (unsigned long i = 0; i < NUM_WINTYPES; i++) {
+ if (!mask[i].shadow) {
+ mask[i].shadow = true;
+ opt->wintype_option[i].shadow = shadow_enable;
+ }
+ if (!mask[i].fade) {
+ mask[i].fade = true;
+ opt->wintype_option[i].fade = fading_enable;
+ }
+ if (!mask[i].focus) {
+ mask[i].focus = true;
+ opt->wintype_option[i].focus = true;
+ }
+ if (!mask[i].blur_background) {
+ mask[i].blur_background = true;
+ opt->wintype_option[i].blur_background = blur_enable;
+ }
+ if (!mask[i].full_shadow) {
+ mask[i].full_shadow = true;
+ opt->wintype_option[i].full_shadow = false;
+ }
+ if (!mask[i].redir_ignore) {
+ mask[i].redir_ignore = true;
+ opt->wintype_option[i].redir_ignore = false;
+ }
+ if (!mask[i].opacity) {
+ mask[i].opacity = true;
+ // Opacity is not set to a concrete number here because the
+ // opacity logic is complicated, and needs an "unset" state
+ opt->wintype_option[i].opacity = NAN;
+ }
+ if (!mask[i].animation) {
+ mask[i].animation = OPEN_WINDOW_ANIMATION_INVALID;
+ opt->wintype_option[i].animation = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+ if (!mask[i].animation_unmap) {
+ mask[i].animation_unmap = OPEN_WINDOW_ANIMATION_INVALID;
+ opt->wintype_option[i].animation_unmap = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+ if (!mask[i].animation_workspace_in) {
+ mask[i].animation_workspace_in = OPEN_WINDOW_ANIMATION_INVALID;
+ opt->wintype_option[i].animation_workspace_in = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+ if (!mask[i].animation_workspace_out) {
+ mask[i].animation_workspace_out = OPEN_WINDOW_ANIMATION_INVALID;
+ opt->wintype_option[i].animation_workspace_out = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+ if (!mask[i].clip_shadow_above) {
+ mask[i].clip_shadow_above = true;
+ opt->wintype_option[i].clip_shadow_above = false;
+ }
+ }
+}
+
+enum open_window_animation parse_open_window_animation(const char *src) {
+ if (strcmp(src, "none") == 0) {
+ return OPEN_WINDOW_ANIMATION_NONE;
+ }else if (strcmp(src, "auto") == 0) {
+ return OPEN_WINDOW_ANIMATION_AUTO;
+ } else if (strcmp(src, "fly-in") == 0) {
+ return OPEN_WINDOW_ANIMATION_FLYIN;
+ } else if (strcmp(src, "zoom") == 0) {
+ return OPEN_WINDOW_ANIMATION_ZOOM;
+ } else if (strcmp(src, "squeeze") == 0) {
+ return OPEN_WINDOW_ANIMATION_SQUEEZE;
+ } else if (strcmp(src, "slide-up") == 0) {
+ return OPEN_WINDOW_ANIMATION_SLIDE_UP;
+ } else if (strcmp(src, "slide-down") == 0) {
+ return OPEN_WINDOW_ANIMATION_SLIDE_DOWN;
+ } else if (strcmp(src, "slide-left") == 0) {
+ return OPEN_WINDOW_ANIMATION_SLIDE_LEFT;
+ } else if (strcmp(src, "slide-right") == 0) {
+ return OPEN_WINDOW_ANIMATION_SLIDE_RIGHT;
+ }
+ return OPEN_WINDOW_ANIMATION_INVALID;
+}
+
+char *parse_config(options_t *opt, const char *config_file, bool *shadow_enable,
+ bool *fading_enable, bool *hasneg, win_option_mask_t *winopt_mask) {
+ // clang-format off
+ *opt = (struct options){
+ .backend = BKEND_XRENDER,
+ .glx_no_stencil = false,
+ .mark_wmwin_focused = false,
+ .mark_ovredir_focused = false,
+ .detect_rounded_corners = false,
+ .resize_damage = 0,
+ .unredir_if_possible = false,
+ .unredir_if_possible_blacklist = NULL,
+ .unredir_if_possible_delay = 0,
+ .redirected_force = UNSET,
+ .stoppaint_force = UNSET,
+ .dbus = false,
+ .benchmark = 0,
+ .benchmark_wid = XCB_NONE,
+ .logpath = NULL,
+
+ .use_damage = true,
+
+ .shadow_red = 0.0,
+ .shadow_green = 0.0,
+ .shadow_blue = 0.0,
+ .shadow_radius = 18,
+ .shadow_offset_x = -15,
+ .shadow_offset_y = -15,
+ .shadow_opacity = .75,
+ .shadow_blacklist = NULL,
+ .shadow_ignore_shaped = false,
+ .xinerama_shadow_crop = false,
+ .shadow_clip_list = NULL,
+
+ .corner_radius = 0,
+
+ .fade_in_step = 0.028,
+ .fade_out_step = 0.03,
+ .fade_delta = 10,
+ .no_fading_openclose = false,
+ .no_fading_destroyed_argb = false,
+ .fade_blacklist = NULL,
+
+ .animations = false,
+ .animation_for_open_window = OPEN_WINDOW_ANIMATION_NONE,
+ .animation_for_transient_window = OPEN_WINDOW_ANIMATION_NONE,
+ .animation_for_unmap_window = OPEN_WINDOW_ANIMATION_AUTO,
+ .animation_for_workspace_switch_in = OPEN_WINDOW_ANIMATION_AUTO,
+ .animation_for_workspace_switch_out = OPEN_WINDOW_ANIMATION_AUTO,
+ .animation_stiffness = 200.0,
+ .animation_window_mass = 1.0,
+ .animation_dampening = 25,
+ .animation_delta = 10,
+ .animation_force_steps = false,
+ .animation_clamping = true,
+ .animation_blacklist = NULL,
+
+ .inactive_opacity = 1.0,
+ .inactive_opacity_override = false,
+ .active_opacity = 1.0,
+ .frame_opacity = 1.0,
+ .detect_client_opacity = false,
+
+ .blur_method = BLUR_METHOD_NONE,
+ .blur_radius = 3,
+ .blur_deviation = 0.84089642,
+ .blur_strength = 5,
+ .blur_background_frame = false,
+ .blur_background_fixed = false,
+ .blur_background_blacklist = NULL,
+ .blur_kerns = NULL,
+ .blur_kernel_count = 0,
+ .inactive_dim = 0.0,
+ .inactive_dim_fixed = false,
+ .invert_color_list = NULL,
+ .opacity_rules = NULL,
+ .max_brightness = 1.0,
+
+ .use_ewmh_active_win = false,
+ .focus_blacklist = NULL,
+ .detect_transient = false,
+ .detect_client_leader = false,
+ .no_ewmh_fullscreen = false,
+
+ .track_leader = false,
+
+ .rounded_corners_blacklist = NULL
+ };
+ // clang-format on
+
+ char *ret = NULL;
+#ifdef CONFIG_LIBCONFIG
+ ret = parse_config_libconfig(opt, config_file, shadow_enable, fading_enable,
+ hasneg, winopt_mask);
+#else
+ (void)config_file;
+ (void)shadow_enable;
+ (void)fading_enable;
+ (void)hasneg;
+ (void)winopt_mask;
+#endif
+ return ret;
+}
diff --git a/dwm/picom/src/config.h b/dwm/picom/src/config.h
new file mode 100644
index 0000000..8d604f2
--- /dev/null
+++ b/dwm/picom/src/config.h
@@ -0,0 +1,378 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2011-2013, Christopher Jeffrey
+// Copyright (c) 2013 Richard Grenville
+// Copyright (c) 2018 Yuxuan Shui
+#pragma once
+
+/// Common functions and definitions for configuration parsing
+/// Used for command line arguments and config files
+
+#include
+#include
+#include
+#include
+#include // for xcb_render_fixed_t, XXX
+#include
+#include
+
+#ifdef CONFIG_LIBCONFIG
+#include
+#endif
+
+#include "compiler.h"
+#include "kernel.h"
+#include "log.h"
+#include "region.h"
+#include "types.h"
+#include "win_defs.h"
+
+typedef struct session session_t;
+
+/// @brief Possible backends
+enum backend {
+ BKEND_XRENDER,
+ BKEND_GLX,
+ BKEND_XR_GLX_HYBRID,
+ BKEND_DUMMY,
+ NUM_BKEND,
+};
+
+enum open_window_animation {
+ OPEN_WINDOW_ANIMATION_NONE = 0,
+ OPEN_WINDOW_ANIMATION_AUTO,
+ OPEN_WINDOW_ANIMATION_FLYIN,
+ OPEN_WINDOW_ANIMATION_ZOOM,
+ OPEN_WINDOW_ANIMATION_SQUEEZE,
+ OPEN_WINDOW_ANIMATION_SLIDE_UP,
+ OPEN_WINDOW_ANIMATION_SLIDE_DOWN,
+ OPEN_WINDOW_ANIMATION_SLIDE_LEFT,
+ OPEN_WINDOW_ANIMATION_SLIDE_RIGHT,
+ OPEN_WINDOW_ANIMATION_SLIDE_IN,
+ OPEN_WINDOW_ANIMATION_SLIDE_OUT,
+ OPEN_WINDOW_ANIMATION_INVALID,
+};
+
+typedef struct win_option_mask {
+ bool shadow : 1;
+ bool fade : 1;
+ bool focus : 1;
+ bool blur_background : 1;
+ bool full_shadow : 1;
+ bool redir_ignore : 1;
+ bool opacity : 1;
+ bool clip_shadow_above : 1;
+ enum open_window_animation animation;
+ enum open_window_animation animation_unmap;
+ enum open_window_animation animation_workspace_in;
+ enum open_window_animation animation_workspace_out;
+} win_option_mask_t;
+
+typedef struct win_option {
+ bool shadow;
+ bool fade;
+ bool focus;
+ bool blur_background;
+ bool full_shadow;
+ bool redir_ignore;
+ double opacity;
+ bool clip_shadow_above;
+ enum open_window_animation animation;
+ enum open_window_animation animation_unmap;
+ enum open_window_animation animation_workspace_in;
+ enum open_window_animation animation_workspace_out;
+} win_option_t;
+
+enum blur_method {
+ BLUR_METHOD_NONE = 0,
+ BLUR_METHOD_KERNEL,
+ BLUR_METHOD_BOX,
+ BLUR_METHOD_GAUSSIAN,
+ BLUR_METHOD_DUAL_KAWASE,
+ BLUR_METHOD_INVALID,
+};
+
+typedef struct _c2_lptr c2_lptr_t;
+
+/// Structure representing all options.
+typedef struct options {
+ // === Debugging ===
+ bool monitor_repaint;
+ bool print_diagnostics;
+ /// Render to a separate window instead of taking over the screen
+ bool debug_mode;
+ // === General ===
+ /// Use the experimental new backends?
+ bool experimental_backends;
+ /// Path to write PID to.
+ char *write_pid_path;
+ /// The backend in use.
+ enum backend backend;
+ /// Whether to sync X drawing with X Sync fence to avoid certain delay
+ /// issues with GLX backend.
+ bool xrender_sync_fence;
+ /// Whether to avoid using stencil buffer under GLX backend. Might be
+ /// unsafe.
+ bool glx_no_stencil;
+ /// Whether to avoid rebinding pixmap on window damage.
+ bool glx_no_rebind_pixmap;
+ /// Custom fragment shader for painting windows, as a string.
+ char *glx_fshader_win_str;
+ /// Whether to detect rounded corners.
+ bool detect_rounded_corners;
+ /// Force painting of window content with blending.
+ bool force_win_blend;
+ /// Resize damage for a specific number of pixels.
+ int resize_damage;
+ /// Whether to unredirect all windows if a full-screen opaque window
+ /// is detected.
+ bool unredir_if_possible;
+ /// List of conditions of windows to ignore as a full-screen window
+ /// when determining if a window could be unredirected.
+ c2_lptr_t *unredir_if_possible_blacklist;
+ /// Delay before unredirecting screen, in milliseconds.
+ long unredir_if_possible_delay;
+ /// Forced redirection setting through D-Bus.
+ switch_t redirected_force;
+ /// Whether to stop painting. Controlled through D-Bus.
+ switch_t stoppaint_force;
+ /// Whether to enable D-Bus support.
+ bool dbus;
+ /// Path to log file.
+ char *logpath;
+ /// Number of cycles to paint in benchmark mode. 0 for disabled.
+ int benchmark;
+ /// Window to constantly repaint in benchmark mode. 0 for full-screen.
+ xcb_window_t benchmark_wid;
+ /// A list of conditions of windows not to paint.
+ c2_lptr_t *paint_blacklist;
+ /// Whether to show all X errors.
+ bool show_all_xerrors;
+ /// Whether to avoid acquiring X Selection.
+ bool no_x_selection;
+ /// Window type option override.
+ win_option_t wintype_option[NUM_WINTYPES];
+
+ // === VSync & software optimization ===
+ /// VSync method to use;
+ bool vsync;
+ /// Whether to use glFinish() instead of glFlush() for (possibly) better
+ /// VSync yet probably higher CPU usage.
+ bool vsync_use_glfinish;
+ /// Whether use damage information to help limit the area to paint
+ bool use_damage;
+
+ // === Shadow ===
+ /// Red, green and blue tone of the shadow.
+ double shadow_red, shadow_green, shadow_blue;
+ int shadow_radius;
+ int shadow_offset_x, shadow_offset_y;
+ double shadow_opacity;
+ /// argument string to shadow-exclude-reg option
+ char *shadow_exclude_reg_str;
+ /// Shadow blacklist. A linked list of conditions.
+ c2_lptr_t *shadow_blacklist;
+ /// Whether bounding-shaped window should be ignored.
+ bool shadow_ignore_shaped;
+ /// Whether to crop shadow to the very Xinerama screen.
+ bool xinerama_shadow_crop;
+ /// Don't draw shadow over these windows. A linked list of conditions.
+ c2_lptr_t *shadow_clip_list;
+
+ // === Fading ===
+ /// How much to fade in in a single fading step.
+ double fade_in_step;
+ /// How much to fade out in a single fading step.
+ double fade_out_step;
+ /// Fading time delta. In milliseconds.
+ int fade_delta;
+ /// Whether to disable fading on window open/close.
+ bool no_fading_openclose;
+ /// Whether to disable fading on ARGB managed destroyed windows.
+ bool no_fading_destroyed_argb;
+ /// Fading blacklist. A linked list of conditions.
+ c2_lptr_t *fade_blacklist;
+
+ // === Animations ===
+ /// Whether to do window animations
+ bool animations;
+ /// Which animation to run when opening a window
+ enum open_window_animation animation_for_open_window;
+ /// Which animation to run when opening a transient window
+ enum open_window_animation animation_for_transient_window;
+ /// Which animation to run when unmapping (e.g. minimizing) a window
+ enum open_window_animation animation_for_unmap_window;
+ /// Which animation to run when switching workspace
+ /// IMPORTANT: will only work if window manager updates
+ /// _NET_CURRENT_DESKTOP before doing the hide/show of windows
+ enum open_window_animation animation_for_workspace_switch_in;
+ enum open_window_animation animation_for_workspace_switch_out;
+ /// Spring stiffness for animation
+ double animation_stiffness;
+ /// Window mass for animation
+ double animation_window_mass;
+ /// Animation dampening
+ double animation_dampening;
+ /// Animation delta. In milliseconds.
+ double animation_delta;
+ /// Whether to force animations to not miss a beat
+ bool animation_force_steps;
+ /// Whether to clamp animations
+ bool animation_clamping;
+ /// Animation blacklist. A linked list of conditions.
+ c2_lptr_t *animation_blacklist;
+ /// TODO: open/close animations
+
+ // === Opacity ===
+ /// Default opacity for inactive windows.
+ /// 32-bit integer with the format of _NET_WM_WINDOW_OPACITY.
+ double inactive_opacity;
+ /// Default opacity for inactive windows.
+ double active_opacity;
+ /// Whether inactive_opacity overrides the opacity set by window
+ /// attributes.
+ bool inactive_opacity_override;
+ /// Frame opacity. Relative to window opacity, also affects shadow
+ /// opacity.
+ double frame_opacity;
+ /// Whether to detect _NET_WM_WINDOW_OPACITY on client windows. Used on window
+ /// managers that don't pass _NET_WM_WINDOW_OPACITY to frame windows.
+ bool detect_client_opacity;
+
+ // === Other window processing ===
+ /// Blur method for background of semi-transparent windows
+ enum blur_method blur_method;
+ // Size of the blur kernel
+ int blur_radius;
+ // Standard deviation for the gaussian blur
+ double blur_deviation;
+ // Strength of the dual_kawase blur
+ int blur_strength;
+ /// Whether to blur background when the window frame is not opaque.
+ /// Implies blur_background.
+ bool blur_background_frame;
+ /// Whether to use fixed blur strength instead of adjusting according
+ /// to window opacity.
+ bool blur_background_fixed;
+ /// Background blur blacklist. A linked list of conditions.
+ c2_lptr_t *blur_background_blacklist;
+ /// Blur convolution kernel.
+ struct conv **blur_kerns;
+ /// Number of convolution kernels
+ int blur_kernel_count;
+ /// How much to dim an inactive window. 0.0 - 1.0, 0 to disable.
+ double inactive_dim;
+ /// Whether to use fixed inactive dim opacity, instead of deciding
+ /// based on window opacity.
+ bool inactive_dim_fixed;
+ /// Conditions of windows to have inverted colors.
+ c2_lptr_t *invert_color_list;
+ /// Rules to change window opacity.
+ c2_lptr_t *opacity_rules;
+ /// Limit window brightness
+ double max_brightness;
+ // Radius of rounded window corners
+ int corner_radius;
+ /// Rounded corners blacklist. A linked list of conditions.
+ c2_lptr_t *rounded_corners_blacklist;
+
+ // === Focus related ===
+ /// Whether to try to detect WM windows and mark them as focused.
+ bool mark_wmwin_focused;
+ /// Whether to mark override-redirect windows as focused.
+ bool mark_ovredir_focused;
+ /// Whether to use EWMH _NET_ACTIVE_WINDOW to find active window.
+ bool use_ewmh_active_win;
+ /// A list of windows always to be considered focused.
+ c2_lptr_t *focus_blacklist;
+ /// Whether to do window grouping with WM_TRANSIENT_FOR.
+ bool detect_transient;
+ /// Whether to do window grouping with WM_CLIENT_LEADER.
+ bool detect_client_leader;
+
+ // === Calculated ===
+ /// Whether we need to track window leaders.
+ bool track_leader;
+
+ // Don't use EWMH to detect fullscreen applications
+ bool no_ewmh_fullscreen;
+
+ // Make transparent windows clip other windows, instead of blending on top of
+ // them
+ bool transparent_clipping;
+} options_t;
+
+extern const char *const BACKEND_STRS[NUM_BKEND + 1];
+
+bool must_use parse_long(const char *, long *);
+bool must_use parse_int(const char *, int *);
+struct conv **must_use parse_blur_kern_lst(const char *, bool *hasneg, int *count);
+bool must_use parse_geometry(session_t *, const char *, region_t *);
+bool must_use parse_rule_opacity(c2_lptr_t **, const char *);
+enum blur_method must_use parse_blur_method(const char *src);
+enum open_window_animation must_use parse_open_window_animation(const char *src);
+
+/**
+ * Add a pattern to a condition linked list.
+ */
+bool condlst_add(c2_lptr_t **, const char *);
+
+#ifdef CONFIG_LIBCONFIG
+/// Parse a configuration file
+/// Returns the actually config_file name used, allocated on heap
+/// Outputs:
+/// shadow_enable = whether shaodw is enabled globally
+/// fading_enable = whether fading is enabled globally
+/// win_option_mask = whether option overrides for specific window type is set for given
+/// options
+/// hasneg = whether the convolution kernel has negative values
+char *
+parse_config_libconfig(options_t *, const char *config_file, bool *shadow_enable,
+ bool *fading_enable, bool *hasneg, win_option_mask_t *winopt_mask);
+#endif
+
+void set_default_winopts(options_t *, win_option_mask_t *, bool shadow_enable,
+ bool fading_enable, bool blur_enable);
+/// Parse a configuration file is that is enabled, also initialize the winopt_mask with
+/// default values
+/// Outputs and returns:
+/// same as parse_config_libconfig
+char *parse_config(options_t *, const char *config_file, bool *shadow_enable,
+ bool *fading_enable, bool *hasneg, win_option_mask_t *winopt_mask);
+
+/**
+ * Parse a backend option argument.
+ */
+static inline attr_pure enum backend parse_backend(const char *str) {
+ for (enum backend i = 0; BACKEND_STRS[i]; ++i) {
+ if (!strcasecmp(str, BACKEND_STRS[i])) {
+ return i;
+ }
+ }
+ // Keep compatibility with an old revision containing a spelling mistake...
+ if (!strcasecmp(str, "xr_glx_hybird")) {
+ log_warn("backend xr_glx_hybird should be xr_glx_hybrid, the misspelt "
+ "version will be removed soon.");
+ return BKEND_XR_GLX_HYBRID;
+ }
+ // cju wants to use dashes
+ if (!strcasecmp(str, "xr-glx-hybrid")) {
+ log_warn("backend xr-glx-hybrid should be xr_glx_hybrid, the alternative "
+ "version will be removed soon.");
+ return BKEND_XR_GLX_HYBRID;
+ }
+ log_error("Invalid backend argument: %s", str);
+ return NUM_BKEND;
+}
+
+/**
+ * Parse a VSync option argument.
+ */
+static inline bool parse_vsync(const char *str) {
+ if (strcmp(str, "no") == 0 || strcmp(str, "none") == 0 ||
+ strcmp(str, "false") == 0 || strcmp(str, "nah") == 0) {
+ return false;
+ }
+ return true;
+}
+
+// vim: set noet sw=8 ts=8 :
diff --git a/dwm/picom/src/config_libconfig.c b/dwm/picom/src/config_libconfig.c
new file mode 100644
index 0000000..06f1ba4
--- /dev/null
+++ b/dwm/picom/src/config_libconfig.c
@@ -0,0 +1,767 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2012-2014 Richard Grenville
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+#include "common.h"
+#include "compiler.h"
+#include "config.h"
+#include "err.h"
+#include "log.h"
+#include "options.h"
+#include "string_utils.h"
+#include "utils.h"
+#include "win.h"
+
+#pragma GCC diagnostic error "-Wunused-parameter"
+
+/**
+ * Wrapper of libconfig's config_lookup_int.
+ *
+ * So it takes a pointer to bool.
+ */
+static inline int lcfg_lookup_bool(const config_t *config, const char *path, bool *value) {
+ int ival;
+
+ int ret = config_lookup_bool(config, path, &ival);
+ if (ret) {
+ *value = ival;
+ }
+
+ return ret;
+}
+
+const char *xdg_config_home(void) {
+ char *xdgh = getenv("XDG_CONFIG_HOME");
+ char *home = getenv("HOME");
+ const char *default_dir = "/.config";
+
+ if (!xdgh) {
+ if (!home) {
+ return NULL;
+ }
+
+ xdgh = cvalloc(strlen(home) + strlen(default_dir) + 1);
+
+ strcpy(xdgh, home);
+ strcat(xdgh, default_dir);
+ } else {
+ xdgh = strdup(xdgh);
+ }
+
+ return xdgh;
+}
+
+char **xdg_config_dirs(void) {
+ char *xdgd = getenv("XDG_CONFIG_DIRS");
+ size_t count = 0;
+
+ if (!xdgd) {
+ xdgd = "/etc/xdg";
+ }
+
+ for (int i = 0; xdgd[i]; i++) {
+ if (xdgd[i] == ':') {
+ count++;
+ }
+ }
+
+ // Store the string and the result pointers together so they can be
+ // freed together
+ char **dir_list = cvalloc(sizeof(char *) * (count + 2) + strlen(xdgd) + 1);
+ auto dirs = strcpy((char *)dir_list + sizeof(char *) * (count + 2), xdgd);
+ auto path = dirs;
+
+ for (size_t i = 0; i < count; i++) {
+ dir_list[i] = path;
+ path = strchr(path, ':');
+ *path = '\0';
+ path++;
+ }
+ dir_list[count] = path;
+
+ size_t fill = 0;
+ for (size_t i = 0; i <= count; i++) {
+ if (dir_list[i][0] == '/') {
+ dir_list[fill] = dir_list[i];
+ fill++;
+ }
+ }
+
+ dir_list[fill] = NULL;
+
+ return dir_list;
+}
+
+TEST_CASE(xdg_config_dirs) {
+ auto old_var = getenv("XDG_CONFIG_DIRS");
+ if (old_var) {
+ old_var = strdup(old_var);
+ }
+ unsetenv("XDG_CONFIG_DIRS");
+
+ auto result = xdg_config_dirs();
+ TEST_STREQUAL(result[0], "/etc/xdg");
+ TEST_EQUAL(result[1], NULL);
+ free(result);
+
+ setenv("XDG_CONFIG_DIRS", ".:.:/etc/xdg:.:/:", 1);
+ result = xdg_config_dirs();
+ TEST_STREQUAL(result[0], "/etc/xdg");
+ TEST_STREQUAL(result[1], "/");
+ TEST_EQUAL(result[2], NULL);
+ free(result);
+
+ setenv("XDG_CONFIG_DIRS", ":", 1);
+ result = xdg_config_dirs();
+ TEST_EQUAL(result[0], NULL);
+ free(result);
+
+ if (old_var) {
+ setenv("XDG_CONFIG_DIRS", old_var, 1);
+ free(old_var);
+ }
+}
+
+/// Search for config file under a base directory
+FILE *open_config_file_at(const char *base, char **out_path) {
+ static const char *config_paths[] = {"/picom.conf", "/picom/picom.conf",
+ "/compton.conf", "/compton/compton.conf"};
+ for (size_t i = 0; i < ARR_SIZE(config_paths); i++) {
+ char *path = mstrjoin(base, config_paths[i]);
+ FILE *ret = fopen(path, "r");
+ if (ret && out_path) {
+ *out_path = path;
+ } else {
+ free(path);
+ }
+ if (ret) {
+ if (strstr(config_paths[i], "compton")) {
+ log_warn("This compositor has been renamed to \"picom\", "
+ "the old config file paths is deprecated. "
+ "Please replace the \"compton\"s in the path "
+ "with \"picom\"");
+ }
+ return ret;
+ }
+ }
+ return NULL;
+}
+
+/**
+ * Get a file stream of the configuration file to read.
+ *
+ * Follows the XDG specification to search for the configuration file.
+ */
+FILE *open_config_file(const char *cpath, char **ppath) {
+ static const char config_filename_legacy[] = "/.compton.conf";
+
+ if (cpath) {
+ FILE *ret = fopen(cpath, "r");
+ if (ret && ppath)
+ *ppath = strdup(cpath);
+ return ret;
+ }
+
+ // First search for config file in user config directory
+ auto config_home = xdg_config_home();
+ auto ret = open_config_file_at(config_home, ppath);
+ free((void *)config_home);
+ if (ret) {
+ return ret;
+ }
+
+ // Fall back to legacy config file in user home directory
+ const char *home = getenv("HOME");
+ if (home && strlen(home)) {
+ auto path = mstrjoin(home, config_filename_legacy);
+ ret = fopen(path, "r");
+ if (ret && ppath) {
+ *ppath = path;
+ } else {
+ free(path);
+ }
+ if (ret) {
+ return ret;
+ }
+ }
+
+ // Fall back to config file in system config directory
+ auto config_dirs = xdg_config_dirs();
+ for (int i = 0; config_dirs[i]; i++) {
+ ret = open_config_file_at(config_dirs[i], ppath);
+ if (ret) {
+ free(config_dirs);
+ return ret;
+ }
+ }
+ free(config_dirs);
+
+ return NULL;
+}
+
+/**
+ * Parse a condition list in configuration file.
+ */
+void parse_cfg_condlst(const config_t *pcfg, c2_lptr_t **pcondlst, const char *name) {
+ config_setting_t *setting = config_lookup(pcfg, name);
+ if (setting) {
+ // Parse an array of options
+ if (config_setting_is_array(setting)) {
+ int i = config_setting_length(setting);
+ while (i--)
+ condlst_add(pcondlst,
+ config_setting_get_string_elem(setting, i));
+ }
+ // Treat it as a single pattern if it's a string
+ else if (CONFIG_TYPE_STRING == config_setting_type(setting)) {
+ condlst_add(pcondlst, config_setting_get_string(setting));
+ }
+ }
+}
+
+/**
+ * Parse an opacity rule list in configuration file.
+ */
+static inline void
+parse_cfg_condlst_opct(options_t *opt, const config_t *pcfg, const char *name) {
+ config_setting_t *setting = config_lookup(pcfg, name);
+ if (setting) {
+ // Parse an array of options
+ if (config_setting_is_array(setting)) {
+ int i = config_setting_length(setting);
+ while (i--)
+ if (!parse_rule_opacity(
+ &opt->opacity_rules,
+ config_setting_get_string_elem(setting, i)))
+ exit(1);
+ }
+ // Treat it as a single pattern if it's a string
+ else if (config_setting_type(setting) == CONFIG_TYPE_STRING) {
+ if (!parse_rule_opacity(&opt->opacity_rules,
+ config_setting_get_string(setting)))
+ exit(1);
+ }
+ }
+}
+
+static inline void parse_wintype_config(const config_t *cfg, const char *member_name,
+ win_option_t *o, win_option_mask_t *mask) {
+ char *str = mstrjoin("wintypes.", member_name);
+ const config_setting_t *setting = config_lookup(cfg, str);
+ free(str);
+
+ int ival = 0;
+ const char *sval = NULL;
+
+ if (setting) {
+ if (config_setting_lookup_bool(setting, "shadow", &ival)) {
+ o->shadow = ival;
+ mask->shadow = true;
+ }
+ if (config_setting_lookup_bool(setting, "fade", &ival)) {
+ o->fade = ival;
+ mask->fade = true;
+ }
+ if (config_setting_lookup_bool(setting, "focus", &ival)) {
+ o->focus = ival;
+ mask->focus = true;
+ }
+ if (config_setting_lookup_bool(setting, "blur-background", &ival)) {
+ o->blur_background = ival;
+ mask->blur_background = true;
+ }
+ if (config_setting_lookup_bool(setting, "full-shadow", &ival)) {
+ o->full_shadow = ival;
+ mask->full_shadow = true;
+ }
+ if (config_setting_lookup_bool(setting, "redir-ignore", &ival)) {
+ o->redir_ignore = ival;
+ mask->redir_ignore = true;
+ }
+ if (config_setting_lookup_bool(setting, "clip-shadow-above", &ival)) {
+ o->clip_shadow_above = ival;
+ mask->clip_shadow_above = true;
+ }
+ if (config_setting_lookup_string(setting, "animation", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID)
+ animation = OPEN_WINDOW_ANIMATION_NONE;
+
+ o->animation = animation;
+ mask->animation = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+ if (config_setting_lookup_string(setting, "animation-unmap", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID)
+ animation = OPEN_WINDOW_ANIMATION_NONE;
+
+ o->animation_unmap = animation;
+ mask->animation_unmap = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+ if (config_setting_lookup_string(setting, "animation-workspace-in", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID)
+ animation = OPEN_WINDOW_ANIMATION_NONE;
+
+ o->animation_workspace_in = animation;
+ mask->animation_workspace_in = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+ if (config_setting_lookup_string(setting, "animation-workspace-out", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID)
+ animation = OPEN_WINDOW_ANIMATION_NONE;
+
+ o->animation_workspace_out = animation;
+ mask->animation_workspace_out = OPEN_WINDOW_ANIMATION_INVALID;
+ }
+
+ double fval;
+ if (config_setting_lookup_float(setting, "opacity", &fval)) {
+ o->opacity = normalize_d(fval);
+ mask->opacity = true;
+ }
+ }
+}
+
+/**
+ * Parse a configuration file from default location.
+ *
+ * Returns the actually config_file name
+ */
+char *parse_config_libconfig(options_t *opt, const char *config_file, bool *shadow_enable,
+ bool *fading_enable, bool *conv_kern_hasneg,
+ win_option_mask_t *winopt_mask) {
+
+ const char *deprecation_message =
+ "option has been deprecated. Please remove it from your configuration file. "
+ "If you encounter any problems without this feature, please feel free to "
+ "open a bug report";
+ char *path = NULL;
+ FILE *f;
+ config_t cfg;
+ int ival = 0;
+ bool bval;
+ double dval = 0.0;
+ // libconfig manages string memory itself, so no need to manually free
+ // anything
+ const char *sval = NULL;
+
+ f = open_config_file(config_file, &path);
+ if (!f) {
+ free(path);
+ if (config_file) {
+ log_fatal("Failed to read configuration file \"%s\".", config_file);
+ return ERR_PTR(-1);
+ }
+ return NULL;
+ }
+
+ config_init(&cfg);
+#ifdef CONFIG_OPTION_ALLOW_OVERRIDES
+ config_set_options(&cfg, CONFIG_OPTION_ALLOW_OVERRIDES);
+#endif
+ {
+ // dirname() could modify the original string, thus we must pass a
+ // copy
+ char *path2 = strdup(path);
+ char *parent = dirname(path2);
+
+ if (parent)
+ config_set_include_dir(&cfg, parent);
+
+ free(path2);
+ }
+
+ {
+ int read_result = config_read(&cfg, f);
+ fclose(f);
+ f = NULL;
+ if (read_result == CONFIG_FALSE) {
+ log_fatal("Error when reading configuration file \"%s\", line "
+ "%d: %s",
+ path, config_error_line(&cfg), config_error_text(&cfg));
+ goto err;
+ }
+ }
+ config_set_auto_convert(&cfg, 1);
+
+ // Get options from the configuration file. We don't do range checking
+ // right now. It will be done later
+
+ // --dbus
+ lcfg_lookup_bool(&cfg, "dbus", &opt->dbus);
+
+ // -D (fade_delta)
+ if (config_lookup_int(&cfg, "fade-delta", &ival)) {
+ opt->fade_delta = ival;
+ }
+ // -I (fade_in_step)
+ if (config_lookup_float(&cfg, "fade-in-step", &dval)) {
+ opt->fade_in_step = normalize_d(dval);
+ }
+ // -O (fade_out_step)
+ if (config_lookup_float(&cfg, "fade-out-step", &dval)) {
+ opt->fade_out_step = normalize_d(dval);
+ }
+ // -r (shadow_radius)
+ config_lookup_int(&cfg, "shadow-radius", &opt->shadow_radius);
+ // -o (shadow_opacity)
+ config_lookup_float(&cfg, "shadow-opacity", &opt->shadow_opacity);
+ // -l (shadow_offset_x)
+ config_lookup_int(&cfg, "shadow-offset-x", &opt->shadow_offset_x);
+ // -t (shadow_offset_y)
+ config_lookup_int(&cfg, "shadow-offset-y", &opt->shadow_offset_y);
+ // -i (inactive_opacity)
+ if (config_lookup_float(&cfg, "inactive-opacity", &dval)) {
+ opt->inactive_opacity = normalize_d(dval);
+ }
+ // --active_opacity
+ if (config_lookup_float(&cfg, "active-opacity", &dval)) {
+ opt->active_opacity = normalize_d(dval);
+ }
+ // --corner-radius
+ config_lookup_int(&cfg, "corner-radius", &opt->corner_radius);
+ // --rounded-corners-exclude
+ parse_cfg_condlst(&cfg, &opt->rounded_corners_blacklist, "rounded-corners-exclude");
+ // -e (frame_opacity)
+ config_lookup_float(&cfg, "frame-opacity", &opt->frame_opacity);
+ // -c (shadow_enable)
+ lcfg_lookup_bool(&cfg, "shadow", shadow_enable);
+ // -m (menu_opacity)
+ if (config_lookup_float(&cfg, "menu-opacity", &dval)) {
+ log_warn("Option `menu-opacity` is deprecated, and will be removed."
+ "Please use the wintype option `opacity` of `popup_menu`"
+ "and `dropdown_menu` instead.");
+ opt->wintype_option[WINTYPE_DROPDOWN_MENU].opacity = dval;
+ opt->wintype_option[WINTYPE_POPUP_MENU].opacity = dval;
+ winopt_mask[WINTYPE_DROPDOWN_MENU].opacity = true;
+ winopt_mask[WINTYPE_POPUP_MENU].opacity = true;
+ }
+ // -f (fading_enable)
+ if (config_lookup_bool(&cfg, "fading", &ival))
+ *fading_enable = ival;
+ // --no-fading-open-close
+ lcfg_lookup_bool(&cfg, "no-fading-openclose", &opt->no_fading_openclose);
+ // --no-fading-destroyed-argb
+ lcfg_lookup_bool(&cfg, "no-fading-destroyed-argb", &opt->no_fading_destroyed_argb);
+ // --shadow-red
+ config_lookup_float(&cfg, "shadow-red", &opt->shadow_red);
+ // --shadow-green
+ config_lookup_float(&cfg, "shadow-green", &opt->shadow_green);
+ // --shadow-blue
+ config_lookup_float(&cfg, "shadow-blue", &opt->shadow_blue);
+ // --shadow-color
+ if (config_lookup_string(&cfg, "shadow-color", &sval)) {
+ struct color rgb;
+ rgb = hex_to_rgb(sval);
+ opt->shadow_red = rgb.red;
+ opt->shadow_green = rgb.green;
+ opt->shadow_blue = rgb.blue;
+ }
+ // --shadow-exclude-reg
+ if (config_lookup_string(&cfg, "shadow-exclude-reg", &sval))
+ opt->shadow_exclude_reg_str = strdup(sval);
+ // --inactive-opacity-override
+ lcfg_lookup_bool(&cfg, "inactive-opacity-override", &opt->inactive_opacity_override);
+ // --inactive-dim
+ config_lookup_float(&cfg, "inactive-dim", &opt->inactive_dim);
+ // --mark-wmwin-focused
+ lcfg_lookup_bool(&cfg, "mark-wmwin-focused", &opt->mark_wmwin_focused);
+ // --mark-ovredir-focused
+ lcfg_lookup_bool(&cfg, "mark-ovredir-focused", &opt->mark_ovredir_focused);
+ // --shadow-ignore-shaped
+ lcfg_lookup_bool(&cfg, "shadow-ignore-shaped", &opt->shadow_ignore_shaped);
+ // --detect-rounded-corners
+ lcfg_lookup_bool(&cfg, "detect-rounded-corners", &opt->detect_rounded_corners);
+ // --xinerama-shadow-crop
+ lcfg_lookup_bool(&cfg, "xinerama-shadow-crop", &opt->xinerama_shadow_crop);
+ // --detect-client-opacity
+ lcfg_lookup_bool(&cfg, "detect-client-opacity", &opt->detect_client_opacity);
+ // --refresh-rate
+ if (config_lookup_int(&cfg, "refresh-rate", &ival)) {
+ log_warn("The refresh-rate %s", deprecation_message);
+ }
+ // --vsync
+ if (config_lookup_string(&cfg, "vsync", &sval)) {
+ bool parsed_vsync = parse_vsync(sval);
+ log_error("vsync option will take a boolean from now on. \"%s\" in "
+ "your configuration should be changed to \"%s\"",
+ sval, parsed_vsync ? "true" : "false");
+ goto err;
+ }
+ lcfg_lookup_bool(&cfg, "vsync", &opt->vsync);
+ // --backend
+ if (config_lookup_string(&cfg, "backend", &sval)) {
+ opt->backend = parse_backend(sval);
+ if (opt->backend >= NUM_BKEND) {
+ log_fatal("Cannot parse backend");
+ goto err;
+ }
+ }
+ // --log-level
+ if (config_lookup_string(&cfg, "log-level", &sval)) {
+ auto level = string_to_log_level(sval);
+ if (level == LOG_LEVEL_INVALID) {
+ log_warn("Invalid log level, defaults to WARN");
+ } else {
+ log_set_level_tls(level);
+ }
+ }
+ // --log-file
+ if (config_lookup_string(&cfg, "log-file", &sval)) {
+ if (*sval != '/') {
+ log_warn("The log-file in your configuration file is not an "
+ "absolute path");
+ }
+ opt->logpath = strdup(sval);
+ }
+ // --sw-opti
+ if (lcfg_lookup_bool(&cfg, "sw-opti", &bval)) {
+ log_warn("The sw-opti %s", deprecation_message);
+ }
+ // --use-ewmh-active-win
+ lcfg_lookup_bool(&cfg, "use-ewmh-active-win", &opt->use_ewmh_active_win);
+ // --unredir-if-possible
+ lcfg_lookup_bool(&cfg, "unredir-if-possible", &opt->unredir_if_possible);
+ // --unredir-if-possible-delay
+ if (config_lookup_int(&cfg, "unredir-if-possible-delay", &ival)) {
+ if (ival < 0) {
+ log_warn("Invalid unredir-if-possible-delay %d", ival);
+ } else {
+ opt->unredir_if_possible_delay = ival;
+ }
+ }
+ // --inactive-dim-fixed
+ lcfg_lookup_bool(&cfg, "inactive-dim-fixed", &opt->inactive_dim_fixed);
+ // --detect-transient
+ lcfg_lookup_bool(&cfg, "detect-transient", &opt->detect_transient);
+ // --detect-client-leader
+ lcfg_lookup_bool(&cfg, "detect-client-leader", &opt->detect_client_leader);
+ // --no-ewmh-fullscreen
+ lcfg_lookup_bool(&cfg, "no-ewmh-fullscreen", &opt->no_ewmh_fullscreen);
+ // --transparent-clipping
+ lcfg_lookup_bool(&cfg, "transparent-clipping", &opt->transparent_clipping);
+ // --shadow-exclude
+ parse_cfg_condlst(&cfg, &opt->shadow_blacklist, "shadow-exclude");
+ // --clip-shadow-above
+ parse_cfg_condlst(&cfg, &opt->shadow_clip_list, "clip-shadow-above");
+ // --fade-exclude
+ parse_cfg_condlst(&cfg, &opt->fade_blacklist, "fade-exclude");
+ // --animations
+ lcfg_lookup_bool(&cfg, "animations", &opt->animations);
+ // --animation-for-open-window
+ if (config_lookup_string(&cfg, "animation-for-open-window", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID) {
+ log_fatal("Invalid open-window animation %s", sval);
+ goto err;
+ }
+ opt->animation_for_open_window = animation;
+ }
+ // --animation-for-transient-window
+ if (config_lookup_string(&cfg, "animation-for-transient-window", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID) {
+ log_fatal("Invalid transient-window animation %s", sval);
+ goto err;
+ }
+ opt->animation_for_transient_window = animation;
+ }
+ // --animation-for-unmap-window
+ if (config_lookup_string(&cfg, "animation-for-unmap-window", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID) {
+ log_fatal("Invalid unmap-window animation %s", sval);
+ goto err;
+ }
+ opt->animation_for_unmap_window = animation;
+ }
+ // --animation-for-workspace-switch-in
+ if (config_lookup_string(&cfg, "animation-for-workspace-switch-in", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID) {
+ log_fatal("Invalid workspace-switch-in animation %s", sval);
+ goto err;
+ }
+ opt->animation_for_workspace_switch_in = animation;
+ }
+ // --animation-for-workspace-switch-out
+ if (config_lookup_string(&cfg, "animation-for-workspace-switch-out", &sval)) {
+ enum open_window_animation animation = parse_open_window_animation(sval);
+ if (animation >= OPEN_WINDOW_ANIMATION_INVALID) {
+ log_fatal("Invalid workspace-switch-out animation %s", sval);
+ goto err;
+ }
+ opt->animation_for_workspace_switch_out = animation;
+ }
+ // --animation-stiffness
+ config_lookup_float(&cfg, "animation-stiffness", &opt->animation_stiffness);
+ // --animation-window-mass
+ config_lookup_float(&cfg, "animation-window-mass", &opt->animation_window_mass);
+ // --animation-dampening
+ config_lookup_float(&cfg, "animation-dampening", &opt->animation_dampening);
+ // --animation-delta
+ config_lookup_float(&cfg, "animation-delta", &opt->animation_delta);
+ // --animation-force-steps
+ lcfg_lookup_bool(&cfg, "animation-force-steps", &opt->animation_force_steps);
+ // --animation-clamping
+ lcfg_lookup_bool(&cfg, "animation-clamping", &opt->animation_clamping);
+ // --animation-exclude
+ parse_cfg_condlst(&cfg, &opt->animation_blacklist, "animation-exclude");
+ // --focus-exclude
+ parse_cfg_condlst(&cfg, &opt->focus_blacklist, "focus-exclude");
+ // --invert-color-include
+ parse_cfg_condlst(&cfg, &opt->invert_color_list, "invert-color-include");
+ // --blur-background-exclude
+ parse_cfg_condlst(&cfg, &opt->blur_background_blacklist, "blur-background-exclude");
+ // --opacity-rule
+ parse_cfg_condlst_opct(opt, &cfg, "opacity-rule");
+ // --unredir-if-possible-exclude
+ parse_cfg_condlst(&cfg, &opt->unredir_if_possible_blacklist,
+ "unredir-if-possible-exclude");
+ // --blur-method
+ if (config_lookup_string(&cfg, "blur-method", &sval)) {
+ enum blur_method method = parse_blur_method(sval);
+ if (method >= BLUR_METHOD_INVALID) {
+ log_fatal("Invalid blur method %s", sval);
+ goto err;
+ }
+ opt->blur_method = method;
+ }
+ // --blur-size
+ config_lookup_int(&cfg, "blur-size", &opt->blur_radius);
+ // --blur-deviation
+ config_lookup_float(&cfg, "blur-deviation", &opt->blur_deviation);
+ // --blur-strength
+ config_lookup_int(&cfg, "blur-strength", &opt->blur_strength);
+ // --blur-background
+ if (config_lookup_bool(&cfg, "blur-background", &ival) && ival) {
+ if (opt->blur_method == BLUR_METHOD_NONE) {
+ opt->blur_method = BLUR_METHOD_KERNEL;
+ }
+ }
+ // --blur-background-frame
+ lcfg_lookup_bool(&cfg, "blur-background-frame", &opt->blur_background_frame);
+ // --blur-background-fixed
+ lcfg_lookup_bool(&cfg, "blur-background-fixed", &opt->blur_background_fixed);
+ // --blur-kern
+ if (config_lookup_string(&cfg, "blur-kern", &sval)) {
+ opt->blur_kerns =
+ parse_blur_kern_lst(sval, conv_kern_hasneg, &opt->blur_kernel_count);
+ if (!opt->blur_kerns) {
+ log_fatal("Cannot parse \"blur-kern\"");
+ goto err;
+ }
+ }
+ // --resize-damage
+ config_lookup_int(&cfg, "resize-damage", &opt->resize_damage);
+ // --glx-no-stencil
+ lcfg_lookup_bool(&cfg, "glx-no-stencil", &opt->glx_no_stencil);
+ // --glx-no-rebind-pixmap
+ lcfg_lookup_bool(&cfg, "glx-no-rebind-pixmap", &opt->glx_no_rebind_pixmap);
+ lcfg_lookup_bool(&cfg, "force-win-blend", &opt->force_win_blend);
+ // --glx-swap-method
+ if (config_lookup_string(&cfg, "glx-swap-method", &sval)) {
+ char *endptr;
+ long val = strtol(sval, &endptr, 10);
+ bool should_remove = true;
+ if (*endptr || !(*sval)) {
+ // sval is not a number, or an empty string
+ val = -1;
+ }
+ if (strcmp(sval, "undefined") != 0 && val != 0) {
+ // If not undefined, we will use damage and buffer-age to limit
+ // the rendering area.
+ should_remove = false;
+ }
+ log_error("glx-swap-method has been removed, your setting "
+ "\"%s\" should be %s.",
+ sval,
+ !should_remove ? "replaced by `use-damage = true`" : "removed");
+ goto err;
+ }
+ // --use-damage
+ lcfg_lookup_bool(&cfg, "use-damage", &opt->use_damage);
+
+ // --max-brightness
+ if (config_lookup_float(&cfg, "max-brightness", &opt->max_brightness) &&
+ opt->use_damage && opt->max_brightness < 1) {
+ log_warn("max-brightness requires use-damage = false. Falling back to "
+ "1.0");
+ opt->max_brightness = 1.0;
+ }
+
+ // --glx-use-gpushader4
+ if (config_lookup_bool(&cfg, "glx-use-gpushader4", &ival)) {
+ log_error("glx-use-gpushader4 has been removed, please remove it "
+ "from your config file");
+ goto err;
+ }
+ // --xrender-sync-fence
+ lcfg_lookup_bool(&cfg, "xrender-sync-fence", &opt->xrender_sync_fence);
+
+ if (lcfg_lookup_bool(&cfg, "clear-shadow", &bval))
+ log_warn("\"clear-shadow\" is removed as an option, and is always"
+ " enabled now. Consider removing it from your config file");
+
+ config_setting_t *blur_cfg = config_lookup(&cfg, "blur");
+ if (blur_cfg) {
+ if (config_setting_lookup_string(blur_cfg, "method", &sval)) {
+ enum blur_method method = parse_blur_method(sval);
+ if (method >= BLUR_METHOD_INVALID) {
+ log_warn("Invalid blur method %s, ignoring.", sval);
+ } else {
+ opt->blur_method = method;
+ }
+ }
+
+ config_setting_lookup_int(blur_cfg, "size", &opt->blur_radius);
+
+ if (config_setting_lookup_string(blur_cfg, "kernel", &sval)) {
+ opt->blur_kerns = parse_blur_kern_lst(sval, conv_kern_hasneg,
+ &opt->blur_kernel_count);
+ if (!opt->blur_kerns) {
+ log_warn("Failed to parse blur kernel: %s", sval);
+ }
+ }
+
+ config_setting_lookup_float(blur_cfg, "deviation", &opt->blur_deviation);
+ config_setting_lookup_int(blur_cfg, "strength", &opt->blur_strength);
+ }
+
+ // --write-pid-path
+ if (config_lookup_string(&cfg, "write-pid-path", &sval)) {
+ if (*sval != '/') {
+ log_warn("The write-pid-path in your configuration file is not"
+ " an absolute path");
+ }
+ opt->write_pid_path = strdup(sval);
+ }
+
+ // Wintype settings
+
+ // XXX ! Refactor all the wintype_* arrays into a struct
+ for (wintype_t i = 0; i < NUM_WINTYPES; ++i) {
+ parse_wintype_config(&cfg, WINTYPES[i], &opt->wintype_option[i],
+ &winopt_mask[i]);
+ }
+
+ // Compatibility with the old name for notification windows.
+ parse_wintype_config(&cfg, "notify", &opt->wintype_option[WINTYPE_NOTIFICATION],
+ &winopt_mask[WINTYPE_NOTIFICATION]);
+
+ config_destroy(&cfg);
+ return path;
+
+err:
+ config_destroy(&cfg);
+ free(path);
+ return ERR_PTR(-1);
+}
diff --git a/dwm/picom/src/dbus.c b/dwm/picom/src/dbus.c
new file mode 100644
index 0000000..e037167
--- /dev/null
+++ b/dwm/picom/src/dbus.c
@@ -0,0 +1,1700 @@
+// SPDX-License-Identifier: MIT
+/*
+ * Compton - a compositor for X11
+ *
+ * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
+ *
+ * Copyright (c) 2011-2013, Christopher Jeffrey
+ * See LICENSE-mit for more information.
+ *
+ */
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "common.h"
+#include "compiler.h"
+#include "config.h"
+#include "list.h"
+#include "log.h"
+#include "string_utils.h"
+#include "types.h"
+#include "uthash_extra.h"
+#include "utils.h"
+#include "win.h"
+
+#include "dbus.h"
+
+struct cdbus_data {
+ /// DBus connection.
+ DBusConnection *dbus_conn;
+ /// DBus service name.
+ char *dbus_service;
+};
+
+// Window type
+typedef uint32_t cdbus_window_t;
+#define CDBUS_TYPE_WINDOW DBUS_TYPE_UINT32
+#define CDBUS_TYPE_WINDOW_STR DBUS_TYPE_UINT32_AS_STRING
+
+typedef uint32_t cdbus_enum_t;
+#define CDBUS_TYPE_ENUM DBUS_TYPE_UINT32
+#define CDBUS_TYPE_ENUM_STR DBUS_TYPE_UINT32_AS_STRING
+
+#define CDBUS_SERVICE_NAME "com.github.chjj.compton"
+#define CDBUS_INTERFACE_NAME CDBUS_SERVICE_NAME
+#define CDBUS_OBJECT_NAME "/com/github/chjj/compton"
+#define CDBUS_ERROR_PREFIX CDBUS_INTERFACE_NAME ".error"
+#define CDBUS_ERROR_UNKNOWN CDBUS_ERROR_PREFIX ".unknown"
+#define CDBUS_ERROR_UNKNOWN_S "Well, I don't know what happened. Do you?"
+#define CDBUS_ERROR_BADMSG CDBUS_ERROR_PREFIX ".bad_message"
+#define CDBUS_ERROR_BADMSG_S \
+ "Unrecognized command. Beware compton " \
+ "cannot make you a sandwich."
+#define CDBUS_ERROR_BADARG CDBUS_ERROR_PREFIX ".bad_argument"
+#define CDBUS_ERROR_BADARG_S "Failed to parse argument %d: %s"
+#define CDBUS_ERROR_BADWIN CDBUS_ERROR_PREFIX ".bad_window"
+#define CDBUS_ERROR_BADWIN_S "Requested window %#010x not found."
+#define CDBUS_ERROR_BADTGT CDBUS_ERROR_PREFIX ".bad_target"
+#define CDBUS_ERROR_BADTGT_S "Target \"%s\" not found."
+#define CDBUS_ERROR_FORBIDDEN CDBUS_ERROR_PREFIX ".forbidden"
+#define CDBUS_ERROR_FORBIDDEN_S "Incorrect password, access denied."
+#define CDBUS_ERROR_CUSTOM CDBUS_ERROR_PREFIX ".custom"
+#define CDBUS_ERROR_CUSTOM_S "%s"
+
+#define cdbus_reply_err(ps, srcmsg, err_name, err_format, ...) \
+ cdbus_reply_errm((ps), dbus_message_new_error_printf( \
+ (srcmsg), (err_name), (err_format), ##__VA_ARGS__))
+
+#define PICOM_WINDOW_INTERFACE "picom.Window"
+#define PICOM_COMPOSITOR_INTERFACE "picom.Compositor"
+
+static DBusHandlerResult cdbus_process(DBusConnection *conn, DBusMessage *m, void *);
+static DBusHandlerResult cdbus_process_windows(DBusConnection *c, DBusMessage *msg, void *ud);
+
+static dbus_bool_t cdbus_callback_add_timeout(DBusTimeout *timeout, void *data);
+
+static void cdbus_callback_remove_timeout(DBusTimeout *timeout, void *data);
+
+static void cdbus_callback_timeout_toggled(DBusTimeout *timeout, void *data);
+
+static dbus_bool_t cdbus_callback_add_watch(DBusWatch *watch, void *data);
+
+static void cdbus_callback_remove_watch(DBusWatch *watch, void *data);
+
+static void cdbus_callback_watch_toggled(DBusWatch *watch, void *data);
+
+/**
+ * Initialize D-Bus connection.
+ */
+bool cdbus_init(session_t *ps, const char *uniq) {
+ auto cd = cmalloc(struct cdbus_data);
+ cd->dbus_service = NULL;
+
+ // Set ps->dbus_data here because add_watch functions need it
+ ps->dbus_data = cd;
+
+ DBusError err = {};
+
+ // Initialize
+ dbus_error_init(&err);
+
+ // Connect to D-Bus
+ // Use dbus_bus_get_private() so we can fully recycle it ourselves
+ cd->dbus_conn = dbus_bus_get_private(DBUS_BUS_SESSION, &err);
+ if (dbus_error_is_set(&err)) {
+ log_error("D-Bus connection failed (%s).", err.message);
+ dbus_error_free(&err);
+ goto fail;
+ }
+
+ if (!cd->dbus_conn) {
+ log_error("D-Bus connection failed for unknown reason.");
+ goto fail;
+ }
+
+ // Avoid exiting on disconnect
+ dbus_connection_set_exit_on_disconnect(cd->dbus_conn, false);
+
+ // Request service name
+ {
+ // Build service name
+ size_t service_len = strlen(CDBUS_SERVICE_NAME) + strlen(uniq) + 2;
+ char *service = ccalloc(service_len, char);
+ snprintf(service, service_len, "%s.%s", CDBUS_SERVICE_NAME, uniq);
+
+ // Make a valid dbus name by converting non alphanumeric characters to
+ // underscore
+ char *tmp = service + strlen(CDBUS_SERVICE_NAME) + 1;
+ while (*tmp) {
+ if (!isalnum((unsigned char)*tmp)) {
+ *tmp = '_';
+ }
+ tmp++;
+ }
+ cd->dbus_service = service;
+
+ // Request for the name
+ int ret = dbus_bus_request_name(cd->dbus_conn, service,
+ DBUS_NAME_FLAG_DO_NOT_QUEUE, &err);
+
+ if (dbus_error_is_set(&err)) {
+ log_error("Failed to obtain D-Bus name (%s).", err.message);
+ dbus_error_free(&err);
+ goto fail;
+ }
+
+ if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret &&
+ DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER != ret) {
+ log_error("Failed to become the primary owner of requested D-Bus "
+ "name (%d).",
+ ret);
+ goto fail;
+ }
+ }
+
+ // Add watch handlers
+ if (!dbus_connection_set_watch_functions(cd->dbus_conn, cdbus_callback_add_watch,
+ cdbus_callback_remove_watch,
+ cdbus_callback_watch_toggled, ps, NULL)) {
+ log_error("Failed to add D-Bus watch functions.");
+ goto fail;
+ }
+
+ // Add timeout handlers
+ if (!dbus_connection_set_timeout_functions(
+ cd->dbus_conn, cdbus_callback_add_timeout, cdbus_callback_remove_timeout,
+ cdbus_callback_timeout_toggled, ps, NULL)) {
+ log_error("Failed to add D-Bus timeout functions.");
+ goto fail;
+ }
+
+ // Add match
+ dbus_bus_add_match(cd->dbus_conn,
+ "type='method_call',interface='" CDBUS_INTERFACE_NAME "'", &err);
+ if (dbus_error_is_set(&err)) {
+ log_error("Failed to add D-Bus match.");
+ dbus_error_free(&err);
+ goto fail;
+ }
+ dbus_connection_register_object_path(
+ cd->dbus_conn, CDBUS_OBJECT_NAME,
+ (DBusObjectPathVTable[]){{NULL, cdbus_process}}, ps);
+ dbus_connection_register_fallback(
+ cd->dbus_conn, CDBUS_OBJECT_NAME "/windows",
+ (DBusObjectPathVTable[]){{NULL, cdbus_process_windows}}, ps);
+ return true;
+fail:
+ ps->dbus_data = NULL;
+ free(cd->dbus_service);
+ free(cd);
+ return false;
+}
+
+/**
+ * Destroy D-Bus connection.
+ */
+void cdbus_destroy(session_t *ps) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (cd->dbus_conn) {
+ // Release DBus name firstly
+ if (cd->dbus_service) {
+ DBusError err = {};
+ dbus_error_init(&err);
+
+ dbus_bus_release_name(cd->dbus_conn, cd->dbus_service, &err);
+ if (dbus_error_is_set(&err)) {
+ log_error("Failed to release DBus name (%s).", err.message);
+ dbus_error_free(&err);
+ }
+ free(cd->dbus_service);
+ }
+
+ // Close and unref the connection
+ dbus_connection_close(cd->dbus_conn);
+ dbus_connection_unref(cd->dbus_conn);
+ }
+ free(cd);
+}
+
+/** @name DBusTimeout handling
+ */
+///@{
+
+typedef struct ev_dbus_timer {
+ ev_timer w;
+ DBusTimeout *t;
+} ev_dbus_timer;
+
+/**
+ * Callback for handling a D-Bus timeout.
+ */
+static void
+cdbus_callback_handle_timeout(EV_P attr_unused, ev_timer *w, int revents attr_unused) {
+ ev_dbus_timer *t = (void *)w;
+ dbus_timeout_handle(t->t);
+}
+
+/**
+ * Callback for adding D-Bus timeout.
+ */
+static dbus_bool_t cdbus_callback_add_timeout(DBusTimeout *timeout, void *data) {
+ session_t *ps = data;
+
+ auto t = ccalloc(1, ev_dbus_timer);
+ double i = dbus_timeout_get_interval(timeout) / 1000.0;
+ ev_timer_init(&t->w, cdbus_callback_handle_timeout, i, i);
+ t->t = timeout;
+ dbus_timeout_set_data(timeout, t, NULL);
+
+ if (dbus_timeout_get_enabled(timeout))
+ ev_timer_start(ps->loop, &t->w);
+
+ return true;
+}
+
+/**
+ * Callback for removing D-Bus timeout.
+ */
+static void cdbus_callback_remove_timeout(DBusTimeout *timeout, void *data) {
+ session_t *ps = data;
+
+ ev_dbus_timer *t = dbus_timeout_get_data(timeout);
+ assert(t);
+ ev_timer_stop(ps->loop, &t->w);
+ free(t);
+}
+
+/**
+ * Callback for toggling a D-Bus timeout.
+ */
+static void cdbus_callback_timeout_toggled(DBusTimeout *timeout, void *data) {
+ session_t *ps = data;
+ ev_dbus_timer *t = dbus_timeout_get_data(timeout);
+
+ assert(t);
+ ev_timer_stop(ps->loop, &t->w);
+ if (dbus_timeout_get_enabled(timeout)) {
+ double i = dbus_timeout_get_interval(timeout) / 1000.0;
+ ev_timer_set(&t->w, i, i);
+ ev_timer_start(ps->loop, &t->w);
+ }
+}
+
+///@}
+
+/** @name DBusWatch handling
+ */
+///@{
+
+typedef struct ev_dbus_io {
+ ev_io w;
+ struct cdbus_data *cd;
+ DBusWatch *dw;
+} ev_dbus_io;
+
+void cdbus_io_callback(EV_P attr_unused, ev_io *w, int revents) {
+ ev_dbus_io *dw = (void *)w;
+ DBusWatchFlags flags = 0;
+ if (revents & EV_READ)
+ flags |= DBUS_WATCH_READABLE;
+ if (revents & EV_WRITE)
+ flags |= DBUS_WATCH_WRITABLE;
+ dbus_watch_handle(dw->dw, flags);
+ while (dbus_connection_dispatch(dw->cd->dbus_conn) != DBUS_DISPATCH_COMPLETE)
+ ;
+}
+
+/**
+ * Determine the poll condition of a DBusWatch.
+ */
+static inline int cdbus_get_watch_cond(DBusWatch *watch) {
+ const unsigned flags = dbus_watch_get_flags(watch);
+ int condition = 0;
+ if (flags & DBUS_WATCH_READABLE)
+ condition |= EV_READ;
+ if (flags & DBUS_WATCH_WRITABLE)
+ condition |= EV_WRITE;
+
+ return condition;
+}
+
+/**
+ * Callback for adding D-Bus watch.
+ */
+static dbus_bool_t cdbus_callback_add_watch(DBusWatch *watch, void *data) {
+ session_t *ps = data;
+
+ auto w = ccalloc(1, ev_dbus_io);
+ w->dw = watch;
+ w->cd = ps->dbus_data;
+ ev_io_init(&w->w, cdbus_io_callback, dbus_watch_get_unix_fd(watch),
+ cdbus_get_watch_cond(watch));
+
+ // Leave disabled watches alone
+ if (dbus_watch_get_enabled(watch))
+ ev_io_start(ps->loop, &w->w);
+
+ dbus_watch_set_data(watch, w, NULL);
+
+ // Always return true
+ return true;
+}
+
+/**
+ * Callback for removing D-Bus watch.
+ */
+static void cdbus_callback_remove_watch(DBusWatch *watch, void *data) {
+ session_t *ps = data;
+ ev_dbus_io *w = dbus_watch_get_data(watch);
+ ev_io_stop(ps->loop, &w->w);
+ free(w);
+}
+
+/**
+ * Callback for toggling D-Bus watch status.
+ */
+static void cdbus_callback_watch_toggled(DBusWatch *watch, void *data) {
+ session_t *ps = data;
+ ev_io *w = dbus_watch_get_data(watch);
+ if (dbus_watch_get_enabled(watch))
+ ev_io_start(ps->loop, w);
+ else
+ ev_io_stop(ps->loop, w);
+}
+
+///@}
+
+/** @name Message argument appending callbacks
+ */
+///@{
+
+/**
+ * Callback to append a bool argument to a message.
+ */
+static bool cdbus_apdarg_bool(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ assert(data);
+
+ dbus_bool_t val = *(const bool *)data;
+
+ if (!dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &val, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append an int32 argument to a message.
+ */
+static bool cdbus_apdarg_int32(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ if (!dbus_message_append_args(msg, DBUS_TYPE_INT32, data, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append an uint32 argument to a message.
+ */
+static bool
+cdbus_apdarg_uint32(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, data, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append a double argument to a message.
+ */
+static bool
+cdbus_apdarg_double(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ if (!dbus_message_append_args(msg, DBUS_TYPE_DOUBLE, data, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append a Window argument to a message.
+ */
+static bool cdbus_apdarg_wid(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ assert(data);
+ cdbus_window_t val = *(const xcb_window_t *)data;
+
+ if (!dbus_message_append_args(msg, CDBUS_TYPE_WINDOW, &val, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append a Window argument to a message as a variant.
+ */
+static bool
+cdbus_append_wid_variant(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ assert(data);
+ cdbus_window_t val = *(const xcb_window_t *)data;
+
+ DBusMessageIter it, it2;
+ dbus_message_iter_init_append(msg, &it);
+ if (!dbus_message_iter_open_container(&it, DBUS_TYPE_VARIANT,
+ CDBUS_TYPE_WINDOW_STR, &it2)) {
+ return false;
+ }
+ if (!dbus_message_iter_append_basic(&it2, CDBUS_TYPE_WINDOW, &val)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+ if (!dbus_message_iter_close_container(&it, &it2)) {
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append a bool argument to a message as a variant.
+ */
+static bool
+cdbus_append_bool_variant(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ assert(data);
+
+ dbus_bool_t val = *(const bool *)data;
+ DBusMessageIter it, it2;
+ dbus_message_iter_init_append(msg, &it);
+ if (!dbus_message_iter_open_container(&it, DBUS_TYPE_VARIANT,
+ DBUS_TYPE_BOOLEAN_AS_STRING, &it2)) {
+ return false;
+ }
+ if (!dbus_message_iter_append_basic(&it2, DBUS_TYPE_BOOLEAN, &val)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+ if (!dbus_message_iter_close_container(&it, &it2)) {
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append an cdbus_enum_t argument to a message.
+ */
+static bool cdbus_apdarg_enum(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ assert(data);
+ if (!dbus_message_append_args(msg, CDBUS_TYPE_ENUM, data, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append a string argument to a message.
+ */
+static bool
+cdbus_apdarg_string(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ const char *str = data;
+ if (!str)
+ str = "";
+
+ if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &str, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Callback to append a string argument to a message as a variant.
+ */
+static bool
+cdbus_append_string_variant(session_t *ps attr_unused, DBusMessage *msg, const void *data) {
+ const char *str = *(const char **)data;
+ if (!str) {
+ str = "";
+ }
+
+ DBusMessageIter it, it2;
+ dbus_message_iter_init_append(msg, &it);
+ if (!dbus_message_iter_open_container(&it, DBUS_TYPE_VARIANT,
+ DBUS_TYPE_STRING_AS_STRING, &it2)) {
+ return false;
+ }
+ if (!dbus_message_iter_append_basic(&it2, DBUS_TYPE_STRING, &str)) {
+ log_error("Failed to append argument.");
+ return false;
+ }
+ if (!dbus_message_iter_close_container(&it, &it2)) {
+ return false;
+ }
+
+ return true;
+}
+
+static bool cdbus_append_empty_dict(session_t *ps attr_unused, DBusMessage *msg,
+ const void *data attr_unused) {
+ DBusMessageIter it, it2;
+ dbus_message_iter_init_append(msg, &it);
+ if (!dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "{sv}", &it2)) {
+ return false;
+ }
+ if (!dbus_message_iter_close_container(&it, &it2)) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Callback to append all window IDs to a message.
+ */
+static bool cdbus_apdarg_wids(session_t *ps, DBusMessage *msg, const void *data attr_unused) {
+ // Get the number of wids we are to include
+ unsigned count = 0;
+ HASH_ITER2(ps->windows, w) {
+ assert(!w->destroyed);
+ ++count;
+ }
+
+ if (!count) {
+ // Nothing to append
+ return true;
+ }
+
+ // Allocate memory for an array of window IDs
+ auto arr = ccalloc(count, cdbus_window_t);
+
+ // Build the array
+ cdbus_window_t *pcur = arr;
+ HASH_ITER2(ps->windows, w) {
+ assert(!w->destroyed);
+ *pcur = w->id;
+ ++pcur;
+ }
+ assert(pcur == arr + count);
+
+ // Append arguments
+ if (!dbus_message_append_args(msg, DBUS_TYPE_ARRAY, CDBUS_TYPE_WINDOW, &arr,
+ count, DBUS_TYPE_INVALID)) {
+ log_error("Failed to append argument.");
+ free(arr);
+ return false;
+ }
+
+ free(arr);
+ return true;
+}
+///@}
+
+/**
+ * Send a D-Bus signal.
+ *
+ * @param ps current session
+ * @param name signal name
+ * @param func a function that modifies the built message, to, for example,
+ * add an argument
+ * @param data data pointer to pass to the function
+ */
+static bool cdbus_signal(session_t *ps, const char *interface, const char *name,
+ bool (*func)(session_t *ps, DBusMessage *msg, const void *data),
+ const void *data) {
+ struct cdbus_data *cd = ps->dbus_data;
+ DBusMessage *msg = NULL;
+
+ // Create a signal
+ msg = dbus_message_new_signal(CDBUS_OBJECT_NAME, interface, name);
+ if (!msg) {
+ log_error("Failed to create D-Bus signal.");
+ return false;
+ }
+
+ // Append arguments onto message
+ if (func && !func(ps, msg, data)) {
+ dbus_message_unref(msg);
+ return false;
+ }
+
+ // Send the message and flush the connection
+ if (!dbus_connection_send(cd->dbus_conn, msg, NULL)) {
+ log_error("Failed to send D-Bus signal.");
+ dbus_message_unref(msg);
+ return false;
+ }
+ dbus_connection_flush(cd->dbus_conn);
+
+ // Free the message
+ dbus_message_unref(msg);
+
+ return true;
+}
+
+/**
+ * Send a signal with a Window ID as argument.
+ */
+static inline bool
+cdbus_signal_wid(session_t *ps, const char *interface, const char *name, xcb_window_t wid) {
+ return cdbus_signal(ps, interface, name, cdbus_apdarg_wid, &wid);
+}
+
+/**
+ * Send a D-Bus reply.
+ *
+ * @param ps current session
+ * @param srcmsg original message
+ * @param func a function that modifies the built message, to, for example,
+ * add an argument
+ * @param data data pointer to pass to the function
+ */
+static bool cdbus_reply(session_t *ps, DBusMessage *srcmsg,
+ bool (*func)(session_t *ps, DBusMessage *msg, const void *data),
+ const void *data) {
+ struct cdbus_data *cd = ps->dbus_data;
+ DBusMessage *msg = NULL;
+
+ // Create a reply
+ msg = dbus_message_new_method_return(srcmsg);
+ if (!msg) {
+ log_error("Failed to create D-Bus reply.");
+ return false;
+ }
+
+ // Append arguments onto message
+ if (func && !func(ps, msg, data)) {
+ dbus_message_unref(msg);
+ return false;
+ }
+
+ // Send the message and flush the connection
+ if (!dbus_connection_send(cd->dbus_conn, msg, NULL)) {
+ log_error("Failed to send D-Bus reply.");
+ dbus_message_unref(msg);
+ return false;
+ }
+ dbus_connection_flush(cd->dbus_conn);
+
+ // Free the message
+ dbus_message_unref(msg);
+
+ return true;
+}
+
+/**
+ * Send a reply with a bool argument.
+ */
+static inline bool cdbus_reply_bool(session_t *ps, DBusMessage *srcmsg, bool bval) {
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_bool, &bval);
+}
+
+/**
+ * Send a reply with an int32 argument.
+ */
+static inline bool cdbus_reply_int32(session_t *ps, DBusMessage *srcmsg, int32_t val) {
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_int32, &val);
+}
+
+/**
+ * Send a reply with an int32 argument, cast from a long.
+ */
+static inline bool cdbus_reply_int32l(session_t *ps, DBusMessage *srcmsg, long val) {
+ int32_t tmp = (int32_t)val;
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_int32, &tmp);
+}
+
+/**
+ * Send a reply with an uint32 argument.
+ */
+static inline bool cdbus_reply_uint32(session_t *ps, DBusMessage *srcmsg, uint32_t val) {
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_uint32, &val);
+}
+
+/**
+ * Send a reply with a double argument.
+ */
+static inline bool cdbus_reply_double(session_t *ps, DBusMessage *srcmsg, double val) {
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_double, &val);
+}
+
+/**
+ * Send a reply with a wid argument.
+ */
+static inline bool cdbus_reply_wid(session_t *ps, DBusMessage *srcmsg, xcb_window_t wid) {
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_wid, &wid);
+}
+
+/**
+ * Send a reply with a string argument.
+ */
+static inline bool cdbus_reply_string(session_t *ps, DBusMessage *srcmsg, const char *str) {
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_string, str);
+}
+
+/**
+ * Send a reply with a enum argument.
+ */
+static inline bool cdbus_reply_enum(session_t *ps, DBusMessage *srcmsg, cdbus_enum_t eval) {
+ return cdbus_reply(ps, srcmsg, cdbus_apdarg_enum, &eval);
+}
+
+/**
+ * Send a D-Bus error reply.
+ *
+ * @param ps current session
+ * @param msg the new error DBusMessage
+ */
+static bool cdbus_reply_errm(session_t *ps, DBusMessage *msg) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (!msg) {
+ log_error("Failed to create D-Bus reply.");
+ return false;
+ }
+
+ // Send the message and flush the connection
+ if (!dbus_connection_send(cd->dbus_conn, msg, NULL)) {
+ log_error("Failed to send D-Bus reply.");
+ dbus_message_unref(msg);
+ return false;
+ }
+ dbus_connection_flush(cd->dbus_conn);
+
+ // Free the message
+ dbus_message_unref(msg);
+
+ return true;
+}
+
+/**
+ * Get n-th argument of a D-Bus message.
+ *
+ * @param count the position of the argument to get, starting from 0
+ * @param type libdbus type number of the type
+ * @param pdest pointer to the target
+ * @return true if successful, false otherwise.
+ */
+static bool cdbus_msg_get_arg(DBusMessage *msg, int count, const int type, void *pdest) {
+ assert(count >= 0);
+
+ DBusMessageIter iter = {};
+ if (!dbus_message_iter_init(msg, &iter)) {
+ log_error("Message has no argument.");
+ return false;
+ }
+
+ {
+ const int oldcount = count;
+ while (count) {
+ if (!dbus_message_iter_next(&iter)) {
+ log_error("Failed to find argument %d.", oldcount);
+ return false;
+ }
+ --count;
+ }
+ }
+
+ if (type != dbus_message_iter_get_arg_type(&iter)) {
+ log_error("Argument has incorrect type.");
+ return false;
+ }
+
+ dbus_message_iter_get_basic(&iter, pdest);
+
+ return true;
+}
+
+/** @name Message processing
+ */
+///@{
+
+/**
+ * Process a list_win D-Bus request.
+ */
+static bool cdbus_process_list_win(session_t *ps, DBusMessage *msg) {
+ cdbus_reply(ps, msg, cdbus_apdarg_wids, NULL);
+
+ return true;
+}
+
+/**
+ * Process a win_get D-Bus request.
+ */
+static bool
+cdbus_process_window_property_get(session_t *ps, DBusMessage *msg, cdbus_window_t wid) {
+ const char *target = NULL;
+ const char *interface = NULL;
+ DBusError err = {};
+
+ if (!dbus_message_get_args(msg, &err, DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &target, DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse argument of \"Get\" (%s).", err.message);
+ dbus_error_free(&err);
+ return false;
+ }
+
+ if (strcmp(interface, PICOM_WINDOW_INTERFACE)) {
+ return false;
+ }
+
+ auto w = find_managed_win(ps, wid);
+
+ if (!w) {
+ log_error("Window %#010x not found.", wid);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADWIN, CDBUS_ERROR_BADWIN_S, wid);
+ return true;
+ }
+
+#define cdbus_m_win_get_do(tgt, member, apdarg_func) \
+ if (!strcmp(#tgt, target)) { \
+ cdbus_reply(ps, msg, apdarg_func, &w->member); \
+ return true; \
+ }
+
+ if (!strcmp("Mapped", target)) {
+ cdbus_reply(ps, msg, cdbus_append_bool_variant,
+ (bool[]){win_is_mapped_in_x(w)});
+ return true;
+ }
+
+ if (!strcmp(target, "Id")) {
+ cdbus_reply(ps, msg, cdbus_append_wid_variant, &w->base.id);
+ return true;
+ }
+
+ // next
+ if (!strcmp("Next", target)) {
+ cdbus_window_t next_id = 0;
+ if (!list_node_is_last(&ps->window_stack, &w->base.stack_neighbour)) {
+ next_id = list_entry(w->base.stack_neighbour.next, struct win,
+ stack_neighbour)
+ ->id;
+ }
+ cdbus_reply(ps, msg, cdbus_append_wid_variant, &next_id);
+ return true;
+ }
+
+ cdbus_m_win_get_do(ClientWin, client_win, cdbus_append_wid_variant);
+ cdbus_m_win_get_do(Leader, leader, cdbus_append_wid_variant);
+ cdbus_m_win_get_do(Name, name, cdbus_append_string_variant);
+ if (!strcmp("Type", target)) {
+ cdbus_reply(ps, msg, cdbus_append_string_variant, &WINTYPES[w->window_type]);
+ return true;
+ }
+ if (!strcmp("RawFocused", target)) {
+ cdbus_reply(ps, msg, cdbus_append_bool_variant,
+ (bool[]){win_is_focused_raw(ps, w)});
+ return true;
+ }
+
+#undef cdbus_m_win_get_do
+
+ log_error(CDBUS_ERROR_BADTGT_S, target);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADTGT, CDBUS_ERROR_BADTGT_S, target);
+
+ return true;
+}
+
+/**
+ * Process a win_get D-Bus request.
+ */
+static bool cdbus_process_win_get(session_t *ps, DBusMessage *msg) {
+ cdbus_window_t wid = XCB_NONE;
+ const char *target = NULL;
+ DBusError err = {};
+
+ if (!dbus_message_get_args(msg, &err, CDBUS_TYPE_WINDOW, &wid, DBUS_TYPE_STRING,
+ &target, DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse argument of \"win_get\" (%s).", err.message);
+ dbus_error_free(&err);
+ return false;
+ }
+
+ auto w = find_managed_win(ps, wid);
+
+ if (!w) {
+ log_error("Window %#010x not found.", wid);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADWIN, CDBUS_ERROR_BADWIN_S, wid);
+ return true;
+ }
+
+#define cdbus_m_win_get_do(tgt, apdarg_func) \
+ if (!strcmp(#tgt, target)) { \
+ apdarg_func(ps, msg, w->tgt); \
+ return true; \
+ }
+
+ if (!strcmp(target, "id")) {
+ cdbus_reply_wid(ps, msg, w->base.id);
+ return true;
+ }
+
+ // next
+ if (!strcmp("next", target)) {
+ cdbus_reply_wid(
+ ps, msg,
+ (list_node_is_last(&ps->window_stack, &w->base.stack_neighbour)
+ ? 0
+ : list_entry(w->base.stack_neighbour.next, struct win, stack_neighbour)
+ ->id));
+ return true;
+ }
+
+ // map_state
+ if (!strcmp("map_state", target)) {
+ cdbus_reply_bool(ps, msg, w->a.map_state);
+ return true;
+ }
+
+ cdbus_m_win_get_do(mode, cdbus_reply_enum);
+ cdbus_m_win_get_do(client_win, cdbus_reply_wid);
+ cdbus_m_win_get_do(ever_damaged, cdbus_reply_bool);
+ cdbus_m_win_get_do(window_type, cdbus_reply_enum);
+ cdbus_m_win_get_do(wmwin, cdbus_reply_bool);
+ cdbus_m_win_get_do(leader, cdbus_reply_wid);
+ if (!strcmp("focused_raw", target)) {
+ cdbus_reply_bool(ps, msg, win_is_focused_raw(ps, w));
+ return true;
+ }
+ cdbus_m_win_get_do(fade_force, cdbus_reply_enum);
+ cdbus_m_win_get_do(shadow_force, cdbus_reply_enum);
+ cdbus_m_win_get_do(focused_force, cdbus_reply_enum);
+ cdbus_m_win_get_do(invert_color_force, cdbus_reply_enum);
+ cdbus_m_win_get_do(name, cdbus_reply_string);
+ cdbus_m_win_get_do(class_instance, cdbus_reply_string);
+ cdbus_m_win_get_do(class_general, cdbus_reply_string);
+ cdbus_m_win_get_do(role, cdbus_reply_string);
+
+ cdbus_m_win_get_do(opacity, cdbus_reply_double);
+ cdbus_m_win_get_do(opacity_target, cdbus_reply_double);
+ cdbus_m_win_get_do(has_opacity_prop, cdbus_reply_bool);
+ cdbus_m_win_get_do(opacity_prop, cdbus_reply_uint32);
+ cdbus_m_win_get_do(opacity_is_set, cdbus_reply_bool);
+ cdbus_m_win_get_do(opacity_set, cdbus_reply_double);
+
+ cdbus_m_win_get_do(frame_opacity, cdbus_reply_double);
+ if (!strcmp("left_width", target)) {
+ cdbus_reply_int32(ps, msg, w->frame_extents.left);
+ return true;
+ }
+ if (!strcmp("right_width", target)) {
+ cdbus_reply_int32(ps, msg, w->frame_extents.right);
+ return true;
+ }
+ if (!strcmp("top_width", target)) {
+ cdbus_reply_int32(ps, msg, w->frame_extents.top);
+ return true;
+ }
+ if (!strcmp("bottom_width", target)) {
+ cdbus_reply_int32(ps, msg, w->frame_extents.bottom);
+ return true;
+ }
+
+ cdbus_m_win_get_do(shadow, cdbus_reply_bool);
+ cdbus_m_win_get_do(invert_color, cdbus_reply_bool);
+ cdbus_m_win_get_do(blur_background, cdbus_reply_bool);
+#undef cdbus_m_win_get_do
+
+ log_error(CDBUS_ERROR_BADTGT_S, target);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADTGT, CDBUS_ERROR_BADTGT_S, target);
+
+ return true;
+}
+
+/**
+ * Process a win_set D-Bus request.
+ */
+static bool cdbus_process_win_set(session_t *ps, DBusMessage *msg) {
+ cdbus_window_t wid = XCB_NONE;
+ const char *target = NULL;
+ DBusError err = {};
+
+ if (!dbus_message_get_args(msg, &err, CDBUS_TYPE_WINDOW, &wid, DBUS_TYPE_STRING,
+ &target, DBUS_TYPE_INVALID)) {
+ log_error("(): Failed to parse argument of \"win_set\" (%s).", err.message);
+ dbus_error_free(&err);
+ return false;
+ }
+
+ auto w = find_managed_win(ps, wid);
+
+ if (!w) {
+ log_error("Window %#010x not found.", wid);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADWIN, CDBUS_ERROR_BADWIN_S, wid);
+ return true;
+ }
+
+#define cdbus_m_win_set_do(tgt, type, real_type) \
+ if (!strcmp(MSTR(tgt), target)) { \
+ real_type val; \
+ if (!cdbus_msg_get_arg(msg, 2, type, &val)) \
+ return false; \
+ w->tgt = val; \
+ goto cdbus_process_win_set_success; \
+ }
+
+ if (!strcmp("shadow_force", target)) {
+ cdbus_enum_t val = UNSET;
+ if (!cdbus_msg_get_arg(msg, 2, CDBUS_TYPE_ENUM, &val))
+ return false;
+ win_set_shadow_force(ps, w, val);
+ goto cdbus_process_win_set_success;
+ }
+
+ if (!strcmp("fade_force", target)) {
+ cdbus_enum_t val = UNSET;
+ if (!cdbus_msg_get_arg(msg, 2, CDBUS_TYPE_ENUM, &val))
+ return false;
+ win_set_fade_force(w, val);
+ goto cdbus_process_win_set_success;
+ }
+
+ if (!strcmp("focused_force", target)) {
+ cdbus_enum_t val = UNSET;
+ if (!cdbus_msg_get_arg(msg, 2, CDBUS_TYPE_ENUM, &val))
+ return false;
+ win_set_focused_force(ps, w, val);
+ goto cdbus_process_win_set_success;
+ }
+
+ if (!strcmp("invert_color_force", target)) {
+ cdbus_enum_t val = UNSET;
+ if (!cdbus_msg_get_arg(msg, 2, CDBUS_TYPE_ENUM, &val))
+ return false;
+ win_set_invert_color_force(ps, w, val);
+ goto cdbus_process_win_set_success;
+ }
+#undef cdbus_m_win_set_do
+
+ log_error(CDBUS_ERROR_BADTGT_S, target);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADTGT, CDBUS_ERROR_BADTGT_S, target);
+
+ return true;
+
+cdbus_process_win_set_success:
+ if (!dbus_message_get_no_reply(msg))
+ cdbus_reply_bool(ps, msg, true);
+ return true;
+}
+
+/**
+ * Process a find_win D-Bus request.
+ */
+static bool cdbus_process_find_win(session_t *ps, DBusMessage *msg) {
+ const char *target = NULL;
+
+ if (!cdbus_msg_get_arg(msg, 0, DBUS_TYPE_STRING, &target))
+ return false;
+
+ xcb_window_t wid = XCB_NONE;
+
+ // Find window by client window
+ if (!strcmp("client", target)) {
+ cdbus_window_t client = XCB_NONE;
+ if (!cdbus_msg_get_arg(msg, 1, CDBUS_TYPE_WINDOW, &client))
+ return false;
+ auto w = find_toplevel(ps, client);
+ if (w) {
+ wid = w->base.id;
+ }
+ }
+ // Find focused window
+ else if (!strcmp("focused", target)) {
+ if (ps->active_win && ps->active_win->state != WSTATE_UNMAPPED) {
+ wid = ps->active_win->base.id;
+ }
+ } else {
+ log_error(CDBUS_ERROR_BADTGT_S, target);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADTGT, CDBUS_ERROR_BADTGT_S, target);
+
+ return true;
+ }
+
+ cdbus_reply_wid(ps, msg, wid);
+
+ return true;
+}
+
+/**
+ * Process a opts_get D-Bus request.
+ */
+static bool cdbus_process_opts_get(session_t *ps, DBusMessage *msg) {
+ const char *target = NULL;
+
+ if (!cdbus_msg_get_arg(msg, 0, DBUS_TYPE_STRING, &target))
+ return false;
+
+#define cdbus_m_opts_get_do(tgt, apdarg_func) \
+ if (!strcmp(#tgt, target)) { \
+ apdarg_func(ps, msg, ps->o.tgt); \
+ return true; \
+ }
+
+#define cdbus_m_opts_get_stub(tgt, apdarg_func, ret) \
+ if (!strcmp(#tgt, target)) { \
+ apdarg_func(ps, msg, ret); \
+ return true; \
+ }
+
+ // version
+ if (!strcmp("version", target)) {
+ cdbus_reply_string(ps, msg, COMPTON_VERSION);
+ return true;
+ }
+
+ // pid
+ if (!strcmp("pid", target)) {
+ cdbus_reply_int32(ps, msg, getpid());
+ return true;
+ }
+
+ // display
+ if (!strcmp("display", target)) {
+ cdbus_reply_string(ps, msg, DisplayString(ps->dpy));
+ return true;
+ }
+
+ cdbus_m_opts_get_stub(config_file, cdbus_reply_string, "Unknown");
+ cdbus_m_opts_get_do(write_pid_path, cdbus_reply_string);
+ cdbus_m_opts_get_do(mark_wmwin_focused, cdbus_reply_bool);
+ cdbus_m_opts_get_do(mark_ovredir_focused, cdbus_reply_bool);
+ cdbus_m_opts_get_do(detect_rounded_corners, cdbus_reply_bool);
+ cdbus_m_opts_get_stub(paint_on_overlay, cdbus_reply_bool, ps->overlay != XCB_NONE);
+ // paint_on_overlay_id: Get ID of the X composite overlay window
+ if (!strcmp("paint_on_overlay_id", target)) {
+ cdbus_reply_uint32(ps, msg, ps->overlay);
+ return true;
+ }
+ cdbus_m_opts_get_do(unredir_if_possible, cdbus_reply_bool);
+ cdbus_m_opts_get_do(unredir_if_possible_delay, cdbus_reply_int32l);
+ cdbus_m_opts_get_do(redirected_force, cdbus_reply_enum);
+ cdbus_m_opts_get_do(stoppaint_force, cdbus_reply_enum);
+ cdbus_m_opts_get_do(logpath, cdbus_reply_string);
+
+ cdbus_m_opts_get_stub(refresh_rate, cdbus_reply_int32, 0);
+ cdbus_m_opts_get_stub(sw_opti, cdbus_reply_bool, false);
+ cdbus_m_opts_get_do(vsync, cdbus_reply_bool);
+ if (!strcmp("backend", target)) {
+ assert(ps->o.backend < sizeof(BACKEND_STRS) / sizeof(BACKEND_STRS[0]));
+ cdbus_reply_string(ps, msg, BACKEND_STRS[ps->o.backend]);
+ return true;
+ }
+
+ cdbus_m_opts_get_do(shadow_red, cdbus_reply_double);
+ cdbus_m_opts_get_do(shadow_green, cdbus_reply_double);
+ cdbus_m_opts_get_do(shadow_blue, cdbus_reply_double);
+ cdbus_m_opts_get_do(shadow_radius, cdbus_reply_int32);
+ cdbus_m_opts_get_do(shadow_offset_x, cdbus_reply_int32);
+ cdbus_m_opts_get_do(shadow_offset_y, cdbus_reply_int32);
+ cdbus_m_opts_get_do(shadow_opacity, cdbus_reply_double);
+ cdbus_m_opts_get_do(xinerama_shadow_crop, cdbus_reply_bool);
+
+ cdbus_m_opts_get_do(fade_delta, cdbus_reply_int32);
+ cdbus_m_opts_get_do(fade_in_step, cdbus_reply_double);
+ cdbus_m_opts_get_do(fade_out_step, cdbus_reply_double);
+ cdbus_m_opts_get_do(no_fading_openclose, cdbus_reply_bool);
+
+ cdbus_m_opts_get_do(blur_method, cdbus_reply_bool);
+ cdbus_m_opts_get_do(blur_background_frame, cdbus_reply_bool);
+ cdbus_m_opts_get_do(blur_background_fixed, cdbus_reply_bool);
+
+ cdbus_m_opts_get_do(inactive_dim, cdbus_reply_double);
+ cdbus_m_opts_get_do(inactive_dim_fixed, cdbus_reply_bool);
+
+ cdbus_m_opts_get_do(max_brightness, cdbus_reply_double);
+
+ cdbus_m_opts_get_do(use_ewmh_active_win, cdbus_reply_bool);
+ cdbus_m_opts_get_do(detect_transient, cdbus_reply_bool);
+ cdbus_m_opts_get_do(detect_client_leader, cdbus_reply_bool);
+ cdbus_m_opts_get_do(use_damage, cdbus_reply_bool);
+
+#ifdef CONFIG_OPENGL
+ cdbus_m_opts_get_do(glx_no_stencil, cdbus_reply_bool);
+ cdbus_m_opts_get_do(glx_no_rebind_pixmap, cdbus_reply_bool);
+#endif
+
+#undef cdbus_m_opts_get_do
+#undef cdbus_m_opts_get_stub
+
+ log_error(CDBUS_ERROR_BADTGT_S, target);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADTGT, CDBUS_ERROR_BADTGT_S, target);
+
+ return true;
+}
+
+// XXX Remove this after header clean up
+void queue_redraw(session_t *ps);
+
+/**
+ * Process a opts_set D-Bus request.
+ */
+static bool cdbus_process_opts_set(session_t *ps, DBusMessage *msg) {
+ const char *target = NULL;
+
+ if (!cdbus_msg_get_arg(msg, 0, DBUS_TYPE_STRING, &target))
+ return false;
+
+#define cdbus_m_opts_set_do(tgt, type, real_type) \
+ if (!strcmp(#tgt, target)) { \
+ real_type val; \
+ if (!cdbus_msg_get_arg(msg, 1, type, &val)) \
+ return false; \
+ ps->o.tgt = val; \
+ goto cdbus_process_opts_set_success; \
+ }
+
+ // fade_delta
+ if (!strcmp("fade_delta", target)) {
+ int32_t val = 0;
+ if (!cdbus_msg_get_arg(msg, 1, DBUS_TYPE_INT32, &val)) {
+ return false;
+ }
+ if (val <= 0) {
+ return false;
+ }
+ ps->o.fade_delta = max2(val, 1);
+ goto cdbus_process_opts_set_success;
+ }
+
+ // fade_in_step
+ if (!strcmp("fade_in_step", target)) {
+ double val = 0.0;
+ if (!cdbus_msg_get_arg(msg, 1, DBUS_TYPE_DOUBLE, &val))
+ return false;
+ ps->o.fade_in_step = normalize_d(val);
+ goto cdbus_process_opts_set_success;
+ }
+
+ // fade_out_step
+ if (!strcmp("fade_out_step", target)) {
+ double val = 0.0;
+ if (!cdbus_msg_get_arg(msg, 1, DBUS_TYPE_DOUBLE, &val))
+ return false;
+ ps->o.fade_out_step = normalize_d(val);
+ goto cdbus_process_opts_set_success;
+ }
+
+ // no_fading_openclose
+ if (!strcmp("no_fading_openclose", target)) {
+ dbus_bool_t val = FALSE;
+ if (!cdbus_msg_get_arg(msg, 1, DBUS_TYPE_BOOLEAN, &val))
+ return false;
+ opts_set_no_fading_openclose(ps, val);
+ goto cdbus_process_opts_set_success;
+ }
+
+ // unredir_if_possible
+ if (!strcmp("unredir_if_possible", target)) {
+ dbus_bool_t val = FALSE;
+ if (!cdbus_msg_get_arg(msg, 1, DBUS_TYPE_BOOLEAN, &val))
+ return false;
+ if (ps->o.unredir_if_possible != val) {
+ ps->o.unredir_if_possible = val;
+ queue_redraw(ps);
+ }
+ goto cdbus_process_opts_set_success;
+ }
+
+ // clear_shadow
+ if (!strcmp("clear_shadow", target)) {
+ goto cdbus_process_opts_set_success;
+ }
+
+ // track_focus
+ if (!strcmp("track_focus", target)) {
+ goto cdbus_process_opts_set_success;
+ }
+
+ // redirected_force
+ if (!strcmp("redirected_force", target)) {
+ cdbus_enum_t val = UNSET;
+ if (!cdbus_msg_get_arg(msg, 1, CDBUS_TYPE_ENUM, &val))
+ return false;
+ ps->o.redirected_force = val;
+ force_repaint(ps);
+ goto cdbus_process_opts_set_success;
+ }
+
+ // stoppaint_force
+ cdbus_m_opts_set_do(stoppaint_force, CDBUS_TYPE_ENUM, cdbus_enum_t);
+
+#undef cdbus_m_opts_set_do
+
+ log_error(CDBUS_ERROR_BADTGT_S, target);
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADTGT, CDBUS_ERROR_BADTGT_S, target);
+
+ return true;
+
+cdbus_process_opts_set_success:
+ if (!dbus_message_get_no_reply(msg))
+ cdbus_reply_bool(ps, msg, true);
+ return true;
+}
+
+/**
+ * Process an Introspect D-Bus request.
+ */
+static bool cdbus_process_introspect(session_t *ps, DBusMessage *msg) {
+ static const char *str_introspect =
+ "\n"
+ "\n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ "\n";
+
+ cdbus_reply_string(ps, msg, str_introspect);
+
+ return true;
+}
+///@}
+
+/**
+ * Process an D-Bus Introspect request, for /windows.
+ */
+static bool cdbus_process_windows_root_introspect(session_t *ps, DBusMessage *msg) {
+ static const char *str_introspect =
+ "\n"
+ "\n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n";
+
+ char *ret = NULL;
+ mstrextend(&ret, str_introspect);
+
+ HASH_ITER2(ps->windows, w) {
+ assert(!w->destroyed);
+ if (!w->managed) {
+ continue;
+ }
+ char *tmp = NULL;
+ asprintf(&tmp, "\n", w->id);
+ mstrextend(&ret, tmp);
+ free(tmp);
+ }
+ mstrextend(&ret, "");
+
+ bool success = cdbus_reply_string(ps, msg, ret);
+ free(ret);
+ return success;
+}
+
+static bool cdbus_process_window_introspect(session_t *ps, DBusMessage *msg) {
+ // clang-format off
+ static const char *str_introspect =
+ "\n"
+ "\n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ "\n";
+ // clang-format on
+
+ return cdbus_reply_string(ps, msg, str_introspect);
+}
+
+/**
+ * Process a message from D-Bus.
+ */
+static DBusHandlerResult
+cdbus_process(DBusConnection *c attr_unused, DBusMessage *msg, void *ud) {
+ session_t *ps = ud;
+ bool handled = false;
+
+#define cdbus_m_ismethod(method) \
+ dbus_message_is_method_call(msg, CDBUS_INTERFACE_NAME, method)
+
+ if (cdbus_m_ismethod("reset")) {
+ log_info("picom is resetting...");
+ ev_break(ps->loop, EVBREAK_ALL);
+ if (!dbus_message_get_no_reply(msg))
+ cdbus_reply_bool(ps, msg, true);
+ handled = true;
+ } else if (cdbus_m_ismethod("repaint")) {
+ force_repaint(ps);
+ if (!dbus_message_get_no_reply(msg))
+ cdbus_reply_bool(ps, msg, true);
+ handled = true;
+ } else if (cdbus_m_ismethod("list_win")) {
+ handled = cdbus_process_list_win(ps, msg);
+ } else if (cdbus_m_ismethod("win_get")) {
+ handled = cdbus_process_win_get(ps, msg);
+ } else if (cdbus_m_ismethod("win_set")) {
+ handled = cdbus_process_win_set(ps, msg);
+ } else if (cdbus_m_ismethod("find_win")) {
+ handled = cdbus_process_find_win(ps, msg);
+ } else if (cdbus_m_ismethod("opts_get")) {
+ handled = cdbus_process_opts_get(ps, msg);
+ } else if (cdbus_m_ismethod("opts_set")) {
+ handled = cdbus_process_opts_set(ps, msg);
+ }
+#undef cdbus_m_ismethod
+ else if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Introspectable",
+ "Introspect")) {
+ handled = cdbus_process_introspect(ps, msg);
+ } else if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Peer", "Ping")) {
+ cdbus_reply(ps, msg, NULL, NULL);
+ handled = true;
+ } else if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Peer",
+ "GetMachineId")) {
+ char *uuid = dbus_get_local_machine_id();
+ if (uuid) {
+ cdbus_reply_string(ps, msg, uuid);
+ dbus_free(uuid);
+ handled = true;
+ }
+ } else if (dbus_message_is_signal(msg, "org.freedesktop.DBus", "NameAcquired") ||
+ dbus_message_is_signal(msg, "org.freedesktop.DBus", "NameLost")) {
+ handled = true;
+ } else {
+ if (DBUS_MESSAGE_TYPE_ERROR == dbus_message_get_type(msg)) {
+ log_error(
+ "Error message of path \"%s\" "
+ "interface \"%s\", member \"%s\", error \"%s\"",
+ dbus_message_get_path(msg), dbus_message_get_interface(msg),
+ dbus_message_get_member(msg), dbus_message_get_error_name(msg));
+ } else {
+ log_error("Illegal message of type \"%s\", path \"%s\" "
+ "interface \"%s\", member \"%s\"",
+ cdbus_repr_msgtype(msg), dbus_message_get_path(msg),
+ dbus_message_get_interface(msg),
+ dbus_message_get_member(msg));
+ }
+ if (DBUS_MESSAGE_TYPE_METHOD_CALL == dbus_message_get_type(msg) &&
+ !dbus_message_get_no_reply(msg))
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADMSG, CDBUS_ERROR_BADMSG_S);
+ handled = true;
+ }
+
+ // If the message could not be processed, and an reply is expected, return
+ // an empty reply.
+ if (!handled && DBUS_MESSAGE_TYPE_METHOD_CALL == dbus_message_get_type(msg) &&
+ !dbus_message_get_no_reply(msg)) {
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_UNKNOWN, CDBUS_ERROR_UNKNOWN_S);
+ handled = true;
+ }
+
+ return handled ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+/**
+ * Process a message from D-Bus, for /windows path.
+ */
+static DBusHandlerResult
+cdbus_process_windows(DBusConnection *c attr_unused, DBusMessage *msg, void *ud) {
+ session_t *ps = ud;
+ bool handled = false;
+ const char *path = dbus_message_get_path(msg);
+ const char *last_segment = strrchr(path, '/');
+ if (last_segment == NULL) {
+ if (DBUS_MESSAGE_TYPE_METHOD_CALL == dbus_message_get_type(msg) &&
+ !dbus_message_get_no_reply(msg))
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_BADMSG, CDBUS_ERROR_BADMSG_S);
+ return DBUS_HANDLER_RESULT_HANDLED;
+ }
+ bool is_root = strncmp(last_segment, "/windows", 8) == 0;
+ if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Introspectable",
+ "Introspect")) {
+ if (is_root) {
+ handled = cdbus_process_windows_root_introspect(ps, msg);
+ } else {
+ handled = cdbus_process_window_introspect(ps, msg);
+ }
+ goto finished;
+ }
+
+ if (!is_root) {
+ auto wid = (cdbus_window_t)strtol(last_segment + 1, NULL, 0);
+ if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Properties",
+ "GetAll")) {
+ handled = cdbus_reply(ps, msg, cdbus_append_empty_dict, NULL);
+ goto finished;
+ }
+
+ if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Properties", "Get")) {
+ handled = cdbus_process_window_property_get(ps, msg, wid);
+ goto finished;
+ }
+ }
+
+ if (dbus_message_is_signal(msg, "org.freedesktop.DBus", "NameAcquired") ||
+ dbus_message_is_signal(msg, "org.freedesktop.DBus", "NameLost")) {
+ return DBUS_HANDLER_RESULT_HANDLED;
+ }
+
+ if (DBUS_MESSAGE_TYPE_ERROR == dbus_message_get_type(msg)) {
+ log_error("Error message of path \"%s\" "
+ "interface \"%s\", member \"%s\", error \"%s\"",
+ dbus_message_get_path(msg), dbus_message_get_interface(msg),
+ dbus_message_get_member(msg), dbus_message_get_error_name(msg));
+ } else {
+ log_error("Illegal message of type \"%s\", path \"%s\" "
+ "interface \"%s\", member \"%s\"",
+ cdbus_repr_msgtype(msg), dbus_message_get_path(msg),
+ dbus_message_get_interface(msg), dbus_message_get_member(msg));
+ }
+ if (DBUS_MESSAGE_TYPE_METHOD_CALL == dbus_message_get_type(msg) &&
+ !dbus_message_get_no_reply(msg)) {
+ handled = cdbus_reply_err(ps, msg, CDBUS_ERROR_BADMSG, CDBUS_ERROR_BADMSG_S);
+ }
+
+finished:
+ if (!handled && dbus_message_get_type(msg) == DBUS_MESSAGE_TYPE_METHOD_CALL &&
+ !dbus_message_get_no_reply(msg)) {
+ handled =
+ cdbus_reply_err(ps, msg, CDBUS_ERROR_UNKNOWN, CDBUS_ERROR_UNKNOWN_S);
+ }
+ return handled ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+/** @name Core callbacks
+ */
+///@{
+void cdbus_ev_win_added(session_t *ps, struct win *w) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (cd->dbus_conn) {
+ cdbus_signal_wid(ps, CDBUS_INTERFACE_NAME, "win_added", w->id);
+ cdbus_signal_wid(ps, PICOM_COMPOSITOR_INTERFACE, "WinAdded", w->id);
+ }
+}
+
+void cdbus_ev_win_destroyed(session_t *ps, struct win *w) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (cd->dbus_conn) {
+ cdbus_signal_wid(ps, CDBUS_INTERFACE_NAME, "win_destroyed", w->id);
+ cdbus_signal_wid(ps, PICOM_COMPOSITOR_INTERFACE, "WinDestroyed", w->id);
+ }
+}
+
+void cdbus_ev_win_mapped(session_t *ps, struct win *w) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (cd->dbus_conn) {
+ cdbus_signal_wid(ps, CDBUS_INTERFACE_NAME, "win_mapped", w->id);
+ cdbus_signal_wid(ps, PICOM_COMPOSITOR_INTERFACE, "WinMapped", w->id);
+ }
+}
+
+void cdbus_ev_win_unmapped(session_t *ps, struct win *w) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (cd->dbus_conn) {
+ cdbus_signal_wid(ps, CDBUS_INTERFACE_NAME, "win_unmapped", w->id);
+ cdbus_signal_wid(ps, PICOM_COMPOSITOR_INTERFACE, "WinUnmapped", w->id);
+ }
+}
+
+void cdbus_ev_win_focusout(session_t *ps, struct win *w) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (cd->dbus_conn) {
+ cdbus_signal_wid(ps, CDBUS_INTERFACE_NAME, "win_focusout", w->id);
+ }
+}
+
+void cdbus_ev_win_focusin(session_t *ps, struct win *w) {
+ struct cdbus_data *cd = ps->dbus_data;
+ if (cd->dbus_conn) {
+ cdbus_signal_wid(ps, CDBUS_INTERFACE_NAME, "win_focusin", w->id);
+ }
+}
+//!@}
diff --git a/dwm/picom/src/dbus.h b/dwm/picom/src/dbus.h
new file mode 100644
index 0000000..54a58af
--- /dev/null
+++ b/dwm/picom/src/dbus.h
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: MIT
+/*
+ * Compton - a compositor for X11
+ *
+ * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
+ *
+ * Copyright (c) 2011-2013, Christopher Jeffrey
+ * See LICENSE-mit for more information.
+ *
+ */
+
+#include
+
+#include
+
+typedef struct session session_t;
+struct win;
+
+/**
+ * Return a string representation of a D-Bus message type.
+ */
+static inline const char *cdbus_repr_msgtype(DBusMessage *msg) {
+ return dbus_message_type_to_string(dbus_message_get_type(msg));
+}
+
+/**
+ * Initialize D-Bus connection.
+ */
+bool cdbus_init(session_t *ps, const char *uniq_name);
+
+/**
+ * Destroy D-Bus connection.
+ */
+void cdbus_destroy(session_t *ps);
+
+/// Generate dbus win_added signal
+void cdbus_ev_win_added(session_t *ps, struct win *w);
+
+/// Generate dbus win_destroyed signal
+void cdbus_ev_win_destroyed(session_t *ps, struct win *w);
+
+/// Generate dbus win_mapped signal
+void cdbus_ev_win_mapped(session_t *ps, struct win *w);
+
+/// Generate dbus win_unmapped signal
+void cdbus_ev_win_unmapped(session_t *ps, struct win *w);
+
+/// Generate dbus win_focusout signal
+void cdbus_ev_win_focusout(session_t *ps, struct win *w);
+
+/// Generate dbus win_focusin signal
+void cdbus_ev_win_focusin(session_t *ps, struct win *w);
+
+// vim: set noet sw=8 ts=8 :
diff --git a/dwm/picom/src/diagnostic.c b/dwm/picom/src/diagnostic.c
new file mode 100644
index 0000000..d275b1a
--- /dev/null
+++ b/dwm/picom/src/diagnostic.c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) 2018 Yuxuan Shui
+
+#include
+#include
+#include
+
+#include "backend/driver.h"
+#include "diagnostic.h"
+#include "config.h"
+#include "picom.h"
+#include "common.h"
+
+void print_diagnostics(session_t *ps, const char *config_file, bool compositor_running) {
+ printf("**Version:** " COMPTON_VERSION "\n");
+ //printf("**CFLAGS:** %s\n", "??");
+ printf("\n### Extensions:\n\n");
+ printf("* Shape: %s\n", ps->shape_exists ? "Yes" : "No");
+ printf("* XRandR: %s\n", ps->randr_exists ? "Yes" : "No");
+ printf("* Present: %s\n", ps->present_exists ? "Present" : "Not Present");
+ printf("\n### Misc:\n\n");
+ printf("* Use Overlay: %s\n", ps->overlay != XCB_NONE ? "Yes" : "No");
+ if (ps->overlay == XCB_NONE) {
+ if (compositor_running) {
+ printf(" (Another compositor is already running)\n");
+ } else if (session_redirection_mode(ps) != XCB_COMPOSITE_REDIRECT_MANUAL) {
+ printf(" (Not in manual redirection mode)\n");
+ } else {
+ printf("\n");
+ }
+ }
+#ifdef __FAST_MATH__
+ printf("* Fast Math: Yes\n");
+#endif
+ printf("* Config file used: %s\n", config_file ?: "None");
+ printf("\n### Drivers (inaccurate):\n\n");
+ print_drivers(ps->drivers);
+
+ for (int i = 0; i < NUM_BKEND; i++) {
+ if (backend_list[i] && backend_list[i]->diagnostics) {
+ printf("\n### Backend: %s\n\n", BACKEND_STRS[i]);
+ auto data = backend_list[i]->init(ps);
+ if (!data) {
+ printf(" Cannot initialize this backend\n");
+ } else {
+ backend_list[i]->diagnostics(data);
+ backend_list[i]->deinit(data);
+ }
+ }
+ }
+}
+
+// vim: set noet sw=8 ts=8 :
diff --git a/dwm/picom/src/diagnostic.h b/dwm/picom/src/diagnostic.h
new file mode 100644
index 0000000..c958589
--- /dev/null
+++ b/dwm/picom/src/diagnostic.h
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) 2018 Yuxuan Shui
+
+#pragma once
+#include
+
+typedef struct session session_t;
+
+void print_diagnostics(session_t *, const char *config_file, bool compositor_running);
diff --git a/dwm/picom/src/err.h b/dwm/picom/src/err.h
new file mode 100644
index 0000000..f989bf9
--- /dev/null
+++ b/dwm/picom/src/err.h
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright (c) 2019 Yuxuan Shui