Programatically Close Pie Menu (2.79)

Hello,

I’m developing an add-on for the 2.79 VSE that includes a pie menu. From the UI perspective, I’ve found that getting the pie menu to close if you choose not to do anything can be really annoying and often requires pressing the ESC key, which is not ideal. I have code that successfully runs when the mouse leaves a specified radius around the pie menu (so you close it by just moving the mouse far enough away), but I haven’t been able to find the correct, magic line of code that actually hides/cancels the pie menu. Returning the modal as cancelled doesn’t seem to work.

Can anyone help? Again this is in Blender 2.79 since I strongly dislike the newer VSE’s.

    def modal(self, context, event):
        if event.type == 'LEFTMOUSE' and event.value == 'RELEASE':
            bpy.ops.wm.call_menu_pie(name="SEQUENCER_MT_pie_menu")
            self.menu_shown = True  # Update the state
            return {'RUNNING_MODAL'}  # Continue running modal function

        # Check distance to close the pie menu if it's more than a threshold.
        if self.menu_shown and distance(self.initial_x, self.initial_y, event.mouse_x, event.mouse_y) > 100:
            self.menu_shown = False
            bpy.ops.wm.call_menu_cancel()  # Attempt to cancel the pie menu. This returns an error. Simply a return{'CANCELLED'} doesn't close it either. There also doesn't appear to be a way to simulate the escape key either.
            return {'CANCELLED'}

Instead of

bpy.ops.wm.call_menu_cancel()

use

context.window.screen = context.window.screen

Explanation:
Assigning the screen (it can be the same one), generates an NC_SCREEN notify code in Blender’s event system, which causes Blender to remove any active ui popup handlers on the window. This includes any open menus, floating panels/dialogs, and pie menus.

Wow this is an awesome feature. The other solution I ever found to close a popup was to move the mouse position for a split second to make Blender think the user was clicking elsewhere.