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