If you want to fork this repository to propose merge requests, please send an email to tiago@skewed.de, and your project limit will be raised.

gtk_draw.py 51.7 KB
Newer Older
1 2 3 4 5
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2020 Tiago de Paula Peixoto <tiago@skewed.de>
7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# 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/>.

21 22
import numpy

Alex Henrie's avatar
Alex Henrie committed
23 24
from .. import GraphView, PropertyMap, ungroup_vector_property, \
    group_vector_property, infect_vertex_property, edge_endpoint_property, _prop
25
from .cairo_draw import *
Alex Henrie's avatar
Alex Henrie committed
26
from .cairo_draw import _edefaults
27 28
from .. draw import sfdp_layout, random_layout, _avg_edge_distance, \
    coarse_graphs
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


def point_in_poly(p, poly):
    i, c = 0, False
    j = len(poly) - 1
    while i < len(poly):
        if (((poly[i][1] > p[1]) != (poly[j][1] > p[1])) and
            (p[0] < (poly[j][0] - poly[i][0]) * (p[1] - poly[i][1]) /
             (poly[j][1] - poly[i][1]) + poly[i][0])):
            c = not c
        j = i
        i += 1
    return c


class VertexMatrix(object):
    def __init__(self, g, pos):
        self.g = g
        self.pos = pos
        self.m = None
        self.m_res = None
        self.update()

    def get_box(self, p, size=None):
        if size is None:
54 55
            return (int(round(float(p[0] / self.m_res))),
                    int(round(float(p[1] / self.m_res))))
56 57 58 59
        else:
            n = int(np.ceil(size / self.m_res))
            b = self.get_box(p)
            boxes = []
60 61
            for i in range(-n, n):
                for j in range(-n, n):
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
                    boxes.append((b[0] + i, b[1] + j))
            return boxes

    def update(self):
        pos_x, pos_y = ungroup_vector_property(self.pos, [0, 1])
        x_range = [pos_x.fa.min(), pos_x.fa.max()]
        y_range = [pos_y.fa.min(), pos_y.fa.max()]
        self.m_res = min(x_range[1] - x_range[0],
                         y_range[1] - y_range[0]) / np.sqrt(self.g.num_vertices())
        self.m_res *= np.sqrt(10)

        self.m = defaultdict(set)
        for v in self.g.vertices():
            i, j = self.get_box(self.pos[v])
            self.m[(i, j)].add(v)

    def update_vertex(self, v, new_pos):
        b = self.get_box(self.pos[v])
        self.m[b].remove(v)
        self.pos[v] = new_pos
        b = self.get_box(self.pos[v])
        self.m[b].add(v)

    def remove_vertex(self, v):
        b = self.get_box(self.pos[v])
        self.m[b].remove(v)

    def add_vertex(self, v):
        b = self.get_box(self.pos[v])
        self.m[b].add(v)

    def get_closest(self, pos):
        pos = np.array(pos)
        box = self.get_box(pos)
96
        dist = numpy.inf
97
        clst = None
98 99
        for i in range(-1, 2):
            for j in range(-1, 2):
100 101 102 103 104 105 106 107 108 109 110 111 112
                b = (box[0] + i, box[1] + j)
                for v in self.m[b]:
                    ndist = ((pos - self.pos[v].a[:2]) ** 2).sum()
                    if ndist < dist:
                        dist = ndist
                        clst = v
        return clst

    def mark_polygon(self, points, selected):
        rect = [min([x[0] for x in points]), min([x[1] for x in points]),
                max([x[0] for x in points]), max([x[1] for x in points])]
        p1 = self.get_box(rect[:2])
        p2 = self.get_box(rect[2:])
113 114
        for i in range(p1[0], p2[0] + 1):
            for j in range(p1[1], p2[1] + 1):
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
                for v in self.m[(i, j)]:
                    p = self.pos[v]
                    if not point_in_poly(p, points):
                        continue
                    selected[v] = True


def apply_transforms(g, pos, m):
    m = tuple(m)
    g = GraphView(g, directed=True)
    libgraph_tool_draw.apply_transforms(g._Graph__graph, _prop("v", g, pos),
                                        m[0], m[1], m[2], m[3], m[4], m[5])


class GraphWidget(Gtk.DrawingArea):
    def __init__(self, g, pos, vprops=None, eprops=None, vorder=None,
                 eorder=None, nodesfirst=False, update_layout=False,
                 layout_K=1., multilevel=False, display_props=None,
133
                 display_props_size=11, fit_view=True, bg_color=None,
134
                 max_render_time=300, layout_callback=None,
135
                 key_press_callback=None, highlight_color=None, **kwargs):
