示例#1
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
示例#2
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()
示例#3
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()
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)
示例#5
0
 def __exit__(self, exc_type, exc_value, exc_tb):
     NSGraphicsContext.restoreGraphicsState()
     return False
示例#6
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)
示例#7
0
 def __exit__(self, exc_type, exc_value, exc_tb):
     NSGraphicsContext.restoreGraphicsState()
     return False