Okay, this is a complex task, as Sway doesn't natively handle screen rotation based on a position sensor (like an accelerometer in a tablet). We'll need to combine a few tools and techniques. Here's a breakdown of the approach and a Sway configuration snippet, along with explanations. This is a starting point, and you'll likely need to adjust it based on your specific hardware and desired behavior.
1. The Problem & Approach
Sway's Limitations: Sway doesn't have built-in support for automatic screen rotation based on sensor data. It relies on external tools to manage this.
Tools Needed:
xrandr: The standard tool for configuring displays in X11 (which Sway uses under the hood). We'll use it to rotate the screen.
iio-sensor-proxy (or similar): This is the key. This tool reads data from the device's sensors (like the accelerometer). It exposes the sensor data as a virtual X11 input device. You might need to install this. The exact package name varies by distribution. (e.g., sudo apt install iio-sensor-proxy on Debian/Ubuntu).
A Script (Bash/Python): We'll write a script that:
Reads the sensor data from iio-sensor-proxy.
Determines the current orientation based on the sensor data.
Uses xrandr to rotate the screen accordingly.
Sway Configuration: We'll configure Sway to run the script periodically or on specific events (like plugging in the tablet).
2. Installation and Setup (Important First Steps)
Install iio-sensor-proxy: This is crucial. The installation process depends on your distribution. Search for "iio-sensor-proxy" in your package manager.
Identify Your Sensor: You need to find the correct sensor name that iio-sensor-proxy recognizes. Run iio-sensor-proxy -h to see a list of available sensors. Look for something related to the accelerometer or orientation. The output will show the sensor's name (e.g., accel).
Test iio-sensor-proxy: Run iio-sensor-proxy -d /dev/iio:deviceX -e accel (replace /dev/iio:deviceX with the correct device path and accel with the correct sensor name). This should output sensor data to the console. If it doesn't, you need to find the correct device path. ls /dev/iio* can help.
X11 Permissions: Ensure the user running the script has permission to access the sensor device. You might need to add the user to the iio group. sudo usermod -a -G iio $USER (then log out and back in).
3. The Script (Bash Example - rotate_screen.sh)
bash
#!/bin/bash
# Configuration
SENSOR_NAME="accel" # Replace with your sensor name
THRESHOLD=0.2 # Adjust this value
OUTPUT_FILE="/tmp/orientation"
# Function to get the orientation
get_orientation() {
# Read the sensor data
data=$(iio-sensor-proxy -d /dev/iio:device0 -e $SENSOR_NAME) # Replace /dev/iio:device0 with your device
# Extract the X-axis value (assuming it's the first value)
x_axis=$(echo "$data" | awk '{print $2}')
# Determine the orientation based on the X-axis value
if (( $(echo "$x_axis > $THRESHOLD" | bc -l) )); then
echo "landscape"
elif (( $(echo "$x_axis < -$THRESHOLD" | bc -l) )); then
echo "reverse_landscape"
else
echo "portrait"
fi
}
# Function to rotate the screen
rotate_screen() {
orientation=$1
case "$orientation" in
"portrait")
xrandr --output HDMI-1 --rotate normal # Replace HDMI-1 with your output name
;;
"landscape")
xrandr --output HDMI-1 --rotate right # Replace HDMI-1 with your output name
;;
"reverse_landscape")
xrandr --output HDMI-1 --rotate inverted # Replace HDMI-1 with your output name
;;
*)
echo "Unknown orientation: $orientation"
;;
esac
}
# Main loop
while true; do
orientation=$(get_orientation)
rotate_screen "$orientation"
sleep 2 # Adjust the sleep time as needed
done
Important Notes about the Script:
Replace Placeholders: You must replace:
/dev/iio:device0 with the correct device path for your sensor.
HDMI-1 with the name of your display output (use xrandr without arguments to list available outputs).
SENSOR_NAME with the correct sensor name.
THRESHOLD: This value determines how much the sensor needs to deviate from flat to trigger a rotation. Adjust it to your liking. A higher value means more movement is required.
sleep: Adjust the sleep time to control how often the script checks the sensor. Too frequent checks can consume resources.
Error Handling: This script lacks robust error handling. You should add checks to ensure iio-sensor-proxy is running and that xrandr commands succeed.
bc -l: The bc -l command is used for floating-point comparisons in Bash. It's necessary because Bash's built-in comparison operators don't handle floating-point numbers well.
Output Name: Find your output name using xrandr. It's usually something like HDMI-0, DP-1, or eDP-1.
4. Sway Configuration (~/.config/sway/config)
sway
# Run the rotation script in the background
exec_always /path/to/rotate_screen.sh &
# Optional: Bind a key to manually rotate the screen (for testing)
bindsym Mod4+r exec /path/to/rotate_screen.sh
Explanation:
exec_always: This command tells Sway to run the script every time Sway starts. The & puts the script in the background.
bindsym (Optional): This creates a keybinding (Mod4+r in this example) that allows you to manually run the script for testing or if the automatic rotation isn't working.
5. Making the Script Executable
bash
chmod +x /path/to/rotate_screen.sh
6. Testing and Troubleshooting
Run the script manually: Open a terminal and run /path/to/rotate_screen.sh. Observe the output and see if the screen rotates as expected.
Check Sway logs: If the script isn't running, check Sway's logs for errors. You can usually find the logs in ~/.local/share/sway/sway.log.
Permissions: Make sure the user running Sway has permission to access the sensor device and run the script.
iio-sensor-proxy: Verify that iio-sensor-proxy is running and that it's exposing the correct sensor data.
xrandr: Test xrandr commands directly in a terminal to make sure they work.
7. Alternative Approaches (Python)
A Python script might be more readable and easier to maintain than a Bash script. Here's a very basic outline:
python
#!/usr/bin/env python3
import subprocess
import time
def get_orientation():
# Replace with your iio-sensor-proxy command
result = subprocess.check_output(["iio-sensor-proxy", "-d", "/dev/iio:device0", "-e", "accel"]).decode("utf-8")
x_axis = float(result.split()[1]) # Assuming X-axis is the second value
if x_axis > 0.2:
return "landscape"
elif x_axis < -0.2:
return "reverse_landscape"
else:
return "portrait"
def rotate_screen(orientation):
if orientation == "portrait":
subprocess.run(["xrandr", "--output", "HDMI-1", "--rotate", "normal"])
elif orientation == "landscape":
subprocess.run(["xrandr", "--output", "HDMI-1", "--rotate", "right"])
elif orientation == "reverse_landscape":
subprocess.run(["xrandr", "--output", "HDMI-1", "--rotate", "inverted"])
if __name__ == "__main__":
while True:
orientation = get_orientation()
rotate_screen(orientation)
time.sleep(2)
Key Considerations:
Hardware Specifics: The exact sensor device path and sensor name will vary depending on your tablet's hardware.
Calibration: You might need to calibrate the sensor data to get accurate orientation readings.
Power Management: Consider the impact of running the script on battery life. You might want to add logic to disable the rotation when the tablet is unplugged.
User Experience: Think about how the rotation will feel to the user. You might want to add a delay before rotating the screen to prevent jarring transitions.
This is a complex project, and it will require some experimentation and debugging. Start with the basics, get the script working manually, and then integrate it into your Sway configuration. Good luck! Let me know if you have any specific questions or run into problems.
User
is it easier to just define a shortcut in the config to do it manually?
Assistant
Yes, absolutely! For many use cases, defining a shortcut in your Sway configuration to manually rotate the screen is significantly easier and more practical than trying to automate it with sensor data. The automated approach is prone to issues with sensor accuracy, power consumption, and configuration complexity.
Here's how you can define shortcuts for screen rotation in your ~/.config/sway/config file:
sway
# Rotate screen to normal (0 degrees)
bindsym Mod4+1 exec xrandr --output HDMI-1 --rotate normal
# Rotate screen to right (90 degrees)
bindsym Mod4+2 exec xrandr --output HDMI-1 --rotate right
# Rotate screen to left (270 degrees)
bindsym Mod4+3 exec xrandr --output HDMI-1 --rotate left
# Rotate screen to inverted (180 degrees)
bindsym Mod4+4 exec xrandr --output HDMI-1 --rotate inverted
Explanation:
bindsym: This command defines a keybinding.
Mod4: This is usually the Windows key (Super key). You can change this to another modifier key if you prefer (e.g., Mod1 for Alt).
+1, +2, +3, +4: These are the keys you'll press in combination with the modifier key. You can choose any keys you like.
exec: This command executes a shell command.
xrandr --output HDMI-1 --rotate ...: This is the xrandr command to rotate the screen. Important: Replace HDMI-1 with the actual name of your display output. You can find this by running xrandr without any arguments.
How to Use:
Save the configuration: Save the changes to your ~/.config/sway/config file.
Reload Sway: You can reload Sway's configuration by pressing Mod4+Shift+c (the default keybinding for reloading the config). Alternatively, you can restart Sway.
Use the shortcuts: Press the key combinations you defined (e.g., Mod4+1, , etc.) to rotate the screen.
Mod4+2
Advantages of the Shortcut Approach:
Simplicity: It's much easier to set up and maintain.
Reliability: It doesn't rely on potentially unreliable sensor data.
Control: You have complete control over when the screen rotates.
No extra dependencies: You don't need to install and configure iio-sensor-proxy or write a complex script.
Low resource usage: No background process is constantly running.
When to Consider the Automated Approach:
The automated approach with sensor data might be worth considering only if:
You absolutely need hands-free, automatic rotation.
You're willing to spend the time and effort to get it working reliably.
You're comfortable with troubleshooting and debugging.
In most cases, the shortcut approach is the best solution for screen rotation in Sway. It's simple, reliable, and gives you the control you need. I recommend starting with the shortcuts and only exploring the automated approach if you have a very specific requirement.