コマンドラインを使用してウィンドウを特定の画面に移動する

コマンドラインを使用してウィンドウを特定の画面に移動する

これはキーボードのみを使用して、別の画面にウィンドウをすばやく配置しますただし、コマンドラインを使用できるようにしたい (必要なのは、bash 履歴からコマンドラインを呼び出すことだけ)。

例: 送信

  • すべてのgnomeターミナルウィンドウにeDP1
  • すべてのEmacsウィンドウをVGA1、そして
  • すべてのChromeウィンドウにHDMI1

(移動後に最大化しますが、F11通常のウィンドウ マネージャー スタイルの最大化という奇妙な方法ではありません)。

実行可能ファイル名でウィンドウを指定したいと思います。

答え1

特定のウィンドウクラスのすべてのウィンドウを(スクリーン)名で特定のスクリーンに移動する

以下のスクリプトは、特定のWM_CLASS(アプリケーション)に属するウィンドウを、画面の名前その方法については、スクリプト内および下記で説明します。

このスクリプトでは、画面が水平に配置され、ほぼ上揃えになっている(差は 100 PX 未満)ことを前提としています。

スクリプト

#!/usr/bin/env python3
import subprocess
import sys

# just a helper function, to reduce the amount of code
get = lambda cmd: subprocess.check_output(cmd).decode("utf-8")

# get the data on all currently connected screens, their x-resolution
screendata = [l.split() for l in get(["xrandr"]).splitlines() if " connected" in l]
screendata = sum([[(w[0], s.split("+")[-2]) for s in w if s.count("+") == 2] for w in screendata], [])

def get_class(classname):
    # function to get all windows that belong to a specific window class (application)
    w_list = [l.split()[0] for l in get(["wmctrl", "-l"]).splitlines()]
    return [w for w in w_list if classname in get(["xprop", "-id", w])]

scr = sys.argv[2]

try:
    # determine the left position of the targeted screen (x)
    pos = [sc for sc in screendata if sc[0] == scr][0]
except IndexError:
    # warning if the screen's name is incorrect (does not exist)
    print(scr, "does not exist. Check the screen name")
else:
    for w in get_class(sys.argv[1]):
        # first move and resize the window, to make sure it fits completely inside the targeted screen
        # else the next command will fail...
        subprocess.Popen(["wmctrl", "-ir", w, "-e", "0,"+str(int(pos[1])+100)+",100,300,300"])
        # maximize the window on its new screen
        subprocess.Popen(["xdotool", "windowsize", "-sync", w, "100%", "100%"])

使い方

  1. スクリプトにはwmctrlと の両方が必要ですxdotool

    sudo apt-get install xdotool wmctrl
    
  2. 以下のスクリプトを空のファイルにコピーし、move_wclass.py

  3. 次のコマンドで実行します:

    python3 /path/to/move_wclass.py <WM_CLASS> <targeted_screen>
    

    例えば:

    python3 /path/to/move_wclass.py gnome-terminal VGA-1
    

にはWM_CLASS一部WM_CLASS、例のように。画面の名前はちょうどおよび完全な名前。

どのように行われるか(コンセプト)

説明は主に概念に関するもので、コーディングについてはあまり説明されていません。

xrandr の出力では、接続されている画面ごとに次のような文字列/行があります。

VGA-1 connected 1280x1024+1680+0

この行は画面上の位置そしてその名前説明したようにここ

このスクリプトは、すべての画面の情報を一覧表示します。画面とウィンドウ クラスを引数としてスクリプトを実行すると、画面の (x) 位置が検索され、特定のクラスのすべてのウィンドウ (-id) が検索されます ( の助けを借りてwmctrl -l、 の出力が参照されますxprop -id <window_id>)。

その後、スクリプトはすべてのウィンドウを 1 つずつ対象画面上の位置に移動し ( を使用wmctrl -ir <window_id> -e 0,<x>,<y>,<width>,<height>)、最大化します ( を使用xdotool windowsize 100% 100%)。

注記

このスクリプトは、私が実行したテストでは正常に動作しました。ただし、Unity でwmctrl、さらにはxdotool、を使用すると、頑固な特性が生じる可能性があり、推論ではなく実験によって解決する必要がある場合があります。例外が発生する可能性がある場合は、お知らせください。

答え2

@jacobs の Python コードをシンプルな bash に書き直して動作するようにしました (Ubuntu 16 Cinnamon でテストしました)。

それを付け加えremove,maximized_vert, remove,maximized_horzなければ、ウィンドウは動かなかった。

#!/bin/bash

