Skip to content

Instantly share code, notes, and snippets.

@tobiasglen
Created December 18, 2024 00:33
Show Gist options
  • Select an option

  • Save tobiasglen/c2b9a46666e46ea4ac8e10f97b1738f5 to your computer and use it in GitHub Desktop.

Select an option

Save tobiasglen/c2b9a46666e46ea4ac8e10f97b1738f5 to your computer and use it in GitHub Desktop.
toggle focus between firefox chatgpt tab and most recent used application/tab
#!/usr/bin/bash
# required programms: kdotool, ydotool, firefox
# - chatgpt needs to be open/pinned to the first tab of firefox
# - Make sure the chatgpt tab is renamed to include "chatgpt" in the title
# - Use something like https://github.com/Lazyuki/ReTitle to do this (e.g. $0 - chatgpt)
command -v kdotool >/dev/null 2>&1 || { echo "DEBUG: Missing kdotool."; exit 1; }
command -v ydotool >/dev/null 2>&1 || { echo "DEBUG: Missing ydotool."; exit 1; }
check_firefox_window() {
kdotool search --class "firefox" --limit 1
}
ACTIVE_WINDOW=$(kdotool getactivewindow)
LAST_WINDOW_FILE="/tmp/last_focused_window"
LAST_WINDOW=$(cat "$LAST_WINDOW_FILE" 2>/dev/null || echo "")
FIREFOX_WINDOW=$(check_firefox_window)
if [ -z "$FIREFOX_WINDOW" ]; then
echo "DEBUG: Starting Firefox..."
firefox &
for _ in {1..10}; do
FIREFOX_WINDOW=$(check_firefox_window)
[ -n "$FIREFOX_WINDOW" ] && sleep 0.2 && break
sleep 0.5
done
[ -z "$FIREFOX_WINDOW" ] && { echo "DEBUG: Firefox did not start."; exit 1; }
fi
CHATGPT_TAB=$(kdotool getwindowname "$FIREFOX_WINDOW" | grep -i "chatgpt")
CTRL="29"
TAB="15"
ALT="100"
if [ "$ACTIVE_WINDOW" == "$FIREFOX_WINDOW" ] && [ -n "$CHATGPT_TAB" ]; then
echo "DEBUG: Inside Firefox on ChatGPT tab."
if [ "$LAST_WINDOW" == "$FIREFOX_WINDOW" ]; then
echo "DEBUG: Switching to previous Firefox tab."
ydotool key ${CTRL}:1 ${TAB}:1 ${TAB}:0 ${CTRL}:0
else
echo "DEBUG: Switching to previous application."
ydotool key ${ALT}:1 ${TAB}:1 ${TAB}:0 ${ALT}:0
fi
elif [ "$ACTIVE_WINDOW" == "$FIREFOX_WINDOW" ]; then
echo "DEBUG: Switching to ChatGPT tab."
ydotool key ${ALT}:1 2:1 2:0 ${ALT}:0
else
echo "DEBUG: Switching to Firefox and ChatGPT tab."
kdotool windowactivate "$FIREFOX_WINDOW"
ydotool key ${ALT}:1 2:1 2:0 ${ALT}:0
fi
echo "$ACTIVE_WINDOW" > "$LAST_WINDOW_FILE" || { echo "DEBUG: Failed to write $LAST_WINDOW_FILE."; exit 1; }
@tobiasglen
Copy link
Copy Markdown
Author

Tested on Arch KDE Plasma6 Wayland

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment