doti3/bin/i3_switch_workspace.php

74 lines
1.4 KiB
PHP
Executable File

#!/usr/bin/php
<?php
function getOrderedWorkspaces()
{
$json = shell_exec('i3-msg -t get_workspaces');
$workspaces = json_decode($json);
$ordered = [];
foreach ($workspaces as $w) {
$ordered[] = $w->name;
}
sort($ordered);
foreach ($ordered as $k => $v) {
foreach ($workspaces as $x => $w) {
if ($w->name == $v) {
$ordered[$k] = $w;
unset($workspaces[$x]);
}
}
}
return $ordered;
}
function getMoveOption()
{
global $argv;
if (!isset($argv[1])) {
$argv[1] = 'next';
}
return in_array($argv[1], ['next', 'previous']) ? $argv[1] : 'next';
}
function getNextWorkspace($workspaces)
{
$key = 0;
foreach ($workspaces as $k => $v) {
if ($v->focused) {
$key = $k;
}
}
return $workspaces[($key + 1) % count($workspaces)];
}
function getPreviousWorkspace($workspaces)
{
$count = count($workspaces);
$key = 0;
foreach ($workspaces as $k => $v) {
if ($v->focused) {
$key = $k;
}
}
return $workspaces[--$key >= 0 ? $key : $count - 1];
}
function moveToWorkspace($workspace)
{
shell_exec(sprintf("i3-msg 'workspace \"%s\"'", $workspace->name));
}
$workspaces = getOrderedWorkspaces();
moveToWorkspace('next' === getMoveOption() ? getNextWorkspace($workspaces) : getPreviousWorkspace($workspaces));