/usr/lib/python2.7/dist-packages/enable/component.py is in python-enable 4.5.1-2ubuntu1.
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 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 | """ Defines the Component class """
from __future__ import with_statement
from uuid import uuid4
# Enthought library imports
from traits.api \
import Any, Bool, Delegate, Enum, Float, Instance, Int, List, \
Property, Str, Trait
from kiva.constants import FILL, STROKE
# Local relative imports
from colors import black_color_trait, white_color_trait
from coordinate_box import CoordinateBox
from enable_traits import bounds_trait, coordinate_trait, LineStyle
from interactor import Interactor
coordinate_delegate = Delegate("inner", modify=True)
DEFAULT_DRAWING_ORDER = ["background", "underlay", "mainlayer", "border", "overlay"]
class Component(CoordinateBox, Interactor):
"""
Component is the base class for most Enable objects. In addition to the
basic position and container features of Component, it also supports
Viewports and has finite bounds.
Since Components can have a border and padding, there is an additional set
of bounds and position attributes that define the "outer box" of the
components. These cannot be set, since they are secondary attributes
(computed from the component's "inner" size and margin-area attributes).
"""
#------------------------------------------------------------------------
# Basic appearance traits
#------------------------------------------------------------------------
# Is the component visible?
visible = Bool(True)
# Does the component use space in the layout even if it is not visible?
invisible_layout = Bool(False)
# Fill the padding area with the background color?
fill_padding = Bool(False)
#------------------------------------------------------------------------
# Object/containment hierarchy traits
#------------------------------------------------------------------------
# Our container object
container = Any # Instance("Container")
# A reference to our top-level Enable Window. This is stored as a shadow
# attribute if this component is the direct child of the Window; otherwise,
# the getter function recurses up the containment hierarchy.
window = Property # Instance("Window")
# The list of viewport that are viewing this component
viewports = List(Instance("enable.viewport.Viewport"))
#------------------------------------------------------------------------
# Layout traits
#------------------------------------------------------------------------
# The layout system to use:
#
# * 'chaco': Chaco-level layout (the "old" system)
# * 'enable': Enable-level layout, based on the db/resolver containment
# model.
# NB: this is in preparation for future work
#layout_switch = Enum("chaco", "enable")
# Dimensions that this component is resizable in. For resizable
# components, get_preferred_size() is called before their actual
# bounds are set.
#
# * 'v': resizable vertically
# * 'h': resizable horizontally
# * 'hv': resizable horizontally and vertically
# * '': not resizable
#
# Note that this setting means only that the *parent* can and should resize
# this component; it does *not* mean that the component automatically
# resizes itself.
resizable = Enum("hv", "h", "v", "")
# The ratio of the component's width to its height. This is used by
# the component itself to maintain bounds when the bounds are changed
# independently, and is also used by the layout system.
aspect_ratio = Trait(None, None, Float)
# When the component's bounds are set to a (width,height) tuple that does
# not conform to the set aspect ratio, does the component center itself
# in the free space?
auto_center = Bool(True)
# A read-only property that returns True if this component needs layout.
# It is a reflection of both the value of the component's private
# _layout_needed attribute as well as any logical layout dependencies with
# other components.
layout_needed = Property
# If the component is resizable, this attribute can be used to specify the
# amount of space that the component would like to get in each dimension,
# as a tuple (width, height). This attribute can be used to establish
# relative sizes between resizable components in a container: if one
# component specifies, say, a fixed preferred width of 50 and another one
# specifies a fixed preferred width of 100, then the latter component will
# always be twice as wide as the former.
fixed_preferred_size = Trait(None, None, bounds_trait)
#------------------------------------------------------------------------
# Overlays and underlays
#------------------------------------------------------------------------
# A list of underlays for this plot. By default, underlays get a chance to
# draw onto the plot area underneath plot itself but above any images and
# backgrounds of the plot.
underlays = List #[AbstractOverlay]
# A list of overlays for the plot. By default, overlays are drawn above the
# plot and its annotations.
overlays = List #[AbstractOverlay]
# Listen for changes to selection metadata on
# the underlying data sources, and render them specially?
use_selection = Bool(False)
#------------------------------------------------------------------------
# Tool and interaction handling traits
#------------------------------------------------------------------------
# An Enable Interactor that all events are deferred to.
controller = Any
# Events are *not* automatically considered "handled" if there is a handler
# defined. Overrides an inherited trait from Enable's Interactor class.
auto_handle_event = False
#------------------------------------------------------------------------
# Padding-related traits
# Padding in each dimension is defined as the number of pixels that are
# part of the component but outside of its position and bounds. Containers
# need to be aware of padding when doing layout, object collision/overlay
# calculations, etc.
#------------------------------------------------------------------------
# The amount of space to put on the left side of the component
padding_left = Int(0)
# The amount of space to put on the right side of the component
padding_right = Int(0)
# The amount of space to put on top of the component
padding_top = Int(0)
# The amount of space to put below the component
padding_bottom = Int(0)
# This property allows a way to set the padding in bulk. It can either be
# set to a single Int (which sets padding on all sides) or a tuple/list of
# 4 Ints representing the left, right, top, bottom padding amounts. When
# it is read, this property always returns the padding as a list of four
# elements even if they are all the same.
padding = Property
# Readonly property expressing the total amount of horizontal padding
hpadding = Property
# Readonly property expressing the total amount of vertical padding
vpadding = Property
# Does the component respond to mouse events over the padding area?
padding_accepts_focus = Bool(True)
#------------------------------------------------------------------------
# Position and bounds of outer box (encloses the padding and border area)
# All of these are read-only properties. To set them directly, use
# set_outer_coordinates() or set_outer_pos_bounds().
#------------------------------------------------------------------------
# The x,y point of the lower left corner of the padding outer box around
# the component. Setting this position will move the component, but
# will not change the padding or bounds.
# This returns a tuple because modifying the returned value has no effect.
# To modify outer_position element-wise, use set_outer_position().
outer_position = Property
# The number of horizontal and vertical pixels in the padding outer box.
# Setting these bounds will modify the bounds of the component, but
# will not change the lower-left position (self.outer_position) or
# the padding.
# This returns a tuple because modifying the returned value has no effect.
# To modify outer_bounds element-wise, use set_outer_bounds().
outer_bounds = Property
outer_x = Property
outer_x2 = Property
outer_y = Property
outer_y2 = Property
outer_width = Property
outer_height = Property
#------------------------------------------------------------------------
# Rendering control traits
#------------------------------------------------------------------------
# The order in which various rendering classes on this component are drawn.
# Note that if this component is placed in a container, in most cases
# the container's draw order is used, since the container calls
# each of its contained components for each rendering pass.
# Typically, the definitions of the layers are:
#
# #. 'background': Background image, shading, and (possibly) borders
# #. 'mainlayer': The main layer that most objects should draw on
# #. 'border': A special layer for rendering the border on top of the
# component instead of under its main layer (see **overlay_border**)
# #. 'overlay': Legends, selection regions, and other tool-drawn visual
# elements
draw_order = Instance(list, args=(DEFAULT_DRAWING_ORDER,))
# If True, then this component draws as a unified whole,
# and its parent container calls this component's _draw() method when
# drawing the layer indicated by **draw_layer**.
# If False, it tries to cooperate in its container's layer-by-layer drawing.
# Its parent container calls self._dispatch_draw() with the name of each
# layer as it goes through its list of layers.
unified_draw = Bool(False)
# If **unified_draw** is True for this component, then this attribute
# determines what layer it will be drawn on. This is used by containers
# and external classes, whose drawing loops call this component.
# If **unified_draw** is False, then this attribute is ignored.
draw_layer = Str("mainlayer")
# Draw the border as part of the overlay layer? If False, draw the
# border as part of the background layer.
overlay_border = Bool(True)
# Draw the border inset (on the plot)? If False, draw the border
# outside the plot area.
inset_border = Bool(True)
#------------------------------------------------------------------------
# Border and background traits
#------------------------------------------------------------------------
# The width of the border around this component. This is taken into account
# during layout, but only if the border is visible.
border_width = Int(1)
# Is the border visible? If this is false, then all the other border
# properties are not used.
border_visible = Bool(False)
# The line style (i.e. dash pattern) of the border.
border_dash = LineStyle
# The color of the border. Only used if border_visible is True.
border_color = black_color_trait
# The background color of this component. By default all components have
# a white background. This can be set to "transparent" or "none" if the
# component should be see-through.
bgcolor = white_color_trait
#------------------------------------------------------------------------
# Backbuffer traits
#------------------------------------------------------------------------
# Should this component do a backbuffered draw, i.e. render itself to an
# offscreen buffer that is cached for later use? If False, then
# the component will *never* render itself backbuffered, even if asked
# to do so.
use_backbuffer = Bool(False)
# Should the backbuffer extend to the pad area?
backbuffer_padding = Bool(True)
# If a draw were to occur, whether the component would actually change.
# This is useful for determining whether a backbuffer is valid, and is
# usually set by the component itself or set on the component by calling
# _invalidate_draw(). It is exposed as a public trait for the rare cases
# when another component wants to know the validity of this component's
# backbuffer.
draw_valid = Bool(False)
# drawn_outer_position specifies the outer position this component was drawn to
# on the last draw cycle. This is used to determine what areas of the screen
# are damaged.
drawn_outer_position = coordinate_trait
# drawn_outer_bounds specifies the bounds of this component on the last draw
# cycle. Used in conjunction with outer_position_last_draw
drawn_outer_bounds = bounds_trait
# The backbuffer of this component. In most cases, this is an
# instance of GraphicsContext, but this requirement is not enforced.
_backbuffer = Any
#------------------------------------------------------------------------
# New layout/object containment hierarchy traits
# These are not used yet.
#------------------------------------------------------------------------
# A list of strings defining the classes to which this component belongs.
# These classes will be used to determine how this component is styled,
# is rendered, is laid out, and receives events. There is no automatic
# management of conflicting class names, so if a component is placed
# into more than one class and that class
classes = List
# The element ID of this component.
id = Str
# These will be used by the new layout system, but are currently unused.
#max_width = Any
#min_width = Any
#max_height = Any
#min_height = Any
#------------------------------------------------------------------------
# Private traits
#------------------------------------------------------------------------
# Shadow trait for self.window. Only gets set if this is the top-level
# enable component in a Window.
_window = Any # Instance("Window")
# Whether or not component itself needs to be laid out. Some times
# components are composites of others, in which case the layout
# invalidation relationships should be implemented in layout_needed.
_layout_needed = Bool(True)
#------------------------------------------------------------------------
# Abstract methods
#------------------------------------------------------------------------
def _do_layout(self):
""" Called by do_layout() to do an actual layout call; it bypasses some
additional logic to handle null bounds and setting **_layout_needed**.
"""
pass
def _draw_component(self, gc, view_bounds=None, mode="normal"):
""" Renders the component.
Subclasses must implement this method to actually render themselves.
Note: This method is used only by the "old" drawing calls.
"""
pass
def _draw_selection(self, gc, view_bounds=None, mode="normal"):
""" Renders a selected subset of a component's data.
This method is used by some subclasses. The notion of selection doesn't
necessarily apply to all subclasses of PlotComponent, but it applies to
enough of them that it is defined as one of the default draw methods.
"""
pass
#------------------------------------------------------------------------
# Public methods
#------------------------------------------------------------------------
def __init__(self, **traits):
# The 'padding' trait sets 4 individual traits in bulk. Make sure that
# it gets set first before other explicit padding traits get set so they
# may override the bulk default.
padding = traits.pop('padding', None)
padding_traits = {}
for name in traits.keys():
# Use .keys() so we can modify the dict during iteration safely.
if name in ['padding_top', 'padding_bottom', 'padding_left',
'padding_right']:
padding_traits[name] = traits.pop(name)
if traits.has_key("container"):
# After the component is otherwise configured, make sure our
# container gets notified of our being added to it.
container = traits.pop("container")
super(Component,self).__init__(**traits)
self._set_padding_traits(padding, padding_traits)
container.add(self)
else:
super(Component,self).__init__(**traits)
self._set_padding_traits(padding, padding_traits)
return
def draw(self, gc, view_bounds=None, mode="default"):
""" Draws the plot component.
Parameters
----------
gc : Kiva GraphicsContext
The graphics context to draw the component on
view_bounds : 4-tuple of integers
(x, y, width, height) of the area to draw
mode : string
The drawing mode to use; can be one of:
'normal'
Normal, antialiased, high-quality rendering
'overlay'
The plot component is being rendered over something else,
so it renders more quickly, and possibly omits rendering
its background and certain tools
'interactive'
The plot component is being asked to render in
direct response to realtime user interaction, and needs to make
its best effort to render as fast as possible, even if there is
an aesthetic cost.
"""
if self.layout_needed:
self.do_layout()
self._draw(gc, view_bounds, mode)
return
def draw_select_box(self, gc, position, bounds, width, dash,
inset, color, bgcolor, marker_size):
""" Renders a selection box around the component.
Subclasses can implement this utility method to render a selection box
around themselves. To avoid burdening subclasses with various
selection-box related traits that they might never use, this method
takes all of its required data as input parameters.
Parameters
----------
gc : Kiva GraphicsContext
The graphics context to draw on.
position : (x, y)
The position of the selection region.
bounds : (width, height)
The size of the selection region.
width : integer
The width of the selection box border
dash : float array
An array of floating point values specifying the lengths of on and
off painting pattern for dashed lines.
inset : integer
Amount by which the selection box is inset on each side within the
selection region.
color : 3-tuple of floats between 0.0 and 1.0
The R, G, and B values of the selection border color.
bgcolor : 3-tuple of floats between 0.0 and 1.0
The R, G, and B values of the selection background.
marker_size : integer
Size, in pixels, of "handle" markers on the selection box
"""
with gc:
gc.set_line_width(width)
gc.set_antialias(False)
x,y = position
x += inset
y += inset
width, height = bounds
width -= 2*inset
height -= 2*inset
rect = (x, y, width, height)
gc.set_stroke_color(bgcolor)
gc.set_line_dash(None)
gc.draw_rect(rect, STROKE)
gc.set_stroke_color(color)
gc.set_line_dash(dash)
gc.draw_rect(rect, STROKE)
if marker_size > 0:
gc.set_fill_color(bgcolor)
half_y = y + height/2.0
y2 = y + height
half_x = x + width/2.0
x2 = x + width
marker_positions = ((x,y), (x,half_y), (x,y2), (half_x,y),
(half_x,y2), (x2,y), (x2, half_y), (x2,y2))
gc.set_line_dash(None)
gc.set_line_width(1.0)
for pos in marker_positions:
gc.rect(pos[0]-marker_size/2.0, pos[1]-marker_size/2.0,
marker_size, marker_size)
gc.draw_path()
return
def get_absolute_coords(self, *coords):
""" Given coordinates relative to this component's origin, returns
the "absolute" coordinates in the frame of the top-level parent
Window enclosing this component's ancestor containers.
Can be called in two ways:
get_absolute_coords(x, y)
get_absolute_coords( (x,y) )
Returns a tuple (x,y) representing the new coordinates.
"""
if self.container is not None:
offset_x, offset_y = \
self.container.get_absolute_coords(*self.position)
else:
offset_x, offset_y = self.position
return (offset_x + coords[0], offset_y + coords[1])
def get_relative_coords(self, *coords):
""" Given absolute coordinates (where the origin is the top-left corner
of the frame in the top-level parent Window) return coordinates relative
to this component's origin.
Can be called in two ways:
get_relative_coords(x, y)
get_relative_coords( (x,y) )
Returns a tuple (x,y) representing the new coordinates.
"""
if self.container is not None:
offset_x, offset_y = \
self.container.get_relative_coords(*self.position)
else:
offset_x, offset_y = self.position
return (coords[0] - offset_x, coords[1] - offset_y)
def request_redraw(self):
"""
Requests that the component redraw itself. Usually this means asking
its parent for a repaint.
"""
for view in self.viewports:
view.request_redraw()
self._request_redraw()
return
def invalidate_draw(self, damaged_regions=None, self_relative=False):
""" Invalidates any backbuffer that may exist, and notifies our parents
and viewports of any damaged regions.
Call this method whenever a component's internal state
changes such that it must be redrawn on the next draw() call."""
self.draw_valid = False
if damaged_regions is None:
damaged_regions = self._default_damaged_regions()
if self_relative:
damaged_regions = [[region[0] + self.x, region[1] + self.y,
region[2], region[3]] for region in damaged_regions]
for view in self.viewports:
view.invalidate_draw(damaged_regions=damaged_regions, self_relative=True,
view_relative=True)
if self.container is not None:
self.container.invalidate_draw(damaged_regions=damaged_regions, self_relative=True)
if self._window is not None:
self._window.invalidate_draw(damaged_regions=damaged_regions, self_relative=True)
return
def invalidate_and_redraw(self):
"""Convenience method to invalidate our contents and request redraw"""
self.invalidate_draw()
self.request_redraw()
def is_in(self, x, y):
# A basic implementation of is_in(); subclasses should provide their
# own if they are more accurate/faster/shinier.
if self.padding_accepts_focus:
bounds = self.outer_bounds
pos = self.outer_position
else:
bounds = self.bounds
pos = self.position
return (x >= pos[0]) and (x < pos[0] + bounds[0]) and \
(y >= pos[1]) and (y < pos[1] + bounds[1])
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)."""
return
def set_outer_position(self, ndx, val):
"""
Since self.outer_position is a property whose value is determined
by other (primary) attributes, it cannot return a mutable type.
This method allows generic (i.e. orientation-independent) code
to set the value of self.outer_position[0] or self.outer_position[1].
"""
if ndx == 0:
self.outer_x = val
else:
self.outer_y = val
return
def set_outer_bounds(self, ndx, val):
"""
Since self.outer_bounds is a property whose value is determined
by other (primary) attributes, it cannot return a mutable type.
This method allows generic (i.e. orientation-independent) code
to set the value of self.outer_bounds[0] or self.outer_bounds[1].
"""
if ndx == 0:
self.outer_width = val
else:
self.outer_height = val
return
#------------------------------------------------------------------------
# Layout-related concrete methods
#------------------------------------------------------------------------
def do_layout(self, size=None, force=False):
""" Tells this component to do layout at a given size.
Parameters
----------
size : (width, height)
Size at which to lay out the component; either or both values can
be 0. If it is None, then the component lays itself out using
**bounds**.
force : Boolean
Whether to force a layout operation. If False, the component does
a layout on itself only if **_layout_needed** is True.
The method always does layout on any underlays or overlays it has,
even if *force* is False.
"""
if self.layout_needed or force:
if size is not None:
self.bounds = size
self._do_layout()
self._layout_needed = False
for underlay in self.underlays:
if underlay.visible or underlay.invisible_layout:
underlay.do_layout()
for overlay in self.overlays:
if overlay.visible or overlay.invisible_layout:
overlay.do_layout()
return
def get_preferred_size(self):
""" Returns the size (width,height) that is preferred for this component
When called on a component that does not contain other components,
this method just returns the component bounds. If the component is
resizable and can draw into any size, the method returns a size that
is visually appropriate. (The component's actual bounds are
determined by its container's do_layout() method.)
"""
if self.fixed_preferred_size is not None:
return self.fixed_preferred_size
else:
size = [0,0]
outer_bounds = self.outer_bounds
if "h" not in self.resizable:
size[0] = outer_bounds[0]
if "v" not in self.resizable:
size[1] = outer_bounds[1]
return size
#------------------------------------------------------------------------
# Protected methods
#------------------------------------------------------------------------
def _set_padding_traits(self, padding, padding_traits):
""" Set the bulk padding trait and all of the others in the correct
order.
Parameters
----------
padding : None, int or list of ints
The bulk padding.
padding_traits : dict mapping str to int
The specific padding traits.
"""
if padding is not None:
self.trait_set(padding=padding)
self.trait_set(**padding_traits)
def _request_redraw(self):
if self.container is not None:
self.container.request_redraw()
elif self._window:
self._window.redraw()
return
def _default_damaged_regions(self):
"""Returns the default damaged regions for this Component. This consists
of the current position/bounds, and the last drawn position/bounds"""
return [list(self.outer_position) + list(self.outer_bounds),
list(self.drawn_outer_position) + list(self.drawn_outer_bounds)]
def _draw(self, gc, view_bounds=None, mode="default"):
""" Draws the component, paying attention to **draw_order**, including
overlays, underlays, and the like.
This method is the main draw handling logic in plot components.
The reason for implementing _draw() instead of overriding the top-level
draw() method is that the Enable base classes may do things in draw()
that mustn't be interfered with (e.g., the Viewable mix-in).
"""
if not self.visible:
return
if self.layout_needed:
self.do_layout()
self.drawn_outer_position = list(self.outer_position[:])
self.drawn_outer_bounds = list(self.outer_bounds[:])
# OpenGL-based graphics-contexts have a `gl_init()` method. We
# test for this to avoid having to import the OpenGL
# GraphicsContext just to do an isinstance() check.
is_gl = hasattr(gc, 'gl_init')
if self.use_backbuffer and (not is_gl):
if self.backbuffer_padding:
x, y = self.outer_position
width, height = self.outer_bounds
else:
x, y = self.position
width, height = self.bounds
if not self.draw_valid:
# get a reference to the GraphicsContext class from the object
GraphicsContext = gc.__class__
if hasattr(GraphicsContext, 'create_from_gc'):
# For some backends, such as the mac, a much more efficient
# backbuffer can be created from the window gc.
bb = GraphicsContext.create_from_gc(gc, (int(width), int(height)))
else:
bb = GraphicsContext((int(width), int(height)))
# if not fill_padding, then we have to fill the backbuffer
# with the window color. This is the only way I've found that
# it works- perhaps if we had better blend support we could set
# the alpha to 0, but for now doing so causes the backbuffer's
# background to be white
if not self.fill_padding:
with bb:
bb.set_antialias(False)
bb.set_fill_color(self.window.bgcolor_)
bb.draw_rect((x, y, width, height), FILL)
# Fixme: should there be a +1 here?
bb.translate_ctm(-x+0.5, -y+0.5)
# There are a couple of strategies we could use here, but we
# have to do something about view_bounds. This is because
# if we only partially render the object into the backbuffer,
# we will have problems if we then render with different view
# bounds.
for layer in self.draw_order:
if layer != "overlay":
self._dispatch_draw(layer, bb, view_bounds, mode)
self._backbuffer = bb
self.draw_valid = True
# Blit the backbuffer and then draw the overlay on top
gc.draw_image(self._backbuffer, (x, y, width, height))
self._dispatch_draw("overlay", gc, view_bounds, mode)
else:
for layer in self.draw_order:
self._dispatch_draw(layer, gc, view_bounds, mode)
return
def _dispatch_draw(self, layer, gc, view_bounds, mode):
""" Renders the named *layer* of this component.
This method can be used by container classes that group many components
together and want them to draw cooperatively. The container iterates
through its components and asks them to draw only certain layers.
"""
# Don't render the selection layer if use_selection is false. This
# is mostly for backwards compatibility.
if layer == "selection" and not self.use_selection:
return
if self.layout_needed:
self.do_layout()
handler = getattr(self, "_draw_" + layer, None)
if handler:
handler(gc, view_bounds, mode)
return
def _draw_border(self, gc, view_bounds=None, mode="default",
force_draw=False):
""" Utility method to draw the borders around this component
The *force_draw* parameter forces the method to draw the border; if it
is false, the border is drawn only when **overlay_border** is True.
"""
if not self.border_visible:
return
if self.overlay_border or force_draw:
if self.inset_border:
self._draw_inset_border(gc, view_bounds, mode)
else:
border_width = self.border_width
with gc:
gc.set_line_width(border_width)
gc.set_line_dash(self.border_dash_)
gc.set_stroke_color(self.border_color_)
gc.draw_rect((self.x-border_width/2.0, self.y-border_width/2.0,
self.width+2*border_width-1,
self.height+2*border_width-1), STROKE)
def _draw_inset_border(self, gc, view_bounds=None, mode="default"):
""" Draws the border of a component.
Unlike the default Enable border, this one is drawn on the inside of
the plot instead of around it.
"""
if not self.border_visible:
return
border_width = self.border_width
with gc:
gc.set_line_width(border_width)
gc.set_line_dash(self.border_dash_)
gc.set_stroke_color(self.border_color_)
gc.set_antialias(0)
gc.draw_rect((self.x+border_width/2.0-0.5,
self.y+border_width/2.0-0.5,
self.width-border_width/2.0,
self.height-border_width/2.0), STROKE)
#------------------------------------------------------------------------
# Protected methods for subclasses to implement
#------------------------------------------------------------------------
def _draw_background(self, gc, view_bounds=None, mode="default"):
""" Draws the background layer of a component.
"""
if self.bgcolor not in ("clear", "transparent", "none"):
if self.fill_padding:
r = tuple(self.outer_position) + \
(self.outer_width-1, self.outer_height-1)
else:
r = tuple(self.position) + (self.width-1, self.height-1)
with gc:
gc.set_antialias(False)
gc.set_fill_color(self.bgcolor_)
gc.draw_rect(r, FILL)
# Call the enable _draw_border routine
if not self.overlay_border and self.border_visible:
# Tell _draw_border to ignore the self.overlay_border
self._draw_border(gc, view_bounds, mode, force_draw=True)
return
def _draw_overlay(self, gc, view_bounds=None, mode="normal"):
""" Draws the overlay layer of a component.
"""
for overlay in self.overlays:
if overlay.visible:
overlay.overlay(self, gc, view_bounds, mode)
return
def _draw_underlay(self, gc, view_bounds=None, mode="normal"):
""" Draws the underlay layer of a component.
"""
for underlay in self.underlays:
# This method call looks funny but it's correct - underlays are
# just overlays drawn at a different time in the rendering loop.
if underlay.visible:
underlay.overlay(self, gc, view_bounds, mode)
return
def _get_visible_border(self):
""" Helper function to return the amount of border, if visible """
if self.border_visible:
if self.inset_border:
return 0
else:
return self.border_width
else:
return 0
#------------------------------------------------------------------------
# Tool-related methods and event dispatch
#------------------------------------------------------------------------
def dispatch(self, event, suffix):
""" Dispatches a mouse event based on the current event state.
Parameters
----------
event : an Enable MouseEvent
A mouse event.
suffix : string
The name of the mouse event as a suffix to the event state name,
e.g. "_left_down" or "_window_enter".
"""
# This hasattr check is necessary to ensure compatibility with Chaco
# components.
if not getattr(self, "use_draw_order", True):
self._old_dispatch(event, suffix)
else:
self._new_dispatch(event, suffix)
return
def _new_dispatch(self, event, suffix):
""" Dispatches a mouse event
If the component has a **controller**, the method dispatches the event
to it, and returns. Otherwise, the following objects get a chance to
handle the event:
1. The component's active tool, if any.
2. Any overlays, in reverse order that they were added and are drawn.
3. The component itself.
4. Any underlays, in reverse order that they were added and are drawn.
5. Any listener tools.
If any object in this sequence handles the event, the method returns
without proceeding any further through the sequence. If nothing
handles the event, the method simply returns.
"""
# Maintain compatibility with .controller for now
if self.controller is not None:
self.controller.dispatch(event, suffix)
return
if self._active_tool is not None:
self._active_tool.dispatch(event, suffix)
if event.handled:
return
# Dispatch to overlays in reverse of draw/added order
for overlay in self.overlays[::-1]:
overlay.dispatch(event, suffix)
if event.handled:
break
if not event.handled:
self._dispatch_stateful_event(event, suffix)
if not event.handled:
# Dispatch to underlays in reverse of draw/added order
for underlay in self.underlays[::-1]:
underlay.dispatch(event, suffix)
if event.handled:
break
# Now that everyone who might veto/handle the event has had a chance
# to receive it, dispatch it to our list of listener tools.
if not event.handled:
for tool in self.tools:
tool.dispatch(event, suffix)
return
def _old_dispatch(self, event, suffix):
""" Dispatches a mouse event.
If the component has a **controller**, the method dispatches the event
to it and returns. Otherwise, the following objects get a chance to
handle the event:
1. The component's active tool, if any.
2. Any listener tools.
3. The component itself.
If any object in this sequence handles the event, the method returns
without proceeding any further through the sequence. If nothing
handles the event, the method simply returns.
"""
if self.controller is not None:
self.controller.dispatch(event, suffix)
return
if self._active_tool is not None:
self._active_tool.dispatch(event, suffix)
if event.handled:
return
for tool in self.tools:
tool.dispatch(event, suffix)
if event.handled:
return
if not event.handled:
self._dispatch_to_enable(event, suffix)
return
def _get_active_tool(self):
return self._active_tool
def _set_active_tool(self, tool):
# Deactivate the existing active tool
old = self._active_tool
if old == tool:
return
self._active_tool = tool
if old is not None:
old.deactivate(self)
if tool is not None and hasattr(tool, "_activate"):
tool._activate()
self.invalidate_and_redraw()
return
def _get_layout_needed(self):
return self._layout_needed
def _tools_items_changed(self):
self.invalidate_and_redraw()
#------------------------------------------------------------------------
# Event handlers
#------------------------------------------------------------------------
def _id_default(self):
""" Generate a random UUID for the ID.
"""
# The first 32bits is plenty.
return uuid4().hex[:8]
def _aspect_ratio_changed(self, old, new):
if new is not None:
self._enforce_aspect_ratio()
def _enforce_aspect_ratio(self, notify=True):
""" This method adjusts the width and/or height of the component so
that the new width and height match the aspect ratio. It uses the
current width and height as a bounding box and finds the largest
rectangle of the desired aspect ratio that will fit.
If **notify** is True, then fires trait events for bounds and
position changing.
"""
ratio = self.aspect_ratio
old_w, old_h = self.bounds
if ratio is None:
return
elif ratio == 0:
self.width = 0
return
elif old_h == 0:
return
elif int(old_w) == int(ratio * old_h):
return
old_aspect = old_w / float(old_h)
new_pos = None
if ratio > old_aspect:
# desired rectangle is wider than bounding box, so use the width
# and compute a smaller height
new_w = old_w
new_h = new_w / ratio
if self.auto_center:
new_pos = self.position[:]
new_pos[1] += (old_h - new_h) / 2.0
else:
# desired rectangle is taller than bounding box, so use the height
# and compute a smaller width
new_h = old_h
new_w = new_h * ratio
if self.auto_center:
new_pos = self.position[:]
new_pos[0] += (old_w - new_w) / 2.0
self.set(bounds=[new_w, new_h], trait_change_notify=notify)
if new_pos:
self.set(position=new_pos, trait_change_notify=notify)
return
def _bounds_changed(self, old, new):
self._enforce_aspect_ratio(notify=True)
if self.container is not None:
self.container._component_bounds_changed(self)
return
def _bounds_items_changed(self, event):
self._enforce_aspect_ratio(notify=True)
if self.container is not None:
self.container._component_bounds_changed(self)
return
def _container_changed(self, old, new):
# We don't notify our container of this change b/c the
# caller who changed our .container should take care of that.
if new is None:
self.position = [0,0]
def _position_changed(self, *args):
if self.container is not None:
self.container._component_position_changed(self)
def _position_items_changed(self, *args):
if self.container is not None:
self.container._component_position_changed(self)
def _visible_changed(self, old, new):
if new:
self._layout_needed = True
def _get_window(self):
if self._window is not None:
return self._window
elif self.container is not None:
return self.container.window
else:
return None
def _set_window(self, win):
self._window = win
#------------------------------------------------------------------------
# Position and padding setters and getters
#------------------------------------------------------------------------
def _get_x(self):
return self.position[0]
def _set_x(self, val):
self.position[0] = val
def _get_y(self):
return self.position[1]
def _set_y(self, val):
self.position[1] = val
def _get_padding(self):
return [self.padding_left, self.padding_right,
self.padding_top, self.padding_bottom]
def _set_padding(self, val):
old_padding = self.padding
if type(val) == int:
self.padding_left = self.padding_right = \
self.padding_top = self.padding_bottom = val
self.trait_property_changed("padding", old_padding, [val]*4)
else:
# assume padding is some sort of array type
if len(val) != 4:
raise RuntimeError("Padding must be a 4-element sequence "
"type or an int. Instead, got" + str(val))
self.padding_left = val[0]
self.padding_right = val[1]
self.padding_top = val[2]
self.padding_bottom = val[3]
self.trait_property_changed("padding", old_padding, val)
return
def _get_hpadding(self):
return 2*self._get_visible_border() + self.padding_right + \
self.padding_left
def _get_vpadding(self):
return 2*self._get_visible_border() + self.padding_bottom + \
self.padding_top
#------------------------------------------------------------------------
# Outer position setters and getters
#------------------------------------------------------------------------
def _get_outer_position(self):
border = self._get_visible_border()
pos = self.position
return (pos[0] - self.padding_left - border,
pos[1] - self.padding_bottom - border)
def _set_outer_position(self, new_pos):
border = self._get_visible_border()
self.position = [new_pos[0] + self.padding_left + border,
new_pos[1] + self.padding_bottom + border]
def _get_outer_x(self):
return self.x - self.padding_left - self._get_visible_border()
def _set_outer_x(self, val):
self.position[0] = val + self.padding_left + self._get_visible_border()
def _get_outer_x2(self):
return self.x2 + self.padding_right + self._get_visible_border()
def _set_outer_x2(self, val):
self.x2 = val - self.padding_right - self._get_visible_border()
def _get_outer_y(self):
return self.y - self.padding_bottom - self._get_visible_border()
def _set_outer_y(self, val):
self.position[1] = val + self.padding_bottom + \
self._get_visible_border()
def _get_outer_y2(self):
return self.y2 + self.padding_top + self._get_visible_border()
def _set_outer_y2(self, val):
self.y2 = val - self.padding_top - self._get_visible_border()
#------------------------------------------------------------------------
# Outer bounds setters and getters
#------------------------------------------------------------------------
def _get_outer_bounds(self):
bounds = self.bounds
return (bounds[0] + self.hpadding, bounds[1] + self.vpadding)
def _set_outer_bounds(self, bounds):
self.bounds = [bounds[0] - self.hpadding, bounds[1] - self.vpadding]
def _get_outer_width(self):
return self.outer_bounds[0]
def _set_outer_width(self, width):
self.bounds[0] = width - self.hpadding
def _get_outer_height(self):
return self.outer_bounds[1]
def _set_outer_height(self, height):
self.bounds[1] = height - self.vpadding
# EOF
|