Beispiel #1
0
 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
Beispiel #2
0
	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
Beispiel #3
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
Beispiel #4
0
 def with_canvas(self, proc):
     NSGraphicsContext.__class__.saveGraphicsState()
     NSGraphicsContext.setCurrentContext_(self._ns_graphics_context)
     try:
         canvas = Canvas()
         proc(canvas)
     finally:
         NSGraphicsContext.__class__.restoreGraphicsState()
Beispiel #5
0
	def with_canvas(self, proc):
		NSGraphicsContext.__class__.saveGraphicsState()
		NSGraphicsContext.setCurrentContext_(self._ns_graphics_context)
		try:
			canvas = Canvas()
			proc(canvas)
		finally:
			NSGraphicsContext.__class__.restoreGraphicsState()
Beispiel #6
0
	def drawForegroundWithOptions_(self, options):
		if self.speedpunklib.getPreference('useFader'):
			visibleRect = self.controller.viewPort
			histOriginX = NSMinX(visibleRect) + 10
			histOriginY = NSMaxY(visibleRect) - 10 - self.histHeight
			NSGraphicsContext.currentContext().saveGraphicsState()
			clippingPath = NSBezierPath.bezierPathWithRoundedRect_cornerRadius_(NSRect((histOriginX, histOriginY), (self.histWidth, self.histHeight)), 5)
			clippingPath.addClip()
			self.speedpunklib.drawGradient(histOriginX, histOriginY, self.histWidth, self.histHeight)
			self.speedpunklib.drawHistogram(histOriginX, histOriginY, self.histWidth, self.histHeight)
			NSGraphicsContext.currentContext().restoreGraphicsState()
Beispiel #7
0
 def erase(self):
     ns = self._ns_path
     self._backcolor._ns_color.set()
     ctx = NSGraphicsContext.currentContext()
     ctx.setCompositingOperation_(NSCompositeCopy)
     ns.fill()
     ctx.setCompositingOperation_(NSCompositeSourceOver)
Beispiel #8
0
def save_graphics_state():
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    try:
        yield context
    finally:
        context.restoreGraphicsState()
Beispiel #9
0
def drawTextAtPoint(text, pt, scale, attributes={}, xAlign="left", yAlign="bottom", flipped=False):
    text = NSAttributedString.alloc().initWithString_attributes_(text, attributes)
    if xAlign != "left" or yAlign != "bottom":
        width, height = text.size()
        width *= scale
        height *= scale
        x, y = pt
        f = 1
        if flipped:
            f = -1
        if xAlign == "center":
            x -= width / 2
        elif xAlign == "right":
            x -= width
        if yAlign == "center":
            y -= height / 2 * f
        elif yAlign == "top":
            y -= height * f
        pt = (x, y)
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(pt[0], pt[1])
    if flipped:
        s = -scale
    else:
        s = scale
    transform.scaleXBy_yBy_(scale, s)
    transform.concat()
    text.drawAtPoint_((0, 0))
    context.restoreGraphicsState()
Beispiel #10
0
 def erase(self):
     ns = self._ns_path
     self._backcolor._ns_color.set()
     ctx = NSGraphicsContext.currentContext()
     ctx.setCompositingOperation_(NSCompositeCopy)
     ns.fill()
     ctx.setCompositingOperation_(NSCompositeSourceOver)
Beispiel #11
0
 def __init__(self):
     self._ns_path = NSBezierPath.bezierPath()
     self._ns_path.setWindingRule_(NSEvenOddWindingRule)
     self._stack = []
     ctx = NSGraphicsContext.currentContext()
     ctx.setCompositingOperation_(NSCompositeSourceOver)
     GCanvas.__init__(self)
     self._printing = not ctx.isDrawingToScreen()
     self.initgraphics()
Beispiel #12
0
 def __init__(self):
     self._ns_path = NSBezierPath.bezierPath()
     self._ns_path.setWindingRule_(NSEvenOddWindingRule)
     self._stack = []
     ctx = NSGraphicsContext.currentContext()
     ctx.setCompositingOperation_(NSCompositeSourceOver)
     GCanvas.__init__(self)
     self._printing = not ctx.isDrawingToScreen()
     self.initgraphics()
Beispiel #13
0
    def draw(self, colorPalette, defaultColor):
        from blackrenderer.backends.coregraphics import CoreGraphicsCanvas

        cgContext = NSGraphicsContext.currentContext().CGContext()
        self.colorFont.drawGlyph(
            self.glyphName,
            CoreGraphicsCanvas(cgContext),
            palette=colorPalette,
            textColor=defaultColor,
        )
Beispiel #14
0
def drawGlyphImage(glyph, scale, rect, backgroundColor=None):
    if glyph.image.fileName is None:
        return
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    aT = NSAffineTransform.transform()
    aT.setTransformStruct_(glyph.image.transformation)
    aT.concat()
    image = glyph.image.getRepresentation("defconAppKit.NSImage")
    image.drawAtPoint_fromRect_operation_fraction_(
        (0, 0), ((0, 0), image.size()), NSCompositeSourceOver, 1.0)
    context.restoreGraphicsState()
