performance-log-viewer.py 109 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#!/usr/bin/env python3

"""
performance-log-viewer.py -- GIMP performance log viewer
Copyright (C) 2018  Ell

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 <https://www.gnu.org/licenses/>.


Usage: performance-log-viewer.py < infile
"""

24 25
import builtins, sys, os, math, statistics, bisect, functools, enum, re, \
       subprocess
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

from collections import namedtuple
from xml.etree   import ElementTree

import gi
gi.require_version ("Gdk", "3.0")
gi.require_version ("Gtk", "3.0")
from gi.repository import GLib, GObject, Gio, Gdk, Gtk, Pango

def compose (head = None, *tail):
    return (
        lambda *args, **kwargs: head (compose (*tail) (*args, **kwargs))
    ) if tail else head or (lambda x: x)

def div (x, y):
    return x / y     if y     else \
           +math.inf if x > 0 else \
           -math.inf if x < 0 else \
           None

def format_float (x):
    return "%g" % (round (100 * x) / 100)

def format_percentage (x, digits = 0):
50
    return "%%.%df%%%%" % digits % (100 * x)
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

def format_size (size):
    return GLib.format_size_full (size, GLib.FormatSizeFlags.IEC_UNITS)

def format_duration (t):
    return "%02d:%02d:%02d.%02d" % (int (t / 3600),
                                    int (t / 60) % 60,
                                    int (t % 60),
                                    round (100 * t) % 100)

def format_color (color):
    return "#%02x%02x%02x" % tuple (
        map (lambda x: min (max (round (255 * x), 0), 255), color)
    )

def is_bright_color (color):
    return max (tuple (color)[0:3]) > 0.5

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
def blend_colors (color1, color2, amount):
    color1 = tuple (color1)
    color2 = tuple (color2)

    a1 = color1[-1]
    a2 = color2[-1]

    a = (1 - amount) * a1 + amount * a2

    return tuple (a and ((1 - amount) * a1 * c1 + amount * a2 * c2) / a
                  for c1, c2 in zip (color1[:-1], color2[:-1])) + (a,)

def rounded_rectangle (cr, x, y, width, height, radius):
    radius = min (radius, width / 2, height / 2)

    cr.arc (x + radius, y + radius, radius, -math.pi, -math.pi / 2)
    cr.rel_line_to (width - 2 * radius, 0)

    cr.arc (x + width - radius, y + radius, radius, -math.pi / 2, 0)
    cr.rel_line_to (0, height - 2 * radius)

    cr.arc (x + width - radius, y + height - radius, radius, 0, math.pi / 2)
    cr.rel_line_to (-(width - 2 * radius), 0)

    cr.arc (x + radius, y + height - radius, radius, math.pi / 2, math.pi)
    cr.rel_line_to (0, -(height - 2 * radius))

    cr.close_path ()

98 99 100 101 102
def get_basename (path):
    match = re.fullmatch (".*[\\\\/](.+?)[\\\\/]?", path)

    return match[1] if match else path

103 104 105 106 107 108 109 110 111 112
search_path = list (filter (
    bool,
    os.environ.get ("PERFORMANCE_LOG_VIEWER_PATH", ".").split (":")
))

editor_command  = os.environ.get ("PERFORMANCE_LOG_VIEWER_EDITOR",
                                  "xdg-open {file}")
editor_command += " &"

def find_file (filename):
113 114
    def lookup (filename):
        filename = re.sub ("[\\\\/]", GLib.DIR_SEPARATOR_S, filename)
115

116 117
        if GLib.path_is_absolute (filename):
            file = Gio.File.new_for_path (filename)
118

119 120
            if file.query_exists ():
                return file
121

122 123
        for path in search_path:
            rest = filename
124

125 126
            while rest:
                file = Gio.File.new_for_path (GLib.build_filenamev ((path, rest)))
127

128 129 130 131 132 133 134 135
                if file.query_exists ():
                    return file

                sep = rest.find (GLib.DIR_SEPARATOR_S)

                rest = rest[sep + 1:] if sep >= 0 else ""

        return None
136

137 138
    if filename not in find_file.cache:
        find_file.cache[filename] = lookup (filename)
139

140
    return find_file.cache[filename]
141

142
find_file.cache = {}
143

144 145 146 147 148
def run_editor (file, line):
    subprocess.call (editor_command.format (file = "\"%s\"" % file.get_path (),
                                            line = line),
                     shell = True)

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
VariableType = namedtuple ("VariableType",
                           ("parse", "format", "format_numeric"))

var_types = {
    "boolean": VariableType (
        parse          = int,
        format         = compose (str, bool),
        format_numeric = format_float
    ),

    "integer": VariableType (
        parse          = int,
        format         = format_float,
        format_numeric = None
    ),

    "size": VariableType (
        parse          = int,
        format         = format_size,
        format_numeric = None
    ),

    "size-ratio": VariableType (
        parse          = lambda x: div (*map (int, x.split ("/"))),
        format         = format_percentage,
        format_numeric = None
    ),

    "int-ratio": VariableType (
        parse          = lambda x: div (*map (int, x.split (":"))),
        format         = lambda x: "%g:%g" % (
180 181 182
                             (0, 0)                     if math.isnan (x) else
                             (1, 0)                     if x == math.inf  else
                             (-1, 0)                    if x == -math.inf else
183
                             (0, 1)                     if x == 0         else
184
                             (round (100 * x) / 100, 1) if abs (x) >  1   else
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
                             (1, round (100 / x) / 100)
                         ),
        format_numeric = None
    ),

    "percentage": VariableType (
        parse          = float,
        format         = format_percentage,
        format_numeric = None
    ),

    "duration": VariableType (
        parse          = float,
        format         = format_duration,
        format_numeric = None
    ),

    "rate-of-change": VariableType (
        parse          = float,
        format         = lambda x: "%s/s" % format_size (x),
        format_numeric = None
    )
}
var_types = {
    type: VariableType (
        parse          = parse,
        format         = lambda x, f = format: \
                             f (x) if x is not None else "N/A",
        format_numeric = lambda x, f = format_numeric or format:
                             f (x) if x is not None else "N/A"
    )
    for type, (parse, format, format_numeric) in var_types.items ()
}

# Read performance log from STDIN
log = ElementTree.fromstring (sys.stdin.buffer.read ())

222
Variable = namedtuple ("Variable", ("type", "desc", "color"))
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
Value    = namedtuple ("Value",    ("value", "raw"))

var_colors = [
    (0.8, 0.4, 0.4),
    (0.8, 0.6, 0.4),
    (0.4, 0.8, 0.4),
    (0.8, 0.8, 0.4),
    (0.4, 0.4, 0.8),
    (0.4, 0.8, 0.8),
    (0.8, 0.4, 0.8),
    (0.8, 0.8, 0.8)
]

var_defs = {}

for var in log.find ("var-defs"):
    color = var_colors[len (var_defs) % len (var_colors)]

241 242 243
    var_defs[var.get ("name")] = Variable (var.get ("type"),
                                           var.get ("desc"),
                                           color)
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

AddressInfo = namedtuple ("AddressInfo", ("id",
                                          "name",
                                          "object",
                                          "symbol",
                                          "offset",
                                          "source",
                                          "line"))

address_map = {}

if log.find ("address-map"):
    for address in log.find ("address-map").iterfind ("address"):
        value = int (address.get ("value"), 0)

        object = address.find ("object").text
        symbol = address.find ("symbol").text
        base   = address.find ("base").text
        source = address.find ("source").text
        line   = address.find ("line").text

        address_map[value] = AddressInfo (
            id     = int (base, 0) if base else value,
            name   = symbol or base or hex (value),
            object = object,
            symbol = symbol,
            offset = value - int (base, 0) if base else None,
            source = source,
            line   = int (line) if line else None
        )

