def __init__(self, posSize, callback):
     self._callback = callback
     # put the controls group into a flipped group.
     # this will give better scroll behavior.
     width = posSize[2] - NSScroller.scrollerWidth() - 2
     view = DefconAppKitTopAnchoredNSView.alloc().init()
     view.setFrame_(((0, 0), (width, 0)))
     # call the super
     super(OpenTypeControlsView, self).__init__(posSize, view, hasHorizontalScroller=False, drawsBackground=False)
     # build the view for the controls
     self._controlGroup = vanilla.Group((0, 0, width, 0))
     view.addSubview_(self._controlGroup.getNSView())
     # build the static controls
     top = 10
     # mode
     self._controlGroup.modeTitle = vanilla.TextBox((10, top, -10, 14),
         NSAttributedString.alloc().initWithString_attributes_("DISPLAY MODE", titleControlAttributes), sizeStyle="small")
     top += 20
     self._controlGroup.modeRadioGroup = vanilla.RadioGroup((10, top, -10, 38),
         ["Glyph Preview", "Glyph Records"], callback=self._controlEditCallback)
     self._controlGroup.modeRadioGroup.set(0)
     top += 48
     self._controlGroup.line1 = vanilla.HorizontalLine((10, top, -10, 1))
     top += 11
     # case
     self._controlGroup.caseTitle = vanilla.TextBox((10, top, -10, 14),
         NSAttributedString.alloc().initWithString_attributes_("CASE CONVERSION", titleControlAttributes), sizeStyle="small")
     top += 20
     self._controlGroup.caseRadioGroup = vanilla.RadioGroup((10, top, -10, 58),
         ["Unchanged", "Uppercase", "Lowercase"], callback=self._controlEditCallback)
     self._controlGroup.caseRadioGroup.set(0)
     top += 68
     # language, script and direction
     self._controlGroup.scriptTitle = vanilla.TextBox((10, top, -10, 14),
         NSAttributedString.alloc().initWithString_attributes_("SCRIPT & LANGUAGE", titleControlAttributes), sizeStyle="small")
     top += 20
     self._controlGroup.scriptPopUpButton = vanilla.PopUpButton((10, top, -10, 20), [], callback=self._controlEditCallback)
     top += 25
     self._controlGroup.languagePopUpButton = vanilla.PopUpButton((10, top, -10, 20), [], callback=self._controlEditCallback)
     top += 35
     self._controlGroup.directionTitle = vanilla.TextBox((10, top, -10, 14),
         NSAttributedString.alloc().initWithString_attributes_("WRITING DIRECTION", titleControlAttributes), sizeStyle="small")
     top += 20
     self._controlGroup.directionRadioGroup = vanilla.RadioGroup((10, top, -10, 38),
         ["Left to Right", "Right to Left"], callback=self._controlEditCallback)
     self._controlGroup.directionRadioGroup.set(0)
     top += 48
     # GSUB and GPOS
     self._controlGroup.line2 = vanilla.HorizontalLine((10, top, -10, 1))
     top += 11
     # set document view height
     (x, y), (w, h) = self._nsObject.documentView().frame()
     self._nsObject.documentView().setFrame_(((x, y), (w, top)))
     x, y, w, h = self._controlGroup.getPosSize()
     self._controlGroup.setPosSize((x, y, w, top))
     # storage
     self._dynamicTop = top
     self._gsubAttributes = {}
     self._gposAttributes = {}
     self._featureNames = {}
Exemplo n.º 2
0
	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
Exemplo n.º 3
0
def agent_to_menu_item(agent) -> rumps.MenuItem:
    ag = plistlib.readPlist(agent)
    label = ag['Label']
    ar = rumps.MenuItem("")
    aj = launchd.LaunchdJob(label)
    exist = aj.exists()
    if exist:
        pid = aj.pid
        status = aj.laststatus
        if pid == -1 and status == 0:
            ar_title = NSAttributedString.alloc().initWithString_attributes_(
                label, b_attr)
            ar._menuitem.setAttributedTitle_(ar_title)
            insert_unload_reload(ar, aj)
            ar.add(
                rumps.MenuItem("Start",
                               callback=lambda x: launchctl("start", label)))
            insert_log_menu_items(ar, ag)
            ar.add("Idle")
            ar.add("No Errors")
        elif pid > 0 and status == 0:
            ar_title = NSAttributedString.alloc().initWithString_attributes_(
                label, g_attr)
            ar._menuitem.setAttributedTitle_(ar_title)
            insert_unload_reload(ar, aj)
            ar.add(
                rumps.MenuItem("Stop",
                               callback=lambda x: launchctl("stop", label)))
            insert_log_menu_items(ar, ag)
            ar.add(f"Running ({pid})")
            ar.add("No Errors")
        elif status != 0:
            ar_title = NSAttributedString.alloc().initWithString_attributes_(
                label, r_attr)
            ar._menuitem.setAttributedTitle_(ar_title)
            insert_unload_reload(ar, aj)
            ar.add(
                rumps.MenuItem("Start",
                               callback=lambda x: launchctl("start", label)))
            insert_log_menu_items(ar, ag)
            ar.add("Stopped")
            ar.add(f"Error ({status})")
    else:
        ar.title = label
        sub_load = rumps.MenuItem(
            title="Load",
            callback=lambda x: launchd.load(f"{USER_AGENTS}/{label}.plist"))
        ar.add(sub_load)
        insert_log_menu_items(ar, ag)
        ar.add("Unloaded")
    return ar
