Example #1
0
    def setPixel(self, event, dragging=False):
        if self.data is None:
            return False
        try:
            editView = self.editViewController().graphicView()
        except:
            return False

        layer = editView.activeLayer()
        try:
            master = layer.parent.parent.masters[layer.layerId]
        except KeyError:
            return False
        if master is None:
            return False

        # Get location of click in font coordinates
        Loc = editView.getActiveLocation_(event)
        loc_pixel = ((Loc.x - self.rect.origin.x) / self.pixel_size,
                     (Loc.y - self.rect.origin.y) / self.pixel_size /
                     self.pixel_ratio)
        if self.prev_location != loc_pixel:
            x, y = loc_pixel
            current = NSGraphicsContext.currentContext()
            context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(
                self.data)
            if context is None:
                self.prev_location = loc_pixel
                print("Could not get context in setPixel")
                return False
            NSGraphicsContext.saveGraphicsState()
            NSGraphicsContext.setCurrentContext_(context)
            if self.erase:
                NSColor.whiteColor().set()
            else:
                NSColor.blackColor().set()
            effective_size = self.pen_size / self.pixel_size
            if dragging and self.prev_location is not None:
                px, py = self.prev_location
                path = NSBezierPath.alloc().init()
                path.setLineCapStyle_(NSRoundLineCapStyle)
                path.setLineWidth_(effective_size)
                # path.strokeLineFromPoint_toPoint_(x, y, x + self.pen_size, y + self.pen_size)
                path.moveToPoint_((px, py))
                path.lineToPoint_((x, y))
                path.stroke()
                self.needs_save = True
            else:
                half = effective_size / 2
                rect = NSMakeRect(x - half, y - half, effective_size,
                                  effective_size)
                path = NSBezierPath.bezierPathWithOvalInRect_(rect)
                path.fill()
                self.needs_save = True
            # For rectangular pens:
            # NSBezierPath.fillRect_(rect)
            NSGraphicsContext.setCurrentContext_(current)
            NSGraphicsContext.restoreGraphicsState()
            self.prev_location = loc_pixel
        return True
Example #2
0
 def drawRect_(self, rect):
     from AppKit import NSRectFill, NSBezierPath, NSColor
     self.color.set()
     NSRectFill(self.bounds())
     NSColor.blackColor().set()
     p = NSBezierPath.bezierPathWithRect_(self.bounds())
     p.setLineWidth_(10)
     p.stroke()
Example #3
0
 def drawRect_(self, rect):
     from AppKit import NSRectFill, NSBezierPath, NSColor
     self.color.set()
     NSRectFill(self.bounds())
     NSColor.blackColor().set()
     p = NSBezierPath.bezierPathWithRect_(self.bounds())
     p.setLineWidth_(10)
     p.stroke()
Example #4
0
    def drawRect_(self, rect):

        NSColor.whiteColor().set()
        NSBezierPath.fillRect_(rect)

        if Glyphs.font is None:
            return

        if not Glyphs.font.selectedLayers:
            return

        glyphToRotate = None
        try:
            glyphToRotate = Glyphs.font.selectedLayers[0]
        except:
            print(traceback.format_exc())

        if glyphToRotate is None:
            return

        try:
            previewPath = glyphToRotate.completeBezierPath

            rotationFactor = self.wrapper._rotationFactor
            Width = NSWidth(self.frame())
            Height = NSHeight(self.frame())

            scaleFactor = 0.666666 / (glyphToRotate.parent.parent.upm /
                                      min(Width, Height))

            ## scaling and zeroing the glyph
            #------------------------
            transform = NSAffineTransform.transform()
            transform.scaleBy_(scaleFactor)
            bounds = glyphToRotate.bounds
            transform.translateXBy_yBy_(-NSMidX(bounds), -NSMidY(bounds))
            previewPath.transformUsingAffineTransform_(transform)

            ## rotation
            #------------------------
            transform = NSAffineTransform.transform()
            transform.rotateByDegrees_(rotationFactor)
            previewPath.transformUsingAffineTransform_(transform)

            ## positioning to the middle of the viewport
            #------------------------
            transform = NSAffineTransform.transform()
            transform.translateXBy_yBy_(Width / 2, Height / 2 - 8)
            previewPath.transformUsingAffineTransform_(transform)

            ## fill path
            #------------------------
            NSColor.blackColor().set()
            previewPath.fill()

        except:
            print(traceback.format_exc())
Example #5
0
    def arrangeObjects_(self, objects):
        "Filtering is not yet connected in IB!"
        # XXX: This doesn't work yet, so disable
        if self.shouldFilter:
            self.shouldFilter = False

        if not self.shouldFilter:
            return super(GraphicsArrayController,
                         self).arrangeObjects_(objects)

        if self.filterColor is None:
            self.filterColor = NSColor.blackColor().colorUsingColorSpaceName_(
                NSCalibratedRGBColorSpace)

        filterHue = self.filterColor.hueComponent()
        filteredObjects = []
        for item in objects:
            hue = item.color.hueComponent()
            if ((fabs(hue - filterHue) < 0.05)
                    or (fabs(hue - filterHue) > 0.95)
                    or (item is self.newCircle)):
                filteredObjects.append(item)
                self.newCircle = None
        return super(GraphicsArrayController,
                     self).arrangeObjects_(filteredObjects)
Example #6
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)
Example #7
0
	def drawTextAtPoint(self, text, textPosition, fontSize=10.0, fontColor=NSColor.blackColor(), align='bottomleft'):
		"""
		Use self.drawTextAtPoint("blabla", myNSPoint) to display left-aligned text at myNSPoint.
		"""
		try:
			
			alignment = {
				'topleft': 6, 
				'topcenter': 7, 
				'topright': 8,
				'left': 3, 
				'center': 4, 
				'right': 5, 
				'bottomleft': 0, 
				'bottomcenter': 1, 
				'bottomright': 2
				}
			
			currentZoom = self.getScale()
			fontAttributes = { 
				NSFontAttributeName: NSFont.labelFontOfSize_(fontSize/currentZoom),
				NSForegroundColorAttributeName: fontColor }
			displayText = NSAttributedString.alloc().initWithString_attributes_(unicode(text), fontAttributes)
			textAlignment = alignment[align] # top left: 6, top center: 7, top right: 8, center left: 3, center center: 4, center right: 5, bottom left: 0, bottom center: 1, bottom right: 2
			displayText.drawAtPoint_alignment_(textPosition, textAlignment)
		except:
			self.logError(traceback.format_exc())
Example #8
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)
Example #9
0
	def drawTextAtPoint(self, text, textPosition, fontSize=10.0, fontColor=NSColor.blackColor(), align='bottomleft'):
		"""
		Use self.drawTextAtPoint("blabla", myNSPoint) to display left-aligned text at myNSPoint.
		"""
		try:

			alignment = {
				'topleft': 6,
				'topcenter': 7,
				'topright': 8,
				'left': 3,
				'center': 4,
				'right': 5,
				'bottomleft': 0,
				'bottomcenter': 1,
				'bottomright': 2
			}

			currentZoom = self.getScale()
			fontAttributes = {
				NSFontAttributeName: NSFont.labelFontOfSize_(fontSize / currentZoom),
				NSForegroundColorAttributeName: fontColor}
			displayText = NSAttributedString.alloc().initWithString_attributes_(unicode(text), fontAttributes)
			textAlignment = alignment[align]  # top left: 6, top center: 7, top right: 8, center left: 3, center center: 4, center right: 5, bottom left: 0, bottom center: 1, bottom right: 2
			displayText.drawAtPoint_alignment_(textPosition, textAlignment)
		except:
			self.logError(traceback.format_exc())
        def drawRect_(self, rect):
            try:
                NSColor.whiteColor().set()
                NSRectFill(self.bounds())
                NSColor.blackColor().setFill()
                p = NSBezierPath.bezierPath()
                xcursor = 0
                ycursor = 0
                for i, g in enumerate(self.glyphs):
                    layer = g.layers[0]
                    if i > 0:
                        # Do anchor correction here
                        prevlayer = self.glyphs[i - 1].layers[0]
                        entry = prevlayer.anchors["entry"]
                        exit = layer.anchors["exit"]
                        if entry and exit:
                            diffX = entry.position.x - exit.position.x
                            diffY = entry.position.y - exit.position.y
                            xcursor = xcursor + diffX
                            ycursor = ycursor + diffY
                        else:
                            NSColor.redColor().setFill()
                    else:
                        xcursor = xcursor - layer.bounds.origin.x
                    thisPath = NSBezierPath.bezierPath()
                    thisPath.appendBezierPath_(layer.completeBezierPath)
                    t = NSAffineTransform.transform()
                    t.translateXBy_yBy_(xcursor,
                                        -layer.master.descender + ycursor)
                    thisPath.transformUsingAffineTransform_(t)
                    p.appendBezierPath_(thisPath)

                t = NSAffineTransform.transform()
                if xcursor > 0:
                    master = self.glyphs[0].layers[0].master
                    vscale = self.bounds().size.height / (master.ascender -
                                                          master.descender)
                    hscale = self.bounds().size.width / xcursor
                    t.scaleBy_(min(hscale, vscale))
                    p.transformUsingAffineTransform_(t)
                p.fill()
            except Exception as e:
                print("Oops!", sys.exc_info()[0], "occured.")
                traceback.print_exc(file=sys.stdout)
