예제 #1
0
    def drawPoints(self, glyph, scale):
        save()
        _onCurveSize = self._onCurvePointsSize * scale
        _offCurveSize = self._offCurvePointsSize * scale
        _strokeWidth = self._strokeWidth * scale
        
        self._pointsColor.set()
        
        path = NSBezierPath.bezierPath()
        offCurveHandlesPath = NSBezierPath.bezierPath()
        pointsData = glyph.getRepresentation("doodle.OutlineInformation")
        
        for point1, point2 in pointsData["bezierHandles"]:
            offCurveHandlesPath.moveToPoint_(point1)
            offCurveHandlesPath.lineToPoint_(point2)

        for point in pointsData.get("offCurvePoints"):
            (x, y) = point["point"]
            path.appendBezierPathWithOvalInRect_(NSMakeRect(x - _offCurveSize, y - _offCurveSize, _offCurveSize * 2, _offCurveSize * 2))
            
        for point in pointsData.get("onCurvePoints"):
            (x, y) = point["point"]
            path.appendBezierPathWithRect_(NSMakeRect(x - _onCurveSize, y - _onCurveSize, _onCurveSize * 2, _onCurveSize * 2))
            
        path.fill()
        offCurveHandlesPath.setLineWidth_(_strokeWidth)
        strokePixelPath(offCurveHandlesPath)
        restore()
예제 #2
0
    def background(self, layer):

        # Check if the drawing should be shown

        currentController = self.controller.view().window().windowController()
        if currentController:
            tool = currentController.toolDrawDelegate()
            if tool.isKindOfClass_(NSClassFromString("GlyphsToolText")) \
                    or tool.isKindOfClass_(NSClassFromString("GlyphsToolHand")) \
                    or tool.isKindOfClass_(NSClassFromString("ScrawlTool")):
                return

        # draw pixels

        data = layer.userData["%s.data" % plugin_id]
        if data is None:
            return
        try:
            data = NSImage.alloc().initWithData_(data)
        except:
            print("Error in image data of layer %s" % layer)
            return

        rect = layer.userData["%s.rect" % plugin_id]
        if rect is None:
            # The drawing rect was not stored in user data.
            # Deduce it from the layer/font metrics.
            font = layer.parent.parent
            pad = int(round(font.upm / 10))

            # find master for image positioning (descender)

            try:
                descender = layer.parent.parent.masters[
                    layer.layerId].descender
            except KeyError:
                descender = int(round(font.upm / 5))

            rect = NSMakeRect(-pad, descender - pad, 2 * pad + layer.width,
                              2 * pad + font.upm)
        else:
            # Use the rect from user data
            rect = NSMakeRect(*rect)
        NSGraphicsContext.saveGraphicsState()
        NSGraphicsContext.currentContext().setImageInterpolation_(
            NSImageInterpolationNone)
        if len(layer.paths) == 0:
            data.drawInRect_(rect)
        else:
            data.drawInRect_fromRect_operation_fraction_(
                rect, NSZeroRect, NSCompositeSourceOver, 0.2)
        NSGraphicsContext.restoreGraphicsState()
예제 #3
0
 def saveScrawlToBackground(self, layer):
     font = layer.parent.parent
     if font.filepath is None:
         print(
             "You must save the Glyphs file before a Scrawl background image can be added."
         )
         return
     data = layer.userData["%s.data" % plugin_id]
     pixel_size = layer.userData["%s.unit" % plugin_id]
     pixel_ratio = layer.master.customParameters['ScrawlPenRatio']
     if pixel_ratio is None:
         pixel_ratio = default_pixel_ratio
     else:
         pixel_ratio = float(pixel_ratio)
     rect = NSMakeRect(*layer.userData["%s.rect" % plugin_id])
     if data is not None:
         image_path = join(dirname(font.filepath),
                           "%s-%s.png" % (layer.layerId, layer.parent.name))
         try:
             imgdata = NSBitmapImageRep.alloc().initWithData_(data)
         except:
             print("Error saving the image file.")
             return
         pngdata = imgdata.representationUsingType_properties_(
             NSPNGFileType, None)
         pngdata.writeToFile_atomically_(image_path, False)
         layer.backgroundImage = GSBackgroundImage(image_path)
         layer.backgroundImage.position = NSPoint(rect.origin.x,
                                                  rect.origin.y)
         layer.backgroundImage.scale = (float(pixel_size),
                                        float(pixel_size * pixel_ratio))