class ThreadState (enum.Enum):
    SUSPENDED = enum.auto ()
    RUNNING   = enum.auto ()

    def __str__ (self):
        return {
            ThreadState.SUSPENDED: "S",
            ThreadState.RUNNING:   "R"
        }[self]

Thread = namedtuple ("Thread", ("id", "name", "state", "frames"))
Frame  = namedtuple ("Frame",  ("id", "address", "info"))

Sample = namedtuple ("Sample", ("t", "vars", "markers", "backtrace"))
Marker = namedtuple ("Marker", ("id", "t", "description"))

samples = []
markers = []

for element in log.find ("samples"):
    if element.tag == "sample":
        sample = Sample (
            t         = int (element.get ("t")),
            vars      = {},
            markers   = markers,
            backtrace = []
        )

        for var in element.find ("vars"):
            sample.vars[var.tag] = Value (
                value = var_types[var_defs[var.tag].type].parse (var.text) \
                        if var.text else None,
                raw   = var.text.strip () if var.text else None
            )

        if element.find ("backtrace"):
            for thread in element.find ("backtrace").iterfind ("thread"):
                id      = thread.get ("id")
                name    = thread.get ("name")
                running = thread.get ("running")

                t = Thread (
                    id     = int (id),
                    name   = name,
                    state  = ThreadState.RUNNING if running and int (running) \
                             else ThreadState.SUSPENDED,
                    frames = []
                )

                for frame in thread.iterfind ("frame"):
                    address = int (frame.get ("address"), 0)

                    info = address_map.get (address, None)

                    if not info:
                        info = AddressInfo (
                            id     = address,
                            name   = hex (address),
                            object = None,
                            symbol = None,
                            offset = None,
                            source = None,
                            line   = None
                        )

                    t.frames.append (Frame (
                        id      = len (t.frames),
                        address = address,
                        info    = info
                    ))

                sample.backtrace.append (t)

        samples.append (sample)

        markers = []
    elif element.tag == "marker":
        marker = Marker (
            id          = int (element.get ("id")),
            t           = int (element.get ("t")),
            description = element.text.strip () if element.text else None
        )

        markers.append (marker)

if samples and markers:
    samples[-1].markers += markers

markers = None

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
DELTA_SAME = __builtins__.object ()

def delta_encode (dest, src):
    if type (dest) == type (src):
        if dest == src:
            return DELTA_SAME
        elif type (dest) == tuple:
            return tuple (delta_encode (d, s) for d, s in zip (dest, src)) + \
                   dest[len (src):]

    return dest

def delta_decode (dest, src):
    if dest == DELTA_SAME:
        return src
    elif type (dest) == type (src):
        if type (dest) == tuple:
            return tuple (delta_decode (d, s) for d, s in zip (dest, src)) + \
                   dest[len (src):]

    return dest

class History (GObject.GObject):
    Source = namedtuple ("HistorySource", ("get", "set"))

    def __init__ (self):
        GObject.GObject.__init__ (self)

        self.sources = []

        self.state = None

        self.undo_stack = []
        self.redo_stack = []

400
        self.blocked         = 0
401 402 403 404 405 406 407 408 409 410 411 412 413 414
        self.n_groups        = 0
        self.pending_record  = False

    @GObject.Property (type = bool, default = False)
    def can_undo (self):
        return bool (self.undo_stack)

    @GObject.Property (type = bool, default = False)
    def can_redo (self):
        return bool (self.redo_stack)

    def add_source (self, get, set):
        self.sources.append (self.Source (get, set))

415 416 417 418 419 420 421 422 423
    def block (self):
        self.blocked += 1

    def unblock (self):
        self.blocked -= 1

    def is_blocked (self):
        return self.blocked > 0

424 425 426 427 428 429 430 431 432 433
    def start_group (self):
        self.n_groups += 1

    def end_group (self):
        self.n_groups -= 1

        if self.n_groups == 0 and self.pending_record:
            self.record ()

    def record (self):
434
        if self.is_blocked ():
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
            return

        if self.n_groups == 0:
            state = tuple (source.get () for source in self.sources)

            if self.state is None:
                self.state = state
            else:
                self.pending_record = False

                delta = delta_encode (self.state, state)

                if delta == DELTA_SAME:
                    return

                self.undo_stack.append (delta_encode (self.state, state))
                self.redo_stack = []

                self.state = state

                self.notify ("can-undo")
                self.notify ("can-redo")
        else:
            self.pending_record = True

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    def update (self):
        if self.is_blocked ():
            return

        if self.n_groups == 0:
            state = tuple (source.get () for source in self.sources)

            for stack in self.undo_stack, self.redo_stack:
                if stack:
                    stack[-1] = delta_encode (delta_decode (stack[-1],
                                                            self.state),
                                              state)

            self.state = state
        else:
            self.pending_record = True

477
    def move (self, src, dest):
478
        self.block ()
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

        state = src.pop ()

        for source, substate, prev_substate in \
            zip (self.sources, self.state, state):
            if prev_substate != DELTA_SAME:
                source.set (delta_decode (prev_substate, substate))

        state = delta_decode (state, self.state)

        dest.append (delta_encode (self.state, state))

        self.state = state

        self.notify ("can-undo")
        self.notify ("can-redo")

496
        self.unblock ()
497 498 499 500 501 502 503 504 505

    def undo (self):
        self.move (self.undo_stack, self.redo_stack)

    def redo (self):
        self.move (self.redo_stack, self.undo_stack)

history = History ()

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
class SelectionOp (enum.Enum):
    REPLACE   = enum.auto ()
    ADD       = enum.auto ()
    SUBTRACT  = enum.auto ()
    INTERSECT = enum.auto ()
    XOR       = enum.auto ()

class Selection (GObject.GObject):
    __gsignals__ = {
        "changed":           (GObject.SIGNAL_RUN_FIRST, None, ()),
        "change-complete":   (GObject.SIGNAL_RUN_FIRST, None, ()),
        "highlight-changed": (GObject.SIGNAL_RUN_FIRST, None, ())
    }

    def __init__ (self, iter = ()):
        GObject.GObject.__init__ (self)

        self.selection  = set (iter)
        self.highlight  = None
        self.cursor     = None
        self.cursor_dir = 0

        self.pending_change_completion = False

530 531 532 533 534 535
    def __eq__ (self, other):
        return type (self)     == type (other)     and \
               self.selection  == other.selection  and \
               self.cursor     == other.cursor     and \
               self.cursor_dir == other.cursor_dir

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
    def __str__ (self):
        n_sel = len (self.selection)

        if n_sel == 0 or n_sel == len (samples):
            return "All Samples"
        elif n_sel == 1:
            i, = self.selection

            return "Sample %d" % i
        else:
            sel = list (self.selection)

            sel.sort ()

            if all (sel[i] + 1 == sel[i + 1] for i in range (n_sel - 1)):
                return "Samples %d–%d" % (sel[0], sel[-1])
            else:
                return "%d Samples" % n_sel

    def copy (self):
        selection = Selection ()

        selection.highlight  = self.highlight
        selection.cursor     = self.cursor
        selection.cursor_dir = self.cursor_dir
        selection.selection  = self.selection.copy ()

        return selection

    def get_effective_selection (self):
        if self.selection:
            return self.selection
        else:
            return set (range (len (samples)))

    def select (self, selection, op = SelectionOp.REPLACE):
        if op == SelectionOp.REPLACE:
            self.selection = selection.copy ()
        elif op == SelectionOp.ADD:
            self.selection |= selection
        elif op == SelectionOp.SUBTRACT:
            self.selection -= selection
        elif op == SelectionOp.INTERSECT:
            self.selection &= selection
        elif op == SelectionOp.XOR:
            self.selection.symmetric_difference_update (selection)

        if len (self.selection) == 1:
            (self.cursor,) = self.selection
        else:
            self.cursor = None

        self.cursor_dir = 0

        self.pending_change_completion = True

        self.emit ("changed")

    def select_range (self, first, last, op = SelectionOp.REPLACE):
        if first > last:
            temp  = first
            first = last
            last  = temp

        first = max (first, 0)
        last  = min (last, len (samples) - 1)

        if first <= last:
            self.select (set (range (first, last + 1)), op)
        else:
            self.select (set (), op)

    def change_complete (self):
        if self.pending_change_completion:
            self.pending_change_completion = False

