使用命令列將視窗移動到特定螢幕

使用命令列將視窗移動到特定螢幕

這類似於僅使用鍵盤即可快速將視窗放置到另一個螢幕,但我希望能夠使用命令列(這樣我所需要做的就是從 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. 該腳本需要wmctrlxdotool

    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>.

隨後,腳本將所有視窗一一移動到目標螢幕上的某個位置(使用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
}

相關內容