136 137 138 139 140 141
        r"""Interactive GTK+ widget displaying a given graph.

        Parameters
        ----------
        g : :class:`~graph_tool.Graph`
            Graph to be drawn.
142
        pos : :class:`~graph_tool.VertexPropertyMap`
143 144 145 146 147 148 149
            Vector-valued vertex property map containing the x and y coordinates of
            the vertices.
        vprops : dict (optional, default: ``None``)
            Dictionary with the vertex properties. Individual properties may also be
            given via the ``vertex_<prop-name>`` parameters, where ``<prop-name>`` is
            the name of the property.
        eprops : dict (optional, default: ``None``)
150
            Dictionary with the edge properties. Individual properties may also be
151 152
            given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
            the name of the property.
153
        vorder : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
154
            If provided, defines the relative order in which the vertices are drawn.
155
        eorder : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
156 157 158
            If provided, defines the relative order in which the edges are drawn.
        nodesfirst : bool (optional, default: ``False``)
            If ``True``, the vertices are drawn first, otherwise the edges are.
Aleksandar Trifunovic's avatar
Aleksandar Trifunovic committed
159
        update_layout : bool (optional, default: ``False``)
160 161 162 163 164
            If ``True``, the layout will be updated dynamically.
        layout_K : float (optional, default: ``1.0``)
            Parameter ``K`` passed to :func:`~graph_tool.draw.sfdp_layout`.
        multilevel : bool (optional, default: ``False``)
            Parameter ``multilevel`` passed to :func:`~graph_tool.draw.sfdp_layout`.
165
        display_props : list of :class:`~graph_tool.VertexPropertyMap` instances (optional, default: ``None``)
166
            List of properties to be displayed when the mouse passes over a vertex.
167
        display_props_size : float (optional, default: ``11.``)
168
            Font size used to display the vertex properties.
169 170 171 172 173 174
        fit_view : bool, float or tuple (optional, default: ``True``)
            If ``True``, the layout will be scaled to fit the entire clip region.
            If a float value is given, it will be interpreted as ``True``, and in
            addition the viewport will be scaled out by that factor. If a tuple
            value is given, it should have four values ``(x, y, w, h)`` that
            specify the view in user coordinates.
175 176
        bg_color : str or sequence (optional, default: ``None``)
            Background color. The default is white.
177 178 179
        max_render_time : int (optional, default: ``300``)
            Maximum amount of time (in milliseconds) spent rendering portions of
            the graph.
180 181 182 183
        layout_callback : function (optional, default: ``Node``)
            User-supplied callback to be called whenever the positions of the layout
            have changed. It needs to have the following signature:

Tiago Peixoto's avatar
Tiago Peixoto committed
184
            .. code-block:: python
185 186 187 188 189 190 191 192 193 194 195 196 197

               def callback(g, picked, pos, vprops, eprops):
                   ...

            where ``g`` is the graph being drawn, ``picked`` is either a single
            vertex or a boolean vertex property map representing the vertices
            currently selected, and ``vprops`` and ``eprops`` are dictionaries with
            the vertex and edge properties currently being used by the layout.
        key_press_callback : function (optional, default: ``Node``)

            User-supplied callback to be called whenever a key-press event has
            happened. It needs to have the following signature:

Tiago Peixoto's avatar
Tiago Peixoto committed
198
            .. code-block:: python
199 200 201 202 203 204 205 206 207

               def callback(g, keyval, picked, pos, vprops, eprops):
                   ...

            where ``g`` is the graph being drawn, ``keyval`` is the key id,
            ``picked`` is either a single vertex or a boolean vertex property map
            representing the vertices currently selected, and ``vprops`` and
            ``eprops`` are dictionaries with the vertex and edge properties
            currently being used by the layout.
208
        vertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``)
209 210 211
            Parameters following the pattern ``vertex_<prop-name>`` specify the
            vertex property with name ``<prop-name>``, as an alternative to the
            ``vprops`` parameter.
212
        edge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``)
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
            Parameters following the pattern ``edge_<prop-name>`` specify the edge
            property with name ``<prop-name>``, as an alternative to the ``eprops``
            parameter.
        **kwargs
            Any extra parameters are passed to :func:`~graph_tool.draw.cairo_draw`.

        Notes
        -----

        The graph drawing can be panned by dragging with the middle mouse button
        pressed. The graph may be zoomed by scrolling with the mouse wheel, or
        equivalent (if the "shift" key is held, the vertex/edge sizes are scaled
        accordingly). The layout may be rotated by dragging while holding the
        "control" key. Pressing the "r" key centers and zooms the layout around the
        graph.  By pressing the "a" key, the current translation, scaling and
        rotation transformations are applied to the vertex positions themselves, and
        the transformation matrix is reset (if this is never done, the given
        position properties are never modified).

        Individual vertices may be selected by pressing the left mouse button. The
        currently selected vertex follows the mouse pointer. To stop the selection,
        the right mouse button must be pressed. Alternatively, a group of vertices
        may be selected by holding the "shift" button while the pointer is dragged
        while pressing the left button. The selected vertices may be moved by
        dragging the pointer with the left button pressed. They may be rotated by
        holding the "control" key and scrolling with the mouse. If the key "z" is
        pressed, the layout is zoomed to fit the selected vertices only.

        If the key "s" is pressed, the dynamic spring-block layout is
        activated. Vertices which are currently selected are not updated.

        """

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        Gtk.DrawingArea.__init__(self)

        vprops = {} if vprops is None else vprops
        eprops = {} if eprops is None else eprops

        props, kwargs = parse_props("vertex", kwargs)
        vprops.update(props)
        props, kwargs = parse_props("edge", kwargs)
        eprops.update(props)
        self.kwargs = kwargs

        self.g = g
        self.pos = pos
        self.vprops = vprops
        self.eprops = eprops
        self.vorder = vorder
        self.eorder = eorder
        self.nodesfirst = nodesfirst

        self.panning = None
        self.tmatrix = cairo.Matrix()  # position to surface
        self.smatrix = cairo.Matrix()  # surface to screen
        self.pointer = [0, 0]
        self.picked = False
270
        self.selected = g.new_vertex_property("bool", False)
271
        self.highlight = g.new_vertex_property("bool", False)
272
        self.sel_edge_filt = g.new_edge_property("bool", False)
273
        self.highlight_color = highlight_color
274 275 276 277
        self.srect = None
        self.drag_begin = None
        self.moved_picked = False
        self.vertex_matrix = None
278
        self.fit_view = fit_view
279 280 281 282 283 284 285

        self.display_prop = g.vertex_index if display_props is None \
                            else display_props
        self.display_prop_size = display_props_size

        self.geometry = None
        self.base = None
286
        self.base_geometry = None
287 288
        self.background = None
        self.bg_color = bg_color if bg_color is not None else [1, 1, 1, 1]
289
        self.regenerate_generator = None
290 291
        self.regenerate_max_time = max_render_time
        self.max_render_time = max_render_time
292
        self.lazy_regenerate = False
293 294 295 296 297 298 299

        self.layout_callback_id = None
        self.layout_K = layout_K
        self.layout_init_step = self.layout_K
        self.epsilon = 0.01 * self.layout_K
        self.multilevel_layout = multilevel

300 301 302
        self.layout_user_callback = layout_callback
        self.key_press_user_callback = key_press_callback

303 304
        if multilevel:
            self.cgs = coarse_graphs(g)
305
            u = next(self.cgs)
306 307 308 309 310 311
            self.cg, self.cpos, self.layout_K, self.cvcount, self.cecount = u
            self.ag = self.g
            self.apos = self.pos
            self.g = self.cg
            self.pos = self.cpos
            self.layout_step = self.layout_K
312
            self._own_props()
313 314
        else:
            self.cg = None
315

316 317 318 319
        if update_layout:
            self.reset_layout()

        # Event signals
320 321 322 323 324 325 326
        self.connect("motion-notify-event", self.motion_notify_event)
        self.connect("button-press-event", self.button_press_event)
        self.connect("button-release-event", self.button_release_event)
        self.connect("scroll-event", self.scroll_event)
        self.connect("key-press-event", self.key_press_event)
        self.connect("key-release-event", self.key_release_event)
        self.connect("destroy-event", self.cleanup)