예제 #4
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
예제 #5
0
 def __init__(self, message, title, default_text='', dimensions=(320, 160)):
     super(SecureRumpsWindow, self).__init__(message, title)
     self._textfield = NSSecureTextField.alloc().initWithFrame_(
         NSMakeRect(0, 0, *dimensions))
     self._textfield.setSelectable_(True)
     self._alert.setAccessoryView_(self._textfield)
     self._textfield.setStringValue_(unicode(default_text))
예제 #6
0
    def _drawUnspecified(self, position, kind, size, vector=(-1, 1)):
        if vector is None:
            vector = (-1, 1)
        angle = atan2(vector[1], vector[0])
        circle_size = size * 1.3
        x, y = position
        NSColor.colorWithCalibratedRed_green_blue_alpha_(0.9, 0.1, 0.0,
                                                         0.85).set()

        t = NSAffineTransform.transform()
        t.translateXBy_yBy_(x, y)
        t.rotateByRadians_(angle)

        myPath = NSBezierPath.alloc().init()
        myPath.setLineWidth_(0)
        myPath.appendBezierPathWithOvalInRect_(
            NSMakeRect(x - 0.5 * circle_size, y - 0.5 * circle_size,
                       circle_size, circle_size))
        myPath.stroke()
        if self.show_labels or distance_between_points(self.mouse_position,
                                                       position) < size:
            self._drawTextLabel(
                transform=t,
                text=kind,
                size=size,
                angle=angle,
            )
예제 #7
0
 def draw(self, rect):
     #NSColor.redColor().set()
     yellowColor.set()
     for n in range(50):
         rgba(random(), random(), random())
         rect = NSMakeRect(n * 400 + M, n * 400 + M, M, M)
         path = NSBezierPath.bezierPathWithRect_(rect)
         path.fill()
예제 #8
0
    def loadScrawl(self):
        if self.current_layer is None:
            return

        pen_size = self.current_layer.userData["%s.size" % plugin_id]
        if pen_size is not None:
            self.pen_size = pen_size  # scrawl pixels
            # Otherwise, keep the previous size

        self.pixel_size = self.current_layer.userData["%s.unit" % plugin_id]
        if self.pixel_size is None:
            self.pixel_size = default_pixel_size  # font units

        self.pixel_ratio = self.current_layer.master.customParameters[
            'ScrawlPenRatio'
        ]
        if self.pixel_ratio is None:
            self.pixel_ratio = default_pixel_ratio
        else:
            self.pixel_ratio = float(self.pixel_ratio)

        # Drawing rect
        rect = self.current_layer.userData["%s.rect" % plugin_id]
        if rect is None:
            self.loadDefaultRect()
        else:
            self.rect = NSMakeRect(*rect)

        # Image data
        data = self.current_layer.userData["%s.data" % plugin_id]
        if data is None:
            self.data = initImage(
                self.current_layer,
                self.rect.size.width,
                self.rect.size.height,
                self.pixel_size,
                self.pixel_ratio
            )
        else:
            try:
                self.data = NSBitmapImageRep.alloc().initWithData_(data)
                self.data.setProperty_withValue_(
                    NSImageColorSyncProfileData,
                    None
                )
            except:
                print("Error in image data of layer %s" % self.current_layer)
                self.data = initImage(
                    self.current_layer,
                    self.rect.size.width,
                    self.rect.size.height,
                    self.pixel_size,
                    self.pixel_ratio
                )
        self.needs_save = False
