コード例 #1
0
ファイル: Pixmap.py プロジェクト: rceballos98/hapticJacket
 def __init__(self, width, height):
     GPixmap.__init__(self)
     # ns_size = NSSize(width, height)
     # ns_image = NSImage.alloc().initWithSize_(ns_size)
     ns_image = NSImage.alloc().init()
     ns_image.setCacheMode_(NSImageCacheNever)
     row_bytes = 4 * width
     ns_bitmap = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
         None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32
     )
     ns_image.addRepresentation_(ns_bitmap)
     ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap)
     ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context)
     ns_tr = NSAffineTransform.transform()
     ns_tr.translateXBy_yBy_(0.0, height)
     ns_tr.scaleXBy_yBy_(1.0, -1.0)
     #  Using __class__ to get +saveGraphicsState instead of -saveGraphicsState
     NSGraphicsContext.__class__.saveGraphicsState()
     try:
         NSGraphicsContext.setCurrentContext_(ns_graphics_context)
         ns_tr.concat()
     finally:
         NSGraphicsContext.__class__.restoreGraphicsState()
     self._init_with_ns_image(ns_image, flipped=True)  # False)
     self._ns_bitmap_image_rep = ns_bitmap
     self._ns_graphics_context = ns_graphics_context
コード例 #2
0
ファイル: Pixmap.py プロジェクト: mnabeelp/PyGUI
	def __init__(self, width, height):
		GPixmap.__init__(self)
		#ns_size = NSSize(width, height)
		#ns_image = NSImage.alloc().initWithSize_(ns_size)
		ns_image = NSImage.alloc().init()
		ns_image.setCacheMode_(NSImageCacheNever)
		row_bytes = 4 * width
		ns_bitmap = NSBitmapImageRep.alloc().\
			initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
			None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32)
		ns_image.addRepresentation_(ns_bitmap)
		ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap)
		ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context)
		ns_tr = NSAffineTransform.transform()
		ns_tr.translateXBy_yBy_(0.0, height)
		ns_tr.scaleXBy_yBy_(1.0, -1.0)
		#  Using __class__ to get +saveGraphicsState instead of -saveGraphicsState
		NSGraphicsContext.__class__.saveGraphicsState()
		try:
			NSGraphicsContext.setCurrentContext_(ns_graphics_context)
			ns_tr.concat()
		finally:
			NSGraphicsContext.__class__.restoreGraphicsState()
		self._init_with_ns_image(ns_image, flipped = True) #False)
		self._ns_bitmap_image_rep = ns_bitmap
		self._ns_graphics_context = ns_graphics_context
コード例 #3
0
	def generateThumbnail(self):
		if not self._thumbnail:
			if usePyObjC:
				from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage
				from Foundation import NSRect
				image = self.image
				rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
					None,
					int(self.thumbnailSize), int(self.thumbnailSize),
					8, 4,
					True,
					False,
					NSCalibratedRGBColorSpace,
					0, 32,
				)
				context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
				oldContext = NSGraphicsContext.currentContext()
				NSGraphicsContext.setCurrentContext_(context)
				image.drawInRect_fromRect_operation_fraction_(
					NSRect((0, 0), (self.thumbnailSize, self.thumbnailSize)),
					NSRect((0, 0), image.size()),
					NSCompositeCopy,
					1.0,
				)
				NSGraphicsContext.setCurrentContext_(oldContext)
				self._thumbnail = NSImage.alloc().initWithSize_((self.thumbnailSize, self.thumbnailSize))
				self._thumbnail.addRepresentation_(rep)
			else:
				import wx
				try:
					image = self.image.Scale(self.thumbnailSize, self.thumbnailSize, wx.IMAGE_QUALITY_HIGH)
				except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH
					image = self.image.Scale(self.thumbnailSize, self.thumbnailSize)
				self._thumbnail = wx.BitmapFromImage(image)
		return self._thumbnail
