summaryrefslogtreecommitdiff
path: root/GstInspector/GUI/window.py
blob: 741a460b53fa937570965b8615e1675ec29ff8f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# -*- coding: utf-8; mode: python; -*-
#
#  GStreamer Inspector - Multimedia system plugin introspection
#
#  Copyright (C) 2007 René Stadler <mail@renestadler.de>
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation; either version 3 of the License, or (at your option)
#  any later version.
#
#  This program is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
#
#  You should have received a copy of the GNU General Public License along with
#  this program.  If not, see <http://www.gnu.org/licenses/>.

"""GStreamer Inspector GUI.window module."""

import logging
from gettext import ngettext

import gobject
import gtk

from GstInspector import Data

from GstInspector.GUI.actions import Actions, DevhelpAction
from GstInspector.GUI.columns import InspectorColumnManager
from GstInspector.GUI.filters import FilterManager, UIFilterNone
from GstInspector.GUI.pages import PageManager
from GstInspector.GUI.utils import widget_add_popup_menu

class PanedState (object):

    def __init__ (self):

        self.logger = logging.getLogger ("ui.paned-state")

        self.horizontal = None
        self.child_size_allocate_id = None

        self.paned_size = 0
        self.target_child_size = None

    def attach (self, paned, child):

        self.paned = paned
        self.child = child

        if isinstance (paned, gtk.HPaned):
            self.horizontal = True
        else:
            self.horizontal = False

        self.paned.connect ("size-allocate",
                            self.__handle_paned_size_allocate)

    def detach (self):

        if self.child_size_allocate_id is not None:
            self.child.disconnect (self.child_size_allocate_id)
            self.child_size_allocate_id = None
        self.child = None

        self.paned.disconnect_by_func (self.__handle_paned_size_allocate)
        self.paned = None

        self.horizontal = None

    def get_child_size (self):

        raise NotImplementedError ()

    def set_child_size (self, size):

        pass

    def __handle_child_size_allocate (self, widget, allocation):

        if self.horizontal:
            size = allocation.width
        else:
            size = allocation.height

        self.set_child_size (size)

    def __handle_paned_size_allocate (self, widget, allocation):

        if self.horizontal:
            size = allocation.width
        else:
            size = allocation.height

        if self.paned_size == size:
            return

        self.paned_size = size

        if self.child_size_allocate_id is None:
            child_size = self.get_child_size ()
            if child_size:
                self.set_size (child_size)

            handler_id = self.child.connect ("size-allocate",
                                             self.__handle_child_size_allocate)
            self.child_size_allocate_id = handler_id
            self.logger.debug ("now listening for child size allocation changes")

        if self.target_child_size is not None:
            self.set_size (self.target_child_size)

    def set_size (self, size):

        # For saving and restoring the child widget's size (and therefore the
        # paned's handle position), we cannot just save and restore
        # paned.props.position.  Doing this breaks for maximized windows as
        # they seem to undergo a maximized-unmaximized-maximized cycle on
        # restore, making the pane handle position increase by the difference
        # between the maximized width and the default width.

        paned_children = self.paned.get_children ()
        if not self.child in paned_children:
            return
        # The 'position' property of gtk.HPaned equals the width of the first
        # child.
        if self.paned.get_child1 () == self.child:
            # Child on the left/top.
            target_position = size
        else:
            # Child on the right/bottom.
            border = self.paned.props.border_width
            handle = self.paned.style_get_property ("handle-size")
            target_position = self.paned_size - 2 * border - handle - size

        if (target_position < self.paned.props.min_position or
            target_position > self.paned.props.max_position):

            self.target_child_size = size
            self.logger.debug ("target position %i out of bounds, postponing",
                               target_position)
        else:
            self.target_child_size = None
            self.paned.props.position = target_position
            self.logger.debug ("set paned position to %i (for size %i)",
                               target_position, size)

class InfoPanedState (PanedState):

    def attach (self, inspector_window):

        self.app = inspector_window.app

        if not self.app.state.info_pane_size:
            label = gtk.Label ("Description: This string should have a good size")
            size = label.size_request ()[0]
            self.app.state.info_pane_size = size

        widgets = inspector_window.widgets
        PanedState.attach (self, widgets.main_hpaned, widgets.element_info_book)

    def detach (self):

        PanedState.detach (self)

        self.app = None

    def get_child_size (self):

        return self.app.state.info_pane_size

    def set_child_size (self, size):

        if self.app.state.info_pane_size != size:
            self.logger.debug ("child size changed to %i", size)
            self.app.state.info_pane_size = size

