/usr/lib/python2.7/dist-packages/enable/container.py is in python-enable 4.1.0-1ubuntu3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 | """ Defines the basic Container class """
from __future__ import with_statement
# Major library imports
import warnings
# Enthought library imports
from kiva import affine
from traits.api import Any, Bool, Enum, HasTraits, Instance, List, \
Property, Tuple
# Local, relative imports
from base import empty_rectangle, intersect_bounds
from component import Component
from events import BlobEvent, BlobFrameEvent, DragEvent, MouseEvent
from abstract_layout_controller import AbstractLayoutController
class AbstractResolver(HasTraits):
"""
A Resolver traverses a component DB and matches a specifier.
"""
def match(self, db, query):
""" Queries a component DB using a dict of keyword-val conditions.
Each resolver defines its set of allowed keywords.
"""
raise NotImplementedError
class DefaultResolver(AbstractResolver):
"""
Basic resolver that searches a container's DB of components using the
following conditions:
id=foo : the component's .id must be 'foo'
class=['foo','bar'] : the component's .class must be in the list
target='foo' : the component's .target is 'foo'; this usually applies
to tools, overlays, and decorators
"""
def match(self, db, query):
pass
class Container(Component):
"""
A Container is a logical container that holds other Components within it and
provides an origin for Components to position themselves. Containers can
be "nested" (although "overlayed" is probably a better term).
If auto_size is True, the container will automatically update its bounds to
enclose all of the components handed to it, so that a container's bounds
serve as abounding box (although not necessarily a minimal bounding box) of
its contained components.
"""
# The list of components within this frame
components = Property # List(Component)
# Whether or not the container should automatically maximize itself to
# fit inside the Window, if this is a top-level container.
#
# NOTE: the way that a Container determines that it's a top-level window is
# that someone has explicitly set its .window attribute. If you need to do
# this for some other reason, you may want to turn fit_window off.
fit_window = Bool(True)
# If true, the container get events before its children. Otherwise, it
# gets them afterwards.
intercept_events = Bool(True)
# Dimensions in which this container can resize to fit its components.
# This trait only applies to dimensions that are also resizable; if the
# container is not resizable in a certain dimension, then fit_components
# has no effect.
#
# Also, note that the container does not *automatically* resize itself
# based on the value of this trait. Rather, this trait determines
# what value is reported in get_preferred_size(); it is up to the parent
# of this container to make sure that it is allocated the size that it
# needs by setting its bounds appropriately.
#
# TODO: Merge resizable and this into a single trait? Or have a separate
# "fit" flag for each dimension in the **resizable** trait?
# TODO: This trait is used in layout methods of various Container
# subclasses in Chaco. We need to move those containers into
# Enable.
fit_components = Enum("", "h", "v", "hv")
# Whether or not the container should auto-size itself to fit all of its
# components.
# Note: This trait is still used, but will be eventually removed in favor
# of **fit_components**.
auto_size = Bool(False)
# The default size of this container if it is empty.
default_size = Tuple(0, 0)
# The layers that the container will draw first, so that they appear
# under the component layers of the same name.
container_under_layers = Tuple("background", "image", "underlay", "mainlayer")
#------------------------------------------------------------------------
# DOM-related traits
# (Note: These are unused as of 8/13/2007)
#------------------------------------------------------------------------
# The layout controller determines how the container's internal layout
# mechanism works. It can perform the actual layout or defer to an
# enclosing container's layout controller. The default controller is
# a cooperative/recursive layout controller.
layout_controller = Instance(AbstractLayoutController)
# This object resolves queries for components
resolver = Instance(AbstractResolver)
#------------------------------------------------------------------------
# Private traits
#------------------------------------------------------------------------
# Shadow trait for self.components
_components = List # List(Component)
# Set of components that last handled a mouse event. We keep track of
# this so that we can generate mouse_enter and mouse_leave events of
# our own.
_prev_event_handlers = Instance( set, () )
# Used by the resolver to cache previous lookups
_lookup_cache = Any
# This container can render itself in a different mode than what it asks of
# its contained components. This attribute stores the rendering mode that
# this container requests of its children when it does a _draw(). If the
# attribute is set to "default", then whatever mode is handed in to _draw()
# is used.
_children_draw_mode = Enum("default", "normal", "overlay", "interactive")
#------------------------------------------------------------------------
# Public methods
#------------------------------------------------------------------------
def __init__(self, *components, **traits):
Component.__init__(self, **traits)
for component in components:
self.add(component)
if "bounds" in traits.keys() and "auto_size" not in traits.keys():
self.auto_size = False
if 'intercept_events' in traits:
warnings.warn("'intercept_events' is a deprecated trait",
warnings.DeprecationWarning)
return
def add(self, *components):
""" Adds components to this container """
for component in components:
if component.container is not None:
component.container.remove(component)
component.container = self
self._components.extend(components)
# Expand our bounds if necessary
if self._should_compact():
self.compact()
self.invalidate_draw()
def remove(self, *components):
""" Removes components from this container """
for component in components:
if component in self._components:
component.container = None
self._components.remove(component)
else:
raise RuntimeError, "Unable to remove component from container."
# Check to see if we need to compact.
if self.auto_size:
if (component.outer_x2 == self.width) or \
(component.outer_y2 == self.height) or \
(component.x == 0) or (component.y == 0):
self.compact()
self.invalidate_draw()
def insert(self, index, component):
"Inserts a component into a specific position in the components list"
if component.container is not None:
component.container.remove(component)
component.container = self
self._components.insert(index, component)
self.invalidate_draw()
def components_at(self, x, y):
"""
Returns a list of the components underneath the given point (given in
the parent coordinate frame of this container).
"""
result = []
if self.is_in(x,y):
xprime = x - self.position[0]
yprime = y - self.position[1]
for component in self._components[::-1]:
if component.is_in(xprime, yprime):
result.append(component)
return result
def raise_component(self, component):
""" Raises the indicated component to the top of the Z-order """
c = self._components
ndx = c.index(component)
if len(c) > 1 and ndx != len(c) - 1:
self._components = c[:ndx] + c[ndx+1:] + [component]
return
def lower_component(self, component):
""" Puts the indicated component to the very bottom of the Z-order """
raise NotImplementedError
def get(self, **kw):
"""
Allows for querying of this container's components.
"""
# TODO: cache requests
return self.resolver.query(self._components, kw)
def cleanup(self, window):
"""When a window viewing or containing a component is destroyed,
cleanup is called on the component to give it the opportunity to
delete any transient state it may have (such as backbuffers)."""
if self._components:
for component in self._components:
component.cleanup(window)
return
def compact(self):
"""
Causes this container to update its bounds to be a compact bounding
box of its components. This may cause the container to recalculate
and adjust its position relative to its parent container (and adjust
the positions of all of its contained components accordingly).
"""
# Loop over our components and determine the bounding box of all of
# the components.
ll_x, ll_y, ur_x, ur_y = self._calc_bounding_box()
if len(self._components) > 0:
# Update our position and the positions of all of our components,
# but do it quietly
for component in self._components:
component.set(position = [component.x-ll_x, component.y-ll_y],
trait_change_notify = False)
# Change our position (in our parent's coordinate frame) and
# update our bounds
self.position = [self.x + ll_x, self.y + ll_y]
self.bounds = [ur_x - ll_x, ur_y - ll_y]
return
#------------------------------------------------------------------------
# Protected methods
#------------------------------------------------------------------------
def _calc_bounding_box(self):
"""
Returns a 4-tuple (x,y,x2,y2) of the bounding box of all our contained
components. Expressed as coordinates in our local coordinate frame.
"""
if len(self._components) == 0:
return (0.0, 0.0, 0.0, 0.0)
else:
comp = self._components[0]
ll_x = comp.outer_x
ll_y = comp.outer_y
ur_x = comp.outer_x2
ur_y = comp.outer_y2
for component in self._components[1:]:
if component.x < ll_x:
ll_x = component.x
if component.x2 > ur_x:
ur_x = component.x2
if component.y < ll_y:
ll_y = component.y
if component.y2 > ur_y:
ur_y = component.y2
return (ll_x, ll_y, ur_x, ur_y)
def _dispatch_draw(self, layer, gc, view_bounds, mode):
""" Renders the named *layer* of this component.
"""
new_bounds = self._transform_view_bounds(view_bounds)
if new_bounds == empty_rectangle:
return
if self.layout_needed:
self.do_layout()
# Give the container a chance to draw first for the layers that are
# considered "under" or "at" the main layer level
if layer in self.container_under_layers:
my_handler = getattr(self, "_draw_container_" + layer, None)
if my_handler:
my_handler(gc, view_bounds, mode)
# Now transform coordinates and draw the children
visible_components = self._get_visible_components(new_bounds)
if visible_components:
with gc:
gc.translate_ctm(*self.position)
for component in visible_components:
if component.unified_draw:
# Plot containers that want unified_draw only get
# called if their draw_layer matches the current layer
# we're rendering
if component.draw_layer == layer:
component._draw(gc, new_bounds, mode)
else:
component._dispatch_draw(layer, gc, new_bounds, mode)
# The container's annotation and overlay layers draw over those of
# its components.
# FIXME: This needs to be abstracted so that when subclasses override
# the draw_order list, these are pulled from the subclass list instead
# of hardcoded here.
if layer in ("annotation", "overlay", "border"):
my_handler = getattr(self, "_draw_container_" + layer, None)
if my_handler:
my_handler(gc, view_bounds, mode)
return
def _draw_container(self, gc, mode="default"):
"Draw the container background in a specified graphics context"
pass
def _draw_container_background(self, gc, view_bounds=None, mode="normal"):
self._draw_background(gc, view_bounds, mode)
def _draw_container_overlay(self, gc, view_bounds=None, mode="normal"):
self._draw_overlay(gc, view_bounds, mode)
def _draw_container_underlay(self, gc, view_bounds=None, mode="normal"):
self._draw_underlay(gc, view_bounds, mode)
def _draw_container_border(self, gc, view_bounds=None, mode="normal"):
self._draw_border(gc, view_bounds, mode)
def _get_visible_components(self, bounds):
""" Returns a list of this plot's children that are in the bounds. """
if bounds is None:
return [c for c in self.components if c.visible]
visible_components = []
for component in self.components:
if not component.visible:
continue
tmp = intersect_bounds(component.outer_position +
component.outer_bounds, bounds)
if tmp != empty_rectangle:
visible_components.append(component)
return visible_components
def _should_layout(self, component):
""" Returns True if it is appropriate for the container to lay out
the component; False if not.
"""
if not component or \
(not component.visible and not component.invisible_layout):
return False
else:
return True
def _should_compact(self):
""" Returns True if the container needs to call compact(). Subclasses
can overload this method as needed.
"""
if self.auto_size:
width = self.width
height = self.height
for component in self.components:
x, y = component.outer_position
x2 = component.outer_x2
y2 = component.outer_y2
if (x2 >= width) or (y2 >= height) or (x < 0) or (y < 0):
return True
else:
return False
def _transform_view_bounds(self, view_bounds):
"""
Transforms the given view bounds into our local space and computes a new
region that can be handed off to our children. Returns a 4-tuple of
the new position+bounds, or None (if None was passed in), or the value
of empty_rectangle (from enable.base) if the intersection resulted
in a null region.
"""
if view_bounds:
# Check if we are visible
tmp = intersect_bounds(self.position + self.bounds, view_bounds)
if tmp == empty_rectangle:
return empty_rectangle
# Compute new_bounds, which is the view_bounds transformed into
# our coordinate space
v = view_bounds
new_bounds = (v[0]-self.x, v[1]-self.y, v[2], v[3])
else:
new_bounds = None
return new_bounds
def _component_bounds_changed(self, component):
"Called by contained objects when their bounds change"
# For now, just punt and call compact()
if self.auto_size:
self.compact()
def _component_position_changed(self, component):
"Called by contained objects when their position changes"
# For now, just punt and call compact()
if self.auto_size:
self.compact()
#------------------------------------------------------------------------
# Deprecated interface
#------------------------------------------------------------------------
def _draw_overlays(self, gc, view_bounds=None, mode="normal"):
""" Method for backward compatability with old drawing scheme.
"""
warnings.warn("Containter._draw_overlays is deprecated.")
for component in self.overlays:
component.overlay(component, gc, view_bounds, mode)
return
#------------------------------------------------------------------------
# Property setters & getters
#------------------------------------------------------------------------
def _get_components(self):
return self._components
def _get_layout_needed(self):
# Override the parent implementation to take into account whether any
# of our contained components need layout.
if self._layout_needed:
return True
else:
for c in self.components:
if c.layout_needed:
return True
else:
return False
#------------------------------------------------------------------------
# Interactor interface
#------------------------------------------------------------------------
def normal_mouse_leave(self, event):
event.push_transform(self.get_event_transform(event), caller=self)
for component in self._prev_event_handlers:
component.dispatch(event, "mouse_leave")
self._prev_event_handlers = set()
event.pop(caller=self)
def _container_handle_mouse_event(self, event, suffix):
"""
This method allows the container to handle a mouse event before its
children get to see it. Once the event gets handled, its .handled
should be set to True, and contained components will not be called
with the event.
"""
#super(Container, self)._dispatch_stateful_event(event, suffix)
Component._dispatch_stateful_event(self, event, suffix)
def get_event_transform(self, event=None, suffix=""):
return affine.affine_from_translation(-self.x, -self.y)
def _dispatch_stateful_event(self, event, suffix):
"""
Dispatches a mouse event based on the current event_state. Overrides
the default Interactor._dispatch_stateful_event by adding some default
behavior to send all events to our contained children.
"suffix" is the name of the mouse event as a suffix to the event state
name, e.g. "_left_down" or "_window_enter".
"""
if not event.handled:
if isinstance(event, BlobFrameEvent):
# This kind of event does not have a meaningful location. Just
# let all of the child components see it.
for component in self._components[::-1]:
component.dispatch(event, suffix)
return
components = self.components_at(event.x, event.y)
# Translate the event's location to be relative to this container
event.push_transform(self.get_event_transform(event, suffix),
caller=self)
try:
new_component_set = set(components)
# For "real" mouse events (i.e., not pre_mouse_* events),
# notify the previous listening components of a mouse or
# drag leave
if not suffix.startswith("pre_"):
components_left = self._prev_event_handlers - new_component_set
if components_left:
leave_event = None
if isinstance(event, MouseEvent):
leave_event = event
leave_suffix = "mouse_leave"
elif isinstance(event, DragEvent):
leave_event = event
leave_suffix = "drag_leave"
elif isinstance(event, (BlobEvent, BlobFrameEvent)):
# Do not generate a 'leave' event.
pass
else:
# TODO: think of a better way to handle this rare case?
leave_event = MouseEvent(x=event.x, y=event.y,
window=event.window)
leave_suffix = "mouse_leave"
if leave_event is not None:
for component in components_left:
component.dispatch(leave_event, "pre_" + leave_suffix)
component.dispatch(leave_event, leave_suffix)
event.handled = False
# Notify new components of a mouse enter, if the event is
# not a mouse_leave or a drag_leave
if suffix not in ("mouse_leave", "drag_leave"):
components_entered = \
new_component_set - self._prev_event_handlers
if components_entered:
enter_event = None
if isinstance(event, MouseEvent):
enter_event = event
enter_suffix = "mouse_enter"
elif isinstance(event, DragEvent):
enter_event = event
enter_suffix = "drag_enter"
elif isinstance(event, (BlobEvent, BlobFrameEvent)):
# Do not generate an 'enter' event.
pass
if enter_event:
for component in components_entered:
component.dispatch(enter_event, "pre_" + enter_suffix)
component.dispatch(enter_event, enter_suffix)
event.handled = False
# Handle the actual event
# Only add event handlers to the list of previous event handlers
# if they actually receive the event (and the event is not a
# pre_* event.
if not suffix.startswith("pre_"):
self._prev_event_handlers = set()
for component in components:
component.dispatch(event, suffix)
if not suffix.startswith("pre_"):
self._prev_event_handlers.add(component)
if event.handled:
break
finally:
event.pop(caller=self)
if not event.handled:
self._container_handle_mouse_event(event, suffix)
return
#------------------------------------------------------------------------
# Event handlers
#------------------------------------------------------------------------
def _auto_size_changed(self, old, new):
# For safety, re-compute our bounds
if new == True:
self.compact()
else:
pass
return
def _window_resized(self, newsize):
if newsize is not None:
self.bounds = [newsize[0]-self.x, newsize[1]-self.y]
#FIXME: Need a _window_changed to remove this handler if the window changes
def _fit_window_changed(self, old, new):
if self._window is not None:
if not self.fit_window:
self._window.on_trait_change(self._window_resized,
"resized", remove=True)
else:
self._window.on_trait_change(self._window_resized, "resized")
return
def _bounds_changed(self, old, new):
# crappy... calling our parent's handler seems like a common traits
# event handling problem
super(Container, self)._bounds_changed(old, new)
self._layout_needed = True
self.invalidate_draw()
def _bounds_items_changed(self, event):
super(Container, self)._bounds_items_changed(event)
self._layout_needed = True
self.invalidate_draw()
def _bgcolor_changed(self):
self.invalidate_draw()
self.request_redraw()
def __components_items_changed(self, event):
self._layout_needed = True
def __components_changed(self, event):
self._layout_needed = True
self.invalidate_draw()
#-------------------------------------------------------------------------
# Old / deprecated draw methods; here for backwards compatibility
#-------------------------------------------------------------------------
def _draw_component(self, gc, view_bounds=None, mode="normal"):
""" Draws the component.
This method is preserved for backwards compatibility. Overrides
the implementation in Component.
"""
with gc:
gc.set_antialias(False)
self._draw_container(gc, mode)
self._draw_background(gc, view_bounds, mode)
self._draw_underlay(gc, view_bounds, mode)
self._draw_children(gc, view_bounds, mode) #This was children_draw_mode
self._draw_overlays(gc, view_bounds, mode)
return
def _draw_children(self, gc, view_bounds=None, mode="normal"):
new_bounds = self._transform_view_bounds(view_bounds)
if new_bounds == empty_rectangle:
return
with gc:
gc.set_antialias(False)
gc.translate_ctm(*self.position)
for component in self.components:
if new_bounds:
tmp = intersect_bounds(component.outer_position +
component.outer_bounds, new_bounds)
if tmp == empty_rectangle:
continue
with gc:
component.draw(gc, new_bounds, mode)
return
|