コード例 #1
0
    def background(self, layer):

        # Fills background path of current glyph with non-photo blue
        NSColor.colorWithRed_green_blue_alpha_(.643, .867, .929, .3).set()
        if layer.background.bezierPath:
            layer.background.bezierPath.fill()
        # Fills background path of current component glyph with vermillion
        NSColor.colorWithRed_green_blue_alpha_(.89, .259, .204, .3).set()
        for backgroundComponent in layer.background.components:
            backgroundComponent.bezierPath.fill()
コード例 #2
0
 def icon_setter(self, _=False):
     if (self.started or not _) and self.render_icon:
         p = (sum(self.current_passthrough_volume) / len(self.current_passthrough_volume) * 2.5) ** 0.25 if _ else 0
         img = NSImage.alloc().initWithSize_((11, 26))
         img.lockFocus()
         fp = NSBezierPath.bezierPathWithRect_(((2, 2), (7, 22)))
         NSColor.darkGrayColor().set()
         fp.fill()
         rp = NSBezierPath.bezierPathWithRect_(((3, 3), (5, p * 20)))
         if p > 0.90:
             NSColor.colorWithRed_green_blue_alpha_((0.5 if self.dark else 1), 0.15, 0.15, 1).set()
         elif p > 0.60:
             NSColor.\
                 colorWithRed_green_blue_alpha_((0.5 if self.dark else 1), (0.5 if self.dark else 0.9), 0, 1).set()
         else:
             NSColor.colorWithRed_green_blue_alpha_(0, (0 if self.dark else 1), (0.5 if self.dark else 0), 1).set()
         rp.fill()
         img.unlockFocus()
         self._icon_nsimage = img
         try:
             self._nsapp.setStatusBarIcon()
         except AttributeError:
             pass