コード例 #4
0
    def setPixel(self, event, dragging=False):
        if self.data is None:
            return False
        try:
            editView = self.editViewController().graphicView()
        except:
            return False

        layer = editView.activeLayer()
        try:
            master = layer.parent.parent.masters[layer.layerId]
        except KeyError:
            return False
        if master is None:
            return False

        # Get location of click in font coordinates
        Loc = editView.getActiveLocation_(event)
        loc_pixel = ((Loc.x - self.rect.origin.x) / self.pixel_size,
                     (Loc.y - self.rect.origin.y) / self.pixel_size /
                     self.pixel_ratio)
        if self.prev_location != loc_pixel:
            x, y = loc_pixel
            current = NSGraphicsContext.currentContext()
            context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(
                self.data)
            if context is None:
                self.prev_location = loc_pixel
                print("Could not get context in setPixel")
                return False
            NSGraphicsContext.saveGraphicsState()
            NSGraphicsContext.setCurrentContext_(context)
            if self.erase:
                NSColor.whiteColor().set()
            else:
                NSColor.blackColor().set()
            effective_size = self.pen_size / self.pixel_size
            if dragging and self.prev_location is not None:
                px, py = self.prev_location
                path = NSBezierPath.alloc().init()
                path.setLineCapStyle_(NSRoundLineCapStyle)
                path.setLineWidth_(effective_size)
                # path.strokeLineFromPoint_toPoint_(x, y, x + self.pen_size, y + self.pen_size)
                path.moveToPoint_((px, py))
                path.lineToPoint_((x, y))
                path.stroke()
                self.needs_save = True
            else:
                half = effective_size / 2
                rect = NSMakeRect(x - half, y - half, effective_size,
                                  effective_size)
                path = NSBezierPath.bezierPathWithOvalInRect_(rect)
                path.fill()
                self.needs_save = True
            # For rectangular pens:
            # NSBezierPath.fillRect_(rect)
            NSGraphicsContext.setCurrentContext_(current)
            NSGraphicsContext.restoreGraphicsState()
            self.prev_location = loc_pixel
        return True
コード例 #5
0
ファイル: Pixmap.py プロジェクト: rceballos98/hapticJacket
 def with_canvas(self, proc):
     NSGraphicsContext.__class__.saveGraphicsState()
     NSGraphicsContext.setCurrentContext_(self._ns_graphics_context)
     try:
         canvas = Canvas()
         proc(canvas)
     finally:
         NSGraphicsContext.__class__.restoreGraphicsState()
コード例 #6
0
ファイル: Pixmap.py プロジェクト: mnabeelp/PyGUI
	def with_canvas(self, proc):
		NSGraphicsContext.__class__.saveGraphicsState()
		NSGraphicsContext.setCurrentContext_(self._ns_graphics_context)
		try:
			canvas = Canvas()
			proc(canvas)
		finally:
			NSGraphicsContext.__class__.restoreGraphicsState()
コード例 #7
0
	def toRGBA(self):
		if usePyObjC:
			from AppKit import NSBitmapImageRep, NSDeviceRGBColorSpace, NSGraphicsContext, NSCompositeCopy
			from Foundation import NSRect
			image = self.image
			size = image.size()
			rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
				None,
				int(size.width), int(size.height),
				8, 4,
				True,
				False,
				NSDeviceRGBColorSpace,
				0, 32,
			)
			context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
			oldContext = NSGraphicsContext.currentContext()
			NSGraphicsContext.setCurrentContext_(context)
			oldFlipped = image.isFlipped()
			image.setFlipped_(True)
			image.drawInRect_fromRect_operation_fraction_(
				NSRect((0, 0), size),
				NSRect((0, 0), size),
				NSCompositeCopy,
				1.0,
			)
			image.setFlipped_(oldFlipped)
			NSGraphicsContext.setCurrentContext_(oldContext)
			# FIXME: take bytesPerRow into account
			data = str(rep.bitmapData())
		else:
			image = self.image.Mirror(horizontally = False) # wxImage coordinates are flipped vertically
			data = list(image.GetData())
			rdata = data[0::3]
			gdata = data[1::3]
			bdata = data[2::3]
			if image.HasAlpha():
				adata = image.GetAlpha()
			else:
				adata = '\xFF' * len(rdata)
			data = ''.join([r + g + b + a for r, g, b, a in zip(rdata, gdata, bdata, adata)])
		return data