def jumpToAlternate():
    font = Glyphs.font
    currentTab = font.currentTab
    layers = currentTab.layers.values()

    string = NSMutableAttributedString.alloc().init()

    for i in xrange(len(layers)):
        layer = layers[i]
        try:
            char = font.characterForGlyph_(layer.parent)
        except:
            continue
        if i == currentTab.layersCursor:
            # the currently active glyph
            currGlyphName = layer.parent.name
            currBaseName = currGlyphName.split('.', 1)[0]
            if not currBaseName:
                # for example .notdef
                return
            alternates = []
            for glyph in font.glyphs:
                baseName = glyph.name.split('.', 1)[0]
                if currBaseName == baseName and not glyph.name.endswith('.sc'):
                    alternates.append(glyph)
            assert (len(alternates) >= 1)
            if len(alternates) == 1:
                # no others found
                return
            for a in xrange(len(alternates)):
                if alternates[a].name == currGlyphName:
                    try:
                        nextGlyph = alternates[a + 1]
                    except IndexError:
                        nextGlyph = alternates[0]
            char = font.characterForGlyph_(nextGlyph)
            singleChar = NSAttributedString.alloc().initWithString_attributes_(
                unichr(char), {})
        else:
            if layer.layerId == layer.associatedMasterId:
                singleChar = NSAttributedString.alloc(
                ).initWithString_attributes_(unichr(char), {})
            else:
                # user-selected layer
                singleChar = NSAttributedString.alloc(
                ).initWithString_attributes_(
                    unichr(char), {"GSLayerIdAttrib": layer.layerId})
        string.appendAttributedString_(singleChar)
    currentTab.layers._owner.graphicView().textStorage().setText_(string)
Exemplo n.º 5
0
Arquivo: dist.py Projeto: ygini/munki
def get_firmware_alert_text(dom):
    '''If the update is a firmware update, returns some alert
    text to display to the user, otherwise returns an empty
    string. If we cannot read a custom firmware readme to use as
    the alert, return "_DEFAULT_FIRMWARE_ALERT_TEXT_" '''

    type_is_firmware = False
    options = dom.getElementsByTagName('options')
    for option in options:
        if 'type' in option.attributes.keys():
            type_value = option.attributes['type'].value
            if type_value == 'firmware':
                type_is_firmware = True
                break
    if type_is_firmware:
        firmware_alert_text = '_DEFAULT_FIRMWARE_ALERT_TEXT_'
        readmes = dom.getElementsByTagName('readme')
        if len(readmes):
            html = readmes[0].firstChild.data
            html_data = buffer(html.encode('utf-8'))
            attributed_string, _ = NSAttributedString.alloc(
            ).initWithHTML_documentAttributes_(html_data, None)
            firmware_alert_text = attributed_string.string()
        return firmware_alert_text
    return ''
Exemplo n.º 6
0
    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)))
Exemplo n.º 7
0
def get_firmware_alert_text(dom):
    '''If the update is a firmware update, returns some alert
    text to display to the user, otherwise returns an empty
    string. If we cannot read a custom firmware readme to use as
    the alert, return "_DEFAULT_FIRMWARE_ALERT_TEXT_" '''

    type_is_firmware = False
    options = dom.getElementsByTagName('options')
    for option in options:
        if 'type' in option.attributes.keys():
            type_value = option.attributes['type'].value
            if type_value == 'firmware':
                type_is_firmware = True
                break
    if type_is_firmware:
        firmware_alert_text = '_DEFAULT_FIRMWARE_ALERT_TEXT_'
        readmes = dom.getElementsByTagName('readme')
        if len(readmes):
            html = readmes[0].firstChild.data
            html_data = buffer(html.encode('utf-8'))
            attributed_string, _ = NSAttributedString.alloc(
                ).initWithHTML_documentAttributes_(html_data, None)
            firmware_alert_text = attributed_string.string()
        return firmware_alert_text
    return ''
Exemplo n.º 8
0
def drawTextAtPoint(text, pt, scale, attributes={}, xAlign="left", yAlign="bottom", flipped=False):
    text = NSAttributedString.alloc().initWithString_attributes_(text, attributes)
    if xAlign != "left" or yAlign != "bottom":
        width, height = text.size()
        width *= scale
        height *= scale
        x, y = pt
        f = 1
        if flipped:
            f = -1
        if xAlign == "center":
            x -= width / 2
        elif xAlign == "right":
            x -= width
        if yAlign == "center":
            y -= height / 2 * f
        elif yAlign == "top":
            y -= height * f
        pt = (x, y)
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(pt[0], pt[1])
    if flipped:
        s = -scale
    else:
        s = scale
    transform.scaleXBy_yBy_(scale, s)
    transform.concat()
    text.drawAtPoint_((0, 0))
    context.restoreGraphicsState()
Exemplo n.º 9
0
    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)))
Exemplo n.º 10
0
 def attributedStringForObjectValue_withDefaultAttributes_(self, obj, attrs):
     if obj is None or isinstance(obj, NSNull):
         obj = ""
     paragraph = NSMutableParagraphStyle.alloc().init()
     paragraph.setLineBreakMode_(NSLineBreakByTruncatingHead)
     attrs = dict(attrs)
     attrs[NSParagraphStyleAttributeName] = paragraph
     return NSAttributedString.alloc().initWithString_attributes_(obj, attrs)
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
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)
Exemplo n.º 13
0
 def attributedStringForObjectValue_withDefaultAttributes_(
         self, obj, attrs):
     if obj is None or isinstance(obj, NSNull):
         obj = ""
     paragraph = NSMutableParagraphStyle.alloc().init()
     paragraph.setLineBreakMode_(NSLineBreakByTruncatingHead)
     attrs = dict(attrs)
     attrs[NSParagraphStyleAttributeName] = paragraph
     return NSAttributedString.alloc().initWithString_attributes_(
         obj, attrs)