예제 #9
0
    def setTrackingArea(self, x, y, w, h, active):
        if active == 'always':
            a = NSTrackingActiveAlways
        else:
            a = NSTrackingActiveWhenFirstResponder

        rect = NSMakeRect(x, y, w, h)
        self.setFrame_(rect)
        opts = NSTrackingMouseEnteredAndExited | a | NSTrackingMouseMoved | \
        NSTrackingInVisibleRect
        trackingArea = NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(rect,
                opts, self, None)
        self.addTrackingArea_(trackingArea)
예제 #10
0
    def loadDefaultRect(self):
        # Make the default drawing rect based on master and layer dimensions
        font = self.current_layer.parent.parent
        upm = font.upm
        pad = int(round(upm / 10))

        try:
            descender = font.masters[self.current_layer.layerId].descender
        except (AttributeError, KeyError):
            descender = int(round(-upm / 5))

        self.rect = NSMakeRect(-pad, descender - pad,
                               2 * pad + self.current_layer.width,
                               2 * pad + upm)
    def createWindow(self) -> NSWindow:
        style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable
                 | NSWindowStyleMaskMiniaturizable
                 | NSWindowStyleMaskResizable)

        window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            NSMakeRect(10, 10, 800, 600),  # Initial
            style,
            NSBackingStoreBuffered,
            False)
        window.setTitle_("My App")
        window.setLevel_(NSStatusWindowLevel)
        window.setFrameAutosaveName_("main-window")

        return window
예제 #12
0
    def imagecapture(self,
                     window_name=None,
                     x=0,
                     y=0,
                     width=None,
                     height=None):
        """
        Captures screenshot of the whole desktop or given window
        
        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param x: x co-ordinate value
        @type x: int
        @param y: y co-ordinate value
        @type y: int
        @param width: width co-ordinate value
        @type width: int
        @param height: height co-ordinate value
        @type height: int

        @return: screenshot with base64 encoded for the client
        @rtype: string
        """
        if x or y or (width and width != -1) or (height and height != -1):
            raise LdtpServerException("Not implemented")
        if window_name:
            handle, name, app = self._get_window_handle(window_name)
            try:
                self._grabfocus(handle)
            except:
                pass
            rect = self._getobjectsize(handle)
            screenshot = CGWindowListCreateImage(
                NSMakeRect(rect[0], rect[1], rect[2], rect[3]), 1, 0, 0)
        else:
            screenshot = CGWindowListCreateImage(CGRectInfinite, 1, 0, 0)
        image = CIImage.imageWithCGImage_(screenshot)
        bitmapRep = NSBitmapImageRep.alloc().initWithCIImage_(image)
        blob = bitmapRep.representationUsingType_properties_(
            NSPNGFileType, None)
        tmpFile = tempfile.mktemp('.png', 'ldtpd_')
        blob.writeToFile_atomically_(tmpFile, False)
        rv = b64encode(open(tmpFile).read())
        os.remove(tmpFile)
        return rv
예제 #13
0
    def __init__(self, dimensions):
        super(DashedRectangle, self).__init__(dimensions, scale="none")

        box_width = self.getPosSize()[2]
        box_height = self.getPosSize()[3]

        line_image = NSImage.alloc().initWithSize_((box_width, box_height))
        line_image.lockFocus()
        path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
            NSMakeRect(.5, .5, box_width - 1, box_height - 1), 5, 5)
        path.setLineWidth_(1.0)
        path.setLineDash_count_phase_((5, 5), 2, 0)
        NSColor.colorWithCalibratedWhite_alpha_(0, 0.1).set()
        path.stroke()
        line_image.unlockFocus()

        self.setImage(imageObject=line_image)