Beispiel #15
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
Beispiel #16
0
    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)
Beispiel #17
0
def drawGlyphImage(glyph, scale, rect, backgroundColor=None):
    if glyph.image.fileName is None:
        return
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    aT = NSAffineTransform.transform()
    aT.setTransformStruct_(glyph.image.transformation)
    aT.concat()
    image = glyph.image.getRepresentation("defconAppKit.NSImage")
    image.drawAtPoint_fromRect_operation_fraction_(
        (0, 0), ((0, 0), image.size()), NSCompositeSourceOver, 1.0
    )
    context.restoreGraphicsState()
Beispiel #18
0
    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)
Beispiel #19
0
def drawGlyphAnchors(glyph,
                     scale,
                     rect,
                     drawAnchor=True,
                     drawText=True,
                     color=None,
                     textColor=None,
                     backgroundColor=None,
                     flipped=False):
    if not glyph.anchors:
        return
    if color is None:
        color = getDefaultColor("glyphAnchor")
    fallbackColor = color
    if backgroundColor is None:
        backgroundColor = getDefaultColor("background")
    anchorSize = 5 * scale
    anchorHalfSize = anchorSize / 2
    for anchor in glyph.anchors:
        if anchor.color is not None:
            color = colorToNSColor(anchor.color)
        else:
            color = fallbackColor
        x = anchor.x
        y = anchor.y
        name = anchor.name
        context = NSGraphicsContext.currentContext()
        context.saveGraphicsState()
        #shadow = NSShadow.alloc().init()
        #shadow.setShadowColor_(backgroundColor)
        #shadow.setShadowOffset_((0, 0))
        #shadow.setShadowBlurRadius_(3)
        #shadow.set()
        if drawAnchor:
            r = ((x - anchorHalfSize, y - anchorHalfSize), (anchorSize,
                                                            anchorSize))
            color.set()
            drawFilledOval(r)
        if drawText and name:
            attributes = {
                NSFontAttributeName: NSFont.boldSystemFontOfSize_(12),
                NSForegroundColorAttributeName: textColor,
            }
            y += 25 * scale
            drawTextAtPoint(name, (x, y),
                            scale,
                            attributes,
                            xAlign="center",
                            yAlign="top",
                            flipped=flipped)
        context.restoreGraphicsState()
Beispiel #20
0
 def getImage(self):
     image = NSImage.alloc().initWithSize_((self.width, self.height))
     image.setFlipped_(True)
     image.lockFocus()
     context = NSGraphicsContext.currentContext()
     bodyRect = ((0, 0), (self.width, self.height - self.headerHeight))
     headerRect = ((0, -self.height + self.headerHeight),
                   (self.width, self.headerHeight))
     # draw a background color
     cellBackgroundColor.set()
     NSRectFill(((0, 0), (self.width, self.height)))
     # background
     context.saveGraphicsState()
     bodyTransform = NSAffineTransform.transform()
     bodyTransform.translateXBy_yBy_(0, self.height - self.headerHeight)
     bodyTransform.scaleXBy_yBy_(1.0, -1.0)
     bodyTransform.concat()
     self.drawCellBackground(bodyRect)
     context.restoreGraphicsState()
     # glyph
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(bodyRect)
         self.drawCellVerticalMetrics(bodyRect)
     context.saveGraphicsState()
     NSBezierPath.clipRect_(
         ((0, 0), (self.width, self.height - self.headerHeight)))
     glyphTransform = NSAffineTransform.transform()
     glyphTransform.translateXBy_yBy_(self.xOffset, self.yOffset)
     glyphTransform.scaleBy_(self.scale)
     glyphTransform.concat()
     self.drawCellGlyph()
     context.restoreGraphicsState()
     # foreground
     context.saveGraphicsState()
     bodyTransform.concat()
     self.drawCellForeground(bodyRect)
     context.restoreGraphicsState()
     # header
     if self.shouldDrawHeader:
         context.saveGraphicsState()
         headerTransform = NSAffineTransform.transform()
         headerTransform.translateXBy_yBy_(0, self.headerHeight)
         headerTransform.scaleXBy_yBy_(1.0, -1.0)
         headerTransform.concat()
         self.drawCellHeaderBackground(headerRect)
         self.drawCellHeaderText(headerRect)
         context.restoreGraphicsState()
     # done
     image.unlockFocus()
     return image
    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)