612 613 614 615
            history.start_group ()

            history.record ()

616 617
            self.emit ("change-complete")

618 619
            history.end_group ()

620 621 622 623 624
    def set_highlight (self, highlight):
        self.highlight = highlight

        self.emit ("highlight-changed")

625 626 627 628 629 630 631 632 633 634 635 636 637 638
    def source_get (self):
        return self.copy ()

    def source_set (self, selection):
        self.cursor     = selection.cursor
        self.cursor_dir = selection.cursor_dir
        self.selection  = selection.selection.copy ()

        self.emit ("changed")
        self.emit ("change-complete")

    def add_history_source (self):
        history.add_source (self.source_get, self.source_set)

639
selection = Selection ()
640
selection.add_history_source ()
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

class FindSamplesPopover (Gtk.Popover):
    def __init__ (self, *args, **kwargs):
        Gtk.Popover.__init__ (self, *args, **kwargs)

        vbox = Gtk.Box (orientation  = Gtk.Orientation.VERTICAL,
                        border_width = 20,
                        spacing      = 8)
        self.add (vbox)
        vbox.show ()

        entry = Gtk.Entry (width_chars      = 40,
                           placeholder_text = "Python expression")
        self.entry = entry
        vbox.pack_start (entry, False, False, 0)
        entry.show ()

        entry.connect ("activate", self.find_samples)

        entry.get_buffer ().connect (
            "notify::text",
            lambda *args: self.entry.get_style_context ().remove_class ("error")
        )

        frame = Gtk.Frame (label       = "Selection",
                           shadow_type = Gtk.ShadowType.NONE)
        vbox.pack_start (frame, False, False, 8)
        frame.get_label_widget ().get_style_context ().add_class ("dim-label")
        frame.show ()

        vbox2 = Gtk.Box (orientation  = Gtk.Orientation.VERTICAL,
                         border_width = 8,
                         spacing      = 8)
        frame.add (vbox2)
        vbox2.show ()

        self.radios = []

679
        radio = Gtk.RadioButton.new_with_mnemonic (None, "_Replace")
680 681 682 683
        self.radios.append ((radio, SelectionOp.REPLACE))
        vbox2.pack_start (radio, False, False, 0)
        radio.show ()

684
        radio = Gtk.RadioButton.new_with_mnemonic_from_widget (radio, "_Add")
685 686 687 688
        self.radios.append ((radio, SelectionOp.ADD))
        vbox2.pack_start (radio, False, False, 0)
        radio.show ()

689
        radio = Gtk.RadioButton.new_with_mnemonic_from_widget (radio, "_Subtract")
690 691 692 693
        self.radios.append ((radio, SelectionOp.SUBTRACT))
        vbox2.pack_start (radio, False, False, 0)
        radio.show ()

694
        radio = Gtk.RadioButton.new_with_mnemonic_from_widget (radio, "_Intersect")
695 696 697 698
        self.radios.append ((radio, SelectionOp.INTERSECT))
        vbox2.pack_start (radio, False, False, 0)
        radio.show ()

699
        button = Gtk.Button.new_with_mnemonic ("_Find")
700
        vbox.pack_start (button, False, False, 0)
701
        button.set_halign (Gtk.Align.CENTER)
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
        button.show ()

        button.connect ("clicked", self.find_samples)

    def do_hide (self):
        self.entry.set_text ("")
        self.entry.get_style_context ().remove_class ("error")

        Gtk.Popover.do_hide (self)

    def find_samples (self, *args):
        def var_name (var):
            return var.replace ("-", "_")

        try:
            f = eval ("lambda thread, function, %s: %s" % (
                ", ".join (map (var_name, var_defs)),
                self.entry.get_text ()))
        except:
            self.entry.get_style_context ().add_class ("error")

            return

        sel = set ()

        for i in range (len (samples)):
            try:
729
                def match_thread (thread, id, state = None):
730 731 732 733 734 735 736
                    return (id is None or                         \
                            (type (id) == int                 and \
                             id == thread.id)                 or  \
                            (type (id) == str                 and \
                             thread.name                      and \
                             re.fullmatch (id, thread.name))) and \
                           (state is None                     or  \
737
                            re.fullmatch (state, str (thread.state)))
738

739 740 741
                def thread (id, state = None):
                    return any (match_thread (thread, id, state)
                                for thread in samples[i].backtrace or [])
742

743
                def function (name, id = None, state = None):
744
                    for thread in samples[i].backtrace or []:
745
                        if match_thread (thread, id, state):
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
                            for frame in thread.frames:
                                if re.fullmatch (name, frame.info.name):
                                    return True

                    return False

                if f (thread, function, **{
                    var_name (var): value.value
                    for var, value in samples[i].vars.items ()
                }):
                    sel.add (i)
            except:
                pass

        op = [op for radio, op in self.radios if radio.get_active ()][0]

        selection.select (sel, op)

        selection.change_complete ()

        self.hide ()

class CellRendererColorToggle (Gtk.CellRendererToggle):
    padding = 3

    color = GObject.Property (type = Gdk.RGBA, default = Gdk.RGBA (0, 0, 0))

    def do_render (self, cr, widget, background_area, cell_area, flags):
        state    = widget.get_state ()
        style    = widget.get_style_context ()
        bg_color = style.get_background_color (state)
        active   = self.get_property ("active")
        size     = max (min (cell_area.width, cell_area.height) -
                        2 * self.padding,
                        0)

        (r, g, b, a) = self.color

        if is_bright_color (bg_color):
            bg = (r, g, b)
            fg = (0.75 * r, 0.75 * g, 0.75 * b)
        else:
            bg = (0.75 * r, 0.75 * g, 0.75 * b)
            fg = (r, g, b)

        x = cell_area.x + (cell_area.width  - size) // 2
        y = cell_area.y + (cell_area.height - size) // 2

        cr.rectangle (x, y, size, size)

        if active:
            cr.set_source_rgba (*bg)
        else:
            Gdk.cairo_set_source_rgba (cr, bg_color)

        cr.fill_preserve ()

        cr.set_source_rgb (*fg)
        cr.set_line_width (2)
        cr.stroke ()

class VariableSet (Gtk.TreeView):
    class Store (Gtk.ListStore):
        NAME   = 0
810
        DESC   = 1
811
        COLOR  = 2
812
        ACTIVE = 3
813 814

        def __init__ (self):
815
            Gtk.ListStore.__init__ (self, str, str, Gdk.RGBA, bool)
816

817 818 819 820 821
            for var, var_def in var_defs.items ():
                i = self.append ((var,
                                  var_def.desc,
                                  Gdk.RGBA (*var_def.color),
                                  False))
822 823 824 825 826 827 828

    def __init__ (self, *args, **kwargs):
        Gtk.TreeView.__init__ (self, *args, headers_visible = False, **kwargs)

        store = self.Store ()
        self.store = store
        self.set_model (store)
829
        self.set_tooltip_column (store.DESC)
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

        col = Gtk.TreeViewColumn ()
        self.append_column (col)

        cell = CellRendererColorToggle ()
        col.pack_start (cell, False)
        col.add_attribute (cell, "active", store.ACTIVE)
        col.add_attribute (cell, "color", store.COLOR)

        cell.connect ("toggled", self.var_toggled)

        cell = Gtk.CellRendererText ()
        col.pack_start (cell, True)
        col.add_attribute (cell, "text", store.NAME)

    def var_toggled (self, cell, path):
        self.store[path][self.store.ACTIVE] = not cell.get_property ("active")