Example #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)
Example #12
0
    def drawRect_(self, rect):
        try:
            NSColor.whiteColor().set()
            NSRectFill(self.bounds())
            NSColor.blackColor().setFill()
            NSColor.blueColor().setStroke()
            p = NSBezierPath.bezierPath()
            xcursor = 0
            string = self.string
            master = self.master
            for s in range(0, len(string)):
                thisPath = NSBezierPath.bezierPath()
                gsglyph = master.font.glyphs[string[s]]
                layer = gsglyph.layers[master.id]
                thisPath.appendBezierPath_(layer.completeBezierPath)
                # print("X cursor was",xcursor)
                xcursor = xcursor - layer.bounds.origin.x
                # print("Moving backwards", layer.bounds.origin.x)
                t = NSAffineTransform.transform()
                t.translateXBy_yBy_(xcursor, -master.descender)
                thisPath.transformUsingAffineTransform_(t)
                # print("Drawing at",xcursor)
                # print(thisPath)
                xcursor = xcursor + layer.bounds.origin.x
                xcursor = xcursor + layer.bounds.size.width
                # print("Adding width", layer.bounds.size.width)
                if s < len(string) - 1:
                    xcursor = xcursor + self.distances[(string[s],
                                                        string[s + 1])]
                p.appendBezierPath_(thisPath)

            t = NSAffineTransform.transform()
            if xcursor > 0:
                vscale = self.bounds().size.height / (master.ascender -
                                                      master.descender)
                hscale = self.bounds().size.width / xcursor
                t.scaleBy_(min(hscale, vscale))
                p.transformUsingAffineTransform_(t)
            p.fill()
        except:
            print("Oops!", sys.exc_info()[0], "occured.")
            traceback.print_exc(file=sys.stdout)
 def __init__(self, posSize, text, callback=None):
     # there must be a callback as it triggers the creation of the delegate
     if callback is None:
         callback = self._fallbackCallback
     super(FeatureTextEditor, self).__init__(posSize, "", callback=callback)
     self._nsObject.setHasHorizontalScroller_(True)
     font = NSFont.fontWithName_size_("Monaco", 10)
     self._textView.setFont_(font)
     self._textView.setUsesFindPanel_(True)
     ## line numbers
     #ruler = DefconAppKitLineNumberView.alloc().init()
     #ruler.setClientView_(self._textView)
     #self._nsObject.setVerticalRulerView_(ruler)
     #self._nsObject.setHasHorizontalRuler_(False)
     #self._nsObject.setHasVerticalRuler_(True)
     #self._nsObject.setRulersVisible_(True)
     #notificationCenter = NSNotificationCenter.defaultCenter()
     #notificationCenter.addObserver_selector_name_object_(
     #    ruler, "clientViewSelectionChanged:", NSTextViewDidChangeSelectionNotification, self._textView
     #)
     # colors
     self._mainColor = NSColor.blackColor()
     self._commentColor = NSColor.colorWithCalibratedWhite_alpha_(.6, 1)
     self._keywordColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
         .8, 0, 0, 1)
     self._tokenColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
         .8, .4, 0, 1)
     self._classNameColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
         0, 0, .8, 1)
     self._includeColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
         .8, 0, .8, 1)
     self._stringColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
         0, .6, 0, 1)
     # build the placard
     placardW = 65
     placardH = 16
     self._placardJumps = []
     self._placard = vanilla.Group((0, 0, placardW, placardH))
     self._placard.featureJumpButton = PlacardPopUpButton(
         (0, 0, placardW, placardH), [],
         callback=self._placardFeatureSelectionCallback,
         sizeStyle="mini")
     self._nsObject.setPlacard_(self._placard.getNSView())
     # registed for syntax coloring notifications
     self._programmaticallySettingText = False
     delegate = self._textViewDelegate
     delegate.vanillaWrapper = weakref.ref(self)
     notificationCenter = NSNotificationCenter.defaultCenter()
     notificationCenter.addObserver_selector_name_object_(
         self._textViewDelegate, "textStorageDidProcessEditing:",
         NSTextStorageDidProcessEditingNotification,
         self._textView.textStorage())
     # set the text
     self.set(text)
Example #14
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)
Example #15
0
 def applicationDidFinishLaunching_(self, aNotification):
     d = {'StderrColor': NSArchiver.archivedDataWithRootObject_(NSColor.redColor()),
          'StdoutColor': NSArchiver.archivedDataWithRootObject_(NSColor.blueColor()),
          'CodeColor': NSArchiver.archivedDataWithRootObject_(NSColor.blackColor()),
          }
     defaults = NSUserDefaults.standardUserDefaults()
     defaults.registerDefaults_(d)
     self.textView.setFont_(self.font())
     self._stderrColor = NSUnarchiver.unarchiveObjectWithData_(defaults['StderrColor'])
     self._stdoutColor = NSUnarchiver.unarchiveObjectWithData_(defaults['StdoutColor'])
     self._codeColor = NSUnarchiver.unarchiveObjectWithData_(defaults['CodeColor'])
     self._executeWithRedirectedIO_args_kwds_(self._interp, (), {})
    def __init__(self):
        f = CurrentFont()
        if f is None:
            return
        self.designSpaceModel = f.lib.get(self.designSpaceModelLibKey,
                                          "twobytwo")
        #print "self.designSpaceModel", self.designSpaceModel
        if self.designSpaceModel == "twobytwo":
            self.masterNames = [
                'narrow-thin', 'wide-thin', 'narrow-bold', 'wide-bold'
            ]
        elif self.designSpaceModel == "twobyone":
            self.masterNames = ['narrow-thin', 'wide-thin']
        self.shapeColor = None
        self.backgroundColor = None
        self.extrapolateMinValue = 0
        self.extrapolateMaxValue = 1
        self.w = vanilla.Window((500, 600),
                                "Responsive Lettering",
                                minSize=(300, 200))
        self.w.preview = HTMLView((0, 0, -0, -140))
        self.w.exportButton = vanilla.Button((-150, -30, -10, 20),
                                             "Export SVG",
                                             callback=self.cbExport)
        columnDescriptions = [
            dict(title="Glyphname", key="name", width=125),
            dict(title="Width", key="width", width=50),
            dict(title="Height", key="height", width=50),
            dict(title="Bounds?", key="bounds", width=75),
            dict(title="Contours", key="contours", width=50),
            dict(title="Points", key="points", width=50),
        ]
        self.w.l = vanilla.List((0, -140, -0, -40),
                                self.wrapGlyphs(),
                                columnDescriptions=columnDescriptions,
                                doubleClickCallback=self.callbackListClick)
        self.w.t = vanilla.TextBox((70, -27, -160, 20),
                                   "FontName",
                                   sizeStyle="small")
        self.w.backgroundColorWell = vanilla.ColorWell(
            (10, -30, 20, 20),
            callback=self.backgroundColorWellCallback,
            color=NSColor.blackColor())
        self.w.shapeColorWell = vanilla.ColorWell(
            (35, -30, 20, 20),
            callback=self.shapeColorWellCallback,
            color=NSColor.whiteColor())

        self.w.bind("became main", self.windowBecameMainCallback)
        self.setColorsFromLib()
        self.update()
        self.w.open()
        self.cbMakePreview(None)
 def transformedValue_(self, priority):
     if priority > 4:
         return NSColor.redColor()
     elif priority > 3:
         return NSColor.orangeColor()
     elif priority > 2:
         return NSColor.blueColor()
     elif priority > 1:
         return NSColor.greenColor()
     elif priority > 0:
         return NSColor.brownColor()
     else:
         return NSColor.blackColor()