Beispiel #22
0
 def background(self, layer):
     self.layer = layer
     # draw pixels
     if self.data is None:
         return
     NSGraphicsContext.saveGraphicsState()
     NSGraphicsContext.currentContext().setImageInterpolation_(
         NSImageInterpolationNone)
     self.data.drawInRect_(self.rect)
     NSGraphicsContext.restoreGraphicsState()
 def getImage(self):
     image = NSImage.alloc().initWithSize_((self.width, self.height))
     image.setFlipped_(True)
     image.lockFocus()
     context = NSGraphicsContext.currentContext()
     bodyRect = ((0, 0), (self.width, self.height - self.headerHeight))
     headerRect = ((0, -self.height + self.headerHeight), (self.width, self.headerHeight))
     # draw a background color
     cellBackgroundColor.set()
     NSRectFill(((0, 0), (self.width, self.height)))
     # background
     context.saveGraphicsState()
     bodyTransform = NSAffineTransform.transform()
     bodyTransform.translateXBy_yBy_(0, self.height - self.headerHeight)
     bodyTransform.scaleXBy_yBy_(1.0, -1.0)
     bodyTransform.concat()
     self.drawCellBackground(bodyRect)
     context.restoreGraphicsState()
     # glyph
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(bodyRect)
         self.drawCellVerticalMetrics(bodyRect)
     context.saveGraphicsState()
     NSBezierPath.clipRect_(((0, 0), (self.width, self.height - self.headerHeight)))
     glyphTransform = NSAffineTransform.transform()
     glyphTransform.translateXBy_yBy_(self.xOffset, self.yOffset)
     glyphTransform.scaleBy_(self.scale)
     glyphTransform.concat()
     self.drawCellGlyph()
     context.restoreGraphicsState()
     # foreground
     context.saveGraphicsState()
     bodyTransform.concat()
     self.drawCellForeground(bodyRect)
     context.restoreGraphicsState()
     # header
     if self.shouldDrawHeader:
         context.saveGraphicsState()
         headerTransform = NSAffineTransform.transform()
         headerTransform.translateXBy_yBy_(0, self.headerHeight)
         headerTransform.scaleXBy_yBy_(1.0, -1.0)
         headerTransform.concat()
         self.drawCellHeaderBackground(headerRect)
         self.drawCellHeaderText(headerRect)
         context.restoreGraphicsState()
     # done
     image.unlockFocus()
     return image
Beispiel #24
0
def drawLine(xy1, xy2, lineWidth=1.0):
    x1, y1 = xy1
    x2, y2 = xy2
    turnOffAntiAliasing = False
    if x1 == x2 or y1 == y2:
        turnOffAntiAliasing = True
    if turnOffAntiAliasing:
        context = NSGraphicsContext.currentContext()
        context.setShouldAntialias_(False)
    path = NSBezierPath.bezierPath()
    path.moveToPoint_((x1, y1))
    path.lineToPoint_((x2, y2))
    if turnOffAntiAliasing and lineWidth == 1.0:
        lineWidth = 0.001
    path.setLineWidth_(lineWidth)
    path.stroke()
    if turnOffAntiAliasing:
        context.setShouldAntialias_(True)
Beispiel #25
0
def drawLine(xy1, xy2, lineWidth=1.0):
    x1, y1 = xy1
    x2, y2 = xy2
    turnOffAntiAliasing = False
    if x1 == x2 or y1 == y2:
        turnOffAntiAliasing = True
    if turnOffAntiAliasing:
        context = NSGraphicsContext.currentContext()
        context.setShouldAntialias_(False)
    path = NSBezierPath.bezierPath()
    path.moveToPoint_((x1, y1))
    path.lineToPoint_((x2, y2))
    if turnOffAntiAliasing and lineWidth == 1.0:
        lineWidth = 0.001
    path.setLineWidth_(lineWidth)
    path.stroke()
    if turnOffAntiAliasing:
        context.setShouldAntialias_(True)
Beispiel #26
0
    def background(self, layer):

        # Check if the drawing should be shown

        currentController = self.controller.view().window().windowController()
        if currentController:
            tool = currentController.toolDrawDelegate()
            if tool.isKindOfClass_(NSClassFromString("GlyphsToolText")) \
                    or tool.isKindOfClass_(NSClassFromString("GlyphsToolHand")) \
                    or tool.isKindOfClass_(NSClassFromString("ScrawlTool")):
                return

        # draw pixels

        data = layer.userData["%s.data" % plugin_id]
        if data is None:
            return
        try:
            data = NSImage.alloc().initWithData_(data)
        except:
            print("Error in image data of layer %s" % layer)
            return

        rect = layer.userData["%s.rect" % plugin_id]
        if rect is None:
            # The drawing rect was not stored in user data.
            # Deduce it from the layer/font metrics.
            font = layer.parent.parent
            pad = int(round(font.upm / 10))

            # find master for image positioning (descender)

            try:
                descender = layer.parent.parent.masters[
                    layer.layerId].descender
            except KeyError:
                descender = int(round(font.upm / 5))

            rect = NSMakeRect(-pad, descender - pad, 2 * pad + layer.width,
                              2 * pad + font.upm)
        else:
            # Use the rect from user data
            rect = NSMakeRect(*rect)
        NSGraphicsContext.saveGraphicsState()
        NSGraphicsContext.currentContext().setImageInterpolation_(
            NSImageInterpolationNone)
        if len(layer.paths) == 0:
            data.drawInRect_(rect)
        else:
            data.drawInRect_fromRect_operation_fraction_(
                rect, NSZeroRect, NSCompositeSourceOver, 0.2)
        NSGraphicsContext.restoreGraphicsState()
