Esempio n. 1
0
 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
Esempio n. 2
0
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)
Esempio n. 3
0
 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)
Esempio n. 4
0
    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)
Esempio n. 5
0
 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)
Esempio n. 6
0
    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()
Esempio n. 7
0
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
Esempio n. 8
0
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
Esempio n. 9
0
 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())
Esempio n. 10
0
 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)
Esempio n. 11
0
 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)
Esempio n. 13
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)
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
Esempio n. 15
0
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)
Esempio n. 16
0
    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
Esempio n. 17
0
 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)
Esempio n. 18
0
    def _drawTextLabel(self, transform, text, size, vector, percent=1.0):
        if text is None:
            return

        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_(
                text_color[0],
                text_color[1],
                text_color[2],
                text_color[3] * percent,
            ),
            # 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)
Esempio n. 19
0
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()
Esempio n. 20
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)
Esempio n. 21
0
    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)
Esempio n. 22
0
    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)
Esempio n. 23
0
    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)
Esempio n. 24
0
 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
Esempio n. 25
0
 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)
Esempio n. 26
0
	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
		)
Esempio n. 27
0
    def __init__(self):
        super().__init__()
        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)
Esempio n. 28
0
    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)
Esempio n. 29
0
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()
Esempio n. 30
0
    def _setupContentView(self):
        # ------------------------------------------ #
        #                   Table View               #
        # ------------------------------------------ #
        rect = NSMakeRect(0, 0, self.WIDTH, self.HEIGHT)
        containerView = NSView.alloc().initWithFrame_(rect)

        # Startup btn
        height = 20
        margin = 20
        width = self.WIDTH - 2 * margin
        self.startupBtn = NSButton.buttonWithTitle_target_action_(
            "Run safetyapp on startup", self, "startupDidChanged:")
        self.startupBtn.setButtonType_(NSButtonTypeSwitch)
        self.startupBtn.setFrame_(
            NSMakeRect(margin, self.HEIGHT - 2 * height, width, height))
        self.startupBtn.setState_(self.data["startup"])
        containerView.addSubview_(self.startupBtn)

        # API Key settings
        titleLabel = NSTextField.labelWithString_("API Key")
        titleLabel.setTextColor_(NSColor.blackColor())
        rect = NSMakeRect(
            self.startupBtn.frame().origin.x,
            self.startupBtn.frame().origin.y -
            self.startupBtn.frame().size.height - height, width, height)
        titleLabel.setFrame_(rect)
        titleLabel.setFont_(NSFont.boldSystemFontOfSize_(14))
        containerView.addSubview_(titleLabel)

        # API Key Sub-label
        titleSubLabel = NSTextField.labelWithString_(
            "Lorem lpsum dolor sit amet")
        titleSubLabel.setTextColor_(NSColor.blackColor())
        rect = NSMakeRect(
            titleLabel.frame().origin.x,
            titleLabel.frame().origin.y - titleLabel.frame().size.height -
            height / 2, width, height)
        titleSubLabel.setFrame_(rect)
        titleSubLabel.setFont_(NSFont.systemFontOfSize_(14))
        containerView.addSubview_(titleSubLabel)

        # API Key text field
        self.apiTextField = NSTextField.textFieldWithString_("")
        rect = NSMakeRect(
            titleSubLabel.frame().origin.x,
            titleSubLabel.frame().origin.y -
            titleSubLabel.frame().size.height - height / 2, width,
            1.2 * height)
        self.apiTextField.setFrame_(rect)
        self.apiTextField.setFocusRingType_(NSFocusRingTypeNone)
        self.apiTextField.setTitleWithMnemonic_(self.data["api_key"])
        self.apiTextField.setEditable_(True)
        containerView.addSubview_(self.apiTextField)
        self.window().makeFirstResponder_(self.apiTextField)

        # Table title
        tableTitleLabel = NSTextField.labelWithString_("Directories")
        tableTitleLabel.setTextColor_(NSColor.blackColor())
        rect = NSMakeRect(
            self.apiTextField.frame().origin.x,
            self.apiTextField.frame().origin.y -
            self.apiTextField.frame().size.height - height, width, height)
        tableTitleLabel.setFrame_(rect)
        tableTitleLabel.setFont_(NSFont.boldSystemFontOfSize_(14))
        containerView.addSubview_(tableTitleLabel)

        # Table sub-title
        tableSubTitleLabel = NSTextField.labelWithString_(
            "Lorem lpsum dolor sit amet")
        tableSubTitleLabel.setTextColor_(NSColor.blackColor())
        rect = NSMakeRect(
            tableTitleLabel.frame().origin.x,
            tableTitleLabel.frame().origin.y -
            tableTitleLabel.frame().size.height - height / 2, width, height)
        tableSubTitleLabel.setFrame_(rect)
        tableSubTitleLabel.setFont_(NSFont.systemFontOfSize_(14))
        containerView.addSubview_(tableSubTitleLabel)

        # ------------------------------------------ #
        #               Toolbar button               #
        # ------------------------------------------ #
        rect = NSMakeRect(20, 20, 67, 21)
        segControl = NSSegmentedControl.alloc().initWithFrame_(rect)
        segControl.setSegmentCount_(2)
        segControl.setSegmentStyle_(NSSegmentStyleSmallSquare)
        segControl.setWidth_forSegment_(32, 0)
        segControl.setWidth_forSegment_(32, 1)
        segControl.setImage_forSegment_(
            NSImage.imageNamed_(NSImageNameAddTemplate), 0)
        segControl.setImage_forSegment_(
            NSImage.imageNamed_(NSImageNameRemoveTemplate), 1)
        segControl.setTarget_(self)
        segControl.setAction_("segControlDidClicked:")
        containerView.addSubview_(segControl)

        rect = NSMakeRect(86, 21,
                          self.WIDTH - 2 * margin - rect.size.width + 1, 21)
        toolbar = NSButton.alloc().initWithFrame_(rect)
        toolbar.setTitle_("")
        toolbar.setRefusesFirstResponder_(True)
        toolbar.setBezelStyle_(NSBezelStyleSmallSquare)
        containerView.addSubview_(toolbar)

        height = tableSubTitleLabel.frame().origin.y - segControl.frame(
        ).origin.y - margin - segControl.frame(
        ).size.height + 1 + tableSubTitleLabel.frame().size.height / 2
        rect = NSMakeRect(
            tableSubTitleLabel.frame().origin.x,
            tableSubTitleLabel.frame().origin.y -
            tableSubTitleLabel.frame().size.height / 2 - height, width, height)
        scrollView = NSScrollView.alloc().initWithFrame_(rect)
        scrollView.setBorderType_(NSBezelBorder)

        self.tableView = NSTableView.alloc().initWithFrame_(
            scrollView.bounds())
        self.tableView.setDataSource_(self)
        self.tableView.setDelegate_(self)
        self.tableView.setFocusRingType_(NSFocusRingTypeNone)

        # Path column
        pathCol = NSTableColumn.alloc().initWithIdentifier_(
            self.PATH_COL_IDENTIFIER)
        pathCol.setTitle_("Directory")  # <-- Table view directory column title
        pathCol.setWidth_(self.WIDTH * 0.8)
        textCell = NSTextFieldCell.alloc().init()
        textCell.setEditable_(True)
        textCell.setTarget_(self)
        pathCol.setDataCell_(textCell)

        # Enable column
        enableCol = NSTableColumn.alloc().initWithIdentifier_(
            self.ENALBE_COL_IDENTIFIER)
        enableCol.setTitle_("Enable?")  # <-- Enable column title
        enableCol.setWidth_(self.WIDTH * 0.2)
        cell = NSButtonCell.alloc().init()
        cell.setButtonType_(NSButtonTypeSwitch)
        cell.setTitle_("")
        cell.setTarget_(self)
        enableCol.setDataCell_(cell)

        self.tableView.addTableColumn_(pathCol)
        self.tableView.addTableColumn_(enableCol)

        scrollView.setDocumentView_(self.tableView)
        scrollView.setHasVerticalScroller_(True)
        containerView.addSubview_(scrollView)
        self.window().setContentView_(containerView)