예제 #14
0
    def __init__(self):
        ''' initializes an alert with custom view containing username and
            password fields with a save to keychain checkbox'''
        # Create an dialog with ok and cancel buttons
        self.alert = NSAlert.alloc().init()
        self.alert.setMessageText_('Please enter your username and password!')
        self.alert.addButtonWithTitle_('Ok')
        self.alert.addButtonWithTitle_('Cancel')

        # create the view for username and password fields
        accessory_view = NSView.alloc().initWithFrame_(
            NSMakeRect(0, 114, 250, 110))

        # setup username field and label
        self.username_field = NSTextField.alloc().initWithFrame_(
            NSMakeRect(0, 70, 250, 22))
        username_label = NSTextField.alloc().initWithFrame_(
            NSMakeRect(0, 94, 250, 20))
        username_label.setStringValue_('Username:'******'Password:'******'Save to Keychain')
        self.keychain_checkbox.cell().setBordered_(False)
        self.keychain_checkbox.cell().setEnabled_(True)
        self.keychain_checkbox.cell().setState_(True)

        # add various objects as subviews
        accessory_view.addSubview_(self.keychain_checkbox)
        accessory_view.addSubview_(username_label)
        accessory_view.addSubview_(self.username_field)
        accessory_view.addSubview_(password_label)
        accessory_view.addSubview_(self.password_field)

        # add custom view to alert dialog
        self.alert.setAccessoryView_(accessory_view)
예제 #15
0
 def open_license(_):
     print(0)
     alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
         'License', None, None, None, 'GNU General Public License, version 3')
     alert.setAlertStyle_(0)
     textview = NSTextView.alloc().initWithFrame_(NSMakeRect(0, 0, 420, 180))
     textview.setEditable_(False)
     if getattr(sys, 'frozen', False):
         # noinspection PyUnresolvedReferences
         textview.setString_('\n' + open(sys._MEIPASS[:len(sys._MEIPASS) - 5] + 'Resources/LICENSE').read())
     else:
         textview.setString_('\n' + open('LICENSE').read())
     sv = NSScrollView.alloc().initWithFrame_(textview.frame())
     sv.setBorderType_(1)
     sv.setHasVerticalScroller_(True)
     sv.setAutoresizingMask_(2 | 16)
     sv.setDocumentView_(textview)
     alert.setAccessoryView_(sv)
     alert.runModal()
예제 #16
0
def average_color_from_screenshot(path=None, path2=None, region=None):
    if region is None:
        region = CG.CGRectInfinite

    # Create screenshot as CGImage
    image = CG.CGDisplayCreateImage(get_widest_display())

    height = CG.CGImageGetHeight(image)
    width = CG.CGImageGetWidth(image)

    if path:
        drawImageToFile(image, path)

    # Create smaller image2 from captured image
    width2 = 1
    height2 = 1
    context = CG.CGBitmapContextCreate(None, width2, height2, 8, width2 * 4,
                                       CG.CGColorSpaceCreateDeviceRGB(), 1)

    CG.CGContextScaleCTM(context,
                         float(width2) / width,
                         float(height2) / height)
    CG.CGContextSetInterpolationQuality(context, CG.kCGInterpolationHigh)

    CG.CGContextDrawImage(context, NSMakeRect(0, 0, width, height), image)
    image2 = CG.CGBitmapContextCreateImage(context)

    if path2:
        drawImageToFile(image2, path2)

    # Extract pixel value
    prov2 = CG.CGImageGetDataProvider(image2)
    data2 = CG.CGDataProviderCopyData(prov2)
    c1 = struct.unpack_from("BBBB", data2, offset=0)

    c2 = NSColor.colorWithCalibratedRed_green_blue_alpha_(
        c1[0] / 255.0, c1[1] / 255.0, c1[2] / 255.0, c1[3] / 255.0)
    result = (c2.hueComponent(), c2.saturationComponent(),
              c2.brightnessComponent())

    return result