Beispiel #27
0
def NSImageFactory(image):
    font = image.font
    if font is None:
        return
    layer = image.layer
    images = font.images
    if image.fileName not in images:
        return None
    imageColor = image.color
    if imageColor is None:
        imageColor = layer.color
    data = images[image.fileName]
    data = NSData.dataWithBytes_length_(data, len(data))
    if imageColor is None:
        return NSImage.alloc().initWithData_(data)
    # make the input image
    inputImage = CIImage.imageWithData_(data)
    # make a color filter
    r, g, b, a = imageColor
    color0 = CIColor.colorWithRed_green_blue_(r, g, b)
    color1 = CIColor.colorWithRed_green_blue_(1, 1, 1)
    falseColorFilter = CIFilter.filterWithName_("CIFalseColor")
    falseColorFilter.setValue_forKey_(inputImage, "inputImage")
    falseColorFilter.setValue_forKey_(color0, "inputColor0")
    falseColorFilter.setValue_forKey_(color1, "inputColor1")
    # get the result
    ciImage = falseColorFilter.valueForKey_("outputImage")
    # make an NSImage
    nsImage = NSImage.alloc().initWithSize_(ciImage.extent().size)
    nsImage.lockFocus()
    context = NSGraphicsContext.currentContext().CIContext()
    context.drawImage_atPoint_fromRect_(ciImage, (0, 0), ciImage.extent())
    nsImage.unlockFocus()
    # apply the alpha
    finalImage = NSImage.alloc().initWithSize_(nsImage.size())
    finalImage.lockFocus()
    nsImage.drawAtPoint_fromRect_operation_fraction_(
        (0, 0), ((0, 0), nsImage.size()), NSCompositeSourceOver, a
    )
    finalImage.unlockFocus()
    return finalImage
Beispiel #28
0
def dt_bitmap2d_from_ci_image(ci_image, width, height, grid):
    """
    :param ci_image: a :class:`Quartz.CIImage` instance from PyObjC
    :param width: desired width in pixels
    :param height: desired height in pixels
    :param grid: a four-tuple (x0, y0, dx, dy) spatial grid
    
    :returns: a :class:`datatank_py.DTBitmap2D.DTBitmap2D` instance
    
    **Requires Mac OS X and PyObjC**

    This function allows you to turn a :class:`Quartz.CIImage` into an object
    that DataTank can use. Only 8-bit RGB images are supported at this time.
    
    """
    
    from datatank_py.DTBitmap2D import DTBitmap2D
    from Quartz import CGRectMake, CGPointZero
    from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext
    
    # No matter what, I can't get NSBitmapImageRep to create a rep from planar data or
    # a passed-in buffer, so I have to let it manage the buffer.  Constraining row bytes
    # seems to work properly, so at least I don't have to deal with that.  I really think
    # PyObjC is buggy here as well.
    
    image_rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 4 * width, 32)
    
    ns_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(image_rep)
    ns_context.CIContext().drawImage_atPoint_fromRect_(ci_image, CGPointZero, CGRectMake(0, 0, width, height))
    ns_context.flushGraphics()
    
    (red, green, blue, alpha) = __bitmap_planes_from_imagerep(image_rep)
    dt_bitmap = DTBitmap2D()
    dt_bitmap.red = red
    dt_bitmap.green = green
    dt_bitmap.blue = blue
    dt_bitmap.grid = grid
    
    return dt_bitmap
Beispiel #29
0
def drawTextAtPoint(text,
                    pt,
                    scale,
                    attributes={},
                    xAlign="left",
                    yAlign="bottom",
                    flipped=False):
    text = NSAttributedString.alloc().initWithString_attributes_(
        text, attributes)
    if xAlign != "left" or yAlign != "bottom":
        width, height = text.size()
        width *= scale
        height *= scale
        x, y = pt
        f = 1
        if flipped:
            f = -1
        if xAlign == "center":
            x -= width / 2
        elif xAlign == "right":
            x -= width
        if yAlign == "center":
            y -= height / 2 * f
        elif yAlign == "top":
            y -= height * f
        pt = (x, y)
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(pt[0], pt[1])
    if flipped:
        s = -scale
    else:
        s = scale
    transform.scaleXBy_yBy_(scale, s)
    transform.concat()
    text.drawAtPoint_((0, 0))
    context.restoreGraphicsState()