Exemplo n.º 14
0
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))
Exemplo n.º 15
0
 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)
Exemplo n.º 16
0
 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)
Exemplo n.º 17
0
 def drawTextAtPoint(self,
                     text,
                     textPosition,
                     textAlignment=3,
                     fontSize=9.0,
                     fontColor=NSColor.brownColor()):
     """
     Use self.drawTextAtPoint("blabla", myNSPoint) to display left-aligned text at myNSPoint.
     """
     try:
         glyphEditView = self.controller.graphicView()
         fontAttributes = {
             NSFontAttributeName: NSFont.labelFontOfSize_(fontSize),
             NSForegroundColorAttributeName: fontColor
         }
         displayText = NSAttributedString.alloc(
         ).initWithString_attributes_(text, fontAttributes)
         displayText.drawAtPoint_alignment_visibleInRect_(
             textPosition, textAlignment, NSMakeRect(NSNotFound, 0, 0, 0))
     except Exception as e:
         self.logToConsole("drawTextAtPoint: %s" % str(e))
Exemplo n.º 18
0
    def set_title(self, title):
        self.title = title

        if title is not None:
            # This is hacky, but works
            # https://github.com/jaredks/rumps/issues/30
            fg_color = NSColor.systemOrangeColor()
            bg_color = NSColor.darkGrayColor()

            font = NSFont.menuBarFontOfSize_(0)
            attributes = propertyListFromPythonCollection(
                {
                    NSForegroundColorAttributeName: fg_color,
                    NSBackgroundColorAttributeName: bg_color,
                    NSFontAttributeName: font,
                },
                conversionHelper=lambda x: x,
            )
            string = NSAttributedString.alloc().initWithString_attributes_(
                " " + title, attributes)
            self._nsapp.nsstatusitem.setAttributedTitle_(string)
Exemplo n.º 19
0
def drawTextAtPoint(text,
                    pt,
                    scale,
                    attributes={},
                    xAlign="left",
                    yAlign="bottom",
                    flipped=False):
    text = NSAttributedString.alloc().initWithString_attributes_(
        text, attributes)
    if xAlign != "left" or yAlign != "bottom":
        width, height = text.size()
        width *= scale
        height *= scale
        x, y = pt
        f = 1
        if flipped:
            f = -1
        if xAlign == "center":
            x -= width / 2
        elif xAlign == "right":
            x -= width
        if yAlign == "center":
            y -= height / 2 * f
        elif yAlign == "top":
            y -= height * f
        pt = (x, y)
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(pt[0], pt[1])
    if flipped:
        s = -scale
    else:
        s = scale
    transform.scaleXBy_yBy_(scale, s)
    transform.concat()
    text.drawAtPoint_((0, 0))
    context.restoreGraphicsState()
Exemplo n.º 20
0
    def set_title(self, title, color_list=None):
        self.title = title
        if color_list is None:
            color_list = self.default_color_list

        if title is not None:
            if self.truncate and len(title) > 40:
                title = title[:37] + '...'

            # This is hacky, but works
            # https://github.com/jaredks/rumps/issues/30
            color = NSColor.colorWithCalibratedRed_green_blue_alpha_(
                color_list[0] / 255, color_list[1] / 255, color_list[2] / 255,
                color_list[3])
            font = NSFont.menuBarFontOfSize_(0)
            attributes = propertyListFromPythonCollection(
                {
                    NSForegroundColorAttributeName: color,
                    NSFontAttributeName: font
                },
                conversionHelper=lambda x: x)
            string = NSAttributedString.alloc().initWithString_attributes_(
                ' ' + title, attributes)
            self._nsapp.nsstatusitem.setAttributedTitle_(string)
Exemplo n.º 21
0
 def getBoldString(self, s):
     return NSAttributedString.alloc().initWithString_attributes_(
         s, {NSFontAttributeName: self.boldFont})