327 328 329 330 331 332 333 334 335

        self.set_events(Gdk.EventMask.EXPOSURE_MASK
                        | Gdk.EventMask.LEAVE_NOTIFY_MASK
                        | Gdk.EventMask.BUTTON_PRESS_MASK
                        | Gdk.EventMask.BUTTON_RELEASE_MASK
                        | Gdk.EventMask.BUTTON_MOTION_MASK
                        | Gdk.EventMask.POINTER_MOTION_MASK
                        | Gdk.EventMask.POINTER_MOTION_HINT_MASK
                        | Gdk.EventMask.SCROLL_MASK
336
                        | Gdk.EventMask.SMOOTH_SCROLL_MASK
337 338 339 340 341 342
                        | Gdk.EventMask.KEY_PRESS_MASK
                        | Gdk.EventMask.KEY_RELEASE_MASK)

        self.set_property("can-focus", True)
        self.connect("draw", self.draw)

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        try:
            self.zoom_gesture = Gtk.GestureZoom.new(self)
            self.zoom_gesture.connect("begin", self.zoom_begin)
            self.zoom_gesture.connect("end", self.zoom_end)
            self.zoom_gesture.connect("scale_changed", self.scale_changed)

            self.rotate_gesture = Gtk.GestureRotate.new(self)
            self.rotate_gesture.connect("begin", self.rotate_begin)
            self.rotate_gesture.connect("end", self.rotate_end)
            self.rotate_gesture.connect("angle_changed", self.angle_changed)

            self.zoom_gesture.group(self.rotate_gesture)

            self.drag_gesture = Gtk.GestureDrag.new(self)
            self.drag_gesture.set_touch_only(True)
            self.drag_gesture.connect("begin", self.drag_gesture_begin)
            self.drag_gesture.connect("end", self.drag_gesture_end)
            self.drag_gesture.connect("drag_update", self.drag_gesture_update)
        except AttributeError:
            pass
        self.is_zooming = False
        self.is_rotating = False
        self.is_drag_gesture = False

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
    def update(self, pos=None, vprops=None, eprops=None, vorder=None, eorder=None,
               nodesfirst=None, display_props=None,
               fit_view=True, bg_color=None, **kwargs):

        props, kwargs = parse_props("vertex", kwargs)
        vprops.update(props)
        props, kwargs = parse_props("edge", kwargs)
        eprops.update(props)

        if pos is not None:
            self.pos = pos
        self.vprops.update(vprops)
        self.eprops.update(eprops)
        if vorder is not None:
            self.vorder = vorder
        if eorder is not None:
            self.eorder = eorder
        if nodesfirst is not None:
            self.nodesfirst = nodesfirst

        self.fit_view = fit_view

        self.display_prop = self.g.vertex_index if display_props is None \
                            else display_props
        self.bg_color = bg_color if bg_color is not None else [1, 1, 1, 1]


394 395
    def cleanup(self):
        """Cleanup callbacks."""
396 397
        if gobject is None:
            return
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
        if self.layout_callback_id is not None:
            ret = gobject.source_remove(self.layout_callback_id)
            if not ret:
                warnings.warn("error removing idle callback...")
            self.layout_callback_id = None

    def __del__(self):
        self.cleanup()

    # Layout update

    def reset_layout(self):
        """Reset the layout algorithm."""
        if self.layout_callback_id is not None:
            gobject.source_remove(self.layout_callback_id)
            self.layout_callback_id = None
        self.layout_step = self.layout_init_step
        self.layout_callback_id = gobject.idle_add(self.layout_callback)

417 418 419 420 421 422 423 424 425 426 427
    def _own_props(self):
        self.selected = self.g.own_property(self.selected)
        self.highlight = self.g.own_property(self.highlight)
        self.sel_edge_filt = self.g.own_property(self.sel_edge_filt)
        for k, vp in self.vprops.items():
            if isinstance(vp, PropertyMap):
                self.vprops[k] = self.g.own_property(vp)
        for k, ep in self.eprops.items():
            if isinstance(ep, PropertyMap):
                self.eprops[k] = self.g.own_property(ep)

428 429
    def layout_callback(self):
        """Perform one step of the layout algorithm."""
430
        if self.layout_callback_id is None or self.g.num_vertices() == 0:
431 432 433 434 435 436 437 438 439 440
            return False
        pos_temp = ungroup_vector_property(self.pos, [0, 1])
        sfdp_layout(self.g, K=self.layout_K,
                    max_iter=5, pos=self.pos,
                    pin=self.selected,
                    init_step=self.layout_step,
                    multilevel=False)
        self.layout_step *= 0.9
        if self.vertex_matrix is not None:
            self.vertex_matrix.update()
441
        self.regenerate_surface(reset=True, complete=True)
442 443 444 445
        self.queue_draw()
        ps = ungroup_vector_property(self.pos, [0, 1])
        delta = np.sqrt((pos_temp[0].fa - ps[0].fa) ** 2 +
                        (pos_temp[1].fa - ps[1].fa) ** 2).mean()
446 447

        if self.layout_user_callback is not None:
448 449
            self.layout_user_callback(self, self.g, self.picked, self.pos,
                                      self.vprops, self.eprops)
450

451 452 453 454 455
        if delta > self.epsilon:
            return True
        else:
            if self.multilevel_layout:
                try:
456
                    u = next(self.cgs)
457 458 459 460
                    self.cg, self.cpos, K, self.cvcount, self.cecount = u
                    self.layout_K *= 0.75
                    self.g = self.cg
                    self.pos = self.cpos
461
                    self._own_props()
462 463 464 465 466 467 468 469 470 471 472
                    self.layout_step = max(self.layout_K,
                                           _avg_edge_distance(self.g,
                                                              self.pos) / 10)
                    if self.vertex_matrix is not None:
                        self.vertex_matrix = VertexMatrix(self.g, self.pos)
                    self.epsilon = 0.05 * self.layout_K * self.g.num_edges()
                    geometry = [self.get_allocated_width(),
                                self.get_allocated_height()]
                    adjust_default_sizes(self.g, geometry, self.vprops,
                                         self.eprops, force=True)
                    self.fit_to_window(ink=False)
473
                    self.regenerate_surface(reset=True, complete=True)
474 475 476
                except StopIteration:
                    self.g = self.ag
                    self.pos = self.apos