Esempio n. 31
0
 def regular(size):
     return {NSFontAttributeName: NSFont.systemFontOfSize_(size)}
Esempio n. 32
0
    def openWindow(self):
        w = FloatingWindow((200, 242), title="Backdrop", closable=False)
        w.glyphList = List((10, 10, -10, 160), [{
            "Visibility": False,
            "Status": None,
            "Name": "None",
            "Position": 0,
            "layer": None
        }],
                           columnDescriptions=[{
                               "title": "Visibility",
                               "cell": CheckBoxListCell(),
                               "width": 30
                           }, {
                               "title": "Status",
                               "width": 20,
                               "editable": False
                           }, {
                               "title": "Name",
                               "width": 80,
                               "editable": False
                           }, {
                               "title": "Position",
                               "width": 30
                           }, {
                               "title": "layer",
                               "width": -3,
                               "editable": False
                           }],
                           showColumnTitles=False,
                           rowHeight=20,
                           drawFocusRing=False,
                           enableDelete=True,
                           editCallback=self.listEdited)
        w.addGlyphButton = Button((10, 180, 90, 20),
                                  "Add Glyph",
                                  callback=self.glyphPopover)
        w.transLeftButton = Button((128, 180, 30, 20),
                                   u"←",
                                   callback=self.moveLeft)
        w.transRightButton = Button((160, 180, 30, 20),
                                    u"→",
                                    callback=self.moveRight)
        w.alignButton = SegmentedButton(
            (10, 209, -7, 21),
            [dict(title=u"􀌀"),
             dict(title=u"􀌁"),
             dict(title=u"􀌂")],
            callback=self.changeAlignment,
            selectionStyle="one")
        w.alignButton.set(self.alignment)
        w.open()

        fm = NSFontManager.sharedFontManager()
        systemFont = NSFont.systemFontOfSize_(NSFont.systemFontSize())
        self.italicFont = fm.fontWithFamily_traits_weight_size_(
            systemFont.fontName(), NSItalicFontMask, 5, systemFont.pointSize())
        self.boldFont = fm.fontWithFamily_traits_weight_size_(
            systemFont.fontName(), NSUnitalicFontMask, 8,
            systemFont.pointSize())

        self.currentWindow = w
        self.toolStatus = True
        try:
            self.currentGlyph = Glyphs.font.selectedLayers[0]
        except:
            pass

        self.refreshGL()
        self.updateWindowUI()