예제 #17
0
    def _drawUnspecified(self,
                         position,
                         kind,
                         size,
                         vector=(-1, 1),
                         level="e"):
        if vector is None:
            vector = (-1, 1)
        angle = atan2(vector[1], vector[0])
        circle_size = size * 1.3
        x, y = position
        if level == "e":
            arrow_color = error_color
        else:
            arrow_color = warning_color
        NSColor.colorWithCalibratedRed_green_blue_alpha_(*arrow_color).set()

        t = NSAffineTransform.transform()
        t.translateXBy_yBy_(x, y)
        t.rotateByRadians_(angle)

        myPath = NSBezierPath.alloc().init()
        myPath.setLineWidth_(0)
        myPath.appendBezierPathWithOvalInRect_(
            NSMakeRect(
                x - 0.5 * circle_size,
                y - 0.5 * circle_size,
                circle_size,
                circle_size,
            ))
        myPath.stroke()
        percent = (-distance_between_points(self.mouse_position, position) /
                   size * 2 + 2)
        if self.show_labels or percent > 0.2:
            self._drawTextLabel(
                transform=t,
                text=kind,
                size=size,
                vector=vector,
                percent=percent,
            )
 def drawTextAtPoint(self,
                     text,
                     textPosition,
                     textAlignment=3,
                     fontSize=9.0,
                     fontColor=NSColor.brownColor()):
     """
     Use self.drawTextAtPoint("blabla", myNSPoint) to display left-aligned text at myNSPoint.
     """
     try:
         glyphEditView = self.controller.graphicView()
         fontAttributes = {
             NSFontAttributeName: NSFont.labelFontOfSize_(fontSize),
             NSForegroundColorAttributeName: fontColor
         }
         displayText = NSAttributedString.alloc(
         ).initWithString_attributes_(text, fontAttributes)
         displayText.drawAtPoint_alignment_visibleInRect_(
             textPosition, textAlignment, NSMakeRect(NSNotFound, 0, 0, 0))
     except Exception as e:
         self.logToConsole("drawTextAtPoint: %s" % str(e))
예제 #19
0
    def foreground(self, layer):
        try:
            self.mouse_position = self.editViewController().graphicView(
            ).getActiveLocation_(Glyphs.currentEvent())
        except:
            # self.logToConsole("foreground: mouse_position: %s" % str(e))
            self.mouse_position = None
            return

        if self.mouse_position is not None:
            # Draw a preview circle at the mouse position
            x, y = self.mouse_position
            rect = NSMakeRect(x - self.pen_size / 2,
                              y - self.pen_size * self.pixel_ratio / 2,
                              self.pen_size, self.pen_size * self.pixel_ratio)
            path = NSBezierPath.bezierPathWithOvalInRect_(rect)
            path.setLineWidth_(1)
            if self.erase:
                NSColor.redColor().set()
            else:
                NSColor.lightGrayColor().set()
            path.stroke()