コード例 #8
0
async def test_colrV1Font():
    fontPath = getFontPath("more_samples-glyf_colr_1.ttf")
    numFonts, opener, getSortInfo = getOpener(fontPath)
    font = opener(fontPath, 0)
    await font.load(None)
    textInfo = TextInfo("c")
    glyphs = font.getGlyphRunFromTextInfo(textInfo)
    glyphNames = [g.name for g in glyphs]
    glyphDrawing, *_ = font.getGlyphDrawings(glyphNames, True)
    boundingBox = glyphDrawing.bounds
    assert (100, 0, 900, 1000) == boundingBox
    surface = CoreGraphicsPixelSurface(boundingBox)
    context = NSGraphicsContext.graphicsContextWithCGContext_flipped_(
        surface.context, False)
    savedContext = NSGraphicsContext.currentContext()
    try:
        NSGraphicsContext.setCurrentContext_(context)
        glyphDrawing.draw(glyphs.colorPalette, (0, 0, 0, 1))
    finally:
        NSGraphicsContext.setCurrentContext_(savedContext)
コード例 #9
0
ファイル: kpfutil.py プロジェクト: BobertForever/kaas
    def render(self, filename):
        ''' Renders the given build's build preview to an image 
        with the given filename.
        '''

        # Sets up a blank bitmap canvas for drawing to. Such an ugly method
        # call. Any easier way to do this in Obj-C?
        init = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_
        im = init(None, self.kpf.width, self.kpf.height, 8, 4, True, False, NSDeviceRGBColorSpace, 0, 0)

        # Set up the Objective-C graphics context based on the bitmap canvas
        # we just created
        context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(im)
        context.setCompositingOperation_(NSCompositeSourceOver)
        NSGraphicsContext.setCurrentContext_(context)

        # Ask the implementation to render itself
        self.__render__()

        # Output the file
        imjpeg = im.representationUsingType_properties_(NSJPEGFileType, None)
        imjpeg.writeToFile_atomically_(filename, False)
コード例 #10
0
ファイル: kpfutil.py プロジェクト: marccolemont/kaas
    def render(self, filename):
        ''' Renders the given build's build preview to an image 
        with the given filename.
        '''

        # Sets up a blank bitmap canvas for drawing to. Such an ugly method
        # call. Any easier way to do this in Obj-C?
        init = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_
        im = init(None, self.kpf.width, self.kpf.height, 8, 4, True, False, NSDeviceRGBColorSpace, 0, 0)

        # Set up the Objective-C graphics context based on the bitmap canvas
        # we just created
        context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(im)
        context.setCompositingOperation_(NSCompositeSourceOver)
        NSGraphicsContext.setCurrentContext_(context)

        # Ask the implementation to render itself
        self.__render__()

        # Output the file
        imjpeg = im.representationUsingType_properties_(NSJPEGFileType, None)
        imjpeg.writeToFile_atomically_(filename, False)