Esempio n. 33
0
class LightMeterTool(BaseEventTool):

    lightMeterToolPrefsLibKey = "com.letterror.lightMeter.prefs"
    textAttributes = {
        NSFontAttributeName : NSFont.systemFontOfSize_(10),
        NSForegroundColorAttributeName : NSColor.whiteColor(),
    }

    def setup(self):
        self.sliderWindow = None
        self.insides = {}
        self._hits = {}
        self._misses = {}
        self.kernel = None
        self.diameterStep = 5
        self.fullColorMarkerSize = 2
        self.diameterMarkerWidth = 0.4
        self.toolStep = 2
        self.isResizing = False
        self.pts = []
        self.dupes = set()
        self.samples = {}
        self.lastPoint = None
        self._insideColor = (35/255.0,60/255.0,29/255.0)    # photoshop
        self._outsideColor = (255/255.0,234/255.0,192/255.0)
        
        self.defaultPrefs = {
                'drawTail':      False,
                'toolStyle':     'fluid',    # grid
                'invert':        False,
                'diameter':      200,
                'toolDiameter':  30,
                'chunkSize':     5,
            }
        self.prefs = {}
        self.getPrefs()
        
    def getPrefs(self):
        # read the prefs from the font lib
        # so we have consistent tool prefs
        # between glyphs
        g = self.getGlyph()
        if g is None:
            # no font? no parent?
            self.prefs.update(self.defaultPrefs)
            return
        parentLib = g.getParent().lib
        if self.lightMeterToolPrefsLibKey in parentLib:
            self.prefs.update(parentLib[self.lightMeterToolPrefsLibKey])
        else:
            self.prefs.update(self.defaultPrefs)
    
    def storePrefs(self):
        # write the current tool preferences to the font.lib
        g = self.getGlyph()
        parentLib = g.getParent().lib
        if not self.lightMeterToolPrefsLibKey in parentLib:
            parentLib[self.lightMeterToolPrefsLibKey] = {}
        parentLib[self.lightMeterToolPrefsLibKey].update(self.prefs)

    def getKernel(self):
        kernelRadius = int(round((0.5*self.prefs['diameter'])/self.prefs['chunkSize']))
        self.kernel = getKernel(kernelRadius, angle=math.radians(30))
    
    def grid(self, pt):
        x, y = pt
        x = x - x%self.prefs['toolDiameter'] + 0.5*self.prefs['toolDiameter']
        y = y - y%self.prefs['toolDiameter'] + 0.5*self.prefs['toolDiameter']
        return x, y
        
    def draw(self, scale):
        # drawBackground(self
        if not hasattr(self, "prefs"):
            return
        s = self.prefs['toolDiameter']    # / scale
        last = None
        if not self.pts: return
        if self.prefs['drawTail']:
            drawThese = self.pts[:]
        else:
            drawThese = [self.pts[-1]]
        stroke(None)
        for (x,y), level, tdm in drawThese:
            key = (x,y),tdm
            if self.prefs['invert']:
                fill(1-level)
            else:
                fill(level)
            stroke(None)
            if self.prefs['toolStyle'] == "grid":
                rect(x-.5*tdm, y-0.5*tdm, tdm, tdm)
            else:
                oval(x-.5*tdm, y-0.5*tdm, tdm, tdm)
            if round(level, 3) == 0:
                stroke(None)
                fill(1)
                oval(x-.5*self.fullColorMarkerSize, y-.5*self.fullColorMarkerSize, self.fullColorMarkerSize, self.fullColorMarkerSize)
            elif round(level,3) == 1.0:
                stroke(None)
                fill(0)
                oval(x-.5*self.fullColorMarkerSize, y-.5*self.fullColorMarkerSize, self.fullColorMarkerSize, self.fullColorMarkerSize)
    
        self.drawDiameter(x, y, scale, showSize=self.isResizing)

        (x,y), level, tdm = drawThese[-1]
        if self.prefs['invert']:
            fill(1-level)
        else:
            fill(level)
        stroke(None)
        if self.prefs['toolStyle'] == "grid":
            rect(x-.5*tdm, y-0.5*tdm, tdm, tdm)
        else:
            oval(x-.5*tdm, y-0.5*tdm, tdm, tdm)
        
        tp, level, tdm = self.pts[-1]
        self.getNSView()._drawTextAtPoint(
            "%3.2f"%(100-100*level),
            self.textAttributes,
            tp,
            yOffset=-30,
            drawBackground=True,
            backgroundColor=NSColor.blueColor())

    def drawDiameter(self, x, y, scale=1, showSize=False):
        
        # draw points contributing to the level.
        s = self.prefs['chunkSize']
        stroke(None)
        for (px,py), v in self._hits.items():
            fill(self._outsideColor[0],self._outsideColor[1],self._outsideColor[2], v*80)
            oval(px-0.5*s, py-0.5*s, s, s)
        for (px,py), v in self._misses.items():
            fill(self._insideColor[0],self._insideColor[1],self._insideColor[2], v*80)
            oval(px-0.5*s, py-0.5*s, s, s)

        stroke(0.5)
        strokeWidth(self.diameterMarkerWidth*scale)
        fill(None)
        oval(x-0.5*self.prefs['diameter'], y-0.5*self.prefs['diameter'], self.prefs['diameter'], self.prefs['diameter'])

        if showSize:
            tp = x, y + 20*scale
            self.getNSView()._drawTextAtPoint(
                u"⌀ %3.2f"%(self.prefs['diameter']),
                self.textAttributes,
                tp,
                yOffset=(.5*self.prefs['diameter'])/scale,
                drawBackground=True,
                backgroundColor=NSColor.grayColor())

    def mouseDown(self, point, event):
        mods = self.getModifiers()
        cmd = mods['commandDown'] > 0
        self.isResizing = False
        if cmd:
            self.clear()
            
    def clear(self):
        self.pts = []
        self.dupes = set()
        self.samples = {}
    
    def drawMargins(self):
        # sample the whole box
        g = self.getGlyph()
        if g.box is None:
            return
        xMin, yMin, xMax, yMax = self.getGlyph().box
        for y in range(yMin, yMax+self.prefs['toolDiameter'], self.prefs['toolDiameter']):
                samplePoint = self.grid((xMin,y))
                self.processPoint(samplePoint)
                samplePoint = self.grid((0,y))
                self.processPoint(samplePoint)
                samplePoint = self.grid((xMax,y))
                self.processPoint(samplePoint)
                samplePoint = self.grid((g.width,y))
                self.processPoint(samplePoint)
            
    def keyDown(self, event):
        letter = event.characters()
        if letter == "i":
            # invert the paint color on drawing
            self.prefs['invert'] = not self.prefs['invert']
            self.storePrefs()
        elif letter == "M":
            # draw the whole bounds
            self.drawMargins()
        elif letter == "p":
            if self.prefs['toolStyle'] == "grid":
                self.prefs['toolStyle'] = "fluid"
            else:
                self.prefs['toolStyle'] = 'grid'
            self.storePrefs()
        elif letter == "t":
            self.prefs['drawTail'] = not self.prefs['drawTail']
            self.storePrefs()
        elif letter == "c":
            self.clear()

        mods = self.getModifiers()
        cmd = mods['commandDown'] > 0
        option = mods['optionDown'] > 0
        arrows = self.getArrowsKeys()
        if cmd:
            # change the grid size
            if arrows['up']:
                self.prefs['toolDiameter'] += self.toolStep
            elif arrows['down']:
                self.prefs['toolDiameter'] -= self.toolStep
                self.prefs['toolDiameter'] = abs(self.prefs['toolDiameter'])
            #self.clear()
            self.getKernel()
            self.calcSample(self.lastPoint)
            self.storePrefs()
        elif option:
            # change the chunk size
            if arrows['left']:
                self.prefs['chunkSize'] += 1
            elif arrows['right']:
                self.prefs['chunkSize'] = max(4, min(40, self.prefs['chunkSize'] - 1))
            self.getKernel()
            self.calcSample(self.lastPoint)
            self.storePrefs()
        else:
            self.isResizing = True
            if arrows['up']:
                self.prefs['diameter'] += self.diameterStep
            elif arrows['down']:
                self.prefs['diameter'] -= self.diameterStep
                self.prefs['diameter'] = abs(self.prefs['diameter'])
            #self.clear()
            self.getKernel()
            self.calcSample(self.lastPoint)
            self.storePrefs()
        UpdateCurrentGlyphView()
        
    def mouseDragged(self, point, delta):
        """ Calculate the blurred gray level for this point. """
        self.isResizing = False
        self.lastPoint = samplePoint = point.x, point.y
        if self.prefs['toolStyle'] == "grid":
            self.lastPoint = samplePoint = self.grid(samplePoint)
        self.processPoint(samplePoint)
    
    def processPoint(self, samplePoint):
        if (self.prefs['toolDiameter'], samplePoint) in self.dupes:
            level = self.samples.get((samplePoint, self.prefs['toolDiameter']))['level']
            i = self.pts.index((samplePoint, level, self.prefs['toolDiameter']))
            del self.pts[i]
            self.pts.append((samplePoint, level, self.prefs['toolDiameter']))
        self.calcSample(samplePoint)
        
    def calcSample(self, samplePoint):
        if samplePoint is None:
            return
        if not self.kernel:
            self.getKernel()
        level = 0
        self._insides = {}
        self._hits = {}
        self._misses = {}
        
        nsPathObject =  self.getGlyph().getRepresentation("defconAppKit.NSBezierPath")
        for pos, val in self.kernel.items():
            thisPos = samplePoint[0]+pos[0]*self.prefs['chunkSize'], samplePoint[1]+pos[1]*self.prefs['chunkSize']
            #a = math.atan2(pos[0], pos[1])
            if thisPos not in self._insides:
                self._insides[thisPos] = nsPathObject.containsPoint_(thisPos)
            if not self._insides[thisPos]:
                level += self.kernel.get(pos)
                self._hits[thisPos] = self.kernel.get(pos)
            else:
                self._misses[thisPos] = self.kernel.get(pos)
        self.pts.append((samplePoint, level, self.prefs['toolDiameter']))
        self.samples[(samplePoint, self.prefs['toolDiameter'])] = dict(level=level)
        self.dupes.add((self.prefs['toolDiameter'], samplePoint))
        return level
        
    def getToolbarTip(self):
        return 'LightMeter'

    def getToolbarIcon(self):
        ## return the toolbar icon
        return toolbarIcon