Beispiel #30
0
def drawGlyphAnchors(glyph, scale, rect, drawAnchor=True, drawText=True, color=None, backgroundColor=None, flipped=False):
    if not glyph.anchors:
        return
    if color is None:
        color = getDefaultColor("glyphAnchor")
    fallbackColor = color
    if backgroundColor is None:
        backgroundColor = getDefaultColor("background")
    anchorSize = 5 * scale
    anchorHalfSize = anchorSize / 2
    for anchor in glyph.anchors:
        if anchor.color is not None:
            color = colorToNSColor(anchor.color)
        else:
            color = fallbackColor
        x = anchor.x
        y = anchor.y
        name = anchor.name
        context = NSGraphicsContext.currentContext()
        context.saveGraphicsState()
        shadow = NSShadow.alloc().init()
        shadow.setShadowColor_(backgroundColor)
        shadow.setShadowOffset_((0, 0))
        shadow.setShadowBlurRadius_(3)
        shadow.set()
        if drawAnchor:
            r = ((x - anchorHalfSize, y - anchorHalfSize), (anchorSize, anchorSize))
            color.set()
            drawFilledOval(r)
        if drawText and name:
            attributes = {
                NSFontAttributeName: NSFont.systemFontOfSize_(9),
                NSForegroundColorAttributeName: color,
            }
            y -= 2 * scale
            drawTextAtPoint(name, (x, y), scale, attributes, xAlign="center", yAlign="top", flipped=flipped)
        context.restoreGraphicsState()
Beispiel #31
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
Beispiel #32
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)
Beispiel #33
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
Beispiel #34
0
 def drawRect_(self, rect):
     cictx = NSGraphicsContext.currentContext().CIContext()
     cictx.drawImage_atPoint_fromRect_(self.outputGradient1, (0, self.BASE_HEIGHT), NSRect((0, 0), (self.WIDTH, self.BASE_HEIGHT * 4)))
     cictx.drawImage_atPoint_fromRect_(self.outputGradient2, (0, 0), NSRect((0, 0), (self.WIDTH, self.BASE_HEIGHT)))
     super(_SickView, self).drawRect_(rect)
Beispiel #35
0
    NSRectFillUsingOperation(rect, NSCompositeSourceOver)
    context.setShouldAntialias_(True)


def drawFilledOval(rect):
    path = NSBezierPath.bezierPath()
    path.appendBezierPathWithOvalInRect_(rect)
    path.fill()


def drawLine((x1, y1), (x2, y2), lineWidth=1.0):
    turnOffAntiAliasing = False
    if x1 == x2 or y1 == y2:
        turnOffAntiAliasing = True
    if turnOffAntiAliasing:
        context = NSGraphicsContext.currentContext()
        context.setShouldAntialias_(False)
    path = NSBezierPath.bezierPath()
    path.moveToPoint_((x1, y1))
    path.lineToPoint_((x2, y2))
    if turnOffAntiAliasing and lineWidth == 1.0:
        lineWidth = 0.001
    path.setLineWidth_(lineWidth)
    path.stroke()
    if turnOffAntiAliasing:
        context.setShouldAntialias_(True)


def drawTextAtPoint(text, pt, scale, attributes={}, xAlign="left", yAlign="bottom", flipped=False):
    text = NSAttributedString.alloc().initWithString_attributes_(text, attributes)
    if xAlign != "left" or yAlign != "bottom":
Beispiel #36
0
 def __enter__(self):
     NSGraphicsContext.saveGraphicsState()
 def drawRectRightToLeft_(self, rect):
     self._alternateRects = {}
     # draw the background
     bounds = self.bounds()
     self._backgroundColor.set()
     NSRectFill(bounds)
     # create some reusable values
     scale = self._scale
     descender = self._descender
     upm = self._upm
     scrollWidth = bounds.size[0]
     # offset for the buffer
     ctx = NSGraphicsContext.currentContext()
     ctx.saveGraphicsState()
     aT = NSAffineTransform.transform()
     aT.translateXBy_yBy_(scrollWidth - self._bufferLeft, self._bufferTop)
     aT.concat()
     # offset for the descender
     aT = NSAffineTransform.transform()
     aT.scaleBy_(scale)
     aT.translateXBy_yBy_(0, descender)
     aT.concat()
     # flip
     flipTransform = NSAffineTransform.transform()
     flipTransform.translateXBy_yBy_(0, upm)
     flipTransform.scaleXBy_yBy_(1.0, -1.0)
     flipTransform.concat()
     # set the glyph color
     self._glyphColor.set()
     # draw the records
     left = scrollWidth - self._bufferLeft
     bottom = self._bufferTop
     height = upm * scale
     previousXA = 0
     for recordIndex, glyphRecord in enumerate(reversed(self._glyphRecords)):
         glyph = glyphRecord.glyph
         w = glyphRecord.advanceWidth
         h = glyphRecord.advanceHeight
         xP = glyphRecord.xPlacement
         yP = glyphRecord.yPlacement
         xA = glyphRecord.xAdvance
         yA = glyphRecord.yAdvance
         # handle offsets from the record
         bottom += yP * scale
         glyphHeight = height + ((h + yA) * scale)
         glyphLeft = left + ((-w + xP - xA) * scale)
         glyphWidth = (-w - xA) * scale
         # store the glyph rect for the alternate menu
         rect = ((glyphLeft, bottom), (glyphWidth, glyphHeight))
         self._alternateRects[rect] = recordIndex
         self._currentZeroZeroPoint = NSPoint(glyphLeft, bottom + height + (descender * scale))
         # handle the placement
         aT = NSAffineTransform.transform()
         if xP:
             xP += previousXA
         aT.translateXBy_yBy_(-w - xA + xP, yP)
         aT.concat()
         # draw the glyph
         rect = ((-w + xA - xP, descender - yP), (w, upm))
         self.drawGlyph(glyph, rect, alternate=bool(glyphRecord.alternates))
         # shift for the next glyph
         aT = NSAffineTransform.transform()
         aT.translateXBy_yBy_(-xP, h + yA - yP)
         aT.concat()
         left += (-w - xP - xA) * scale
         previousXA = xA
     ctx.restoreGraphicsState()