コード例 #11
0
def initImage(layer, width, height, pixel_size=default_pixel_size, ratio=1):
    # See https://developer.apple.com/documentation/appkit/nsbitmapimagerep/1395538-init
    img = NSBitmapImageRep.alloc(
    ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(
        None,  # BitmapDataPlanes
        int(round(width / pixel_size)),  # pixelsWide
        int(round(height / pixel_size / ratio)),  # pixelsHigh
        8,  # bitsPerSample: 1, 2, 4, 8, 12, or 16
        1,  # samplesPerPixel: 1 - 5
        False,  # hasAlpha
        False,  # isPlanar
        NSDeviceWhiteColorSpace,  # colorSpaceName
        # NSDeviceRGBColorSpace,
        0,  # bitmapFormat
        0,  # bytesPerRow
        0,  # bitsPerPixel
    )
    """
        NSCalibratedWhiteColorSpace
        NSCalibratedBlackColorSpace
        NSCalibratedRGBColorSpace
        NSDeviceWhiteColorSpace
        NSDeviceBlackColorSpace
        NSDeviceRGBColorSpace
        NSDeviceCMYKColorSpace
        NSNamedColorSpace
        NSCustomColorSpace
    """
    # The image is filled black for some reason, make it white
    current = NSGraphicsContext.currentContext()
    context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(img)
    NSGraphicsContext.setCurrentContext_(context)
    NSColor.whiteColor().set()
    # NSBezierPath.setLineWidth_(1)
    NSBezierPath.fillRect_(NSMakeRect(0, 0, width, int(round(height / ratio))))
    NSGraphicsContext.setCurrentContext_(current)
    return img
コード例 #12
0
    def as_matrix(self, normalize=False, binarize=False):
        """Renders the glyph as a matrix. By default, the matrix values are integer pixel greyscale values
    in the range 0 to 255, but they can be normalized or turned into binary values with the
    appropriate keyword arguments. The matrix is returned as a `GlyphRendering` object which
    can be further manipulated."""
        box_height = int(self.font.full_height_px)
        box_width = int(self.ink_width)

        b = NSBitmapImageRep.alloc(
        ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
            None, box_width, box_height, 8, 1, False, False,
            NSCalibratedWhiteColorSpace, 0, 0)
        ctx = NSGraphicsContext.graphicsContextWithBitmapImageRep_(b)
        assert (ctx)
        NSGraphicsContext.setCurrentContext_(ctx)

        NSColor.whiteColor().setFill()
        p2 = NSBezierPath.bezierPath()
        p2.appendBezierPath_(self.layer.completeBezierPath)
        t = NSAffineTransform.transform()
        t.translateXBy_yBy_(-self.lsb,
                            -self.font.descender * self.font.scale_factor)
        t.scaleBy_(self.font.scale_factor)
        p2.transformUsingAffineTransform_(t)
        p2.fill()

        png = b.representationUsingType_properties_(NSPNGFileType, None)
        png.writeToFile_atomically_("/tmp/foo.png", False)
        Z = np.array(b.bitmapData())
        box_width_up = Z.shape[0] / box_height
        Z = Z.reshape((box_height, box_width_up))[0:box_height, 0:box_width]

        if normalize or binarize:
            Z = Z / 255.0
        if binarize:
            Z = Z.astype(int)
        return GlyphRendering.init_from_numpy(self, Z)
コード例 #13
0
def runAutopsy(fonts, glyphNames):
	if fonts and glyphNames:
		
		starttime = time.time()
		
		global pagewidth, pageheight
		#global myDialog
		
		if Glyphs.intDefaults["com_yanone_Autopsy_PageOrientation"] == Portrait:
			if not Glyphs.boolDefaults["com_yanone_Autopsy_PageSize_a4"]:
				pagewidth = letter[0]
				pageheight = letter[1]
			else:
				pagewidth = A4[0]
				pageheight = A4[1]
		else:
			if not Glyphs.boolDefaults["com_yanone_Autopsy_PageSize_a4"]:
				pagewidth = letter[1]
				pageheight = letter[0]
			else:
				pagewidth = A4[1]
				pageheight = A4[0]
		
		#############
		#
		# Collect information about the glyphs
		#
	
		# Dimensions
		reports = Ddict(dict)
	
		glyphwidth = Ddict(dict)
		maxwidthperglyph = Ddict(dict)
		maxwidth = 0
		maxsinglewidth = 0
		glyphheight = Ddict(dict)
		maxheightperglyph = Ddict(dict)
		maxheight = 0
		maxsingleheight = 0
		
		for glyphName in glyphNames:
	
			glyphwidth[glyphName] = 0
			glyphheight[glyphName] = 0
			maxwidthperglyph[glyphName] = 0
			maxheightperglyph[glyphName] = 0
			reports[glyphName]['width'] = Report()
			reports[glyphName]['height'] = Report()
			reports[glyphName]['bboxwidth'] = Report()
			reports[glyphName]['bboxheight'] = Report()
			reports[glyphName]['highestpoint'] = Report()
			reports[glyphName]['lowestpoint'] = Report()
			reports[glyphName]['leftsidebearing'] = Report()
			reports[glyphName]['rightsidebearing'] = Report()
			for font in fonts:
				FontMaster = font.masters[0]
				if font.glyphs.has_key(glyphName):
					g = font.glyphs[glyphName].layers[FontMaster.id]
					#print "__g", g
					glyphwidth[glyphName] = g.width
					height = ascender(font) - descender(font)

					widthforgraph = glyphwidth[glyphName]
					if widthforgraph == 0:
						widthforgraph = g.bounds.size.width
					heightforgraph = height
	
					# width of kegel
					reports[glyphName]['width'].addvalue((glyphwidth[glyphName], widthforgraph, heightforgraph))
					# sum of widths per glyph
					if reports[glyphName]['width'].sum > maxwidth:
						maxwidth = reports[glyphName]['width'].sum
					if reports[glyphName]['width'].max > maxsinglewidth:
						maxsinglewidth = reports[glyphName]['width'].max
						
					# height of kegel
					glyphheight[glyphName] = height
					reports[glyphName]['height'].addvalue((glyphheight[glyphName], widthforgraph, heightforgraph))
					# sum of heights per glyph
					if reports[glyphName]['height'].sum > maxheight:
						maxheight = reports[glyphName]['height'].sum
					if reports[glyphName]['height'].max > maxsingleheight:
						maxsingleheight = reports[glyphName]['height'].max
					
					# BBox
					overthetop = 20000
					
					bbox = g.bounds
					
					if bbox.size.width < -1*overthetop or bbox.size.width > overthetop:
						reports[glyphName]['bboxwidth'].addvalue((0, widthforgraph, heightforgraph))
					else:
						reports[glyphName]['bboxwidth'].addvalue((bbox.size.width, widthforgraph, heightforgraph))
					
					if bbox.size.height < -1*overthetop or bbox.size.height > overthetop:
						reports[glyphName]['bboxheight'].addvalue((0, widthforgraph, heightforgraph))
					else:
						reports[glyphName]['bboxheight'].addvalue((bbox.size.height, widthforgraph, heightforgraph))
					
					
					if (bbox.origin.y + bbox.size.height) < -1*overthetop or (bbox.origin.y + bbox.size.height) > overthetop:
						reports[glyphName]['highestpoint'].addvalue((0, widthforgraph, heightforgraph))
					else:
						reports[glyphName]['highestpoint'].addvalue((bbox.origin.y + bbox.size.height, widthforgraph, heightforgraph))
					
					if bbox.origin.y < -1*overthetop or bbox.origin.y > overthetop:
						reports[glyphName]['lowestpoint'].addvalue((0, widthforgraph, heightforgraph))
					else:
						reports[glyphName]['lowestpoint'].addvalue((bbox.origin.y, widthforgraph, heightforgraph))
					
					# L + R sidebearing
					reports[glyphName]['leftsidebearing'].addvalue((g.LSB, widthforgraph, heightforgraph))
					reports[glyphName]['rightsidebearing'].addvalue((g.RSB, widthforgraph, heightforgraph))

		

		# Recalculate drawing boards
		numberoftables = 0
		# GSNotImplemented
		# for table in availablegraphs:
		# 	if eval('myDialog.graph_' + table):
		# 		numberoftables += 1

		if numberoftables < 3:
			numberoftables = 3
		try:
			r = 2.0 / numberoftables
		except:
			r = .8
		SetScrapBoard(r)

			
		# Calculate ratio
		global ratio
		if Glyphs.intDefaults["com_yanone_Autopsy_PageOrientation"] == Portrait:
			ratio = (scrapboard['top'] - scrapboard['bottom']) / maxheight * mm
			ratio2 = (scrapboard['right'] - scrapboard['left']) / maxsinglewidth * mm
			maxratio = 0.3
			if ratio > maxratio:
				ratio = maxratio
			if ratio > ratio2:
				ratio = ratio2
		else:
			ratio = (scrapboard['right'] - scrapboard['left']) / maxwidth * mm
			ratio2 = (scrapboard['top'] - scrapboard['bottom']) / maxsingleheight * mm
			maxratio = 0.3
			if ratio > maxratio:
				ratio = maxratio
			if ratio > ratio2:
				ratio = ratio2
		
		
		# PDF Init stuff
		filename = Glyphs.defaults["com_yanone_Autopsy_filename"]
		tempFileName = NSTemporaryDirectory()+"%d.pdf"%random.randint(1000,100000)
		
		pageRect = CGRectMake (0, 0, pagewidth, pageheight)
		
		fileURL = NSURL.fileURLWithPath_(tempFileName)
		pdfContext = CGPDFContextCreateWithURL(fileURL, pageRect, None)
		CGPDFContextBeginPage(pdfContext, None)
		
		pdfNSGraphicsContext = NSGraphicsContext.graphicsContextWithGraphicsPort_flipped_(pdfContext, False)
		NSGraphicsContext.saveGraphicsState()
		NSGraphicsContext.setCurrentContext_(pdfNSGraphicsContext)
		
		try:
		
			drawTitlePage(fonts)
			CGPDFContextEndPage(pdfContext)
			### MAIN PAGES ###
		
			
			for i, glyphName in enumerate(glyphNames):
				CGPDFContextBeginPage(pdfContext, None)
				drawGlyph(fonts, glyphName, i, ratio, reports)
				# End page
				CGPDFContextEndPage(pdfContext)
			
		except:
			print "__Main"
			print traceback.format_exc()
			
		finally:
			# close PDF
			NSGraphicsContext.restoreGraphicsState()
			CGPDFContextClose(pdfContext)
		
		output("time: " + str(time.time() - starttime) + "sec, ca." + str((time.time() - starttime) / len(glyphNames)) + "sec per glyph")
		
		
		if errors:
			print "__Errors", errors
			for error in errortexts:
				#print "__Message", error, programname
				dlg = message(error)
			
		# if not errors and fonts and myDialog.openPDF:
		if not errors and fonts:
			try:
				os.rename(tempFileName, filename)
			except:
				dlg = Message("Error", "Problem copying final pdf")
			if Glyphs.defaults["com_yanone_Autopsy_openPDF"]:
				launchfile(filename)
コード例 #14
0
	def generateImage(self):
		size = self.imageSize
		dx, dy = self.dx, self.dy
		image = self.texture.image
		if usePyObjC:
			from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage
			from Foundation import NSRect
			rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
				None,
				int(size), int(size),
				8, 4,
				True,
				False,
				NSCalibratedRGBColorSpace,
				0, 32,
			)
			context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
			oldContext = NSGraphicsContext.currentContext()
			NSGraphicsContext.setCurrentContext_(context)
			image.drawInRect_fromRect_operation_fraction_(
				NSRect((0, 0), (size, size)),
				NSRect((0, 0), image.size()),
				NSCompositeCopy,
				1.0,
			)
			NSGraphicsContext.setCurrentContext_(oldContext)
			image = NSImage.alloc().initWithSize_((size, size))
			image.addRepresentation_(rep)
			rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
				None,
				int(size), int(size),
				8, 4,
				True,
				False,
				NSCalibratedRGBColorSpace,
				0, 32,
			)
			context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
			oldContext = NSGraphicsContext.currentContext()
			NSGraphicsContext.setCurrentContext_(context)
			srcPoints = (
				(0, 0),
				(size - dx, 0),
				(0, size - dy),
				(size - dx, size - dy),
			)
			dstPoints = (
				(dx, dy),
				(0, dy),
				(dx, 0),
				(0, 0),
			)
			sizes = (
				(size - dx, size - dy),
				(dx, size - dy),
				(size - dx, dy),
				(dx, dy),
			)
			for src, dst, siz in zip(srcPoints, dstPoints, sizes):
				if siz[0] > 0 and siz[1] > 0: # not sure if Cocoa appreciates trying to draw an image with invalid bounds
					image.drawInRect_fromRect_operation_fraction_(
						NSRect(dst, siz),
						NSRect(src, siz),
						NSCompositeCopy,
						1.0,
					)
			NSGraphicsContext.setCurrentContext_(oldContext)
			result = NSImage.alloc().initWithSize_((size, size))
			result.addRepresentation_(rep)
		else:
			import wx
			try:
				image = image.Scale(size, size, wx.IMAGE_QUALITY_HIGH)
			except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH
				image = image.Scale(size, size)
			result = wx.BitmapFromImage(image)
		return result