Exemplo n.º 22
0
 def setFont(self, font):
     # script list
     if font is None:
         scriptList = []
     else:
         scriptList = ["DFLT"] + font.getScriptList()
     unsupportedScripts = [i for i in scriptTags if i not in scriptList]
     if unsupportedScripts:
         scriptList.append(NSMenuItem.separatorItem())
         scriptList += unsupportedScripts
     self._controlGroup.scriptPopUpButton.setItems(scriptList)
     # language list
     if font is None:
         languageList = []
     else:
         languageList = ["Default"] + font.getLanguageList()
     unsupportedLanguages = [i for i in languageTags if i not in languageList]
     if unsupportedLanguages:
         languageList.append(NSMenuItem.separatorItem())
         languageList += unsupportedLanguages
     self._controlGroup.languagePopUpButton.setItems(languageList)
     # teardown existing controls
     for attr in self._gsubAttributes:
         delattr(self._controlGroup, attr)
     for attr in self._gposAttributes:
         delattr(self._controlGroup, attr)
     for attr in self._featureNames:
         delattr(self._controlGroup, attr)
     if hasattr(self._controlGroup, "gposTitle"):
         del self._controlGroup.gposTitle
     if hasattr(self._controlGroup, "gsubTitle"):
         del self._controlGroup.gsubTitle
     # stylistic set names
     if hasattr(font, "stylisticSetNames"):
         stylisticSetNames = font.stylisticSetNames
     else:
         stylisticSetNames = {}
     # GSUB
     top = self._dynamicTop
     if font is None:
         gsub = None
     else:
         gsub = font.gsub
     if gsub is None:
         gsubFeatureList = []
     else:
         gsubFeatureList = gsub.getFeatureList()
     self._gsubAttributes = {}
     self._featureNames = {}
     if gsubFeatureList:
         self._controlGroup.gsubTitle = vanilla.TextBox((10, top, -10, 14),
             NSAttributedString.alloc().initWithString_attributes_("GSUB", titleControlAttributes), sizeStyle="small")
         top += 20
         for tag in gsubFeatureList:
             state = font.gsub.getFeatureState(tag)
             attr = "gsubCheckBox_%s" % tag
             obj = vanilla.CheckBox((10, top, -10, 22), tag, value=state, callback=self._controlEditCallback)
             setattr(self._controlGroup, attr, obj)
             self._gsubAttributes[attr] = tag
             top += 20
             # stylistic set name
             if tag in stylisticSetNames:
                 attr = "ssName_%s" % tag
                 setName = stylisticSetNames[tag]
                 if hasattr(self._controlGroup, attr):
                     obj = getattr(self._controlGroup, attr)
                     obj.set(setName)
                 else:
                     obj = vanilla.TextBox((26, top, -10, 13), setName, sizeStyle="mini")
                     setattr(self._controlGroup, attr, obj)
                 self._featureNames[attr] = setName
                 top += 13
         top += 10
     # GPOS
     if font is None:
         gpos = None
     else:
         gpos = font.gpos
     if gpos is None:
         gposFeatureList = []
     else:
         gposFeatureList = gpos.getFeatureList()
     self._gposAttributes = {}
     if gposFeatureList:
         self._controlGroup.gposTitle = vanilla.TextBox((10, top, -10, 14),
             NSAttributedString.alloc().initWithString_attributes_("GPOS", titleControlAttributes), sizeStyle="small")
         top += 20
         for tag in gposFeatureList:
             state = font.gpos.getFeatureState(tag)
             attr = "gposCheckBox_%s" % tag
             obj = vanilla.CheckBox((10, top, -10, 22), tag, value=state, callback=self._controlEditCallback)
             setattr(self._controlGroup, attr, obj)
             self._gposAttributes[attr] = tag
             top += 20
         top += 10
     # set the view size
     (x, y), (w, h) = self._nsObject.documentView().frame()
     self._nsObject.documentView().setFrame_(((x, y), (w, top)))
     x, y, w, h = self._controlGroup.getPosSize()
     self._controlGroup.setPosSize((x, y, w, top))
Exemplo n.º 23
0
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
Exemplo n.º 24
0
	def drawRect_(self, rect): ## must be `drawRect_` - nothing else

		bounds = self.bounds()
		scaleFactor = self._scaleFactor
		thisUPM = self._upm * scaleFactor # = self._layer.parent.parent.upm
		rectX, rectY, rectWidth, rectHeight = 0, 0, thisUPM, thisUPM
		self.rect = rect


		# self._layer.drawInFrame_(bounds)  # used in Georgs GlyphView

		try:
			thisGlyph = self._layer.parent
			layerWidth = self._layer.width * scaleFactor
			descender = self._layer.glyphMetrics()[3] * scaleFactor
			
			# ## This order is important! Wont work the other way around.
			# try: # pre Glyphs 2.3
			# 	bezierPathOnly = self._layer.copy().bezierPath()  # Path Only
			# 	bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath() # Path & Components
			# except: # Glyphs 2.3
			# 	bezierPathOnly = self._layer.copy().bezierPath  # Path Only
			# 	bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath  # Path & Components

			## This order is important! Wont work the other way around.
			try: # Glyphs 2.3
				bezierPathOnly = self._layer.copy().bezierPath  # Path Only
				bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath  # Path & Components
			except: # Glyphs 2.4
				bezierPathOnly = self._layer.copy().bezierPath  # Path Only
				bezierPathWithComponents = self._layer.completeBezierPath  # Path & Components


			# Set the scale
			#--------------
			scale = NSAffineTransform.transform()
			scale.translateXBy_yBy_( rectWidth/2 - (layerWidth / 2.0) + self._margin/2, -descender + self._margin/2 )
			scale.scaleBy_( scaleFactor )

			if bezierPathWithComponents:
				bezierPathWithComponents.transformUsingAffineTransform_( scale )
			if bezierPathOnly:
				bezierPathOnly.transformUsingAffineTransform_( scale )

			# Draw components in gray
			#------------------------
			NSColor.darkGrayColor().set() # lightGrayColor
			bezierPathWithComponents.fill()
			
			
			# Draw only path in black
			#------------------------
			if thisGlyph.export:
				NSColor.blackColor().set()
				if bezierPathOnly:
					bezierPathOnly.fill()
			# Draw non-exported glyphs in orange
			#-----------------------------------
			else:
				NSColor.orangeColor().set()
				bezierPathWithComponents.fill()
			
			# AUTO-WIDTH LABEL
			#-----------------
			if self._layer.hasAlignedWidth():
				paragraphStyle = NSMutableParagraphStyle.alloc().init()
				paragraphStyle.setAlignment_(2) ## 0=L, 1=R, 2=C, 3=justified
				attributes = {}
				attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(10)
				attributes[NSForegroundColorAttributeName] = NSColor.lightGrayColor()
				attributes[NSParagraphStyleAttributeName] = paragraphStyle
				String = NSAttributedString.alloc().initWithString_attributes_("Auto-Width", attributes)
				# String.drawAtPoint_((rectWidth, 0))
				NSColor.redColor().set()
				# NSRectFill(((0, 0), (self.rect.size.width, 15)))
				String.drawInRect_(((0, 0), (self.rect.size.width, 15)))
		except:
			pass # print traceback.format_exc()
