简体   繁体   中英

Python Resize and Move Active Window X11

I am trying to write (in python) my own "tiling assistant" for a non tiling WM, like Xfce, MATE, ecc. This code should place the active windows on the center, left part or right part of the screen.

I am using pyewmh lib to interact with X11.

When I try to resize and move a window it does't work correctly and I don't know why !

This is my python code:

import argparse
from contextlib import contextmanager
from typing import Any, Dict, Optional, Tuple, Union, Callable  # noqa

from ewmh import 

# wm manager
ewmh = EWMH()

# get desktop size and real desktop sizes
w, h = ewmh.getDesktopGeometry()
xr, yr, wr, hr = ewmh.getWorkArea()[:4]


def main():
    print("Desktop Geometry: ", w, h)
    print("Desktop WorkArea:", xr, yr, wr, hr)

    # execute user selected tiling operation
    options[args.mode]()

    ewmh.display.flush()


def __edit_window(win=None, x=None, y=None, w=None, h=None):
    if win is None:
        win = ewmh.getActiveWindow()

    ewmh.setMoveResizeWindow(
        win,
        x=x,
        y=y,
        w=w,
        h=h
    )

    if h is None:
        ewmh.setWmState(win, 1, '_NET_WM_STATE_MAXIMIZED_VERT')

    print(f"New Window {win} pos: ({x}, {y}), New Window size: ({w}, {h})")


def tile_left():
    """
        Tile window to the left part of the screen.
        -m tile_left
    """

    print(f"Left Tiling Window")

    __edit_window(x=0, y=0, w=int(wr/2)) # w or wr ??


def tile_right():
    """
        Tile window to the right part of the screen.
        -m tile_right
    """

    print(f"Tiling Right Window")

    __edit_window(x=int(wr/2), y=0, w=int(wr / 2)) # w or wr ??


def centering_window():
    """
        Centers the active window.
        -m center
        Used with --noresize the active window is not resized when centered
    """

    print(f"Centering Window")

    win = ewmh.getActiveWindow()
    win_size = get_window_size(win)

    # disable maximised_vert 
    ewmh.setWmState(win, 0, '_NET_WM_STATE_MAXIMIZED_VERT')

    if args.noresize:
        # centering windows without resize dims
        print('\t with NoResize mode')

        __edit_window(win, x=int((wr - win_size.width) / 2), y=int((hr - win_size.height) / 2), w=win_size.width, h=win_size.height)  # w or wr ??

    else:
        # centering windows and resize dims
        print('\t with Resize mode')

        __edit_window(x=(xr + 50), y=(yr + 50), w=(wr - 100), h=(hr - 100))  # w or wr ??


def get_window_size(window):
    """Returns window size object"""
    # get window dims
    win_size = window.get_geometry()
    print(f"Window pos: ({win_size.x}, {win_size.y})  Window size: ({win_size.width}, {win_size.height})")

    return win_size


if __name__ == '__main__':
    # define selectable options
    # type: Dict[str, Callable[[None], None]]
    options = {
        'center': centering_window,  # center window
        'tile_left': tile_left,  # tiling window to the left
        'tile_right': tile_right,  # tiling window to the right
    }

    # init argument parser
    parser = argparse.ArgumentParser(description='My awesome python tiling assistant !')

    # arguments
    parser.add_argument(
        '-m',
        '--mode',
        type=str,
        choices=options.keys(),
        required=True,
        help='Choose how to tile the active window'
    )
    parser.add_argument(
        '--noresize',
        action='store_true',
        help='Center window without resize it'
    )

    args = parser.parse_args()

    main()

The next image show the problem: 在此处输入图像描述

There are some space between 2 terminals and between right terminal and screen border.

I have problems to set the correct window height too. I fixed it buy using the _NET_WM_STATE_MAXIMIZED_VERT prop, but when I try to move the window with the mouse it is kinda stuck in the Maximesed_Vert status.

It's not easy to make such a script work correctly for different desktop environments (DE) (like XFCE, KDE, Gnome etc.), since these DEs decorate windows differently. Also CSD (client side decoration) or not makes a difference. I know someone who is currently working on a similar project which should work on several DEs. His program gathers several geometry data in order to make this work. See https://gitlab.com/corthbandt/shinglify/-/blob/main/ewmhbackend.go function refresh().

I also wrote a tiling helper in python xpytile , which works pretty well on XFCE. Perhaps you can use this as a starting point. My script can, besides tiling, also resize side-by-side windows simulaneously. Unfortunately I couldn't make use of the EMWH-module, like you do, since that caused annoying flickering during the auto-resizing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM