summaryrefslogtreecommitdiff
path: root/swap_workspaces
blob: 9269e4a01cb6e92f3f285190815a11ffafb76b29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/bash

current_workspace() {
	wmctrl -d | awk '{print $1" "$2}' | grep "*" | awk '{print $1}'
}

workspace_exists() {
	wmctrl -d | awk '{print $1}' | grep -w -- "${1}"
}

workspace_windows() {
	wmctrl -l | {
		while IFS= read -r line; do
			local parts=($line)
			local id="${parts[@]:0:1}"
			local workspace=${parts[@]:1:1}
			if [[ "$workspace" != "$1" ]]; then
				continue
			fi
			echo "$id"
		done
	}
}

move_window() {
	wmctrl -i -r "$1" -t "$2"
}

usage() {
	cat <<-_EOF
	A program to move all windows from workspace <1> to workspace <2>.

	If the first workspace is not specified, current workspace is assumed.
	Workspace numbering starts with 0.

	This is useful when you want to reorder workspaces but your DE doesn't have such
	feature.

	Usage:
	    $(basename "$0") [<1>] <2>

	Dependencies:
	    wmctrl
	_EOF
	exit 1
}

FROM=$1
TO=$2

if [ ! -x "$(command -v wmctrl)" ]; then
	echo "Please make sure that wmctrl is installed."
	exit 1
fi

if [ -z "$TO" ]; then
	if [ -z "$FROM" ]; then
		usage
	fi
	TO="$FROM"
	FROM=$(current_workspace)
fi

if [ "$FROM" == "$TO" ]; then
	exit
fi

if [[ ! $(workspace_exists "$FROM") ]]; then
	echo "workspace $FROM not found"
	exit 1
elif [[ ! $(workspace_exists "$TO") ]]; then
	echo "workspace $TO not found"
	exit 1
fi

WINDOWS_FROM=($(workspace_windows "$FROM"))
WINDOWS_TO=($(workspace_windows "$TO"))

for id in "${WINDOWS_FROM[@]}"; do
	move_window "$id" "$TO"
done

for id in "${WINDOWS_TO[@]}"; do
	move_window "$id" "$FROM"
done