Esempio n. 34
0
def drawGlyphPoints(glyph,
                    scale,
                    rect,
                    drawStartPoint=True,
                    drawOnCurves=True,
                    drawOffCurves=True,
                    drawCoordinates=True,
                    color=None,
                    backgroundColor=None,
                    flipped=False):
    layer = glyph.layer
    if layer is not None:
        if layer.color is not None:
            color = colorToNSColor(layer.color)
    if color is None:
        color = getDefaultColor("glyphPoints")
    if backgroundColor is None:
        backgroundColor = getDefaultColor("background")
    # get the outline data
    outlineData = glyph.getRepresentation("defconAppKit.OutlineInformation")
    points = []
    # start point
    if drawStartPoint and outlineData["startPoints"]:
        startWidth = startHeight = 15 * scale
        startHalf = startWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point, angle in outlineData["startPoints"]:
            x, y = point
            if angle is not None:
                path.moveToPoint_((x, y))
                path.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_clockwise_(
                    (x, y), startHalf, angle - 90, angle + 90, True)
                path.closePath()
            else:
                path.appendBezierPathWithOvalInRect_(
                    ((x - startHalf, y - startHalf), (startWidth,
                                                      startHeight)))
        r = color.redComponent()
        g = color.greenComponent()
        b = color.blueComponent()
        a = color.alphaComponent()
        a *= 0.3
        startPointColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
            r, g, b, a)
        startPointColor.set()
        path.fill()
    # off curve
    if drawOffCurves and outlineData["offCurvePoints"]:
        # lines
        color.set()
        for point1, point2 in outlineData["bezierHandles"]:
            drawLine(point1, point2)
        # points
        offWidth = 3 * scale
        offHalf = offWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point in outlineData["offCurvePoints"]:
            x, y = point["point"]
            points.append((x, y))
            x -= offHalf
            y -= offHalf
            path.appendBezierPathWithOvalInRect_(
                ((x, y), (offWidth, offWidth)))
        path.setLineWidth_(3.0 * scale)
        color.set()
        path.stroke()
        backgroundColor.set()
        path.fill()
        color.set()
        path.setLineWidth_(1.0 * scale)
    # on curve
    if drawOnCurves and outlineData["onCurvePoints"]:
        width = 4 * scale
        half = width / 2.0
        smoothWidth = 5 * scale
        smoothHalf = smoothWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point in outlineData["onCurvePoints"]:
            x, y = point["point"]
            points.append((x, y))
            if point["smooth"]:
                x -= smoothHalf
                y -= smoothHalf
                path.appendBezierPathWithOvalInRect_(
                    ((x, y), (smoothWidth, smoothWidth)))
            else:
                x -= half
                y -= half
                path.appendBezierPathWithRect_(((x, y), (width, width)))
        backgroundColor.set()
        path.setLineWidth_(3.0 * scale)
        path.stroke()
        color.set()
        path.fill()
    # coordinates
    if drawCoordinates:
        r = color.redComponent()
        g = color.greenComponent()
        b = color.blueComponent()
        a = color.alphaComponent()
        a *= 0.6
        color = NSColor.colorWithCalibratedRed_green_blue_alpha_(r, g, b, a)
        fontSize = 9
        attributes = {
            NSFontAttributeName: NSFont.systemFontOfSize_(fontSize),
            NSForegroundColorAttributeName: color
        }
        for x, y in points:
            posX = x
            posY = y - 3
            x = round(x, 1)
            if int(x) == x:
                x = int(x)
            y = round(y, 1)
            if int(y) == y:
                y = int(y)
            text = "%d  %d" % (x, y)
            drawTextAtPoint(text, (posX, posY),
                            scale,
                            attributes=attributes,
                            xAlign="center",
                            yAlign="top",
                            flipped=flipped)