Example #18
0
 def transformedValue_(self, priority):
     if priority > 4:
         return NSColor.redColor()
     elif priority > 3:
         return NSColor.orangeColor()
     elif priority > 2:
         return NSColor.blueColor()
     elif priority > 1:
         return NSColor.greenColor()
     elif priority > 0:
         return NSColor.brownColor()
     else:
         return NSColor.blackColor()
Example #19
0
 def drawCellGlyph(self):
     layers = self.font.layers
     for layerName in reversed(layers.layerOrder):
         layer = layers[layerName]
         if self.glyph.name not in layer:
             continue
         layerColor = None
         if layer.color is not None:
             layerColor = colorToNSColor(layer.color)
         if layerColor is None:
             layerColor = NSColor.blackColor()
         glyph = layer[self.glyph.name]
         path = glyph.getRepresentation("defconAppKit.NSBezierPath")
         layerColor.set()
         path.fill()
 def drawCellGlyph(self):
     layers = self.font.layers
     for layerName in reversed(layers.layerOrder):
         layer = layers[layerName]
         if self.glyph.name not in layer:
             continue
         layerColor = None
         if layer.color is not None:
             layerColor = colorToNSColor(layer.color)
         if layerColor is None:
             layerColor = NSColor.blackColor()
         glyph = layer[self.glyph.name]
         path = glyph.getRepresentation("defconAppKit.NSBezierPath")
         layerColor.set()
         path.fill()
 def __init__(self):
             
     self.w = Window((400, 400), "Layer Preview", minSize=(400, 300))
     
     self.w.preview = GlyphLayerPreview((0, 0, -0, -30))
     self.currentGlyphChanged()
     
     self.w.useColor = CheckBox((10, -30, 100, 22), "Use Color:", callback=self.useColorCallback)
     
     self.w.color = ColorWell((120, -35, 40, 30), color=NSColor.blackColor(), callback=self.colorCallback)
     
     self.w.testInstall = Button((-170, -30, -10, 22), "Test Install Layers", callback=self.testInstallCallback)
     
     addObserver(self, "currentGlyphChanged", "currentGlyphChanged")
     
     self.setUpBaseWindowBehavior()
     self.w.open()
 def __init__(self, posSize, text, callback=None):
     # there must be a callback as it triggers the creation of the delegate
     if callback is None:
         callback = self._fallbackCallback
     super(FeatureTextEditor, self).__init__(posSize, "", callback=callback)
     self._nsObject.setHasHorizontalScroller_(True)
     font = NSFont.fontWithName_size_("Monaco", 10)
     self._textView.setFont_(font)
     self._textView.setUsesFindPanel_(True)
     ## line numbers
     #ruler = DefconAppKitLineNumberView.alloc().init()
     #ruler.setClientView_(self._textView)
     #self._nsObject.setVerticalRulerView_(ruler)
     #self._nsObject.setHasHorizontalRuler_(False)
     #self._nsObject.setHasVerticalRuler_(True)
     #self._nsObject.setRulersVisible_(True)
     #notificationCenter = NSNotificationCenter.defaultCenter()
     #notificationCenter.addObserver_selector_name_object_(
     #    ruler, "clientViewSelectionChanged:", NSTextViewDidChangeSelectionNotification, self._textView
     #)
     # colors
     self._mainColor = NSColor.blackColor()
     self._commentColor = NSColor.colorWithCalibratedWhite_alpha_(.6, 1)
     self._keywordColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, 0, 0, 1)
     self._tokenColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, .4, 0, 1)
     self._classNameColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, .8, 1)
     self._includeColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, 0, .8, 1)
     self._stringColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0, .6, 0, 1)
     # build the placard
     placardW = 65
     placardH = 16
     self._placardJumps = []
     self._placard = vanilla.Group((0, 0, placardW, placardH))
     self._placard.featureJumpButton = PlacardPopUpButton((0, 0, placardW, placardH),
         [], callback=self._placardFeatureSelectionCallback, sizeStyle="mini")
     self._nsObject.setPlacard_(self._placard.getNSView())
     # registed for syntax coloring notifications
     self._programmaticallySettingText = False
     delegate = self._textViewDelegate
     delegate.vanillaWrapper = weakref.ref(self)
     notificationCenter = NSNotificationCenter.defaultCenter()
     notificationCenter.addObserver_selector_name_object_(
         self._textViewDelegate, "textStorageDidProcessEditing", NSTextStorageDidProcessEditingNotification, self._textView.textStorage())
     # set the text
     self.set(text)
Example #23
0
    def __init__(self):
        self.libkey = "com.fontfont.colorfont"
        self._font = None

        self.show_only_glyphs_with_layers = True

        self.color = NSColor.blackColor()
        self.colorbg = NSColor.whiteColor()
        self._selected_color_index = None

        # live update the canvas when glyphs are edited
        self._debug_enable_live_editing = True

        self._auto_layer_regex_ok = True

        # self.oldDisplaySettings = getGlyphViewDisplaySettings()
        # setGlyphViewDisplaySettings({"On Curve Points": False, "Off Curve Points": False})

        self.w = get_ui(self, "None")
        self.d = get_drawer(self)
        self.setUpBaseWindowBehavior()

        # self._callback_ui_glyph_list_selection()

        addObserver(self, "_observer_glyph_changed", "currentGlyphChanged")
        addObserver(self, "_observer_draw_glyph_window", "drawBackground")
        addObserver(self, "_observer_draw_glyph_window", "drawInactive")
        addObserver(self, "_observer_font_will_close", "fontWillClose")
        addObserver(self, "_observer_font_did_open", "fontDidOpen")

        # grey out controls that are not implemented yet
        self.d.generateGoogleFormat.enable(False)
        self.d.preferPlacedImages.enable(False)

        # disable regex check box, because it is read only
        self.d.auto_layer_regex_ok.enable(False)

        # If sbix or cbdt is inactive, disable bitmap sizes box
        # self._check_bitmap_ui_active()

        self.w.open()

        self.font = CurrentFont()
    def arrangeObjects_(self, objects):
        "Filtering is not yet connected in IB!"
        # XXX: This doesn't work yet, so disable
        if self.shouldFilter:
            self.shouldFilter = False

        if not self.shouldFilter:
            return super(GraphicsArrayController, self).arrangeObjects_(objects)

        if self.filterColor is None:
            self.filterColor = NSColor.blackColor().colorUsingColorSpaceName_(NSCalibratedRGBColorSpace)

        filterHue = self.filterColor.hueComponent()
        filteredObjects = []
        for item in objects:
            hue = item.color.hueComponent()
            if ((fabs(hue - filterHue) < 0.05) or
                (fabs(hue - filterHue) > 0.95) or
                (item is self.newCircle)):
                filteredObjects.append(item)
                self.newCircle = None
        return super(GraphicsArrayController, self).arrangeObjects_(filteredObjects)
    def __init__(self):

        self.w = Window((400, 400), "Layer Preview", minSize=(400, 300))

        self.w.preview = GlyphLayerPreview((0, 0, -0, -30))
        self.currentGlyphChanged()

        self.w.useColor = CheckBox((10, -30, 100, 22),
                                   "Use Color:",
                                   callback=self.useColorCallback)

        self.w.color = ColorWell((120, -35, 40, 30),
                                 color=NSColor.blackColor(),
                                 callback=self.colorCallback)

        self.w.testInstall = Button((-170, -30, -10, 22),
                                    "Test Install Layers",
                                    callback=self.testInstallCallback)

        addObserver(self, "currentGlyphChanged", "currentGlyphChanged")

        self.setUpBaseWindowBehavior()
        self.w.open()
