Skip to content

Commit

Permalink
feat(arch): improve focus_or_run.sh
Browse files Browse the repository at this point in the history
Chromium seems to spawn multiple windows, only one of which is focusable
with xdotool windowactivate. Add a function to filter found windows for
the appropriate one if the initial focusing operation fails.
  • Loading branch information
eliasnorrby committed Nov 25, 2020
1 parent 7ac3118 commit 0546b90
Showing 1 changed file with 50 additions and 11 deletions.
61 changes: 50 additions & 11 deletions base/arch/focus_or_run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,58 @@

# Usage: focus_or_run program [class]

_is_callable () {
# Will search windows based on 'class' (defaults to 'program').
# If a window is found, it is focused, otherwise the program is
# executed.

_is_callable() {
command -v "$1" >/dev/null || return 1
}

CLASS=${2:-$1}
PROGRAM=$1
_focus_or_run() {
CLASS=${2:-$1}
PROGRAM=$1

WINDOWS=$(xdotool search --class "$CLASS")

if [ -n "$WINDOWS" ]; then
RESULT=$(xdotool windowactivate "$WINDOWS" 2>&1 >/dev/null)
if echo "$RESULT" | grep failed >/dev/null; then
_try_harder "$WINDOWS"
fi
elif _is_callable "$PROGRAM"; then
exec "$PROGRAM"
else
echo "Could not focus or run: $PROGRAM"
fi
}

# There will be multiple matches for some calls, e.g:
# xdotool search --class chromium
# Only one ID will work for focusing - the one corresponding
# to the window with _NET_WM_DESKTOP specified. We need to find
# the appropriate ID and pass it to xdotool windowactivate.

WINDOW=$(xdotool search --class --limit 1 "$CLASS")
# xprop is used to fetch the property for each window id.
# The result is either
# _NET_WM_DESKTOP: not found.
# or
# _NET_WM_DESKTOP(CARDINAL) = <number>

# We grep this string for '=' to find our ID.
_try_harder() {
while read -r wid; do
if _specifies_desktop "$wid"; then
xdotool windowactivate "$wid"
exit
fi
done <<EOF
$1
EOF
}

_specifies_desktop() {
xprop -id "$1" _NET_WM_DESKTOP | grep '=' >/dev/null
}

if [ -n "$WINDOW" ] ; then
xdotool windowactivate "$WINDOW"
elif _is_callable "$PROGRAM" ; then
exec "$PROGRAM"
else
echo "Could not focus or run: $PROGRAM"
fi
_focus_or_run "$@"

0 comments on commit 0546b90

Please sign in to comment.