class WindowState (object):

    def __init__ (self):

        self.logger = logging.getLogger ("ui.window-state")

        self.is_maximized = False

        self.state = None
        self.window = None

    def attach (self, state, window):

        self.state = state
        self.window = window

        window.connect ("window-state-event",
                        self.handle_window_state_event)

        geometry = state.geometry
        if geometry:
            position, size = geometry[0:2], geometry[2:4]
            window.move (*position)
            window.set_default_size (*size)

        if state.maximized:
            self.logger.debug ("initially maximized")
            window.maximize ()

    def detach (self):

        state = self.state
        window = self.window

        self.state = None
        self.window = None

        window.disconnect_by_func (self.handle_window_state_event)

        state.maximized = self.is_maximized
        if not self.is_maximized:
            position = tuple (window.get_position ())
            size = tuple (window.get_size ())
            state.geometry = position + size

    def handle_window_state_event (self, window, event):

        if not event.changed_mask & gtk.gdk.WINDOW_STATE_MAXIMIZED:
            return

        if event.new_window_state & gtk.gdk.WINDOW_STATE_MAXIMIZED:
            self.logger.debug ("maximized")
            self.is_maximized = True
        else:
            self.logger.debug ("unmaximized")
            self.is_maximized = False

class InspectorWindowState (object):

    def __init__ (self):

        self.window_state = WindowState ()
        self.info_paned_state = InfoPanedState ()

    def attach (self, inspector_window):

        app = inspector_window.app
        widgets = inspector_window.widgets

        state = app.state
        window = widgets.inspector_window

        self.window_state.attach (state, window)
        self.info_paned_state.attach (inspector_window)

    def detach (self):

        self.window_state.detach ()
        self.info_paned_state.detach ()