Example #26
0
class RamsayStDataCollection(object):

    _fallBackFillColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
        .34, .54, .92, .7)
    _fallBackStrokeColor = NSColor.blackColor()
    _fallbackData = {
        '-': ('n', 'H'),
        'A': ('H', 'V'),
        'C': ('c', 'G'),
        'B': ('P', 'D'),
        'E': ('B', 'F'),
        'D': ('B', 'P'),
        'G': ('C', 'O'),
        'F': ('P', 'E'),
        'I': ('J', 'H'),
        'H': ('I', 'P'),
        'K': ('k', 'I'),
        'J': ('j', 'I'),
        'M': ('H', 'N'),
        'L': ('I', 'H'),
        'O': ('C', 'o'),
        'N': ('M', 'V'),
        'Q': ('O', 'G'),
        'P': ('R', 'p'),
        'S': ('C', 's'),
        'R': ('B', 'P'),
        'U': ('u', 'H'),
        'T': ('I', 'H'),
        'W': ('w', 'V'),
        'V': ('v', 'W'),
        'Y': ('y', 'V'),
        'X': ('x', 'Y'),
        'Z': ('z', 'X'),
        'a': ('n', 'e'),
        'c': ('e', 'C'),
        'b': ('d', 'p'),
        'e': ('o', 'c'),
        'd': ('q', 'b'),
        'g': ('o', 'q'),
        'f': ('i', 't'),
        'i': ('period', 'j'),
        'h': ('l', 'n'),
        'k': ('h', 'K'),
        'j': ('i', 'period'),
        'm': ('n', 'w'),
        'l': ('h', 'k'),
        'o': ('c', 'O'),
        'n': ('h', 'm'),
        'q': ('d', 'p'),
        'p': ('q', 'P'),
        's': ('e', 'S'),
        'r': ('s', 'n'),
        'u': ('v', 'n'),
        't': ('s', 'f'),
        'w': ('v', 'W'),
        'v': ('u', 'w'),
        'y': ('v', 'Y'),
        'x': ('y', 'X'),
        'z': ('x', 'Z')
    }
    _fallbackShowPreview = True

    def __init__(self):
        self.load()

    def load(self):
        self.fillColor = getExtensionDefaultColor(_fillColorDefaultKey,
                                                  self._fallBackFillColor)
        self.strokeColor = getExtensionDefaultColor(_strokeColorDefaultKey,
                                                    self._fallBackStrokeColor)
        self.showPreview = getExtensionDefault(_showPreviewDefaultKey,
                                               self._fallbackShowPreview)
        self.data = getExtensionDefault(_dataDefaultKey, self._fallbackData)

    def save(self):
        setExtensionDefaultColor(_fillColorDefaultKey, self.fillColor)
        setExtensionDefaultColor(_strokeColorDefaultKey, self.strokeColor)
        setExtensionDefault(_showPreviewDefaultKey, self.showPreview)
        setExtensionDefault(_dataDefaultKey, self.data)

    def keys(self):
        return self.data.keys()

    def __contains__(self, key):
        return key in self.data

    def get(self, value, fallback=("n", "n")):
        return self.data.get(value, fallback)

    def set(self, item):
        key = item.glyphName()
        if key is None:
            return
        self.data[key] = item.getRamsaySt()

    def setItems(self, data):
        self.data = dict()
        for item in data:
            self.data[item.glyphName()] = item.getRamsaySt()
        self.save()

    def getItems(self):
        keys = list(self.data.keys())
        keys.sort()
        return [RamsayStDataItem(key, self.data[key]) for key in keys]

    def newItem(self, glyphName):
        return RamsayStDataItem(glyphName, (" ", " "))
 def drawPreviewNeighBors(self, info):
     if not RamsayStData.showPreview:
         return
     fillColor = NSColor.blackColor()
     fillColor.set()
     self._drawNeighborsGlyphs(info["glyph"], stroke=False)
Example #28
0
    def initWithFrame_(self, frame):

        print "initWithFrame",  frame

        self._location = self._locationDefault
        self._itemColor = self._itemColorDefault
        self._backgroundColor = self._backgroundColorDefault

        
        self.dragging = None
        
        result = super(OpenView, self).initWithFrame_(frame)

        # self.setBounds_( (0,0) , self.window().frame.size )

        printB("initWithFrame",  self ,all_names=True)
        # printB("view.initWithFrame", self, add=['frame','bounds'])

        print "result of super(OpenView, self).initWithFrame_(frame) is", result
        if result is None:
            return result

        # // setup the CALayer for the overall full-screen view

        #
        #   backing layer
        #
        
        backingLayer = getQCCompLayer()
        frame = self.frame()
        backingLayer.setBounds_( ((0, 0), (frame.size.width, frame.size.height)) )
        
        # backingLayer.setFrame_(  view.frame() )      
        # backingLayer.frame = NSRectToCGRect(frame);
        # backingLayer.backgroundColor = CGColorCreateGenericRGB(1, 1, 1, 1.0);
        backingLayer.setOpaque_(objc.YES)

        # 
        # printB("QCLayer", backingLayer)
        # 
        # 
        # print_setters(backingLayer)
    
        if True:
            # rootLayer = CALayer.layer()
            self.setLayer_(backingLayer)
            self.setWantsLayer_( objc.YES )
            rootLayer = backingLayer            
        else:
            self.setWantsLayer_( objc.YES )
            rootLayer = self.layer()

        # printB("initWithFrame (super)",  super(OpenView, self) )
        # printB("initWithFrame (view)",  self )        


        printB("View",  self ) # frame = bounds for origin (0,0)?
        # print_setters(self, add=['bounds', 'frame'])

        printB("rootLayer", rootLayer, add=['bounds'])


        #
        #   overlay Layer
        #
        #  The overlay layer is used to draw any drag handles, so that they are always on top of all slides. 
        #  We must take care to make sure this layer is always the last one.
        #
        
        overlayLayer = MyOverLayer.layer() # (_LTOverlayLayer was MyOverLayer)
        overlayLayer.setFrame_( backingLayer.frame() ) # view.frame() )      
        overlayLayer.setOpaque_( objc.NO )

        borderWidth = 4.0
        overlayLayer.setBorderWidth_(borderWidth)
        # borderColor = CGColorCreateGenericGray(.4, 0.75)
        borderColor = CGColorCreateGenericRGB(1, 0.5, 0.2, 0.8);
        overlayLayer.setBorderColor_( borderColor )         
        
        zPosition = 20
        
        overlayLayer.setZPosition_(zPosition)

        #   zPosition
        #
        # Increasing zPosition moves the layer towards the front
        # Decreasing it moves it away and towards the back
        #

        # We want to be the delegate so we can do the drag handle drawing        
        overlayLayer.setDelegate_(self)
        # overlayLayer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.0);
        # overlayLayer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;

        # printB("overlayLayer", overlayLayer, all_names=True)
        # printB("overlayLayer", overlayLayer, only = ['borderColor', 'borderWidth', 'bounds'] )

        backingLayer.addSublayer_(overlayLayer)

        layerDict = {
            'origin' : (420,120),
            'size'  :  (120,120),
            'zPosition'  :  12,
            'image_path'  :  "/Users/donb/projects/openworld/gray button 96px.psd",
            'cornerRadius'  :  16,
            'borderWidth'  :  1.0,
        }

        testLayer = createLayer(**layerDict)
        rootLayer.addSublayer_(testLayer)

        layerDict = {
            'origin' : (420,120),
            'size'  :  (120,120),
            'zPosition'  :  12,
            'image_path'  :  "/Users/donb/projects/openworld/gray button 96px.psd",
            'cornerRadius'  :  16,
            'borderWidth'  :  1.0,
        }
        # 
        # testLayer = createLayer(**layerDict)
        # rootLayer.addSublayer_(testLayer)
        # 
        
        app = NSApp()
        applicationIconImage=app.applicationIconImage()

        layerDict['image']=applicationIconImage
        layerDict['origin']=(100,400)
        layerDict['size']=applicationIconImage.size()
        testLayer3 = createLayer( **layerDict)
        rootLayer.addSublayer_(testLayer3)
        

        # printB("testLayer3",  testLayer3  ) # frame = bounds for origin (0,0)?

        
        
        # lake_picture_path = "/Library/Desktop Pictures/Lake.jpg"    
        # theLakeImage = getImage(lake_picture_path)

        layerDict['origin']=(300,300)
        layerDict['image_path']="/Library/Desktop Pictures/Lake.jpg"
        del layerDict['image']        
        layerDict['size']=(300,300)

        testLayer2 = createLayer( **layerDict)
        rootLayer.addSublayer_(testLayer2)


 
        layerDict['origin']=(420,60)
        layerDict['text_string']="full-size and on the 1080p LCD"
        layerDict['zPosition'] = 20
        layerDict['textColor']=NSColor.blackColor()
        
        del layerDict['image_path']
        
        testLayer3 = createTextLayer( **layerDict)
        rootLayer.addSublayer_(testLayer3)



        whiteColor = CGColorCreateGenericRGB(0.0, 0.5, 1.0, 1.0)

        layerDict['textColor']=NSColor.whiteColor()
        layerDict['zPosition'] = 19
        
        testLayer4 = createTextLayer(**layerDict)
        rootLayer.addSublayer_(testLayer4)

        blurFilter = CIFilter.filterWithName_("CIGaussianBlur")
 
        blurFilter.setDefaults()
        # blurFilter.setValue_forKey_( 2.0, "inputRadius" )
        blurFilter.setValue_forKey_( .75, "inputRadius" )
        blurFilter.setName_("blur")
 
        testLayer4.setFilters_( [blurFilter] )
        # // init ivars
        # _slides = [[NSMutableArray array] retain];
        # self.selectionIndexes = [NSIndexSet indexSet];

        # // init the input trackers
        # [self _initTrackers];

        # // register for dragging
        # [self registerForDraggedTypes:[NSArray arrayWithObject:(NSString *)kUTTypeFileURL]];

        # // we want touch events
        self.setAcceptsTouchEvents_(objc.YES)
     
    
        return result