Esempio n. 35
0
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)
Esempio n. 36
0
class ZoneCheckerTool(EditingTool):

    zoneCheckerToolPrefsLibKey = "com.letterror.zoneChecker.prefs"
    textAttributes = {
        NSFontAttributeName: NSFont.systemFontOfSize_(10),
        NSForegroundColorAttributeName: NSColor.whiteColor(),
    }

    margin = 3  # how far off are points?

    def setup(self):
        self.markColor = (255 / 255.0, 0 / 255.0, 0 / 255.0, 0.8)
        self.okColor = (0 / 255.0, 0 / 255.0, 255 / 255.0, 0.8)
        self.outside = []
        self.inside = []

    def _p(self, items):
        if len(items) % 2 != 0:
            return []
        return [(items[i], items[i + 1]) for i in range(0, len(items) - 1, 2)]

    def findMisalignedPoints(self):
        g = CurrentGlyph()
        f = CurrentFont()
        if f is None:
            return
        if not g:
            return

        self.outside = []
        self.inside = []
        zones = []

        for a, b in self._p(f.info.postscriptBlueValues):
            zones.append((a, b))
        for a, b in self._p(f.info.postscriptOtherBlues):
            zones.append((a, b))
        for a, b in self._p(f.info.postscriptFamilyBlues):
            zones.append((a, b))
        for c in g.contours:
            for p in c.points:
                if p.type == "offCurve":
                    continue
                y = p.y
                for a, b in zones:
                    if (a - self.margin < y < b + self.margin):
                        if not (a <= y <= b):
                            self.outside.append((p.x, p.y))
                        else:
                            self.inside.append((p.x, p.y))

    def draw(self, scale):
        self.findMisalignedPoints()
        if scale == 0:
            return
        save()
        fill(None)
        for x, y in self.outside:
            d = scale * 25
            d2 = 2 * d
            strokeWidth(20 * scale)
            stroke(self.markColor[0], self.markColor[1], self.markColor[2],
                   self.markColor[3])
            oval(x - d, y - d, d2, d2)
        for x, y in self.inside:
            d = scale * 9
            d2 = 2 * d
            strokeWidth(2 * scale)
            stroke(self.okColor[0], self.okColor[1], self.okColor[2],
                   self.okColor[3])
            oval(x - d, y - d, d2, d2)
        restore()

        # self.getNSView()._drawTextAtPoint(
        #     "%3.2f"%(100-100*level),
        #     self.textAttributes,
        #     tp,
        #     yOffset=-30,
        #     drawBackground=True,
        #     backgroundColor=NSColor.blueColor())

    def mouseDown(self, point, event):
        pass
        # mods = self.getModifiers()
        # cmd = mods['commandDown'] > 0
        # self.isResizing = False
        # if cmd:
        #     self.clear()

    def clear(self):
        self.marked = None
        pass
        # self.pts = []
        # self.dupes = set()
        # self.samples = {}

    def keyDown(self, event):
        pass
        # letter = event.characters()
        # if letter == "i":
        #     # invert the paint color on drawing
        #     self.prefs['invert'] = not self.prefs['invert']
        #     self.storePrefs()
        # UpdateCurrentGlyphView()

    def mouseDragged(self, point, delta):
        """ Calculate the blurred gray level for this point. """
        pass

    def getToolbarTip(self):
        return 'ZoneChecker'

    def getToolbarIcon(self):
        ## return the toolbar icon
        return toolbarIcon
Esempio n. 37
0
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
currentStrokeWidth = 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):
Esempio n. 38
0
#
#		Python GUI - Standard Fonts - PyObjC
#