if [ ! -z "$1" ] || [ -z "$2" ]; then
    command=$(wmctrl -l | grep $1 | cut -d" " -f1)

    if [ ! -z "$command" ]; then
        position=$(xrandr | grep "^$2" | cut -d"+" -f2)

        if [ ! -z "$position" ]; then
            for window in $command; do 
               wmctrl -ir $window -b remove,maximized_vert
               wmctrl -ir $window -b remove,maximized_horz 
               wmctrl -ir $window -e 0,$position,0,1920,1080
               wmctrl -ir $window -b add,maximized_vert
               wmctrl -ir $window -b add,maximized_horz 
            done
        else
            echo -e "not found monitor with given name"
        fi
    else
        echo -e "not found windows with given name"
    fi
else
    echo -e "specify window and monitor name;\nmove.sh window-name monitor-name"
fi
  1. sudo apt-get install xdotool wmctrl
  2. /path/to/script.sh "window-name" "monitor-name"

答え3

記録のために、この質問との組み合わせに私が使用しているものは次のとおりです。複数のモニター設定を復元する:

# configure multiple displays and
# move the windows to their appropriate displays

import subprocess
import os
import wmctrl
import re

mydisplays = [("VGA1",0,"left"),
              ("eDP1",1080,"normal"),
              ("HDMI1",3000,"left")]

# https://askubuntu.com/questions/702002/restore-multiple-monitor-settings
def set_displays ():
    subprocess.check_call(" && ".join([
        "xrandr --output %s --pos %dx0  --rotate %s" % d for d in mydisplays]),
                          shell=True)

# https://askubuntu.com/questions/702071/move-windows-to-specific-screens-using-the-command-line
mywindows = [("/emacs$","VGA1"),
             ("/chrome$","HDMI1"),
             ("gnome-terminal","eDP1")]
def max_windows ():
    didi = dict([(d,x) for d,x,_ in mydisplays])
    for w in wmctrl.Window.list():
        try:
            exe = os.readlink("/proc/%d/exe" % (w.pid))
            for (r,d) in mywindows:
                if re.search(r,exe):
                    x = didi[d]
                    print "%s(%s) --> %s (%d)" % (r,exe,d,x)
                    w.set_properties(("remove","maximized_vert","maximized_horz"))
                    w.resize_and_move(x,0,w.w,w.h)
                    w.set_properties(("add","maximized_vert","maximized_horz"))
                    break
        except OSError:
            continue

def cmdlines (cmd):
    return subprocess.check_output(cmd).splitlines()

def show_displays ():
    for l in cmdlines(["xrandr"]):
        if " connected " in l:
            print l

if __name__ == '__main__':
    show_displays()
    set_displays()
    show_displays()
    max_windows()

使用する必要があるマウスコントロールバージョン0.3以降(私のプルリクエスト)。

答え4

@AndrzejPiszczek の回答に基づいて、すべてのウィンドウを特定の画面に移動する方法は次のとおりです。

function move_win {
    if [ -z "$1" ]; then
        echo -e "Specify a screen, possible options: "
        echo -e $(xrandr | grep " connected " | cut -d'-' -f1)
        return
    fi

    MONITOR=$1

    # get all relevant windows on all screens
    windows=$(wmctrl -l | egrep -v " -1 " | cut -d" " -f1)

    if [ ! -z "$windows" ]; then
        # get the necessary metrics from the screen the windows should be moved to 
        # will contain: width, height, offsetX, offsetY
        screen_values=($(xrandr | grep "^$MONITOR-.* connected" | grep -Eo '[0-9]+x[0-9]+\+[0-9]+\+[0-9]+' | sed 's/x/ /g; s/+/ /g'))

        if (( ${#screen_values[@]} )); then
            # get the start/end position of the screen so we can later determine
            # if the window is already on the screen or not
            screen_start_pos=$(( ${screen_values[2]} ))
            screen_end_pos=$(( ${screen_values[2]} + ${screen_values[0]} ))

            for window in $windows; do
                # get the window name
                window_name=$(wmctrl -lG | grep "$window" | awk -F "$HOSTNAME " '{print $2}')
                # extract relevant window geometry values such as x, y, width, height
                window_values=($(wmctrl -lG | grep "$window" | awk -F " " '{print $3, $5, $6}'))

                # if the window's X origin position is already inside the screen's 
                # total width then don't move it (this won't work exactly for windows only partially on the screen)
                if (( ${window_values[0]} >= $screen_end_pos || ${window_values[0]} < $screen_start_pos )); then
                    echo -e "Moving to screen $MONITOR: $window_name"
                  
                    wmctrl -ir $window -b remove,maximized_vert
                    wmctrl -ir $window -b remove,maximized_horz
                    # the -e parameters are gradient,x,y,width,height
                    # move window to (X,Y) -> (0,0) of new screen and the same window dimensions
                    wmctrl -ir $window -e 0,$screen_start_pos,0,${window_values[1]},${window_values[2]}
                else
                    echo -e "Already on screen $MONITOR: $window_name"
                fi
            done
        else 
            echo -e "No screen found"
        fi
    else
        echo -e "No windows found"
    fi
}

関連情報