Example #29
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)
Example #30
0
def show_backdrop(comm_queue, image_path):
    from AppKit import NSWindow, NSWindowCollectionBehaviorCanJoinAllSpaces, NSWindowCollectionBehaviorStationary, \
                       NSWindowCollectionBehaviorIgnoresCycle, NSBorderlessWindowMask, NSBackingStoreBuffered, NSColor, \
                       NSApplication, NSScreen, NSView, NSImage, NSImageView, NSZeroRect, NSCompositeCopy, NSApp, \
                       NSTimer, NSObject, NSEvent, NSApplicationDefined, NSMakePoint, NSBundle
    from Quartz import kCGDesktopWindowLevel
    from ctypes import CDLL, Structure, POINTER, c_uint32, byref
    from ctypes.util import find_library
    class ProcessSerialNumber(Structure):
        _fields_    = [('highLongOfPSN', c_uint32),
                       ('lowLongOfPSN',  c_uint32)]
    kCurrentProcess = 2
    kProcessTransformToUIElementAppication = 4
    ApplicationServices           = CDLL(find_library('ApplicationServices'))
    TransformProcessType          = ApplicationServices.TransformProcessType
    TransformProcessType.argtypes = [POINTER(ProcessSerialNumber), c_uint32]
    class MainController(NSObject):
        timer = None
        def kickRunLoop(self):
            event = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, \
                            NSMakePoint(0,0), 0, 0.0, 0, None, 0, 0, 0)
            NSApp.postEvent_atStart_(event, True)
        def checkProcess_(self, timer):
            if not comm_queue.empty():
                # We Get Signal, Take Off Every Zig - er, time to shut down this forked process
                # Clear the queue
                while not comm_queue.empty():
                    ignore = comm_queue.get_nowait()
                NSApp.stop_(None)
                # After you stop the runloop, the app has to receive another event to determine the runloop stopped ...
                self.kickRunLoop()
        def run(self):
            # You could adjust the 1.0 here to how ever many seconds you wanted to wait between checks to terminate
            self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, self.checkProcess_, None, True)
            NSApp.run()
    class FullScreenWindow(NSWindow):
        def canBecomeKeyWindow(self):
            return False
        def canBecomeMainWindow(self):
            return False
    class LockView(NSView):
        def getTopOffset(self, height):
            return (self.bounds().size.height / 2) - height / 2
        def getLeftOffset(self, width):
            return (self.bounds().size.width / 2) - width / 2
        def drawRect_(self, rect):
            image = NSImage.alloc().initWithContentsOfFile_(image_path)
            rep = image.representations()[0]
            bg_width = rep.pixelsWide()
            bg_height = rep.pixelsHigh()
            image.drawInRect_fromRect_operation_fraction_(((self.getLeftOffset(bg_width), self.getTopOffset(bg_height)), (bg_width, bg_height)), NSZeroRect, NSCompositeCopy, 1.0)
            imageView = NSImageView.alloc().init()
            imageView.setImage_(image)
            self.addSubview_(imageView)
    bundle = NSBundle.mainBundle()
    info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
    # Did you know you can override parts of infoDictionary (Info.plist, after loading) even though Apple says it's read-only?
    # This is enough to make an app faceless / without a Dock icon
    info['LSUIElement'] = '1'
    # Initialize our shared application instance
    app = NSApplication.sharedApplication()
    # ... This isn't really necessary, but it's nice to ensure that the application truly is UIElement type
    psn    = ProcessSerialNumber(0, kCurrentProcess)
    ApplicationServices.TransformProcessType(psn, kProcessTransformToUIElementAppication)
    screen = NSScreen.mainScreen()
    myWindow = FullScreenWindow.alloc().initWithContentRect_styleMask_backing_defer_(screen.frame(), NSBorderlessWindowMask, NSBackingStoreBuffered, True)
    myView = LockView.alloc().initWithFrame_(screen.frame())
    myWindow.setContentView_(myView)
    myWindow.setLevel_(kCGDesktopWindowLevel)
    myWindow.setCollectionBehavior_(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)
    myWindow.setBackgroundColor_(NSColor.blackColor())
    myWindow.makeKeyAndOrderFront_(myWindow)
    myWindow.display()
    controller = MainController.alloc().init()
    controller.run()
Example #31
0
    image = NSImage.alloc().initWithSize_((19, 19))
    image.lockFocus()
    backgroundColor.set()
    NSRectFillUsingOperation(((0, 0), (19, 19)), NSCompositeSourceOver)
    foregroundColor.set()
    path = NSBezierPath.bezierPathWithRect_(((0.5, 0.5), (18, 18)))
    for (mT, lT) in paths:
        path.moveToPoint_(mT)
        path.lineToPoint_(lT)
    path.setLineWidth_(1.0)
    path.stroke()
    image.unlockFocus()
    return image


color1 = NSColor.blackColor()
color2 = NSColor.colorWithCalibratedWhite_alpha_(1, 0.5)

pathYT = [((6.5, 7.5), (6.5, 18.5)), ((12.5, 7.5), (12.5, 18.5))]
pathYC = [((6.5, 4.5), (6.5, 14.5)), ((12.5, 4.5), (12.5, 14.5))]
pathYB = [((6.5, 0.5), (6.5, 11.5)), ((12.5, 0.5), (12.5, 11.5))]

pathXL = [((0.5, 6.5), (11.5, 6.5)), ((0.5, 12.5), (11.5, 12.5))]
pathXC = [((4.5, 6.5), (14.5, 6.5)), ((4.5, 12.5), (14.5, 12.5))]
pathXR = [((7.5, 6.5), (18.5, 6.5)), ((7.5, 12.5), (18.5, 12.5))]

pathCC = [((9.5, 4.5), (9.5, 14.5)), ((4.5, 9.5), (14.5, 9.5))]
pathDX = [((6.5, 0.5), (6.5, 18.5)), ((12.5, 0.5), (12.5, 18.5))]
pathDY = [((0.5, 6.5), (18.5, 6.5)), ((0.5, 12.5), (18.5, 12.5))]