class SampleGraph (Gtk.DrawingArea):
    def __init__ (self, model = None, *args, **kwargs):
        Gtk.DrawingArea.__init__ (self, *args, can_focus = True, **kwargs)

        self.style_widget = Gtk.Entry ()

        self.model = model

        if model:
            model.connect ("row-changed", lambda *args: self.update ())

            self.update ()

        self.selection = None
        self.sel       = None

        selection.connect ("changed", self.selection_changed)
        selection.connect ("highlight-changed",
                           lambda selection: self.queue_draw ())

        self.add_events (Gdk.EventMask.BUTTON_PRESS_MASK   |
                         Gdk.EventMask.BUTTON_RELEASE_MASK |
                         Gdk.EventMask.KEY_PRESS_MASK      |
                         Gdk.EventMask.KEY_RELEASE_MASK)

        self.selection_changed (selection)

    def sample_to_x (self, i):
        if not samples:
            return None

        width     = self.get_allocated_width ()
        n_samples = max (len (samples), 2)

        return 1 + (width - 3) * i / (n_samples - 1)

    def sample_to_range (self, i):
        if not samples:
            return None

        width     = self.get_allocated_width ()
        n_samples = max (len (samples), 2)

        return (1 + math.floor ((width - 3) * (i - 0.5) / (n_samples - 1)),
                1 + math.ceil  ((width - 3) * (i + 0.5) / (n_samples - 1)))

    def x_to_sample (self, x):
        if not samples:
            return None

        width     = max (self.get_allocated_width (), 4)
        n_samples = len (samples)

        return round ((n_samples - 1) * (x - 1) / (width - 3))

    def update (self):
        if not samples or not self.model:
            return

        self.max_value = 1

        for row in self.model:
            var_name   = row[self.model.NAME]
            var_active = row[self.model.ACTIVE]

            if var_active:
914 915 916 917 918 919 920 921
                values = (sample.vars[var_name].value for sample in samples)
                values = filter (lambda x: x is not None, values)
                values = filter (math.isfinite,           values)

                try:
                    self.max_value = max (self.max_value, max (values))
                except:
                    pass
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

        self.queue_draw ()

    def selection_changed (self, selection):
        if selection.selection:
            self.sel = list (selection.selection)
            self.sel.sort ()
        else:
            self.sel = None

        self.queue_draw ()

    def do_get_preferred_width (self):
        return (300, 300)

    def do_get_preferred_height (self):
        if self.model:
            return (32, 256)
        else:
            return (16, 16)

    def update_selection (self):
        sel = self.selection.copy ()

        i0 = self.selection_i0
        i1 = self.selection_i1

        if self.selection_range:
            swap = i0 > i1

            if swap:
                temp = i0
                i0   = i1
                i1   = temp

            n_samples = len (samples)

            while i0 > 0             and not samples[i0 - 1].markers: i0 -= 1
            while i1 < n_samples - 1 and not samples[i1 + 1].markers: i1 += 1

            if swap:
                temp = i0
                i0   = i1
                i1   = temp

        sel.select_range (i0, i1, self.selection_op)

        selection.select (sel.selection)

        selection.cursor     = i1
        selection.cursor_dir = i1 - i0

    def do_button_press_event (self, event):
        self.grab_focus ()

977 978
        if event.button == 1:
            i = self.x_to_sample (event.x)
979

980 981
            if i is None:
                return False
982

983 984 985 986 987
            self.selection       = selection.copy ()
            self.selection_i0    = i
            self.selection_i1    = i
            self.selection_op    = SelectionOp.REPLACE
            self.selection_range = event.type != Gdk.EventType.BUTTON_PRESS
988

989
            state = event.state & Gdk.ModifierType.MODIFIER_MASK
990

991 992 993 994 995 996 997
            if state == Gdk.ModifierType.SHIFT_MASK:
                self.selection_op = SelectionOp.ADD
            elif state == Gdk.ModifierType.CONTROL_MASK:
                self.selection_op = SelectionOp.SUBTRACT
            elif state == (Gdk.ModifierType.SHIFT_MASK |
                           Gdk.ModifierType.CONTROL_MASK):
                self.selection_op = SelectionOp.INTERSECT
998

999
            self.update_selection ()
1000

1001 1002 1003
            self.grab_add ()
        elif event.button == 3:
            selection.select (set ())
1004

1005
            self.grab_add ()
1006 1007 1008 1009

        return True

    def do_button_release_event (self, event):
1010 1011
        if event.button == 1 or event.button == 3:
            self.selection = None
1012

1013
            selection.change_complete ()
1014

1015
            self.grab_remove ()
1016

1017
            return True
1018

1019
        return False
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

    def do_motion_notify_event (self, event):
        i = self.x_to_sample (event.x)

        selection.set_highlight (i)

        if self.selection and i is not None:
            self.selection_i1 = i

            self.update_selection ()

            return True

        return False

luz.paz's avatar
luz.paz committed
1035
    def do_leave_notify_event (self, event):
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
        selection.set_highlight (None)

        return False

    def do_key_press_event (self, event):
        if event.keyval == Gdk.KEY_Left    or \
           event.keyval == Gdk.KEY_Right   or \
           event.keyval == Gdk.KEY_Home    or \
           event.keyval == Gdk.KEY_KP_Home or \
           event.keyval == Gdk.KEY_End     or \
           event.keyval == Gdk.KEY_KP_End:
            n_samples = len (samples)

            state = event.state & Gdk.ModifierType.MODIFIER_MASK

            op = SelectionOp.REPLACE

            if state == Gdk.ModifierType.SHIFT_MASK:
                op = SelectionOp.XOR

            cursor     = selection.cursor
            cursor_dir = selection.cursor_dir

            if event.keyval == Gdk.KEY_Left or \
               event.keyval == Gdk.KEY_Home or \
               event.keyval == Gdk.KEY_KP_Home:
                if selection.cursor is not None:
                    if cursor_dir <= 0 or op == SelectionOp.REPLACE:
                        cursor -= 1
                else:
                    cursor = n_samples - 1

                cursor_dir = -1
            elif event.keyval == Gdk.KEY_Right or \
                 event.keyval == Gdk.KEY_End   or \
                 event.keyval == Gdk.KEY_KP_End:
                if cursor is not None:
                    if cursor_dir >= 0 or op == SelectionOp.REPLACE:
                        cursor += 1
                else:
                    cursor = 0

                cursor_dir = +1

            if cursor < 0 or cursor >= n_samples:
                cursor = min (max (cursor, 0), n_samples - 1)

                selection.cursor     = cursor
                selection.cursor_dir = cursor_dir

                if op != SelectionOp.REPLACE:
                    return True

            i0 = cursor

            if event.keyval == Gdk.KEY_Home or \
               event.keyval == Gdk.KEY_KP_Home:
                cursor = 0
            elif event.keyval == Gdk.KEY_End or \
                 event.keyval == Gdk.KEY_KP_End:
                cursor = n_samples - 1

            if op == SelectionOp.REPLACE:
                i0 = cursor

            selection.select_range (i0, cursor, op)

1103 1104 1105
            if len (selection.selection) > 1:
                selection.cursor     = cursor
                selection.cursor_dir = cursor_dir
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

            return True
        elif event.keyval == Gdk.KEY_Escape:
            selection.select (set ())

            return True

        return False

    def do_key_release_event (self, event):
        selection.change_complete ()

        return False

    def do_draw (self, cr):
        state           = self.get_state ()
        style           = (self.style_widget if self.model else
                           self).get_style_context ()
        (width, height) = (self.get_allocated_width  (),
                           self.get_allocated_height ())

        fg_color        = tuple (style.get_color (state))
        grid_color      = (*fg_color[:3], 0.25 * fg_color[3])
        highlight_color = grid_color
        selection_color = (*fg_color[:3], 0.15 * fg_color[3])

        Gtk.render_background (style, cr, 0, 0, width, height)

        if self.model:
1135 1136
            max_value = self.max_value
            vscale    = (height - 4) / max_value
1137 1138 1139 1140 1141 1142 1143

            cr.save ()

            cr.translate (0, height - 2)
            cr.scale (1, -1)

            first_sample = True
1144
            has_infinite = False
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

            for row in self.model:
                var_name   = row[self.model.NAME]
                var_active = row[self.model.ACTIVE]

                if var_active:
                    is_boolean    = var_defs[var_name].type == "boolean"
                    is_continuous = not is_boolean

                    for i in range (len (samples)):
                        value = samples[i].vars[var_name].value

                        if value is not None:
1158 1159 1160 1161 1162 1163 1164 1165 1166
                            first_sample = False

                            if math.isinf (value):
                                first_sample = True
                                has_infinite = True

                                value = max_value
                            elif is_boolean:
                                value *= max_value
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

                            y = value * vscale

                            if is_continuous:
                                x = self.sample_to_x (i)

                                if first_sample:
                                    cr.move_to (x, y)
                                else:
                                    cr.line_to (x, y)
                            else:
                                (x0, x1) = self.sample_to_range (i)

                                if first_sample:
                                    cr.move_to (x0, y)
                                else:
                                    cr.line_to (x0, y)

                                cr.line_to (x1, y)
                        else:
                            first_sample = True

                    (r, g, b) = var_defs[var_name].color

                    cr.set_source_rgb (r, g, b)
                    cr.set_line_width (2)
                    cr.stroke ()

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
                    if has_infinite:
                        cr.save ()

                        for i in range (len (samples)):
                            value = samples[i].vars[var_name].value

                            if value is not None and math.isinf (value):
                                first_sample = False

                                y = max_value * vscale

                                if is_continuous:
                                    x = self.sample_to_x (i)

                                    if first_sample:
                                        cr.move_to (x, y)
                                    else:
                                        cr.line_to (x, y)
                                else:
                                    (x0, x1) = self.sample_to_range (i)

                                    if first_sample:
                                        cr.move_to (x0, y)
                                    else:
                                        cr.line_to (x0, y)

                                    cr.line_to (x1, y)
                            else:
                                first_sample = True

                        cr.set_dash ([6, 6], 0)
                        cr.stroke ()

                        cr.restore ()

1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
            cr.restore ()

            cr.set_line_width (1)

            cr.set_source_rgba (*grid_color)

            n_hgrid_lines = 4
            n_vgrid_lines = 1

            for i in range (n_hgrid_lines + 1):
                cr.move_to (0, round (i * (height - 1) / n_hgrid_lines) + 0.5)
                cr.rel_line_to (width, 0)

                cr.stroke ()

            for i in range (n_vgrid_lines + 1):
                cr.move_to (round (i * (width - 1) / n_vgrid_lines) + 0.5, 0)
                cr.rel_line_to (0, height)

                cr.stroke ()
        else:
            for i in range (len (samples)):
                if samples[i].markers:
                    (x0, x1) = self.sample_to_range (i)

                    cr.rectangle (x0, 0, x1 - x0, height)

            cr.set_source_rgba (*fg_color)
            cr.fill ()

        if selection.highlight is not None:
            (x0, x1) = self.sample_to_range (selection.highlight)

            cr.rectangle (x0, 0, x1 - x0, height)

            (r, g, b, a) = style.get_color (state)

            cr.set_source_rgba (*highlight_color)
            cr.fill ()

        if self.sel:
            def draw_selection ():
                x0 = self.sample_to_range (i0)[0]
                x1 = self.sample_to_range (i1)[1]

                cr.rectangle (x0, 0, x1 - x0, height)

                (r, g, b, a) = style.get_color (state)

                cr.set_source_rgba (*selection_color)
                cr.fill ()

            i0 = None

            for i in self.sel:
                if i0 is None:
                    i0 = i
                    i1 = i
                elif i == i1 + 1:
                    i1 = i
                else:
                    draw_selection ()

                    i0 = i
                    i1 = i

            if i0 is not None:
                draw_selection ()