from AppKit import NSFont
from GUI import Font

system_font = Font._from_ns_font(NSFont.systemFontOfSize_(0))
application_font = Font._from_ns_font(NSFont.userFontOfSize_(0))
Esempio n. 39
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())
Esempio n. 40
0
	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))
Esempio n. 41
0
 def _setSizeStyle(self, sizeStyle):
     value = sizeStyle
     self._nsObject.cell().setControlSize_(value)
     font = NSFont.systemFontOfSize_(value)
     self._nsObject.setFont_(font)
     self._nsObject.setTextColor_(self.color)
Esempio n. 42
0
def drawGlyphPoints(glyph,
                    scale,
                    rect,
                    drawStartPoint=False,
                    drawOnCurves=False,
                    drawOffCurves=False,
                    drawCoordinates=False,
                    colorCornerPointsFill=None,
                    colorCornerPointsStroke=None,
                    colorTangentPointsFill=None,
                    colorTangentPointsStroke=None,
                    colorCurvePointsFill=None,
                    colorCurvePointsStroke=None,
                    colorOffCurvePointsFill=None,
                    colorOffCurvePointsStroke=None,
                    colorOffCurveQuadPointsStroke=None,
                    colorSmoothPointStroke=None,
                    colorStartPointsArrow=None,
                    colorOpenStartPointsArrow=None,
                    colorPointCoordinate=None,
                    colorPointCoordinateBackground=None,
                    colorHandlesStroke=None,
                    colorHandlesQuadStroke=None,
                    backgroundColor=None,
                    pointSizeOnCurve=False,
                    pointSizeOffCurve=False,
                    flipped=False):

    # get the outline data
    outlineData = glyph.getRepresentation("defconAppKit.OutlineInformation")
    points = []
    # start point
    if drawStartPoint and outlineData["startPoints"]:
        startWidth = startHeight = 15 * scale
        startHalf = startWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point, angle in outlineData["startPoints"]:
            x, y = point
            if angle is not None:
                path.moveToPoint_((x, y))
                path.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_clockwise_(
                    (x, y), startHalf, angle - 90, angle + 90, True)
                path.closePath()
            else:
                path.appendBezierPathWithOvalInRect_(
                    ((x - startHalf, y - startHalf), (startWidth,
                                                      startHeight)))
        colorStartPointsArrow.set()
        path.fill()
    # off curve
    if drawOffCurves and outlineData["offCurvePoints"]:
        # lines
        colorHandlesStroke.set()
        for point1, point2 in outlineData["bezierHandles"]:
            drawLine(point1, point2)
        # points
        offWidth = pointSizeOffCurve * scale
        offHalf = offWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point in outlineData["offCurvePoints"]:
            x, y = point["point"]
            points.append((x, y))
            x -= offHalf
            y -= offHalf
            path.appendBezierPathWithOvalInRect_(
                ((x, y), (offWidth, offWidth)))
        path.setLineWidth_(2.0 * scale)
        colorOffCurvePointsStroke.set()
        path.stroke()
        #backgroundColor.set()
        #path.fill()
        colorOffCurvePointsFill.set()
        path.setLineWidth_(1.0 * scale)
        path.fill()
    # on curve
    if drawOnCurves and outlineData["onCurvePoints"]:
        width = pointSizeOnCurve * scale
        half = width / 2.0
        triOuter = width / math.sqrt(3)
        triInner = width * math.sqrt(3) / 6.0
        for point in outlineData["onCurvePoints"]:
            path = NSBezierPath.bezierPath()
            x, y = point["point"]
            points.append((x, y))
            if point["segmentType"] == "curve":
                if point["smooth"]:
                    path.appendBezierPathWithOvalInRect_(
                        ((x - half, y - half), (width, width)))
                    colorSmoothPointStroke.set()
                    path.setLineWidth_(2 * scale)
                    path.stroke()
                    colorCurvePointsFill.set()
                    path.fill()
                else:
                    path.appendBezierPathWithOvalInRect_(
                        ((x - half, y - half), (width, width)))
                    colorCurvePointsStroke.set()
                    path.setLineWidth_(2 * scale)
                    path.stroke()
                    colorCurvePointsFill.set()
                    path.fill()
            elif point["segmentType"] == "line":
                if point["smooth"]:
                    path.moveToPoint_((x - half, y - triInner))
                    path.lineToPoint_((x, y + triOuter))
                    path.lineToPoint_((x + half, y - triInner))
                    #path.lineToPoint_((x-half, y-third))
                    path.closePath()
                    #path.appendBezierPathWithRect_(((x-half, y-half), (width, width)))
                    colorTangentPointsStroke.set()
                    path.setLineWidth_(2 * scale)
                    path.stroke()
                    colorTangentPointsFill.set()
                    path.fill()
                else:
                    path.appendBezierPathWithRect_(
                        ((x - half, y - half), (width, width)))
                    colorCornerPointsStroke.set()
                    path.setLineWidth_(2 * scale)
                    path.stroke()
                    colorCornerPointsFill.set()
                    path.fill()
        # path.appendBezierPathWithOvalInRect_(((x, y), (smoothWidth, smoothWidth)))
        # path.appendBezierPathWithRect_(((x, y), (width, width)))
    # coordinates
    if drawCoordinates:
        fontSize = 9
        attributes = {
            NSFontAttributeName: NSFont.systemFontOfSize_(fontSize),
            NSForegroundColorAttributeName: colorPointCoordinate
        }
        for x, y in points:
            posX = x
            posY = y - 3
            x = round(x, 1)
            if int(x) == x:
                x = int(x)
            y = round(y, 1)
            if int(y) == y:
                y = int(y)
            text = "%d  %d" % (x, y)
            drawTextAtPoint(text, (posX, posY),
                            scale,
                            attributes=attributes,
                            xAlign="center",
                            yAlign="top",
                            flipped=flipped)