pathDT = [((0.5, 6.5), (18.5, 6.5)), ((0.5, 12.5), (18.5, 12.5)),
Example #32
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)
Example #33
0
	def drawRect_(self, rect): ## must be `drawRect_` - nothing else

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


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

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

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


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

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

			# Draw components in gray
			#------------------------
			NSColor.darkGrayColor().set() # lightGrayColor
			bezierPathWithComponents.fill()
			
			
			# Draw only path in black
			#------------------------
			if thisGlyph.export:
				NSColor.blackColor().set()
				if bezierPathOnly:
					bezierPathOnly.fill()
			# Draw non-exported glyphs in orange
			#-----------------------------------
			else:
				NSColor.orangeColor().set()
				bezierPathWithComponents.fill()
			
			# AUTO-WIDTH LABEL
			#-----------------
			if self._layer.hasAlignedWidth():
				paragraphStyle = NSMutableParagraphStyle.alloc().init()
				paragraphStyle.setAlignment_(2) ## 0=L, 1=R, 2=C, 3=justified
				attributes = {}
				attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(10)
				attributes[NSForegroundColorAttributeName] = NSColor.lightGrayColor()
				attributes[NSParagraphStyleAttributeName] = paragraphStyle
				String = NSAttributedString.alloc().initWithString_attributes_("Auto-Width", attributes)
				# String.drawAtPoint_((rectWidth, 0))
				NSColor.redColor().set()
				# NSRectFill(((0, 0), (self.rect.size.width, 15)))
				String.drawInRect_(((0, 0), (self.rect.size.width, 15)))
		except:
			pass # print traceback.format_exc()
Example #34
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()
Example #35
0
 def drawPreviewNeighBors(self, info):
     if not RamsayStData.showPreview:
         return
     fillColor = NSColor.blackColor()
     fillColor.set()
     self._drawNeighborsGlyphs(info["glyph"], stroke=False)
Example #36
0
 def drawPreviewNeighBors(self, info):
     fillColor = NSColor.blackColor()
     fillColor.set()
     self._drawNeightborsGlyphs(info["glyph"], stroke=False)
Example #37
0
def addCountBadgeToIcon(count, iconImage=None):
    if iconImage is None:
        iconImage = NSImage.alloc().initWithSize_((40, 40))
        iconImage.lockFocus()
        NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 1, .5).set()
        path = NSBezierPath.bezierPath()
        path.appendBezierPathWithOvalInRect_(((0, 0), iconImage.size()))
        path.fill()
        iconImage.unlockFocus()

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

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

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

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

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

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

    badgeLeft = imageWidth - badgeWidth - 3
    badgeBottom = 3

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

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

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

    # done
    image.unlockFocus()
    return image
Example #38
0
from Foundation import NSMakeRect, NSAffineTransform, NSClassFromString, NSMakePoint, NSZeroRect

def drawGlyph(glyph):
	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):
Example #39
0
    r = r / 255.0
    g = g / 255.0
    b = b / 255.0
    return NSColor.colorWithCalibratedRed_green_blue_alpha_(r, g, b, a)


def rgba(r, g, b, a=1.0):
    """rgb values between 0 and 1"""
    return getRGBA(r * 255, b * 255, g * 255, a)


rgb = rgba

# Preset colors.

blackColor = NSColor.blackColor()
opaqueBlackColor = getRGBA(0, 0, 0, 0.5)
blueColor = NSColor.blueColor()
brownColor = NSColor.brownColor()
clearColor = NSColor.clearColor()
cyanColor = NSColor.cyanColor()
darkGrayColor = getRGBA(80, 80, 80)
darkGreyColor = darkGrayColor
grayColor = NSColor.grayColor()
greyColor = grayColor
grayColor = NSColor.grayColor()
greenColor = NSColor.greenColor()
lightGreenColor = getRGBA(75, 211, 154)
darkGreenColor = getRGBA(41, 120, 37)
lightestGrayColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
    0.98, 0.98, 0.98, 1)
Example #40
0
	def drawRect_(self, rect):
		# drawing a full black rectangle
		# set current drawing color
		NSColor.blackColor().set()
		#fill with black
		NSRectFill(rect)
Example #41
0
def show_backdrop(comm_queue, image_path):
    from AppKit import NSWindow, NSWindowCollectionBehaviorCanJoinAllSpaces, NSWindowCollectionBehaviorStationary, \
                       NSWindowCollectionBehaviorIgnoresCycle, NSBorderlessWindowMask, NSBackingStoreBuffered, NSColor, \
                       NSApplication, NSScreen, NSView, NSImage, NSImageView, NSZeroRect, NSCompositeCopy, NSApp, \
                       NSTimer, NSObject, NSEvent, NSApplicationDefined, NSMakePoint, NSBundle
    from Quartz import kCGDesktopWindowLevel
    from ctypes import CDLL, Structure, POINTER, c_uint32, byref
    from ctypes.util import find_library

    class ProcessSerialNumber(Structure):
        _fields_ = [('highLongOfPSN', c_uint32), ('lowLongOfPSN', c_uint32)]

    kCurrentProcess = 2
    kProcessTransformToUIElementAppication = 4
    ApplicationServices = CDLL(find_library('ApplicationServices'))
    TransformProcessType = ApplicationServices.TransformProcessType
    TransformProcessType.argtypes = [POINTER(ProcessSerialNumber), c_uint32]

    class MainController(NSObject):
        timer = None

        def kickRunLoop(self):
            event = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, \
                            NSMakePoint(0,0), 0, 0.0, 0, None, 0, 0, 0)
            NSApp.postEvent_atStart_(event, True)

        def checkProcess_(self, timer):
            if not comm_queue.empty():
                # We Get Signal, Take Off Every Zig - er, time to shut down this forked process
                # Clear the queue
                while not comm_queue.empty():
                    ignore = comm_queue.get_nowait()
                NSApp.stop_(None)
                # After you stop the runloop, the app has to receive another event to determine the runloop stopped ...
                self.kickRunLoop()

        def run(self):
            # You could adjust the 1.0 here to how ever many seconds you wanted to wait between checks to terminate
            self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
                1.0, self, self.checkProcess_, None, True)
            NSApp.run()

    class FullScreenWindow(NSWindow):
        def canBecomeKeyWindow(self):
            return False

        def canBecomeMainWindow(self):
            return False

    class LockView(NSView):
        def getTopOffset(self, height):
            return (self.bounds().size.height / 2) - height / 2

        def getLeftOffset(self, width):
            return (self.bounds().size.width / 2) - width / 2

        def drawRect_(self, rect):
            image = NSImage.alloc().initWithContentsOfFile_(image_path)
            rep = image.representations()[0]
            bg_width = rep.pixelsWide()
            bg_height = rep.pixelsHigh()
            image.drawInRect_fromRect_operation_fraction_(
                ((self.getLeftOffset(bg_width), self.getTopOffset(bg_height)),
                 (bg_width, bg_height)), NSZeroRect, NSCompositeCopy, 1.0)
            imageView = NSImageView.alloc().init()
            imageView.setImage_(image)
            self.addSubview_(imageView)

    bundle = NSBundle.mainBundle()
    info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
    # Did you know you can override parts of infoDictionary (Info.plist, after loading) even though Apple says it's read-only?
    # This is enough to make an app faceless / without a Dock icon
    info['LSUIElement'] = '1'
    # Initialize our shared application instance
    app = NSApplication.sharedApplication()
    # ... This isn't really necessary, but it's nice to ensure that the application truly is UIElement type
    psn = ProcessSerialNumber(0, kCurrentProcess)
    ApplicationServices.TransformProcessType(
        psn, kProcessTransformToUIElementAppication)
    screen = NSScreen.mainScreen()
    myWindow = FullScreenWindow.alloc(
    ).initWithContentRect_styleMask_backing_defer_(screen.frame(),
                                                   NSBorderlessWindowMask,
                                                   NSBackingStoreBuffered,
                                                   True)
    myView = LockView.alloc().initWithFrame_(screen.frame())
    myWindow.setContentView_(myView)
    myWindow.setLevel_(kCGDesktopWindowLevel)
    myWindow.setCollectionBehavior_(NSWindowCollectionBehaviorCanJoinAllSpaces
                                    | NSWindowCollectionBehaviorStationary
                                    | NSWindowCollectionBehaviorIgnoresCycle)
    myWindow.setBackgroundColor_(NSColor.blackColor())
    myWindow.makeKeyAndOrderFront_(myWindow)
    myWindow.display()
    controller = MainController.alloc().init()
    controller.run()