477
                    self._own_props()
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
                    self.g.copy_property(self.cpos, self.pos)
                    if self.vertex_matrix is not None:
                        self.vertex_matrix = VertexMatrix(self.g, self.pos)
                    self.multilevel_layout = False
                    self.layout_init_step = max(self.layout_K,
                                                _avg_edge_distance(self.g,
                                                                   self.pos) /
                                                                   10)
                    self.epsilon = 0.01 * self.layout_K

                return True
            self.layout_callback_id = None
            return False

    # Actual drawing

494 495 496 497
    def regenerate_surface(self, reset=False, complete=False):
        r"""Redraw the graph surface."""

        if reset:
498 499
            self.regenerate_generator = None
            self.regen_context = None
500 501 502 503 504 505

        geometry = [self.get_allocated_width() * 3,
                    self.get_allocated_height() * 3]

        if (self.base is None or self.base_geometry[0] != geometry[0] or
            self.base_geometry[1] != geometry[1] or reset):
506

507 508 509
            w = self.get_window()
            if w is None:
                return False
Tiago Peixoto's avatar
Tiago Peixoto committed
510 511 512 513

            self.regenerate_generator = None
            self.regen_context = None

514 515 516
            self.base = w.create_similar_surface(cairo.CONTENT_COLOR_ALPHA,
                                                 *geometry)
            self.base_geometry = geometry
517 518 519 520

            m = cairo.Matrix()
            m.translate(self.get_allocated_width(),
                        self.get_allocated_height())
521 522
            self.smatrix = self.smatrix.multiply(m)
            self.tmatrix = self.tmatrix.multiply(self.smatrix)
523 524 525
            self.smatrix = cairo.Matrix()
            self.smatrix.translate(-self.get_allocated_width(),
                                   -self.get_allocated_height())
526

527 528
        if self.regenerate_generator is None:
            cr = cairo.Context(self.base)
529 530
            cr.set_source_rgba(*self.bg_color)
            cr.paint()
531 532 533 534 535 536 537 538
            cr.set_matrix(self.tmatrix)
            mtime = -1 if complete else self.regenerate_max_time
            res = 5 * self.get_scale_factor()
            gen = cairo_draw(self.g, self.pos, cr, self.vprops, self.eprops,
                             self.vorder, self.eorder, self.nodesfirst, res=res,
                             max_render_time=mtime, **self.kwargs)
            self.regenerate_generator = gen
            self.regen_context = cr
539 540 541 542 543 544 545

        if self.regenerate_generator is not None:
            try:
                next(self.regenerate_generator)
            except StopIteration:
                self.regenerate_generator = None
                self.regen_context = None
546
        self.lazy_regenerate = False
547 548 549 550 551 552 553 554 555 556

    def draw(self, da, cr):
        r"""Redraw the widget."""

        geometry = [self.get_allocated_width(),
                    self.get_allocated_height()]

        if self.geometry is None:
            adjust_default_sizes(self.g, geometry, self.vprops, self.eprops)
            self.fit_to_window(ink=False)
557
            self.regenerate_surface()
558 559
            self.geometry = geometry

560 561
        cr.save()
        cr.set_matrix(self.smatrix)
562 563 564 565 566 567 568
        c1 = self.pos_to_device((0, 0), surface=True, cr=cr)
        c2 = self.pos_to_device((0, self.base_geometry[1]), surface=True, cr=cr)
        c3 = self.pos_to_device((self.base_geometry[0], 0), surface=True, cr=cr)
        c4 = self.pos_to_device(self.base_geometry, surface=True, cr=cr)
        c = [c1, c2, c3, c4]
        ul = [min([x[0] for x in c]), min([x[1] for x in c])]
        lr = [max([x[0] for x in c]), max([x[1] for x in c])]
569
        cr.restore()
570

571 572 573
        if ((ul[0] > 0 or lr[0] < geometry[0] or
             ul[1] > 0 or lr[1] < geometry[1]) or
            self.lazy_regenerate):
574
            self.regenerate_surface(reset=True)
575
        elif self.regenerate_generator is not None:
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
            self.regenerate_surface()

        if self.background is None:
            # draw checkerboard
            self.background = cairo.ImageSurface(cairo.FORMAT_ARGB32, 14, 14)
            bcr = cairo.Context(self.background)
            bcr.rectangle(0, 0, 7, 7)
            bcr.set_source_rgb(102. / 256, 102. / 256, 102. / 256)
            bcr.fill()
            bcr.rectangle(7, 0, 7, 7)
            bcr.set_source_rgb(153. / 256, 153. / 256, 153. / 256)
            bcr.fill()
            bcr.rectangle(0, 7, 7, 7)
            bcr.set_source_rgb(153. / 256, 153. / 256, 153. / 256)
            bcr.fill()
            bcr.rectangle(7, 7, 7, 7)
            bcr.set_source_rgb(102. / 256, 102. / 256, 102. / 256)
            bcr.fill()
            del bcr
            self.background = cairo.SurfacePattern(self.background)
            self.background.set_extend(cairo.EXTEND_REPEAT)

        cr.set_source(self.background)
        cr.paint()

        cr.save()
        cr.set_matrix(self.smatrix)
        cr.set_source_surface(self.base)
        cr.paint()
        cr.restore()

607
        if self.selected.fa.sum() > 0:
608
            # draw immediate neighborhood
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
            if self.selected.fa.sum() == 1:
                vprops = dict(**self.vprops)
                vprops["halo"] = self.highlight
                vprops["halo_color"] = (0.9372549019607843, 0.1607843137254902, 0.1607843137254902, .9)
                vprops["halo_size"] = 1.3

                if self.highlight_color is not None:
                    vprops["halo_color"] = self.highlight_color

                eprops = {}
                eprops["color"] = (0.9372549019607843, 0.1607843137254902, 0.1607843137254902, .9)
                if "control_points" in self.eprops:
                   eprops["control_points"] = self.eprops["control_points"]

                if self.highlight_color is not None:
                    eprops["color"] = self.highlight_color

                self.highlight.fa = self.selected.fa
                infect_vertex_property(GraphView(self.g, directed=False),
                                       self.highlight, [True])
                self.highlight.fa = numpy.logical_xor(self.selected.fa,
                                                      self.highlight.fa)

                hsrc = edge_endpoint_property(self.g, self.selected, "source")
                htgt = edge_endpoint_property(self.g, self.selected, "target")
                self.sel_edge_filt.fa = numpy.logical_or(hsrc.fa, htgt.fa)

                u = GraphView(self.g,
                              vfilt=numpy.logical_or(self.highlight.fa,
                                                     self.selected.fa),
                              efilt=self.sel_edge_filt)

                eprops["pen_width"] = self.eprops.get("pen_width",
                                                      _edefaults["pen_width"])

                if isinstance(eprops["pen_width"], PropertyMap):
                    pw = eprops["pen_width"]
                    pw = u.own_property(pw.copy())
                    pw.fa *= 1.1
                else:
                    eprops["pen_width"] *= 1.1

                cr.save()
