10 Commits

Author SHA1 Message Date
feba0f3580 bump version 2025-08-25 09:53:53 +02:00
2fbb3ebc59 add doc about prev flag 2025-08-25 09:53:40 +02:00
T.v.Dein
8e48b42bad enhance window switch debugging (#4) 2025-08-25 09:02:14 +02:00
kkvark
7a5657b778 add --prev option and sort floating_nodes (#3)
* add --prev option
* sort floating_nodes to avoid skipping floating windows
2025-08-25 08:59:21 +02:00
0bdef90f97 swich to i3ipc library 2025-08-15 12:32:33 +02:00
3402df69b4 Merge branch 'main' of github.com:TLINDEN/swaycycle 2025-08-14 20:51:39 +02:00
b21d8ebed9 duplicate error check 2025-08-14 20:51:14 +02:00
Thomas von Dein
a481cc7172 get rid screenshot, doesnt help anyone 2025-08-12 21:39:17 +02:00
Thomas von Dein
cb8421e6f6 cleanup doc 2025-08-12 21:38:24 +02:00
051b68c266 little doc tweaks 2025-08-12 18:34:26 +02:00
5 changed files with 88 additions and 180 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

View File

@@ -5,12 +5,11 @@ floating ones or windows in sub-containers. So it simulates the
behavior of other window managers and desktop environments. Just bind
the tool to `ALT-tab` and there you go.
![Screenshot](https://github.com/TLINDEN/swaycycle/blob/main/.github/assets/screenshot.png)
## Installation
Download the binary for your architecture from the [release
page](https://github.com/TLINDEN/swaycycle/releases) and copy to to to
page](https://github.com/TLINDEN/swaycycle/releases) and copy to
some location within your `$PATH`.
To build the tool from source, checkout the repo and execute
@@ -25,6 +24,13 @@ Add such a line to your sway config file (e.g. in `$HOME/.config/sway/config`):
bindsym $mod+Tab exec ~/bin/swaycycle
```
You may also add a second key binding to do the reverse, which is
sometimes very useful:
```default
bindsym $mod+Shift+Tab exec ~/bin/swaycycle --prev
```
## Debugging
You may call `swaycycle` in a terminal window on a workspace with at
@@ -76,7 +82,7 @@ https://github.com/tlinden/swaycycle/issues.
- [sway-ipc(7)](https://www.mankier.com/7/sway-ipc)
- [swaywm](https://github.com/swaywm/sway/)
- [swayfs](https://github.com/WillPower3309/swayfx)
- [swayfx](https://github.com/WillPower3309/swayfx)
## Copyright and license

1
go.mod
View File

@@ -9,6 +9,7 @@ require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/spf13/pflag v1.0.7 // indirect
github.com/tlinden/i3ipc v0.0.0-20250815101608-4f7e27528be3 // indirect
github.com/tlinden/yadu v0.1.3 // indirect
golang.org/x/sys v0.14.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect

2
go.sum
View File

@@ -11,6 +11,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M=
github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/tlinden/i3ipc v0.0.0-20250815101608-4f7e27528be3 h1:/kIZO4852sAVemXtqnsBid0r4Q1h87jDwHa8f7v1h5I=
github.com/tlinden/i3ipc v0.0.0-20250815101608-4f7e27528be3/go.mod h1:mc0toDHmgqgX6FpE69U5yMPnHuLTdekHRslSLDp8xSE=
github.com/tlinden/yadu v0.1.3 h1:5cRCUmj+l5yvlM2irtpFBIJwVV2DPEgYSaWvF19FtcY=
github.com/tlinden/yadu v0.1.3/go.mod h1:l3bRmHKL9zGAR6pnBHY2HRPxBecf7L74BoBgOOpTcUA=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

253
main.go
View File

@@ -18,42 +18,22 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"net"
"os"
"runtime/debug"
"sort"
"github.com/lmittmann/tint"
"github.com/mattn/go-isatty"
"github.com/tlinden/i3ipc"
"github.com/tlinden/yadu"
flag "github.com/spf13/pflag"
)
type Node struct {
Id int `json:"id"`
Nodetype string `json:"type"` // output, workspace or container
Name string `json:"name"` // workspace number or app name
Nodes []Node `json:"nodes"`
FloatingNodes []Node `json:"floating_nodes"`
Focused bool `json:"focused"`
Window int `json:"window"` // wayland native
X11Window string `json:"app_id"` // x11 compat
Current_workspace string `json:"current_workspace"`
}
type Response struct {
Success bool `json:"success"`
ParseError bool `json:"parse_error"`
Error string `json:"error"`
}
const (
root = iota + 1
output
@@ -63,7 +43,7 @@ const (
LevelNotice = slog.Level(2)
VERSION = "v0.2.0"
VERSION = "v0.3.1"
IPC_HEADER_SIZE = 14
IPC_MAGIC = "i3-ipc"
@@ -74,10 +54,12 @@ const (
)
var (
Visibles = []Node{}
Visibles = []*i3ipc.Node{}
CurrentWorkspace = ""
Previous = false
Debug = false
Dumptree = false
Dumpvisibles = false
Version = false
Verbose = false
Notswitch = false
@@ -90,9 +72,11 @@ const Usage string = `This is swaycycle - cycle focus through all visible window
Usage: swaycycle [-vdDn] [-l <log>]
Options:
-p, --prev cycle backward
-n, --no-switch do not switch windows
-d, --debug enable debugging
-D, --dump dump the sway tree (needs -d as well)
--dump-visibles dump a list of visible windows on current workspace (needs -d)
-l, --logfile string write output to logfile
-v, --version show program version
@@ -101,8 +85,10 @@ Licensed under the terms of the GNU GPL version 3.
`
func main() {
flag.BoolVarP(&Previous, "prev", "p", false, "cycle backward")
flag.BoolVarP(&Debug, "debug", "d", false, "enable debugging")
flag.BoolVarP(&Dumptree, "dump", "D", false, "dump the sway tree (needs -d as well)")
flag.BoolVarP(&Dumpvisibles, "dump-visibles", "", false, "dump a list of visible windows on current workspace (needs -d)")
flag.BoolVarP(&Notswitch, "no-switch", "n", false, "do not switch windows")
flag.BoolVarP(&Version, "version", "v", false, "show program version")
flag.BoolVarP(&Showhelp, "help", "h", Showhelp, "show help")
@@ -133,19 +119,21 @@ func main() {
}
// connect to sway unix socket
unixsock, err := setupIPC()
if err != nil {
log.Fatalf("Failed to connect to sway unix socket: %s", err)
}
ipc := i3ipc.NewI3ipc()
// retrieve the raw json tree
rawjson, err := getTree(unixsock)
err := ipc.Connect()
if err != nil {
log.Fatalf("Failed to retrieve raw json tree: %s", err)
log.Fatal(err)
}
defer ipc.Close()
sway, err := ipc.GetTree()
if err != nil {
log.Fatal(err)
}
// traverse the tree and find visible windows
if err := processJSON(rawjson); err != nil {
if err := processJSON(sway); err != nil {
log.Fatalf("%s", err)
}
@@ -153,114 +141,23 @@ func main() {
os.Exit(0)
}
id := findNextWindow()
slog.Debug("findNextWindow", "nextid", id)
id := 0
if Previous {
id = findPrevWindow()
slog.Debug("findPrevWindow", "nextid", id)
} else {
id = findNextWindow()
slog.Debug("findNextWindow", "nextid", id)
}
if id > 0 && !Notswitch {
switchFocus(id, unixsock)
switchFocus(id, ipc)
}
}
// connect to unix socket
func setupIPC() (net.Conn, error) {
sockfile := os.Getenv("SWAYSOCK")
if sockfile == "" {
return nil, fmt.Errorf("Environment variable SWAYSOCK does not exist or is empty")
}
conn, err := net.Dial("unix", sockfile)
if err != nil {
return nil, err
}
return conn, nil
}
// send a sway message header
func sendHeaderIPC(sock net.Conn, messageType uint32, len uint32) error {
sendPayload := make([]byte, IPC_HEADER_SIZE)
copy(sendPayload, []byte(IPC_MAGIC))
binary.LittleEndian.PutUint32(sendPayload[6:], len)
binary.LittleEndian.PutUint32(sendPayload[10:], messageType)
_, err := sock.Write(sendPayload)
if err != nil {
return fmt.Errorf("failed to send header to IPC %w", err)
}
return nil
}
// send a payload, header had to be sent before
func sendPayloadIPC(sock net.Conn, payload []byte) error {
_, err := sock.Write(payload)
if err != nil {
return fmt.Errorf("failed to send payload to IPC %w", err)
}
return nil
}
// read a response, reads response header and returns payload only
func readResponseIPC(sock net.Conn) ([]byte, error) {
// read header
buf := make([]byte, IPC_HEADER_SIZE)
_, err := sock.Read(buf)
if err != nil {
return nil, fmt.Errorf("failed to read header from socket: %s", err)
}
slog.Debug("got IPC header", "header", hex.EncodeToString(buf))
if string(buf[:6]) != IPC_MAGIC {
return nil, fmt.Errorf("got invalid IPC response from sway socket")
}
payloadLen := binary.LittleEndian.Uint32(buf[6:10])
if payloadLen == 0 {
return nil, fmt.Errorf("got empty payload IPC response from sway socket")
}
// read payload
payload := make([]byte, payloadLen)
_, err = sock.Read(payload)
if err != nil {
return nil, fmt.Errorf("failed to read payload from socket: %s", err)
}
return payload, nil
}
// get raw JSON tree via sway IPC
func getTree(sock net.Conn) ([]byte, error) {
err := sendHeaderIPC(sock, IPC_GET_TREE, 0)
if err != nil {
return nil, err
}
payload, err := readResponseIPC(sock)
if err != nil {
return nil, err
}
return payload, nil
}
// get into the sway tree, determine current workspace and extract all
// its visible windows, store them in the global var Visibles
func processJSON(jsoncode []byte) error {
sway := Node{}
if err := json.Unmarshal(jsoncode, &sway); err != nil {
return fmt.Errorf("Failed to unmarshal json: %w", err)
}
func processJSON(sway *i3ipc.Node) error {
if !istype(sway, root) && len(sway.Nodes) == 0 {
return fmt.Errorf("Invalid or empty JSON structure")
}
@@ -278,7 +175,9 @@ func processJSON(jsoncode []byte) error {
}
}
slog.Debug("processed visible windows", "visibles", Visibles)
if Dumpvisibles {
dumpVisibles()
}
return nil
}
@@ -310,46 +209,30 @@ func findNextWindow() int {
return 0
}
func findPrevWindow() int {
vislen := len(Visibles)
if vislen == 0 {
return 0
}
prevnode := Visibles[vislen-1].Id
for _, node := range Visibles {
if node.Focused {
return prevnode
}
prevnode = node.Id
}
return 0
}
// actually switch focus using a swaymsg command
func switchFocus(id int, sock net.Conn) error {
command := fmt.Sprintf("[con_id=%d] focus", id)
slog.Debug("executing", "command", command)
// send switch focus command
err := sendHeaderIPC(sock, IPC_RUN_COMMAND, uint32(len(command)))
func switchFocus(id int, ipc *i3ipc.I3ipc) error {
responses, err := ipc.RunContainerCommand(id, "focus")
if err != nil {
return err
}
if err != nil {
return fmt.Errorf("failed to send run_command to IPC %w", err)
}
err = sendPayloadIPC(sock, []byte(command))
if err != nil {
return fmt.Errorf("failed to send switch focus command: %w", err)
}
// check response from sway
payload, err := readResponseIPC(sock)
if err != nil {
return err
}
responses := []Response{}
if err := json.Unmarshal(payload, &responses); err != nil {
return fmt.Errorf("Failed to unmarshal json response: %w", err)
}
if len(responses) == 0 {
return fmt.Errorf("Got invalid IPC zero response")
}
if !responses[0].Success {
slog.Debug("IPC response to switch focus command", "response", responses)
return fmt.Errorf("Failed to switch focus: %s", responses[0].Error)
log.Fatalf("failed to send focus command to container %d: %w (%s)",
id, responses[0].Error, err)
}
slog.Info("switched focus", "con_id", id)
@@ -358,13 +241,19 @@ func switchFocus(id int, sock net.Conn) error {
}
// iterate recursively over given node list extracting visible windows
func recurseNodes(nodes []Node) {
func recurseNodes(nodes []*i3ipc.Node) {
for _, node := range nodes {
// we handle nodes and floating_nodes identical
node.Nodes = append(node.Nodes, node.FloatingNodes...)
if istype(node, workspace) {
if node.Name == CurrentWorkspace {
//floating_nodes need to be sorted because
//order changes each time they are focused.
FloatVis := node.FloatingNodes
sort.Slice(FloatVis, func(i, j int) bool {
return FloatVis[i].Id < FloatVis[j].Id
})
//now we can handle nodes and floating_nodes identical
node.Nodes = append(node.Nodes, FloatVis...)
recurseNodes(node.Nodes)
return
}
@@ -384,6 +273,16 @@ func recurseNodes(nodes []Node) {
}
}
func dumpVisibles() {
windows := make([]string, len(Visibles))
for idx, node := range Visibles {
windows[idx] = fmt.Sprintf("id: %02d, focus: %5t, name: %s", node.Id, node.Focused, node.Name)
}
slog.Debug("visible windows on current workspace", "visibles", windows)
}
// we use line wise logging, unless debugging is enabled
func setupLogging(output io.Writer) {
logLevel := &slog.LevelVar{}
@@ -425,8 +324,8 @@ func setupLogging(output io.Writer) {
}
// little helper to distinguish sway tree node types
func istype(nd Node, which int) bool {
switch nd.Nodetype {
func istype(nd *i3ipc.Node, which int) bool {
switch nd.Type {
case "root":
return which == root
case "output":