Exemplo n.º 25
0
	def drawRect_(self, rect): ## needs to be `drawRect_` -- nothing else

		bounds = self.bounds()

		# thisUPM = self._layer.parent.parent.upm
		scaleFactor = self._scaleFactor
		thisUPM = self._upm * scaleFactor
		rectX, rectY, rectWidth, rectHeight = 0, 0, thisUPM, thisUPM
		self.rect = rect

		# self._layer.drawInFrame_(bounds)  # used in Georgs GlyphView


		try:
			layerWidth = self._layer.width * scaleFactor
			descender = self._layer.glyphMetrics()[3] * scaleFactor
			
			## this order is important! Wont work the other way around
			try: # pre Glyphs 2.3
				bezierPathOnly = self._layer.copy().bezierPath()  # Path Only
				bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath() # Path & Components				
			except: # Glyphs 2.3
				bezierPathOnly = self._layer.copy().bezierPath  # Path Only
				bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath  # Path & Components			

				

			scale = NSAffineTransform.transform()
			scale.translateXBy_yBy_( rectWidth/2 - (layerWidth / 2.0) + self._margin/2, -descender + self._margin/2 )
			scale.scaleBy_( scaleFactor )

			if bezierPathWithComponents:
				bezierPathWithComponents.transformUsingAffineTransform_( scale )
			if bezierPathOnly:
				bezierPathOnly.transformUsingAffineTransform_( scale )

			## DRAW COMPONENTS IN GRAY
			NSColor.darkGrayColor().set() # lightGrayColor
			bezierPathWithComponents.fill()
			
			## CHANGE COLOR FOR NON-EXPORTED GLYPHS
			thisGlyph = self._layer.parent
			if thisGlyph.export:
				NSColor.blackColor().set()

				## DRAW ONLY PATH IN BLACK
				if bezierPathOnly:
					bezierPathOnly.fill()
			else:
				NSColor.orangeColor().set()
				bezierPathWithComponents.fill()
			
			# print self.bounds()

			## AUTO-WIDTH LABEL
			if self._layer.hasAlignedWidth():
				paragraphStyle = NSMutableParagraphStyle.alloc().init()
				paragraphStyle.setAlignment_(2) ## 0=L, 1=R, 2=C, 3=justified
				attributes = {}
				attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(10)
				attributes[NSForegroundColorAttributeName] = NSColor.lightGrayColor()
				attributes[NSParagraphStyleAttributeName] = paragraphStyle
				String = NSAttributedString.alloc().initWithString_attributes_("Auto-Width", attributes)
				# String.drawAtPoint_((rectWidth, 0))
				NSColor.redColor().set()
				# NSRectFill(((0, 0), (self.rect.size.width, 15)))
				String.drawInRect_(((0, 0), (self.rect.size.width, 15)))
		except:
			# pass
			print traceback.format_exc()
Exemplo n.º 26
0
def WhiteText(string):
    attributes = {NSForegroundColorAttributeName: NSColor.whiteColor()}

    return NSAttributedString.alloc().initWithString_attributes_(
        string, attributes)
Exemplo n.º 27
0
    def export(self, sender):
        self.savePreferences(sender)
        otfExport = bool(self.w.otf.get())
        otfRemoveOverlaps = bool(self.w.otfRemoveOverlaps.get())
        otfAutohint = bool(self.w.otfAutohint.get())
        ttfExport = bool(self.w.ttf.get())
        ttfRemoveOverlaps = bool(self.w.ttfRemoveOverlaps.get())
        ttfAutohint = bool(self.w.ttfAutohint.get())

        formats = {
            "otf": {
                "export": otfExport,
                "removeOverlaps": otfRemoveOverlaps,
                "autohint": otfAutohint
            },
            "ttf": {
                "export": ttfExport,
                "removeOverlaps": ttfRemoveOverlaps,
                "autohint": ttfAutohint
            },
        }

        shouldExport = False
        for key in formats.keys():
            if formats[key]["export"] == True:
                shouldExport = True
                break

        # Quit if no formats are set to export
        if shouldExport == False:
            print("No files to export!")
            Glyphs.showMacroWindow()
            quit()

        if self.w.allOpenFonts.get():
            fonts = Glyphs.fonts
        else:
            fonts = [Glyphs.fonts[0]]

        # Configure the progress bar
        formatsCount = 0
        for ext in formats:
            if formats[ext]["export"] == True:
                formatsCount += 1
        totalCount = 0
        for font in fonts:
            totalCount += len(font.instances)
        totalCount = formatsCount * totalCount

        for f, font in enumerate(fonts):

            fontName = NSAttributedString.alloc().initWithString_attributes_(
                "[%s/%s] " % (f + 1, len(fonts)) +
                os.path.basename(Glyphs.font.filepath), self.attributes)
            self.w.currentFont.set(fontName)

            # # Configure the progress bar
            # formatsCount = 0
            # for ext in formats:
            # 	if formats[ext]["export"] == True:
            # 		formatsCount += 1
            # totalCount = formatsCount * len(font.instances)

            # Set install folder
            subfolder = self.w.subfolder.get()
            currentFolder = os.path.dirname(font.filepath)
            installFolder = os.path.join(currentFolder, subfolder)
            try:
                os.makedirs(installFolder)
            except OSError as exc:  # Python >2.5
                if exc.errno == errno.EEXIST and os.path.isdir(installFolder):
                    pass
                else:
                    raise

            currentCount = 0
            count = {"otf": 0, "ttf": 0}

            for ext in formats:
                if formats[ext]["export"] == True:
                    for instance in font.instances:
                        try:
                            if instance.active:
                                fileName = "%s.%s" % (instance.fontName, ext)
                                print("Exporting %s" % fileName)
                                exportStatus = instance.generate(
                                    Format=ext.upper(),
                                    FontPath=installFolder + "/" + fileName,
                                    AutoHint=formats[ext]["autohint"],
                                    RemoveOverlap=formats[ext]
                                    ["removeOverlaps"])
                                if exportStatus == True:
                                    count[ext] += 1
                                if exportStatus != True:
                                    print(exportStatus)
                                    Glyphs.showMacroWindow()
                        except Exception as e:
                            print(e)
                        currentCount += 1
                        self.w.progress.set(100 / totalCount * currentCount)

            print("Exported %s" % (font.familyName))
            print("%s otf files" % (count["otf"]))
            print("%s ttf files" % (count["ttf"]))
            Glyphs.showNotification(
                "Exported %s" % (os.path.basename(font.filepath)),
                "%s otf files\n%s ttf files" % (count["otf"], count["otf"]))
        self.w.close()
