How to convert mouse position into UV Editor space?

I would like to know how can I convert the position of the mouse (system mouse cursor) into an appropriate coordinate in the UV Image Editor.

For the sake of the example I have put on a demo that will change the location of the cursor as a modal. Ignore the MOUSEMOVE part because I don’t have a clue how to implement it.


import bpy


class UVCursorPosition(bpy.types.Operator):
    bl_idname = "uv.uv_cursor_position"
    bl_label = "zzz"


    def invoke(self, context, event):
        print("Operator Running")
        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}


    def modal(self, context, event):


        if event.type == 'MOUSEMOVE':
            coord = [event.mouse_region_x, event.mouse_region_y]
            # dx = (2.0 * coord[0] / context.region.width) - 1.0
            dx = coord[0] / context.region.width
            zoom = context.space_data.zoom[0]
            image_size = bpy.data.images[0].size
            bpy.ops.uv.cursor_set(location=(dx, 0))
            #context.space_data.cursor_location.x = dx * image_size[0] * zoom
            print(zoom, dx)


        elif event.type == 'ESC':
            print("Operator Cancelled")
            return {'CANCELLED'}


        return {'PASS_THROUGH'}


def register():
    bpy.utils.register_class(UVCursorPosition)


def unregister():
    bpy.utils.unregister_class(UVCursorPosition)


if __name__ == "__main__":
    register()

I found it, if anyone is interested…


if event.type == 'MOUSEMOVE':
            coordinates = context.region.view2d.region_to_view(event.mouse_region_x, event.mouse_region_y)
            image_size = bpy.data.images[0].size
            context.space_data.cursor_location.x = coordinates[0] * image_size[0]