How to determine which viewport the user clicks in?

I’m trying to create an operator that lets the user set the position of the viewport camera to match that of another viewport. Basically, I want to user to start the operator in one viewport, click on the other viewport they want to copy the view from and then update the context.region_data.view_matrix to match that of the second viewport.

I suspect that the information I need is buried in the context parameter passed into the modal() method, but I cannot find any documentation on what exactly this object contains. Is there a way for me to capture the region_data.view_matrix of the second viewport I click on and then copy that into the region_data.view_matrix of the viewport I started in?

You can do some good old hit testing to get the area under the cursor.

def hit_test_area(context, x, y):
    for ar in context.screen.areas:
        if 0 <= x - ar.x <= ar.width:
            if 0 <= y - ar.y <= ar.height:
                return ar
    return None

Example usage in a modal operator:

if event.type == 'LEFTMOUSE':
    area = hit_test_area(context, event.mouse_x, event.mouse_y)
    if area is not None and area.type == 'VIEW_3D':
        rv3d =

That said, do note that modal operators run only in the window they were called in. If a user initiates the modal from one viewport, then clicks a viewport in a separate floating window, your modal won’t be able to catch the left mouse event.

1 Like