class SampleGraphList (Gtk.Box):
    Item = namedtuple (
        "SampleGraphListGraph", ("widget",
                                 "model",
                                 "remove_button",
                                 "move_up_button",
                                 "move_down_button")
    )

    def __init__ (self, *args, **kwargs):
        Gtk.Box.__init__ (self,
                          *args,
                          orientation = Gtk.Orientation.VERTICAL,
                          **kwargs)

        self.items = []

        self.vset_size_group = Gtk.SizeGroup (
            mode = Gtk.SizeGroupMode.HORIZONTAL
        )

        hbox = Gtk.Box (orientation = Gtk.Orientation.HORIZONTAL)
        self.pack_start (hbox, False, False, 0)
        hbox.show ()

        empty = Gtk.DrawingArea ()
        hbox.pack_start (empty, False, True, 0)
        self.vset_size_group.add_widget (empty)
        empty.show ()

        graph = SampleGraph (has_tooltip = True)
        hbox.pack_start (graph, True, True, 0)
        graph.show ()

        graph.connect ("query-tooltip", self.graph_query_tooltip)

        separator = Gtk.Separator (orientation = Gtk.Orientation.HORIZONTAL)
        self.pack_start (separator, False, False, 0)
        separator.show ()

        vbox = Gtk.Box (orientation = Gtk.Orientation.VERTICAL)
        self.items_vbox = vbox
        self.pack_start (vbox, False, False, 0)
        vbox.show ()

        self.add_item (0)

    def update_items (self):
        for widget in self.items_vbox.get_children ():
            self.items_vbox.remove (widget)

        i = 0

        for item in self.items:
            if i > 0:
                separator = Gtk.Separator (
                    orientation = Gtk.Orientation.HORIZONTAL
                )
                self.items_vbox.pack_start (separator, False, False, 0)
                separator.show ()

            self.items_vbox.pack_start (item.widget, False, False, 0)

            item.remove_button.set_sensitive    (len (self.items) > 1)
            item.move_up_button.set_sensitive   (i > 0)
            item.move_down_button.set_sensitive (i < len (self.items) - 1)

            i += 1

    def add_item (self, i):
        hbox = Gtk.Box (orientation = Gtk.Orientation.HORIZONTAL)
        hbox.show ()

        vbox = Gtk.Box (orientation = Gtk.Orientation.VERTICAL)
        hbox.pack_start (vbox, False, True, 0)
        self.vset_size_group.add_widget (vbox)
        vbox.show ()

        scroll = Gtk.ScrolledWindow (
            hscrollbar_policy = Gtk.PolicyType.NEVER,
            vscrollbar_policy = Gtk.PolicyType.AUTOMATIC
        )
        vbox.pack_start (scroll, True, True, 0)
        scroll.show ()

        vset = VariableSet ()
        scroll.add (vset)
        vset.show ()

        buttons = Gtk.ButtonBox (orientation = Gtk.Orientation.HORIZONTAL)
        vbox.pack_start (buttons, False, False, 0)
        buttons.set_layout (Gtk.ButtonBoxStyle.EXPAND)
        buttons.show ()

        button = Gtk.Button.new_from_icon_name ("list-add-symbolic",
                                                Gtk.IconSize.BUTTON)
        add_button = button
        buttons.add (button)
        button.show ()

        button = Gtk.Button.new_from_icon_name ("list-remove-symbolic",
                                                Gtk.IconSize.BUTTON)
        remove_button = button
        buttons.add (button)
        button.show ()

        button = Gtk.Button.new_from_icon_name ("go-up-symbolic",
                                                Gtk.IconSize.BUTTON)
        move_up_button = button
        buttons.add (button)
        button.show ()

        button = Gtk.Button.new_from_icon_name ("go-down-symbolic",
                                                Gtk.IconSize.BUTTON)
        move_down_button = button
        buttons.add (button)
        button.show ()

        graph = SampleGraph (vset.get_model (), has_tooltip = True)
        hbox.pack_start (graph, True, True, 0)
        graph.show ()

        graph.connect ("query-tooltip", self.graph_query_tooltip)

        item = self.Item (
            widget           = hbox,
            model            = vset.get_model (),
            remove_button    = remove_button,
            move_up_button   = move_up_button,
            move_down_button = move_down_button
        )
        self.items.insert (i, item)

        add_button.connect       ("clicked",
                                  lambda *args: self.add_item (
                                                    self.items.index (item) + 1
                                                ))
        remove_button.connect    ("clicked",
                                  lambda *args: self.remove_item (
                                                    self.items.index (item)
                                                ))
        move_up_button.connect   ("clicked",
                                  lambda *args: self.move_item (
                                                    self.items.index (item),
                                                    -1
                                                ))
        move_down_button.connect ("clicked",
                                  lambda *args: self.move_item (
                                                    self.items.index (item),
                                                    +1
                                                ))

        self.update_items ()

    def remove_item (self, i):
        del self.items[i]

        self.update_items ()

    def move_item (self, i, offset):
        item = self.items[i]
        del self.items[i]
        self.items.insert (i + offset, item)

        self.update_items ()

    def graph_query_tooltip (self, graph, x, y, keyboard_mode, tooltip):
        if keyboard_mode:
            return False

        i = graph.x_to_sample (x)

        if i is None or i < 0 or i >= len (samples):
            return False

        grid = Gtk.Grid (column_spacing = 4)
        tooltip.set_custom (grid)
        grid.show ()

        row = 0

        label = Gtk.Label ()
        grid.attach (label, 0, row, 2, 1)
        label.set_markup ("<b>Sample %d</b>" % i)
        label.show ()

        row += 1

        label = Gtk.Label ()
        grid.attach (label, 0, row, 2, 1)
        label.set_markup ("<sub>%s</sub>" %
                          format_duration (samples[i].t / 1000000))
        label.get_style_context ().add_class ("dim-label")
        label.show ()

        row += 1

        for item in self.items:
            model = item.model

            vars = tuple (var[model.NAME] for var in model if var[model.ACTIVE])

            if not vars:
                continue

            separator = Gtk.Separator (orientation = Gtk.Orientation.HORIZONTAL)
            grid.attach (separator, 0, row, 2, 1)
            separator.show ()

            row += 1

            for var in vars:
                color = format_color (var_defs[var].color)

                label = Gtk.Label (halign = Gtk.Align.START)
                grid.attach (label, 0, row, 1, 1)
                label.set_markup (
                    "<span color=\"%s\"><b>%s</b></span>" % (color, var)
                )
                label.show ()

                value = samples[i].vars[var].value
                text  = var_types[var_defs[var].type].format (value) \
                        if value is not None else "N/A"

                label = Gtk.Label (text, halign = Gtk.Align.END)
                grid.attach (label, 1, row, 1, 1)
                label.show ()

                row += 1

        markers = samples[i].markers

        if markers:
            separator = Gtk.Separator (orientation = Gtk.Orientation.HORIZONTAL)
            grid.attach (separator, 0, row, 2, 1)
            separator.show ()

            row += 1

            for marker in markers:
                label = Gtk.Label (halign = Gtk.Align.START)
                grid.attach (label, 0, row, 1, 1)
                label.set_markup ("<b>Marker %d</b>" % (marker.id))
                label.show ()

                if marker.description:
                    label = Gtk.Label (marker.description,
                                       halign = Gtk.Align.END)
                    grid.attach (label, 1, row, 1, 1)
                    label.show ()

                row += 1

        return True

class InformationViewer (Gtk.ScrolledWindow):
    class Store (Gtk.ListStore):
        NAME  = 0
        VALUE = 1

        def __init__ (self):
            Gtk.ListStore.__init__ (self, str, str)

    def __init__ (self, *args, **kwargs):
        Gtk.ScrolledWindow.__init__ (
            self,
            *args,
            hscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
            vscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
            **kwargs
        )

        vbox = Gtk.Box (orientation  = Gtk.Orientation.VERTICAL,
                        border_width = 32,
                        margin_left  = 64,
                        margin_right = 64,
                        spacing      = 32)
        self.add (vbox)
        vbox.show ()

        def add_element (element):
            name    = {
                "params":       "Log Parameters",
                "gimp-version": "GIMP Version",
                "env":          "Environment",
                "gegl-config":  "GEGL Config"
            }.get (element.tag, element.tag)
            text    = element.text.strip ()
            n_items = len (element)

            if not text and n_items == 0:
                return

            vbox2 = Gtk.Box (orientation = Gtk.Orientation.VERTICAL,
                             spacing     = 16)
            vbox.pack_start (vbox2, False, False, 0)
            vbox2.show ()

            label = Gtk.Label (xalign = 0)
            vbox2.pack_start (label, False, False, 0)
            label.set_markup ("<b>%s</b>" % name)
            label.show ()

            frame = Gtk.Frame (shadow_type = Gtk.ShadowType.IN)
            vbox2.pack_start (frame, False, False, 0)
            frame.show ()

            if text:
                scrolled = Gtk.ScrolledWindow (
                    hscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
                    vscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
                    height_request    = 400
                )
                frame.add (scrolled)
                scrolled.show ()

                text = Gtk.TextView (editable      = False,
                                     monospace     = True,
                                     wrap_mode     = Gtk.WrapMode.WORD,
                                     left_margin   = 16,
                                     right_margin  = 16,
                                     top_margin    = 16,
                                     bottom_margin = 16)
                scrolled.add (text)
                text.get_buffer ().set_text (element.text.strip (), -1)
                text.show ()
            else:
                scrolled = Gtk.ScrolledWindow (
                    hscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
                    vscrollbar_policy = Gtk.PolicyType.NEVER
                )
                frame.add (scrolled)
                scrolled.show ()

                store = self.Store ()

                for item in element:
                    store.append ((item.tag, item.text.strip ()))

                tree = Gtk.TreeView (model = store)
                scrolled.add (tree)
                tree.show ()

                col = Gtk.TreeViewColumn (title = "Name")
                tree.append_column (col)

                cell = Gtk.CellRendererText ()
                col.pack_start (cell, False)
                col.add_attribute (cell, "text", store.NAME)

                col = Gtk.TreeViewColumn (title = "Value")
                tree.append_column (col)
                col.set_alignment (0.5)

                cell = Gtk.CellRendererText (xalign = 1)
                col.pack_start (cell, False)
                col.add_attribute (cell, "text", store.VALUE)

        params = log.find ("params")

        if params:
            add_element (params)

        info = log.find ("info")

        if info:
            for element in info:
                add_element (element)

1669
class VariablesViewer (Gtk.ScrolledWindow):
1670
    class Store (Gtk.ListStore):
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
        NAME        =  0
        DESC        =  1
        COLOR       =  2
        VALUE       =  3
        RAW         =  4
        MIN         =  5
        MAX         =  6
        MEDIAN      =  7
        MEAN        =  8
        STDEV       =  9
        LAST_COLUMN = 10
1682 1683 1684 1685 1686

        def __init__ (self):
            n_stats = self.LAST_COLUMN - self.COLOR

            Gtk.ListStore.__init__ (self,
1687
                                    *((str, str, Gdk.RGBA) + n_stats * (str,)))
1688 1689
            enum.Enum.__init__ (self)

1690
            for var, var_def in var_defs.items ():