Esempio n. 43
0
 def _setSizeStyle(self, value):
     value = _sizeStyleMap[value]
     self._nsObject.setControlSize_(value)
     font = NSFont.systemFontOfSize_(
         NSFont.systemFontSizeForControlSize_(value))
     self._nsObject.setFont_(font)
Esempio n. 44
0
def drawGlyphPoints(glyph, scale, rect, drawStartPoint=True, drawOnCurves=True, drawOffCurves=True, drawCoordinates=True, color=None, backgroundColor=None, flipped=False):
    layer = glyph.layer
    if layer is not None:
        if layer.color is not None:
            color = colorToNSColor(layer.color)
    if color is None:
        color = getDefaultColor("glyphPoints")
    if backgroundColor is None:
        backgroundColor = getDefaultColor("background")
    # get the outline data
    outlineData = glyph.getRepresentation("defconAppKit.OutlineInformation")
    points = []
    # start point
    if drawStartPoint and outlineData["startPoints"]:
        startWidth = startHeight = 15 * scale
        startHalf = startWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point, angle in outlineData["startPoints"]:
            x, y = point
            if angle is not None:
                path.moveToPoint_((x, y))
                path.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_clockwise_(
                    (x, y), startHalf, angle - 90, angle + 90, True)
                path.closePath()
            else:
                path.appendBezierPathWithOvalInRect_(((x - startHalf, y - startHalf), (startWidth, startHeight)))
        r = color.redComponent()
        g = color.greenComponent()
        b = color.blueComponent()
        a = color.alphaComponent()
        a *= 0.3
        startPointColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(r, g, b, a)
        startPointColor.set()
        path.fill()
    # off curve
    if drawOffCurves and outlineData["offCurvePoints"]:
        # lines
        color.set()
        for point1, point2 in outlineData["bezierHandles"]:
            drawLine(point1, point2)
        # points
        offWidth = 3 * scale
        offHalf = offWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point in outlineData["offCurvePoints"]:
            x, y = point["point"]
            points.append((x, y))
            x -= offHalf
            y -= offHalf
            path.appendBezierPathWithOvalInRect_(((x, y), (offWidth, offWidth)))
        path.setLineWidth_(3.0 * scale)
        color.set()
        path.stroke()
        backgroundColor.set()
        path.fill()
        color.set()
        path.setLineWidth_(1.0 * scale)
    # on curve
    if drawOnCurves and outlineData["onCurvePoints"]:
        width = 4 * scale
        half = width / 2.0
        smoothWidth = 5 * scale
        smoothHalf = smoothWidth / 2.0
        path = NSBezierPath.bezierPath()
        for point in outlineData["onCurvePoints"]:
            x, y = point["point"]
            points.append((x, y))
            if point["smooth"]:
                x -= smoothHalf
                y -= smoothHalf
                path.appendBezierPathWithOvalInRect_(((x, y), (smoothWidth, smoothWidth)))
            else:
                x -= half
                y -= half
                path.appendBezierPathWithRect_(((x, y), (width, width)))
        backgroundColor.set()
        path.setLineWidth_(3.0 * scale)
        path.stroke()
        color.set()
        path.fill()
    # coordinates
    if drawCoordinates:
        r = color.redComponent()
        g = color.greenComponent()
        b = color.blueComponent()
        a = color.alphaComponent()
        a *= 0.6
        color = NSColor.colorWithCalibratedRed_green_blue_alpha_(r, g, b, a)
        fontSize = 9
        attributes = {
            NSFontAttributeName: NSFont.systemFontOfSize_(fontSize),
            NSForegroundColorAttributeName: color
        }
        for x, y in points:
            posX = x
            posY = y - 3
            x = round(x, 1)
            if int(x) == x:
                x = int(x)
            y = round(y, 1)
            if int(y) == y:
                y = int(y)
            text = "%d  %d" % (x, y)
            drawTextAtPoint(text, (posX, posY), scale, attributes=attributes, xAlign="center", yAlign="top", flipped=flipped)