652
                cr.set_matrix(self.tmatrix.multiply(self.smatrix))
653 654 655 656 657 658
                cairo_draw(u, self.pos, cr, vprops, eprops, self.vorder,
                           self.eorder, self.nodesfirst)
                cr.restore()

            # draw selected edges
            vprops = dict(**self.vprops)
659 660 661 662
            vprops["halo"] = True

            eprops = {}

663 664
            u = GraphView(self.g, vfilt=self.selected,
                          efilt=self.sel_edge_filt)
665 666

            cr.save()
667
            cr.set_matrix(self.tmatrix.multiply(self.smatrix))
668 669 670 671 672 673 674 675 676 677 678 679 680 681
            cairo_draw(u, self.pos, cr, vprops, eprops, self.vorder,
                       self.eorder, self.nodesfirst)
            cr.restore()

        if self.srect is not None:
            cr.move_to(self.srect[0], self.srect[1])
            cr.line_to(self.srect[0], self.srect[3])
            cr.line_to(self.srect[2], self.srect[3])
            cr.line_to(self.srect[2], self.srect[1])
            cr.line_to(self.srect[0], self.srect[1])
            cr.close_path()
            cr.set_source_rgba(0, 0, 1, 0.3)
            cr.fill()

682
        if self.regenerate_generator is not None:
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
            icon = self.render_icon(Gtk.STOCK_EXECUTE, Gtk.IconSize.BUTTON)
            Gdk.cairo_set_source_pixbuf(cr, icon, 10, 10)
            cr.paint()

        if (self.picked is not None and self.picked is not False and
            not isinstance(self.picked, PropertyMap)):
            if isinstance(self.display_prop, PropertyMap):
                txt = str(self.display_prop[self.picked])
            else:
                txt = ", ".join([str(x[self.picked])
                                 for x in self.display_prop])
            geometry = [self.get_allocated_width(),
                        self.get_allocated_height()]
            pos = [10, geometry[1] - 10]
            cr.set_font_size(self.display_prop_size)
            ext = cr.text_extents(txt)
            pad = 8
            cr.rectangle(pos[0] - pad / 2, pos[1] - ext[3] - pad / 2,
                         ext[2] + pad, ext[3] + pad)
            cr.set_source_rgba(1, 1, 1, 1.0)
            cr.fill()
            cr.move_to(pos[0], pos[1])
            cr.set_source_rgba(0, 0, 0, 1.0)
            cr.show_text(txt)

708
        if self.regenerate_generator is not None:
709
            self.queue_draw()
710 711 712 713 714 715
        return False

    # Position and transforms

    def pos_to_device(self, pos, dist=False, surface=False, cr=None):
        """Convert a position from the graph space to the widget space."""
716
        ox, oy = self.get_window().get_position()
717
        if cr is None:
718
            cr = self.get_window().cairo_create()
719 720 721
            if surface:
                cr.set_matrix(self.smatrix)
            else:
722
                cr.set_matrix(self.tmatrix.multiply(self.smatrix))
723 724 725
        if dist:
            return cr.user_to_device_distance(pos[0], pos[1])
        else:
726 727
            x, y = cr.user_to_device(pos[0], pos[1])
            return (x - ox, y - oy)
728 729 730

    def pos_from_device(self, pos, dist=False, surface=False, cr=None):
        """Convert a position from the widget space to the device space."""
731
        ox, oy = self.get_window().get_position()
732
        if cr is None:
733
            cr = self.get_window().cairo_create()
734 735 736
            if surface:
                cr.set_matrix(self.smatrix)
            else:
737
                cr.set_matrix(self.tmatrix.multiply(self.smatrix))
738 739 740
        if dist:
            return cr.device_to_user_distance(pos[0], pos[1])
        else:
741
            return cr.device_to_user(pos[0] + ox, pos[1] + oy)
742 743 744 745

    def apply_transform(self):
        r"""Apply current transform matrix to vertex coordinates."""
        zoom = self.pos_from_device((1, 0), dist=True)[0]
746
        apply_transforms(self.g, self.pos, self.smatrix.multiply(self.tmatrix))
747 748 749
        self.tmatrix = cairo.Matrix()
        self.tmatrix.scale(zoom, zoom)
        self.smatrix = cairo.Matrix()
750
        apply_transforms(self.g, self.pos, self.smatrix.multiply(self.tmatrix))
751 752 753 754 755 756 757 758 759 760 761
        self.tmatrix = cairo.Matrix()
        self.tmatrix.scale(1. / zoom, 1. / zoom)
        if self.vertex_matrix is not None:
            self.vertex_matrix.update()
        self.fit_to_window()
        self.regenerate_surface()
        self.queue_draw()

    def fit_to_window(self, ink=False, g=None):
        r"""Fit graph to window."""
        geometry = [self.get_allocated_width(), self.get_allocated_height()]
762
        ox, oy = self.get_window().get_position()
763 764 765
        if g is None:
            g = self.g
        pos = g.own_property(self.pos)
766 767 768 769 770
        if self.fit_view != False:
            try:
                x, y, w, h = self.fit_view
                zoom = min(geometry[0] / w, geometry[1] / h)
            except TypeError:
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
                pad = self.fit_view if self.fit_view is not True else 0.9

                M = self.tmatrix.multiply(self.smatrix)
                pos_x, pos_y = ungroup_vector_property(pos, [0, 1])
                P = np.zeros((2, len(pos_x.fa)))
                P[0, :] = pos_x.fa
                P[1, :] = pos_y.fa
                T = np.zeros((2, 2))
                O = np.zeros(2)
                T[0, 0], T[1, 0], T[0, 1], T[1, 1], O[0], O[1] = M
                P = np.dot(T, P)
                P[0] += O[0]
                P[1] += O[1]
                pos_x.fa = P[0, :]
                pos_y.fa = P[1, :]
                pos = group_vector_property([pos_x, pos_y])

                x, y, zoom = fit_to_view_ink(g, pos, geometry, self.vprops,
                                             self.eprops, pad=pad)
