kovidgoyal / kitty

Cross-platform, fast, feature-rich, GPU based terminal
https://sw.kovidgoyal.net/kitty/
GNU General Public License v3.0
22.13k stars 907 forks source link

Kitty terminal closing Intercept #7367

Closed Raghav-rv28 closed 3 weeks ago

Raghav-rv28 commented 3 weeks ago

Hi, First and foremost, awesome Terminal.

i am building an utility script which intercepts the SIGTERM signal (closing of terminal with shortcuts like alt+f4 or using gui close button) image for closing the kitty terminal and before doing this i run my own script which does some cleanup/saving. Im running into the roadblock since the SIGTERM is not working as expected in the terminal exactly. i tried going through the documentation but so far no luck.

I can work with custom kittens to intercept closing events like close_os_window, close_tab which work fine but i want to cover all bases where a terminal might get accidentally closed.

Now this isnt the only script i tried. i tried using other methods as well like changing the shortcuts to run the script and close the terminal but that was its own can of worms so didnt go down that route too much.

Current solution on which i landed on: (Not Working)

pre_terminate_function() {
    echo "Performing pre-termination tasks for Kitty terminal (PID: $1)..."
}

handle_sigterm() {
    local pid=$1
    echo "Received SIGTERM signal for Kitty terminal (PID: $pid)."
    pre_terminate_function "$pid"

    echo "Passing on SIGTERM signal to Kitty terminal (PID: $pid)."
    kill -SIGTERM "$pid"
}

watch_kitty_terminals() {
    echo "Monitoring Kitty terminal processes..."
    while true; do
        kitty_pids=$(pgrep -x kitty)

        if [ -z "$kitty_pids" ]; then
            echo "No Kitty terminals found."
        fi

        for pid in $kitty_pids; do
            # Check if the process is still running
            if ! ps -p "$pid" > /dev/null; then
                continue
            fi

            # Set up trap for SIGTERM
            trap "handle_sigterm $pid" SIGTERM
        done

        sleep 2
    done
}

watch_kitty_terminals

Any help or feedback would be appreciated. Thanks

kovidgoyal commented 3 weeks ago

You cannot intercept signals sent to other processes. What is your actual use case.

Raghav-rv28 commented 3 weeks ago

I am doing this to build a tui which helps manages session and easily configure the terminal:

i would like to build a script which saves the session data for a particular kitty terminal instance. we have inbuilt commands like kitty @ ls which help us do this. i built a python kitten script which looks something like this:

from typing import List
import json
import os
from kitty.boss import Boss

def main(args: List[str]) -> str:
    pass

from kittens.tui.handler import result_handler
@result_handler(no_ui=True)
def handle_result(args: List[str], answer: str, target_window_id: int, boss: Boss) -> None:
    w = boss.window_id_map.get(target_window_id)
    if w is not None:
        json_data_str = boss.call_remote_control(w, ('ls', f'--match=id:{w.id}'))
        json_data = json.loads(json_data_str)
        # Define the file path
        home_dir = os.path.expanduser("~")

        # Define the file path with the correct username
        file_path = os.path.join(home_dir, '.config','kitty', 'lastsession.kitty')        
        # Check if the file exists
        if not os.path.exists(file_path):
            # If the file doesn't exist, create a new one
            with open(file_path, 'w') as f:
                json.dump({}, f)  # Write an empty JSON object

        # Write JSON data to the file
        with open(file_path, 'w') as f:
            json.dump(json_data, f)
    boss.close_tab()

this is the simplified version but i have more ifs and else which check for different arguments incoming. i have also mapped some shortcuts in my kitty config file as follows:

map ctrl+shift+q kitten autosave.py close_tab map ctrl+shift+w kitten autosave.py close_window

i tried the same for alt+f4 which is a common way of closing the terminal, but no dice. Then as i researched more i found that if i am 'trapping' the SIGTERM signal for the kitty instance it would cover the whole "accidentally closing terminal edge case" instead of me handling each individual closing separately.

Any help would be useful.

kovidgoyal commented 3 weeks ago

If you want to perform special actions on window close events, you use the watcher infrastructure in kitty https://sw.kovidgoyal.net/kitty/conf/#opt-kitty.watcher

You absolutely cannot handle signals in your code. signals are an asynchronous, global mechanism.