summaryrefslogtreecommitdiff
path: root/GstDebugViewer/GUI.py
blob: d043f6ca67a8d19c3beff22aa6eb266dbee14de3 (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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
# -*- coding: utf-8; mode: python; -*-
#
#  GStreamer Debug Viewer - View and analyze GStreamer debug log files
#
#  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 Debug Viewer GUI module."""

__author__ = u"René Stadler <mail@renestadler.de>"
__version__ = "0.1"

def _ (s):
    return s

import sys
import os
import os.path
from operator import add
from sets import Set
import logging

import pygtk
pygtk.require ("2.0")

import gobject
import gtk
import gtk.glade

## import gnome # FIXME

from GstDebugViewer import Common, Data, Main

class ColorTheme (object):

    def __init__ (self):

        self.colors = {}

    def add_color (self, key, fg_color, bg_color = None, bg_color2 = None):

        self.colors[key] = (fg_color, bg_color, bg_color2,)

    @staticmethod
    def hex_string_to_floats (s):

        if s.startswith ("#"):
            s = s[1:]
        return tuple ((float (int (hs, 16)) / 255. for hs in (s[:2], s[2:4], s[4:],)))

    def colors_float (self, key):

        return tuple ((self.hex_string_to_floats (color)
                       for color in self.colors[key]))

class LevelColorTheme (ColorTheme):

    pass

class LevelColorThemeTango (LevelColorTheme):

    def __init__ (self):

        LevelColorTheme.__init__ (self)

        self.add_color (Data.debug_level_none, None, None, None)
        self.add_color (Data.debug_level_log, "#000000", "#ad7fa8", "#e0a4d9")
        self.add_color (Data.debug_level_debug, "#000000", "#729fcf", "#8cc4ff")
        self.add_color (Data.debug_level_info, "#000000", "#8ae234", "#9dff3b")
        self.add_color (Data.debug_level_warning, "#000000", "#fcaf3e", "#ffc266")
        self.add_color (Data.debug_level_error, "#ffffff", "#ef2929", "#ff4545")

class LogModelBase (gtk.GenericTreeModel):

    __metaclass__ = Common.GUI.MetaModel

    columns = ("COL_TIME", gobject.TYPE_UINT64,
               "COL_PID", int,
               "COL_THREAD", gobject.TYPE_UINT64,
               "COL_LEVEL", object,               
               "COL_CATEGORY", str,
               "COL_FILENAME", str,
               "COL_LINE_NUMBER", int,
               "COL_FUNCTION", str,
               "COL_OBJECT", str,
               "COL_MESSAGE", str,)

    def __init__ (self):

        gtk.GenericTreeModel.__init__ (self)

        ##self.props.leak_references = False

        self.line_offsets = []
        self.line_levels = [] # FIXME: Not so nice!
        self.line_cache = {}

    def ensure_cached (self, line_offset):

        raise NotImplementedError ("derived classes must override this method")

    def access_offset (self, offset):

        raise NotImplementedError ("derived classes must override this method")

    def iter_rows_offset (self):

        for i, offset in enumerate (self.line_offsets):
            self.ensure_cached (offset)
            row = self.line_cache[offset]
            row[self.COL_LEVEL] = self.line_levels[i] # FIXME
            yield (row, offset,)

    def on_get_flags (self):

        flags = gtk.TREE_MODEL_LIST_ONLY | gtk.TREE_MODEL_ITERS_PERSIST

        return flags

    def on_get_n_columns (self):
        
        return len (self.column_types)

    def on_get_column_type (self, col_id):

        return self.column_types[col_id]

    def on_get_iter (self, path):

        if not path:
            return

        if len (path) > 1:
            # Flat model.
            return None

        line_index = path[0]

        if line_index > len (self.line_offsets) - 1:
            return None

        return line_index

    def on_get_path (self, rowref):

        line_index = rowref

        return (line_index,)

    def on_get_value (self, line_index, col_id):

        last_index = len (self.line_offsets) - 1

        if line_index > last_index:
            return None

        if col_id == self.COL_LEVEL:
            return self.line_levels[line_index]

        line_offset = self.line_offsets[line_index]
        self.ensure_cached (line_offset)

        value = self.line_cache[line_offset][col_id]
        if col_id == self.COL_MESSAGE:
            message_offset = value
            value = self.access_offset (line_offset + message_offset).strip ()

        return value

    def on_iter_next (self, line_index):

        last_index = len (self.line_offsets) - 1

        if line_index >= last_index:
            return None
        else:
            return line_index + 1

    def on_iter_children (self, parent):

        return self.on_iter_nth_child (parent, 0)

    def on_iter_has_child (self, rowref):

        return False

    def on_iter_n_children (self, rowref):

        if rowref is not None:
            return 0

        return len (self.line_offsets)

    def on_iter_nth_child (self, parent, n):

        last_index = len (self.line_offsets) - 1

        if parent or n > last_index:
            return None

        return n

    def on_iter_parent (self, child):

        return None

    ## def on_ref_node (self, rowref):

    ##     pass

    ## def on_unref_node (self, rowref):

    ##     pass

class LazyLogModel (LogModelBase):

    def __init__ (self, log_obj = None):

        LogModelBase.__init__ (self)

        self.__log_obj = log_obj

        if log_obj:
            self.set_log (log_obj)

    def set_log (self, log_obj):

        self.__fileobj = log_obj.fileobj

        self.line_cache.clear ()
        self.line_offsets = log_obj.line_cache.offsets
        self.line_levels = log_obj.line_cache.levels

    def access_offset (self, offset):

        self.__fileobj.seek (offset)
        return self.__fileobj.readline ()

    def ensure_cached (self, line_offset):

        if line_offset in self.line_cache:
            return

        if line_offset == 0:
            self.__fileobj.seek (0)
            line = self.__fileobj.readline ()
        else:
            # Seek a bit further backwards to verify that offset (still) points
            # to the beginning of a line:
            self.__fileobj.seek (line_offset - len (os.linesep))
            line_start = (self.__fileobj.readline () == os.linesep)
            if not line_start:
                # FIXME: We should re-read the file instead!
                raise ValueError ("file changed!")
            line = self.__fileobj.readline ()

        self.line_cache[line_offset] = Data.LogLine.parse_full (line)

class FilteredLogModel (LogModelBase):

    def __init__ (self, lazy_log_model):

        LogModelBase.__init__ (self)

        self.parent_model = lazy_log_model
        self.access_offset = lazy_log_model.access_offset
        self.ensure_cached = lazy_log_model.ensure_cached
        self.line_cache = lazy_log_model.line_cache
        self.reset ()
        
    def reset (self):

        del self.line_offsets[:]
        self.line_offsets += self.parent_model.line_offsets
        del self.line_levels[:]
        self.line_levels += self.parent_model.line_levels

    def add_filter (self, filter):

        func = filter.filter_func
        #enum = self.lazy_log_model.iter_rows_offset ()
        enum = self.iter_rows_offset ()
        self.line_offsets[:] = (offset for row, offset in enum
                                if func (row))

class Filter (object):

    pass

class DebugLevelFilter (Filter):

    def __init__ (self, debug_level):

        col_id = LogModelBase.COL_LEVEL
        def filter_func (row):
            return row[col_id] < debug_level
        self.filter_func = filter_func

# Sync with gst-inspector!
class Column (object):

    """A single list view column, managed by a ColumnManager instance."""

    name = None
    id = None
    label_header = None
    get_modify_func = None
    get_data_func = None
    get_sort_func = None

    def __init__ (self):

        view_column = gtk.TreeViewColumn (self.label_header)
        view_column.props.reorderable = True

        self.view_column = view_column

# FIXME: Merge with gst-inspector?
class SizedColumn (Column):

    default_size = None

    def compute_default_size (self, view, model):

        return None

# Sync with gst-inspector?
class TextColumn (SizedColumn):

    font_family = None

    def __init__ (self):

        Column.__init__ (self)

        column = self.view_column
        cell = gtk.CellRendererText ()
        column.pack_start (cell)

        if self.font_family:
            cell.props.family = self.font_family
            cell.props.family_set = True

        if self.get_data_func:
            data_func = self.get_data_func ()
            id_ = self.id
            def cell_data_func (column, cell, model, tree_iter):
                data_func (cell.props, model.get_value (tree_iter, id_), model.get_path (tree_iter))
            column.set_cell_data_func (cell, cell_data_func)
        elif not self.get_modify_func:
            column.add_attribute (cell, "text", self.id)
        else:
            modify_func = self.get_modify_func ()
            id_ = self.id
            def cell_data_func (column, cell, model, tree_iter):
                cell.props.text = modify_func (model.get (tree_iter, id_)[0])
            column.set_cell_data_func (cell, cell_data_func)

        column.props.resizable = True
        ## column.set_sort_column_id (self.id)

    def compute_default_size (self, view, model):

        values = self.get_values_for_size ()
        if not values:
            return SizedColumn.compute_default_size (self, view, model)

        cell = self.view_column.get_cells ()[0]

        if self.get_modify_func is not None:
            format = self.get_modify_func ()
        else:
            def identity (x):
                return x
            format = identity
        max_width = 0
        for value in values:
            cell.props.text = format (value)
            rect, x, y, w, h = self.view_column.cell_get_size ()
            max_width = max (max_width, w)

        return max_width

    def get_values_for_size (self):

        return ()

class TimeColumn (TextColumn):

    name = "time"
    label_header = _("Time")
    id = LazyLogModel.COL_TIME
    font_family = "monospace"

    @staticmethod
    def get_modify_func ():

        time_args = Data.time_args
        def format_time (value):
            # TODO: This is hard coded to omit hours as well as the last 3
            # digits at the end, since current gst uses g_get_current_time,
            # which has microsecond precision only.
            return time_args (value)[2:-3]

        return format_time

    def get_values_for_size (self):

        # TODO: Use more than just 0:00:00.000000000 to account for funny fonts
        # maybe? Well, or use monospaced...
        values = [0]

        return values

class LevelColumn (TextColumn):

    name = "level"
    label_header = _("L")
    id = LazyLogModel.COL_LEVEL

    def __init__ (self):

        TextColumn.__init__ (self)

        cell = self.view_column.get_cells ()[0]
        cell.props.xalign = .5

    @staticmethod
    def get_modify_func ():

        def format_level (value):
            return value.name[0]

        return format_level

    @staticmethod
    def get_data_func ():

        theme = LevelColorThemeTango ()
        colors = theme.colors
        def level_data_func (cell_props, level, path):
            cell_props.text = level.name[0]
            cell_colors = colors[level]
            # FIXME: Use GdkColors!
            cell_props.foreground = cell_colors[0]
            if path[0] % 2:
                cell_props.background = cell_colors[1]
            else:
                cell_props.background = cell_colors[2]

        return level_data_func

    def get_values_for_size (self):

        values = [Data.debug_level_log, Data.debug_level_debug,
                  Data.debug_level_info, Data.debug_level_warning,
                  Data.debug_level_error]

        return values

class PidColumn (TextColumn):

    name = "pid"
    label_header = _("PID")
    id = LazyLogModel.COL_PID
    font_family = "monospace"

    @staticmethod
    def get_modify_func ():

        return str

    def get_values_for_size (self):

        # TODO: Same as for TimeColumn.  There is no guarantee that 999999 is
        # the widest string; use fixed font or come up with something better.

        return ["999999"]

class ThreadColumn (TextColumn):

    name = "thread"
    label_header = _("Thread")
    id = LazyLogModel.COL_THREAD
    font_family = "monospace"

    @staticmethod
    def get_modify_func ():

        def format_thread (value):
            return "0x%07x" % (value,)

        return format_thread

    def get_values_for_size (self):

        # TODO: Same as for TimeColumn.  There is no guarantee that ffffff is
        # the widest string; use fixed font or come up with something better.

        return [int ("ffffff", 16)]

class CategoryColumn (TextColumn):

    name = "category"
    label_header = _("Category")
    id = LazyLogModel.COL_CATEGORY

    def get_values_for_size (self):

        return ["GST_LONG_CATEGORY", "somelongelement"]

class FilenameColumn (TextColumn):

    name = "filename"
    label_header = _("Filename")
    id = LazyLogModel.COL_FILENAME

    def get_values_for_size (self):

        return ["gstsomefilename.c"]

class FunctionColumn (TextColumn):

    name = "function"
    label_header = _("Function")
    id = LazyLogModel.COL_FUNCTION

    def get_values_for_size (self):

        return ["gst_this_should_be_enough"]

## class FullCodeLocation (TextColumn):

##     name = "code-location"
##     label_header = _("Code Location")
##     id = LazyLogModel.COL_FILENAME

##     def get_values_for_size (self):

##         return ["gstwhateverfile.c:1234"]

class ObjectColumn (TextColumn):

    name = "object"
    label_header = _("Object")
    id = LazyLogModel.COL_OBJECT

    def get_values_for_size (self):

        return ["longobjectname00"]

class MessageColumn (TextColumn):

    name = "message"
    label_header = _("Message")
    id = LazyLogModel.COL_MESSAGE

class ColumnManager (Common.GUI.Manager):

    column_classes = ()

    @classmethod
    def iter_item_classes (cls):

        return iter (cls.column_classes)

    def __init__ (self):

        self.view = None
        self.actions = None
        self.__columns_changed_id = None
        self.columns = []
        self.column_order = list (self.column_classes)

        self.action_group = gtk.ActionGroup ("ColumnActions")

        def make_entry (col_class):
            return ("show-%s-column" % (col_class.name,),
                    None,
                    col_class.label_header,
                    None,
                    None,
                    None,
                    True,)

        entries = [make_entry (cls) for cls in self.column_classes]
        self.action_group.add_toggle_actions (entries)

    def iter_items (self):

        return iter (self.columns)

    def attach (self):

        for col_class in self.column_classes:
            action = self.get_toggle_action (col_class)
            if action.props.active:
                self._add_column (col_class ())
            action.connect ("toggled",
                            self.__handle_show_column_action_toggled,
                            col_class.name)

        self.__columns_changed_id = self.view.connect ("columns-changed",
                                                       self.__handle_view_columns_changed)

    def detach (self):

        if self.__columns_changed_id is not None:
            self.view.disconnect (self.__columns_changed_id)
            self.__columns_changed_id = None

    def attach_sort (self):

        sort_model = self.view.props.model

        # Inform the sorted tree model of any custom sorting functions.
        for col_class in self.column_classes:
            if col_class.get_sort_func:
                sort_func = col_class.get_sort_func ()
                sort_model.set_sort_func (col_class.id, sort_func)

    def enable_sort (self):

        sort_model = self.view.props.model

        if sort_model:
            self.logger.debug ("activating sort")
            sort_model.set_sort_column_id (*self.default_sort)
            self.default_sort = None
        else:
            self.logger.debug ("not activating sort (no model set)")

    def disable_sort (self):

        self.logger.debug ("deactivating sort")

        sort_model = self.view.props.model

        self.default_sort = tree_sortable_get_sort_column_id (sort_model)

        sort_model.set_sort_column_id (TREE_SORTABLE_UNSORTED_COLUMN_ID,
                                       gtk.SORT_ASCENDING)

    def get_toggle_action (self, column_class):

        action_name = "show-%s-column" % (column_class.name,)
        return self.action_group.get_action (action_name)

    def get_initial_column_order (self):

        return tuple (self.column_classes)

    def _add_column (self, column):

        name = column.name
        pos = self.__get_column_insert_position (column)
        if self.view.props.fixed_height_mode:
            column.view_column.props.sizing = gtk.TREE_VIEW_COLUMN_FIXED
        self.columns.insert (pos, column)
        self.view.insert_column (column.view_column, pos)

    def _remove_column (self, column):

        self.columns.remove (column)
        self.view.remove_column (column.view_column)

    def __get_column_insert_position (self, column):

        col_class = self.find_item_class (name = column.name)
        pos = self.column_order.index (col_class)
        before = self.column_order[:pos]
        shown_names = [col.name for col in self.columns]
        for col_class in before:
            if not col_class.name in shown_names:
                pos -= 1
        return pos

    def __iter_next_hidden (self, column_class):

        pos = self.column_order.index (column_class)
        rest = self.column_order[pos + 1:]
        for next_class in rest:
            try:
                self.find_item (name = next_class.name)
            except KeyError:
                # No instance -- the column is hidden.
                yield next_class
            else:
                break

    def __handle_show_column_action_toggled (self, toggle_action, name):

        if toggle_action.props.active:
            try:
                # This should fail.
                column = self.find_item (name = name)
            except KeyError:
                col_class = self.find_item_class (name = name)
                self._add_column (col_class ())
            else:
                # Out of sync for some reason.
                return
        else:
            try:
                column = self.find_item (name = name)
            except KeyError:
                # Out of sync for some reason.
                return
            else:
                self._remove_column (column)

    def __handle_view_columns_changed (self, element_view):

        view_columns = element_view.get_columns ()
        new_visible = [self.find_item (view_column = column)
                       for column in view_columns]

        # We only care about reordering here.
        if len (new_visible) != len (self.columns):
            return

        if new_visible != self.columns:

            new_order = []
            for column in new_visible:
                col_class = self.find_item_class (name = column.name)
                new_order.append (col_class)
                new_order.extend (self.__iter_next_hidden (col_class))
            
            names = (column.name for column in new_visible)
            self.logger.debug ("visible columns reordered: %s",
                               ", ".join (names))

            self.columns[:] = new_visible
            self.column_order[:] = new_order

class ViewColumnManager (ColumnManager):

    column_classes = (TimeColumn, LevelColumn, PidColumn, ThreadColumn, CategoryColumn,
                      FilenameColumn, FunctionColumn, ObjectColumn, MessageColumn,)

    def __init__ (self, state):

        ColumnManager.__init__ (self)

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

        self.state = state

    def attach (self, view):

        self.view = view
        view.connect ("notify::model", self.__handle_notify_model)

        order = self.state.column_order
        if len (order) == len (self.column_classes):
            self.column_order[:] = order

        visible = self.state.columns_visible
        if not visible:
            visible = self.column_classes
        for col_class in self.column_classes:
            action = self.get_toggle_action (col_class)
            action.props.active = (col_class in visible)

        ColumnManager.attach (self)

    def detach (self):

        self.state.column_order = self.column_order
        self.state.columns_visible = self.columns

        return ColumnManager.detach (self)

    def size_column (self, column, view, model):

        if column.default_size is None:
            default_size = column.compute_default_size (view, model)
        else:
            default_size = column.default_size
        # FIXME: Abstract away fixed size setting in Column class!
        if default_size is None:
            # Dummy fallback:
            column.view_column.props.fixed_width = 50
            self.logger.warning ("%s column does not implement default size", column.name)
        else:
            column.view_column.props.fixed_width = default_size

    def _add_column (self, column):

        result = ColumnManager._add_column (self, column)
        model = self.view.props.model
        self.size_column (column, self.view, model)
        return result

    def _remove_column (self, column):

        column.default_size = column.view_column.props.fixed_width
        return ColumnManager._remove_column (self, column)

    def __handle_notify_model (self, view, gparam):

        model = self.view.props.model
        self.logger.debug ("model changed: %r", model)
        if model is None:
            return
        for column in self.iter_items ():
            self.size_column (column, view, model)

class Window (object):

    def __init__ (self, app):

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

        self.dispatcher = None
        self.progress_bar = None
        self.update_progress_id = None

        self.window_state = Common.GUI.WindowState ()
        self.column_manager = ViewColumnManager (app.state)

        self.actions = Common.GUI.Actions ()

        group = gtk.ActionGroup ("MenuActions")
        group.add_actions ([("FileMenuAction", None, _("_File")),
                            ("ViewMenuAction", None, _("_View")),
                            ("ViewColumnsMenuAction", None, _("_Columns")),
                            ("HelpMenuAction", None, _("_Help"))])
        self.actions.add_group (group)

        group = gtk.ActionGroup ("WindowActions")
        group.add_actions ([("new-window", gtk.STOCK_NEW, _("_New Window"), "<Ctrl>N"),
                            ("open-file", gtk.STOCK_OPEN, _("_Open File"), "<Ctrl>O"),
                            ("close-window", gtk.STOCK_CLOSE, _("Close _Window"), "<Ctrl>W"),
                            ("cancel-load", gtk.STOCK_CANCEL, None,),
                            ("show-about", gtk.STOCK_ABOUT, None)])
        ## group.add_toggle_actions ([("show-line-density", None, _("Line _Density"), "<Ctrl>D")])
        self.actions.add_group (group)

        group = gtk.ActionGroup ("RowActions")
        group.add_actions ([("edit-copy-line", gtk.STOCK_COPY, _("Copy line"), "<Ctrl>C"),
                            ("edit-copy-message", gtk.STOCK_COPY, _("Copy message")),
                            ("filter-out-higher-levels", None, _("Filter out higher debug levels"))])
        self.actions.add_group (group)

        self.actions.add_group (self.column_manager.action_group)

        self.file = None
        self.log_model = LazyLogModel ()
        self.log_filter = FilteredLogModel (self.log_model)

        glade_filename = os.path.join (Main.Paths.data_dir, "gst-debug-viewer.glade")
        self.widget_factory = Common.GUI.WidgetFactory (glade_filename)
        self.widgets = self.widget_factory.make ("main_window")

        ui_filename = os.path.join (Main.Paths.data_dir,
                                    "gst-debug-viewer.ui")
        self.ui_factory = Common.GUI.UIFactory (ui_filename, self.actions)

        self.ui_manager = ui = self.ui_factory.make ()
        menubar = ui.get_widget ("/ui/menubar")        
        self.widgets.vbox_main.pack_start (menubar, False, False, 0)
        self.view_popup = ui.get_widget ("/ui/menubar/ViewMenu").get_submenu ()

        self.gtk_window = self.widgets.main_window
        self.gtk_window.add_accel_group (ui.get_accel_group ())
        self.log_view = self.widgets.log_view
        self.log_view.drag_dest_unset ()
        self.log_view.props.fixed_height_mode = True

        self.log_view.connect ("button-press-event", self.handle_log_view_button_press_event)

        self.attach ()
        self.column_manager.attach (self.log_view)

    def get_top_attach_point (self):

        return self.widgets.vbox_main

    def attach (self):

        self.window_state.attach (window = self.gtk_window, state = self.app.state)

        self.clipboard = gtk.Clipboard (self.gtk_window.get_display (),
                                        gtk.gdk.SELECTION_CLIPBOARD)

        for action_name in ("new-window", "open-file", "close-window",
                            "cancel-load",
                            "edit-copy-line", "edit-copy-message",
                            "filter-out-higher-levels",
                            "show-about",):
            name = action_name.replace ("-", "_")
            action = getattr (self.actions, name)
            handler = getattr (self, "handle_%s_action_activate" % (name,))
            action.connect ("activate", handler)

        self.gtk_window.connect ("delete-event", self.handle_window_delete_event)

        self.features = []
        for plugin_feature in self.app.iter_plugin_features ():
            feature = plugin_feature ()
            feature.attach (self)
            self.features.append (feature)

        # FIXME: With multiple selection mode, browsing the list with key
        # up/down slows to a crawl! WTF is wrong with this stupid widget???
        ## sel = self.log_view.get_selection ()
        ## sel.set_mode (gtk.SELECTION_MULTIPLE)

    def detach (self):

        self.window_state.detach ()
        self.column_manager.detach ()

    def get_active_line_index (self):

        selection = self.log_view.get_selection ()
        model, tree_iter = selection.get_selected ()
        if tree_iter is None:
            raise ValueError ("no line selected")
        path = model.get_path (tree_iter)
        return path[0]

    def get_active_line (self):

        selection = self.log_view.get_selection ()
        model, tree_iter = selection.get_selected ()
        if tree_iter is None:
            raise ValueError ("no line selected")
        model = self.log_view.props.model
        return model.get (tree_iter, *LogModelBase.column_ids)

    def close (self, *a, **kw):

        self.logger.debug ("closing window, detaching")
        self.detach ()
        self.gtk_window.hide ()
        self.logger.debug ("requesting close from app")
        self.app.close_window (self)

    def handle_window_delete_event (self, window, event):

        self.actions.close_window.activate ()

    def handle_new_window_action_activate (self, action):

        pass

    def handle_open_file_action_activate (self, action):

        dialog = gtk.FileChooserDialog (None, self.gtk_window,
                                        gtk.FILE_CHOOSER_ACTION_OPEN,
                                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                         gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT,))
        response = dialog.run ()
        dialog.hide ()
        if response == gtk.RESPONSE_ACCEPT:
            self.set_log_file (dialog.get_filename ())
        dialog.destroy ()

    def handle_cancel_load_action_activate (self, action):

        self.logger.debug ("cancelling data load")

        self.set_log_file (None)
        if self.progress_dialog:
            self.progress_dialog.destroy ()
            self.progress_dialog = None
        self.progress_bar = None
        if self.update_progress_id is not None:
            gobject.source_remove (self.update_progress_id)
            self.update_progress_id = None

    def handle_close_window_action_activate (self, action):

        self.close ()

    def handle_edit_copy_line_action_activate (self, action):

        line_index = self.get_active_line_index ()
        line = self.log_file.get_full_line (line_index)
        self.logger.warning ("FIXME: This gets the wrong level; we still have the level in the model only (d'oh)")
        self.clipboard.set_text (line.line_string ())

    def handle_edit_copy_message_action_activate (self, action):

        col_id = LogModelBase.COL_MESSAGE
        self.clipboard.set_text (self.get_active_line ()[col_id])

    def handle_filter_out_higher_levels_action_activate (self, action):

        row = self.get_active_line ()
        debug_level = row[LogModelBase.COL_LEVEL]

        try:
            target_level = debug_level.higher_level ()
        except ValueError:
            return
        self.log_filter.add_filter (DebugLevelFilter (target_level))

        # FIXME:
        self.log_view.props.model = gtk.TreeStore (str)
        self.log_view.props.model = self.log_filter

    def handle_show_about_action_activate (self, action):

        from GstDebugViewer import version

        dialog = self.widget_factory.make_one ("about_dialog")
        dialog.props.version = version
        dialog.run ()
        dialog.destroy ()

    @staticmethod
    def _timestamp_cell_data_func (column, renderer, model, tree_iter):

        ts = model.get_value (tree_iter, LogModel.COL_TIME)
        renderer.props.text = Data.time_args (ts)

    def _message_cell_data_func (self, column, renderer, model, tree_iter):

        offset = model.get_value (tree_iter, LogModel.COL_MESSAGE_OFFSET)
        self.log_file.seek (offset)
        renderer.props.text = strip_escape (self.log_file.readline ().strip ())

    def set_log_file (self, filename):

        if filename is None:
            if self.dispatcher is not None:
                self.dispatcher.cancel ()
            self.dispatcher = None
            self.log_file = None
            self.have_log_file_changed ()
        else:
            self.logger.debug ("setting log file %r", filename)

            self.dispatcher = Common.Data.GSourceDispatcher ()
            self.log_file = Data.LogFile (filename, self.dispatcher)
            self.log_file.consumers.append (self)
            self.log_file.start_loading ()

    def have_log_file_changed (self):

        for feature in self.features:
            feature.handle_log_file_changed ()

    def handle_log_view_button_press_event (self, view, event):

        if event.button != 3:
            return False

        self.view_popup.popup (None, None, None, event.button, event.get_time ())
        return True

    def handle_load_started (self):

        self.logger.debug ("load has started")

        widgets = self.widget_factory.make ("progress_dialog")
        dialog = widgets.progress_dialog
        dialog.connect ("response", self.handle_progress_dialog_response)
        self.progress_dialog = dialog
        self.progress_bar = widgets.progress_bar
        dialog.set_transient_for (self.gtk_window)
        dialog.show ()

        self.update_progress_id = gobject.timeout_add (250, self.update_load_progress)

    def handle_progress_dialog_response (self, dialog, response):

        self.actions.cancel_load.activate ()

    def update_load_progress (self):

        if not self.progress_bar:
            self.logger.debug ("progress window is gone, removing progress update timeout")
            self.update_progress_id = None
            return False

        progress = self.log_file.get_load_progress ()
        self.logger.debug ("update progress to %i%%", progress * 100)
        self.progress_bar.props.fraction = progress

        return True

    def handle_load_finished (self):

        self.logger.debug ("load has finshed")

        if self.update_progress_id is not None:
            gobject.source_remove (self.update_progress_id)
            self.update_progress_id = None

        self.progress_dialog.hide ()
        self.progress_dialog.destroy ()
        self.progress_dialog = None
        self.progress_bar = None

        self.log_model.set_log (self.log_file)

        self.log_filter.reset ()

        def idle_set ():
            ##self.log_view.props.model = self.log_model
            self.log_view.props.model = self.log_filter
            self.have_log_file_changed ()
            return False

        gobject.idle_add (idle_set)

class AppState (Common.GUI.AppState):

    geometry = Common.GUI.StateInt4 ("window-geometry")
    maximized = Common.GUI.StateBool ("window-maximized")

    column_order = Common.GUI.StateItemList ("column-order", ViewColumnManager)
    columns_visible = Common.GUI.StateItemList ("columns-visible", ViewColumnManager)

class App (object):

    def __init__ (self):

        self.load_plugins ()

        self.attach ()

    def load_plugins (self):

        from GstDebugViewer import Plugins

        self.plugins = list (Plugins.load ([os.path.dirname (Plugins.__file__)]))

    def iter_plugin_features (self):

        for plugin in self.plugins:
            for feature in plugin.features:
                yield feature

    def attach (self):

        config_home = Common.utils.XDG.CONFIG_HOME

        state_filename = os.path.join (config_home, "gst-debug-viewer", "state")

        self.state = AppState (state_filename)

        self.windows = [Window (self)]

    def detach (self):

        # TODO: If we take over deferred saving from the inspector, specify now
        # = True here!
        self.state.save ()

    def run (self):

        try:
            Common.Main.MainLoopWrapper (gtk.main, gtk.main_quit).run ()
        except:
            raise
        else:
            self.detach ()

    def close_window (self, window):

        # For some reason, going down takes some time for large files.  Let's
        # block until the window is hidden:
        gobject.idle_add (gtk.main_quit)
        gtk.main ()
        
        gtk.main_quit ()

import time

class TestParsingPerformance (object):

    def __init__ (self, filename):

        self.main_loop = gobject.MainLoop ()
        self.log_file = Data.LogFile (filename, Common.Data.DefaultDispatcher ())
        self.log_file.consumers.append (self)

    def start (self):

        self.log_file.start_loading ()

    def handle_load_started (self):

        self.start_time = time.time ()

    def handle_load_finished (self):

        diff = time.time () - self.start_time
        print "line cache built in %0.1f ms" % (diff * 1000.,)

        start_time = time.time ()
        model = LazyLogModel (self.log_file)
        for row in model:
            pass
        diff = time.time () - start_time
        print "data parsed in %0.1f ms" % (diff * 1000.,)
        print "overall time spent: %0.1f s" % (time.time () - self.start_time,)

        import resource
        rusage = resource.getrusage (resource.RUSAGE_SELF)
        print "time spent in user mode: %.2f s" % (rusage.ru_utime,)
        print "time spent in system mode: %.2f s" % (rusage.ru_stime,)

def main ():

    if len (sys.argv) > 1 and sys.argv[1] == "benchmark":
        test = TestParsingPerformance (sys.argv[2])
        test.start ()
        return

    app = App ()

    window = app.windows[0]
    if len (sys.argv) > 1:
        window.set_log_file (sys.argv[-1])

    app.run ()

if __name__ == "__main__":
    main ()