790
        else:
791 792
            x, y, zoom = 0, 0, 1

793
        m = cairo.Matrix()
794
        m.translate(ox, oy)
795
        m.scale(zoom, zoom)
796
        m.translate(-x, -y)
797
        self.tmatrix = self.tmatrix.multiply(self.smatrix.multiply(m))
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
        self.smatrix = cairo.Matrix()
        if ink:
            scale_ink(zoom, self.vprops, self.eprops)

    # Picking vertices

    def init_picked(self):
        r"""Init picked vertices."""
        self.selected.fa = False
        p = self.pos_from_device(self.pointer)
        if self.vertex_matrix is None:
            self.vertex_matrix = VertexMatrix(self.g, self.pos)
        self.picked = self.vertex_matrix.get_closest(p)
        if self.picked is not None:
            self.selected.a[int(self.picked)] = True

    # Key and pointer bindings

    def button_press_event(self, widget, event):
        r"""Handle button press."""
818 819 820 821

        if self.g.num_vertices() == 0:
            return

822 823 824
        if self.is_zooming or self.is_rotating or self.is_drag_gesture:
            return

825 826 827 828 829 830 831 832 833 834 835 836 837
        x = event.x
        y = event.y
        state = event.state
        self.pointer = [x, y]

        if event.button == 1 and not state & Gdk.ModifierType.CONTROL_MASK:
            if state & Gdk.ModifierType.SHIFT_MASK:
                self.srect = [x, y, x, y]
            elif self.picked == False:
                self.init_picked()
                self.queue_draw()
            if self.drag_begin is None:
                self.drag_begin = [x, y]
838
        elif (event.button == 2 or
839 840
            (event.button == 1 and state & Gdk.ModifierType.CONTROL_MASK)):
            self.panning = (event.x, event.y)
841
        elif event.button == 3:
842 843 844 845 846 847 848 849 850 851 852
            if isinstance(self.picked, PropertyMap):
                self.picked = None
                self.selected.fa = False
                self.queue_draw()
            elif self.picked is not False:
                self.picked = False
                self.selected.fa = False
                self.queue_draw()

    def button_release_event(self, widget, event):
        r"""Handle button release."""
853 854 855 856

        if self.g.num_vertices() == 0:
            return

857 858 859
        if self.is_zooming or self.is_rotating or self.is_drag_gesture:
            return

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
        state = event.state
        if event.button == 1:
            if self.srect is not None:
                if self.picked == False:
                    self.init_picked()
                if not isinstance(self.picked, PropertyMap):
                    self.picked = self.selected

                if state & Gdk.ModifierType.CONTROL_MASK:
                    old_picked = self.picked.fa.copy()
                    self.picked.fa = False

                p1 = [self.srect[0], self.srect[1]]
                p2 = [self.srect[2], self.srect[3]]
                poly = [p1, [p1[0], p2[1]], p2, [p2[0], p1[1]]]
                poly = [self.pos_from_device(x) for x in poly]

                self.vertex_matrix.mark_polygon(poly, self.picked)

                if state & Gdk.ModifierType.CONTROL_MASK:
                    self.picked.fa = old_picked - self.picked.fa & old_picked

                self.srect = None

                self.queue_draw()
            self.drag_begin = None

            if self.moved_picked:
888
                if self.layout_user_callback is not None:
889 890 891
                    self.layout_user_callback(self, self.g, self.picked,
                                              self.pos, self.vprops,
                                              self.eprops)
892
                self.moved_picked = False
893
                self.regenerate_surface(complete=True)
894
                self.queue_draw()
895
        elif event.button == 2:
896 897 898 899 900
            self.panning = None
            self.queue_draw()

    def motion_notify_event(self, widget, event):
        r"""Handle pointer motion."""
901 902 903 904

        if self.is_zooming or self.is_rotating:
            return

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
        if event.is_hint:
            x, y, state = event.window.get_pointer()[1:]
        else:
            x = event.x
            y = event.y
            state = event.state
        self.pointer = [x, y]

        if (state & Gdk.ModifierType.BUTTON1_MASK and
            not state & Gdk.ModifierType.CONTROL_MASK):
            if state & Gdk.ModifierType.SHIFT_MASK:
                if self.srect is not None:
                    self.srect[2:] = self.pointer
                    self.queue_draw()
            elif (self.picked is not None and self.picked is not False
                  and self.srect is None):
                p = self.pos_from_device(self.pointer)
                if isinstance(self.picked, PropertyMap):
                    if self.drag_begin is not None:
                        c = self.pos_from_device(self.drag_begin)
                        u = GraphView(self.g, vfilt=self.picked)
                        delta = np.asarray(p) - np.asarray(c)
                        for v in u.vertices():
                            new_pos = self.pos[v].a + delta
                            self.vertex_matrix.update_vertex(self.g.vertex(int(v)),
                                                             new_pos)
                        self.drag_begin = self.pointer
                elif self.vertex_matrix is not None:
                    self.vertex_matrix.update_vertex(self.picked, p)
                self.moved_picked = True
                self.queue_draw()
        elif (state & Gdk.ModifierType.BUTTON2_MASK or
              (state & Gdk.ModifierType.BUTTON1_MASK and
               state & Gdk.ModifierType.CONTROL_MASK)):
            if self.panning is not None:
                offset = [x - self.panning[0],
                          y - self.panning[1]]
                m = cairo.Matrix()
                m.translate(offset[0], offset[1])
                self.smatrix = self.smatrix * m
            self.panning = (x, y)
            self.queue_draw()
        else:
            self.panning = None

            if self.picked is not False:
                p = self.pos_from_device(self.pointer)
952 953
                if self.vertex_matrix is None:
                    self.vertex_matrix = VertexMatrix(self.g, self.pos)
954 955 956 957 958 959 960 961 962 963 964
                v = self.vertex_matrix.get_closest(p)
                if v is not None and not isinstance(self.picked, PropertyMap):
                    if self.picked is not None:
                        self.selected[self.picked] = False
                        if self.picked != v:
                            self.queue_draw()
                    self.picked = v
                    self.selected[v] = True

    def scroll_event(self, widget, event):
        r"""Handle scrolling."""