Beispiel #38
0
 def grestore(self):
     (self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
         self._pensize, self._font) = self._stack.pop()
     self.transformstack.pop()
     NSGraphicsContext.currentContext().restoreGraphicsState()
Beispiel #39
0
 def gsave(self):
     self._stack.append((self._pencolor, self._fillcolor, self._textcolor,
                         self._backcolor, self._pensize, self._font))
     NSGraphicsContext.currentContext().saveGraphicsState()
Beispiel #40
0
 def drawRect_(self, rect):
     super(BackgroundView, self).drawRect_(rect)
     NSGraphicsContext.currentContext().CIContext().drawImage_atPoint_fromRect_(self.outputGradient2, (0, 0), NSRect((0, 0), (WIDTH, BASE_HEIGHT)))
Beispiel #41
0
 def __exit__(self, exc_type, exc_value, exc_tb):
     NSGraphicsContext.restoreGraphicsState()
     return False
Beispiel #42
0
def restore():
	# restore the current graphic state 
	NSGraphicsContext.currentContext().restoreGraphicsState()
 def drawRect_(self, dirtyRect):
   context = NSGraphicsContext.currentContext().CGContext()
   Quartz.CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0)
   Quartz.CGContextFillRect(context, dirtyRect)
Beispiel #44
0
 def drawRectRightToLeft_(self, rect):
     self._alternateRects = {}
     # draw the background
     bounds = self.bounds()
     self._backgroundColor.set()
     NSRectFill(bounds)
     # create some reusable values
     scale = self._scale
     descender = self._descender
     upm = self._upm
     scrollWidth = bounds.size[0]
     # offset for the buffer
     ctx = NSGraphicsContext.currentContext()
     ctx.saveGraphicsState()
     aT = NSAffineTransform.transform()
     aT.translateXBy_yBy_(scrollWidth - self._bufferLeft, self._bufferTop)
     aT.concat()
     # offset for the descender
     aT = NSAffineTransform.transform()
     aT.scaleBy_(scale)
     aT.translateXBy_yBy_(0, descender)
     aT.concat()
     # flip
     flipTransform = NSAffineTransform.transform()
     flipTransform.translateXBy_yBy_(0, upm)
     flipTransform.scaleXBy_yBy_(1.0, -1.0)
     flipTransform.concat()
     # set the glyph color
     self._glyphColor.set()
     # draw the records
     left = scrollWidth - self._bufferLeft
     bottom = self._bufferTop
     height = upm * scale
     previousXA = 0
     for recordIndex, glyphRecord in enumerate(reversed(
             self._glyphRecords)):
         glyph = glyphRecord.glyph
         w = glyphRecord.advanceWidth
         h = glyphRecord.advanceHeight
         xP = glyphRecord.xPlacement
         yP = glyphRecord.yPlacement
         xA = glyphRecord.xAdvance
         yA = glyphRecord.yAdvance
         # handle offsets from the record
         bottom += yP * scale
         glyphHeight = height + ((h + yA) * scale)
         glyphLeft = left + ((-w + xP - xA) * scale)
         glyphWidth = (-w - xA) * scale
         # store the glyph rect for the alternate menu
         rect = ((glyphLeft, bottom), (glyphWidth, glyphHeight))
         self._alternateRects[rect] = recordIndex
         self._currentZeroZeroPoint = NSPoint(
             glyphLeft, bottom + height + (descender * scale))
         # handle the placement
         aT = NSAffineTransform.transform()
         if xP:
             xP += previousXA
         aT.translateXBy_yBy_(-w - xA + xP, yP)
         aT.concat()
         # draw the glyph
         rect = ((-w + xA - xP, descender - yP), (w, upm))
         self.drawGlyph(glyph, rect, alternate=bool(glyphRecord.alternates))
         # shift for the next glyph
         aT = NSAffineTransform.transform()
         aT.translateXBy_yBy_(-xP, h + yA - yP)
         aT.concat()
         left += (-w - xP - xA) * scale
         previousXA = xA
     ctx.restoreGraphicsState()
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)
Beispiel #46
0
def drawFilledRect(rect):
    context = NSGraphicsContext.currentContext()
    context.setShouldAntialias_(False)
    NSRectFillUsingOperation(rect, NSCompositeSourceOver)
    context.setShouldAntialias_(True)