1691
                i = self.append (((var,
1692 1693
                                   var_def.desc,
                                   Gdk.RGBA (*var_def.color)) +
1694 1695 1696 1697 1698
                                  n_stats * ("",)))

    def __init__ (self, *args, **kwargs):
        Gtk.Box.__init__ (self,
                          *args,
1699 1700
                          hscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
                          vscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
1701 1702
                          **kwargs)

1703
        self.needs_update = True
1704 1705 1706 1707 1708

        store = self.Store ()
        self.store = store

        tree = Gtk.TreeView (model = store)
1709
        self.add (tree)
1710
        tree.set_tooltip_column (store.DESC)
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
        tree.show ()

        self.single_sample_cols = []
        self.multi_sample_cols  = []

        col = Gtk.TreeViewColumn (title = "Variable")
        tree.append_column (col)
        col.set_resizable (True)

        cell = CellRendererColorToggle (active = True)
        col.pack_start (cell, False)
        col.add_attribute (cell, "color", store.COLOR)

        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", store.NAME)

        def add_value_column (title, column, single_sample):
            col = Gtk.TreeViewColumn (title = title)
            tree.append_column (col)
            col.set_resizable (True)
            col.set_alignment (0.5)

            cell = Gtk.CellRendererText (xalign = 1)
            col.pack_start (cell, False)
            col.add_attribute (cell, "text", column)

            if single_sample:
                self.single_sample_cols.append (col)
            else:
                self.multi_sample_cols.append (col)

        add_value_column ("Value",     store.VALUE,  True)
        add_value_column ("Raw",       store.RAW,    True)
        add_value_column ("Min",       store.MIN,    False)
        add_value_column ("Max",       store.MAX,    False)
        add_value_column ("Median",    store.MEDIAN, False)
        add_value_column ("Mean",      store.MEAN,   False)
        add_value_column ("Std. Dev.", store.STDEV,  False)

        col = Gtk.TreeViewColumn ()
        tree.append_column (col)

        selection.connect ("change-complete", self.selection_change_complete)

1756 1757 1758 1759 1760
    def update (self):
        if not self.needs_update:
            return

        self.needs_update = False
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

        sel   = selection.get_effective_selection ()
        n_sel = len (sel)

        if n_sel == 1:
            i, = sel

            for row in self.store:
                var_name = row[self.store.NAME]

                var      = samples[i].vars[var_name]
                var_type = var_types[var_defs[var_name].type]

                row[self.store.VALUE] = var_type.format (var.value)
                row[self.store.RAW]   = var.raw if var.raw is not None \
                                        else "N/A"
        else:
            for row in self.store:
                var_name = row[self.store.NAME]

                var_type = var_types[var_defs[var_name].type]

                vals = (samples[i].vars[var_name].value for i in sel)
                vals = tuple (val for val in vals if val is not None)

                if vals:
                    min_val = min               (vals)
                    max_val = max               (vals)
                    median  = statistics.median (vals)
                    mean    = statistics.mean   (vals)
                    stdev   = statistics.pstdev (vals, mean)

                    row[self.store.MIN]    = var_type.format         (min_val)
                    row[self.store.MAX]    = var_type.format         (max_val)
                    row[self.store.MEDIAN] = var_type.format         (median)
                    row[self.store.MEAN]   = var_type.format_numeric (mean)
                    row[self.store.STDEV]  = var_type.format_numeric (stdev)
                else:
                    row[self.store.MIN]    = \
                    row[self.store.MAX]    = \
                    row[self.store.MEDIAN] = \
                    row[self.store.MEAN]   = \
                    row[self.store.STDEV]  = var_type.format (None)

        for col in self.single_sample_cols: col.set_visible (n_sel == 1)
        for col in self.multi_sample_cols:  col.set_visible (n_sel > 1)

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
    def do_map (self):
        self.update ()

        Gtk.ScrolledWindow.do_map (self)

    def selection_change_complete (self, selection):
        self.needs_update = True

        if self.get_mapped ():
            self.update ()

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
class BacktraceViewer (Gtk.Box):
    class ThreadStore (Gtk.ListStore):
        INDEX = 0
        ID    = 1
        NAME  = 2
        STATE = 3

        def __init__ (self):
            Gtk.ListStore.__init__ (self, int, int, str, str)

    class FrameStore (Gtk.ListStore):
        ID       = 0
        ADDRESS  = 1
        OBJECT   = 2
        FUNCTION = 3
        OFFSET   = 4
        SOURCE   = 5
        LINE     = 6

        def __init__ (self):
            Gtk.ListStore.__init__ (self, int, str, str, str, str, str, str)

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
    class CellRendererViewSource (Gtk.CellRendererPixbuf):
        file = GObject.Property (type = Gio.File, default = None)
        line = GObject.Property (type = int,      default = 0)

        def __init__ (self, *args, **kwargs):
            Gtk.CellRendererPixbuf.__init__ (
                self,
                *args,
                icon_name = "text-x-generic-symbolic",
                mode      = Gtk.CellRendererMode.ACTIVATABLE,
                **kwargs)

            self.connect ("notify::file",
                          lambda *args:
                              self.set_property ("visible", bool (self.file)))

        def do_activate (self, event, widget, path, *args):
            if self.file:
1859
                run_editor (self.file, self.line)
1860 1861 1862 1863 1864

                return True

            return False

1865 1866 1867 1868 1869 1870
    def __init__ (self, *args, **kwargs):
        Gtk.Box.__init__ (self,
                          *args,
                          orientation = Gtk.Orientation.HORIZONTAL,
                          **kwargs)

1871 1872
        self.needs_update = True

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
        vbox = Gtk.Box (orientation = Gtk.Orientation.VERTICAL)
        self.pack_start (vbox, False, False, 0)
        vbox.show ()

        header = Gtk.HeaderBar (title = "Threads", has_subtitle = False)
        vbox.pack_start (header, False, False, 0)
        header.show ()

        scrolled = Gtk.ScrolledWindow (
            hscrollbar_policy = Gtk.PolicyType.NEVER,
            vscrollbar_policy = Gtk.PolicyType.AUTOMATIC
        )
        vbox.pack_start (scrolled, True, True, 0)
        scrolled.show ()

        store = self.ThreadStore ()
        self.thread_store = store
1890
        store.set_sort_column_id (store.ID, Gtk.SortType.ASCENDING)
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948

        tree = Gtk.TreeView (model = store)
        self.thread_tree = tree
        scrolled.add (tree)
        tree.set_search_column (store.NAME)
        tree.show ()

        tree.connect ("row-activated", self.threads_row_activated)

        tree.get_selection ().connect ("changed",
                                       self.threads_selection_changed)

        col = Gtk.TreeViewColumn (title = "ID")
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText (xalign = 1)
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.ThreadStore.ID)

        col = Gtk.TreeViewColumn (title = "Name")
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.ThreadStore.NAME)

        col = Gtk.TreeViewColumn (title = "State")
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.ThreadStore.STATE)

        separator = Gtk.Separator (orientation = Gtk.Orientation.VERTICAL)
        self.pack_start (separator, False, False, 0)
        separator.show ()

        vbox = Gtk.Box (orientation = Gtk.Orientation.VERTICAL)
        self.pack_start (vbox, True, True, 0)
        vbox.show ()

        header = Gtk.HeaderBar (title = "Stack", has_subtitle = False)
        vbox.pack_start (header, False, False, 0)
        header.show ()

        scrolled = Gtk.ScrolledWindow (
            hscrollbar_policy = Gtk.PolicyType.AUTOMATIC,
            vscrollbar_policy = Gtk.PolicyType.AUTOMATIC
        )
        vbox.pack_start (scrolled, True, True, 0)
        scrolled.show ()

        store = self.FrameStore ()
        self.frame_store = store

1949
        tree = Gtk.TreeView (model = store, has_tooltip = True)
