def __init__(self, posSize, titles, isVertical=True, callback=None, sizeStyle="regular"): self._setupView(self.nsMatrixClass, posSize, callback=callback) self._isVertical = isVertical matrix = self._nsObject matrix.setMode_(NSRadioModeMatrix) matrix.setCellClass_(self.nsCellClass) # XXX! this does not work for vertical radio groups! matrix.setAutosizesCells_(True) # we handle the control size setting here # since the actual NS object is a NSMatrix cellSizeStyle = _sizeStyleMap[sizeStyle] font = NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(cellSizeStyle)) # intercell spacing and cell spacing are based on the sizeStyle if sizeStyle == "regular": matrix.setIntercellSpacing_((4.0, 2.0)) matrix.setCellSize_((posSize[2], 18)) elif sizeStyle == "small": matrix.setIntercellSpacing_((3.5, 2.0)) matrix.setCellSize_((posSize[2], 15)) elif sizeStyle == "mini": matrix.setIntercellSpacing_((3.0, 2.0)) matrix.setCellSize_((posSize[2], 12)) else: raise ValueError("sizeStyle must be 'regular', 'small' or 'mini'") for _ in range(len(titles)): if isVertical: matrix.addRow() else: matrix.addColumn() for title, cell in zip(titles, matrix.cells()): cell.setButtonType_(NSRadioButton) cell.setTitle_(title) cell.setControlSize_(cellSizeStyle) cell.setFont_(font)
def init(self, wizard): self = super(SetupWizardWindow, self).initWithContentRect_styleMask_backing_defer_(NSRect((0, 0), (580, 500)), NSTitledWindowMask | NSClosableWindowMask, NSBackingStoreBuffered, NO) if self is not None: self._wizard = wizard self._dropbox_app = wizard.dropbox_app self.setReleasedWhenClosed_(NO) self.center() self.setLevel_(NSFloatingWindowLevel) self._system_font = NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(NSRegularControlSize)) self._small_system_font = NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(NSSmallControlSize)) self.setTitle_(SetupWizardStrings.window_title) self._renderers = {Button: self._create_button, CenteredMultiControlLine: self._create_centered_multi_control_line, Checkbox: self._create_checkbox, Choice: self._create_choice, CreditCardType: self._create_credit_card_type, Date: self._create_date, ExampleText: self._create_example_text, FancyRadioGroup: self._create_fancy_radio_group, FlagChoice: self._create_flag_choice, HelpButton: self._create_help_button, Image: self._create_image, LocationChanger: self._create_location_changer, MultiControlLine: self._create_multi_control_line, MultiControlLineSimple: self._create_multi_control_line, TextBlock: self._create_text_block, TextInput: self._create_text_input, PlanChoices: self._create_plan_choices, RadioGroup: self._create_radio_group, SelectiveSync: self._create_selective_sync, Spacer: self._create_spacer} self._buttons = {} return self
def __init__( self ): # Window 'self.w': windowWidth = 400 windowHeight = 300 windowWidthResize = 1000 # user can resize width by this value windowHeightResize = 1000 # user can resize height by this value self.w = vanilla.FloatingWindow( ( windowWidth, windowHeight ), # default window size "Merge Suffixed Glyphs into Color Layers", # window title minSize = ( windowWidth, windowHeight ), # minimum size (for resizing) maxSize = ( windowWidth + windowWidthResize, windowHeight + windowHeightResize ), # maximum size (for resizing) autosaveName = "com.mekkablue.MergeSuffixedGlyphsIntoColorLayers.mainwindow" # stores last window position and size ) # UI elements: linePos, inset, lineHeight = 12, 15, 22 self.w.descriptionText = vanilla.TextBox( (inset, linePos+2, -inset, 14), "Merge suffixed glyphs into the following color indexes:", sizeStyle='small', selectable=True ) linePos += lineHeight self.w.indexToSuffix = vanilla.TextEditor( (2, linePos, -2, -110), "# Syntax: CPAL index = glyph name suffix\n# list them in chronological order (bottom-up)\n# use hashtags for comments\n0=.shadow\n2=.body\n1=.front", callback=self.SavePreferences, checksSpelling=False ) #self.w.indexToSuffix.getNSTextEditor().setToolTip_("Syntax: colorindex=.suffix, use hashtags for comments. List them in chronological order (bottom-up). Example:\n0=.shadow\n2=.body\n1=.front") self.w.indexToSuffix.getNSScrollView().setHasVerticalScroller_(1) self.w.indexToSuffix.getNSScrollView().setHasHorizontalScroller_(1) self.w.indexToSuffix.getNSScrollView().setRulersVisible_(0) legibleFont = NSFont.legibileFontOfSize_(NSFont.systemFontSize()) textView = self.w.indexToSuffix.getNSTextView() textView.setFont_(legibleFont) textView.setHorizontallyResizable_(1) textView.setVerticallyResizable_(1) textView.setAutomaticDataDetectionEnabled_(1) textView.setAutomaticLinkDetectionEnabled_(1) textView.setDisplaysLinkToolTips_(1) textSize = textView.minSize() textSize.width = 1000 textView.setMinSize_(textSize) linePos = -105 self.w.disableSuffixedGlyphs = vanilla.CheckBox( (inset, linePos-1, -inset, 20), "Deactivate export for glyphs with listed suffixes", value=True, callback=self.SavePreferences, sizeStyle='small' ) linePos += lineHeight self.w.deletePreexistingColorLayers = vanilla.CheckBox( (inset, linePos-1, -inset, 20), "Delete preexisting Color layers in target glyphs", value=True, callback=self.SavePreferences, sizeStyle='small' ) linePos += lineHeight self.w.processCompleteFont = vanilla.CheckBox( (inset, linePos-1, -inset, 20), "Process complete font (otherwise only add into selected glyphs)", value=False, callback=self.SavePreferences, sizeStyle='small' ) linePos += lineHeight # Run Button: self.w.runButton = vanilla.Button( (-80-inset, -20-inset, -inset, -inset), "Merge", sizeStyle='regular', callback=self.MergeSuffixedGlyphsIntoColorLayersMain ) # self.w.setDefaultButton( self.w.runButton ) # Load Settings: if not self.LoadPreferences(): print("Note: 'Merge Suffixed Glyphs into Color Layers' could not load preferences. Will resort to defaults") # Open window and focus on it: self.w.open() self.w.makeKey()
def __init__(self, posSize, title=None, fillColor=None, borderColor=None, borderWidth=None, cornerRadius=None): self._setupView(self.nsBoxClass, posSize) if title: self._nsObject.setTitle_(title) if osVersionCurrent < osVersion10_10: self._nsObject.titleCell().setTextColor_(NSColor.blackColor()) font = NSFont.systemFontOfSize_( NSFont.systemFontSizeForControlSize_(NSSmallControlSize)) self._nsObject.setTitleFont_(font) else: self._nsObject.setTitlePosition_(NSNoTitle) if fillColor is not None: self.setFillColor(fillColor) if borderColor is not None: self.setBorderColor(borderColor) if borderWidth is not None: self.setBorderWidth(borderWidth) if cornerRadius is not None: self.setCornerRadius(cornerRadius)
def drawFontVerticalMetrics(glyph, scale, rect, drawLines=True, drawText=True, color=None, backgroundColor=None, flipped=False): font = glyph.font if font is None: return if color is None: color = getDefaultColor("fontVerticalMetrics") if backgroundColor is None: backgroundColor = getDefaultColor("background") color.set() # gather y positions toDraw = ( ("Descender", "descender"), ("X Height", "xHeight"), ("Cap Height", "capHeight"), ("Ascender", "ascender") ) toDraw = [(name, getattr(font.info, attr)) for name, attr in toDraw if getattr(font.info, attr) is not None] toDraw.append(("Baseline", 0)) positions = {} for name, position in toDraw: if position not in positions: positions[position] = [] positions[position].append(name) # create lines xMin = rect[0][0] xMax = xMin + rect[1][0] lines = [] for y, names in sorted(positions.items()): names = ", ".join(names) lines.append(((xMin, y), (xMax, y), names)) # draw lines if drawLines: lineWidth = 1.0 * scale for pt1, pt2, names in lines: drawLine(pt1, pt2, lineWidth=lineWidth) # draw text if drawText: fontSize = 9 shadow = NSShadow.shadow() shadow.setShadowColor_(backgroundColor) shadow.setShadowBlurRadius_(5) shadow.setShadowOffset_((0, 0)) attributes = { NSFontAttributeName: NSFont.systemFontOfSize_(fontSize), NSForegroundColorAttributeName: color } glowAttributes = { NSFontAttributeName: NSFont.systemFontOfSize_(fontSize), NSForegroundColorAttributeName: color, NSStrokeColorAttributeName: backgroundColor, NSStrokeWidthAttributeName: 25, NSShadowAttributeName: shadow } for pt1, pt2, names in lines: x, y = pt1 x += 5 * scale y -= (fontSize / 2.0) * scale drawTextAtPoint(names, (x, y), scale, glowAttributes, flipped=flipped) drawTextAtPoint(names, (x, y), scale, attributes, flipped=flipped)
def init(self): self = super(LineNumberNSRulerView, self).init() self._font = NSFont.labelFontOfSize_(NSFont.systemFontSizeForControlSize_(NSMiniControlSize)) self._textColor = NSColor.colorWithCalibratedWhite_alpha_(.42, 1) self._rulerBackgroundColor = None self._lineIndices = None return self
def SmallTextListCell(editable=False): cell = NSTextFieldCell.alloc().init() size = NSSmallControlSize cell.setControlSize_(size) font = NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(size)) cell.setFont_(font) cell.setEditable_(editable) return cell
def settings(self): self.name = Glyphs.localize({ 'en': 'Alignment', 'de': 'Ausrichtung', 'es': 'Alineación', 'fr': 'Alignement', 'pt': 'Alinhamento', }) width = 150 self.marginTop = 7 self.marginLeft = 7 self.lineSpacing = 21 smallSize = NSFont.systemFontSizeForControlSize_( NSFont.smallSystemFontSize() ) textFieldHeight = smallSize + 7 textFieldWidth = 50 # lockHeight = textFieldHeight innerWidth = width - 2 * self.marginLeft height = ( MAX_ZONES + 4 ) * self.lineSpacing + self.marginTop * 3 self.posx_TextField = width - textFieldWidth - self.marginLeft # Create Vanilla window and group with controls self.paletteView = Window( (width, height), minSize=(width, height - 10), maxSize=(width, height + 200 ) ) self.paletteView.group = Group( (0, 0, width, height ) ) posy = self.marginTop # set up fields for center headlineBbox = NSAttributedString.alloc().initWithString_attributes_( 'Bounding box', { NSFontAttributeName:NSFont.boldSystemFontOfSize_( smallSize ) } ) self.paletteView.group.headlineBbox = TextBox( ( 10, posy, innerWidth, 18 ), headlineBbox, sizeStyle='small' ) posy += self.lineSpacing self.paletteView.group.centerXLabel = TextBox( ( 10, posy + 3, innerWidth, 18 ), 'center x', sizeStyle='small' ) self.posy_centerX = posy # self.paletteView.group.lockX = ImageButton( ( self.posx_TextField - lockHeight - 5, posy, lockHeight, lockHeight ), imageNamed='GSLockUnlockedTemplate', bordered=False, imagePosition='top', callback=self.lockCallback, sizeStyle='regular' ) # self.lockXlocked = False self.paletteView.group.centerX = ArrowEditText( ( self.posx_TextField, posy, textFieldWidth, textFieldHeight ), callback=self.editTextCallback, continuous=False, readOnly=False, formatter=None, placeholder='multiple', sizeStyle='small' ) posy += self.lineSpacing self.paletteView.group.centerYLabel = TextBox( ( 10, posy + 3, innerWidth, 18 ), 'center y', sizeStyle='small' ) self.posy_centerY = posy # self.paletteView.group.lockY = ImageButton( ( self.posx_TextField - lockHeight - 5, posy, lockHeight, lockHeight ), imageNamed='GSLockUnlockedTemplate', bordered=False, imagePosition='top', callback=self.lockCallback, sizeStyle='regular' ) # self.lockYlocked = False self.paletteView.group.centerY = ArrowEditText( ( self.posx_TextField, posy, textFieldWidth, textFieldHeight ), callback=self.editTextCallback, continuous=False, readOnly=False, formatter=None, placeholder='multiple', sizeStyle='small' ) posy += self.lineSpacing + self.marginTop # set up fields for overshoot headlineOvershoot = NSAttributedString.alloc().initWithString_attributes_( 'Overshoot', { NSFontAttributeName:NSFont.boldSystemFontOfSize_( NSFont.systemFontSizeForControlSize_( smallSize ) ) } ) self.paletteView.group.headlineOvershoot = TextBox( ( 10, posy, innerWidth, 18 ), headlineOvershoot, sizeStyle='small' ) posy += self.lineSpacing self.paletteView.group, 'lineAbove', HorizontalLine( ( self.marginLeft, posy - 3, innerWidth, 1 ) ) for i in range( MAX_ZONES ): setattr( self.paletteView.group, 'name' + str( i ), TextBox( ( 10, posy, innerWidth, 18 ), '', sizeStyle='small' ) ) setattr( self.paletteView.group, 'value' + str( i ), TextBox( ( self.posx_TextField, posy, textFieldWidth - 3, textFieldHeight ), '', sizeStyle='small', alignment='right' ) ) posy += self.lineSpacing setattr( self.paletteView.group, 'line' + str( i ), HorizontalLine( ( self.marginLeft, posy - 3, innerWidth, 1 ) ) ) # set dialog to NSView self.dialog = self.paletteView.group.getNSView() # set self.font self.font = None windowController = self.windowController() if windowController: self.font = windowController.document().font
def init(self): self = super(LineNumberNSRulerView, self).init() self._font = NSFont.labelFontOfSize_( NSFont.systemFontSizeForControlSize_(NSMiniControlSize)) self._textColor = NSColor.colorWithCalibratedWhite_alpha_(.42, 1) self._rulerBackgroundColor = None self._lineIndices = None return self
def text_Bold(text): size = NSRegularControlSize attrs = {} string = NSMutableAttributedString.alloc().initWithString_attributes_( text, attrs) attrs[NSFontAttributeName] = NSFont.boldSystemFontOfSize_( NSFont.systemFontSizeForControlSize_(size)) attributedString = NSMutableAttributedString.alloc( ).initWithString_attributes_(text, attrs) return attributedString
def __init__(self, posSize, title=None): self._setupView(self.nsBoxClass, posSize) if title: self._nsObject.setTitle_(title) if osVersionCurrent < osVersion10_10: self._nsObject.titleCell().setTextColor_(NSColor.blackColor()) font = NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(NSSmallControlSize)) self._nsObject.setTitleFont_(font) else: self._nsObject.setTitlePosition_(NSNoTitle)
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, posSize, title=None): self._setupView(self.nsBoxClass, posSize) if title: self._nsObject.setTitle_(title) if osVersionCurrent < osVersion10_10: self._nsObject.titleCell().setTextColor_(NSColor.blackColor()) font = NSFont.systemFontOfSize_( NSFont.systemFontSizeForControlSize_(NSSmallControlSize)) self._nsObject.setTitleFont_(font) else: self._nsObject.setTitlePosition_(NSNoTitle)
def text_Gray(text): size = NSRegularControlSize attrs = {} attrs[NSForegroundColorAttributeName] = NSColor.grayColor() string = NSMutableAttributedString.alloc().initWithString_attributes_( text, attrs) #attrs[NSFontAttributeName] = NSFont.boldSystemFontOfSize_(NSFont.systemFontSizeForControlSize_(size)) attrs[NSFontAttributeName] = NSFont.systemFontOfSize_( NSFont.systemFontSizeForControlSize_(size)) attributedString = NSMutableAttributedString.alloc( ).initWithString_attributes_(text, attrs) return attributedString
def initWithFrame_imageDir_(self, frame, imageDir): self = super(IntroView, self).initWithFrame_(frame) if not self: return None dropboxImage = NSImage.alloc().initWithContentsOfFile_(os.path.join(imageDir, u'box_stroked_150.png')) iW, iH = dropboxImage.size() newHeight = iH * 300.0 / iW self.dropboxViewFinalPosition = NSRect((25, frame.size[1] - 43 - newHeight), (300, newHeight)) self.dropboxView = ShadowedImage.alloc().initWithFrame_(self.dropboxViewFinalPosition) self.dropboxView.setImageScaling_(NSScaleToFit) self.dropboxView.setImage_(dropboxImage) self.dropboxView.setShadowColor_(NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 0.5)) self.dropboxView.setShadowOffset_((0.0, -2.0)) self.dropboxView.setShadowBlurRadius_(5.0) logoImage = NSImage.alloc().initWithContentsOfFile_(os.path.join(imageDir, u'dropboxlogo.png')) iW, iH = logoImage.size() newHeight = iH * 300.0 / iW self.logoViewFinalPosition = NSRect((25, frame.size[1] - 334 - newHeight), (300, newHeight)) self.logoView = NSImageView.alloc().initWithFrame_(self.logoViewFinalPosition) self.logoView.setImage_(logoImage) 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().mutableString().setString_(u'Version %s' % build_number.VERSION) self.versionView.textStorage().setFont_(NSFont.labelFontOfSize_(14)) self.versionView.layoutManager().glyphRangeForTextContainer_(self.versionView.textContainer()) textSize1 = self.versionView.layoutManager().usedRectForTextContainer_(self.versionView.textContainer()).size textAnchor1 = 5 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().mutableString().setString_(u'Copyright \xa9 2007-2010 Dropbox Inc.') self.versionView2.setFont_(NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(NSSmallControlSize))) self.versionView2.layoutManager().glyphRangeForTextContainer_(self.versionView2.textContainer()) textSize2 = self.versionView2.layoutManager().usedRectForTextContainer_(self.versionView2.textContainer()).size textAnchor2 = 4 bottomToLogoViewBaseline = self.logoView.frame().origin[1] + 17 textSeparation = 10 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) for _view in (self.dropboxView, self.logoView, self.versionView, self.versionView2): self.addSubview_(_view) return self
def __init__(self, font, size): self._max_size = NSMakeSize(sys.float_info.max, sys.float_info.max) self._options = 1 << 3 # NSStringDrawingOptions.NSStringDrawingUsesDeiceMetrics # https://developer.apple.com/documentation/uikit/nsstringdrawingoptions?language=objc if font == "<System>": nsfont = NSFont.systemFontOfSize_(size) else: nsfont = NSFont.fontWithName_size_(font, size) self._attributes = NSMutableDictionary.dictionary() self._attributes.setObject_forKey_(nsfont, NSFontAttributeName) self._terminator = '1' self._terminator_width = self._measure(self._terminator)
def _setFont(self, font): self.font.getNSTextField().setFont_(NSFont.fontWithName_size_(font.fontName(), 10)) size = font.pointSize() if size == int(size): size = int(size) s = u"%s %spt" % (font.displayName(), size) self.font.set(s)
def _drawBackground(self, infoDict): assert self.elementShape in SHAPE_OPTIONS glyph = infoDict['glyph'] currentTool = getActiveEventTool() view = currentTool.getNSView() textAttributes = { NSFontAttributeName: NSFont.systemFontOfSize_(bodySizeCaption), NSForegroundColorAttributeName: NSColor.blackColor() } # load data if point is selected if PLUGIN_KEY in glyph.lib: for eachContour in glyph: for eachPt in eachContour.points: if eachPt.selected is True and eachPt.type != 'offCurve' and eachPt.naked( ).uniqueID in glyph.lib[PLUGIN_KEY]: self.loadDataFromLib(glyph, eachPt.naked().uniqueID) # draw interpolateValued ovals if self.preview is True and PLUGIN_KEY in glyph.lib: self._drawElements(glyph, SUB_COLOR, 4, 'canvas') # draw master ovals if self.preview is True and PLUGIN_KEY in glyph.lib: for eachContour in glyph: for eachSegment in eachContour: ID = eachSegment.onCurve.naked().uniqueID if ID in glyph.lib[PLUGIN_KEY]: elementDict = glyph.lib[PLUGIN_KEY][ID] save() fill(*MASTER_COLOR) translate(eachSegment.onCurve.x, eachSegment.onCurve.y) rotate(elementDict['angle']) if self.elementShape == 'Oval': oval(-elementDict['width'] / 2., -elementDict['height'] / 2., elementDict['width'], elementDict['height']) else: rect(-elementDict['width'] / 2., -elementDict['height'] / 2., elementDict['width'], elementDict['height']) restore() # draw values if self.drawValues is True and PLUGIN_KEY in glyph.lib: for eachContour in glyph: for eachSegment in eachContour: ID = eachSegment.onCurve.naked().uniqueID if ID in glyph.lib[PLUGIN_KEY]: nibData = glyph.lib[PLUGIN_KEY][ID] values = '%s: %s\n%s: %s\n%s: %s' % ( 'width', nibData['width'], 'height', nibData['height'], 'angle', nibData['angle']) view._drawTextAtPoint( values, textAttributes, (eachSegment.onCurve.x, eachSegment.onCurve.y), yOffset=2.8 * bodySizeCaption)
def awakeFromNib(self): NSLog("Awake from nib.") self.setPreviewMode(True) self.bodyField.setDelegate_(self) self.urlField.setDelegate_(self) self.titleField.setDelegate_(self) # Style the bodyField. self.bodyField.setFont_(NSFont.fontWithName_size_("Monaco", 13)) self.bodyField.setRichText_(NO) self.bodyField.setUsesFontPanel_(NO) # Authenticate to twitter if we can. if self.twitter.is_authenticated(): self.twitter.login() self.twitterCheckbox.setState_(NSOnState) self.ltp.syndicators.append(self.twitter) # Authenticate to G+ if we can. if self.gplus.is_authenticated(): self.gplus.login() self.gplusCheckbox.setState_(NSOnState) self.ltp.syndicators.append(self.gplus) # Listen to the NSApplicationWillTerminateNotification. center = NSNotificationCenter.defaultCenter() center.addObserver_selector_name_object_(self, "applicationWillTerminateNotification:", NSApplicationWillTerminateNotification, None) self.setupStatusBar() self.didPublish = False self.didPreview = False
def __init__(self): GObject.GObject.__init__(self) self.props.margin = 0 self.props.spacing = 6 # On OSX, make the font slightly smaller for status bar try: from AppKit import NSFont from gi.repository import Pango system_font = NSFont.systemFontOfSize_(9) self.modify_font( Pango.FontDescription(system_font.displayName() + " 9")) except: pass hbox = self.get_message_area() label = hbox.get_children()[0] hbox.props.spacing = 6 label.props.ellipsize = Pango.EllipsizeMode.NONE hbox.remove(label) hbox.pack_end(label, False, True, 0) self.box_box = Gtk.HBox(homogeneous=False, spacing=6) self.pack_end(self.box_box, False, True, 0) self.box_box.pack_end(self.construct_line_display(), False, True, 0) self.box_box.pack_end(self.construct_highlighting_selector(), False, True, 0) self.box_box.pack_end(self.construct_encoding_selector(), False, True, 0) self.box_box.show_all()
def drawTextAtPoint(self, text, textPosition, fontSize=10.0, fontColor=NSColor.blackColor(), align='bottomleft'): """ Use self.drawTextAtPoint("blabla", myNSPoint) to display left-aligned text at myNSPoint. """ try: alignment = { 'topleft': 6, 'topcenter': 7, 'topright': 8, 'left': 3, 'center': 4, 'right': 5, 'bottomleft': 0, 'bottomcenter': 1, 'bottomright': 2 } currentZoom = self.getScale() fontAttributes = { NSFontAttributeName: NSFont.labelFontOfSize_(fontSize / currentZoom), NSForegroundColorAttributeName: fontColor} displayText = NSAttributedString.alloc().initWithString_attributes_(unicode(text), fontAttributes) textAlignment = alignment[align] # top left: 6, top center: 7, top right: 8, center left: 3, center center: 4, center right: 5, bottom left: 0, bottom center: 1, bottom right: 2 displayText.drawAtPoint_alignment_(textPosition, textAlignment) except: self.logError(traceback.format_exc())
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 __init__(self): # Window 'self.w': edY = 200 txY = 14 spX = 10 spY = 5 btnX = 250 btnY = 20 windowWidth = 350 windowHeight = edY * 2 + spY * 6 + txY * 2 + btnY + 14 self.w = vanilla.FloatingWindow( (windowWidth, windowHeight), # default window size "Analyse Manuscript", # window title autosaveName= "com.Tosche.AnalyseManuscript.mainwindow" # stores last window position and size ) # UI elements: self.w.text1 = vanilla.TextBox((spX, spY, -spX, txY), 'Paste your text below...', sizeStyle='small') self.w.dump = vanilla.TextEditor((spX, spY * 2 + txY, -spX, edY), "", callback=self.updateChar) self.w.text2 = vanilla.TextBox((spX, spY * 3 + txY + edY, -spX, txY), "0 Unicode characters", sizeStyle='small') self.w.chars = vanilla.TextEditor( (spX, spY * 4 + txY * 2 + edY, -spX, edY), "", readOnly=True) self.w.chars._textView.setFont_(NSFont.fontWithName_size_("Menlo", 12)) self.w.dump._textView.setAutomaticSpellingCorrectionEnabled_(False) self.w.dump._textView.setAutomaticTextReplacementEnabled_(False) self.w.dump._textView.setContinuousSpellCheckingEnabled_(False) self.w.dump._textView.setGrammarCheckingEnabled_(False) self.w.dump._textView.setAutomaticQuoteSubstitutionEnabled_(False) # Run Button: self.w.markPopup = vanilla.PopUpButton( (spX, -btnY - spY - 7, 70, -spY - 7), [ "Mark", "Red", "Orange", "Brown", "Yellow", "Light Green", "Dark Green", "Cyan", "Blue", "Purple", "Pink", "Light Grey", "Dark Grey" ], callback=self.markGlyphs) self.w.runButton = vanilla.Button( (-btnX - spX, -btnY - spY - 7, -spX, -spY - 7), "Add missing characters", sizeStyle='regular', callback=self.AnalyseManuscriptMain) self.w.setDefaultButton(self.w.runButton) # Open window and focus on it: self.w.open() menu = self.w.markPopup._nsObject.menu() menu.setAutoenablesItems_(False) menu.itemAtIndex_(0).setEnabled_(False) divider = NSMenuItem.separatorItem() menu.insertItem_atIndex_(divider, 1) self.w.makeKey()
def getFontPathOfFont(fontName): font = NSFont.fontWithName_size_(fontName, 25) if font is not None: fontRef = CTFontDescriptorCreateWithNameAndSize( font.fontName(), font.pointSize()) url = CTFontDescriptorCopyAttribute(fontRef, kCTFontURLAttribute) return url.path() return None
def _set_defaults(self): self._inner_padding = WIZARD_BOX_PADDING self.titleCell().setLineBreakMode_(NSLineBreakByWordWrapping) self.setTitleFont_(NSFont.boldSystemFontOfSize_(14)) self.titleCell().setTextColor_(Colors.black) self.titleCell().setAlignment_(NSLeftTextAlignment) self.setBackgroundColor_(Colors.setup_wizard_background) self.setBorderColor_(Colors.setup_wizard_border) self._resize_content_view()
def getFontPathOfFont(self, fontName): u"""Answer the path that is source of the given font name. Answer None if the font cannot be found.""" nsFont = NSFont.fontWithName_size_(fontName, 25) if nsFont is not None: fontRef = CTFontDescriptorCreateWithNameAndSize( nsFont.fontName(), nsFont.pointSize()) url = CTFontDescriptorCopyAttribute(fontRef, kCTFontURLAttribute) return url.path() return None
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 __init__( self ): # Window 'self.w': windowWidth = 300 windowHeight = 170 windowWidthResize = 500 # user can resize width by this value windowHeightResize = 0 # user can resize height by this value self.w = vanilla.FloatingWindow( ( windowWidth, windowHeight ), # default window size "Position Clicker", # window title minSize = ( windowWidth, windowHeight ), # minimum size (for resizing) maxSize = ( windowWidth + windowWidthResize, windowHeight + windowHeightResize ), # maximum size (for resizing) autosaveName = "com.mekkablue.PositionClicker.mainwindow" # stores last window position and size ) # UI elements: linePos, inset, lineHeight, indent = 12, 15, 22, 100 self.w.descriptionText = vanilla.TextBox( (inset, linePos, -inset, 14), "Report positional combos that do not click:", sizeStyle='small', selectable=True ) self.w.descriptionText.getNSTextField().setToolTip_("Clicking means that when two matching positional shapes follow each other (e.g. initial and final), they ‘click’, i.e., they share at least 2 point coordinates. Or whatever number is set in the minimal node count setting below.") linePos += lineHeight tooltip = "Reference glyph. Pick a medial glyph with paths for clicking. We recommend behDotless-ar.medi." self.w.referenceText = vanilla.TextBox( (inset, linePos+2, indent, 14), "Click with glyph", sizeStyle='small', selectable=True ) self.w.referenceText.getNSTextField().setToolTip_(tooltip) self.w.referenceGlyphName = vanilla.ComboBox( (inset+indent, linePos-4, -inset-23, 25), self.getAllMediGlyphNames(), callback=self.SavePreferences, sizeStyle='regular' ) self.w.referenceGlyphName.getNSComboBox().setFont_(NSFont.userFixedPitchFontOfSize_(11)) self.w.referenceGlyphName.getNSComboBox().setToolTip_(tooltip) self.w.updateButton = vanilla.SquareButton( (-inset-20, linePos-1, -inset, 18), "↺", sizeStyle='small', callback=self.updateReferenceGlyphs ) self.w.updateButton.getNSButton().setToolTip_("Update the list in the combo box with all .medi glyphs in the frontmost font.") linePos += lineHeight tooltip = "The amount of point coordinates that must be shared between two consecutive positional forms. E.g., if set to 2, an initial and a final shape must have two or more nodes exactly on top of each other when they follow each other." self.w.clickCountText = vanilla.TextBox( (inset, linePos+2, indent, 14), "Minimal node count", sizeStyle='small', selectable=True ) self.w.clickCount = vanilla.EditText( (inset+indent, linePos-1, -inset, 19), "2", callback=self.SavePreferences, sizeStyle='small' ) linePos += lineHeight self.w.includeNonExporting = vanilla.CheckBox( (inset, linePos-1, -inset, 20), "Include non-exporting glyphs", value=False, callback=self.SavePreferences, sizeStyle='small' ) self.w.includeNonExporting.getNSButton().setToolTip_("Will also measure glyphs that are set to not export.") linePos += lineHeight self.w.reuseTab = vanilla.CheckBox( (inset, linePos-1, -inset, 20), "Reuse current tab", value=False, callback=self.SavePreferences, sizeStyle='small' ) self.w.reuseTab.getNSButton().setToolTip_("Will use the current tab for output. Will open a new tab only if there is no Edit tab open already.") linePos += lineHeight # Run Button: self.w.runButton = vanilla.Button( (-100-inset, -20-inset, -inset, -inset), "Open Tab", sizeStyle='regular', callback=self.PositionClickerMain ) self.w.setDefaultButton( self.w.runButton ) # Load Settings: if not self.LoadPreferences(): print("Note: 'Position Clicker' could not load preferences. Will resort to defaults") # Open window and focus on it: self.w.open() self.w.makeKey()
def initWithDropboxApp_initialIgnoreList_takeAction_callback_remote_(self, dropbox_app, initial_ignore_list, take_action, callback, remote): self = super(SelectiveSyncView, self).initWithFrame_(NSZeroRect) if self is None: return self._initial_ignore_list = initial_ignore_list self._callback = callback self._take_action = take_action self._remote = remote self.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable) self._dropbox_app = dropbox_app self.initBrowser(self._remote) self.initButtons() f = NSFont.systemFontOfSize_(NSFont.smallSystemFontSize()) self.infoLabel = NSTextField.createLabelWithText_font_(selsync_strings.info, f) self.addSubview_(self.infoLabel) self.reloadInvalidState() self.layoutForWidth_(DEFAULT_ADVANCED_WIDTH if self.forest.advanced_view else DEFAULT_SIMPLE_WIDTH) return self
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 start(self): super(GlyphNameHUDControl, self).start() events.addObserver(self, "currentGlyphChangedCallback", "currentGlyphChanged") self.view.textBox = vanilla.TextBox((0, 0, 0, 0), "") textField = self.view.textBox.getNSTextField() font = NSFont.systemFontOfSize_(20) textField.setFont_(font) textField.setTextColor_(RoboHUDController().getForegroundColor())
def __init__(self, posSize, titles, isVertical=True, callback=None, sizeStyle="regular"): self._setupView(self.nsMatrixClass, posSize, callback=callback) self._isVertical = isVertical matrix = self._nsObject matrix.setMode_(NSRadioModeMatrix) matrix.setCellClass_(self.nsCellClass) # XXX! this does not work for vertical radio groups! matrix.setAutosizesCells_(True) # we handle the control size setting here # since the actual NS object is a NSMatrix cellSizeStyle = _sizeStyleMap[sizeStyle] font = NSFont.systemFontOfSize_( NSFont.systemFontSizeForControlSize_(cellSizeStyle)) # intercell spacing and cell spacing are based on the sizeStyle if posSize == "auto": w = 0 else: w = posSize[2] if sizeStyle == "regular": matrix.setIntercellSpacing_((4.0, 2.0)) matrix.setCellSize_((w, 18)) elif sizeStyle == "small": matrix.setIntercellSpacing_((3.5, 2.0)) matrix.setCellSize_((w, 15)) elif sizeStyle == "mini": matrix.setIntercellSpacing_((3.0, 2.0)) matrix.setCellSize_((w, 12)) else: raise ValueError("sizeStyle must be 'regular', 'small' or 'mini'") for _ in range(len(titles)): if isVertical: matrix.addRow() else: matrix.addColumn() for title, cell in zip(titles, matrix.cells()): cell.setButtonType_(NSRadioButton) cell.setTitle_(title) cell.setControlSize_(cellSizeStyle) cell.setFont_(font)
def main(): # "Skia-Regular 14.00 pt. P [] (0x7ff98cb0b410) fobj=0x7ff98cb0ad90, spc=3.50" font = NSFont.fontWithName_size_("HelveticaNeue-Medium",14.0) font = NSFont.fontWithName_size_("Avenir Next LT Pro Ultra Light Italic",14.0) print "font is", font print "font.displayName() is", font.displayName() # attributes = NSDictionary.dictionaryWithObjectsAndKeys_(font, NSFontAttributeName, None ) # print "attributes is", attributes s = "CGColorCreateGenericRGB(0.8, 0.8, 0.8, 0.4)" # print dir(NSAttributedString) # s2 = NSAttributedString.alloc().initWithString_attributes_(s, attributes) # # print "s2 is", s2 s3 = NSAttributedString.alloc().initWithString_attributes_(s, { "NSFont":font }) print "s3 is", s3 # , "s2 == s3", s2 == s3 print "s3.size() is", s3.size() # s3.size() is <NSSize width=293.0 height=21.0> cat = CATextLayer.alloc().init() cat.setString_(s3) # cat.setFont_(font) # cat.setFontSize_(font.pointSize() ) # necessary after setFont? s4 = cat.string() print "s4 is", s4, "s3 == s4", s3 == s4 print "cat.bounds() is", cat.frame()
def DrawText(font, fontsize, fontcolour, x, y, text): attributes = { NSFontAttributeName: NSFont.fontWithName_size_(font, fontsize), NSForegroundColorAttributeName: NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_( fontcolour[0], fontcolour[1], fontcolour[2], fontcolour[3], 1) } String = NSAttributedString.alloc().initWithString_attributes_( text, attributes) String.drawAtPoint_((x, y))
def drawCellHeaderText(self, rect): paragraph = NSMutableParagraphStyle.alloc().init() paragraph.setAlignment_(NSCenterTextAlignment) paragraph.setLineBreakMode_(NSLineBreakByTruncatingMiddle) attributes = { NSFontAttributeName: NSFont.systemFontOfSize_(10.0), NSForegroundColorAttributeName: NSColor.colorWithCalibratedRed_green_blue_alpha_(.22, .22, .27, 1.0), NSParagraphStyleAttributeName: paragraph, } text = NSAttributedString.alloc().initWithString_attributes_(self.glyph.name, attributes) text.drawInRect_(rect)
def __init__(self, posSize, text, callback=None): # there must be a callback as it triggers the creation of the delegate if callback is None: callback = self._fallbackCallback super(FeatureTextEditor, self).__init__(posSize, "", callback=callback) self._nsObject.setHasHorizontalScroller_(True) font = NSFont.fontWithName_size_("Monaco", 10) self._textView.setFont_(font) self._textView.setUsesFindPanel_(True) ## line numbers #ruler = DefconAppKitLineNumberView.alloc().init() #ruler.setClientView_(self._textView) #self._nsObject.setVerticalRulerView_(ruler) #self._nsObject.setHasHorizontalRuler_(False) #self._nsObject.setHasVerticalRuler_(True) #self._nsObject.setRulersVisible_(True) #notificationCenter = NSNotificationCenter.defaultCenter() #notificationCenter.addObserver_selector_name_object_( # ruler, "clientViewSelectionChanged:", NSTextViewDidChangeSelectionNotification, self._textView #) # colors self._mainColor = NSColor.blackColor() self._commentColor = NSColor.colorWithCalibratedWhite_alpha_(.6, 1) self._keywordColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( .8, 0, 0, 1) self._tokenColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( .8, .4, 0, 1) self._classNameColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( 0, 0, .8, 1) self._includeColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( .8, 0, .8, 1) self._stringColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( 0, .6, 0, 1) # build the placard placardW = 65 placardH = 16 self._placardJumps = [] self._placard = vanilla.Group((0, 0, placardW, placardH)) self._placard.featureJumpButton = PlacardPopUpButton( (0, 0, placardW, placardH), [], callback=self._placardFeatureSelectionCallback, sizeStyle="mini") self._nsObject.setPlacard_(self._placard.getNSView()) # registed for syntax coloring notifications self._programmaticallySettingText = False delegate = self._textViewDelegate delegate.vanillaWrapper = weakref.ref(self) notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver_selector_name_object_( self._textViewDelegate, "textStorageDidProcessEditing:", NSTextStorageDidProcessEditingNotification, self._textView.textStorage()) # set the text self.set(text)
def __init__( self ): # Window 'self.w': windowWidth = 350 windowHeight = 140 windowWidthResize = 100 # user can resize width by this value windowHeightResize = 0 # user can resize height by this value self.w = vanilla.FloatingWindow( ( windowWidth, windowHeight ), # default window size "Set Family Alignment Zones", # window title minSize = ( windowWidth, windowHeight ), # minimum size (for resizing) maxSize = ( windowWidth + windowWidthResize, windowHeight + windowHeightResize ), # maximum size (for resizing) autosaveName = "com.mekkablue.SetFamilyAlignmentZones.mainwindow" # stores last window position and size ) # UI elements: linePos, inset, lineHeight = 12, 15, 22 self.w.descriptionText = vanilla.TextBox( (inset, linePos+2, -inset, lineHeight*2), u"Choose an instance (typically the Regular), and insert its zones as PostScript Family Alignment Zones.", sizeStyle='small', selectable=True ) linePos += lineHeight*2 self.w.instanceText = vanilla.TextBox( (inset, linePos+2, inset+55, 14), u"Instance:", sizeStyle='small', selectable=True ) self.w.instancePicker = vanilla.PopUpButton( (inset+55, linePos, -inset-25, 17), (), sizeStyle='small' ) self.w.instancePicker.getNSPopUpButton().setToolTip_("Inactive instances are marked.") # set font to tabular figures: popUpFont = NSFont.monospacedDigitSystemFontOfSize_weight_(NSFont.smallSystemFontSize(), 0.0) self.w.instancePicker.getNSPopUpButton().setFont_(popUpFont) self.w.updateButton = vanilla.SquareButton( (-inset-20, linePos, -inset, 18), u"↺", sizeStyle='small', callback=self.updateInstancePicker ) self.w.updateButton.getNSButton().setToolTip_("Click to update the menu with the instances of the current font.") linePos += lineHeight # Run Button: self.w.runButton = vanilla.Button( (-110-inset, -20-inset, -inset, -inset), "Insert FAZ", sizeStyle='regular', callback=self.SetFamilyAlignmentZonesMain ) self.w.setDefaultButton( self.w.runButton ) # Open window and focus on it: self.updateInstancePicker() self.w.open() self.w.makeKey()
def tokenString(self): font = NSFont.fontWithName_size_(fallbackFont.fontName(), 10) attr = _textAttributesForStyle(self._style, font) attr[NSForegroundColorAttributeName] = self.color() if NSUnderlineColorAttributeName in attr: attr[NSUnderlineColorAttributeName] = self.color() txt = self.token() if txt == "Token": txt = "Fallback" else: txt = txt.replace("Token.", "") return NSMutableAttributedString.alloc().initWithString_attributes_(txt, attr)
def drawFontVerticalMetrics(glyph, scale, rect, drawLines=True, drawText=True, colorMetrics=None, colorMetricsTitles=None, backgroundColor=None, flipped=False): font = glyph.font if font is None: return backgroundColor.set() # gather y positions toDraw = (("Descender", "descender"), ("X Height", "xHeight"), ("Cap Height", "capHeight"), ("Ascender", "ascender")) toDraw = [(name, getattr(font.info, attr)) for name, attr in toDraw if getattr(font.info, attr) is not None] toDraw.append(("Baseline", 0)) positions = {} for name, position in toDraw: if position not in positions: positions[position] = [] positions[position].append(name) # create lines xMin = rect[0][0] xMax = xMin + rect[1][0] lines = [] for y, names in sorted(positions.items()): names = ", ".join(names) lines.append(((xMin, y), (xMax, y), names)) # draw lines if drawLines: colorMetrics.set() lineWidth = 0.5 * scale for pt1, pt2, names in lines: drawLine(pt1, pt2, lineWidth=lineWidth) # draw text if drawText: colorMetricsTitles.set() fontSize = 12 attributes = { NSFontAttributeName: NSFont.systemFontOfSize_(fontSize), NSForegroundColorAttributeName: colorMetricsTitles } for pt1, pt2, names in lines: x, y = pt1 x = glyph.width x += 15 * scale y += 10 * scale y -= (fontSize / 2.0) * scale drawTextAtPoint(names, (x, y), scale, attributes, flipped=flipped)
def macos_font(loader, node): seq = loader.construct_sequence(node) if len(seq) != 2: raise ValueError('only two arguments may be provided, the font name and size') font_name, font_size = seq font = NSFont.fontWithName_size_(font_name, font_size) if font is None: raise ValueError('unable to find the font requested') return bytes(NSKeyedArchiver.archivedDataWithRootObject_(font))
def __init__(self): self.alphabetSet = alphabetSetLower # set up window self.w = vanilla.Window((420, 150), "Pangrammer Helper") # set up remaining letters display self.w.alphabet = vanilla.TextBox((15, 15, -15, 20), self.alphabetSet) # set up text field, inserting Space Center text if available if CurrentSpaceCenter() is None: pangram = "Type your pangram here" else: sp = CurrentSpaceCenter() pangram = sp.getRaw() self.w.pangramEditor = vanilla.TextEditor( (15, 40, -15, 70), pangram, callback=self.textEditorCallback) self.w.counter = vanilla.TextBox((-250, 112, -15, 20), "Pangram length: 0", alignment='right') self.w.checkBox = vanilla.CheckBox((15, 110, -15, 20), "", callback=self.checkBoxCallback, value=False) self.w.checkBoxLabel = vanilla.TextBox( # don’t know how to access the NSText of a Vanilla check box label (32, 112, -15, 20), "Mixed case") # set the editor font to be monospaced, and the rest to be system font monospace_font = NSFont.userFixedPitchFontOfSize_(12) system_font = NSFont.systemFontOfSize_(12) self.w.pangramEditor.getNSTextView().setFont_(monospace_font) self.w.alphabet.getNSTextField().setFont_(system_font) self.w.counter.getNSTextField().setFont_(system_font) self.w.checkBoxLabel.getNSTextField().setFont_(system_font) self.w.open() # set remaining letters and counter to reflect contents of text field self.textEditorCallback(self)
def drawGlyphAnchors(glyph, scale, rect, drawAnchor=True, drawText=True, color=None, textColor=None, backgroundColor=None, flipped=False): if not glyph.anchors: return if color is None: color = getDefaultColor("glyphAnchor") fallbackColor = color if backgroundColor is None: backgroundColor = getDefaultColor("background") anchorSize = 5 * scale anchorHalfSize = anchorSize / 2 for anchor in glyph.anchors: if anchor.color is not None: color = colorToNSColor(anchor.color) else: color = fallbackColor x = anchor.x y = anchor.y name = anchor.name context = NSGraphicsContext.currentContext() context.saveGraphicsState() #shadow = NSShadow.alloc().init() #shadow.setShadowColor_(backgroundColor) #shadow.setShadowOffset_((0, 0)) #shadow.setShadowBlurRadius_(3) #shadow.set() if drawAnchor: r = ((x - anchorHalfSize, y - anchorHalfSize), (anchorSize, anchorSize)) color.set() drawFilledOval(r) if drawText and name: attributes = { NSFontAttributeName: NSFont.boldSystemFontOfSize_(12), NSForegroundColorAttributeName: textColor, } y += 25 * scale drawTextAtPoint(name, (x, y), scale, attributes, xAlign="center", yAlign="top", flipped=flipped) context.restoreGraphicsState()
def fontName2FontPath(self, fontName): u"""Answer the unchanged path, if it exists as file. Answer the path that is source of the given font name. Answer None if the font cannot be found.""" # If the font cannot be found by name, then test if the file exists as path and answer it. if os.path.exists(fontName): # return fontName # Otherwise try OSX for the conversion. nsFont = NSFont.fontWithName_size_(fontName, 25) if nsFont is not None: fontRef = CTFontDescriptorCreateWithNameAndSize( nsFont.fontName(), nsFont.pointSize()) url = CTFontDescriptorCopyAttribute(fontRef, kCTFontURLAttribute) return url.path() return None
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 initWithFrame_andText_(self, frame, text): self = super(TextPane, self).initWithFrame_(frame) if not self: return self.tx = NSTextView.alloc().initWithFrame_(NSRect((0, 0), frame.size)) self.tx.setDrawsBackground_(NO) self.tx.setEditable_(NO) self.tx.setSelectable_(NO) self.tx.textStorage().mutableString().setString_(text) self.tx.setAlignment_range_(NSCenterTextAlignment, NSMakeRange(0, self.tx.string().length())) self.tx.setFont_(NSFont.userFontOfSize_(self.SIZE)) self.tx.layoutManager().glyphRangeForTextContainer_(self.tx.textContainer()) textSize2 = self.tx.layoutManager().usedRectForTextContainer_(self.tx.textContainer()).size self.tx.setFrame_(NSRect(((frame.size[0] - textSize2[0]) / 2.0, (frame.size[1] - textSize2[1]) / 2.0), textSize2)) self.addSubview_(self.tx) return self
def checkSampleSize(self): text = self.w.selectionUnicodeText.get() minFontSize = 20 maxFontSize = 50 charsForLarge = 35 charsForSmall = 50 if len(text) < charsForLarge: fontSize = maxFontSize elif len(text) > charsForSmall: fontSize = minFontSize else: fs = (len(text)-charsForLarge)/(charsForSmall-charsForLarge) fontSize = maxFontSize + fs * (minFontSize-maxFontSize) tf = self.w.selectionUnicodeText.getNSTextField() nsBig = NSFont.systemFontOfSize_(fontSize) tf.setFont_(nsBig)
def init(self): self = super(PyInterpreter, self).init() if self is None: return None self._font = NSFont.userFixedPitchFontOfSize_(10) self._historyLength = 50 self._history = [u""] self._historyView = 0 self._characterIndexForInput = 0 self._stdin = PseudoUTF8Input(self._nestedRunLoopReaderUntilEOLchars_) self._stderr = PseudoUTF8Output(self.writeStderr_) self._stdout = PseudoUTF8Output(self.writeStdout_) self._isInteracting = False self._console = AsyncInteractiveConsole() self._interp = self._console.asyncinteract(write=self.writeCode_).next self._autoscroll = True return self
def __init__(self, posSize, text, callback=None): # there must be a callback as it triggers the creation of the delegate if callback is None: callback = self._fallbackCallback super(FeatureTextEditor, self).__init__(posSize, "", callback=callback) self._nsObject.setHasHorizontalScroller_(True) font = NSFont.fontWithName_size_("Monaco", 10) self._textView.setFont_(font) self._textView.setUsesFindPanel_(True) ## line numbers #ruler = DefconAppKitLineNumberView.alloc().init() #ruler.setClientView_(self._textView) #self._nsObject.setVerticalRulerView_(ruler) #self._nsObject.setHasHorizontalRuler_(False) #self._nsObject.setHasVerticalRuler_(True) #self._nsObject.setRulersVisible_(True) #notificationCenter = NSNotificationCenter.defaultCenter() #notificationCenter.addObserver_selector_name_object_( # ruler, "clientViewSelectionChanged:", NSTextViewDidChangeSelectionNotification, self._textView #) # colors self._mainColor = NSColor.blackColor() self._commentColor = NSColor.colorWithCalibratedWhite_alpha_(.6, 1) self._keywordColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, 0, 0, 1) self._tokenColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, .4, 0, 1) self._classNameColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, .8, 1) self._includeColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, 0, .8, 1) self._stringColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0, .6, 0, 1) # build the placard placardW = 65 placardH = 16 self._placardJumps = [] self._placard = vanilla.Group((0, 0, placardW, placardH)) self._placard.featureJumpButton = PlacardPopUpButton((0, 0, placardW, placardH), [], callback=self._placardFeatureSelectionCallback, sizeStyle="mini") self._nsObject.setPlacard_(self._placard.getNSView()) # registed for syntax coloring notifications self._programmaticallySettingText = False delegate = self._textViewDelegate delegate.vanillaWrapper = weakref.ref(self) notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver_selector_name_object_( self._textViewDelegate, "textStorageDidProcessEditing", NSTextStorageDidProcessEditingNotification, self._textView.textStorage()) # set the text self.set(text)
def _drawTextLabel(self, transform, text, size, vector): if vector is None: vector = (-1, 1) angle = atan2(vector[0], -vector[1]) text_size = 0.5 * size #para_style = NSMutableParagraphStyle.alloc().init() #para_style.setAlignment_(NSCenterTextAlignment) attrs = { NSFontAttributeName: NSFont.systemFontOfSize_(text_size), NSForegroundColorAttributeName: NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.4, 0.4, 0.6, 0.7 ), #NSParagraphStyleAttributeName: para_style, } myString = NSString.string().stringByAppendingString_(text) bbox = myString.sizeWithAttributes_(attrs) bw = bbox.width bh = bbox.height text_pt = NSPoint() text_pt.y = 0 if -0.5 * pi < angle <= 0.5 * pi: text_pt.x = -1.3 * size - bw / 2 * cos(angle) - bh / 2 * sin(angle) else: text_pt.x = -1.3 * size + bw / 2 * cos(angle) + bh / 2 * sin(angle) text_pt = transform.transformPoint_(text_pt) rr = NSRect( origin = (text_pt.x - bw / 2, text_pt.y - bh / 2), size = (bw, bh) ) if DEBUG: NSColor.colorWithCalibratedRed_green_blue_alpha_( 0, 0, 0, 0.15 ).set() myRect = NSBezierPath.bezierPathWithRect_(rr) myRect.setLineWidth_(0.05 * size) myRect.stroke() myString.drawInRect_withAttributes_( rr, attrs )
def drawGlyphAnchors(glyph, scale, rect, drawAnchor=True, drawText=True, color=None, backgroundColor=None, flipped=False): if not glyph.anchors: return if color is None: color = getDefaultColor("glyphAnchor") fallbackColor = color if backgroundColor is None: backgroundColor = getDefaultColor("background") anchorSize = 5 * scale anchorHalfSize = anchorSize / 2 for anchor in glyph.anchors: if anchor.color is not None: color = colorToNSColor(anchor.color) else: color = fallbackColor x = anchor.x y = anchor.y name = anchor.name context = NSGraphicsContext.currentContext() context.saveGraphicsState() shadow = NSShadow.alloc().init() shadow.setShadowColor_(backgroundColor) shadow.setShadowOffset_((0, 0)) shadow.setShadowBlurRadius_(3) shadow.set() if drawAnchor: r = ((x - anchorHalfSize, y - anchorHalfSize), (anchorSize, anchorSize)) color.set() drawFilledOval(r) if drawText and name: attributes = { NSFontAttributeName: NSFont.systemFontOfSize_(9), NSForegroundColorAttributeName: color, } y -= 2 * scale drawTextAtPoint(name, (x, y), scale, attributes, xAlign="center", yAlign="top", flipped=flipped) context.restoreGraphicsState()
def init(self): self = super().init() if self is None: return None self._font = NSFont.userFixedPitchFontOfSize_(10) self._historyLength = 50 self._history = [''] self._historyView = 0 self._characterIndexForInput = 0 self._stdin = PseudoUTF8Input(self._nestedRunLoopReaderUntilEOLchars_) self._stderr = PseudoUTF8Output(self.writeStderr_) self._stdout = PseudoUTF8Output(self.writeStdout_) self._isInteracting = False self._console = AsyncInteractiveConsole() self._interp = self._console.asyncinteract( write=self.writeCode_, banner="Python %s in %s\n%s\n" % ( sys.version, NSBundle.mainBundle().objectForInfoDictionaryKey_('CFBundleName'), 'Type "help", "copyright", "credits" or "license" for more information.' ) ).__next__ self._autoscroll = True return self
def initWithFrame_(self, frame): self = super(GreetingsToView, self).initWithFrame_(frame) if not self: return None self.timers = [] poem = ('thanks for watching!', 'we love working on', 'Dropbox', 'and we really hope', 'it makes your life', 'easier.', '~~~', 'remember,', "do what's right", 'love thy neighbor', 'and', 'be yourself', '<3', '~~~', 'find us on the web at', 'http://dropbox.com/', '~~~', '4/15/2011') self.views = [] total_height = 0 for a in poem: 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_(a) vv.textStorage().setFont_(NSFont.labelFontOfSize_(14)) vv.textStorage().setForegroundColor_(NSColor.colorWithCalibratedRed_green_blue_alpha_(1.0, 1.0, 1.0, 0.0)) vv.textStorage().endEditing() vv.layoutManager().glyphRangeForTextContainer_(vv.textContainer()) size = vv.layoutManager().usedRectForTextContainer_(vv.textContainer()).size vv.setFrameSize_(size) total_height += size[1] self.addSubview_(vv) self.views.append(vv) SPACING = 11 total_height += SPACING * (len(self.views) - 1) placement = frame.size[1] - (frame.size[1] - total_height) / 2.0 for a in self.views: w, h = a.frame().size placement -= h a.setFrameOrigin_(((frame.size[0] - w) / 2.0, placement)) placement -= SPACING return self
def fontSize(fontSize): # Set the font size. currentFont = NSFont.fontWithName_size_(currentFont.fontName(), fontSize)
path = glyph._layer.bezierPath drawPath(path) def save(): # save the current graphic state NSGraphicsContext.currentContext().saveGraphicsState() def restore(): # restore the current graphic state NSGraphicsContext.currentContext().restoreGraphicsState() currentPath = None currentFillColor = NSColor.blackColor() currentStrokeColor = None currentGradient = None currentFont = NSFont.systemFontOfSize_(NSFont.systemFontSize()) def rect(x, y, width, height): # draws a rectangle drawPath(NSBezierPath.bezierPathWithRect_(NSMakeRect(x, y, width, height))) def oval(x, y, width, height): # draws an oval drawPath(NSBezierPath.bezierPathWithOvalInRect_(NSMakeRect(x, y, width, height))) def line(x1, y1, x2=None, y2=None): # draws a line if x2 is None and y2 is None and isinstance(x1, tuple) and isinstance(y1, tuple): (x1, y1), (x2, y2) = x1, y1 p = NSBezierPath.bezierPath() p.moveToPoint_(NSMakePoint(x1, y1))
def font(fontName, fontSize=None): # Set the font by PostScript name. # Optionally set the font size. if fontSize is None: fontSize = NSFont.systemFontSize() NSFont.fontWithName_size_(fontName, fontSize)