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
def __init__(self, style='standard', zoomable=None, **kwds): # We ignore zoomable, since it's the same as resizable. self._style = style options = dict(_default_options_for_style[style]) for option in ['movable', 'closable', 'hidable', 'resizable']: if option in kwds: options[option] = kwds.pop(option) self._ns_style_mask = self._ns_window_style_mask(**options) if style == 'fullscreen': ns_rect = NSScreen.mainScreen().frame() else: ns_rect = NSRect(NSPoint(0, 0), NSSize(self._default_width, self._default_height)) ns_window = PyGUI_NSWindow.alloc() ns_window.initWithContentRect_styleMask_backing_defer_( ns_rect, self._ns_style_mask, AppKit.NSBackingStoreBuffered, True) ns_content = PyGUI_NS_ContentView.alloc() ns_content.initWithFrame_(NSRect(NSPoint(0, 0), NSSize(0, 0))) ns_content.pygui_component = self ns_window.setContentView_(ns_content) ns_window.setAcceptsMouseMovedEvents_(True) ns_window.setDelegate_(ns_window) ns_window.pygui_component = self self._ns_window = ns_window GWindow.__init__(self, style=style, closable=options['closable'], _ns_view=ns_window.contentView(), _ns_responder=ns_window, _ns_set_autoresizing_mask=False, **kwds)
def _create_ns_textfield(self, editable, text, font, multiline = False, password = False, border = False, padding = (0, 0)): self._ns_is_password = password if password: ns_class = PyGUI_NSSecureTextField else: ns_class = PyGUI_NSTextField ns_frame = NSRect(NSPoint(0, 0), NSSize(20, 10)) ns_textfield = ns_class.alloc().initWithFrame_(ns_frame) ns_textfield.pygui_component = self if multiline and not password: ns_textfield.pygui_multiline = True # Be careful here -- calling setBordered_ seems to affect isBezeled as well if editable: ns_textfield.setBezeled_(border) else: ns_textfield.setBordered_(border) if not editable: ns_textfield.setDrawsBackground_(False) ns_textfield.setEditable_(editable) ns_textfield.setSelectable_(editable) ns_textfield.setFont_(font._ns_font) ns_textfield.setStringValue_(text) ns_size_to_fit(ns_textfield, padding = padding) return ns_textfield
def buildNotdef(thisFont, override=False): questionGlyph = thisFont.glyphs["question"] if not questionGlyph: print( "⚠️ Error building .notdef: No question mark is available in your font. Cannot create .notdef." ) else: name = ".notdef" notdefGlyph = createGlyph(thisFont, name, None, override=override) if notdefGlyph: sourceLayer = questionGlyph.layers[0] area = areaOfLayer(sourceLayer) for qLayer in questionGlyph.layers: if qLayer.isMasterLayer or qLayer.isSpecialLayer: qArea = areaOfLayer(qLayer) if qArea > area: sourceLayer = qLayer area = qArea if sourceLayer: # Build .notdef from question mark and circle: questionmarkLayer = sourceLayer.copyDecomposedLayer() scaleLayerByFactor(questionmarkLayer, 0.8) qOrigin = questionmarkLayer.bounds.origin qWidth = questionmarkLayer.bounds.size.width qHeight = questionmarkLayer.bounds.size.height qCenter = NSPoint(qOrigin.x + 0.5 * qWidth, qOrigin.y + 0.5 * qHeight) side = max((qWidth, qHeight)) * 1.5 circleRect = NSRect( NSPoint(qCenter.x - 0.5 * side, qCenter.y - 0.5 * side), NSSize(side, side)) circle = circleInsideRect(circleRect) try: # GLYPHS 3 questionmarkLayer.shapes.append(circle) except: # GLYPHS 2 questionmarkLayer.paths.append(circle) questionmarkLayer.correctPathDirection() # Create glyph: notdefGlyph.leftMetricsKey = "=40" notdefGlyph.rightMetricsKey = "=|" for masterID in [m.id for m in thisFont.masters]: notdefLayer = notdefGlyph.layers[masterID] for thisPath in questionmarkLayer.paths: try: # GLYPHS 3: notdefLayer.shapes.append(thisPath.copy()) except: # GLYPHS 2: notdefLayer.paths.append(thisPath.copy()) notdefLayer.syncMetrics() else: print( "⚠️ Error building .notdef: Could not determine source layer of glyph 'question'." )
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
def fill(self): ns = self._ns_path # self._fillcolor._ns_color.set() if self._fillcolor.image: ns.addClip() self._fillcolor._ns_color.drawInRect_fromRect_operation_fraction_( NSRect((self.minx, self.miny), (self.maxx - self.minx, self.maxy - self.miny)), NSZeroRect, NSCompositeSourceOver, 1.0) else: self._fillcolor._ns_color.setFill() ns.fill()
def windowWillReturnFieldEditor_toObject_(self, ns_window, ns_obj): # Return special field editor for newline handling in text fields. #print "Window: Field editor requested for", object.__repr__(ns_obj) ### #editor = self.pygui_field_editor #if not editor: try: editor = self.pygui_field_editor except AttributeError: #print "...creating new field editor" ### editor = PyGUI_FieldEditor.alloc().initWithFrame_( NSRect(NSPoint(0, 0), NSSize(0, 0))) editor.setFieldEditor_(True) editor.setDrawsBackground_(False) self.pygui_field_editor = editor return editor
def drawRect_(self, rect): """ we raw the background gradient and graph outline then clip the inner rect and draw the bars """ bounds = self.bounds() # get our view bounds insetBounds = NSInsetRect(bounds, 2, 2) # set the inside ortion r = NSBezierPath.bezierPathWithRect_( bounds) # create a new bezier rect self.grad.drawInBezierPath_angle_(r, 90.0) # and draw gradient in it self.borderColor.set() # set border to white NSBezierPath.setDefaultLineWidth_(1.0) # set line width for outline NSBezierPath.strokeRect_(bounds) # draw outline NSBezierPath.clipRect_(insetBounds) # set the clipping path insetBounds.size.height -= 2 # leave room at the top (purely my personal asthetic if self.dataQueue: barRect = NSRect() # init the rect # find out the max value so we can scale the graph maxB = max(max(self.dataQueue), self.minHeigth or 1) # disable anti-aliasing since it looks bad shouldAA = NSGraphicsContext.currentContext().shouldAntialias() NSGraphicsContext.currentContext().setShouldAntialias_(False) # draw each bar barRect.origin.x = insetBounds.size.width - self.lineWidth + 2 for sample in reversed(self.dataQueue): # set drawing color if sample >= self.limit: self.lineColorAboveLimit.set() else: self.lineColor.set() barRect.origin.y = insetBounds.origin.y barRect.size.width = self.lineWidth barRect.size.height = ( (int(sample) * insetBounds.size.height) / maxB) NSBezierPath.fillRect_(barRect) barRect.origin.x = barRect.origin.x - self.lineWidth - self.lineSpacing NSGraphicsContext.currentContext().setShouldAntialias_(shouldAA)
def background(self, layer): NSColor.colorWithRed_green_blue_alpha_(*self.color).set() focusRect = NSRect( NSPoint(0.0, layer.master.descender), NSSize(layer.width, layer.master.ascender - layer.master.descender), ) focusField = NSBezierPath.bezierPathWithRect_(focusRect) italicAngle = layer.master.italicAngle skewOriginHeight = layer.master.xHeight / 2 shiftX = math.tan(math.radians(italicAngle)) * skewOriginHeight * -1 transform = self.transform(skew=italicAngle, shiftX=shiftX) focusField.transformUsingAffineTransform_(transform) focusField.appendBezierPath_( layer.completeBezierPath.bezierPathByReversingPath()) focusField.fill()
if not thisFont.glyphs[".notdef"]: if thisFont.glyphs["question"]: sourceMasterID = thisFont.masters[len(thisFont.masters) - 1].id sourceLayer = thisFont.glyphs["question"].layers[sourceMasterID] if sourceLayer: # Build .notdef from question mark and circle: questionmarkLayer = sourceLayer.copyDecomposedLayer() scaleLayerByFactor(questionmarkLayer, 0.8) qOrigin = questionmarkLayer.bounds.origin qWidth = questionmarkLayer.bounds.size.width qHeight = questionmarkLayer.bounds.size.height qCenter = NSPoint(qOrigin.x + 0.5 * qWidth, qOrigin.y + 0.5 * qHeight) side = max((qWidth, qHeight)) * 1.5 circleRect = NSRect( NSPoint(qCenter.x - 0.5 * side, qCenter.y - 0.5 * side), NSSize(side, side)) circle = circleInsideRect(circleRect) questionmarkLayer.paths.append(circle) questionmarkLayer.correctPathDirection() # Create glyph: notdefName = ".notdef" notdefGlyph = GSGlyph() notdefGlyph.name = notdefName thisFont.glyphs.append(notdefGlyph) if thisFont.glyphs[notdefName]: print("%s added successfully" % notdefName) print(thisFont.glyphs[notdefName]) print(len(thisFont.glyphs[notdefName].layers)) for masterID in [m.id for m in thisFont.masters]:
class Window(GWindow): # _ns_window PyGUI_NSWindow # _ns_style_mask int def __init__(self, style='standard', zoomable=None, **kwds): # We ignore zoomable, since it's the same as resizable. self._style = style options = dict(_default_options_for_style[style]) for option in ['movable', 'closable', 'hidable', 'resizable']: if option in kwds: options[option] = kwds.pop(option) self._ns_style_mask = self._ns_window_style_mask(**options) if style == 'fullscreen': ns_rect = NSScreen.mainScreen().frame() else: ns_rect = NSRect(NSPoint(0, 0), NSSize(self._default_width, self._default_height)) ns_window = PyGUI_NSWindow.alloc() ns_window.initWithContentRect_styleMask_backing_defer_( ns_rect, self._ns_style_mask, AppKit.NSBackingStoreBuffered, True) ns_content = PyGUI_NS_ContentView.alloc() ns_content.initWithFrame_(NSRect(NSPoint(0, 0), NSSize(0, 0))) ns_content.pygui_component = self ns_window.setContentView_(ns_content) ns_window.setAcceptsMouseMovedEvents_(True) ns_window.setDelegate_(ns_window) ns_window.pygui_component = self self._ns_window = ns_window GWindow.__init__(self, style=style, closable=options['closable'], _ns_view=ns_window.contentView(), _ns_responder=ns_window, _ns_set_autoresizing_mask=False, **kwds) def _ns_window_style_mask(self, movable, closable, hidable, resizable): if movable or closable or hidable or resizable: mask = AppKit.NSTitledWindowMask if closable: mask |= AppKit.NSClosableWindowMask if hidable: mask |= AppKit.NSMiniaturizableWindowMask if resizable: mask |= AppKit.NSResizableWindowMask else: mask = AppKit.NSBorderlessWindowMask return mask def destroy(self): #print "Window.destroy:", self ### self.hide() app = application() if app._ns_key_window is self: app._ns_key_window = None GWindow.destroy(self) # We can't drop all references to the NSWindow yet, because this method # can be called from its windowShouldClose: method, and allowing an # NSWindow to be released while executing one of its own methods seems # to be a very bad idea (Cocoa hangs). So we hide the NSWindow and store # a reference to it in a global. It will be released the next time a # window is closed and the global is re-used. global _ns_zombie_window _ns_zombie_window = self._ns_window self._ns_window.pygui_component = None #self._ns_window = None def get_bounds(self): ns_window = self._ns_window ns_frame = ns_window.frame() (l, y), (w, h) = ns_window.contentRectForFrameRect_styleMask_( ns_frame, self._ns_style_mask) b = Globals.ns_screen_height - y result = (l, b - h, l + w, b) return result def set_bounds(self, (l, t, r, b)): y = Globals.ns_screen_height - b ns_rect = NSRect(NSPoint(l, y), NSSize(r - l, b - t)) ns_window = self._ns_window ns_frame = ns_window.frameRectForContentRect_styleMask_( ns_rect, self._ns_style_mask) ns_window.setFrame_display_(ns_frame, False)
def generateImage(self): size = self.imageSize dx, dy = self.dx, self.dy image = self.texture.image if usePyObjC: from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage from Foundation import NSRect rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, int(size), int(size), 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 32, ) context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep) oldContext = NSGraphicsContext.currentContext() NSGraphicsContext.setCurrentContext_(context) image.drawInRect_fromRect_operation_fraction_( NSRect((0, 0), (size, size)), NSRect((0, 0), image.size()), NSCompositeCopy, 1.0, ) NSGraphicsContext.setCurrentContext_(oldContext) image = NSImage.alloc().initWithSize_((size, size)) image.addRepresentation_(rep) rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, int(size), int(size), 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 32, ) context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep) oldContext = NSGraphicsContext.currentContext() NSGraphicsContext.setCurrentContext_(context) srcPoints = ( (0, 0), (size - dx, 0), (0, size - dy), (size - dx, size - dy), ) dstPoints = ( (dx, dy), (0, dy), (dx, 0), (0, 0), ) sizes = ( (size - dx, size - dy), (dx, size - dy), (size - dx, dy), (dx, dy), ) for src, dst, siz in zip(srcPoints, dstPoints, sizes): if siz[0] > 0 and siz[1] > 0: # not sure if Cocoa appreciates trying to draw an image with invalid bounds image.drawInRect_fromRect_operation_fraction_( NSRect(dst, siz), NSRect(src, siz), NSCompositeCopy, 1.0, ) NSGraphicsContext.setCurrentContext_(oldContext) result = NSImage.alloc().initWithSize_((size, size)) result.addRepresentation_(rep) else: import wx try: image = image.Scale(size, size, wx.IMAGE_QUALITY_HIGH) except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH image = image.Scale(size, size) result = wx.BitmapFromImage(image) return result