Example #42
0
W = 800  # Width of the sample image. Heights is calculated from string.
# Height of the sample image
ML = 2  # Margin between text and image side in pixels.
MR = 1
MT = 0  # Above ascender, depending on extended ascender feature
MB = 1  # Below descender, depending on extended descender feature

LAYER_OPTIONS = ('1', '2', '3', '4', '5')
# Tracking in amount of pixels
TRACKING_OPTIONS = ('-2', '-1', '0', '1', '2', '3', '4', '5')

Save_PDF = True
Sample_Text = u'TypeLab'  # Initial sample string
Spacing_Variant = True  #random()<0.5
Tracking = 0
Background_Color = NSColor.blackColor()
Italic = False
Italic_Shapes = False  # [ss08]
Condensed = False  # [ss07] Excludes Double if selected
Smallcaps = False  # [smcp]
Caps_As_Smallcaps = False  # [c2cs]
Extended_Ascenders = False  # [ss01]
Extended_Capitals = False  # [ss02]
Extended_Descenders = False  # [ss03]
Contrast_Pixel = False  # [ss04] and [ss05]
Alternative_g = False  # [ss09]
LC_Figures = False  # [onum]
Layers = 2  # Popup list index. Default is 3
Gray_Scale = True
Slashed_Zero = True  # [zero]
Layer_Offset_X = -3
Example #43
0
 def drawRect_(self, rect):
     self.lockFocus()
     NSColor.blackColor().set()
     NSRectFill(self.bounds())
     self.unlockFocus()        
Example #44
0
class Size:
    """ A class representing dimensions in pixel of an object """

    def __init__(self, width, height):
        self.width = width
        self.height = height


class Color:
    """ A class representing a color """

    def __init__(self, ns_color):
        self.ns_color = ns_color


Color.BLACK = Color(NSColor.blackColor())
Color.BLUE = Color(NSColor.blueColor())
Color.BROWN = Color(NSColor.brownColor())
Color.CYAN = Color(NSColor.cyanColor())
Color.DARK_GRAY = Color(NSColor.darkGrayColor())
Color.GRAY = Color(NSColor.grayColor())
Color.GREEN = Color(NSColor.greenColor())
Color.MAGENTA = Color(NSColor.magentaColor())
Color.ORANGE = Color(NSColor.orangeColor())
Color.PURPLE = Color(NSColor.purpleColor())
Color.RED = Color(NSColor.redColor())
Color.WHITE = Color(NSColor.whiteColor())
Color.YELLOW = Color(NSColor.yellowColor())


class Font:
    def __init__(self):

        if len(AllFonts()) == 0:
            print "Please open at least one font before using Ground Control"
            return

        # [windowWidth, maxWindowWidth, minWindowWidth]
        self.xDimensions = [1200, 2880, 400]
        # [windowHeight, maxWindowHeight, minWindowHeight headerHeight, footerHeight]
        self.yDimensions = [600, 1800, 400, 50, 28]
        self.allLinesHeight = self.yDimensions[0] - (self.yDimensions[3] + self.yDimensions[4])
        self.lineNames = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth"]
        self.pointSizeList = ["36", "48", "56", "64", "72", "96", "128", "160", "192", "256", "364", "512"]
        self.trackingValuesList = ["%+d" % i for i in range(-100, -60, 20)] + ["%+d" % i for i in range(-60, -30, 10)] + ["%+d" % i for i in range(-30, -10, 6)] + ["%+d" % i for i in range(-10, 10, 2)] + ["%+d" % i for i in range(10, 30, 6)] + ["%+d" % i for i in range(30, 60, 10)] + ["%+d" % i for i in range(60, 120, 20)]
        self.fontsOnBench = []
        self.charMap = CurrentFont().getCharacterMapping()
        self.glyphSet = ["A", "B", "C"]
        self.lastModifiedFont = None
        self.globalTrackingValue = 0
        self.minNumberOfLines = 2
        self.maxNumberOfLines = 9
        self.selectedLine = None
        self.showAllControls = False
        self.displaySettings = {"Show Metrics": [[False, False] for i in range(self.maxNumberOfLines)], "Inverse": [[False, False] for i in range(self.maxNumberOfLines)], "Upside Down": [[False, False] for i in range(self.maxNumberOfLines)]}
        self.baseColor = NSColor.blackColor()
        self.selectionColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.3, .1, .1, 0.8)

        self.w = Window((self.xDimensions[0], self.yDimensions[0]), "Ground Control " + GCVersion, maxSize=(self.xDimensions[1], self.yDimensions[1]), minSize=(self.xDimensions[2], self.yDimensions[2]))
        self.w.header = Group((0, 0, -0, self.yDimensions[3]))
        self.w.allLines = Group((0, self.w.header.getPosSize()[3], -0, self.allLinesHeight))
        self.w.footer = Group((0, -self.yDimensions[4], -0, self.yDimensions[4]))

        import os
        if os.path.isfile("GroundControlPrefList.txt"):
            with open("GroundControlPrefList.txt") as myfile:
                prefList = myfile.read().split("\n")
        else:
            prefList = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "HHH0HHH00HHH000HHH", "nnnonnnoonnnooonnn"]

        self.w.header.inputText = ComboBox((10, 10, -320, 22),
            prefList,
            continuous = True,
            completes = True,
            callback = self.inputCallback)
        self.w.header.pointSizePopUp = PopUpButton((-305, 10, 60, 22), self.pointSizeList, callback=self.pointSizePopUpCallback)
        self.w.header.pointSizePopUp.setTitle("128")
        self.w.header.globalTrackingPopUp = PopUpButton((-175, 10, 60, 22), self.trackingValuesList, callback=self.trackingPopUpCallback)
        self.w.header.globalTrackingPopUp.setTitle("+0")
        self.w.header.applyAllTrackingButton = Button((-110, 10, 100, 22), "Apply All", callback=self.ApplyAllTracking)

        self.w.footer.toggleAllControlsButton = Button((-260, 7, 100, 14), "All Controls", sizeStyle="mini", callback=self.toggleAllLineControlsCallback)
        self.w.footer.addLineButton = Button((-135, 7, 60, 14), "Add", sizeStyle="mini", callback=self.addBenchLine)
        self.w.footer.removeLineButton = Button((-70, 7, 60, 14), "Remove", sizeStyle="mini", callback=self.removeLastBenchLine)
        self.w.footer.options = Group((10, 5, -260, 18))
        self.w.footer.options.fontName = TextBox((0, 2, 50, 18), "All", sizeStyle="small")
        self.w.footer.options.showMetrics = CheckBox((50, 0, 90, 18), "Show Metrics", sizeStyle="small", callback=self.showMetricsCallback)
        self.w.footer.options.inverse = CheckBox((150, 0, 60, 18), "Inverse", sizeStyle="small", callback=self.inverseCallback)
        self.w.footer.options.upsideDown = CheckBox((220, 0, 90, 18), "Flip", sizeStyle="small", callback=self.flipCallback)

        index = 0

        for lineName in self.lineNames:

            # One part of the object is Methods & Attributes
            setattr(self.w.allLines, lineName + "MethAttr", BenchLine(index))
            thisLineMethAttr = getattr(self.w.allLines, lineName + "MethAttr")

            # The second part of the object corresponds to the Vanilla objects, MultiLineView, buttons and such
            setattr(self.w.allLines, lineName + "Vanillas", thisLineMethAttr.display())
            thisLineVanillas = getattr(self.w.allLines, lineName + "Vanillas")

            thisLineVanillas.show(False)
            thisLineMethAttr.setFontCombo(self.allFontsList())
            thisLineMethAttr.setTrackingCombo(self.trackingValuesList)
            index += 1

        self.getFontsOnBench()
        self.setBench()

        addObserver(self, "_currentGlyphChanged", "currentGlyphChanged")
        addObserver(self, "updateCurrentGlyphInView", "keyDown")
        addObserver(self, "updateCurrentGlyphInView", "mouseDown")
        addObserver(self, "updateCurrentGlyphInView", "mouseDragged")
        addObserver(self, "updateFontsCallback", "fontDidOpen")
        addObserver(self, "updateFontsCallback", "fontDidClose")
        self.w.bind("resize", self.resizeWindowCallback)
        self.w.open()
