Search code examples
pythongtkpygobjectwnck

Detect when a window opens in wnck python


I am making a window tiling script using libwnck. I would like to detect when the user opens a new window in order to resize it. Here is the gist of my code so far:

import gi

gi.require_version("Wnck", "3.0")
from gi.repository import Wnck

screen = Wnck.Screen.get_default()
screen.force_update()

# Here I resize all windows in the current workspace using
# window.set_geometry

# The script ends here however I'd like it to continue forever
# and detect a "window opened event"

From the documentation it looks like there are virtual methods like do_window_opened but I have no idea how to get it working in python.


Solution

  • Here is a working simple test code. Hope it can help you and is what you want.

    import gi
    
    gi.require_version('Wnck', '3.0')
    gi.require_version('Gtk', '3.0')
    
    from gi.repository import Wnck
    from gi.repository import Gtk
    
    
    def test_do_when_window_opened_simple():
        Gtk.init([])
        screen: Wnck.Screen = Wnck.Screen.get_default()
        screen.force_update()
    
        def do_window_opened(this_screen: Wnck.Screen, opened_window: Wnck.Window):
            print('hello')
            app: Wnck.Application = opened_window.get_application()
            app_name = app.get_name()
            print('app name -> ' + app_name)
            print('window name -> ' + opened_window.get_name())
    
        screen.connect('window-opened', do_window_opened)
    
        Gtk.main()
    
    
    if __name__ == '__main__':
        test_do_when_window_opened_simple()
    

    See also:

    Please check the first comment of this link

    Please check the example of this link, it's written in C though

    Note: the Wnck.Screen object has a function named 'do_window_opened', but it's not implemented. I received an error message 'gi.repository.GLib.GError: g-invoke-error-quark: Class WnckScreen doesn't implement window_opened (1)' when trying to call it.