コード例 #15
0
def runAutopsy(fonts, glyphNames):
    if fonts and glyphNames:

        starttime = time.time()

        global pagewidth, pageheight
        #global myDialog

        if Glyphs.intDefaults[
                "com_yanone_Autopsy_PageOrientation"] == Portrait:
            if not Glyphs.boolDefaults["com_yanone_Autopsy_PageSize_a4"]:
                pagewidth = letter[0]
                pageheight = letter[1]
            else:
                pagewidth = A4[0]
                pageheight = A4[1]
        else:
            if not Glyphs.boolDefaults["com_yanone_Autopsy_PageSize_a4"]:
                pagewidth = letter[1]
                pageheight = letter[0]
            else:
                pagewidth = A4[1]
                pageheight = A4[0]

        #############
        #
        # Collect information about the glyphs
        #

        # Dimensions
        reports = Ddict(dict)

        glyphwidth = Ddict(dict)
        maxwidthperglyph = Ddict(dict)
        maxwidth = 0
        maxsinglewidth = 0
        glyphheight = Ddict(dict)
        maxheightperglyph = Ddict(dict)
        maxheight = 0
        maxsingleheight = 0

        for glyphName in glyphNames:

            glyphwidth[glyphName] = 0
            glyphheight[glyphName] = 0
            maxwidthperglyph[glyphName] = 0
            maxheightperglyph[glyphName] = 0
            reports[glyphName]['width'] = Report()
            reports[glyphName]['height'] = Report()
            reports[glyphName]['bboxwidth'] = Report()
            reports[glyphName]['bboxheight'] = Report()
            reports[glyphName]['highestpoint'] = Report()
            reports[glyphName]['lowestpoint'] = Report()
            reports[glyphName]['leftsidebearing'] = Report()
            reports[glyphName]['rightsidebearing'] = Report()
            for font in fonts:
                FontMaster = font.masters[0]
                if font.glyphs.has_key(glyphName):
                    g = font.glyphs[glyphName].layers[FontMaster.id]
                    #print "__g", g
                    glyphwidth[glyphName] = g.width
                    height = ascender(font) - descender(font)

                    widthforgraph = glyphwidth[glyphName]
                    if widthforgraph == 0:
                        widthforgraph = g.bounds.size.width
                    heightforgraph = height

                    # width of kegel
                    reports[glyphName]['width'].addvalue(
                        (glyphwidth[glyphName], widthforgraph, heightforgraph))
                    # sum of widths per glyph
                    if reports[glyphName]['width'].sum > maxwidth:
                        maxwidth = reports[glyphName]['width'].sum
                    if reports[glyphName]['width'].max > maxsinglewidth:
                        maxsinglewidth = reports[glyphName]['width'].max

                    # height of kegel
                    glyphheight[glyphName] = height
                    reports[glyphName]['height'].addvalue(
                        (glyphheight[glyphName], widthforgraph,
                         heightforgraph))
                    # sum of heights per glyph
                    if reports[glyphName]['height'].sum > maxheight:
                        maxheight = reports[glyphName]['height'].sum
                    if reports[glyphName]['height'].max > maxsingleheight:
                        maxsingleheight = reports[glyphName]['height'].max

                    # BBox
                    overthetop = 20000

                    bbox = g.bounds

                    if bbox.size.width < -1 * overthetop or bbox.size.width > overthetop:
                        reports[glyphName]['bboxwidth'].addvalue(
                            (0, widthforgraph, heightforgraph))
                    else:
                        reports[glyphName]['bboxwidth'].addvalue(
                            (bbox.size.width, widthforgraph, heightforgraph))

                    if bbox.size.height < -1 * overthetop or bbox.size.height > overthetop:
                        reports[glyphName]['bboxheight'].addvalue(
                            (0, widthforgraph, heightforgraph))
                    else:
                        reports[glyphName]['bboxheight'].addvalue(
                            (bbox.size.height, widthforgraph, heightforgraph))

                    if (bbox.origin.y +
                            bbox.size.height) < -1 * overthetop or (
                                bbox.origin.y + bbox.size.height) > overthetop:
                        reports[glyphName]['highestpoint'].addvalue(
                            (0, widthforgraph, heightforgraph))
                    else:
                        reports[glyphName]['highestpoint'].addvalue(
                            (bbox.origin.y + bbox.size.height, widthforgraph,
                             heightforgraph))

                    if bbox.origin.y < -1 * overthetop or bbox.origin.y > overthetop:
                        reports[glyphName]['lowestpoint'].addvalue(
                            (0, widthforgraph, heightforgraph))
                    else:
                        reports[glyphName]['lowestpoint'].addvalue(
                            (bbox.origin.y, widthforgraph, heightforgraph))

                    # L + R sidebearing
                    reports[glyphName]['leftsidebearing'].addvalue(
                        (g.LSB, widthforgraph, heightforgraph))
                    reports[glyphName]['rightsidebearing'].addvalue(
                        (g.RSB, widthforgraph, heightforgraph))

        # Recalculate drawing boards
        numberoftables = 0
        # GSNotImplemented
        # for table in availablegraphs:
        # 	if eval('myDialog.graph_' + table):
        # 		numberoftables += 1

        if numberoftables < 3:
            numberoftables = 3
        try:
            r = 2.0 / numberoftables
        except:
            r = .8
        SetScrapBoard(r)

        # Calculate ratio
        global ratio
        if Glyphs.intDefaults[
                "com_yanone_Autopsy_PageOrientation"] == Portrait:
            ratio = (scrapboard['top'] - scrapboard['bottom']) / maxheight * mm
            ratio2 = (scrapboard['right'] -
                      scrapboard['left']) / maxsinglewidth * mm
            maxratio = 0.3
            if ratio > maxratio:
                ratio = maxratio
            if ratio > ratio2:
                ratio = ratio2
        else:
            ratio = (scrapboard['right'] - scrapboard['left']) / maxwidth * mm
            ratio2 = (scrapboard['top'] -
                      scrapboard['bottom']) / maxsingleheight * mm
            maxratio = 0.3
            if ratio > maxratio:
                ratio = maxratio
            if ratio > ratio2:
                ratio = ratio2

        # PDF Init stuff
        filename = Glyphs.defaults["com_yanone_Autopsy_filename"]
        tempFileName = NSTemporaryDirectory() + "%d.pdf" % random.randint(
            1000, 100000)

        pageRect = CGRectMake(0, 0, pagewidth, pageheight)

        fileURL = NSURL.fileURLWithPath_(tempFileName)
        pdfContext = CGPDFContextCreateWithURL(fileURL, pageRect, None)
        CGPDFContextBeginPage(pdfContext, None)

        pdfNSGraphicsContext = NSGraphicsContext.graphicsContextWithGraphicsPort_flipped_(
            pdfContext, False)
        NSGraphicsContext.saveGraphicsState()
        NSGraphicsContext.setCurrentContext_(pdfNSGraphicsContext)

        try:

            drawTitlePage(fonts)
            CGPDFContextEndPage(pdfContext)
            ### MAIN PAGES ###

            for i, glyphName in enumerate(glyphNames):
                CGPDFContextBeginPage(pdfContext, None)
                drawGlyph(fonts, glyphName, i, ratio, reports)
                # End page
                CGPDFContextEndPage(pdfContext)

        except:
            print "__Main"
            print traceback.format_exc()

        finally:
            # close PDF
            NSGraphicsContext.restoreGraphicsState()
            CGPDFContextClose(pdfContext)

        output("time: " + str(time.time() - starttime) + "sec, ca." +
               str((time.time() - starttime) / len(glyphNames)) +
               "sec per glyph")

        if errors:
            print "__Errors", errors
            for error in errortexts:
                #print "__Message", error, programname
                dlg = message(error)

        # if not errors and fonts and myDialog.openPDF:
        if not errors and fonts:
            try:
                os.rename(tempFileName, filename)
            except:
                dlg = Message("Error", "Problem copying final pdf")
            if Glyphs.defaults["com_yanone_Autopsy_openPDF"]:
                launchfile(filename)