def setup_tmux_hooks(): """Registers tmux hooks which are required to notice a change in the visibility of the pane this program runs in. Also it's required to notice new tmux clients displaying our pane. Returns: function which unregisters the registered hooks """ events = ( 'client-session-changed', 'session-window-changed', 'pane-mode-changed', 'client-detached' ) lock_directory_path = pathlib.PosixPath(tempfile.gettempdir()) / 'ueberzug' lock_file_path = lock_directory_path / tmux_util.get_session_id() own_pid = str(os.getpid()) command_template = 'ueberzug query_windows ' try: lock_directory_path.mkdir() except FileExistsError: pass def update_hooks(pid_file, pids): pids = ' '.join(pids) command = command_template + pids pid_file.seek(0) pid_file.truncate() pid_file.write(pids) pid_file.flush() for event in events: if pids: tmux_util.register_hook(event, command) else: tmux_util.unregister_hook(event) def remove_hooks(): """Removes the hooks registered by the outer function.""" with files.lock(lock_file_path) as lock_file: pids = set(lock_file.read().split()) pids.discard(own_pid) update_hooks(lock_file, pids) with files.lock(lock_file_path) as lock_file: pids = set(lock_file.read().split()) pids.add(own_pid) update_hooks(lock_file, pids) return remove_hooks
def remove_hooks(): """Removes the hooks registered by the outer function.""" with files.lock(lock_file_path) as lock_file: pids = set(lock_file.read().split()) pids.discard(own_pid) update_hooks(lock_file, pids)