예제 #20
0
def initImage(layer, width, height, pixel_size=default_pixel_size, ratio=1):
    # See https://developer.apple.com/documentation/appkit/nsbitmapimagerep/1395538-init
    img = NSBitmapImageRep.alloc(
    ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(
        None,  # BitmapDataPlanes
        int(round(width / pixel_size)),  # pixelsWide
        int(round(height / pixel_size / ratio)),  # pixelsHigh
        8,  # bitsPerSample: 1, 2, 4, 8, 12, or 16
        1,  # samplesPerPixel: 1 - 5
        False,  # hasAlpha
        False,  # isPlanar
        NSDeviceWhiteColorSpace,  # colorSpaceName
        # NSDeviceRGBColorSpace,
        0,  # bitmapFormat
        0,  # bytesPerRow
        0,  # bitsPerPixel
    )
    """
        NSCalibratedWhiteColorSpace
        NSCalibratedBlackColorSpace
        NSCalibratedRGBColorSpace
        NSDeviceWhiteColorSpace
        NSDeviceBlackColorSpace
        NSDeviceRGBColorSpace
        NSDeviceCMYKColorSpace
        NSNamedColorSpace
        NSCustomColorSpace
    """
    # The image is filled black for some reason, make it white
    current = NSGraphicsContext.currentContext()
    context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(img)
    NSGraphicsContext.setCurrentContext_(context)
    NSColor.whiteColor().set()
    # NSBezierPath.setLineWidth_(1)
    NSBezierPath.fillRect_(NSMakeRect(0, 0, width, int(round(height / ratio))))
    NSGraphicsContext.setCurrentContext_(current)
    return img
예제 #21
0
파일: main.py 프로젝트: sycomix/unicron
    def __init__(self):
        self.locations = [
            'User Agents', 'Global Agents', 'Global Daemons', 'System Agents',
            'System Daemons'
        ]
        self.listItems = []
        self.selected = {}

        # Preferences
        self.homedir = os.path.expanduser('~')
        self.prefsFolder = self.homedir + "/Library/Preferences/"
        self.prefsFile = "de.nelsonfritsch.unicron.plist"

        if os.path.isfile(self.prefsFolder + self.prefsFile):
            self.prefs = self._loadPrefs(self)
        else:
            self.prefs = dict(showSystemWarning=True, windowStyle='System')
            self._savePrefs(self)

        # Preferences Window
        self.prefsWindow = Window((300, 105), 'Preferences')

        self.styles = ['System', 'Light', 'Dark']
        self.prefsWindow.styleTxt = TextBox((10, 10, -10, 20), "Window Style:")
        self.prefsWindow.style = PopUpButton((30, 35, -10, 20),
                                             self.styles,
                                             callback=self.prefsSetStyle)

        self.prefsWindow.restore = Button((10, 75, -10, 20),
                                          'Restore Warnings',
                                          callback=self.prefsRestoreWarnings)

        # Main Window
        minsize = 285
        self.w = Window((minsize, 400),
                        'Unicron',
                        closable=True,
                        fullSizeContentView=True,
                        titleVisible=False,
                        minSize=(minsize, minsize),
                        maxSize=(600, 1200),
                        autosaveName="UnicronMainWindow")

        self.pathList = NSPopUpButton.alloc().initWithFrame_(
            ((0, 0), (160, 20)))
        self.pathList.addItemsWithTitles_(self.locations)

        refreshIcon = NSImage.alloc().initWithSize_((32, 32))
        sourceImage = NSImage.imageNamed_(NSImageNameRefreshTemplate)

        w, h = sourceImage.size()

        if w > h:
            diffx = 0
            diffy = w - h
        else:
            diffx = h - w
            diffy = 0

        maxSize = max([w, h])
        refreshIcon.lockFocus()
        sourceImage.drawInRect_fromRect_operation_fraction_(
            NSMakeRect(diffx, diffy + 4, 22, 22),
            NSMakeRect(0, 0, maxSize, maxSize), NSCompositeSourceOver, 1)
        refreshIcon.unlockFocus()
        refreshIcon.setTemplate_(True)

        toolbarItems = [
            dict(itemIdentifier="Daemons",
                 label="Daemons",
                 toolTip="Daemon Group",
                 view=self.pathList,
                 callback=self.populateList),
            dict(itemIdentifier="image",
                 label="Image",
                 imageObject=refreshIcon,
                 callback=self.populateList),
        ]
        self.w.addToolbar("Unicron Toolbar",
                          toolbarItems=toolbarItems,
                          displayMode="icon")

        self.w.blend = Group((0, 0, 0, 0), blendingMode='behindWindow')

        self.listColumnDescriptions = [{
            'title': '',
            'key': 'image',
            'width': 25,
            'typingSensitive': True,
            'allowsSorting': True,
            'cell': ImageListCell()
        }, {
            'title': 'Name',
            'key': 'name',
            'typingSensitive': True,
            'allowsSorting': True,
        }]
        self.rowHeight = 20
        self.w.list = List((0, 37, -0, 0),
                           items=self.listItems,
                           columnDescriptions=self.listColumnDescriptions,
                           showColumnTitles=True,
                           allowsEmptySelection=True,
                           allowsMultipleSelection=False,
                           autohidesScrollers=True,
                           drawFocusRing=False,
                           rowHeight=self.rowHeight,
                           selectionCallback=self._selectionCallback,
                           menuCallback=self._menuCallback)

        self.w.list._nsObject.setBorderType_(NSNoBorder)

        self.w.statusbar = Group((0, -26, 0, 0), blendingMode='behindWindow')
        self.w.statusbar.border = HorizontalLine((0, 0, 0, 1))

        self.w.counter = TextBox((16, -20, -16, 15),
                                 '',
                                 alignment='center',
                                 sizeStyle='small')
        self.populateList(self)
        self.w.rowIndicator = Group((0, 0, 0, 10))

        self.prefsSetStyle(self)

        self.w.open()
예제 #22
0
 def __init__(self, title, message, items, icon=None, hide_dock=True):
     super(SelectDialog, self).__init__(title, message, icon=icon, hide_dock=hide_dock)
     self.select_dropdown = NSPopUpButton.alloc().initWithFrame_(NSMakeRect(0, 0, 300, 24))
     self.select_dropdown.addItemsWithTitles_(items)
     self.alert.setAccessoryView_(self.select_dropdown)
예제 #23
0
 def drawGradient(self, originX, originY, width, height):
     gradient = gradients[self.curves]
     gradient.drawInRect_angle_(NSMakeRect(originX, originY, width, height),
                                0)
예제 #24
0
 def __init__(self, title, message):
     InputDialog.__init__(self, title, message)
     self.input = NSSecureTextField.alloc().initWithFrame_(
         NSMakeRect(0, 0, 200, 24))
     self.alert.setAccessoryView_(self.input)
예제 #25
0
    def setupUI(self):
        self.statusbar = NSStatusBar.systemStatusBar()
        # Create the statusbar item
        self.statusitem = self.statusbar.statusItemWithLength_(
            NSVariableStatusItemLength)
        # Set initial image
        raw_data = base64.b64decode(''.join(
            GOAGENT_ICON_DATA.strip().splitlines()))
        self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data))
        self.image = NSImage.alloc().initWithData_(self.image_data)
        self.statusitem.setImage_(self.image)
        # Let it highlight upon clicking
        self.statusitem.setHighlightMode_(1)
        # Set a tooltip
        self.statusitem.setToolTip_(GOAGENT_TITLE)

        # Build a very simple menu
        self.menu = NSMenu.alloc().init()
        # Show Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Show', 'show:', '')
        self.menu.addItem_(menuitem)
        # Hide Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Hide', 'hide2:', '')
        self.menu.addItem_(menuitem)
        # Rest Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Reload', 'reset:', '')
        self.menu.addItem_(menuitem)
        # Default event
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Quit', 'exit:', '')
        self.menu.addItem_(menuitem)
        # Bind it to the status item
        self.statusitem.setMenu_(self.menu)

        # Console window
        frame = NSMakeRect(0, 0, 550, 350)
        self.console_window = NSWindow.alloc(
        ).initWithContentRect_styleMask_backing_defer_(
            frame, NSClosableWindowMask | NSTitledWindowMask,
            NSBackingStoreBuffered, False)
        self.console_window.setTitle_(GOAGENT_TITLE)
        self.console_window.setDelegate_(self)

        # Console view inside a scrollview
        self.scroll_view = NSScrollView.alloc().initWithFrame_(frame)
        self.scroll_view.setBorderType_(NSNoBorder)
        self.scroll_view.setHasVerticalScroller_(True)
        self.scroll_view.setHasHorizontalScroller_(False)
        self.scroll_view.setAutoresizingMask_(NSViewWidthSizable
                                              | NSViewHeightSizable)

        self.console_view = NSTextView.alloc().initWithFrame_(frame)
        self.console_view.setVerticallyResizable_(True)
        self.console_view.setHorizontallyResizable_(True)
        self.console_view.setAutoresizingMask_(NSViewWidthSizable)

        self.scroll_view.setDocumentView_(self.console_view)

        contentView = self.console_window.contentView()
        contentView.addSubview_(self.scroll_view)

        # Hide dock icon
        NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
