@@ -132,15 +132,28 @@ def __init__(self, dpi):
132132 super ().__init__ ()
133133
134134 def set_context (self , ctx ):
135- self .gc .ctx = _to_context (ctx )
135+ surface = ctx .get_target ()
136+ if hasattr (surface , "get_width" ) and hasattr (surface , "get_height" ):
137+ size = surface .get_width (), surface .get_height ()
138+ elif hasattr (surface , "get_extents" ): # GTK4 RecordingSurface.
139+ ext = surface .get_extents ()
140+ size = ext .width , ext .height
141+ else : # vector surfaces.
142+ ctx .save ()
143+ ctx .reset_clip ()
144+ rect , * rest = ctx .copy_clip_rectangle_list ()
145+ if rest :
146+ raise TypeError ("Cannot infer surface size" )
147+ size = rect .width , rect .height
148+ ctx .restore ()
149+ self .gc .ctx = ctx
150+ self .width , self .height = size
136151
152+ @_api .deprecated ("3.6" , alternative = "set_context" )
137153 def set_ctx_from_surface (self , surface ):
138154 self .gc .ctx = cairo .Context (surface )
139- # Although it may appear natural to automatically call
140- # `self.set_width_height(surface.get_width(), surface.get_height())`
141- # here (instead of having the caller do so separately), this would fail
142- # for PDF/PS/SVG surfaces, which have no way to report their extents.
143155
156+ @_api .deprecated ("3.6" )
144157 def set_width_height (self , width , height ):
145158 self .width = width
146159 self .height = height
@@ -472,9 +485,8 @@ def print_rgba(self, fobj):
472485 def _get_printed_image_surface (self ):
473486 self ._renderer .dpi = self .figure .dpi
474487 width , height = self .get_width_height ()
475- self ._renderer .set_width_height (width , height )
476488 surface = cairo .ImageSurface (cairo .FORMAT_ARGB32 , width , height )
477- self ._renderer .set_ctx_from_surface ( surface )
489+ self ._renderer .set_context ( cairo . Context ( surface ) )
478490 self .figure .draw (self ._renderer )
479491 return surface
480492
@@ -514,8 +526,7 @@ def _save(self, fmt, fobj, *, orientation='portrait'):
514526 raise ValueError ("Unknown format: {!r}" .format (fmt ))
515527
516528 self ._renderer .dpi = self .figure .dpi
517- self ._renderer .set_width_height (width_in_points , height_in_points )
518- self ._renderer .set_ctx_from_surface (surface )
529+ self ._renderer .set_context (cairo .Context (surface ))
519530 ctx = self ._renderer .gc .ctx
520531
521532 if orientation == 'landscape' :
0 commit comments