def GlyphCellDetailFactory(glyph):
    font = glyph.font

    imageWidth = 200
    imageHeight = 280

    scale = 120 / font.info.unitsPerEm
    glyphLeftOffset = (imageWidth - (glyph.width * scale)) / 2

    basePath = roundedRectBezierPath(((.5, .5), (imageWidth - 1, imageHeight - 1)), 7)
    basePath.setLineWidth_(1.0)

    glyphPath = glyph.getRepresentation("defconAppKit.NSBezierPath")

    line1Path = NSBezierPath.bezierPath()
    line1Path.moveToPoint_((1, 120.5))
    line1Path.lineToPoint_((imageWidth - 1, 120.5))
    line1Path.setLineWidth_(1.0)

    line2Path = NSBezierPath.bezierPath()
    line2Path.moveToPoint_((1, 121.5))
    line2Path.lineToPoint_((imageWidth - 1, 121.5))
    line2Path.setLineWidth_(1.0)

    lineColor = NSColor.colorWithCalibratedWhite_alpha_(.5, 1.0)

    paragraph = NSMutableParagraphStyle.alloc().init()
    paragraph.setAlignment_(NSRightTextAlignment)
    paragraph.setLineBreakMode_(NSLineBreakByCharWrapping)
    leftAttributes = {
        NSFontAttributeName: NSFont.systemFontOfSize_(12.0),
        NSForegroundColorAttributeName: NSColor.whiteColor(),
        NSParagraphStyleAttributeName: paragraph
    }

    paragraph = NSMutableParagraphStyle.alloc().init()
    paragraph.setAlignment_(NSLeftTextAlignment)
    paragraph.setLineBreakMode_(NSLineBreakByTruncatingMiddle)
    rightAttributes = {
        NSFontAttributeName: NSFont.systemFontOfSize_(12.0),
        NSForegroundColorAttributeName: NSColor.whiteColor(),
        NSParagraphStyleAttributeName: paragraph
    }

    nameTitle = NSAttributedString.alloc().initWithString_attributes_("Name", leftAttributes)
    nameText = NSAttributedString.alloc().initWithString_attributes_(glyph.name, rightAttributes)

    uniTitle = NSAttributedString.alloc().initWithString_attributes_("Unicode", leftAttributes)
    uni = glyph.unicode
    if uni is None:
        uni = ""
    else:
        uni = hex(uni)[2:].upper()
        if len(uni) < 4:
            uni = uni.zfill(4)
    uniText = NSAttributedString.alloc().initWithString_attributes_(str(uni), rightAttributes)

    widthTitle = NSAttributedString.alloc().initWithString_attributes_("Width", leftAttributes)
    width = glyph.width
    if width is None:
        width = 0
    width = round(width, 3)
    if width == int(width):
        width = int(width)
    widthText = NSAttributedString.alloc().initWithString_attributes_(str(width), rightAttributes)

    leftTitle = NSAttributedString.alloc().initWithString_attributes_("Left Margin", leftAttributes)
    leftMargin = glyph.leftMargin
    if leftMargin is None:
        leftMargin = 0
    leftMargin = round(leftMargin, 3)
    if leftMargin == int(leftMargin):
        leftMargin = int(leftMargin)
    leftText = NSAttributedString.alloc().initWithString_attributes_(str(leftMargin), rightAttributes)

    rightTitle = NSAttributedString.alloc().initWithString_attributes_("Right Margin", leftAttributes)
    rightMargin = glyph.rightMargin
    if rightMargin is None:
        rightMargin = 0
    rightMargin = round(rightMargin, 3)
    if rightMargin == int(rightMargin):
        rightMargin = int(rightMargin)
    rightText = NSAttributedString.alloc().initWithString_attributes_(str(rightMargin), rightAttributes)

    image = NSImage.alloc().initWithSize_((imageWidth, imageHeight))
    image.setFlipped_(True)
    image.lockFocus()

    NSColor.colorWithCalibratedWhite_alpha_(0, .65).set()
    basePath.fill()
    lineColor.set()
    basePath.stroke()

    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(glyphLeftOffset, 145)
    transform.scaleBy_(scale)
    transform.translateXBy_yBy_(0, -font.info.descender)
    transform.concat()

    NSColor.whiteColor().set()
    glyphPath.fill()
    context.restoreGraphicsState()

    lineColor.set()
    line1Path.stroke()
    NSColor.colorWithCalibratedWhite_alpha_(0, .5).set()
    line2Path.stroke()

    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(0, 110)
    transform.scaleXBy_yBy_(1.0, -1.0)
    transform.concat()

    nameTitle.drawInRect_(((0, 0), (90, 17)))
    nameText.drawInRect_(((95, 0), (85, 17)))

    uniTitle.drawInRect_(((0, 20), (90, 17)))
    uniText.drawInRect_(((95, 20), (85, 17)))

    widthTitle.drawInRect_(((0, 40), (90, 17)))
    widthText.drawInRect_(((95, 40), (85, 17)))

    leftTitle.drawInRect_(((0, 60), (90, 17)))
    leftText.drawInRect_(((95, 60), (85, 17)))

    rightTitle.drawInRect_(((0, 80), (90, 17)))
    rightText.drawInRect_(((95, 80), (85, 17)))

    image.unlockFocus()
    return image
Beispiel #48
0
 def __exit__(self, exc_type, exc_value, exc_tb):
     NSGraphicsContext.restoreGraphicsState()
     return False