예제 #26
0
 def setSize(self, w, h):
     self.setFrame_(NSMakeRect(0, 0, w, h))
예제 #27
0
	def drawDot(self, point, colorDots):
		widthP = int(self.w.ptThickness.get()) / self.scale
		rect = NSMakeRect(point[0]-widthP, point[1]-widthP, widthP * 2, widthP * 2)
		path = NSBezierPath.bezierPathWithOvalInRect_(rect)
		colorDots.set()
		path.fill()
예제 #28
0
    def settings(self):
        from vanilla import Group, Slider, TextBox, Window
        self.name = 'Scrawl'
        self.slider_value = 1  # current slider value

        # Create Vanilla window and group with controls
        viewWidth = 266
        viewHeight = 42
        self.sliderMenuView = Window((viewWidth, viewHeight))
        self.sliderMenuView.group = Group((0, 0, viewWidth, viewHeight))
        self.w = self.sliderMenuView.group
        y = 0
        self.w.text = TextBox((20, y, -20, 17), "%s Pen Size" % self.name)
        y += 18
        self.w.pen_size = Slider(
            (20, y, -60, 24),
            minValue=1,
            maxValue=256,
            value=float(self.slider_value),
            tickMarkCount=0,
            # stopOnTickMarks = False,
            # continuuous = True,
            callback=self.slider_callback,
            sizeStyle="small",
        )
        self.w.pen_size_text = TextBox((-50, y + 3, -20, 17),
                                       "%s" % default_pen_size)

        self.generalContextMenus = [
            {
                "view": self.sliderMenuView.group.getNSView()
            },
            {
                "name":
                Glyphs.localize({
                    'en': u'Delete Scrawl',
                    'de': u'Gekritzel löschen'
                }),
                "action":
                self.delete_data
            },
            {
                "name":
                Glyphs.localize({
                    'en':
                    u'Save Scrawl To Background Image',
                    'de':
                    u'Gekritzel als Hintergrundbild speichern'
                }),
                "action":
                self.save_background
            },
            # {
            #     "name": Glyphs.localize({
            #         'en': u'Save current size as master default',
            #         'de': u'Aktuelle Größe als Master-Standard speichern'
            #     }),
            #     "action": self.save_background
            # },
        ]
        self.keyboardShortcut = 'c'
        self.pen_size = default_pen_size
        self.pixel_size = default_pixel_size
        self.pixel_ratio = default_pixel_ratio
        self.rect = NSMakeRect(0, 0, 1000, 1000)
        self.data = None
        self.prev_location = None
        self.erase = False
        self.mouse_position = None
        self.layer = None
        self.needs_save = False
        self.current_layer = self.get_current_layer()
