Ubuntu – How to make a shortcut to close all the windows of the same application

keyboardlaunchershortcut-keysunity

When I right click on an application's icon in the Unity launcher, I can press Quit to close all the windows corresponding to that application. Is it possible to do the same with a keyboard shortcut which operates on the active window (and all the other windows corresponding to the same application)?

I could do something similar with xkill, but in that case I do not have the message that remembers me of unsaved files.

Best Answer

The answer by user72216 didn't work always. For example if I opened several Okular (a KDE PDF viewer) windows, the code won't close all windows, as different window ids are assigned to the windows. The following code extracts all window ids and closes them gracefully:

#!/usr/bin/env python3
import subprocess

def get(cmd):
    return subprocess.check_output(cmd).decode("utf-8").strip()

pid = get(["xdotool", "getactivewindow", "getwindowpid"])

# Identify the name of the application
username = get(["users"])
jobs = get(["ps","-u",username])
jobname = ""
for w in jobs.splitlines():
    jobinfo = w.split()
    if pid == jobinfo[0]:
        jobname = jobinfo[-1]
        break

# Get all pids that match the jobname
pidlist = []
for w in jobs.splitlines():
    jobinfo = w.split()
    if jobinfo[-1] == jobname:
        pidlist = pidlist + [jobinfo[0]]

# Close all windows with having the pids
wlist = get(["wmctrl", "-lp"])
for pid in pidlist:
    for w in wlist.splitlines():
        if pid in w and not "Desktop" in w:
            print(w.split()[0])
            subprocess.call(["wmctrl", "-ic", w.split()[0]])