Beispiel #49
0
 def __enter__(self):
     NSGraphicsContext.saveGraphicsState()
Beispiel #50
0
def save():
	# save the current graphic state 
	NSGraphicsContext.currentContext().saveGraphicsState()
Beispiel #51
0
def restore():
    # restore the current graphic state
    NSGraphicsContext.currentContext().restoreGraphicsState()
Beispiel #52
0
def save():
    # save the current graphic state
    NSGraphicsContext.currentContext().saveGraphicsState()
Beispiel #53
0
def drawFilledRect(rect):
    context = NSGraphicsContext.currentContext()
    context.setShouldAntialias_(False)
    NSRectFillUsingOperation(rect, NSCompositeSourceOver)
    context.setShouldAntialias_(True)
Beispiel #54
0
 def grestore(self):
     (self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
      self._pensize, self._font) = self._stack.pop()
     NSGraphicsContext.currentContext().restoreGraphicsState()
Beispiel #55
0
 def gsave(self):
     self._stack.append((
         self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
         self._pensize, self._font))
     self.transformstack.append([])
     NSGraphicsContext.currentContext().saveGraphicsState()
Beispiel #56
0
 def drawRect_(self, rect):
     NSColor.whiteColor().set()
     NSBezierPath.bezierPathWithRect_(NSRect((0, 0), self.frame().size)).fill()
     NSGraphicsContext.currentContext().CIContext().drawImage_atPoint_fromRect_(self._filter.valueForKey_('outputImage'), (0, 0), self.image.extent())
Beispiel #57
0
def addCountBadgeToIcon(count, iconImage=None):
    if iconImage is None:
        iconImage = NSImage.alloc().initWithSize_((40, 40))
        iconImage.lockFocus()
        NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 1, .5).set()
        path = NSBezierPath.bezierPath()
        path.appendBezierPathWithOvalInRect_(((0, 0), iconImage.size()))
        path.fill()
        iconImage.unlockFocus()

    # badge text
    textShadow = NSShadow.alloc().init()
    textShadow.setShadowOffset_((2, -2))
    textShadow.setShadowColor_(
        NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 1.0))
    textShadow.setShadowBlurRadius_(2.0)

    paragraph = NSMutableParagraphStyle.alloc().init()
    paragraph.setAlignment_(NSCenterTextAlignment)
    paragraph.setLineBreakMode_(NSLineBreakByCharWrapping)
    attributes = {
        NSFontAttributeName: NSFont.boldSystemFontOfSize_(12.0),
        NSForegroundColorAttributeName: NSColor.whiteColor(),
        NSParagraphStyleAttributeName: paragraph,
        NSShadowAttributeName: textShadow
    }
    text = NSAttributedString.alloc().initWithString_attributes_(
        str(count), attributes)
    rectWidth, rectHeight = NSString.stringWithString_(
        str(count)).sizeWithAttributes_(attributes)
    rectWidth = int(round(rectWidth + 8))
    rectHeight = int(round(rectHeight + 4))
    rectLeft = 0
    rectBottom = 0

    # badge shadow
    badgeShadow = NSShadow.alloc().init()
    badgeShadow.setShadowOffset_((0, -2))
    badgeShadow.setShadowColor_(NSColor.blackColor())
    badgeShadow.setShadowBlurRadius_(4.0)

    # badge path
    badgePath = roundedRectBezierPath(
        ((rectLeft, rectBottom), (rectWidth, rectHeight)), 3)

    # badge image
    badgeWidth = rectWidth + 3
    badgeHeight = rectHeight + 3
    badgeImage = NSImage.alloc().initWithSize_((badgeWidth, badgeHeight))
    badgeImage.lockFocus()
    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(1.5, 1.5)
    transform.concat()
    NSColor.colorWithCalibratedRed_green_blue_alpha_(.2, .2, .25, 1.0).set()
    badgePath.fill()
    NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, .8, .9, 1.0).set()
    badgePath.setLineWidth_(1.0)
    badgePath.stroke()
    text.drawInRect_(((0, -1), (rectWidth, rectHeight)))
    badgeImage.unlockFocus()

    # make the composite image
    imageWidth, imageHeight = iconImage.size()
    imageWidth += (badgeWidth - 15)
    imageHeight += 10

    badgeLeft = imageWidth - badgeWidth - 3
    badgeBottom = 3

    image = NSImage.alloc().initWithSize_((imageWidth, imageHeight))
    image.lockFocus()
    context = NSGraphicsContext.currentContext()

    # icon
    iconImage.drawAtPoint_fromRect_operation_fraction_(
        (0, 10), ((0, 0), iconImage.size()), NSCompositeSourceOver, 1.0)

    # badge
    context.saveGraphicsState()
    badgeShadow.set()
    badgeImage.drawAtPoint_fromRect_operation_fraction_(
        (badgeLeft, badgeBottom), ((0, 0), badgeImage.size()),
        NSCompositeSourceOver, 1.0)
    context.restoreGraphicsState()

    # done
    image.unlockFocus()
    return image