Example #46
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
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,
Example #47
0
    def __init__(self):

        if len(AllFonts()) == 0:
            print "Please open at least one font before using Ground Control"
            return

        # [windowWidth, maxWindowWidth, minWindowWidth]
        self.xDimensions = [1200, 2880, 400]
        # [windowHeight, maxWindowHeight, minWindowHeight headerHeight, footerHeight]
        self.yDimensions = [600, 1800, 400, 50, 28]
        self.allLinesHeight = self.yDimensions[0] - (self.yDimensions[3] +
                                                     self.yDimensions[4])
        self.lineNames = [
            "first", "second", "third", "fourth", "fifth", "sixth", "seventh",
            "eighth", "ninth"
        ]
        self.pointSizeList = [
            "36", "48", "56", "64", "72", "96", "128", "160", "192", "256",
            "364", "512"
        ]
        self.trackingValuesList = ["%+d" % i for i in range(-100, -60, 20)] + [
            "%+d" % i for i in range(-60, -30, 10)
        ] + ["%+d" % i for i in range(-30, -10, 6)] + [
            "%+d" % i for i in range(-10, 10, 2)
        ] + ["%+d" % i for i in range(10, 30, 6)] + [
            "%+d" % i for i in range(30, 60, 10)
        ] + ["%+d" % i for i in range(60, 120, 20)]
        self.fontsOnBench = []
        self.charMap = CurrentFont().getCharacterMapping()
        self.glyphSet = ["A", "B", "C"]
        self.lastModifiedFont = None
        self.globalTrackingValue = 0
        self.minNumberOfLines = 2
        self.maxNumberOfLines = 9
        self.selectedLine = None
        self.showAllControls = False
        self.displaySettings = {
            "Show Metrics":
            [[False, False] for i in range(self.maxNumberOfLines)],
            "Inverse": [[False, False] for i in range(self.maxNumberOfLines)],
            "Upside Down":
            [[False, False] for i in range(self.maxNumberOfLines)]
        }
        self.baseColor = NSColor.blackColor()
        self.selectionColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
            .3, .1, .1, 0.8)

        self.w = Window((self.xDimensions[0], self.yDimensions[0]),
                        "Ground Control " + GCVersion,
                        maxSize=(self.xDimensions[1], self.yDimensions[1]),
                        minSize=(self.xDimensions[2], self.yDimensions[2]))
        self.w.header = Group((0, 0, -0, self.yDimensions[3]))
        self.w.allLines = Group(
            (0, self.w.header.getPosSize()[3], -0, self.allLinesHeight))
        self.w.footer = Group(
            (0, -self.yDimensions[4], -0, self.yDimensions[4]))

        import os
        if os.path.isfile("GroundControlPrefList.txt"):
            with open("GroundControlPrefList.txt") as myfile:
                prefList = myfile.read().split("\n")
        else:
            prefList = [
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
                "HHH0HHH00HHH000HHH", "nnnonnnoonnnooonnn"
            ]

        self.w.header.inputText = ComboBox((10, 10, -320, 22),
                                           prefList,
                                           continuous=True,
                                           completes=True,
                                           callback=self.inputCallback)
        self.w.header.pointSizePopUp = PopUpButton(
            (-305, 10, 60, 22),
            self.pointSizeList,
            callback=self.pointSizePopUpCallback)
        self.w.header.pointSizePopUp.setTitle("128")
        self.w.header.globalTrackingPopUp = PopUpButton(
            (-175, 10, 60, 22),
            self.trackingValuesList,
            callback=self.trackingPopUpCallback)
        self.w.header.globalTrackingPopUp.setTitle("+0")
        self.w.header.applyAllTrackingButton = Button(
            (-110, 10, 100, 22), "Apply All", callback=self.ApplyAllTracking)

        self.w.footer.toggleAllControlsButton = Button(
            (-260, 7, 100, 14),
            "All Controls",
            sizeStyle="mini",
            callback=self.toggleAllLineControlsCallback)
        self.w.footer.addLineButton = Button((-135, 7, 60, 14),
                                             "Add",
                                             sizeStyle="mini",
                                             callback=self.addBenchLine)
        self.w.footer.removeLineButton = Button(
            (-70, 7, 60, 14),
            "Remove",
            sizeStyle="mini",
            callback=self.removeLastBenchLine)
        self.w.footer.options = Group((10, 5, -260, 18))
        self.w.footer.options.fontName = TextBox((0, 2, 50, 18),
                                                 "All",
                                                 sizeStyle="small")
        self.w.footer.options.showMetrics = CheckBox(
            (50, 0, 90, 18),
            "Show Metrics",
            sizeStyle="small",
            callback=self.showMetricsCallback)
        self.w.footer.options.inverse = CheckBox((150, 0, 60, 18),
                                                 "Inverse",
                                                 sizeStyle="small",
                                                 callback=self.inverseCallback)
        self.w.footer.options.upsideDown = CheckBox((220, 0, 90, 18),
                                                    "Flip",
                                                    sizeStyle="small",
                                                    callback=self.flipCallback)

        index = 0

        for lineName in self.lineNames:

            # One part of the object is Methods & Attributes
            setattr(self.w.allLines, lineName + "MethAttr", BenchLine(index))
            thisLineMethAttr = getattr(self.w.allLines, lineName + "MethAttr")

            # The second part of the object corresponds to the Vanilla objects, MultiLineView, buttons and such
            setattr(self.w.allLines, lineName + "Vanillas",
                    thisLineMethAttr.display())
            thisLineVanillas = getattr(self.w.allLines, lineName + "Vanillas")

            thisLineVanillas.show(False)
            thisLineMethAttr.setFontCombo(self.allFontsList())
            thisLineMethAttr.setTrackingCombo(self.trackingValuesList)
            index += 1

        self.getFontsOnBench()
        self.setBench()

        addObserver(self, "_currentGlyphChanged", "draw")
        addObserver(self, "updateFontsCallback", "fontDidOpen")
        addObserver(self, "updateFontsCallback", "fontDidClose")
        self.w.bind("resize", self.resizeWindowCallback)
        self.w.open()
    def __init__(self):
        f = CurrentFont()
        if f is None:
            return
        self.shapeColor = None
        self.backgroundColor = None
        self.extrapolateMinValue = 0
        self.extrapolateMaxValue = 1
        self.w = vanilla.Window((500, 600), "Responsive Lettering", minSize=(300,200))
        self.w.preview = HTMLView((0,0,-0, -140))
        self.w.exportButton = vanilla.Button((-150, -30, -10, 20), "Export SVG", callback=self.cbExport)        
        columnDescriptions = [
            dict(title="Glyphname", key="name", width=125),
            dict(title="Width", key="width", width=50),
            dict(title="Height", key="height", width=50),
            dict(title="Bounds?", key="bounds", width=75),
            dict(title="Contours", key="contours", width=50),
            dict(title="Points", key="points", width=50),
        ]
        self.w.l = vanilla.List((0,-140,-0,-40), self.wrapGlyphs(), columnDescriptions=columnDescriptions, doubleClickCallback=self.callbackListClick)
        self.w.t = vanilla.TextBox((70,-27,-160,20), "FontName", sizeStyle="small")
        self.w.backgroundColorWell = vanilla.ColorWell((10,-30, 20, 20), callback=self.backgroundColorWellCallback, color=NSColor.blackColor())
        self.w.shapeColorWell = vanilla.ColorWell((35,-30, 20, 20), callback=self.shapeColorWellCallback, color=NSColor.whiteColor())

        self.w.bind("became main", self.windowBecameMainCallback)
        self.setColorsFromLib()
        self.update()
        self.w.open()
        self.cbMakePreview(None)