1""" 2This module defines a number of context managers. These are meant to be used 3in the context of the with statement (introduced in Python 2.5). 4""" 5from Quartz.CoreGraphics import * 6 7__all__ = ('CGSavedGState', 'CGTransparencyLayer', 'CGContextPage') 8 9 10class CGSavedGState (object): 11 """ 12 Context manager for saving and restoring the graphics state. 13 14 Usage:: 15 16 with CGSavedGState(context): 17 statement 18 19 This is equivalent to: 20 CGContextSaveGState(context) 21 try: 22 statement 23 24 finally: 25 CGContextRestoreGState(context) 26 """ 27 def __init__(self, context): 28 self.context = context 29 30 def __enter__(self): 31 CGContextSaveGState(self.context) 32 return self 33 34 def __exit__(self, exc_type, exc_value, exc_tp): 35 CGContextRestoreGState(self.context) 36 return False 37 38class CGTransparencyLayer (object): 39 """ 40 Context manager for working in a transparancylayer. 41 42 Usage:: 43 44 with CGTransparencyLayer(context, info [, rect]): 45 statement 46 47 This is equivalent to: 48 CGContextBeginTransparencyLayer(context, info) 49 try: 50 statement 51 52 finally: 53 CGContextEndTransparencyLayer(context) 54 """ 55 def __init__(self, context, info, rect = None): 56 self.context = context 57 self.info = info 58 self.rect = rect 59 60 def __enter__(self): 61 if self.rect is None: 62 result = CGContextBeginTransparencyLayer(self.context, self.info) 63 else: 64 result = CGContextBeginTransparencyLayerWithRect(self.context, self.rect, self.info) 65 return result 66 67 def __exit__(self, exc_type, exc_value, exc_tp): 68 CGContextEndTransparencyLayer(self.context) 69 return False 70 71class CGContextPage (object): 72 """ 73 Context manager for saving and restoring the graphics state. 74 75 Usage:: 76 77 with CGContextPage(context): 78 statement 79 80 This is equivalent to: 81 CGContextBeginPage(context, None) 82 try: 83 statement 84 85 finally: 86 CGContextEndPage(context) 87 """ 88 def __init__(self, context, mediaBox = None): 89 self.context = context 90 self.mediaBox = mediaBox 91 92 def __enter__(self): 93 mediaRect = CGContextBeginPage(self.context, self.mediaBox) 94 95 def __exit__(self, exc_type, exc_value, exc_tp): 96 CGContextEndPage(self.context) 97 return False 98 99 100