1950 1951 1952 1953 1954
        scrolled.add (tree)
        tree.set_search_column (store.FUNCTION)
        tree.show ()

        tree.connect ("row-activated", self.frames_row_activated)
1955 1956 1957 1958 1959 1960 1961 1962
        tree.connect ("query-tooltip", self.frames_query_tooltip)

        def format_filename_col (tree_col, cell, model, iter, col):
            object = model[iter][col]

            cell.set_property ("text", get_basename (object) if object else "")

        self.tooltip_columns = {}
1963 1964 1965 1966 1967

        col = Gtk.TreeViewColumn (title = "#")
        tree.append_column (col)
        col.set_resizable (True)

1968
        cell = Gtk.CellRendererText (xalign = 1)
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.FrameStore.ID)

        col = Gtk.TreeViewColumn (title = "Address")
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText (xalign = 1)
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.FrameStore.ADDRESS)

        col = Gtk.TreeViewColumn (title = "Object")
1981
        self.tooltip_columns[col] = store.OBJECT
1982 1983 1984 1985 1986
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
1987
        col.set_cell_data_func (cell, format_filename_col, store.OBJECT)
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005

        col = Gtk.TreeViewColumn (title = "Function")
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.FrameStore.FUNCTION)

        col = Gtk.TreeViewColumn (title = "Offset")
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText (xalign = 1)
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.FrameStore.OFFSET)

        col = Gtk.TreeViewColumn (title = "Source")
2006
        self.tooltip_columns[col] = store.SOURCE
2007 2008 2009 2010 2011
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
2012
        col.set_cell_data_func (cell, format_filename_col, store.SOURCE)
2013 2014 2015 2016 2017 2018 2019 2020 2021

        col = Gtk.TreeViewColumn (title = "Line")
        tree.append_column (col)
        col.set_resizable (True)

        cell = Gtk.CellRendererText (xalign = 1)
        col.pack_start (cell, False)
        col.add_attribute (cell, "text", self.FrameStore.LINE)

2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
        def format_view_source_col (tree_col, cell, model, iter, cols):
            filename = model[iter][cols[0]] or None
            line     = model[iter][cols[1]] or "0"

            cell.set_property ("file", filename and find_file (filename))
            cell.set_property ("line", int (line))

        def format_view_source_tooltip (row):
            filename = row[store.SOURCE]

            if filename:
                file = find_file (filename)

                if file:
                    return file.get_path ()

            return None

2040
        col = Gtk.TreeViewColumn ()
2041
        self.tooltip_columns[col] = format_view_source_tooltip
2042 2043
        tree.append_column (col)

2044 2045 2046 2047 2048
        cell = self.CellRendererViewSource (xalign = 0)
        col.pack_start (cell, False)
        col.set_cell_data_func (cell, format_view_source_col, (store.SOURCE,
                                                               store.LINE))

2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
        selection.connect ("change-complete", self.selection_change_complete)

    @GObject.Property (type = bool, default = False)
    def available (self):
        sel = selection.get_effective_selection ()

        if len (sel) == 1:
            i, = sel

            return bool (samples[i].backtrace)

        return False

2062 2063 2064 2065 2066 2067
    def update (self):
        if not self.needs_update or not self.available:
            return

        self.needs_update = False

2068 2069 2070 2071 2072 2073 2074
        tid = None

        sel_rows = self.thread_tree.get_selection ().get_selected_rows ()[1]

        if sel_rows:
            tid = self.thread_store[sel_rows[0]][self.ThreadStore.ID]

2075
        i, = selection.get_effective_selection ()
2076

2077
        self.thread_store.clear ()
2078

2079 2080
        for t in range (len (samples[i].backtrace)):
            thread = samples[i].backtrace[t]
2081

2082 2083 2084 2085 2086 2087 2088 2089 2090
            iter = self.thread_store.append (
                (t, thread.id, thread.name, str (thread.state))
            )

            if thread.id == tid:
                self.thread_tree.get_selection ().select_iter (iter)

    def do_map (self):
        self.update ()
2091

2092 2093 2094 2095 2096 2097 2098
        Gtk.Box.do_map (self)

    def selection_change_complete (self, selection):
        self.needs_update = True

        if self.get_mapped ():
            self.update ()
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177

        self.notify ("available")

    def threads_row_activated (self, tree, path, col):
        iter = self.thread_store.get_iter (path)

        tid = self.thread_store[iter][self.ThreadStore.ID]

        sel = set ()

        for i in range (len (samples)):
            threads = filter (lambda thread:
                                thread.id    == tid and
                                thread.state == ThreadState.RUNNING,
                              samples[i].backtrace or [])

            if list (threads):
                sel.add (i)

        selection.select (sel)

        selection.change_complete ()

    def threads_selection_changed (self, tree_sel):
        self.frame_store.clear ()

        (store, rows) = tree_sel.get_selected_rows ()

        if not rows:
            return

        i, = selection.get_effective_selection ()

        try:
            frames = samples[i].backtrace[store[rows[0]][store.INDEX]].frames

            for frame in frames:
                info = frame.info

                self.frame_store.append ((
                    frame.id, hex (frame.address), info.object, info.symbol,
                    hex (info.offset) if info.offset is not None else None,
                    info.source, str (info.line) if info.line else None
                ))
        except:
            pass

    def frames_row_activated (self, tree, path, col):
        iter = self.frame_store.get_iter (path)

        address = int (self.frame_store[iter][self.FrameStore.ADDRESS], 0)
        info    = address_map.get (address, None)

        if not info:
            return

        id = info.id

        if not id:
            return

        sel = set ()

        def has_frame (sample, id):
            for thread in sample.backtrace or []:
                for frame in thread.frames:
                    if frame.info.id == id:
                        return True

            return False

        for i in range (len (samples)):
            if has_frame (samples[i], id):
                sel.add (i)

        selection.select (sel)

        selection.change_complete ()

2178 2179 2180 2181 2182
    def frames_query_tooltip (self, tree, x, y, keyboard_mode, tooltip):
        hit, x, y, model, path, iter =  tree.get_tooltip_context (x, y,
                                                                  keyboard_mode)

        if hit:
2183
            column = None
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199

            if keyboard_mode:
                cursor_path, cursor_col = tree.get_cursor ()

                if path.compare (cursor_path) == 0:
                    column = self.tooltip_columns[cursor_col]
            else:
                for col in self.tooltip_columns:
                    area = tree.get_cell_area (path, col)

                    if x >= area.x and x < area.x + area.width and \
                       y >= area.y and y < area.y + area.height:
                        column = self.tooltip_columns[col]

                        break

2200 2201 2202 2203 2204 2205 2206
            if column is not None:
                value = None

                if type (column) == int:
                    value = model[iter][column]
                else:
                    value = column (model[iter])
2207 2208 2209 2210 2211 2212 2213 2214

                if value:
                    tooltip.set_text (str (value))

                    return True

        return False

2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
class CellRendererPercentage (Gtk.CellRendererText):
    padding = 0

    def __init__ (self, *args, **kwargs):
        Gtk.CellRendererText.__init__ (self, *args, xalign = 1, **kwargs)

        self.value = 0

    @GObject.property (type = float)
    def value (self):
        return self.value_property

    @value.setter
    def value (self, value):
        self.value_property = value

        self.set_property ("text", format_percentage (value, 2))

    def do_render (self, cr, widget, background_area, cell_area, flags):
        full_width  = cell_area.width  - 2 * self.padding
        full_height = cell_area.height - 2 * self.padding

        if full_width <= 0 or full_height <= 0:
            return

        state    = widget.get_state ()
        style    = widget.get_style_context ()
        fg_color = style.get_color (state)

        rounded_rectangle (cr,
                           cell_area.x + self.padding,
                           cell_area.y + self.padding,