def drawWithFrame_inView_(self, frame, view): row = view.selectedRow() columnCount = len(view.tableColumns()) frames = [ view.frameOfCellAtColumn_row_(i, row) for i in range(columnCount) ] selected = frame in frames (x, y), (w, h) = frame y += 1 h -= 2 if selected: pillTextAttributes[NSForegroundColorAttributeName] = self._color foregroundColor = NSColor.whiteColor() else: pillTextAttributes[ NSForegroundColorAttributeName] = NSColor.whiteColor() foregroundColor = self._color text = self.title() text = NSAttributedString.alloc().initWithString_attributes_( text, pillTextAttributes) textRect = text.boundingRectWithSize_options_((w, h), 0) (textX, textY), (textW, textH) = textRect foregroundColor.set() path = NSBezierPath.bezierPath() radius = h / 2.0 path.appendBezierPathWithOvalInRect_(((x, y), (h, h))) path.appendBezierPathWithOvalInRect_(((x + textW - 1, y), (h, h))) path.appendBezierPathWithRect_(((x + radius, y), (textW - 1, h))) path.fill() text.drawInRect_(((x + radius, y), (textW, textH)))
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
def drawWithFrame_inView_(self, frame, view): row = view.selectedRow() columnCount = len(view.tableColumns()) frames = [view.frameOfCellAtColumn_row_(i, row) for i in xrange(columnCount)] selected = frame in frames (x, y), (w, h) = frame y += 1 h -= 2 if selected: pillTextAttributes[NSForegroundColorAttributeName] = self._color foregroundColor = NSColor.whiteColor() else: pillTextAttributes[NSForegroundColorAttributeName] = NSColor.whiteColor() foregroundColor = self._color text = self.title() text = NSAttributedString.alloc().initWithString_attributes_(text, pillTextAttributes) textRect = text.boundingRectWithSize_options_((w, h), 0) (textX, textY), (textW, textH) = textRect foregroundColor.set() path = NSBezierPath.bezierPath() radius = h / 2.0 path.appendBezierPathWithOvalInRect_(((x, y), (h, h))) path.appendBezierPathWithOvalInRect_(((x + textW - 1, y), (h, h))) path.appendBezierPathWithRect_(((x + radius, y), (textW - 1, h))) path.fill() text.drawInRect_(((x + radius, y), (textW, textH)))
def drawRect_(self, rect): NSColor.whiteColor().set() NSRectFill(self.bounds()) origin = (self.center[0] - self.radius, self.center[1] - self.radius) size = (2 * self.radius, 2 * self.radius) dotRect = (origin, size) self.color.set() NSBezierPath.bezierPathWithOvalInRect_(dotRect).fill()
def drawRect_(self, rect): super(PictureView, self).drawRect_(rect) pos = self.dropboxViewFinalPosition.origin size = self.dropboxViewFinalPosition.size a = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(NSRect((pos[0] - 3, pos[1] - 3), (size[0] + 6, size[1] + 6)), 5.0, 5.0) a.setLineWidth_(2) NSColor.whiteColor().set() a.fill()
def drawRect_(self, rect): NSColor.whiteColor().set() NSRectFill(self.bounds()) origin = (self.center[0]-self.radius, self.center[1]-self.radius) size = (2 * self.radius, 2 * self.radius) dotRect = (origin, size) self.color.set() NSBezierPath.bezierPathWithOvalInRect_(dotRect).fill()
def drawRect_(self, rect): printB("drawRect", rect ) """.""" NSColor.whiteColor().set() NSBezierPath.fillRect_(rect) self.itemColor().set() NSBezierPath.fillRect_(self.calculatedItemBounds())
def drawRect_(self, rect): NSColor.whiteColor().set() NSBezierPath.fillRect_(rect) if Glyphs.font is None: return if not Glyphs.font.selectedLayers: return glyphToRotate = None try: glyphToRotate = Glyphs.font.selectedLayers[0] except: print(traceback.format_exc()) if glyphToRotate is None: return try: previewPath = glyphToRotate.completeBezierPath rotationFactor = self.wrapper._rotationFactor Width = NSWidth(self.frame()) Height = NSHeight(self.frame()) scaleFactor = 0.666666 / (glyphToRotate.parent.parent.upm / min(Width, Height)) ## scaling and zeroing the glyph #------------------------ transform = NSAffineTransform.transform() transform.scaleBy_(scaleFactor) bounds = glyphToRotate.bounds transform.translateXBy_yBy_(-NSMidX(bounds), -NSMidY(bounds)) previewPath.transformUsingAffineTransform_(transform) ## rotation #------------------------ transform = NSAffineTransform.transform() transform.rotateByDegrees_(rotationFactor) previewPath.transformUsingAffineTransform_(transform) ## positioning to the middle of the viewport #------------------------ transform = NSAffineTransform.transform() transform.translateXBy_yBy_(Width / 2, Height / 2 - 8) previewPath.transformUsingAffineTransform_(transform) ## fill path #------------------------ NSColor.blackColor().set() previewPath.fill() except: print(traceback.format_exc())
def drawRect_(self, rect): if not self.border: return super(ThumbnailBoxView, self).drawRect_(rect) with save_graphics_state(): self._shadow.set() NSColor.whiteColor().set() NSBezierPath.bezierPathWithRect_(NSInsetRect(rect, self.BORDER_INSET, self.BORDER_INSET)).fill() size = self.image().size() self.image().drawInRect_fromRect_operation_fraction_(NSInsetRect(rect, self.IMAGE_INSET, self.IMAGE_INSET), NSMakeRect(*rect_to_centered_square(size.width, size.height)), NSCompositeSourceOver, 1.0)
def drawRect_(self, rect): frame = self.frame() NSColor.whiteColor().set() NSRectFill(frame) try: if self._glyph is not None: if self._glyph.__class__.__name__ in ("NSKVONotifying_GSLayer", "GSLayer"): layer = self._glyph elif isinstance(self._glyph, RGlyph): layer = self._glyph._layer if layer: layer.drawInFrame_(frame) except: print traceback.format_exc()
def drawRect_(self, rect): frame = self.frame() NSColor.whiteColor().set() NSRectFill(frame) try: if self._glyph is not None: if self._glyph.__class__.__name__ in ("NSKVONotifying_GSLayer", "GSLayer"): layer = self._glyph elif isinstance(self._glyph, RGlyph): layer = self._glyph._layer if layer: layer.drawInFrame_(frame) except: print(traceback.format_exc())
def drawIndexOfElements(self, d, glyph, view): x, y = glyph[0].points[0].x, glyph[0].points[0].y view._drawTextAtPoint(str(d), attributes, (x, y), drawBackground=True, backgroundColor=red, backgroundStrokeColor=NSColor.whiteColor())
def __init__(self, posSize, layer = None, backgroundColor = None): self._setupView(self.nsViewClass, posSize) self.layer = layer if backgroundColor != None: self.backgroundColor = backgroundColor else: self.backgroundColor = NSColor.whiteColor()
def showWindow_(self, sender): width, height = 400, 300 minWidth, minHeight = 100, 100 maxWidth, maxHeight = 500, 500 # max size of window = size of largest screen: for screen in NSScreen.screens(): screenSize = screen.visibleFrame().size maxWidth = max(int(screenSize.width), maxWidth) maxHeight = max(int(screenSize.height), maxHeight) w = FloatingWindow((width, height), self.name, minSize=(minWidth, minHeight), maxSize=(maxWidth, maxHeight)) w.center() window = w.getNSWindow() window.setTitlebarAppearsTransparent_(1) window.setStandardWindowTitleButtonsAlphaValue_(0.00001) window.setBackgroundColor_(NSColor.whiteColor()) window.setAlphaValue_(0.9) window.setMovableByWindowBackground_(1) w.im = ImageView((10, 10, -10, -10), horizontalAlignment='center', verticalAlignment='center', scale='proportional') w.im.setImage(imagePath=self.iconPath) imview = w.im.getNSImageView() imview.setEditable_(True) imview.setFocusRingType_(NSFocusRingTypeNone) w.open() w.select()
def initWithFrame_view_size_name_captionText_(self, frame, view, size, name, caption_text): self = super(PictureView, self).initWithFrame_(frame) if not self: return _size = iW, iH = size xOffset = (frame.size[0] - iW) / 2.0 yOffset = frame.size[1] - xOffset - iH self.dropboxViewFinalPosition = NSRect((xOffset, yOffset), _size) self.dropboxView = view self.dropboxView.setFrame_(self.dropboxViewFinalPosition) self.addSubview_(self.dropboxView) self.versionView = NSTextView.alloc().initWithFrame_(NSRect((0, 0), frame.size)) self.versionView.setDrawsBackground_(NO) self.versionView.setEditable_(NO) self.versionView.setSelectable_(NO) self.versionView.textStorage().beginEditing() self.versionView.textStorage().mutableString().setString_(name) self.versionView.textStorage().setForegroundColor_(NSColor.whiteColor()) self.versionView.textStorage().setFont_(NSFont.labelFontOfSize_(18)) self.versionView.textStorage().endEditing() self.versionView.setAlignment_range_(NSCenterTextAlignment, NSMakeRange(0, self.versionView.string().length())) self.versionView.layoutManager().glyphRangeForTextContainer_(self.versionView.textContainer()) textSize1 = self.versionView.layoutManager().usedRectForTextContainer_(self.versionView.textContainer()).size textAnchor1 = 0 self.versionView2 = NSTextView.alloc().initWithFrame_(NSRect((0, 0), frame.size)) self.versionView2.setDrawsBackground_(NO) self.versionView2.setEditable_(NO) self.versionView2.setSelectable_(NO) self.versionView2.textStorage().beginEditing() self.versionView2.textStorage().mutableString().setString_(u'"%s"' % (caption_text,)) self.versionView2.textStorage().setForegroundColor_(NSColor.whiteColor()) self.versionView2.textStorage().setFont_(NSFont.labelFontOfSize_(13)) self.versionView2.textStorage().endEditing() self.versionView2.setAlignment_range_(NSCenterTextAlignment, NSMakeRange(0, self.versionView2.string().length())) self.versionView2.layoutManager().glyphRangeForTextContainer_(self.versionView2.textContainer()) textSize2 = self.versionView2.layoutManager().usedRectForTextContainer_(self.versionView2.textContainer()).size textAnchor2 = 0 bottomToLogoViewBaseline = yOffset textSeparation = (yOffset - textSize1[1] - textSize2[1]) * 0.2 combinedHeight = textSize1[1] + textSize2[1] + textSeparation self.versionView2FinalPosition = NSRect(((frame.size[0] - textSize2[0]) / 2.0, (bottomToLogoViewBaseline - combinedHeight) / 2.0), (textSize2[0], textSize2[1] + textAnchor2)) self.versionView2.setFrame_(self.versionView2FinalPosition) self.versionViewFinalPosition = NSRect(((frame.size[0] - textSize1[0]) / 2.0, self.versionView2.frame().origin[1] + textSeparation + self.versionView2.frame().size[1]), (textSize1[0], textSize1[1] + textAnchor1)) self.versionView.setFrame_(self.versionViewFinalPosition) self.addSubview_(self.versionView) self.addSubview_(self.versionView2) return self
def drawBackground(self): if "glyphViewBackgroundColor" in self._theme: self._backgroundColor = drawing.colorToNSColor( self._theme["glyphViewBackgroundColor"]) else: self._backgroundColor = NSColor.whiteColor() self._backgroundColor.set() NSRectFill(self.bounds())
def __init__(self): self.modifiedGlyph = None self.w = FloatingWindow((400, 170), "Corner Tool") self.w.getNSWindow().setBackgroundColor_(NSColor.whiteColor()) self.modes = ["Break", "Build", "Pit"] self.objectTypes = {"Build": "Segment", "Break": "Corner point", "Pit": "Corner point"} self.parameters = { "radius": VanillaSingleValueParameter("radius", 20, (-200, 200), numType="int"), "roundness": VanillaSingleValueParameter("roundness", 1.25, (0, 4), numType="float"), "depth": VanillaSingleValueParameter("depth", 30, (-100, 100), numType="int"), "breadth": VanillaSingleValueParameter("breadth", 30, (0, 150), numType="int"), "bottom": VanillaSingleValueParameter("bottom", 5, (0, 40), numType="int"), } self.currentMode = "Break" self.previewGlyph = None self.w.modes = RadioGroup((15, 15, 70, -15), self.modes, callback=self.changeMode) for i, mode in enumerate(self.modes): setattr(self.w, mode, Group((120, 15, -15, -15))) modeGroup = getattr(self.w, mode) modeGroup.apply = GradientButton((-35, 0, -0, -0), title=u">", callback=self.apply) modeGroup.infoBox = Box((0, 0, -50, 35)) modeGroup.info = TextBox((10, 8, -50, 20), "No selection") if i > 0: modeGroup.show(False) self.w.Break.radius = ParameterSliderTextInput( self.parameters["radius"], (0, 60, -25, 25), title="Radius", callback=self.makePreviewGlyph ) self.w.Break.roundness = ParameterSliderTextInput( self.parameters["roundness"], (0, 95, -25, 25), title="Roundness", callback=self.makePreviewGlyph ) self.w.Pit.depth = ParameterSliderTextInput( self.parameters["depth"], (0, 50, -25, 25), title="Depth", callback=self.makePreviewGlyph ) self.w.Pit.breadth = ParameterSliderTextInput( self.parameters["breadth"], (0, 80, -25, 25), title="Breadth", callback=self.makePreviewGlyph ) self.w.Pit.bottom = ParameterSliderTextInput( self.parameters["bottom"], (0, 110, -25, 25), title="bottom", callback=self.makePreviewGlyph ) addObserver(self, "preview", "draw") addObserver(self, "preview", "drawInactive") addObserver(self, "previewSolid", "drawPreview") addObserver(self, "makePreviewGlyph", "mouseDown") addObserver(self, "makePreviewGlyph", "mouseDragged") addObserver(self, "makePreviewGlyph", "keyDown") addObserver(self, "makePreviewGlyph", "keyUp") addObserver(self, "setControls", "mouseUp") addObserver(self, "setControls", "selectAll") addObserver(self, "setControls", "deselectAll") addObserver(self, "setControls", "currentGlyphChanged") self.w.bind("close", self.windowClose) self.setControls() self.w.open()
def attributed_text_at_size(text, size): paragraph_style = NSMutableParagraphStyle.new() paragraph_style.setAlignment_(NSCenterTextAlignment) attrs = { NSParagraphStyleAttributeName: paragraph_style, NSFontAttributeName: NSFont.boldSystemFontOfSize_(size), NSForegroundColorAttributeName: NSColor.whiteColor() } return NSAttributedString.alloc().initWithString_attributes_(text, attrs)
def drawRect_(self, rect): try: NSColor.whiteColor().set() NSRectFill(self.bounds()) NSColor.blackColor().setFill() p = NSBezierPath.bezierPath() xcursor = 0 ycursor = 0 for i, g in enumerate(self.glyphs): layer = g.layers[0] if i > 0: # Do anchor correction here prevlayer = self.glyphs[i - 1].layers[0] entry = prevlayer.anchors["entry"] exit = layer.anchors["exit"] if entry and exit: diffX = entry.position.x - exit.position.x diffY = entry.position.y - exit.position.y xcursor = xcursor + diffX ycursor = ycursor + diffY else: NSColor.redColor().setFill() else: xcursor = xcursor - layer.bounds.origin.x thisPath = NSBezierPath.bezierPath() thisPath.appendBezierPath_(layer.completeBezierPath) t = NSAffineTransform.transform() t.translateXBy_yBy_(xcursor, -layer.master.descender + ycursor) thisPath.transformUsingAffineTransform_(t) p.appendBezierPath_(thisPath) t = NSAffineTransform.transform() if xcursor > 0: master = self.glyphs[0].layers[0].master vscale = self.bounds().size.height / (master.ascender - master.descender) hscale = self.bounds().size.width / xcursor t.scaleBy_(min(hscale, vscale)) p.transformUsingAffineTransform_(t) p.fill() except Exception as e: print("Oops!", sys.exc_info()[0], "occured.") traceback.print_exc(file=sys.stdout)
def flatButt(self, this, match=False): this = this.getNSButton() this.setBezelStyle_(buttstyle) this.setBordered_(False) this.setWantsLayer_(True) this.setBackgroundColor_(NSColor.whiteColor()) if match == True: this.setBackgroundColor_( NSColor.colorWithCalibratedRed_green_blue_alpha_( .9, 1, .85, 1))
def drawRect_(self, rect): try: NSColor.whiteColor().set() NSRectFill(self.bounds()) NSColor.blackColor().setFill() NSColor.blueColor().setStroke() p = NSBezierPath.bezierPath() xcursor = 0 string = self.string master = self.master for s in range(0, len(string)): thisPath = NSBezierPath.bezierPath() gsglyph = master.font.glyphs[string[s]] layer = gsglyph.layers[master.id] thisPath.appendBezierPath_(layer.completeBezierPath) # print("X cursor was",xcursor) xcursor = xcursor - layer.bounds.origin.x # print("Moving backwards", layer.bounds.origin.x) t = NSAffineTransform.transform() t.translateXBy_yBy_(xcursor, -master.descender) thisPath.transformUsingAffineTransform_(t) # print("Drawing at",xcursor) # print(thisPath) xcursor = xcursor + layer.bounds.origin.x xcursor = xcursor + layer.bounds.size.width # print("Adding width", layer.bounds.size.width) if s < len(string) - 1: xcursor = xcursor + self.distances[(string[s], string[s + 1])] p.appendBezierPath_(thisPath) t = NSAffineTransform.transform() if xcursor > 0: vscale = self.bounds().size.height / (master.ascender - master.descender) hscale = self.bounds().size.width / xcursor t.scaleBy_(min(hscale, vscale)) p.transformUsingAffineTransform_(t) p.fill() except: print("Oops!", sys.exc_info()[0], "occured.") traceback.print_exc(file=sys.stdout)
def mouseEntered(self, event): g = self.w.getGlyph() if g is None: return f = g.font if f is None: return self.showButtons = True sbui = windowViewManger.get(self.w) sbui.L.Lminus.show(True) sbui.L.Lround.show(True) sbui.L.Lplus.show(True) sbui.L.Lright.show(True) sbui.R.Rminus.show(True) sbui.R.Rround.show(True) sbui.R.Rplus.show(True) sbui.R.Rleft.show(True) sbui.C.Cminus.show(True) sbui.C.Cround.show(True) sbui.C.Ccenter.show(True) sbui.C.Cplus.show(True) sbui.L.Ltext.getNSTextField().setBackgroundColor_(NSColor.whiteColor()) sbui.R.Rtext.getNSTextField().setBackgroundColor_(NSColor.whiteColor()) sbui.C.Ctext.getNSTextField().setBackgroundColor_(NSColor.whiteColor()) uniquecomponents = [] for c in g.components: if c.baseGlyph not in uniquecomponents: uniquecomponents.append(c.baseGlyph) for i, c in enumerate(uniquecomponents): try: this = getattr(sbui.L, 'buttobj_%s' % i) this.show(True) this = getattr(sbui.R, 'buttobj_%s' % i) this.show(True) this = getattr(sbui.C, 'buttobj_%s' % i) this.show(True) except: return sbui.update()
def __init__(self, dimensions, font): font_name = font.info.familyName attribution = "{} by {}".format(font_name, font.info.designer) attribution_attributes = { NSFontAttributeName: NSFont.systemFontOfSize_(NSFont.systemFontSize()), NSForegroundColorAttributeName: NSColor.whiteColor() } formatted_attribution = NSMutableAttributedString.alloc().initWithString_attributes_(attribution, attribution_attributes) formatted_attribution.addAttribute_value_range_(NSFontAttributeName, NSFont.boldSystemFontOfSize_(NSFont.systemFontSize()), [0, len(font_name)]) super(AttributionText, self).__init__(dimensions, formatted_attribution)
def __init__(self): f = CurrentFont() if f is None: return self.designSpaceModel = f.lib.get(self.designSpaceModelLibKey, "twobytwo") #print "self.designSpaceModel", self.designSpaceModel if self.designSpaceModel == "twobytwo": self.masterNames = [ 'narrow-thin', 'wide-thin', 'narrow-bold', 'wide-bold' ] elif self.designSpaceModel == "twobyone": self.masterNames = ['narrow-thin', 'wide-thin'] self.shapeColor = None self.backgroundColor = None self.extrapolateMinValue = 0 self.extrapolateMaxValue = 1 self.w = vanilla.Window((500, 600), "Responsive Lettering", minSize=(300, 200)) self.w.preview = HTMLView((0, 0, -0, -140)) self.w.exportButton = vanilla.Button((-150, -30, -10, 20), "Export SVG", callback=self.cbExport) columnDescriptions = [ dict(title="Glyphname", key="name", width=125), dict(title="Width", key="width", width=50), dict(title="Height", key="height", width=50), dict(title="Bounds?", key="bounds", width=75), dict(title="Contours", key="contours", width=50), dict(title="Points", key="points", width=50), ] self.w.l = vanilla.List((0, -140, -0, -40), self.wrapGlyphs(), columnDescriptions=columnDescriptions, doubleClickCallback=self.callbackListClick) self.w.t = vanilla.TextBox((70, -27, -160, 20), "FontName", sizeStyle="small") self.w.backgroundColorWell = vanilla.ColorWell( (10, -30, 20, 20), callback=self.backgroundColorWellCallback, color=NSColor.blackColor()) self.w.shapeColorWell = vanilla.ColorWell( (35, -30, 20, 20), callback=self.shapeColorWellCallback, color=NSColor.whiteColor()) self.w.bind("became main", self.windowBecameMainCallback) self.setColorsFromLib() self.update() self.w.open() self.cbMakePreview(None)
def __init__(self, posSize, pointSize=100, rightToLeft=False, applyKerning=False, glyphColor=None, backgroundColor=None, alternateHighlightColor=None, autohideScrollers=True, showPointSizePlacard=False): if glyphColor is None: glyphColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( 0, 0, 0, 1) if backgroundColor is None: backgroundColor = NSColor.whiteColor() if alternateHighlightColor is None: alternateHighlightColor = defaultAlternateHighlightColor self._applyKerning = applyKerning self._glyphLineView = self.glyphLineViewClass.alloc().init() self._glyphLineView.setPointSize_(pointSize) self._glyphLineView.setRightToLeft_(rightToLeft) self._glyphLineView.setGlyphColor_(glyphColor) self._glyphLineView.setBackgroundColor_(backgroundColor) self._glyphLineView.setAlternateHighlightColor_( alternateHighlightColor) self._glyphLineView.vanillaWrapper = weakref.ref(self) # don't autohide if the placard is to be visible. # bad things will happen if this is not the case. if showPointSizePlacard: autohideScrollers = False # setup the scroll view super(GlyphLineView, self).__init__(posSize, self._glyphLineView, autohidesScrollers=autohideScrollers, backgroundColor=backgroundColor) # placard if showPointSizePlacard: self._pointSizes = ["Auto"] + [str(i) for i in pointSizes] placardW = 55 placardH = 16 self._placard = vanilla.Group((0, 0, placardW, placardH)) self._placard.button = PlacardPopUpButton( (0, 0, placardW, placardH), self._pointSizes, callback=self._placardSelection, sizeStyle="mini") self.setPlacard(self._placard) pointSize = str(pointSize) if pointSize in self._pointSizes: index = self._pointSizes.index(pointSize) self._placard.button.set(index)
def init(self): self = super(DefconAppKitGlyphLineNSView, self).init() self._showLayers = False self._layerDrawingAttributes = {} self._fallbackDrawingAttributes = dict( showGlyphFill=True, showGlyphStroke=False, showGlyphOnCurvePoints=False, showGlyphStartPoints=False, showGlyphOffCurvePoints=False, showGlyphPointCoordinates=False, showGlyphAnchors=False, showGlyphImage=False, showGlyphMargins=False, showFontVerticalMetrics=False, showFontPostscriptBlues=False, showFontPostscriptFamilyBlues=False) self._glyphRecords = [] self._alternateRects = {} self._currentZeroZeroPoint = NSPoint(0, 0) self._rightToLeft = False self._pointSize = 150 self._impliedPointSize = 150 self._scale = 1.0 self._inverseScale = 0.1 self._upm = 1000 self._descender = -250 self._bufferLeft = self._bufferRight = self._bufferBottom = self._bufferTop = 15 self._cutoffDisplayPointSizes = dict(showFontVerticalMetrics=150, showGlyphStartPoints=175, showGlyphOnCurvePoints=175, showGlyphOffCurvePoints=175, showGlyphPointCoordinates=250, showGlyphAnchors=50) self._fitToFrame = None self._backgroundColor = NSColor.whiteColor() self._glyphColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( 0, 0, 0, 1) self._strokeColor = None self._pointColor = None self._alternateHighlightColor = defaultAlternateHighlightColor self._notdefBackgroundColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( 1, 0, 0, .25) return self
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
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)
def initWithFrame_(self, frame): self = super(GreetingsTo, self).initWithFrame_(frame) if not self: return self.timers = [] for __text in ('greetings', 'to', 'AAPL', 'GOOG', 'MSFT', (':)', '_smile'), (':P', '_wink')): if type(__text) is str: _text = attr = __text else: _text, attr = __text vv = NSTextView.alloc().initWithFrame_(NSRect((0, 0), frame.size)) vv.setDrawsBackground_(NO) vv.setEditable_(NO) vv.setSelectable_(NO) vv.setAlignment_range_(NSCenterTextAlignment, NSMakeRange(0, vv.string().length())) vv.textStorage().beginEditing() vv.textStorage().mutableString().setString_(_text) vv.textStorage().setFont_(NSFont.labelFontOfSize_(42 if _text in ('greetings', 'to') else 36)) vv.textStorage().setForegroundColor_(NSColor.whiteColor()) vv.textStorage().endEditing() vv.layoutManager().glyphRangeForTextContainer_(vv.textContainer()) vv.setFrameSize_(vv.layoutManager().usedRectForTextContainer_(vv.textContainer()).size) setattr(self, attr, vv) vv.setHidden_(True) self.addSubview_(vv) self.blast_order = (self.greetings, self.to, self.AAPL, self.GOOG, self.MSFT, self._smile) self.greetings.setHidden_(False) self.greetings.setFrameOrigin_(((frame.size[0] - self.greetings.frame().size[0]) / 2.0, BASE_HEIGHT - 100)) self.to.setFrameOrigin_(((frame.size[0] - self.to.frame().size[0]) / 2.0, BASE_HEIGHT - 100 - self.greetings.frame().size[1] - 20)) offset = (frame.size[0] - (self.AAPL.frame().size[0] + self.GOOG.frame().size[0] + 60)) / 2.0 self.AAPL_POS = (offset, 220) self.GOOG_POS = (WIDTH - self.GOOG.frame().size[0] - offset, 220) self.MSFT_POS = ((frame.size[0] - self.MSFT.frame().size[0]) / 2.0, 200 - self.AAPL.frame().size[1] - 80) self._wink.setFrameOrigin_(((frame.size[0] - self._wink.frame().size[0]) / 2.0, 200 - self._wink.frame().size[1])) self._smile.setFrameOrigin_(((frame.size[0] - self._wink.frame().size[0]) / 2.0, 200 - self._wink.frame().size[1])) return self
def drawText( self, text, fontColor=NSColor.whiteColor() ): try: fontSize = Glyphs.defaults["%s.fontSize"%self.vID] fontAttributes = { #NSFontAttributeName: NSFont.labelFontOfSize_(10.0), NSFontAttributeName: NSFont.monospacedDigitSystemFontOfSize_weight_(fontSize,0.0), NSForegroundColorAttributeName: NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.5, 0.5, 0.5, 1 ) } displayText = NSAttributedString.alloc().initWithString_attributes_(text, fontAttributes) textAlignment = 0 upperLeftCorner = NSPoint( self.controller.viewPort.origin.x + 5 , self.controller.viewPort.origin.y + self.controller.viewPort.size.height - 32) displayText.drawAtPoint_alignment_(upperLeftCorner, textAlignment) except: print(traceback.format_exc())
def __init__(self): self.modifiedGlyph = None self.w = FloatingWindow((400, 170), 'Corner Tool') self.w.getNSWindow().setBackgroundColor_(NSColor.whiteColor()) self.modes = ['Break', 'Build','Pit'] self.objectTypes = {'Build':'Segment', 'Break':'Corner point', 'Pit':'Corner point'} self.parameters = { 'radius': VanillaSingleValueParameter('radius', 20, (-200, 200), numType='int'), 'roundness': VanillaSingleValueParameter('roundness', 1.25, (0, 4), numType='float'), 'depth': VanillaSingleValueParameter('depth', 30, (-100, 100), numType='int'), 'breadth': VanillaSingleValueParameter('breadth', 30, (0, 150), numType='int'), 'bottom': VanillaSingleValueParameter('bottom', 5, (0, 40), numType='int') } self.currentMode = 'Break' self.previewGlyph = None self.w.modes = RadioGroup((15, 15, 70, -15), self.modes, callback=self.changeMode) for i, mode in enumerate(self.modes): setattr(self.w, mode, Group((120, 15, -15, -15))) modeGroup = getattr(self.w, mode) modeGroup.apply = GradientButton((-35, 0, -0, -0), title=u'>', callback=self.apply) modeGroup.infoBox = Box((0, 0, -50, 35)) modeGroup.info = TextBox((10, 8, -50, 20), 'No selection') if i > 0: modeGroup.show(False) self.w.Break.radius = ParameterSliderTextInput(self.parameters['radius'], (0, 60, -25, 25), title='Radius', callback=self.makePreviewGlyph) self.w.Break.roundness = ParameterSliderTextInput(self.parameters['roundness'], (0, 95, -25, 25), title='Roundness', callback=self.makePreviewGlyph) self.w.Pit.depth = ParameterSliderTextInput(self.parameters['depth'], (0, 50, -25, 25), title='Depth', callback=self.makePreviewGlyph) self.w.Pit.breadth = ParameterSliderTextInput(self.parameters['breadth'], (0, 80, -25, 25), title='Breadth', callback=self.makePreviewGlyph) self.w.Pit.bottom = ParameterSliderTextInput(self.parameters['bottom'], (0, 110, -25, 25), title='bottom', callback=self.makePreviewGlyph) addObserver(self, 'preview', 'draw') addObserver(self, 'preview', 'drawInactive') addObserver(self, 'previewSolid', 'drawPreview') addObserver(self, 'makePreviewGlyph', 'mouseDown') addObserver(self, 'makePreviewGlyph', 'mouseDragged') addObserver(self, 'makePreviewGlyph', 'keyDown') addObserver(self, 'makePreviewGlyph', 'keyUp') addObserver(self, 'setControls', 'mouseUp') addObserver(self, 'setControls', 'selectAll') addObserver(self, 'setControls', 'deselectAll') addObserver(self, 'setControls', 'currentGlyphChanged') self.w.bind('close', self.windowClose) self.setControls() self.w.open()
def __init__(self): self.modifiedGlyph = None self.w = FloatingWindow((400, 170), 'Corner Tool') self.w.getNSWindow().setBackgroundColor_(NSColor.whiteColor()) self.modes = ['Break', 'Build','Pit'] self.objectTypes = {'Build':'Segment', 'Break':'Corner point', 'Pit':'Corner point'} self.parameters = { 'radius': VanillaSingleValueParameter('radius', 20, (-200, 200), numType='int'), 'roundness': VanillaSingleValueParameter('roundness', 1.25, (0, 4), numType='float'), 'depth': VanillaSingleValueParameter('depth', 30, (-100, 100), numType='int'), 'breadth': VanillaSingleValueParameter('breadth', 30, (0, 150), numType='int'), 'bottom': VanillaSingleValueParameter('bottom', 5, (0, 40), numType='int') } self.currentMode = 'Break' self.previewGlyph = None self.w.modes = RadioGroup((15, 15, 70, -15), self.modes, callback=self.changeMode) for i, mode in enumerate(self.modes): setattr(self.w, mode, Group((120, 15, -15, -15))) modeGroup = getattr(self.w, mode) modeGroup.apply = GradientButton((-35, 0, -0, -0), title=u'>', callback=self.apply) modeGroup.infoBox = Box((0, 0, -50, 35)) modeGroup.info = TextBox((10, 8, -50, 20), 'No selection') if i > 0: modeGroup.show(False) self.w.Break.radius = ParameterSliderTextInput(self.parameters['radius'], (0, 60, -25, 25), title='Radius', callback=self.makePreviewGlyph) self.w.Break.roundness = ParameterSliderTextInput(self.parameters['roundness'], (0, 95, -25, 25), title='Roundness', callback=self.makePreviewGlyph) self.w.Pit.depth = ParameterSliderTextInput(self.parameters['depth'], (0, 50, -25, 25), title='Depth', callback=self.makePreviewGlyph) self.w.Pit.breadth = ParameterSliderTextInput(self.parameters['breadth'], (0, 80, -25, 25), title='Breadth', callback=self.makePreviewGlyph) self.w.Pit.bottom = ParameterSliderTextInput(self.parameters['bottom'], (0, 110, -25, 25), title='bottom', callback=self.makePreviewGlyph) addObserver(self, 'preview', 'draw') addObserver(self, 'preview', 'drawInactive') addObserver(self, 'makePreviewGlyph', 'mouseDown') addObserver(self, 'makePreviewGlyph', 'mouseDragged') addObserver(self, 'makePreviewGlyph', 'keyDown') addObserver(self, 'makePreviewGlyph', 'keyUp') addObserver(self, 'setControls', 'mouseUp') addObserver(self, 'setControls', 'selectAll') addObserver(self, 'setControls', 'deselectAll') addObserver(self, 'setControls', 'currentGlyphChanged') self.w.bind('close', self.windowClose) self.setControls() self.w.open()
def __init__(self, dimensions, font): font_name = font.info.familyName or "" attribution = "{} by {}".format(font_name, font.info.openTypeNameDesigner) attribution_attributes = { NSFontAttributeName: NSFont.systemFontOfSize_(NSFont.systemFontSize()), NSForegroundColorAttributeName: NSColor.whiteColor() } formatted_attribution = NSMutableAttributedString.alloc( ).initWithString_attributes_(attribution, attribution_attributes) formatted_attribution.addAttribute_value_range_( NSFontAttributeName, NSFont.boldSystemFontOfSize_(NSFont.systemFontSize()), [0, len(font_name)]) super(AttributionText, self).__init__(dimensions, formatted_attribution)
def init(self): self = super(DefconAppKitGlyphNSView, self).init() self._glyph = None # drawing attributes self._layerDrawingAttributes = {} self._fallbackDrawingAttributes = dict( showGlyphFill=True, showGlyphStroke=True, showGlyphOnCurvePoints=True, showGlyphStartPoints=True, showGlyphOffCurvePoints=False, showGlyphPointCoordinates=False, showGlyphAnchors=True, showGlyphImage=False, showGlyphMargins=True, showFontVerticalMetrics=True, showFontVerticalMetricsTitles=True, showFontPostscriptBlues=False, showFontPostscriptFamilyBlues=False ) # cached vertical metrics self._unitsPerEm = 1000 self._descender = -250 self._capHeight = 750 self._ascender = 750 # drawing data cache self._drawingRect = None self._fitToFrame = None self._scale = 1.0 self._inverseScale = 0.1 self._impliedPointSize = 1000 # drawing calculation self._centerVertically = True self._centerHorizontally = True self._noPointSizePadding = 200 self._verticalCenterYBuffer = 0 self._backgroundColor = NSColor.whiteColor() return self
def init(self): self = super(DefconAppKitGlyphThemeNSView, self).init() self._glyph = None # drawing attributes self._theme = {} self._layerDrawingAttributes = {} self._fallbackDrawingAttributes = dict( showGlyphFill=True, showGlyphStroke=True, showGlyphOnCurvePoints=True, showGlyphStartPoints=True, showGlyphOffCurvePoints=False, showGlyphPointCoordinates=False, showGlyphAnchors=True, showGlyphImage=False, showGlyphMargins=True, showFontVerticalMetrics=True, showFontVerticalMetricsTitles=True, showFontPostscriptBlues=False, showFontPostscriptFamilyBlues=False) # cached vertical metrics self._unitsPerEm = 1000 self._descender = -250 self._capHeight = 750 self._ascender = 750 # drawing data cache self._drawingRect = None self._fitToFrame = None self._scale = 1.0 self._inverseScale = 0.1 self._impliedPointSize = 1000 # drawing calculation self._centerVertically = True self._centerHorizontally = True self._noPointSizePadding = -250 self._verticalCenterYBuffer = 100 self._backgroundColor = NSColor.whiteColor() return self
def __init__(self): width, height = 600,50 self.w = vanilla.FloatingWindow((width, height),"") self.w.center() # Setting Window Appearance window = self.w.getNSWindow() window.setTitlebarAppearsTransparent_(1) # Hide title bar window.setStandardWindowTitleButtonsAlphaValue_(0.00001) # Hiding buttons hack window.setBackgroundColor_(NSColor.whiteColor()) # Window background window.setAlphaValue_(0.9) # Slight transparency, don't know how to apply vibrancy like in spotlight self.w.editText = vanilla.EditText((20, 0, -20, -14), continuous=False, callback=self.test) # Setting EditText Appearance font = NSFont.systemFontOfSize_weight_(28,-0.5) box = self.w.editText.getNSTextField() box.setBordered_(False) box.setDrawsBackground_(False) box.setFont_(font) box.setFocusRingType_(NSFocusRingTypeNone) # Open window and focus self.w.open() self.w.select() self.w.infoText = vanilla.TextBox((10, -25, -1, -1), "") infoBox = self.w.infoText.getNSTextField() infoBox.setBordered_(False) infoBox.setDrawsBackground_(False) # infoBox.setFont_(font) infoBox.setFocusRingType_(NSFocusRingTypeNone) self.w.line = vanilla.HorizontalLine((10, -56, -10, 0)) self.w.line.show(0)
def __init__(self): self.libkey = "com.fontfont.colorfont" self._font = None self.show_only_glyphs_with_layers = True self.color = NSColor.blackColor() self.colorbg = NSColor.whiteColor() self._selected_color_index = None # live update the canvas when glyphs are edited self._debug_enable_live_editing = True self._auto_layer_regex_ok = True # self.oldDisplaySettings = getGlyphViewDisplaySettings() # setGlyphViewDisplaySettings({"On Curve Points": False, "Off Curve Points": False}) self.w = get_ui(self, "None") self.d = get_drawer(self) self.setUpBaseWindowBehavior() # self._callback_ui_glyph_list_selection() addObserver(self, "_observer_glyph_changed", "currentGlyphChanged") addObserver(self, "_observer_draw_glyph_window", "drawBackground") addObserver(self, "_observer_draw_glyph_window", "drawInactive") addObserver(self, "_observer_font_will_close", "fontWillClose") addObserver(self, "_observer_font_did_open", "fontDidOpen") # grey out controls that are not implemented yet self.d.generateGoogleFormat.enable(False) self.d.preferPlacedImages.enable(False) # disable regex check box, because it is read only self.d.auto_layer_regex_ok.enable(False) # If sbix or cbdt is inactive, disable bitmap sizes box # self._check_bitmap_ui_active() self.w.open() self.font = CurrentFont()
def init(self): self = super(DefconAppKitGlyphLineNSView, self).init() self._showLayers = False self._layerDrawingAttributes = {} self._fallbackDrawingAttributes = dict( showGlyphFill=True, showGlyphStroke=False, showGlyphOnCurvePoints=False, showGlyphStartPoints=False, showGlyphOffCurvePoints=False, showGlyphPointCoordinates=False, showGlyphAnchors=False, showGlyphImage=False, showGlyphMargins=False, showFontVerticalMetrics=False, showFontPostscriptBlues=False, showFontPostscriptFamilyBlues=False ) self._glyphRecords = [] self._alternateRects = {} self._currentZeroZeroPoint = NSPoint(0, 0) self._rightToLeft = False self._pointSize = 150 self._impliedPointSize = 150 self._scale = 1.0 self._inverseScale = 0.1 self._upm = 1000 self._descender = -250 self._bufferLeft = self._bufferRight = self._bufferBottom = self._bufferTop = 15 self._fitToFrame = None self._backgroundColor = NSColor.whiteColor() self._glyphColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 1) self._alternateHighlightColor = defaultAlternateHighlightColor self._notdefBackgroundColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(1, 0, 0, .25) return self
def getFittingString(t, fontName, layerIndex, fontSize=None): # Make formatted string of large type. # Then see if it fits and calculate the fitting size. # First guess, to see if constructed formatted string fits. initialFontSize = 500 glb = globals() colorLabel = 'Layer_Color_%d' % layerIndex layerColor = getColor(layerIndex) if glb.get(colorLabel) is None: glb[colorLabel] = NSColor.whiteColor() try: r, g, b, opacity = layerColor.getRed_green_blue_alpha_( None, None, None, None) except ValueError: r = random() g = random() b = random() opacity = 0.4 + 0.6 * random() # Not totally opaque. glb[colorLabel] = NSColor.colorWithCalibratedRed_green_blue_alpha_( r, g, b, opacity) if not color: r = g = b = random() * 0.8 if fontSize is None: # Calculate the size for the given string for the selected font/spacing. # Then use the resulting with as source to calculate the fitting fontSize. fs = context.newString(Sample_Text, style=dict(font=fontName, fontSize=initialFontSize)) fsWidth, fsHeight = fs.size() fontSize = initialFontSize * (W - 2 * M) / fsWidth # Make new formatted string in fitting fontSize fs = context.newString(t, style=dict(font=fontName, fontSize=fontSize, textFill=(r, g, b, opacity))) return fontSize, fs
def __init__(self, posSize, pointSize=100, rightToLeft=False, applyKerning=False, glyphColor=None, backgroundColor=None, alternateHighlightColor=None, autohideScrollers=True, showPointSizePlacard=False): if glyphColor is None: glyphColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 1) if backgroundColor is None: backgroundColor = NSColor.whiteColor() if alternateHighlightColor is None: alternateHighlightColor = defaultAlternateHighlightColor self._applyKerning = applyKerning self._glyphLineView = self.glyphLineViewClass.alloc().init() self._glyphLineView.setPointSize_(pointSize) self._glyphLineView.setRightToLeft_(rightToLeft) self._glyphLineView.setGlyphColor_(glyphColor) self._glyphLineView.setBackgroundColor_(backgroundColor) self._glyphLineView.setAlternateHighlightColor_(alternateHighlightColor) self._glyphLineView.vanillaWrapper = weakref.ref(self) # don't autohide if the placard is to be visible. # bad things will happen if this is not the case. if showPointSizePlacard: autohideScrollers = False # setup the scroll view super(GlyphLineView, self).__init__(posSize, self._glyphLineView, autohidesScrollers=autohideScrollers, backgroundColor=backgroundColor) # placard if showPointSizePlacard: self._pointSizes = ["Auto"] + [str(i) for i in pointSizes] placardW = 55 placardH = 16 self._placard = vanilla.Group((0, 0, placardW, placardH)) self._placard.button = PlacardPopUpButton((0, 0, placardW, placardH), self._pointSizes, callback=self._placardSelection, sizeStyle="mini") self.setPlacard(self._placard) pointSize = str(pointSize) if pointSize in self._pointSizes: index = self._pointSizes.index(pointSize) self._placard.button.set(index)
value=9, tickMarkCount=11, stopOnTickMarks=True)), dict(name='starCols', ui='Slider', args=dict(minValue=1, maxValue=21, value=11, tickMarkCount=11, stopOnTickMarks=True)), dict(name='oddStripeColor', ui='ColorWell', args=dict(color=NSColor.redColor())), dict(name='evenStripeColor', ui='ColorWell', args=dict(color=NSColor.whiteColor())), dict(name='cantonColor', ui='ColorWell', args=dict(color=NSColor.blueColor())), dict(name='starColor', ui='ColorWell', args=dict(color=NSColor.whiteColor())), dict(name='jasperize', ui='Slider', args=dict(minValue=1, maxValue=6, value=1, tickMarkCount=6, stopOnTickMarks=True)), ], globals())
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
def __init__(self, *args, **kwargs): super(HUDTextBox, self).__init__(*args, **kwargs) self._nsObject.setTextColor_(NSColor.whiteColor())
def __init__(self, dimensions, text): super(Overlay.CenteredText, self).__init__(dimensions, text, alignment="center") self._nsObject.setTextColor_(NSColor.whiteColor())
showGlyphMargins showFontVerticalMetrics showFontVerticalMetricsTitles showFontPostscriptBlues showFontPostscriptFamilyBlues """ # ------ # Colors # ------ defaultColors = dict( # General # ------- background=NSColor.whiteColor(), # Font # ---- # vertical metrics fontVerticalMetrics=NSColor.colorWithCalibratedWhite_alpha_(.4, .5), fontPostscriptBlues=NSColor.colorWithCalibratedRed_green_blue_alpha_( .5, .7, 1, .3), fontPostscriptFamilyBlues=NSColor.colorWithCalibratedRed_green_blue_alpha_( 1, 1, .5, .3), # Glyph # ----- # margins
def WhiteText(string): attributes = { NSForegroundColorAttributeName: NSColor.whiteColor() } return NSAttributedString.alloc().initWithString_attributes_(string, attributes)
def __init__(self, ns_color): self.ns_color = ns_color Color.BLACK = Color(NSColor.blackColor()) Color.BLUE = Color(NSColor.blueColor()) Color.BROWN = Color(NSColor.brownColor()) Color.CYAN = Color(NSColor.cyanColor()) Color.DARK_GRAY = Color(NSColor.darkGrayColor()) Color.GRAY = Color(NSColor.grayColor()) Color.GREEN = Color(NSColor.greenColor()) Color.MAGENTA = Color(NSColor.magentaColor()) Color.ORANGE = Color(NSColor.orangeColor()) Color.PURPLE = Color(NSColor.purpleColor()) Color.RED = Color(NSColor.redColor()) Color.WHITE = Color(NSColor.whiteColor()) Color.YELLOW = Color(NSColor.yellowColor()) class Font: """ Text font """ def __init__(self, name, size): self.ns_font = NSFont.fontWithName_size_(name, size) class Sound: """ A system sound """ def __init__(self, path): self.path = path
class ZoneCheckerTool(EditingTool): zoneCheckerToolPrefsLibKey = "com.letterror.zoneChecker.prefs" textAttributes = { NSFontAttributeName: NSFont.systemFontOfSize_(10), NSForegroundColorAttributeName: NSColor.whiteColor(), } margin = 3 # how far off are points? def setup(self): self.markColor = (255 / 255.0, 0 / 255.0, 0 / 255.0, 0.8) self.okColor = (0 / 255.0, 0 / 255.0, 255 / 255.0, 0.8) self.outside = [] self.inside = [] def _p(self, items): if len(items) % 2 != 0: return [] return [(items[i], items[i + 1]) for i in range(0, len(items) - 1, 2)] def findMisalignedPoints(self): g = CurrentGlyph() f = CurrentFont() if f is None: return if not g: return self.outside = [] self.inside = [] zones = [] for a, b in self._p(f.info.postscriptBlueValues): zones.append((a, b)) for a, b in self._p(f.info.postscriptOtherBlues): zones.append((a, b)) for a, b in self._p(f.info.postscriptFamilyBlues): zones.append((a, b)) for c in g.contours: for p in c.points: if p.type == "offCurve": continue y = p.y for a, b in zones: if (a - self.margin < y < b + self.margin): if not (a <= y <= b): self.outside.append((p.x, p.y)) else: self.inside.append((p.x, p.y)) def draw(self, scale): self.findMisalignedPoints() if scale == 0: return save() fill(None) for x, y in self.outside: d = scale * 25 d2 = 2 * d strokeWidth(20 * scale) stroke(self.markColor[0], self.markColor[1], self.markColor[2], self.markColor[3]) oval(x - d, y - d, d2, d2) for x, y in self.inside: d = scale * 9 d2 = 2 * d strokeWidth(2 * scale) stroke(self.okColor[0], self.okColor[1], self.okColor[2], self.okColor[3]) oval(x - d, y - d, d2, d2) restore() # self.getNSView()._drawTextAtPoint( # "%3.2f"%(100-100*level), # self.textAttributes, # tp, # yOffset=-30, # drawBackground=True, # backgroundColor=NSColor.blueColor()) def mouseDown(self, point, event): pass # mods = self.getModifiers() # cmd = mods['commandDown'] > 0 # self.isResizing = False # if cmd: # self.clear() def clear(self): self.marked = None pass # self.pts = [] # self.dupes = set() # self.samples = {} def keyDown(self, event): pass # letter = event.characters() # if letter == "i": # # invert the paint color on drawing # self.prefs['invert'] = not self.prefs['invert'] # self.storePrefs() # UpdateCurrentGlyphView() def mouseDragged(self, point, delta): """ Calculate the blurred gray level for this point. """ pass def getToolbarTip(self): return 'ZoneChecker' def getToolbarIcon(self): ## return the toolbar icon return toolbarIcon
from AppKit import NSColor, NSGraphicsContext, NSForegroundColorAttributeName, NSAttributedString, NSFont, \ NSFontAttributeName, NSAffineTransform, NSRectFill, NSRectFillListUsingOperation, NSImage, NSParagraphStyleAttributeName, \ NSBezierPath, NSMutableParagraphStyle, NSCenterTextAlignment, NSLineBreakByTruncatingMiddle, NSCompositeSourceOver from defconAppKit.tools.drawing import colorToNSColor GlyphCellHeaderHeight = 14 GlyphCellMinHeightForHeader = 40 cellBackgroundColor = NSColor.whiteColor() cellHeaderBaseColor = NSColor.colorWithCalibratedWhite_alpha_(0.968, 1.0) cellHeaderHighlightColor = NSColor.colorWithCalibratedWhite_alpha_(0.98, 1.0) cellHeaderLineColor = NSColor.colorWithCalibratedWhite_alpha_(0, .2) cellMetricsLineColor = NSColor.colorWithCalibratedWhite_alpha_(0, .08) cellMetricsFillColor = NSColor.colorWithCalibratedWhite_alpha_(0, .08) def GlyphCellFactory(glyph, width, height, drawHeader=False, drawMetrics=False): obj = GlyphCellFactoryDrawingController(glyph=glyph, font=glyph.font, width=width, height=height, drawHeader=drawHeader, drawMetrics=drawMetrics) return obj.getImage() class GlyphCellFactoryDrawingController(object): """ This draws the cell with the layers stacked in this order: ------------------ header text ------------------ header background ------------------ foreground
from AppKit import NSColor, NSGraphicsContext, NSForegroundColorAttributeName, NSAttributedString, NSFont, \ NSFontAttributeName, NSAffineTransform, NSRectFill, NSRectFillListUsingOperation, NSImage, NSParagraphStyleAttributeName, \ NSBezierPath, NSMutableParagraphStyle, NSCenterTextAlignment, NSLineBreakByTruncatingMiddle, NSCompositeSourceOver from defconAppKit.tools.drawing import colorToNSColor GlyphCellHeaderHeight = 14 GlyphCellMinHeightForHeader = 40 cellBackgroundColor = NSColor.whiteColor() cellHeaderBaseColor = NSColor.colorWithCalibratedWhite_alpha_(0.968, 1.0) cellHeaderHighlightColor = NSColor.colorWithCalibratedWhite_alpha_(0.98, 1.0) cellHeaderLineColor = NSColor.colorWithCalibratedWhite_alpha_(0, .2) cellMetricsLineColor = NSColor.colorWithCalibratedWhite_alpha_(0, .08) cellMetricsFillColor = NSColor.colorWithCalibratedWhite_alpha_(0, .08) def GlyphCellFactory(glyph, width, height, drawHeader=False, drawMetrics=False): obj = GlyphCellFactoryDrawingController(glyph=glyph, font=glyph.font, width=width, height=height, drawHeader=drawHeader, drawMetrics=drawMetrics) return obj.getImage() class GlyphCellFactoryDrawingController(object):
class PlacardScrollView(vanilla.ScrollView): nsScrollViewClass = DefconAppKitPlacardNSScrollView def setPlacard(self, placard): if isinstance(placard, vanilla.VanillaBaseObject): placard = placard.getNSView() self._nsObject.setPlacard_(placard) # ------------- # Button Colors # ------------- placardGradientColor1 = NSColor.whiteColor() placardGradientColor2 = NSColor.colorWithCalibratedWhite_alpha_(.9, 1) placardGradientColorFallback = NSColor.colorWithCalibratedWhite_alpha_(.95, 1) # ---------------- # Segmented Button # ---------------- class DefconAppKitPlacardNSSegmentedCell(NSSegmentedCell): def drawingRectForBounds_(self, rect): return rect def cellSizeForBounds_(self, rect): return rect.size
showFontVerticalMetrics showFontVerticalMetricsTitles showFontPostscriptBlues showFontPostscriptFamilyBlues """ # ------ # Colors # ------ defaultColors = dict( # General # ------- background=NSColor.whiteColor(), # Font # ---- # vertical metrics fontVerticalMetrics=NSColor.colorWithCalibratedWhite_alpha_(.4, .5), fontPostscriptBlues=NSColor.colorWithCalibratedRed_green_blue_alpha_(.5, .7, 1, .3), fontPostscriptFamilyBlues=NSColor.colorWithCalibratedRed_green_blue_alpha_(1, 1, .5, .3), # Glyph # ----- # margins glyphMarginsFill=NSColor.colorWithCalibratedWhite_alpha_(.5, .11),
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())
def __init__(self): f = CurrentFont() if f is None: return self.shapeColor = None self.backgroundColor = None self.extrapolateMinValue = 0 self.extrapolateMaxValue = 1 self.w = vanilla.Window((500, 600), "Responsive Lettering", minSize=(300,200)) self.w.preview = HTMLView((0,0,-0, -140)) self.w.exportButton = vanilla.Button((-150, -30, -10, 20), "Export SVG", callback=self.cbExport) columnDescriptions = [ dict(title="Glyphname", key="name", width=125), dict(title="Width", key="width", width=50), dict(title="Height", key="height", width=50), dict(title="Bounds?", key="bounds", width=75), dict(title="Contours", key="contours", width=50), dict(title="Points", key="points", width=50), ] self.w.l = vanilla.List((0,-140,-0,-40), self.wrapGlyphs(), columnDescriptions=columnDescriptions, doubleClickCallback=self.callbackListClick) self.w.t = vanilla.TextBox((70,-27,-160,20), "FontName", sizeStyle="small") self.w.backgroundColorWell = vanilla.ColorWell((10,-30, 20, 20), callback=self.backgroundColorWellCallback, color=NSColor.blackColor()) self.w.shapeColorWell = vanilla.ColorWell((35,-30, 20, 20), callback=self.shapeColorWellCallback, color=NSColor.whiteColor()) self.w.bind("became main", self.windowBecameMainCallback) self.setColorsFromLib() self.update() self.w.open() self.cbMakePreview(None)
def initWithFrame_(self, frame): print "initWithFrame", frame self._location = self._locationDefault self._itemColor = self._itemColorDefault self._backgroundColor = self._backgroundColorDefault self.dragging = None result = super(OpenView, self).initWithFrame_(frame) # self.setBounds_( (0,0) , self.window().frame.size ) printB("initWithFrame", self ,all_names=True) # printB("view.initWithFrame", self, add=['frame','bounds']) print "result of super(OpenView, self).initWithFrame_(frame) is", result if result is None: return result # // setup the CALayer for the overall full-screen view # # backing layer # backingLayer = getQCCompLayer() frame = self.frame() backingLayer.setBounds_( ((0, 0), (frame.size.width, frame.size.height)) ) # backingLayer.setFrame_( view.frame() ) # backingLayer.frame = NSRectToCGRect(frame); # backingLayer.backgroundColor = CGColorCreateGenericRGB(1, 1, 1, 1.0); backingLayer.setOpaque_(objc.YES) # # printB("QCLayer", backingLayer) # # # print_setters(backingLayer) if True: # rootLayer = CALayer.layer() self.setLayer_(backingLayer) self.setWantsLayer_( objc.YES ) rootLayer = backingLayer else: self.setWantsLayer_( objc.YES ) rootLayer = self.layer() # printB("initWithFrame (super)", super(OpenView, self) ) # printB("initWithFrame (view)", self ) printB("View", self ) # frame = bounds for origin (0,0)? # print_setters(self, add=['bounds', 'frame']) printB("rootLayer", rootLayer, add=['bounds']) # # overlay Layer # # The overlay layer is used to draw any drag handles, so that they are always on top of all slides. # We must take care to make sure this layer is always the last one. # overlayLayer = MyOverLayer.layer() # (_LTOverlayLayer was MyOverLayer) overlayLayer.setFrame_( backingLayer.frame() ) # view.frame() ) overlayLayer.setOpaque_( objc.NO ) borderWidth = 4.0 overlayLayer.setBorderWidth_(borderWidth) # borderColor = CGColorCreateGenericGray(.4, 0.75) borderColor = CGColorCreateGenericRGB(1, 0.5, 0.2, 0.8); overlayLayer.setBorderColor_( borderColor ) zPosition = 20 overlayLayer.setZPosition_(zPosition) # zPosition # # Increasing zPosition moves the layer towards the front # Decreasing it moves it away and towards the back # # We want to be the delegate so we can do the drag handle drawing overlayLayer.setDelegate_(self) # overlayLayer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.0); # overlayLayer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable; # printB("overlayLayer", overlayLayer, all_names=True) # printB("overlayLayer", overlayLayer, only = ['borderColor', 'borderWidth', 'bounds'] ) backingLayer.addSublayer_(overlayLayer) layerDict = { 'origin' : (420,120), 'size' : (120,120), 'zPosition' : 12, 'image_path' : "/Users/donb/projects/openworld/gray button 96px.psd", 'cornerRadius' : 16, 'borderWidth' : 1.0, } testLayer = createLayer(**layerDict) rootLayer.addSublayer_(testLayer) layerDict = { 'origin' : (420,120), 'size' : (120,120), 'zPosition' : 12, 'image_path' : "/Users/donb/projects/openworld/gray button 96px.psd", 'cornerRadius' : 16, 'borderWidth' : 1.0, } # # testLayer = createLayer(**layerDict) # rootLayer.addSublayer_(testLayer) # app = NSApp() applicationIconImage=app.applicationIconImage() layerDict['image']=applicationIconImage layerDict['origin']=(100,400) layerDict['size']=applicationIconImage.size() testLayer3 = createLayer( **layerDict) rootLayer.addSublayer_(testLayer3) # printB("testLayer3", testLayer3 ) # frame = bounds for origin (0,0)? # lake_picture_path = "/Library/Desktop Pictures/Lake.jpg" # theLakeImage = getImage(lake_picture_path) layerDict['origin']=(300,300) layerDict['image_path']="/Library/Desktop Pictures/Lake.jpg" del layerDict['image'] layerDict['size']=(300,300) testLayer2 = createLayer( **layerDict) rootLayer.addSublayer_(testLayer2) layerDict['origin']=(420,60) layerDict['text_string']="full-size and on the 1080p LCD" layerDict['zPosition'] = 20 layerDict['textColor']=NSColor.blackColor() del layerDict['image_path'] testLayer3 = createTextLayer( **layerDict) rootLayer.addSublayer_(testLayer3) whiteColor = CGColorCreateGenericRGB(0.0, 0.5, 1.0, 1.0) layerDict['textColor']=NSColor.whiteColor() layerDict['zPosition'] = 19 testLayer4 = createTextLayer(**layerDict) rootLayer.addSublayer_(testLayer4) blurFilter = CIFilter.filterWithName_("CIGaussianBlur") blurFilter.setDefaults() # blurFilter.setValue_forKey_( 2.0, "inputRadius" ) blurFilter.setValue_forKey_( .75, "inputRadius" ) blurFilter.setName_("blur") testLayer4.setFilters_( [blurFilter] ) # // init ivars # _slides = [[NSMutableArray array] retain]; # self.selectionIndexes = [NSIndexSet indexSet]; # // init the input trackers # [self _initTrackers]; # // register for dragging # [self registerForDraggedTypes:[NSArray arrayWithObject:(NSString *)kUTTypeFileURL]]; # // we want touch events self.setAcceptsTouchEvents_(objc.YES) return result
from AppKit import NSColor, NSImage, NSAffineTransform, NSCompositeSourceOver, \ NSRectFillUsingOperation MenuImageBackgroundColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0.35, 0.35, 0.37, 1.0) MenuImageGlyphColor = NSColor.whiteColor() def MenuImageRepresentationFactory(glyph): font = glyph.font cellHeight = 60.0 cellWidth = 60.0 imageSize = (cellWidth, cellHeight) availableHeight = cellHeight * .6 yBuffer = int((cellHeight - availableHeight) / 2) upm = font.info.unitsPerEm descender = font.info.descender scale = availableHeight / upm glyphWidth = glyph.width * scale centerOffset = (cellWidth - glyphWidth) * 0.5 path = glyph.getRepresentation("defconAppKit.NSBezierPath") image = NSImage.alloc().initWithSize_(imageSize) image.lockFocus() bounds = ((0, 0), imageSize) MenuImageBackgroundColor.set() NSRectFillUsingOperation(bounds, NSCompositeSourceOver) transform = NSAffineTransform.transform() transform.translateXBy_yBy_(centerOffset, yBuffer) transform.scaleXBy_yBy_(scale, scale) transform.translateXBy_yBy_(0, abs(descender)) transform.concat()
from AppKit import NSFontAttributeName, NSFont, NSForegroundColorAttributeName, NSColor, NSActionCell, \ NSBezierPath, NSAttributedString pillTextAttributes = { NSFontAttributeName: NSFont.fontWithName_size_("Helvetica Bold", 12.0), NSForegroundColorAttributeName: NSColor.whiteColor() } pillColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.75, .75, .8, 1.0) class DefconAppKitPillCell(NSActionCell): def setColor_(self, color): self._color = color def drawWithFrame_inView_(self, frame, view): row = view.selectedRow() columnCount = len(view.tableColumns()) frames = [view.frameOfCellAtColumn_row_(i, row) for i in xrange(columnCount)] selected = frame in frames (x, y), (w, h) = frame y += 1 h -= 2 if selected: pillTextAttributes[NSForegroundColorAttributeName] = self._color foregroundColor = NSColor.whiteColor()
def initWithFrame_(self, frame): self = super(ColorView, self).initWithFrame_(frame) if not self: return self.color = NSColor.whiteColor() return self