Exemplo n.º 28
0
    def __init__(self):

        self.w = vanilla.Window(
            (self.windowWidth, self.windowHeight),
            "Export OTF and TTF into Subfolder",
            minSize=(self.windowWidth, self.windowHeight),
            maxSize=(self.windowWidth, self.windowHeight),
            autosaveName="com.harbortype.exportOtfTtf.mainwindow")

        fontName = NSAttributedString.alloc().initWithString_attributes_(
            "File: " + os.path.basename(Glyphs.font.filepath), self.attributes)
        self.w.currentFont = vanilla.TextBox(
            (self.margin, self.margin - 10, -self.margin, self.line),
            fontName,
            alignment="right")
        self.currentLine += self.line

        self.w.subfolder_title = vanilla.TextBox(
            (self.margin, self.margin + self.currentLine, 80, self.line),
            "Subfolder: ")
        self.w.subfolder = vanilla.EditText(
            (self.margin + 80, self.margin + self.currentLine - 3,
             -self.margin, self.line), )
        self.currentLine += self.line + 13

        self.w.allOpenFonts = vanilla.CheckBox(
            (self.margin, self.margin + self.currentLine, self.column,
             self.line),
            "All open fonts",
            callback=self.savePreferences)

        self.currentLine += self.line + 13

        self.w.line = vanilla.VerticalLine(
            (self.windowWidth / 2, self.margin + self.currentLine, 1,
             self.line * 3))

        self.w.otf = vanilla.CheckBox(
            (self.margin, self.margin + self.currentLine, self.column,
             self.line),
            "Export OTF",
            callback=self.savePreferences)
        self.currentLine += self.line
        self.w.otfRemoveOverlaps = vanilla.CheckBox(
            (self.margin * 2, self.margin + self.currentLine, self.column,
             self.line),
            "Remove overlaps",
            callback=self.savePreferences)
        self.currentLine += self.line
        self.w.otfAutohint = vanilla.CheckBox(
            (self.margin * 2, self.margin + self.currentLine, self.column,
             self.line),
            "Autohint",
            callback=self.savePreferences)
        self.currentLine -= self.line * 2

        self.w.ttf = vanilla.CheckBox(
            (self.margin * 3 + self.column, self.margin + self.currentLine,
             self.column, self.line),
            "Export TTF",
            callback=self.savePreferences)
        self.currentLine += self.line
        self.w.ttfRemoveOverlaps = vanilla.CheckBox(
            (self.margin * 4 + self.column, self.margin + self.currentLine,
             self.column, self.line),
            "Remove overlaps",
            callback=self.savePreferences)
        self.currentLine += self.line
        self.w.ttfAutohint = vanilla.CheckBox(
            (self.margin * 4 + self.column, self.margin + self.currentLine,
             self.column, self.line),
            "Autohint",
            callback=self.savePreferences)
        self.currentLine += self.line * 1.5

        self.w.progress = vanilla.ProgressBar(
            (self.margin, self.margin + self.currentLine,
             self.windowWidth - self.margin * 2, 16), )
        self.w.progress.set(0)  # set progress indicator to zero

        self.w.closeButton = vanilla.Button(
            (self.margin, -self.margin - self.line,
             self.windowWidth - self.margin * 2, self.line),
            "Cancel",
            callback=self.closeWindow)
        self.w.runButton = vanilla.Button(
            (self.margin, -self.margin - self.line * 2 - 8,
             self.windowWidth - self.margin * 2, self.line),
            "Export fonts",
            callback=self.export)

        if not self.loadPreferences():
            print("Note: Could not load preferences. Will resort to defaults.")

        self.w.setDefaultButton(self.w.runButton)
        try:
            # Python 3
            self.w.closeButton.bind(chr(27), [])
        except:
            # Python 2
            self.w.closeButton.bind(unichr(27), [])
        self.w.open()
        self.w.makeKey()