예제 #29
0
        color = r, g, b, a
        copy_to_clipboard({
            "hex": color_to_hex,
            "uicolor": color_to_uicolor,
            "rgba": color_to_rgba,
            "rgb": color_to_rgb
        }.get(format, color_to_hex)(color))
        self.close()

    def close(self):
        app.terminate_(None)


cb = Callback.alloc().init()

accessory = NSView.alloc().initWithFrame_(NSMakeRect(0, 0, 200, 34))
for i, name in enumerate(['Cancel', 'Copy']):
    button = NSButton.alloc().init()
    button.setBezelStyle_(NSRoundedBezelStyle)
    button.setTitle_(name)
    button.sizeToFit()
    x = (i + 0.5) / 2 * 200 - button.frame().size.width / 2
    frame = NSMakeRect(x, (34 - button.frame().size.height) / 2,
                       button.frame().size.width,
                       button.frame().size.height)
    button.setFrame_(frame)
    button.setAutoresizingMask_(NSViewMaxXMargin | NSViewMinXMargin
                                | NSViewMaxYMargin | NSViewMinYMargin)
    button.setTarget_(cb)
    button.setAction_({"Cancel": "close", "Copy": "copy"}[name])
    accessory.addSubview_(button)
예제 #30
0
 def draw(self, rect):  # Drawing delegate from the Canvas drawing evening
     for n in range(50):
         rgba(random(), random(), random()).set()
         rect = NSMakeRect(random() * 400 + M, random() * 400 + M, M, M)
         path = NSBezierPath.bezierPathWithRect_(rect)
         path.fill()