Esempio n. 45
0
 def _setSizeStyle(self, value):
     value = _sizeStyleMap[value]
     self._nsObject.cell().setControlSize_(value)
     font = NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(value))
     self._nsObject.setFont_(font)
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
Esempio n. 47
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()
Esempio n. 48
0
    def layout(self):
        self._thumbnail = ThumbnailBoxView.alloc().initWithFrame_(NSZeroRect)
        self._thumbnail.setImage_(Images.Box64)
        self._thumbnail.setImageAlignment_(NSImageAlignCenter)
        self._thumbnail.setImageScaling_(NSScaleToFit)
        self._thumbnail.setFrameSize_(self.THUMBNAIL_SIZE)
        self._thumbnail.setFrameOrigin_(self.THUMBNAIL_ORIGIN)
        self._thumbnail.setShadowOffset_(self.SHADOW_OFFSET)
        self._thumbnail.setShadowBlurRadius_(self.SHADOW_BLUR)
        self._thumbnail.setShadowColor_(NSColor.blackColor().colorWithAlphaComponent_(0.3))
        self._label = NSTextField.createLabelWithText_font_('', NSFont.boldSystemFontOfSize_(13))
        self._label.setFrameOrigin_(self.LABEL_ORIGIN)
        self._progress_bar = NSProgressIndicator.alloc().initWithFrame_(NSRect(self.PROGRESS_ORIGIN, self.PROGRESS_SIZE))
        self._progress_bar.setStyle_(NSProgressIndicatorBarStyle)
        self._progress_bar.setIndeterminate_(YES)
        self._progress_bar.setFrameOrigin_(self.PROGRESS_ORIGIN)
        self._estimate = NSTextField.createLabelWithText_font_('', NSFont.systemFontOfSize_(NSFont.smallSystemFontSize()))
        self._estimate.setFrameOrigin_(self.ESTIMATE_ORIGIN)
        self._hide_button = self.addNormalRoundButtonWithTitle_action_(MiscStrings.hide_button, self.handleHideButton_)
        self._hide_button.setKeyEquivalent_(ENTER_KEY)
        self._hide_button.alignRightInSuperview()
        self._hide_button.alignBottomInSuperview()
        self._cancel_button = self.addNormalRoundButtonWithTitle_action_(MiscStrings.cancel_button, self.handleCancelButton_)
        self._cancel_button.placeLeftOfButton_(self._hide_button)
        self.addSubview_(self._thumbnail)
        self.addSubview_(self._label)
        self.addSubview_(self._progress_bar)
        self.addSubview_(self._estimate)

        @message_sender(AppHelper.callAfter)
        def handleMessage(message):
            self._label.setStringValue_(message)
            self._label.sizeToFit()

        @message_sender(AppHelper.callAfter)
        def handleTotalBytes(total_bytes):
            self._progress_bar.setIndeterminate_(YES if total_bytes == 0 else NO)
            self._progress_bar.setMinValue_(0.0)
            self._progress_bar.setMaxValue_(total_bytes)
            self._progress_bar.setDoubleValue_(self.ui.cur_bytes.get())

        @message_sender(AppHelper.callAfter)
        def handleCurBytes(cur_bytes):
            self._progress_bar.setDoubleValue_(cur_bytes)
            self._estimate.setStringValue_(self.ui.get_remaining_message())
            self._estimate.sizeToFit()

        @message_sender(AppHelper.callAfter)
        def handleLastPhoto(path):
            if path:
                if time.time() - self.last_photo_time > self.THUMBNAIL_TIMEOUT:
                    image = NSImage.alloc().initByReferencingFile_(unicode(path))
                    if image.isValid():
                        self._thumbnail.setBorder_(True)
                        self._thumbnail.setImage_(image)
                        self.last_photo_time = time.time()
            else:
                self._thumbnail.setBorder_(False)
                self._thumbnail.setImage_(Images.Box64)

        handleMessage(self.ui.message.get())
        handleTotalBytes(self.ui.total_bytes.get())
        handleCurBytes(self.ui.cur_bytes.get())
        handleLastPhoto(self.ui.last_photo.get())
        self.ui.message.register(handleMessage)
        self.ui.total_bytes.register(handleTotalBytes)
        self.ui.cur_bytes.register(handleCurBytes)
        self.ui.last_photo.register(handleLastPhoto)
Esempio n. 49
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
Esempio n. 50
0
def _drawArrow(position, kind, size, vector=(-1, 1), label_size=1):
        angle = atan2(vector[0], -vector[1])
        print vector, "%0.2f°" % degrees(angle)
        x, y = position
        head_ratio = 0.7
        w = size * 0.5
        tail_width = 0.3
        chin = 0.5 * (w - w * tail_width) # part under the head
        
        NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.9, 0.1, 0.0, 0.85 ).set()
        t = NSAffineTransform.transform()
        t.translateXBy_yBy_(x, y)
        t.rotateByRadians_(angle)
        myPath = NSBezierPath.alloc().init()
        
        myPath.moveToPoint_(         (0, 0)                                       )
        myPath.relativeLineToPoint_( (-size * head_ratio,        w * 0.5)         )
        myPath.relativeLineToPoint_( (0,                         -chin)           )
        myPath.relativeLineToPoint_( (-size * (1 - head_ratio),  0)               )
        myPath.relativeLineToPoint_( (0,                         -w * tail_width) )
        myPath.relativeLineToPoint_( (size * (1 - head_ratio),   0)               )
        myPath.relativeLineToPoint_( (0,                         -chin)           )
        myPath.closePath()
        myPath.transformUsingAffineTransform_(t)
        myPath.fill()
        
        drawPath(myPath)
        
        myString = NSString.string().stringByAppendingString_(kind)
        attrs = {
            NSFontAttributeName:            NSFont.systemFontOfSize_(label_size),
            NSForegroundColorAttributeName: NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.4, 0.4, 0.6, 0.7 ),
        }
        bbox = myString.sizeWithAttributes_(attrs)
        #print bbox
        
        p = NSPoint()
        bw = bbox.width
        bh = bbox.height
        
        #print "   ", cos(angle)
        if -0.5 * pi < angle <= 0.5 * pi:
            p.x, p.y = (
                - size - 20 - bh/2 * sin(angle) - bw/2 * cos(angle), # + bw/2.0 * cos(angle - pi)
                0
            )
        else:
            p.x, p.y = (
                - size - 20 + bh/2 * sin(angle) + bw/2 * cos(angle), # + bw/2.0 * cos(angle - pi)
                0,
            )
        p = t.transformPoint_(p)
        #print p
        
        #fontSize(label_size)
        #text(kind, (p.x - bbox.width/2, p.y - bbox.height/2))
        fill(None)
        rect(p.x - bbox.width/2, p.y - bbox.height/2, bbox.width, bbox.height)
        fill(1, 0, 0)
        #oval(p.x -bh/2.0 , p.y -bh/2.0, bh, bh)
        #myString.drawAtPoint_withAttributes_(p, attrs)
        rr = NSRect(origin=(p.x -bh/2.0, p.y -bw/2.0), size=(bw, bh))
        #print rr
        
        myString.drawInRect_withAttributes_(rr, attrs)
        myString.drawAtPoint_withAttributes_(p, attrs)