Exemplo n.º 29
0
def addCountBadgeToIcon(count, iconImage=None):
    if iconImage is None:
        iconImage = NSImage.alloc().initWithSize_((40, 40))
        iconImage.lockFocus()
        NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 1, .5).set()
        path = NSBezierPath.bezierPath()
        path.appendBezierPathWithOvalInRect_(((0, 0), iconImage.size()))
        path.fill()
        iconImage.unlockFocus()

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

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

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

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

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

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

    badgeLeft = imageWidth - badgeWidth - 3
    badgeBottom = 3

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

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

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

    # done
    image.unlockFocus()
    return image
Exemplo n.º 30
0
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))
Exemplo n.º 31
0
 def layout(self):
     height = self.BORDER + self.IMAGE_PADDING
     width = self.VIEW_SIZE[0] - self.BORDER * 2
     image = NonBlurryImageView.alloc().initWithFrame_(NSZeroRect)
     image.setImage_(self.image)
     image.setFrameSize_(self.image.size())
     self.addSubview_(image)
     image.setFrameOrigin_((0, height))
     image.centerHorizontallyInSuperview()
     height += NSHeight(image.frame()) + self.HEADER_PADDING
     label1 = NSTextField.createLabelWithText_font_maxWidth_origin_(self.header, NSFont.boldSystemFontOfSize_(self.HEADER_SIZE) if self.BOLD_HEADER else NSFont.systemFontOfSize_(self.HEADER_SIZE), width, NSPoint(0, height))
     self.addSubview_(label1)
     label1.centerHorizontallyInSuperview()
     label1.setTextColor_(self.HEADER_COLOR)
     height += NSHeight(label1.frame()) + self.SUBHEADER_PADDING
     label2 = NSTextField.createLabelWithText_font_maxWidth_origin_(NSAttributedString.boldify(self.subheader, font=NSFont.systemFontOfSize_(self.SUBHEADER_SIZE), bold_font=NSFont.boldSystemFontOfSize_(self.SUBHEADER_SIZE), center=True, line_height=self.SUBHEADER_LINE_HEIGHT), NSFont.systemFontOfSize_(self.SUBHEADER_SIZE), width, NSPoint(0, height))
     self.addSubview_(label2)
     label2.setAlignment_(NSCenterTextAlignment)
     label2.setTextColor_(self.SUBHEADER_COLOR)
     label2.balancedWrapToWidth_(width)
     label2.centerHorizontallyInSuperview()
     if self.checkbox_text:
         checkbox = NSButton.alloc().initWithFrame_(NSZeroRect)
         self.addSubview_(checkbox)
         checkbox.setButtonType_(NSSwitchButton)
         checkbox.setAttributedTitle_(NSAttributedString.boldify(self.checkbox_text, font=NSFont.systemFontOfSize_(self.CHECKBOX_SIZE), bold_font=NSFont.boldSystemFontOfSize_(self.CHECKBOX_SIZE)))
         checkbox.setTextColor_(Colors.camera_font)
         checkbox.sizeToFit()
         if NSWidth(checkbox.frame()) > width:
             checkbox.setAttributedTitle_(CameraStrings.splash_always_import_no_name)
             checkbox.setTextColor_(Colors.camera_font)
             checkbox.sizeToFit()
         checkbox.setState_(True)
         checkbox.centerHorizontallyInSuperview()
         checkbox.alignBottomInSuperview(self.BORDER - checkbox.flippedBaselineOffset())
         self.checkbox = checkbox
     else:
         self.checkbox = None
     height += NSHeight(label2.frame()) + self.FINE_PRINT_PADDING
     if self.fine_print:
         fine_print = NSTextField.createLabelWithText_font_maxWidth_origin_(self.fine_print, NSFont.systemFontOfSize_(self.FINE_PRINT_SIZE), width, NSPoint(0, height))
         self.addSubview_(fine_print)
         fine_print.setAlignment_(NSCenterTextAlignment)
         fine_print.setTextColor_(Colors.fine_print)
         fine_print.balancedWrapToWidth_(width)
         fine_print.centerHorizontallyInSuperview()
         self.fine_print_label = fine_print
     else:
         self.fine_print_label = None
     self.combo = None
     if self.choice_selector:
         subview = NSView.alloc().initWithFrame_(NSZeroRect)
         combo_descriptor = NSTextField.createLabelWithText_(NSAttributedString.boldify(self.choice_selector.text, font=NSFont.systemFontOfSize_(NSRegularControlSize), bold_font=NSFont.boldSystemFontOfSize_(NSRegularControlSize)))
         combo_descriptor.setTextColor_(self.SUBHEADER_COLOR)
         subview.addSubview_(combo_descriptor)
         combo = NSPopUpButton.createNormalPopUpButtonWithChoices_default_(self.choice_selector.selections, self.choice_selector.default_index)
         combo.sizeToFit()
         subview.addSubview_(combo)
         descriptor_frame = combo_descriptor.frame()
         half = combo.frame().size.height / 2.0
         descriptor_half = descriptor_frame.size.height / 2.0
         combo_descriptor.setFrameOrigin_(NSPoint(descriptor_frame.origin.x, half - descriptor_half + 2.0))
         combo.setFrameOrigin_(NSPoint(descriptor_frame.origin.x + descriptor_frame.size.width, 0))
         subview.setFrameSize_((combo.frame().size.width + descriptor_frame.size.width, combo.frame().size.height))
         self.addSubview_(subview)
         subview.centerHorizontallyInSuperview()
         subview.alignBottomInSuperview(CONTENT_BORDER + self.CHOICE_SELECTOR_PADDING)
         self.combo = combo