965

966 967 968
        if self.is_zooming or self.is_rotating:
            return

969 970 971 972 973 974 975
        self.regenerate_max_time = 50

        def restore_render_time():
            self.regenerate_max_time = self.max_render_time
            return False
        self.surface_callback = gobject.timeout_add(2000, restore_render_time)

976 977 978 979 980
        state = event.state

        angle = 0
        zoom = 1.

981 982 983 984 985 986 987 988 989
        if event.direction == Gdk.ScrollDirection.SMOOTH:
            is_smooth, dx, dy = event.get_scroll_deltas()
            if dy == 0:
                return
        else:
            dy = 1

        if (event.direction == Gdk.ScrollDirection.UP or
            event.direction == Gdk.ScrollDirection.SMOOTH):
990
            if state & Gdk.ModifierType.CONTROL_MASK:
991
                if state & Gdk.ModifierType.SHIFT_MASK:
992
                    angle = .01 * dy
993
                else:
994
                    angle = .1 * dy
995
            else:
996 997 998 999
                if dy > 0:
                    zoom = 1. + (1. / .9 - 1) * abs(dy)
                else:
                    zoom = 1. / (1. + abs(dy) / 9)
1000
                if state & Gdk.ModifierType.SHIFT_MASK:
1001
                    scale_ink(zoom, self.vprops, self.eprops)
1002 1003
        elif event.direction == Gdk.ScrollDirection.DOWN:
            if state & Gdk.ModifierType.CONTROL_MASK:
1004
                if state & Gdk.ModifierType.SHIFT_MASK:
1005
                    angle = -.01
1006
                else:
1007
                    angle = -.1
1008
            else:
1009
                zoom = .9
1010
                if state & Gdk.ModifierType.SHIFT_MASK:
1011
                    scale_ink(zoom, self.vprops, self.eprops)
1012 1013 1014 1015

        # keep centered
        if zoom != 1:
            center = self.pointer
1016
            cpos = self.pos_from_device(center)
1017 1018 1019

            m = cairo.Matrix()
            m.scale(zoom, zoom)
1020
            self.tmatrix = self.tmatrix.multiply(m)
1021

1022 1023
            ncpos = self.pos_from_device(center)
            self.tmatrix.translate(ncpos[0] - cpos[0],
1024
                                   ncpos[1] - cpos[1])
1025
            self.lazy_regenerate = True
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
        if angle != 0:
            if not isinstance(self.picked, PropertyMap):
                center = (self.pointer[0], self.pointer[1])
                m = cairo.Matrix()
                m.translate(center[0], center[1])
                m.rotate(angle)
                m.translate(-center[0], -center[1])
                self.smatrix = self.smatrix.multiply(m)
            else:
                center = self.pos_from_device(self.pointer)
                u = GraphView(self.g, vfilt=self.picked)

                if self.vertex_matrix is not None:
                    for v in u.vertices():
                        self.vertex_matrix.remove_vertex(self.g.vertex(int(v)))

                m = cairo.Matrix()
                m.rotate(angle)
                m.translate(-center[0], -center[1])

                apply_transforms(u, self.pos, m)

                m = cairo.Matrix()
                m.translate(center[0], center[1])
                apply_transforms(u, self.pos, m)

                if self.vertex_matrix is not None:
                    for v in u.vertices():
                        self.vertex_matrix.add_vertex(self.g.vertex(int(v)))
                self.moved_picked = True

        self.queue_draw()

    def key_press_event(self, widget, event):
        r"""Handle key press."""

1063 1064 1065
        if self.is_zooming or self.is_rotating:
            return

1066
        #print event.keyval
1067
        if event.keyval == ord('r'):
1068
            self.fit_to_window()
1069
            self.regenerate_surface(reset=True)
1070
            self.queue_draw()
1071
        elif event.keyval == ord('s'):
1072
            self.reset_layout()
1073
        elif event.keyval == ord('a'):
1074
            self.apply_transform()
1075
        elif event.keyval == ord('p'):
1076 1077 1078 1079 1080 1081 1082
            if self.picked == False:
                self.init_picked()
            else:
                self.picked = False
                self.selected.fa = False
                self.vertex_matrix = None
                self.queue_draw()
1083
        elif event.keyval == ord('z'):
1084 1085 1086
            if isinstance(self.picked, PropertyMap):
                u = GraphView(self.g, vfilt=self.picked)
                self.fit_to_window(g=u)
1087
                self.regenerate_surface(reset=True)
1088 1089 1090 1091
                self.queue_draw()

    def key_release_event(self, widget, event):
        r"""Handle release event."""
1092 1093 1094

        if self.is_zooming or self.is_rotating:
            return
1095 1096

        if self.key_press_user_callback is not None:
1097 1098 1099
            self.key_press_user_callback(self, self.g, event.keyval,
                                         self.picked, self.pos, self.vprops,
                                         self.eprops)
1100

1101
        if event.keyval == 65507: # Control_L
1102 1103
            if self.moved_picked:
                self.moved_picked = False
1104
                self.regenerate_surface(reset=True, complete=True)
1105 1106
                self.queue_draw()

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
    # Touch gestures

    def zoom_begin(self, gesture, seq):
        self.is_zooming = True
        self.zoom_scale = 1.

    def zoom_end(self, gesture, seq):
        self.is_zooming = False
        self.regenerate_surface(reset=True)
        self.queue_draw()

    def scale_changed(self, gesture, scale):
        zoom = scale / self.zoom_scale
        self.zoom_scale = scale
        center = gesture.get_bounding_box_center()[1:]
        cpos = self.pos_from_device(center, surface=True)
        self.smatrix.scale(zoom, zoom)
        ncpos = self.pos_from_device(center, surface=True)
        self.smatrix.translate(ncpos[0] - cpos[0],
                               ncpos[1] - cpos[1])
        scale_ink(zoom, self.vprops, self.eprops)
        self.queue_draw()

    def rotate_begin(self, gesture, seq):
        self.is_rotating = True
        self.angle = None

    def rotate_end(self, gesture, seq):
        self.is_rotating = False

    def angle_changed(self, gesture, angle, angle_delta):
        if self.angle is None:
            self.angle = angle
        delta = angle - self.angle
        self.angle = angle
        center = gesture.get_bounding_box_center()[1:]
        m = cairo.Matrix()
        m.translate(center[0], center[1])
        m.rotate(delta)
        m.translate(-center[0], -center[1])
        self.smatrix = self.smatrix.multiply(m)
        self.queue_draw()

    def drag_gesture_begin(self, gesture, seq):
        self.drag_last = (0, 0)
        self.is_drag_gesture = True
        self.picked = False
        self.selected.fa = False

    def drag_gesture_end(self, gesture, seq):
        self.is_drag_gesture = False

    def drag_gesture_update(self, gesture, dx, dy):
        delta = (dx - self.drag_last[0], dy - self.drag_last[1])
        self.drag_last = (dx, dy)
        m = cairo.Matrix()
        m.translate(delta[0], delta[1])
        self.smatrix = self.smatrix.multiply(m)
        self.queue_draw()
