@@ -134,15 +134,28 @@ def __init__(self, dpi):
134134 super ().__init__ ()
135135
136136 def set_context (self , ctx ):
137- self .gc .ctx = _to_context (ctx )
137+ surface = ctx .get_target ()
138+ if hasattr (surface , "get_width" ) and hasattr (surface , "get_height" ):
139+ size = surface .get_width (), surface .get_height ()
140+ elif hasattr (surface , "get_extents" ): # GTK4 RecordingSurface.
141+ ext = surface .get_extents ()
142+ size = ext .width , ext .height
143+ else : # vector surfaces.
144+ ctx .save ()
145+ ctx .reset_clip ()
146+ rect , * rest = ctx .copy_clip_rectangle_list ()
147+ if rest :
148+ raise TypeError ("Cannot infer surface size" )
149+ size = rect .width , rect .height
150+ ctx .restore ()
151+ self .gc .ctx = ctx
152+ self .width , self .height = size
138153
154+ @_api .deprecated ("3.6" , alternative = "set_context" )
139155 def set_ctx_from_surface (self , surface ):
140156 self .gc .ctx = cairo .Context (surface )
141- # Although it may appear natural to automatically call
142- # `self.set_width_height(surface.get_width(), surface.get_height())`
143- # here (instead of having the caller do so separately), this would fail
144- # for PDF/PS/SVG surfaces, which have no way to report their extents.
145157
158+ @_api .deprecated ("3.6" )
146159 def set_width_height (self , width , height ):
147160 self .width = width
148161 self .height = height
@@ -474,9 +487,8 @@ def print_rgba(self, fobj):
474487 def _get_printed_image_surface (self ):
475488 self ._renderer .dpi = self .figure .dpi
476489 width , height = self .get_width_height ()
477- self ._renderer .set_width_height (width , height )
478490 surface = cairo .ImageSurface (cairo .FORMAT_ARGB32 , width , height )
479- self ._renderer .set_ctx_from_surface ( surface )
491+ self ._renderer .set_context ( cairo . Context ( surface ) )
480492 self .figure .draw (self ._renderer )
481493 return surface
482494
@@ -516,8 +528,7 @@ def _save(self, fmt, fobj, *, orientation='portrait'):
516528 raise ValueError ("Unknown format: {!r}" .format (fmt ))
517529
518530 self ._renderer .dpi = self .figure .dpi
519- self ._renderer .set_width_height (width_in_points , height_in_points )
520- self ._renderer .set_ctx_from_surface (surface )
531+ self ._renderer .set_context (cairo .Context (surface ))
521532 ctx = self ._renderer .gc .ctx
522533
523534 if orientation == 'landscape' :
0 commit comments