コード例 #3
0
ファイル: Auto Bumper.py プロジェクト: NaN-xyz/Glyphs-Scripts
    def __init__(self):
        # register prefs if run for the first time:
        if not Glyphs.defaults["com.mekkablue.Bumper.kernStrings"]:
            self.RegisterPreferences()

        # Window 'self.w':
        windowWidth = 500
        windowHeight = 365
        windowWidthResize = 500  # user can resize width by this value
        windowHeightResize = 500  # user can resize height by this value
        self.w = vanilla.FloatingWindow(
            (windowWidth, windowHeight),  # default window size
            "Auto Bumper",  # window title
            minSize=(windowWidth, windowHeight),  # minimum size (for resizing)
            maxSize=(windowWidth + windowWidthResize, windowHeight +
                     windowHeightResize),  # maximum size (for resizing)
            autosaveName=
            "com.mekkablue.Bumper.mainwindow"  # stores last window position and size
        )

        # UI elements:
        inset, lineHeight, currentHeight = 14, 24, -10
        currentHeight += lineHeight

        self.w.text_1 = vanilla.TextBox(
            (inset, currentHeight, -inset, 14),
            "Add supplementary kerning for specified glyphs in the current master:",
            sizeStyle='small')
        currentHeight += lineHeight

        self.w.swapButton = vanilla.SquareButton(
            (-inset - 20, currentHeight, -inset, 42),
            u"↰\n↲",
            sizeStyle='regular',
            callback=self.swap)

        self.w.text_left = vanilla.TextBox((inset, currentHeight + 3, 80, 14),
                                           "Left glyphs:",
                                           sizeStyle='small')
        self.w.leftGlyphs = vanilla.ComboBox(
            (inset + 80, currentHeight, -inset - 102, 18),
            self.kernStringList(self),
            callback=self.SavePreferences,
            sizeStyle='small')
        self.w.leftGlyphs.getNSComboBox().setToolTip_(
            u"Measures the specified glyphs from their right side to the following glyph. You can type the character ‘é’ or the slash-escaped glyph name ‘/eacute’. Or specify a category after an at sign ‘@Letter’, add a subcategory after a colon ‘@Letter:Lowercase’.\nAdd default strings in the text box at the bottom of the window. Expand the window at the bottom to access it."
        )
        self.w.leftIsGroups = vanilla.CheckBox(
            (-inset - 94, currentHeight + 1, -inset - 22, 17),
            u"As groups",
            value=True,
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.leftIsGroups.getNSButton().setToolTip_(
            u"If on, will measure only the specified glyph, but set the calculated kerning for the whole right group of the glyph (i.e., add group kerning). If off, will set the kerning for the glyph only (i.e., add an exception)."
        )
        currentHeight += lineHeight

        self.w.text_right = vanilla.TextBox((inset, currentHeight + 3, 80, 14),
                                            "Right glyphs:",
                                            sizeStyle='small')
        self.w.rightGlyphs = vanilla.ComboBox(
            (inset + 80, currentHeight, -inset - 102, 18),
            self.kernStringList(self),
            callback=self.SavePreferences,
            sizeStyle='small')
        self.w.rightGlyphs.getNSComboBox().setToolTip_(
            u"Measures from the previous glyphs to the specified glyphs to their left side. You can type the character ‘é’ or the slash-escaped glyph name ‘/eacute’. Or specify a category after an at sign ‘@Letter’, add a subcategory after a colon ‘@Letter:Lowercase’.\nAdd default strings in the text box at the bottom of the window. Expand the window at the bottom to access it."
        )
        self.w.rightIsGroups = vanilla.CheckBox(
            (-inset - 94, currentHeight + 1, -inset - 22, 17),
            u"As groups",
            value=True,
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.rightIsGroups.getNSButton().setToolTip_(
            u"If on, will measure only the specified glyph, but set the calculated kerning for the whole left group of the glyph (i.e., add group kerning). If off, will set the kerning for the glyph only (i.e., add an exception)."
        )
        currentHeight += lineHeight

        self.w.suffixText = vanilla.TextBox((inset, currentHeight + 3, 80, 14),
                                            u"Add suffix:",
                                            sizeStyle='small',
                                            selectable=True)
        self.w.suffix = vanilla.EditText((inset + 80, currentHeight, 150, 19),
                                         "",
                                         callback=self.SavePreferences,
                                         sizeStyle='small')
        self.w.suffix.getNSTextField().setToolTip_(
            "Looks for the suffixed version of the listed glyphs, with this suffix added to the name. Useful with .sc for smallcaps. Enter WITH the leading dot for dot suffixes. Can also be used with 'superior' for figures."
        )
        currentHeight += lineHeight

        self.w.text_21 = vanilla.TextBox((inset, currentHeight + 3, 80, 14),
                                         "Min distance:",
                                         sizeStyle='small')
        self.w.minDistance = vanilla.EditText(
            (inset + 80, currentHeight, 60, 19),
            "50",
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.minDistance.getNSTextField().setPlaceholderString_("50")
        self.w.minDistance.getNSTextField().setToolTip_(
            u"Adds kerning if the shortest distance between two glyphs is shorter than specified value. Leave blank or set to zero to ignore."
        )
        self.w.text_22 = vanilla.TextBox(
            (inset + 80 * 2, currentHeight + 3, 80, 14),
            "Max distance:",
            sizeStyle='small')
        self.w.maxDistance = vanilla.EditText(
            (inset + 80 * 3, currentHeight, 60, 19),
            "200",
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.maxDistance.getNSTextField().setPlaceholderString_("200")
        self.w.maxDistance.getNSTextField().setToolTip_(
            u"Adds kerning if the shortest distance between two glyphs is larger than specified value. Leave blank or set to zero to ignore."
        )
        self.w.text_23 = vanilla.TextBox(
            (inset + 80 * 4, currentHeight + 3, 80, 14),
            "Round by:",
            sizeStyle='small')
        self.w.roundFactor = vanilla.EditText(
            (inset + 80 * 5, currentHeight, -inset, 19),
            "10",
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.roundFactor.getNSTextField().setPlaceholderString_("10")
        self.w.roundFactor.getNSTextField().setToolTip_(
            u"Rounds calculated kerning. Leave blank or set to zero to ignore."
        )
        currentHeight += lineHeight

        self.w.text_speed = vanilla.TextBox((inset, currentHeight + 3, 42, 14),
                                            "Speed:",
                                            sizeStyle='small')
        self.w.speedPopup = vanilla.PopUpButton(
            (inset + 42, currentHeight + 1, 80, 17),
            ["very slow", "slow", "medium", "fast", "very fast"],
            callback=self.SavePreferences,
            sizeStyle='small')
        self.w.speedPopup.getNSPopUpButton().setToolTip_(
            u"Specifies the number of measurements. Measuring is processor-intensive and can take a while. Slow: many measurements, fast: few measurements."
        )
        intervalIndex = Glyphs.defaults["com.mekkablue.Bumper.speedPopup"]
        if intervalIndex is None:
            intervalIndex = 0
        self.w.text_speedExplanation = vanilla.TextBox(
            (inset + 42 + 90, currentHeight + 3, -15, 14),
            "Measuring every %i units." % intervalList[intervalIndex],
            sizeStyle='small')
        currentHeight += lineHeight

        self.w.text_6 = vanilla.TextBox((inset, currentHeight + 3, 130, 14),
                                        "Ignore height intervals:",
                                        sizeStyle='small')
        self.w.ignoreIntervals = vanilla.EditText(
            (inset + 130, currentHeight, -inset, 19),
            "",
            callback=self.SavePreferences,
            sizeStyle='small')
        self.w.ignoreIntervals.getNSTextField().setPlaceholderString_(
            "200:300, 400:370, -200:-150")
        self.w.ignoreIntervals.getNSTextField().setToolTip_(
            u"Does not measure on y coordinates in intervals specified as y1:y2. Separate multiple intervals with commas."
        )
        currentHeight += lineHeight

        self.w.keepExistingKerning = vanilla.CheckBox(
            (inset + 5, currentHeight, -inset, 17),
            u"Keep (don’t overwrite) existing kerning",
            value=True,
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.keepExistingKerning.getNSButton().setToolTip_(
            u"If the kern pair already exists in the font, it will not be overwritten."
        )
        currentHeight += lineHeight

        self.w.excludeNonExporting = vanilla.CheckBox(
            (inset + 5, currentHeight, 200, 17),
            u"Exclude non-exporting glyphs",
            value=True,
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.excludeNonExporting.getNSButton().setToolTip_(
            u"If one of the specified glyphs is not set to export, Auto Bumper will skip it."
        )
        self.w.avoidZeroKerning = vanilla.CheckBox(
            (inset + 200, currentHeight, -inset, 17),
            u"Avoid zero kerns",
            value=True,
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.avoidZeroKerning.getNSButton().setToolTip_(
            u"If the calculated (and rounded) kerning value is 0, it will not be added to the font."
        )
        currentHeight += lineHeight

        self.w.reportInMacroWindow = vanilla.CheckBox(
            (inset + 5, currentHeight, -inset, 17),
            u"Also report in Macro Window (a few seconds slower)",
            value=False,
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.reportInMacroWindow.getNSButton().setToolTip_(
            u"Outputs a detailed report in the Macro Window, and opens it.")
        currentHeight += lineHeight

        self.w.openNewTabWithKernPairs = vanilla.CheckBox(
            (inset + 5, currentHeight, -inset, 17),
            u"Open new Edit tab with new kern pairs",
            value=False,
            sizeStyle='small',
            callback=self.SavePreferences)
        self.w.openNewTabWithKernPairs.getNSButton().setToolTip_(
            u"If kern pairs were added, opens them in a new Edit tab, for inspection."
        )
        currentHeight += lineHeight

        # Progress Bar:
        self.w.bar = vanilla.ProgressBar((inset, currentHeight, -inset, 16))
        currentHeight += lineHeight

        # (Hidden) Preferences Kern Strings:
        self.w.kernStrings = vanilla.TextEditor((1, currentHeight, -1, -45),
                                                callback=self.SavePreferences)
        self.w.kernStrings.getNSTextView().setToolTip_(
            "Add your default kern strings here. They will show up in the left/right dropdowns at the top. Everything after a hashtag (#) is ignored. Use blank lines for structuring."
        )

        self.w.text_kernStrings = vanilla.TextBox(
            (inset, -14 - inset, -100 - inset, -inset),
            "Expand window below to access default strings.",
            sizeStyle='small')
        self.w.text_kernStrings.getNSTextField().setTextColor_(
            NSColor.colorWithRed_green_blue_alpha_(0, 0, 0, 0.2))

        # Run Button:
        self.w.runButton = vanilla.Button(
            (-100 - inset, -20 - inset, -inset, -inset),
            "Kern",
            sizeStyle='regular',
            callback=self.BumperMain)
        self.w.setDefaultButton(self.w.runButton)

        # Load Settings:
        if not self.LoadPreferences():
            print(
                "Note: Auto Bumper could not load preferences. Will resort to defaults"
            )

        # Open window and focus on it:
        self.w.open()
        self.w.makeKey()
コード例 #4
0
    def draw_highlight(self, layer, info):

        total = [l for l in Glyphs.font.currentTab.composedLayers]
        cursor = Glyphs.font.currentTab.layersCursor
        selecRange = Glyphs.font.currentTab.textRange

        searchList = [
            self.get_glyphNames(i, "/")
            for i in self.get_glyphNames(self.w.group.search.get(), ",")
        ]

        def split_layers_by_line(layerList):
            mainList = []
            subList = []
            for l in layerList:
                if l == GSControlLayer.newline():
                    mainList.append(subList)
                    subList = []
                else:
                    subList.append(l)
            mainList.append(subList)
            return mainList

        def sum_kerns_up_to_idx(layerList, idx):
            prevLayer = None
            totalKerning = 0
            for i, l in enumerate(layerList):
                if i > 0:
                    pair = Glyphs.font.kerningForPair(
                        l.associatedMasterId, prevLayer.parent.rightKerningKey,
                        l.parent.leftKerningKey)
                    if "%s" % pair != "9.22337203685e+18" and pair:
                        totalKerning += pair
                if i == idx - 1:
                    return totalKerning
                prevLayer = l

        def get_cursor():
            mainCounter = 0
            lineCounter = 0
            cursorDict = {}
            for line in split_layers_by_line(total):
                subListWidths = [l.width for l in line]
                for i, y in enumerate(line):
                    if cursor == mainCounter:
                        cursorDict["line"] = lineCounter
                        cursorDict["xOffset"] = sum(
                            subListWidths[:i]) + sum_kerns_up_to_idx(
                                line, i + 1)
                    mainCounter += 1
                mainCounter += 1
                lineCounter += 1
            return cursorDict

        def get_pos(searchList):
            mainCounter = 0
            lineCounter = 0
            for line in split_layers_by_line(total):
                skipIndexes = []
                subListWidths = [l.width for l in line]
                subListNames = [l.parent.name for l in line]
                cursorLine = get_cursor()["line"]
                cursorOffset = get_cursor()["xOffset"]
                if searchList:
                    search_len = len(searchList)
                    for i in range(len(line)):
                        if i not in skipIndexes:
                            if searchList == subListNames[i:i + search_len]:
                                if "EditView Line Height" in Glyphs.font.customParameters:
                                    lineHeight = Glyphs.font.customParameters[
                                        "EditView Line Height"]
                                else:
                                    lineHeight = (abs(l.master.descender) +
                                                  l.master.ascender) + 200
                                lineDiff = lineCounter - cursorLine
                                yPos = -(lineDiff * lineHeight)
                                xPos = -cursorOffset + sum(
                                    subListWidths[:i]) + sum_kerns_up_to_idx(
                                        line, i + 1)
                                width = sum(subListWidths[i:i + search_len]
                                            ) + sum_kerns_up_to_idx(
                                                line[i:i + search_len],
                                                search_len)
                                yield dict([("x", xPos), ("y", yPos),
                                            ("xHeight", l.master.xHeight),
                                            ("angle", l.master.italicAngle),
                                            ("descender", l.master.descender),
                                            ("ascender", l.master.ascender),
                                            ("width", width),
                                            ("idx", mainCounter)])
                                skipIndexes += range(i, i + search_len)
                        mainCounter += 1
                    lineCounter += 1

        def draw_bbox(x1, y1, x2, y2, x3, y3, x4, y4, outline=False):
            path = NSBezierPath.bezierPath()
            path.moveToPoint_((x1, y1))
            path.lineToPoint_((x2, y2))
            path.lineToPoint_((x3, y3))
            path.lineToPoint_((x4, y4))
            path.lineToPoint_((x1, y1))
            if not outline:
                path.fill()
            else:
                path.setLineWidth_(30)
                path.stroke()

        def ital(yPos):
            offset = tan(radians(angle)) * xHeight / 2
            shift = tan(radians(angle)) * yPos - offset
            return shift

        def pick_color(option):
            return {
                0: (1, 0.99305, 0.561298, 0.6),
                1: (0.777493, 1, 0.972014, 0.6),
                2: (1, 0.877378, 0.980916, 0.6),
                3: (0.761078, 1, 0.783448, 0.6),
                4: (0.80931, 0.884228, 1, 0.6),
            }.get(option)

        c = 0
        matchNb = 0
        for s in searchList:
            for posDict in list(get_pos(s)):
                try:
                    xPos = posDict["x"]
                    yPos = posDict["y"]
                    xHeight = posDict["xHeight"]
                    angle = posDict["angle"]
                    descender = posDict["descender"]
                    ascender = posDict["ascender"]
                    width = posDict["width"]
                    idx = posDict["idx"]

                    x1, y1 = xPos + ital(descender), yPos + descender
                    x2, y2 = xPos + ital(ascender), yPos + ascender
                    x3, y3 = xPos + ital(ascender) + width, yPos + ascender
                    x4, y4 = xPos + width + ital(descender), yPos + descender
                    color = NSColor.colorWithRed_green_blue_alpha_(
                        pick_color(c)[0],
                        pick_color(c)[1],
                        pick_color(c)[2],
                        pick_color(c)[3]).set()

                    if selecRange > 0:
                        if idx < cursor - 1 or idx > cursor - 1 + selecRange - 1:
                            draw_bbox(x1,
                                      y1,
                                      x2,
                                      y2,
                                      x3,
                                      y3,
                                      x4,
                                      y4,
                                      outline=True)
                        else:
                            draw_bbox(x1,
                                      y1,
                                      x2,
                                      y2,
                                      x3,
                                      y3,
                                      x4,
                                      y4,
                                      outline=False)
                            matchNb += 1
                    else:
                        draw_bbox(x1,
                                  y1,
                                  x2,
                                  y2,
                                  x3,
                                  y3,
                                  x4,
                                  y4,
                                  outline=False)
                        matchNb += 1

                except:
                    import traceback
                    print(traceback.format_exc())
            c += 1
            if c > 4:
                c = 0

            if matchNb > 1:
                self.w.group.replaceBtn.setTitle("Replace %s matches" %
                                                 matchNb)
            elif matchNb == 1:
                self.w.group.replaceBtn.setTitle("Replace 1 match")
            else:
                self.w.group.replaceBtn.setTitle("Replace")