1166 1167 1168 1169

class GraphWindow(Gtk.Window):
    def __init__(self, g, pos, geometry, vprops=None, eprops=None, vorder=None,
                 eorder=None, nodesfirst=False, update_layout=False, **kwargs):
1170 1171 1172 1173 1174 1175
        r"""Interactive GTK+ window containing a :class:`~graph_tool.draw.GraphWidget`.

        Parameters
        ----------
        g : :class:`~graph_tool.Graph`
            Graph to be drawn.
1176
        pos : :class:`~graph_tool.VertexPropertyMap`
1177 1178 1179 1180 1181 1182 1183 1184 1185
            Vector-valued vertex property map containing the x and y coordinates of
            the vertices.
        geometry : tuple
            Widget geometry.
        vprops : dict (optional, default: ``None``)
            Dictionary with the vertex properties. Individual properties may also be
            given via the ``vertex_<prop-name>`` parameters, where ``<prop-name>`` is
            the name of the property.
        eprops : dict (optional, default: ``None``)
1186
            Dictionary with the edge properties. Individual properties may also be
1187 1188
            given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
            the name of the property.
1189
        vorder : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
1190
            If provided, defines the relative order in which the vertices are drawn.
1191
        eorder : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
            If provided, defines the relative order in which the edges are drawn.
        nodesfirst : bool (optional, default: ``False``)
            If ``True``, the vertices are drawn first, otherwise the edges are.
        update_layout : bool (optional, default: ``True``)
            If ``True``, the layout will be updated dynamically.
        **kwargs
            Any extra parameters are passed to :class:`~graph_tool.draw.GraphWidget` and
            :func:`~graph_tool.draw.cairo_draw`.
        """

1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
        Gtk.Window.__init__(self, title="graph-tool's interactive window™")
        icon = GdkPixbuf.Pixbuf.new_from_file('%s/graph-tool-logo.svg' %
                                              os.path.dirname(__file__))
        self.set_icon(icon)
        self.set_default_size(geometry[0], geometry[1])

        self.graph = GraphWidget(g, pos, vprops, eprops, vorder, eorder,
                                 nodesfirst, update_layout, **kwargs)
        self.add(self.graph)

    def __del__(self):
        self.graph.cleanup()


1216 1217
_window_list = []

1218 1219
def interactive_window(g, pos=None, vprops=None, eprops=None, vorder=None,
                       eorder=None, nodesfirst=False, geometry=(500, 400),
1220 1221 1222
                       update_layout=True, sync=True, main=True,
                       window=None, return_window=False, **kwargs):
    r"""Display an interactive GTK+ window containing the given graph.
1223 1224 1225 1226 1227

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
1228
    pos : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
        Vector-valued vertex property map containing the x and y coordinates of
        the vertices. If not given, it will be computed using :func:`sfdp_layout`.
    vprops : dict (optional, default: ``None``)
        Dictionary with the vertex properties. Individual properties may also be
        given via the ``vertex_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
    eprops : dict (optional, default: ``None``)
        Dictionary with the vertex properties. Individual properties may also be
        given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
1239
    vorder : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
1240
        If provided, defines the relative order in which the vertices are drawn.
1241
    eorder : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
1242 1243 1244 1245 1246 1247 1248
        If provided, defines the relative order in which the edges are drawn.
    nodesfirst : bool (optional, default: ``False``)
        If ``True``, the vertices are drawn first, otherwise the edges are.
    geometry : tuple (optional, default: ``(500, 400)``)
        Window geometry.
    update_layout : bool (optional, default: ``True``)
        If ``True``, the layout will be updated dynamically.
1249 1250
    main : bool (optional, default: ``True``)
        If ``False``, the GTK+ main loop will not be called.
1251 1252 1253 1254 1255
    window : :class:`~graph_tool.draw.GraphWindow` (optional, default: ``None``)
        If provided, specifies the window where the drawing will
        occur. Otherwise a new one will be created.
    return_window : bool (optional, default: ``False``)
        If ``True``, the GTK+ window will be returned.
1256 1257 1258 1259 1260 1261
    **kwargs
        Any extra parameters are passed to :class:`~graph_tool.draw.GraphWindow`,
        :class:`~graph_tool.draw.GraphWidget` and :func:`~graph_tool.draw.cairo_draw`.

    Returns
    -------
1262
    pos : :class:`~graph_tool.VertexPropertyMap`
1263
        Vector vertex property map with the x and y coordinates of the vertices.
1264
    selected : :class:`~graph_tool.VertexPropertyMap` (optional, only if ``output is None``)
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
        Boolean-valued vertex property map marking the vertices which were
        selected interactively.

    Notes
    -----

    See documentation of :class:`~graph_tool.draw.GraphWidget` for key bindings
    information.

    """
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    if window is None:
        if pos is None:
            if update_layout:
                pos = random_layout(g, [1, 1])
            else:
                pos = sfdp_layout(g)
        win = GraphWindow(g, pos, geometry, vprops, eprops, vorder, eorder,
                          nodesfirst, update_layout, **kwargs)
        win.show_all()
        _window_list.append(win)
    else:
        win = window
        win.graph.update(pos, vprops, eprops, vorder, eorder, nodesfirst,
                         **kwargs)
        win.graph.regenerate_surface(complete=True)
        win.graph.queue_draw()

1292
    if main:
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
        def destroy_callback(*args, **kwargs):
            global _window_list
            for w in _window_list:
                w.destroy()
            Gtk.main_quit()
        win.connect("delete_event", destroy_callback)
        Gtk.main()
    else:
        while Gtk.events_pending():
            Gtk.main_iteration()

    if return_window:
        return win
1306
    return pos, win.graph.selected.copy()