Exemplo n.º 32
0
 def getItalicString(self, s):
     return NSAttributedString.alloc().initWithString_attributes_(
         s, {NSFontAttributeName: self.italicFont})
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
Exemplo n.º 34
0
def make_attributed_string(text, font=NSFont.menuFontOfSize_(0.0)):
    attributes = propertyListFromPythonCollection({NSFontAttributeName: font},
                                                  conversionHelper=lambda x: x)

    return NSAttributedString.alloc().initWithString_attributes_(
        text, attributes)
Exemplo n.º 35
0
 i_raw += 1
 i_composed += 1
 while rawTextLayers[i_raw].parent.name != layers[i_composed].parent.name:
     i_composed += 1
     if i_composed >= len(layers):
         break
     for i_raw_candidate in range(i_raw, len(layers)):
         if rawTextLayers[i_raw_candidate].parent.name == layers[
                 i_composed].parent.name:
             for i_raw_add in range(i_raw, i_raw_candidate):
                 rawTextGlyph = rawTextLayers[i_raw_add].parent
                 try:
                     char = font.characterForGlyph_(rawTextGlyph)
                 except:
                     continue
                 singleChar = NSAttributedString.alloc(
                 ).initWithString_attributes_(unichr(char), {})
                 string.appendAttributedString_(singleChar)
             i_raw = i_raw_candidate
             break
 if i_composed >= len(layers):
     break
 rawTextGlyph = rawTextLayers[i_raw].parent
 try:
     char = font.characterForGlyph_(rawTextGlyph)
 except:
     continue
 # initialise single char without attributes
 # which switches the glyph to the active master
 singleChar = NSAttributedString.alloc().initWithString_attributes_(
     unichr(char), {})
 layer = rawTextLayers[i_raw]
Exemplo n.º 36
0
	def drawRect_(self, rect):
		# self._layer.drawInFrame_(bounds)  # used in Georgs GlyphView
		try:
			bounds = self.bounds()
			NSColor.textBackgroundColor().set()
			NSRectFill(bounds)
			scaleFactor = self._scaleFactor

			thisGlyph = self._layer.parent
			layerWidth = self._layer.width * scaleFactor
			descender = self._layer.glyphMetrics()[3] * scaleFactor
			ascender = self._layer.glyphMetrics()[1] * scaleFactor

			## This order is important! Wont work the other way around.
			bezierPathOnly = self._layer.bezierPath # Path Only
			if bezierPathOnly is not None:
				bezierPathOnly = bezierPathOnly.copy()
			bezierPathWithComponents = self._layer.completeBezierPath  # Path & Components
			bezierPathOpenWithComponents = self._layer.completeOpenBezierPath  # Path & Components
			
			# Set the scale
			#--------------
			scale = NSAffineTransform.transform()
			scale.translateXBy_yBy_((bounds.size.width - layerWidth) / 2.0, (bounds.size.height - ascender + descender) / 2.0 - descender)
			scale.scaleBy_(scaleFactor)
			
			
			# Draw only path in black
			#------------------------
			if thisGlyph.export:
				pathColor = NSColor.textColor()
				componentColor = NSColor.secondaryLabelColor()
			else:
				pathColor = NSColor.orangeColor()
				componentColor = NSColor.orangeColor()
				
			if bezierPathWithComponents:
				bezierPathWithComponents.transformUsingAffineTransform_(scale)
				componentColor.set() # Draw components in gray
				bezierPathWithComponents.fill()
			if bezierPathOnly:
				pathColor.set()
				bezierPathOnly.transformUsingAffineTransform_(scale)
				bezierPathOnly.fill()
			if bezierPathOpenWithComponents:
				pathColor.set()
				bezierPathOpenWithComponents.transformUsingAffineTransform_(scale)
				bezierPathOpenWithComponents.stroke()
			# Draw non-exported glyphs in orange
			#-----------------------------------
			else:
				NSColor.orangeColor().set()
				bezierPathWithComponents.transformUsingAffineTransform_(scale)
				bezierPathWithComponents.fill()
			
			attributes = {}
			attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(14)
			attributes[NSForegroundColorAttributeName] = NSColor.secondaryLabelColor()
			
			thisLKG = thisGlyph.leftKerningGroup
			thisRKG = thisGlyph.rightKerningGroup
			if thisLKG is not None:
				String = NSAttributedString.alloc().initWithString_attributes_(thisLKG, attributes)
				String.drawAtPoint_alignment_((12, 5), 0)
			if thisRKG is not None:
				String = NSAttributedString.alloc().initWithString_attributes_(thisRKG, attributes)
				String.drawAtPoint_alignment_((bounds.size.width - 12, 5), 2)

			# AUTO-WIDTH LABEL
			#-----------------
			if self._layer.hasAlignedWidth():
				attributes[NSForegroundColorAttributeName] = NSColor.lightGrayColor()
				attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(11)
				String = NSAttributedString.alloc().initWithString_attributes_("Auto-Width", attributes)
				String.drawAtPoint_alignment_((bounds.size.width / 2.0, 5), 1)
		except:
			print(traceback.format_exc())
Exemplo n.º 37
0
def WhiteText(string):
    attributes = {
        NSForegroundColorAttributeName: NSColor.whiteColor()
    }

    return NSAttributedString.alloc().initWithString_attributes_(string, attributes)