class InspectorWindow (Data.Consumer):

    def _get_active (self):

        selection = self.element_view.get_selection ()
        model, tree_iter = selection.get_selected ()
        if tree_iter is None:
            return None
        else:
            element = model.get (tree_iter, self.element_model.COL_ELEMENT)[0]
            return element

    def _set_active (self, element):

        model = self.element_view.props.model
        col = self.element_model.COL_ELEMENT
        selection = self.element_view.get_selection ()

        if model is None:
            raise KeyError ("view model is None, cannot set active element")

        for row in model:
            if row[col] == element:
                selection.select_iter (row.iter)
                return
        else:
            raise KeyError ("no such row with element %r" % (element,))

    active = property (_get_active, _set_active)
    count = -1

    def __init__ (self, app):

        self.logger = logging.getLogger ("ui.window")

        InspectorWindow.count += 1
        self.count = InspectorWindow.count

        self.app = app

        self.idle_update_source = None

        self.page_manager = PageManager ()
        self.filter_manager = FilterManager ()
        self.column_manager = InspectorColumnManager ()
        self.window_state = InspectorWindowState ()

        # These would rather belong in the App object such that one instance of
        # each action could be shared between all windows.  However,
        # GtkUIManager breaks the accelerators then (which could be a bug in
        # GTK+).  That or I'm getting the usage pattern for gtk actions wrong.
        # It seems sharing this way should be just fine since all of the
        # action's state is common between all windows at any time (at least
        # sharing the menu actions works).
        app_group = gtk.ActionGroup ("AppActions")
        new_window = ("new-window", gtk.STOCK_NEW,_("_New Window"),)
        reload_data = ("reload-data", gtk.STOCK_REFRESH, _("_Refresh Data"), "<Ctrl>R",)
        app_group.add_actions ([new_window, reload_data])

        group = gtk.ActionGroup ("WindowActions")
        group.add_actions ([("show-about", gtk.STOCK_ABOUT),
                            ("close-window", gtk.STOCK_CLOSE, None)])
        group.add_action_with_accel (DevhelpAction ("show-documentation"), "<Ctrl>D")
        group.add_toggle_actions ([("show-filter", None, _("Filter"), "<Ctrl>F")])

        actions = Actions ()
        actions.add_group (group)
        actions.add_group (app_group)
        actions.add_group (self.page_manager.action_group)
        actions.add_group (self.column_manager.action_group)

        widgets = self.app.widget_factory.make ("inspector_window",
                                                autoconnect = self)

        self.actions = actions
        self.widgets = widgets

        self.gtk_window = widgets.inspector_window
        self.element_view = widgets.main_view
        self.element_count_label = widgets.row_count_label

        ui = self.app.ui_factory.make (self.actions)
        self.gtk_window.add_accel_group (ui.get_accel_group ())
        menu_bar = ui.get_widget ("/ui/menubar")
        box = widgets.main_vbox
        box.pack_start (menu_bar, False, False, 0)
        menu_bar.show ()

        # We need to keep a reference to the context menubar around, otherwise
        # the child menus will have invalid windows:
        self.context_menubar = ui.get_widget ("/ui/context")

        menu = ui.get_widget ("/ui/context/NameValueContextMenu")
        self.name_value_popup = menu.get_submenu ()
        menu = ui.get_widget ("/ui/menubar/ViewMenu/ViewColumnsMenu")
        self.columns_popup = menu.get_submenu ()

        model = self.app.element_model
        self.element_model = model
        self.element_filter = model.filter_new ()
        self.filter_func = UIFilterNone.filter_func
        model_get = model.get
        element_col = model.COL_ELEMENT
        def filter_func (model, tree_iter):
            element = model_get (tree_iter, element_col)[0]
            if element is None:
                # This happens during (re)load.  The model filter reacts to
                # row-inserted signals and lets us evaluate these new rows.
                # However, our ElementModel is based on gtk.ListStore.  For
                # these, adding a row and setting its values are separated
                # operations.  Therefore, all added rows are initially empty.
                return False
            else:
                return self.filter_func (element)
        self.element_filter.set_visible_func (filter_func)

        self.default_focus_widget = None
        self.default_active_name = self.app.state.element

        self.attach ()

    def __repr__ (self):

        return "<%s object (index %i) at 0x%x>" % (type (self).__name__,
                                                   self.count,
                                                   id (self),)

    def attach (self):

        self.window_state.attach (self)

        action = self.actions.close_window
        handler = self.handle_close_window_action_activate
        action.connect ("activate", handler)

        action = self.actions.show_filter
        handler = self.handle_show_filter_action_toggled
        action.connect ("toggled", handler)

        action = self.actions.show_about
        handler = self.handle_show_about_action_activate
        action.connect ("activate", handler)

        window = self.gtk_window
        window.connect ("delete-event", self.handle_window_delete_event)
        window.connect ("realize", self.handle_window_realize)

        model = self.app.element_model
        view = self.element_view
        view.drag_dest_unset ()
        view.unset_rows_drag_source ()
        view_selection = view.get_selection ()
        view_selection.connect ("changed", self.handle_element_view_selection_changed)
        widget_add_popup_menu (view, self.columns_popup)

        self.page_manager.attach (self)
        self.filter_manager.attach (self)
        self.column_manager.attach (self)

        default_filter = self.app.state.filter
        if default_filter and default_filter != UIFilterNone:
            self.actions.show_filter.props.active = True

        if len (model):
            # Model is already filled, so we are a new window created after
            # data has been loaded.
            self.post_attach ()

        window.show ()

    def post_attach (self):

        view = self.element_view
        view.props.model = gtk.TreeModelSort (self.element_filter)
        view.set_search_column (self.element_model.COL_FACTORY_NAME)

        self.filter_manager.handle_load_finished ()

        self.update_element_count ()

        # Sorting was postponed until now, which is much faster:
        self.column_manager.enable_sort ()

        if self.default_active_name is None:
            self.select_first_row ()
        else:
            try:
                self.active = self.find_element (name = self.default_active_name)
            except KeyError:
                self.select_first_row ()

        self.scroll_to_active ()

        if self.default_focus_widget is None:
            # The element view isn't set as initial default right away because
            # the tree view sets the first column header button as focus widget
            # if the model contains no rows (like before load).
            self.default_focus_widget = self.element_view
        self.default_focus_widget.grab_focus ()

    def detach (self):

        state = self.app.state

        if self.active is not None:
            state.element = self.active.name

        self.page_manager.detach ()
        self.filter_manager.detach ()
        self.column_manager.detach ()
        self.window_state.detach ()

        self.gtk_window.hide ()

        state.save ()

        self.gtk_window.destroy ()

    def find_element (self, name):

        col = self.element_model.COL_ELEMENT

        for row in self.element_model:
            element = row[col]
            if element.name == name:
                return element
        else:
            raise KeyError ("no such element with name %r" % (name,))

    def set_filter_func (self, func):

        if func == self.filter_func:
            self.logger.debug ("ignoring attempt to set same filter func again")
            return

        if self.active is not None:
            self.default_active_name = self.active.name

        self.logger.debug ("changing filter func, refiltering element model")
        self.filter_func = func
        self.element_filter.refilter ()
        self.update_element_count ()

        if self.active is None and self.default_active_name is not None:
            try:
                self.active = self.find_element (name = self.default_active_name)
            except KeyError:
                pass
            else:
                self.scroll_to_active ()

    def set_busy_cursor (self, setting):

        window = self.gtk_window

        if not window.window:
            return

        if setting:
            window.window.set_cursor (gtk.gdk.Cursor (gtk.gdk.WATCH))
        else:
            window.window.set_cursor (None)

    def show_filter (self):

        self.logger.debug ("showing filter")
        self.widgets.filter_vbox.show ()
        self.filter_manager.pop_default_active ()

    def hide_filter (self):

        self.logger.debug ("hiding filter")
        self.widgets.filter_vbox.hide ()
        self.filter_manager.push_default_active ()

    def handle_window_realize (self, window):

        self.set_busy_cursor (not window.props.sensitive)

    def handle_show_filter_action_toggled (self, toggle_action):

        visible = toggle_action.props.active

        if visible:
            self.show_filter ()
        else:
            self.hide_filter ()

    def handle_filter_close_button_clicked (self, button):

        self.actions.show_filter.props.active = False

    def handle_show_about_action_activate (self, action):

        import GstInspector

        dialog = self.app.widget_factory.make_one ("about_dialog")

        # This workaround for the issue in GTK+ bug #345822 ensures that the
        # dialog displays the program name as set in the glade file when we run
        # against GTK+ 2.12.

        # TODO: Once we depend on a recent enough pygobject, remove these
        # checks.  The about dialog will pick up the application name from what
        # we set in main.
        try:
            gobject.set_application_name
        except AttributeError:
            try:
                dialog.props.program_name = _("GStreamer Inspector")
            except AttributeError:
                pass

        dialog.props.version = GstInspector.version

        dialog.run ()

        dialog.destroy ()

    def handle_window_delete_event (self, window, event):

        self.app.close_window (self)

    def handle_close_window_action_activate (self, action):

        self.app.close_window (self)

    def handle_load_started (self):

        """Data.Consumer method."""

        if self.active is not None:
            self.default_active_name = self.active.name

        self.filtered_row_insertions = 0
        self.element_filter.connect ("row-inserted", self.handle_filtered_row_inserted)

        if self.default_focus_widget is not None:
            focus_widget = self.gtk_window.get_focus ()
            if focus_widget:
                self.default_focus_widget = focus_widget

        self.gtk_window.props.sensitive = False
        self.set_busy_cursor (True)
        self.update_element_count ()

        self.filter_manager.handle_load_started ()

        if self.element_view.props.model:
            self.column_manager.disable_sort ()

    def handle_filtered_row_inserted (self, model, tree_path, tree_iter):

        self.filtered_row_insertions += 1
        if self.filtered_row_insertions % 11 == 0:
            self.update_element_count ()

    def handle_load_finished (self):

        """Data.Consumer method."""

        self.element_filter.disconnect_by_func (self.handle_filtered_row_inserted)
        del self.filtered_row_insertions

        self.set_busy_cursor (False)
        self.gtk_window.props.sensitive = True

        self.post_attach ()

    def update (self, element):

        if self.idle_update_source is not None:
            # Already queued up.
            return

        # The real update is deferred, we retrieve the selected row
        # when it is really executed.

        def real_update ():

            element = self.active
            if element is not None:
                self.page_manager.update (element)
                self.actions.show_documentation.entry = element.hierarchy[-1]
                self.app.state.element = element.name
                self.app.state.save ()

            self.idle_update_source = None
            return False

        self.idle_update_source = gobject.timeout_add (50, real_update)

    def update_element_count (self):

        """Update the label text to reflect the number of currently displayed
        elements in the list view."""

        model = self.element_filter
        count = model.iter_n_children (None)
        text = ngettext ("%i Element shown", "%i Elements shown", count)
        self.element_count_label.props.label = text % (count,)

    def handle_element_view_selection_changed (self, tree_selection):

        element = self.active
        if element is None:
            # Unselected.  The filter has changed and the element got filtered
            # out.  We do not update in this case; doing so would be too odd to
            # the user.  Things reach a consistent state again if the user
            # picks another element or changes the filter again to make the
            # previously selected one reappear (of which we stored the name in
            # self.default_active_name).
            return
        else:
            self.update (element)

    def select_first_row (self):

        view = self.element_view
        # Get the derived model, which accounts for filtering and sorting:
        model = view.props.model
        if model is None:
            return
        tree_iter = model.get_iter_first ()
        if tree_iter is None:
            return
        view.scroll_to_cell (model.get_path (tree_iter), view.get_column (0))
        selection = view.get_selection ()
        selection.select_iter (tree_iter)

    def scroll_to_active (self):

        view = self.element_view
        model = view.props.model
        col = self.element_model.COL_ELEMENT

        if model is None:
            return

        element = self.active
        if element is None:
            return

        for row in model:
            if row[col] == element:
                tree_iter = model.get_iter (row.path)
                view.scroll_to_cell (model.get_path (tree_iter),
                                     view.get_column (0),
                                     True, 0.5, 0.0)

from gettext import gettext as _