def drawRect_(self, rect):
     gradient = NSGradient.alloc().initWithColors_([
         NSColor.colorWithDeviceRed_green_blue_alpha_(
             121 / 256.0, 121 / 256.0, 121 / 256.0, 1),
         NSColor.colorWithDeviceRed_green_blue_alpha_(
             111 / 256.0, 111 / 256.0, 111 / 256.0, 1)
     ])
     gradient.drawInRect_angle_(rect, 90.0)
     NSView.drawRect_(self, rect)
Exemplo n.º 2
0
    def getColor(self):
        color = NSColor.colorWithRed_green_blue_alpha_(0, 0, 0,
                                                       0.9)  # Initial value

        colorStr = Glyphs.font.customParameters['blindfoldColor']
        if colorStr:
            colorTuple = eval(colorStr)
            if type(colorTuple) == tuple and len(colorTuple) == 4:
                color = NSColor.colorWithRed_green_blue_alpha_(*colorTuple)

        color.set()
Exemplo n.º 3
0
    def makeDragImage(self):
        if self.delegate is None:
            return

        image = NSImage.alloc().initWithSize_(self.frame().size)
        image.lockFocus()

        frame = self.frame()
        frame.origin = NSZeroPoint
        rect = NSInsetRect(frame, 1.5, 1.5)

        if self.conferencing and not self.draggedOut:
            NSColor.selectedControlColor().colorWithAlphaComponent_(0.7).set()
        else:
            NSColor.whiteColor().colorWithAlphaComponent_(0.7).set()
        path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
        path.fill()

        if self.selected:
            path.setLineWidth_(3)
            NSColor.grayColor().set()
        else:
            path.setLineWidth_(1)
            NSColor.grayColor().set()
        path.stroke()

        NSColor.blackColor().set()
        point = NSMakePoint(8, NSMaxY(frame)-20)
        uri = format_identity_to_string(self.delegate.sessionController.remotePartyObject, check_contact=False, format='compact')
        NSString.stringWithString_(uri).drawAtPoint_withAttributes_(point,
              NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(12), NSFontAttributeName))
        point = NSMakePoint(8, 6)
        if self.conferencing:
            NSString.stringWithString_(NSLocalizedString("Drop outside to remove from conference", "Audio session label")).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))
        else:
            audio_sessions = [sess.hasStreamOfType("audio") for sess in NSApp.delegate().contactsWindowController.sessionControllersManager.sessionControllers]
            if self.delegate.transferEnabled:
                text = NSLocalizedString("Drop this over a session or contact", "Audio session label") if len(audio_sessions) > 1 else NSLocalizedString("Drop this over a contact to transfer", "Audio session label")
            else:
                text = NSLocalizedString("Drop this over a session to conference", "Audio session label")
            NSString.stringWithString_(text).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))

        icon = NSImage.imageNamed_("NSEveryone")
        rect = frame
        s = icon.size()
        p = NSMakePoint(NSWidth(rect) - s.width - 8, rect.size.height - s.height - 8)
        r = NSMakeRect(0, 0, s.width, s.height)
        icon.drawAtPoint_fromRect_operation_fraction_(p, r, NSCompositeSourceOver, 0.5)

        image.unlockFocus()
        return image
class ConferenceFileCell(NSTextFieldCell):
    conference_file = None

    nameAttrs = NSDictionary.dictionaryWithObjectsAndKeys_(
      NSFont.systemFontOfSize_(12.0), NSFontAttributeName)

    nameAttrs_highlighted = NSDictionary.dictionaryWithObjectsAndKeys_(
      NSFont.systemFontOfSize_(12.0), NSFontAttributeName,
      NSColor.whiteColor(), NSForegroundColorAttributeName)

    infoAttrs = NSDictionary.dictionaryWithObjectsAndKeys_(
      NSFont.systemFontOfSize_(NSFont.labelFontSize()-1), NSFontAttributeName,
      NSColor.grayColor(), NSForegroundColorAttributeName)

    infoAttrs_highlighted = NSDictionary.dictionaryWithObjectsAndKeys_(
      NSFont.systemFontOfSize_(NSFont.labelFontSize()-1), NSFontAttributeName,
      NSColor.whiteColor(), NSForegroundColorAttributeName)

    def drawingRectForBounds_(self, rect):
        return rect

    @objc.python_method
    def cellSize(self):
        if self.conference_file is None:
            return objc.super(ConferenceFileCell, self).cellSize()
        return NSMakeSize(100, 30)

    def drawWithFrame_inView_(self, frame, view):
        if self.conference_file is None:
            tmp = frame
            return objc.super(ConferenceFileCell, self).drawWithFrame_inView_(tmp, view)

        self.drawIcon(self.conference_file.icon, 2, frame.origin.y+3, 28, 28)

        # 1st line: file name
        frame.origin.x = 35
        frame.origin.y += 2
        attrs = self.nameAttrs if not self.isHighlighted() else self.nameAttrs_highlighted
        self.conference_file.name.drawAtPoint_withAttributes_(frame.origin, attrs)

        # 2nd line: file sender
        point = frame.origin
        point.y += 15
        attrs = self.infoAttrs if not self.isHighlighted() else self.infoAttrs_highlighted
        self.conference_file.sender.drawAtPoint_withAttributes_(point, attrs)

    @objc.python_method
    def drawIcon(self, icon, origin_x, origin_y, size_x, size_y):
        size = icon.size()
        rect = NSMakeRect(0, 0, size.width, size.height)
        trect = NSMakeRect(origin_x, origin_y, (size_y/size.height) * size.width, size_x)
        icon.drawInRect_fromRect_operation_fraction_respectFlipped_hints_(trect, rect, NSCompositeSourceOver, 1.0, True, None)
 def _NH_BlinkFileTransferDidEnd(self, notification):
     if notification.data.error:
         self.sizeText.setTextColor_(NSColor.redColor())
         if type(self.transfer) == OutgoingPushFileTransferHandler:
             self.retryButton.setHidden_(False)
     else:
         self.sizeText.setTextColor_(NSColor.blueColor())
         if self.transfer.direction == 'incoming':
             self.revealButton.setHidden_(False)
     self.fromText.setStringValue_(self.transfer.target_text)
     self.sizeText.setStringValue_(self.transfer.progress_text)
     self.failed = notification.data.error
     self.done = True
     self.relayoutForDone()
    def initWithFrame_(self, frame):
        """ basic constructor for views. here we init colors and gradients """

        self = super(CBGraphView, self).initWithFrame_(frame)

        if self:
            self.gradientGray = NSColor.colorWithCalibratedRed_green_blue_alpha_(50/255.0, 50/255.0, 50/255.0, 1.0)
            self.lineColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(33/255.0, 104/255.0, 198/255.0, 1.0)
            self.lineColorAboveLimit = NSColor.redColor()
            self.borderColor = NSColor.whiteColor()

            self.grad = NSGradient.alloc().initWithStartingColor_endingColor_(NSColor.blackColor(), self.gradientGray)
            self.grad.retain()

        return self
Exemplo n.º 7
0
    def handle_remote_response(self, same_secrets=False):
        if not same_secrets:
            self.statusText.setTextColor_(NSColor.redColor())
            self.statusText.setStringValue_(NSLocalizedString("Identity verification failed. Try again later.", "Label"))
            result = False
        else:
            self.stream.encryption.verified = True
            self.statusText.setTextColor_(NSColor.greenColor())
            self.statusText.setStringValue_(NSLocalizedString("Identity verification succeeded", "Label"))
            self.controller.revalidateToolbar()
            self.controller.updateEncryptionWidgets()
            result = True

        self._finish(result)
        return result
    def retryTransfer_(self, sender):
        if self.oldTransferInfo:
            try:
                account = (account for account in AccountManager().iter_accounts() if account.id == self.oldTransferInfo.local_uri).next()
            except StopIteration:
                account = AccountManager().default_account
            from FileTransferWindowController import openFileTransferSelectionDialog
            target_uri = normalize_sip_uri_for_outgoing_session(self.oldTransferInfo.remote_uri, AccountManager().default_account)
            openFileTransferSelectionDialog(account, target_uri, self.oldTransferInfo.file_path)
        else:
            self.failed = False
            self.done = False

            self.updateProgressInfo()
            self.progressBar.setIndeterminate_(True)
            self.progressBar.startAnimation_(None)
            self.progressBar.setHidden_(True)

            self.updateChecksumProgressInfo(0)
            self.checksumProgressBar.setIndeterminate_(False)
            self.checksumProgressBar.startAnimation_(None)
            self.checksumProgressBar.setHidden_(False)

            self.sizeText.setTextColor_(NSColor.grayColor())
            self.relayoutForRetry()
            self.transfer.retry()
 def initWithContentRect_styleMask_backing_defer_(self, contentRect, aStyle, bufferingType, flag):
     self = super(RoundWindow, self).initWithContentRect_styleMask_backing_defer_(contentRect, NSBorderlessWindowMask, bufferingType, flag)
     if self:
         self.setStyleMask_(NSBorderlessWindowMask|NSResizableWindowMask)
         self.setOpaque_(False)
         self.setBackgroundColor_(NSColor.clearColor())
         return self
Exemplo n.º 10
0
    def initialize(self):
        paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy()
        paraStyle.setAlignment_(NSCenterTextAlignment)

        self.badgeAttributes = NSMutableDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(8),
                                NSFontAttributeName, NSColor.whiteColor(), NSForegroundColorAttributeName,
                                paraStyle, NSParagraphStyleAttributeName)
Exemplo n.º 11
0
    def drawCentralArea(self, layer):
        '''Draw the central area (第二中心区域).'''
        spacing = self.centralAreaSpacing

        descender = layer.descender
        ascender = layer.ascender

        if not self.centralAreaRotateState:
            width = self.centralAreaWidth
            height = ascender - descender
            x_mid = layer.width * self.centralAreaPosition / 100
            (x0, y0) = (x_mid - spacing / 2 - width / 2, descender)
            (x1, y1) = (x_mid + spacing / 2 - width / 2, descender)
        else:
            width = layer.width
            height = self.centralAreaWidth
            y_mid = descender + (ascender -
                                 descender) * self.centralAreaPosition / 100
            (x0, y0) = (0, y_mid - spacing / 2 - height / 2)
            (x1, y1) = (0, y_mid + spacing / 2 - height / 2)

        # TODO: color
        color = NSColor.systemGrayColor().colorWithAlphaComponent_(0.2)
        color.set()

        NSBezierPath.fillRect_(((x0, y0), (width, height)))
        NSBezierPath.fillRect_(((x1, y1), (width, height)))
Exemplo n.º 12
0
	def colorForParameterValue( self, parameterString ):
		"""
		Turns '0.3;0.4;0.9' into RGB values and returns an NSColor object.
		"""
		try:
			# default color:
			RGBA = [ 0.4, 0.0, 0.3, 0.15 ]
			
			# if set, take user input as color:
			if parameterString is not None:
				parameterValues = parameterString.split(";")
				for i in range(len( parameterValues )):
					thisValueString = parameterValues[i]
					try:
						thisValue = abs(float( thisValueString ))
						if thisValue > 1.0:
							thisValue %= 1.0
						RGBA[i] = thisValue
					except Exception as e:
						pass
						# self.logToConsole( "Could not convert '%s' (from '%s') to a float. Keeping default." % (thisValueString, parameterString) )
			
			# return the color:
			thisColor = NSColor.colorWithCalibratedRed_green_blue_alpha_( RGBA[0], RGBA[1], RGBA[2], RGBA[3] )
			return thisColor
		except Exception as e:
			self.logToConsole( "colorForParameterValue: %s" % str(e) )
Exemplo n.º 13
0
    def drawMedialAxes(self, layer):
        '''Draw the medial axes (水平垂直轴线).'''
        # TODO: set vertical and horizontal in dialog
        vertical = 0.5
        horizontal = 0.5

        scale = self.getScale()

        view = Glyphs.font.currentTab.graphicView()
        visibleRect = view.visibleRect()
        activePosition = view.activePosition()

        viewOriginX = (visibleRect.origin.x - activePosition.x) / scale
        viewOriginY = (visibleRect.origin.y - activePosition.y) / scale
        viewWidth = visibleRect.size.width / scale
        viewHeight = visibleRect.size.height / scale

        height = layer.ascender - layer.descender
        width = layer.width

        x = horizontal * width
        y = layer.descender + vertical * height

        # TODO: color
        color = NSColor.systemGreenColor()
        color.set()

        path = NSBezierPath.bezierPath()
        path.moveToPoint_((viewOriginX, y))
        path.lineToPoint_((viewOriginX + viewWidth, y))
        path.moveToPoint_((x, viewOriginY))
        path.lineToPoint_((x, viewOriginY + viewHeight))
        path.setLineWidth_(1 / scale)
        path.stroke()
Exemplo n.º 14
0
 def initWithFrame_(self, frame):
     self = super(ListView, self).initWithFrame_(frame)
     if self:
         self.setBackgroundColor_(NSColor.whiteColor())
         NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "windowChangedKey:", NSWindowDidBecomeKeyNotification, None)
         NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "windowChangedKey:", NSWindowDidResignKeyNotification, None)
     return self
Exemplo n.º 15
0
    def okClicked_(self, sender):
        self.statusText.setTextColor_(NSColor.blackColor())
        if self.finished:
            self.window.orderOut_(self)
            return

        secret = self.secretText.stringValue().encode('utf-8')
        if not secret:
            return

        if self.response:
            self.ctx.smpGotSecret(secret, appdata={'stream': self.chatController.stream})
            self.progressBar.setIndeterminate_(False)
            self.progressBar.setDoubleValue_(6)
            self.continueButton.setEnabled_(False)
            self.statusText.setStringValue_('Responding to verification request...')
        else:
            try:
                qtext = self.questionText.stringValue()
                if qtext:
                    self.ctx.smpInit(secret, question=qtext.encode('utf-8'), appdata={'stream': self.chatController.stream})
                else:
                    self.ctx.smpInit(secret, appdata={'stream': self.chatController.stream})
                self.progressBar.setIndeterminate_(False)
                self.progressBar.setDoubleValue_(3)
                self.statusText.setStringValue_('Verification request sent')
                self.continueButton.setEnabled_(False)
            except potr.context.NotEncryptedError, e:
                self.statusText.setStringValue_('Chat session is not OTR encrypted')
            except RuntimeError, e:
                self.statusText.setStringValue_('OTR encryption error: %s' % e)
Exemplo n.º 16
0
 def _NH_BlinkFileTransferDidEnd(self, notification):
     self.sizeText.setTextColor_(NSColor.blueColor())
     self.progressBar.stopAnimation_(None)
     self.updateProgressInfo()
     self.relayoutForDone()
     self.done = True
     self.failed = False
    def retryTransfer_(self, sender):
        if self.oldTransferInfo:
            try:
                account = next(
                    (account for account in AccountManager().iter_accounts()
                     if account.id == self.oldTransferInfo.local_uri))
            except StopIteration:
                account = AccountManager().default_account
            target_uri = normalize_sip_uri_for_outgoing_session(
                self.oldTransferInfo.remote_uri,
                AccountManager().default_account)
            filenames = [
                unicodedata.normalize('NFC', self.oldTransferInfo.file_path)
            ]
            NSApp.delegate(
            ).contactsWindowController.sessionControllersManager.send_files_to_contact(
                account, target_uri, filenames)
        else:
            self.failed = False
            self.done = False

            self.updateProgressInfo()
            self.progressBar.setIndeterminate_(True)
            self.progressBar.startAnimation_(None)
            self.progressBar.setHidden_(True)

            self.updateChecksumProgressInfo(0)
            self.checksumProgressBar.setIndeterminate_(False)
            self.checksumProgressBar.startAnimation_(None)
            self.checksumProgressBar.setHidden_(False)

            self.sizeText.setTextColor_(NSColor.grayColor())
            self.relayoutForRetry()
            self.transfer.retry()
Exemplo n.º 18
0
    def colorForParameterValue(self, parameterString):
        """
		Turns '0.3;0.4;0.9' into RGB values and returns an NSColor object.
		"""
        try:
            # default color:
            RGBA = [0.4, 0.0, 0.3, 0.15]

            # if set, take user input as color:
            if parameterString is not None:
                parameterValues = parameterString.split(";")
                for i in range(len(parameterValues)):
                    thisValueString = parameterValues[i]
                    try:
                        thisValue = abs(float(thisValueString))
                        if thisValue > 1.0:
                            thisValue %= 1.0
                        RGBA[i] = thisValue
                    except Exception as e:
                        pass
                        # self.logToConsole( "Could not convert '%s' (from '%s') to a float. Keeping default." % (thisValueString, parameterString) )

            # return the color:
            thisColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
                RGBA[0], RGBA[1], RGBA[2], RGBA[3])
            return thisColor
        except Exception as e:
            self.logToConsole("colorForParameterValue: %s" % str(e))
 def initWithContentRect_styleMask_backing_defer_(self, contentRect, aStyle, bufferingType, flag):
     self = objc.super(BorderlessRoundWindow, self).initWithContentRect_styleMask_backing_defer_(contentRect, aStyle, bufferingType, flag)
     if self:
         self.setStyleMask_(NSBorderlessWindowMask|NSResizableWindowMask)
         self.setOpaque_(False)
         self.setBackgroundColor_(NSColor.clearColor())
         self.setMinSize_(NSSize(100, 50))
         return self
Exemplo n.º 20
0
    def initialize(self):
        paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy()
        paraStyle.setAlignment_(NSCenterTextAlignment)

        self.badgeAttributes = NSMutableDictionary.dictionaryWithObjectsAndKeys_(
            NSFont.boldSystemFontOfSize_(8), NSFontAttributeName,
            NSColor.whiteColor(), NSForegroundColorAttributeName, paraStyle,
            NSParagraphStyleAttributeName)
Exemplo n.º 21
0
    def drawRect_(self, rect):
        NSImageView.drawRect_(self, rect)

        if self.cropRectangle:
            rect = NSZeroRect
            rect.size = self.frame().size

            NSColor.whiteColor().set()
            NSFrameRect(self.cropRectangle)

            clip = NSBezierPath.bezierPathWithRect_(rect)
            clip.setWindingRule_(NSEvenOddWindingRule)
            clip.appendBezierPathWithRect_(self.cropRectangle)

            clip.addClip()

            NSColor.blackColor().colorWithAlphaComponent_(0.6).set()
            NSBezierPath.bezierPathWithRect_(rect).fill()
Exemplo n.º 22
0
    def initWithFrame_(self, frame):
        """ basic constructor for views. here we init colors and gradients """

        self = objc.super(CBGraphView, self).initWithFrame_(frame)

        if self:
            self.gradientGray = NSColor.colorWithCalibratedRed_green_blue_alpha_(
                50 / 255.0, 50 / 255.0, 50 / 255.0, 1.0)
            self.lineColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
                33 / 255.0, 104 / 255.0, 198 / 255.0, 1.0)
            self.lineColorAboveLimit = NSColor.redColor()
            self.borderColor = NSColor.whiteColor()

            self.grad = NSGradient.alloc().initWithStartingColor_endingColor_(
                NSColor.blackColor(), self.gradientGray)
            self.grad.retain()

        return self
Exemplo n.º 23
0
    def drawRect_(self, rect):
        NSImageView.drawRect_(self, rect)

        if self.cropRectangle:
            rect = NSZeroRect
            rect.size = self.frame().size

            NSColor.whiteColor().set()
            NSFrameRect(self.cropRectangle)

            clip = NSBezierPath.bezierPathWithRect_(rect)
            clip.setWindingRule_(NSEvenOddWindingRule)
            clip.appendBezierPathWithRect_(self.cropRectangle)

            clip.addClip()

            NSColor.blackColor().colorWithAlphaComponent_(0.6).set()
            NSBezierPath.bezierPathWithRect_(rect).fill()
    def initWithFrame_oldTransfer_(self, frame, transferInfo):
        self = NSView.initWithFrame_(self, frame)
        if self:
            self.oldTransferInfo = transferInfo
            self.file_path = transferInfo.file_path
            self.remote_uri = transferInfo.remote_uri
            self.local_uri = transferInfo.local_uri

            NSBundle.loadNibNamed_owner_("FileTransferItemView", self)

            self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(
                self.file_path))

            self.nameText.setStringValue_(os.path.basename(self.file_path))
            self.fromText.setStringValue_(
                'To %s from account %s' %
                (transferInfo.remote_uri,
                 transferInfo.local_uri) if transferInfo.direction ==
                'outgoing' else 'From %s to account %s' %
                (transferInfo.remote_uri, transferInfo.local_uri))

            self.revealButton.setHidden_(not os.path.exists(self.file_path))

            time_print = format_date(transferInfo.time)
            if transferInfo.status == "completed":
                self.sizeText.setTextColor_(NSColor.blueColor())
                t = NSLocalizedString("Completed transfer of ", "Label")
                status = t + "%s %s" % (format_size(transferInfo.file_size,
                                                    1024), time_print)
            else:
                self.sizeText.setTextColor_(NSColor.redColor())
                status = "%s %s" % (transferInfo.status.title(), time_print)

            self.sizeText.setStringValue_(status)
            frame.size = self.view.frame().size
            self.setFrame_(frame)
            self.addSubview_(self.view)
            self.relayoutForDone()
            if transferInfo.direction == "outgoing" and transferInfo.status != "completed" and os.path.exists(
                    self.file_path):
                self.retryButton.setHidden_(False)
            self.done = True
        return self
Exemplo n.º 25
0
	def scrollView(self):
		''' Generate vanilla attribute ScrollView'''
		m = 10
		bgColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.96, .96, .96, 1) # NSColor.yellowColor()
		s = ScrollView((self.scrollViewMargin, self.scrollViewMargin, self.previewSize - self.scrollViewMargin*2, self.previewSize - self.scrollViewMargin*2), # with margins
			self.view,
			hasHorizontalScroller=False,
			hasVerticalScroller=False,
			backgroundColor=bgColor,
			# drawsBackground=False,
			)
		return s
Exemplo n.º 26
0
    def __init__(self, account, encryptedKeyPair):
        NSBundle.loadNibNamed_owner_("ImportPrivateKeyWindow", self)
        self.account = account
        self.encryptedKeyPair = encryptedKeyPair

        self.checksum.setStringValue_('')
        self.importButton.setEnabled_(False)
        self.window.makeFirstResponder_(self.pincode)
        self.status.setTextColor_(NSColor.blackColor())

        self.status.setStringValue_(
            NSLocalizedString("Enter pincode to decrypt the key",
                              "status label"))
Exemplo n.º 27
0
 def initWithFrame_(self, frame):
     self = objc.super(ListView, self).initWithFrame_(frame)
     if self:
         self.setBackgroundColor_(NSColor.whiteColor())
         NSNotificationCenter.defaultCenter(
         ).addObserver_selector_name_object_(
             self, "windowChangedKey:", NSWindowDidBecomeKeyNotification,
             None)
         NSNotificationCenter.defaultCenter(
         ).addObserver_selector_name_object_(
             self, "windowChangedKey:", NSWindowDidResignKeyNotification,
             None)
     return self
 def setSelected_(self, flag):
     if flag:
         self.nameText.setTextColor_(NSColor.whiteColor())
         self.fromText.setTextColor_(NSColor.whiteColor())
         self.sizeText.setTextColor_(NSColor.whiteColor())
     else:
         self.nameText.setTextColor_(NSColor.blackColor())
         self.fromText.setTextColor_(NSColor.grayColor())
         if self.failed:
             self.sizeText.setTextColor_(NSColor.redColor())
         else:
             self.sizeText.setTextColor_(NSColor.grayColor())
Exemplo n.º 29
0
 def setSelected_(self, flag):
     if flag:
         self.nameText.setTextColor_(NSColor.whiteColor())
         self.fromText.setTextColor_(NSColor.whiteColor())
         self.sizeText.setTextColor_(NSColor.whiteColor())
     else:
         self.nameText.setTextColor_(NSColor.blackColor())
         self.fromText.setTextColor_(NSColor.grayColor())
         if self.failed:
             self.sizeText.setTextColor_(NSColor.redColor())
         else:
             self.sizeText.setTextColor_(NSColor.grayColor())
Exemplo n.º 30
0
    def _NH_BlinkFileTransferDidFail(self, notification):
        self.sizeText.setTextColor_(NSColor.redColor())

        self.checksumProgressBar.setHidden_(True)
        self.checksumProgressBar.stopAnimation_(None)
        self.progressBar.setHidden_(True)
        self.progressBar.stopAnimation_(None)
        self.updateProgressInfo()

        self.stopButton.setHidden_(True)
        if type(self.transfer) == OutgoingPushFileTransferHandler:
            self.retryButton.setHidden_(False)
        self.relayoutForDone()
        self.done = True
        self.failed = True
    def replaceWithTransfer_(self, transfer):
        self.transfer = transfer
        NotificationCenter().add_observer(self, sender=transfer)
        self.stopButton.setHidden_(False)
        self.retryButton.setHidden_(True)
        self.progressBar.setHidden_(True)
        self.checksumProgressBar.setHidden_(False)
        self.checksumProgressBar.setIndeterminate_(False)
        self.checksumProgressBar.startAnimation_(None)
        self.sizeText.setTextColor_(NSColor.grayColor())

        frame = self.frame()
        frame.size.height = 68
        self.setFrame_(frame)
        self.addSubview_(self.view)
Exemplo n.º 32
0
    def retryTransfer_(self, sender):
        self.failed = False
        self.done = False

        self.updateProgressInfo()
        self.progressBar.setIndeterminate_(True)
        self.progressBar.startAnimation_(None)
        self.progressBar.setHidden_(True)

        self.updateChecksumProgressInfo(0)
        self.checksumProgressBar.setIndeterminate_(False)
        self.checksumProgressBar.startAnimation_(None)
        self.checksumProgressBar.setHidden_(False)

        self.sizeText.setTextColor_(NSColor.grayColor())
        self.relayoutForRetry()
        self.transfer.retry()
Exemplo n.º 33
0
class SMSSplitView(NSSplitView):
    text = None
    attributes = NSDictionary.dictionaryWithObjectsAndKeys_(
        NSFont.systemFontOfSize_(NSFont.labelFontSize() - 1),
        NSFontAttributeName, NSColor.darkGrayColor(),
        NSForegroundColorAttributeName)

    def setText_(self, text):
        self.text = NSString.stringWithString_(text)
        self.setNeedsDisplay_(True)

    def dividerThickness(self):
        return NSFont.labelFontSize() + 1

    def drawDividerInRect_(self, rect):
        NSSplitView.drawDividerInRect_(self, rect)
        if self.text:
            point = NSMakePoint(
                NSMaxX(rect) -
                self.text.sizeWithAttributes_(self.attributes).width - 10,
                rect.origin.y)
            self.text.drawAtPoint_withAttributes_(point, self.attributes)
Exemplo n.º 34
0
    def __init__(self, sessionController):

        self.notification_center = NotificationCenter()

        self.sessionController = None
        self.audio_stream = None
        self.chat_stream = None

        self.add_session(sessionController)
        self.add_audio_stream()
        self.add_chat_stream()

        self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
        NSBundle.loadNibNamed_owner_("SessionInfoPanel", self)

        sessionBoxTitle = NSAttributedString.alloc().initWithString_attributes_("SIP Session", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.sessionBox.setTitle_(sessionBoxTitle)

        audioBoxTitle = NSAttributedString.alloc().initWithString_attributes_("Audio Stream", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.audioBox.setTitle_(audioBoxTitle)

        chatBoxTitle = NSAttributedString.alloc().initWithString_attributes_("Chat Stream", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.chatBox.setTitle_(chatBoxTitle)

        self.audio_rtt_graph.setLineWidth_(1.0)
        self.audio_rtt_graph.setLineSpacing_(1.0)
        self.audio_rtt_graph.setAboveLimit_(200) # if higher than 200 ms show red color
        self.audio_rtt_graph.setMinimumHeigth_(200)

        self.audio_packet_loss_graph.setLineWidth_(1.0)
        self.audio_packet_loss_graph.setLineSpacing_(1.0)
        self.audio_packet_loss_graph.setAboveLimit_(3) # if higher than 3% show red color
        self.audio_packet_loss_graph.setLineColor_(NSColor.greenColor())
        self.audio_packet_loss_graph.setMinimumHeigth_(5)

        self.resetSession()
        self.updatePanelValues()
Exemplo n.º 35
0
    def drawRect_(self, rect):
        VerticalBoxView.drawRect_(self, rect)

        if self.alternateRows:
            i = 0
            NSColor.colorWithCalibratedRed_green_blue_alpha_(237/256.0, 243/256.0, 254/256.0, 1.0).set()
            for v in self.subviews():
                if i % 2 == 1:
                    NSRectFill(v.frame())
                i += 1

        if self.selection != -1 and self.selection < self.subviews().count():
            if self.window().isKeyWindow():
                NSColor.alternateSelectedControlColor().set()
            else:
                NSColor.lightGrayColor().set()
            NSRectFill(self.subviews()[self.selection].frame())
Exemplo n.º 36
0
    def drawRect_(self, rect):
        VerticalBoxView.drawRect_(self, rect)

        if self.alternateRows:
            i = 0
            NSColor.colorWithCalibratedRed_green_blue_alpha_(
                237 / 256.0, 243 / 256.0, 254 / 256.0, 1.0).set()
            for v in self.subviews():
                if i % 2 == 1:
                    NSRectFill(v.frame())
                i += 1

        if self.selection != -1 and self.selection < self.subviews().count():
            if self.window().isKeyWindow():
                NSColor.alternateSelectedControlColor().set()
            else:
                NSColor.lightGrayColor().set()
            NSRectFill(self.subviews()[self.selection].frame())
Exemplo n.º 37
0
    def drawCjkGuide(self, layer):
        '''Draw the CJK guide (汉字参考线).'''
        self.initCjkGuideGlyph()

        # TODO: color
        color = NSColor.systemOrangeColor().colorWithAlphaComponent_(0.1)
        color.set()

        cjkGuideLayer = Glyphs.font.glyphs[CJK_GUIDE_GLYPH].layers[0]

        trans = NSAffineTransform.transform()
        if self.cjkGuideScalingState:
            # TODO: currently only xScale is necessary
            # cjkGuideMaster = cjkGuideLayer.associatedFontMaster()
            # cjkGuideDescender = cjkGuideMaster.descender
            # cjkGuideAscender = cjkGuideMaster.ascender
            # cjkGuideHeight = cjkGuideAscender - cjkGuideDescender

            # master = layer.associatedFontMaster()
            # descender = master.descender
            # ascender = master.ascender
            # height = ascender - descender

            xScale = layer.width / cjkGuideLayer.width
            # yScale = height / cjkGuideHeight

            # trans.translateXBy_yBy_(0, cjkGuideDescender)
            # trans.scaleXBy_yBy_(xScale, yScale)
            # trans.translateXBy_yBy_(0, -descender)

            trans.scaleXBy_yBy_(xScale, 1)

        if cjkGuideLayer.bezierPath is not None:
            path = cjkGuideLayer.bezierPath.copy()
            path.transformUsingAffineTransform_(trans)
            path.fill()
Exemplo n.º 38
0
    def okClicked_(self, sender):
        self.statusText.setTextColor_(NSColor.blackColor())
        if self.finished:
            self.window.orderOut_(self)
            return

        secret = self.secretText.stringValue()
        secret = secret.encode() if secret else None

        if self.requested_by_remote:
            self.controller.sessionController.log_info("OTR SMP verification will be answered")
            self.stream.encryption.smp_answer(secret)
            self.smp_running = True
            self.progressBar.setDoubleValue_(6)
        else:
            qtext = self.questionText.stringValue()
            qtext = qtext.encode() if qtext else None
            self.controller.sessionController.log_info("OTR SMP verification will be requested")
            self.stream.encryption.smp_verify(secret, qtext)
            self.progressBar.setIndeterminate_(False)
            self.smp_running = True
            self.progressBar.setDoubleValue_(3)
            self.statusText.setStringValue_(NSLocalizedString("Verification request sent", "Label"))
            self.continueButton.setEnabled_(False)
Exemplo n.º 39
0
    def getButtonImageForState(self, size, pushed):
        image = NSImage.alloc().initWithSize_(size)
        image.lockFocus()

        rect = NSMakeRect(1, 1, size.width-1, size.height-1)

        NSColor.clearColor().set()
        NSRectFill(rect)

        try:
            NSColor.blackColor().set()
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 8.0, 8.0)
            path.fill()
            path.setLineWidth_(2)
            NSColor.grayColor().set()
            path.stroke()
        finally:
            image.unlockFocus()
        return image
Exemplo n.º 40
0
    def show(self):
        BlinkLogger().log_debug('Show %s' % self)
        self.active = True

        if self.captureSession is None:
            # Find a video camera
            device = self.getDevice()

            if not device:
                return

            self.captureSession = AVCaptureSession.alloc().init()
            if self.captureSession.canSetSessionPreset_(
                    AVCaptureSessionPresetHigh):
                self.captureSession.setSessionPreset_(
                    AVCaptureSessionPresetHigh)

            NSWorkspace.sharedWorkspace().notificationCenter(
            ).addObserver_selector_name_object_(
                self, "computerDidWake:", NSWorkspaceDidWakeNotification, None)
            NSWorkspace.sharedWorkspace().notificationCenter(
            ).addObserver_selector_name_object_(
                self, "computerWillSleep:", NSWorkspaceWillSleepNotification,
                None)

            max_resolution = (0, 0)
            BlinkLogger().log_debug(
                "%s camera provides %d formats" %
                (device.localizedName(), len(device.formats())))
            for desc in device.formats():
                m = self.resolution_re.match(repr(desc))
                if m:
                    data = m.groupdict()
                    width = int(data['width'])
                    height = int(data['height'])
                    BlinkLogger().log_debug(
                        "Supported resolution: %dx%d %.2f" %
                        (width, height, width / float(height)))
                    if width > max_resolution[0]:
                        max_resolution = (width, height)

            width, height = max_resolution
            if width == 0 or height == 0:
                width = 1280
                height = 720
                BlinkLogger().log_info(
                    "Error: %s camera does not provide any supported video format"
                    % device.localizedName())
            else:
                if NSApp.delegate(
                ).contactsWindowController.sessionControllersManager.isMediaTypeSupported(
                        'video'):
                    BlinkLogger().log_info(
                        "Opened %s camera at %0.fx%0.f resolution" %
                        (SIPApplication.video_device.real_name, width, height))

            self.aspect_ratio = width / float(
                height) if width > height else height / float(width)

            self.captureDeviceInput = AVCaptureDeviceInput.alloc(
            ).initWithDevice_error_(device, None)
            if self.captureDeviceInput:
                try:
                    self.captureSession.addInput_(self.captureDeviceInput[0])
                except ValueError as e:
                    BlinkLogger().log_info(
                        'Failed to add camera input to capture session: %s' %
                        str(e))
                    return
            else:
                BlinkLogger().log_info('Failed to aquire input %s' % self)
                return

            self.setWantsLayer_(True)
            self.videoPreviewLayer = AVCaptureVideoPreviewLayer.alloc(
            ).initWithSession_(self.captureSession)
            self.layer().addSublayer_(self.videoPreviewLayer)
            self.videoPreviewLayer.setFrame_(self.layer().bounds())
            self.videoPreviewLayer.setAutoresizingMask_(
                kCALayerWidthSizable | kCALayerHeightSizable)
            self.videoPreviewLayer.setBackgroundColor_(
                CGColorGetConstantColor(kCGColorBlack))
            self.videoPreviewLayer.setVideoGravity_(
                AVLayerVideoGravityResizeAspectFill)

            self.videoPreviewLayer.setCornerRadius_(5.0)
            self.videoPreviewLayer.setMasksToBounds_(True)

            self.setMirroring()

            self.stillImageOutput = AVCaptureStillImageOutput.new()
            pixelFormat = NSNumber.numberWithInt_(kCVPixelFormatType_32BGRA)
            self.stillImageOutput.setOutputSettings_(
                NSDictionary.dictionaryWithObject_forKey_(
                    pixelFormat, kCVPixelBufferPixelFormatTypeKey))

            self.captureSession.addOutput_(self.stillImageOutput)

        if self.captureSession and self.videoPreviewLayer:
            BlinkLogger().log_info('Start aquire local video %s' % self)
            self.videoPreviewLayer.setBackgroundColor_(
                NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 0.4))
            self.captureSession.startRunning()
Exemplo n.º 41
0
 def append_error_line(self, textView, line):
     red = NSDictionary.dictionaryWithObject_forKey_(NSColor.redColor(), NSForegroundColorAttributeName)
     textView.textStorage().appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(line+"\n", red))
     textView.scrollRangeToVisible_(NSMakeRange(textView.textStorage().length()-1, 1))
Exemplo n.º 42
0
    def drawRect_(self, rect):
        rect = NSInsetRect(self.bounds(), 1.5, 1.5)
        if not self.conferencing:
            NSColor.whiteColor().set()
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                rect, 5.0, 5.0)
            path.fill()

        if self.conferencing:
            if self.draggedOut:
                NSColor.whiteColor().set()
            else:
                # bgcolor for conference area
                NSColor.colorWithDeviceRed_green_blue_alpha_(
                    196 / 255.0, 230 / 255.0, 254 / 255.0, 1.0).set()
            border = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                rect, 5.0, 5.0)
            border.setLineWidth_(1)
            border.fill()
            NSColor.grayColor().set()
            border.stroke()

            # hack: if we're the 1st item, draw the border around all conferenced boxes
            subviews = self.superview().subviews()
            if subviews.objectAtIndex_(0) == self:
                # first in conference list
                rect.size.height += 5
                rect.origin.y -= 5
                path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                    rect, 5.0, 5.0)
            else:
                prev = None
                last = True
                for view in subviews:
                    if prev == self:
                        last = not view.conferencing
                        break
                    prev = view
                # last in conference list
                if last:
                    rect.size.height += 5
                    path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                        rect, 5.0, 5.0)
                else:
                    rect.origin.y -= 5
                    rect.size.height += 10
                    path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                        rect, 5.0, 5.0)

            if self.selected or self.highlighted:
                path.setLineWidth_(3)
            else:
                path.setLineWidth_(1)
            if self.highlighted:
                NSColor.orangeColor().set()
            else:
                NSColor.grayColor().set()
            if self.selected or self.highlighted:
                path.stroke()
        elif self.highlighted:
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                rect, 5.0, 5.0)
            path.setLineWidth_(3)
            NSColor.orangeColor().set()
            path.stroke()
        elif self.selected:
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                rect, 5.0, 5.0)
            path.setLineWidth_(3)
            NSColor.grayColor().set()
            path.stroke()
        else:
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                rect, 5.0, 5.0)
            path.setLineWidth_(1)
            NSColor.grayColor().set()
            path.stroke()
Exemplo n.º 43
0
    def makeDragImage(self):
        if self.delegate is None:
            return

        image = NSImage.alloc().initWithSize_(self.frame().size)
        image.lockFocus()

        frame = self.frame()
        frame.origin = NSZeroPoint
        rect = NSInsetRect(frame, 1.5, 1.5)

        if self.conferencing and not self.draggedOut:
            NSColor.selectedControlColor().colorWithAlphaComponent_(0.7).set()
        else:
            NSColor.whiteColor().colorWithAlphaComponent_(0.7).set()
        path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
            rect, 5.0, 5.0)
        path.fill()

        if self.selected:
            path.setLineWidth_(3)
            NSColor.grayColor().set()
        else:
            path.setLineWidth_(1)
            NSColor.grayColor().set()
        path.stroke()

        NSColor.blackColor().set()
        point = NSMakePoint(8, NSMaxY(frame) - 20)
        uri = format_identity_to_string(
            self.delegate.sessionController.remoteIdentity,
            check_contact=False,
            format='compact')
        NSString.stringWithString_(uri).drawAtPoint_withAttributes_(
            point,
            NSDictionary.dictionaryWithObjectsAndKeys_(
                NSFont.boldSystemFontOfSize_(12), NSFontAttributeName))
        point = NSMakePoint(8, 6)
        if self.conferencing:
            NSString.stringWithString_(
                NSLocalizedString(
                    "Drop outside to remove from conference",
                    "Audio status label")).drawAtPoint_withAttributes_(
                        point,
                        NSDictionary.dictionaryWithObjectsAndKeys_(
                            NSFont.systemFontOfSize_(10), NSFontAttributeName))
        else:
            audio_sessions = [
                sess.hasStreamOfType("audio")
                for sess in NSApp.delegate().contactsWindowController.
                sessionControllersManager.sessionControllers
            ]
            if self.delegate.transferEnabled:
                text = NSLocalizedString(
                    "Drop this over a session or contact", "Audio status label"
                ) if len(audio_sessions) > 1 else NSLocalizedString(
                    "Drop this over a contact to transfer",
                    "Audio status label")
            else:
                text = NSLocalizedString(
                    "Drop this over a session to conference",
                    "Audio status label")
            NSString.stringWithString_(text).drawAtPoint_withAttributes_(
                point,
                NSDictionary.dictionaryWithObjectsAndKeys_(
                    NSFont.systemFontOfSize_(10), NSFontAttributeName))

        icon = NSImage.imageNamed_("NSEveryone")
        rect = frame
        s = icon.size()
        p = NSMakePoint(
            NSWidth(rect) - s.width - 8, rect.size.height - s.height - 8)
        r = NSMakeRect(0, 0, s.width, s.height)
        icon.drawAtPoint_fromRect_operation_fraction_(p, r,
                                                      NSCompositeSourceOver,
                                                      0.5)

        image.unlockFocus()
        return image
Exemplo n.º 44
0
    def handle_tlv(self, tlvs):
        self.statusText.setTextColor_(NSColor.blackColor())
        if tlvs:
            fingerprint = self.ctx.getCurrentKey()
            is1qtlv = self.get_tlv(tlvs, potr.proto.SMP1QTLV)
            # check for TLV_SMP_ABORT or state = CHEATED
            if self.smp_running and not self.ctx.smpIsValid():
                self.statusText.setTextColor_(NSColor.redColor())
                self.statusText.setStringValue_('Verification failed. You may try again later.')
                self._finish()

            # check for TLV_SMP1
            elif self.get_tlv(tlvs, potr.proto.SMP1TLV):
                self.statusText.setStringValue_('Verification request received')
                self.smp_running = True
                self.question = None
                self.show(True)
                self.progressBar.setIndeterminate_(False)
                self.progressBar.setDoubleValue_(3)

            # check for TLV_SMP1Q
            elif is1qtlv:
                self.smp_running = True
                self.question = is1qtlv.msg
                self.show(True)
                self.progressBar.setIndeterminate_(False)
                self.progressBar.setDoubleValue_(3)

            # check for TLV_SMP2
            elif self.get_tlv(tlvs, potr.proto.SMP2TLV):
                self.progressBar.setIndeterminate_(False)
                self.progressBar.setDoubleValue_(6)
                self.statusText.setStringValue_('Verification in progress...')

            # check for TLV_SMP3
            elif self.get_tlv(tlvs, potr.proto.SMP3TLV):
                if self.ctx.smpIsSuccess():
                    self.statusText.setTextColor_(NSColor.greenColor())
                    self.statusText.setStringValue_('Verification succeeded')
                    if fingerprint:
                        self.chatController.otr_account.setTrust(self.chatController.sessionController.remoteSIPAddress, str(fingerprint), 'verified')
                        self.chatController.chatWindowController.revalidateToolbar()
                        self.chatController.updateEncryptionWidgets()
                    self._finish()
                else:
                    self.statusText.setTextColor_(NSColor.redColor())
                    self.statusText.setStringValue_('Verification failed. You may try again later.')
                    self._finish()

            # check for TLV_SMP4
            elif self.get_tlv(tlvs, potr.proto.SMP4TLV):
                if self.ctx.smpIsSuccess():
                    self.statusText.setTextColor_(NSColor.greenColor())
                    self.statusText.setStringValue_('Verification succeeded')
                    if fingerprint:
                        self.chatController.otr_account.setTrust(self.chatController.sessionController.remoteSIPAddress, str(fingerprint), 'verified')
                        self.chatController.chatWindowController.revalidateToolbar()
                        self.chatController.updateEncryptionWidgets()
                    self._finish()
                else:
                    self.statusText.setTextColor_(NSColor.redColor())
                    self.statusText.setStringValue_('Verification failed. You may try again later.')
                    self._finish()
Exemplo n.º 45
0
    def importButtonClicked_(self, sender):
        BlinkLogger().log_info("Import private key")
        pincode = str(self.pincode.stringValue()).strip()
        data = self.encryptedKeyPair.decode()
        keyPair = self.decrypt(data, pincode)

        try:
            keyPair = keyPair.decode()
        except UnicodeDecodeError as e:
            self.status.setTextColor_(NSColor.redColor())
            BlinkLogger().log_error("Import private key failed: %s" % str(e))
            self.status.setStringValue_(
                NSLocalizedString("Key import failed", "status label"))
        else:
            public_key_checksum_match = re.findall(
                r"--PUBLIC KEY SHA1 CHECKSUM--(\w+)--", keyPair)
            private_key_checksum_match = re.findall(
                r"--PRIVATE KEY SHA1 CHECKSUM--(\w+)--", keyPair)

            if (public_key_checksum_match):
                public_key_checksum = public_key_checksum_match[0]
            else:
                public_key_checksum = None

            if (private_key_checksum_match):
                private_key_checksum = private_key_checksum_match[0]
            else:
                private_key_checksum = None

            public_key = ''
            private_key = ''

            start_public = False
            start_private = False

            for l in keyPair.split("\n"):
                if l == "-----BEGIN RSA PUBLIC KEY-----":
                    start_public = True
                    start_private = False

                if l == "-----END RSA PUBLIC KEY-----":
                    public_key = public_key + l
                    start_public = False
                    start_private = False

                if l == "-----BEGIN RSA PRIVATE KEY-----":
                    start_public = False
                    start_private = True

                if l == "-----END RSA PRIVATE KEY-----":
                    private_key = private_key + l
                    start_public = False
                    start_private = False

                if start_public:
                    public_key = public_key + l + '\n'

                if start_private:
                    private_key = private_key + l + '\n'

            if (public_key and private_key and public_key_checksum):
                self.importButton.setEnabled_(False)
                BlinkLogger().log_info("Key imported sucessfully")
                self.status.setTextColor_(NSColor.greenColor())
                self.status.setStringValue_(
                    NSLocalizedString("Key imported sucessfully",
                                      "status label"))
                self.checksum.setStringValue_(public_key_checksum)

                self.account.sms.private_key = private_key
                self.account.sms.public_key = public_key
                self.account.sms.public_key_checksum = public_key_checksum
                self.account.save()

                if self.dealloc_timer is None:
                    self.dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
                        6.0, self, "deallocTimer:", None, True)
                    NSRunLoop.currentRunLoop().addTimer_forMode_(
                        self.dealloc_timer, NSRunLoopCommonModes)
                    NSRunLoop.currentRunLoop().addTimer_forMode_(
                        self.dealloc_timer, NSEventTrackingRunLoopMode)

            else:
                BlinkLogger().log_error("Key import failed")
                self.status.setStringValue_(
                    NSLocalizedString("Key import failed", "status label"))
                self.status.setTextColor_(NSColor.redColor())
Exemplo n.º 46
0
    def updateButtons(self):
        for button in (self.holdButton, self.hangupButton, self.chatButton, self.infoButton, self.muteButton, self.aspectButton, self.contactsButton, self.fullscreenButton, self.myvideoButton, self.pauseButton):

            lightGrayTitle = NSAttributedString.alloc().initWithString_attributes_(button.label(), NSDictionary.dictionaryWithObject_forKey_(NSColor.lightGrayColor(), NSForegroundColorAttributeName))
            button.setLabel_(lightGrayTitle)
Exemplo n.º 47
0
    def drawRect_(self, rect):
        rect = NSInsetRect(self.bounds(), 1.5, 1.5)
        if not self.conferencing:
            NSColor.whiteColor().set()
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
            path.fill()

        if self.conferencing:
            if self.draggedOut:
                NSColor.whiteColor().set()
            else:
                # bgcolor for conference area
                NSColor.colorWithDeviceRed_green_blue_alpha_(196/255.0, 230/255.0, 254/255.0, 1.0).set()
            border = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
            border.setLineWidth_(1)
            border.fill()
            NSColor.grayColor().set()
            border.stroke()

            # hack: if we're the 1st item, draw the border around all conferenced boxes
            subviews = self.superview().subviews()
            if subviews.objectAtIndex_(0) == self:
                # first in conference list
                rect.size.height += 5
                rect.origin.y -= 5
                path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
            else:
                prev = None
                last = True
                for view in subviews:
                    if prev == self:
                        last = not view.conferencing
                        break
                    prev = view
                # last in conference list
                if last:
                    rect.size.height += 5
                    path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
                else:
                    rect.origin.y -= 5
                    rect.size.height += 10
                    path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)

            if self.selected or self.highlighted:
                path.setLineWidth_(3)
            else:
                path.setLineWidth_(1)
            if self.highlighted:
                NSColor.orangeColor().set()
            else:
                NSColor.grayColor().set()
            if self.selected or self.highlighted:
                path.stroke()
        elif self.highlighted:
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
            path.setLineWidth_(3)
            NSColor.orangeColor().set()
            path.stroke()
        elif self.selected:
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
            path.setLineWidth_(3)
            NSColor.grayColor().set()
            path.stroke()
        else:
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
            path.setLineWidth_(1)
            NSColor.grayColor().set()
            path.stroke()
Exemplo n.º 48
0
 def drawRect_(self, rect):
     gradient = NSGradient.alloc().initWithColors_(
                 [NSColor.colorWithDeviceRed_green_blue_alpha_(121/256.0, 121/256.0, 121/256.0, 1),
                  NSColor.colorWithDeviceRed_green_blue_alpha_(111/256.0, 111/256.0, 111/256.0, 1)])
     gradient.drawInRect_angle_(rect, 90.0)
     NSView.drawRect_(self, rect)
Exemplo n.º 49
0
    def drawPresenceIcon(self):
        status = 'offline'
        if type(self.contact) is BlinkMyselfConferenceContact:
            account = self.contact.account
            if account.enabled and account.presence.enabled:
                settings = SIPSimpleSettings()
                status = settings.presence_state.status.lower()
        elif type(self.contact) is BlinkConferenceContact:
            blink_contact = self.contact.presence_contact
            if type(blink_contact) is not BlinkPresenceContact:
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is BlinkHistoryViewerContact:
            blink_contact = self.contact.presence_contact
            if type(blink_contact) is not BlinkPresenceContact:
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)

        elif type(self.contact) is HistoryBlinkContact:
            blink_contact = self.contact.contact
            if type(blink_contact) is not BlinkPresenceContact:
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif isinstance(self.contact, BlinkPresenceContact):
            blink_contact = self.contact
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is BonjourBlinkContact:
            account = BonjourAccount()
            if not account.presence.enabled:
                return
            blink_contact = self.contact
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is SystemAddressBookBlinkContact:
            return
        elif type(self.contact) is LdapSearchResultContact:
            return
        elif type(self.contact) is SearchResultContact:
            return

        if not status:
            return
        try:
            icon = presence_status_icons[status]
        except KeyError:
            pass

        has_locations = None
        if type(self.contact) is BlinkPresenceContact:
            try:
                has_locations = any(device['location'] for device in self.contact.presence_state['devices'].values() if device['location'] is not None)
            except KeyError:
                pass

        frame = self.frame
        frame.origin.y -= 17
        if has_locations:
            left = self.view.frame().size.width - 22
            self.drawIcon(self.locationIcon, left, self.frame.origin.y +14, 16, 16)

        # presence bar
        frame.size.width = 5
        if type(self.contact) in (BlinkConferenceContact, BlinkMyselfConferenceContact):
            frame.size.height = 14
            frame.origin.y += 15
        frame.origin.x = self.view.frame().size.width - 6

        rect = NSInsetRect(frame, 0, 0)

        if status == 'available':
            NSColor.greenColor().set()
        elif status == 'away':
            NSColor.yellowColor().set()
        elif status == 'busy':
            NSColor.redColor().set()
        else:
            NSColor.whiteColor().set()

        border = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 2.0, 2.0)
        border.setLineWidth_(0.08)
        border.fill()
        NSColor.blackColor().set()
        border.stroke()
Exemplo n.º 50
0
    def drawRect_(self, rect):
        r = self.bounds()
        r.size.width -= 0.5
        r.size.height += 4
        if self.draggedOut:
            NSColor.colorWithDeviceWhite_alpha_(0.4, 1.0).set()
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                r, 5, 5)
            path.fill()
        else:
            if self == self.switcher.activeItem():
                NSColor.controlColor().set()
            else:
                NSColor.colorWithDeviceWhite_alpha_(0.6, 1.0).set()
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                r, 5, 5)
            path.fill()
            NSColor.colorWithDeviceRed_green_blue_alpha_(0.3, 0.3, 0.3,
                                                         1.0).set()
            path.stroke()

        if self.badgeLabel and not self.mouseInside and not self.busyIndicator and not self.composing:
            # draw the number in redbadge indicator
            gradient = NSGradient.alloc().initWithStartingColor_endingColor_(
                NSColor.colorWithDeviceRed_green_blue_alpha_(0.9, 0.2, 0.2, 1),
                NSColor.colorWithDeviceRed_green_blue_alpha_(1.0, 0.2, 0.2, 1))
            size = self.badgeLabel.size()
            size.width += 4
            if size.width < 12:
                size.width = 12
            bez = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
                NSMakeRect(3, 5, size.width, 12), 6, 6)
            gradient.drawInBezierPath_angle_(bez, 90 + 45)
            self.badgeLabel.drawInRect_(NSMakeRect(3, 5, size.width, 12))

        if not self.mouseInside and not self.busyIndicator and self.composing:
            rect = NSZeroRect.copy()
            rect.size = self.composeIcon.size()
            self.composeIcon.drawAtPoint_fromRect_operation_fraction_(
                NSMakePoint(1, 3), rect, NSCompositeSourceOver, 1)

        if not self.busyIndicator and self.screen_sharing_active:
            rect = NSZeroRect.copy()
            rect.size = self.screenIcon.size()
            self.screenIcon.drawAtPoint_fromRect_operation_fraction_(
                NSMakePoint(17, 3), rect, NSCompositeSourceOver, 1)

        if not self.draggedOut:
            shadow = NSShadow.alloc().init()
            shadow.setShadowOffset_(NSMakeSize(0, -1))
            if self == self.switcher.activeItem():
                shadow.setShadowColor_(NSColor.whiteColor())
            else:
                shadow.setShadowColor_(
                    NSColor.colorWithDeviceWhite_alpha_(0.7, 1.0))
            para = NSParagraphStyle.defaultParagraphStyle().mutableCopy()
            para.setLineBreakMode_(NSLineBreakByTruncatingTail)
            para.setAlignment_(NSCenterTextAlignment)
            attribs = NSDictionary.dictionaryWithObjectsAndKeys_(
                NSFont.systemFontOfSize_(11), NSFontAttributeName, shadow,
                NSShadowAttributeName, para, NSParagraphStyleAttributeName)

            rect = self.bounds()
            rect.origin.y -= 3
            rect.origin.x += 20
            rect.origin.x = rect.origin.x + 12 if self.screen_sharing_active else rect.origin.x
            rect.size.width -= 46
            rect.size.width = rect.size.width - 12 if self.screen_sharing_active else rect.size.width
            self.label.drawInRect_withAttributes_(rect, attribs)
Exemplo n.º 51
0
    def drawRect_(self, rect):
        r = self.bounds()
        r.size.width -= 0.5
        r.size.height += 4
        if self.draggedOut:
            NSColor.colorWithDeviceWhite_alpha_(0.4, 1.0).set()
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(r, 5, 5)
            path.fill()
        else:
            if self == self.switcher.activeItem():
                NSColor.controlColor().set()
            else:
                NSColor.colorWithDeviceWhite_alpha_(0.6, 1.0).set()
            path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(r, 5, 5)
            path.fill()
            NSColor.colorWithDeviceRed_green_blue_alpha_(0.3, 0.3, 0.3, 1.0).set()
            path.stroke()

        if self.badgeLabel and not self.mouseInside and not self.busyIndicator and not self.composing:
            # draw the number in redbadge indicator
            gradient = NSGradient.alloc().initWithStartingColor_endingColor_(
                          NSColor.colorWithDeviceRed_green_blue_alpha_(0.9, 0.2, 0.2, 1),
                          NSColor.colorWithDeviceRed_green_blue_alpha_(1.0, 0.2, 0.2, 1))
            size = self.badgeLabel.size()
            size.width += 4
            if size.width < 12:
                size.width = 12
            bez = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(NSMakeRect(3, 5, size.width, 12), 6, 6)
            gradient.drawInBezierPath_angle_(bez, 90+45)
            self.badgeLabel.drawInRect_(NSMakeRect(3, 5, size.width, 12))

        if not self.mouseInside and not self.busyIndicator and self.composing:
            rect = NSZeroRect.copy()
            rect.size = self.composeIcon.size()
            self.composeIcon.drawAtPoint_fromRect_operation_fraction_(NSMakePoint(1, 3), rect, NSCompositeSourceOver, 1)

        if not self.busyIndicator and self.screen_sharing_active:
            rect = NSZeroRect.copy()
            rect.size = self.screenIcon.size()
            self.screenIcon.drawAtPoint_fromRect_operation_fraction_(NSMakePoint(17, 3), rect, NSCompositeSourceOver, 1)

        if not self.draggedOut:
            shadow = NSShadow.alloc().init()
            shadow.setShadowOffset_(NSMakeSize(0, -1))
            if self == self.switcher.activeItem():
                shadow.setShadowColor_(NSColor.whiteColor())
            else:
                shadow.setShadowColor_(NSColor.colorWithDeviceWhite_alpha_(0.7, 1.0))
            para = NSParagraphStyle.defaultParagraphStyle().mutableCopy()
            para.setLineBreakMode_(NSLineBreakByTruncatingTail)
            para.setAlignment_(NSCenterTextAlignment)
            attribs = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(11), NSFontAttributeName,
                            shadow, NSShadowAttributeName,
                            para, NSParagraphStyleAttributeName)

            rect = self.bounds()
            rect.origin.y -= 3
            rect.origin.x += 20
            rect.origin.x = rect.origin.x + 12 if self.screen_sharing_active else rect.origin.x
            rect.size.width -= 46
            rect.size.width = rect.size.width - 12 if self.screen_sharing_active else rect.size.width
            self.label.drawInRect_withAttributes_(rect, attribs)
Exemplo n.º 52
0
    def drawPresenceIcon(self):
        status = 'offline'
        if type(self.contact) is BlinkMyselfConferenceContact:
            account = self.contact.account
            if account.enabled and account.presence.enabled:
                settings = SIPSimpleSettings()
                status = settings.presence_state.status.lower()
        elif type(self.contact) is BlinkConferenceContact:
            blink_contact = self.contact.presence_contact
            if not isinstance(blink_contact, BlinkPresenceContact):
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is BlinkHistoryViewerContact:
            blink_contact = self.contact.presence_contact
            if not isinstance(blink_contact, BlinkPresenceContact):
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)

        elif type(self.contact) is HistoryBlinkContact:
            blink_contact = self.contact.contact
            if not isinstance(blink_contact, BlinkPresenceContact):
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif isinstance(self.contact, BlinkPresenceContact):
            blink_contact = self.contact
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is BonjourBlinkContact:
            account = BonjourAccount()
            if not account.presence.enabled:
                return
            blink_contact = self.contact
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is SystemAddressBookBlinkContact:
            return
        elif type(self.contact) is LdapSearchResultContact:
            return
        elif type(self.contact) is SearchResultContact:
            return

        if not status:
            return
        try:
            icon = presence_status_icons[status]
        except KeyError:
            pass

        has_locations = None
        if isinstance(self.contact,
                      (BlinkOnlineContact, BlinkPresenceContact)):
            try:
                has_locations = any(device['location'] for device in list(
                    self.contact.presence_state['devices'].values())
                                    if device['location'] is not None)
            except KeyError:
                pass

        frame = self.frame
        frame.origin.y -= 17
        #if has_locations:
        #    left = self.view.frame().size.width - 22
        #    self.drawIcon(self.locationIcon, left, self.frame.origin.y +14, 16, 16)

        # presence bar
        frame.size.width = 5
        if type(self.contact) in (BlinkConferenceContact,
                                  BlinkMyselfConferenceContact):
            frame.size.height = 14
            frame.origin.y += 15
        frame.origin.x = self.view.frame().size.width - 6

        rect = NSInsetRect(frame, 0, 0)

        if status == 'available':
            NSColor.greenColor().set()
        elif status == 'away':
            NSColor.yellowColor().set()
        elif status == 'busy':
            NSColor.redColor().set()
        else:
            NSColor.whiteColor().set()

        border = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
            rect, 2.0, 2.0)
        border.setLineWidth_(0.08)
        border.fill()
        NSColor.blackColor().set()
        border.stroke()

        # sleep icon
        if isinstance(self.contact,
                      (BlinkOnlineContact, BlinkPresenceContact)):
            if self.contact.presence_state['time_offset'] is not None:
                ctime = datetime.datetime.utcnow(
                ) + self.contact.presence_state['time_offset']
                hour = int(ctime.strftime("%H"))
                if hour > 21 or hour < 7:
                    left = self.view.frame().size.width - 26
                    self.drawIcon(self.nightIcon, left,
                                  self.frame.origin.y + 14, 16, 16)
Exemplo n.º 53
0
class ContactCell(NSTextFieldCell):
    contact = None
    view = None
    frame = None

    audioIcon = NSImage.imageNamed_("audio_16")
    audioHoldIcon = NSImage.imageNamed_("paused_16")
    chatIcon = NSImage.imageNamed_("pencil_16")
    screenIcon = NSImage.imageNamed_("display_16")
    locationIcon = NSImage.imageNamed_("location")
    nightIcon = NSImage.imageNamed_("moon")

    style = NSParagraphStyle.defaultParagraphStyle().mutableCopy()
    style.setLineBreakMode_(NSLineBreakByTruncatingTail)
    firstLineAttributes = NSDictionary.dictionaryWithObjectsAndKeys_(
        NSFont.systemFontOfSize_(12.0), NSFontAttributeName, style,
        NSParagraphStyleAttributeName)
    firstLineAttributes_highlighted = NSDictionary.dictionaryWithObjectsAndKeys_(
        NSFont.systemFontOfSize_(12.0), NSFontAttributeName,
        NSColor.whiteColor(), NSForegroundColorAttributeName, style,
        NSParagraphStyleAttributeName)
    secondLineAttributes = NSDictionary.dictionaryWithObjectsAndKeys_(
        NSFont.systemFontOfSize_(NSFont.labelFontSize() - 1),
        NSFontAttributeName, NSColor.grayColor(),
        NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName)
    secondLineAttributes_highlighted = NSDictionary.dictionaryWithObjectsAndKeys_(
        NSFont.systemFontOfSize_(NSFont.labelFontSize() - 1),
        NSFontAttributeName, NSColor.whiteColor(),
        NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName)

    def setContact_(self, contact):
        self.contact = contact

    def setMessageIcon_(self, icon):
        self.messageIcon = icon

    def drawingRectForBounds_(self, rect):
        return rect

    def cellSize(self):
        if self.contact is None:
            return objc.super(ContactCell, self).cellSize()
        return NSMakeSize(100, 30)

    def drawWithFrame_inView_(self, frame, view):
        if self.contact is None:
            return objc.super(ContactCell,
                              self).drawWithFrame_inView_(frame, view)

        self.frame = frame
        self.view = view

        try:
            icon = self.contact.avatar.icon
            self.drawIcon(icon, 2, self.frame.origin.y + 3, 28, 28)

            self.drawActiveMedia()
            self.drawFirstLine()
            self.drawSecondLine()
            self.drawPresenceIcon()
        except Exception:
            pass

    @objc.python_method
    def drawFirstLine(self):
        frame = self.frame
        frame.origin.x = 35
        frame.origin.y += 2

        rect = NSMakeRect(frame.origin.x, frame.origin.y,
                          frame.size.width - 10, frame.size.height)
        attrs = self.firstLineAttributes if not self.isHighlighted(
        ) else self.firstLineAttributes_highlighted
        self.stringValue().drawInRect_withAttributes_(rect, attrs)

    @objc.python_method
    def drawSecondLine(self):
        frame = self.frame
        frame.origin.y += 15
        if self.contact.detail:
            rect = NSMakeRect(frame.origin.x, frame.origin.y,
                              frame.size.width - 25, frame.size.height)
            attrs = self.secondLineAttributes if not self.isHighlighted(
            ) else self.secondLineAttributes_highlighted
            self.contact.detail.drawInRect_withAttributes_(rect, attrs)

    @objc.python_method
    def drawActiveMedia(self):
        if type(self.contact) not in (BlinkConferenceContact,
                                      BlinkMyselfConferenceContact):
            return

        padding = 16
        left = self.frame.size.width - 8
        if 'audio-onhold' in self.contact.active_media:
            left = left - padding
            self.drawIcon(self.audioHoldIcon, left, self.frame.origin.y + 14,
                          16, 16)
        elif 'audio' in self.contact.active_media:
            left = left - padding
            self.drawIcon(self.audioIcon, left, self.frame.origin.y + 14, 16,
                          16)

        if 'message' in self.contact.active_media:
            left = left - padding
            self.drawIcon(self.chatIcon, left, self.frame.origin.y + 14, 16,
                          16)

        if 'screen' in self.contact.active_media:
            left = left - padding - 2
            self.drawIcon(self.screenIcon, left, self.frame.origin.y + 14, 16,
                          16)

    @objc.python_method
    def drawPresenceIcon(self):
        status = 'offline'
        if type(self.contact) is BlinkMyselfConferenceContact:
            account = self.contact.account
            if account.enabled and account.presence.enabled:
                settings = SIPSimpleSettings()
                status = settings.presence_state.status.lower()
        elif type(self.contact) is BlinkConferenceContact:
            blink_contact = self.contact.presence_contact
            if not isinstance(blink_contact, BlinkPresenceContact):
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is BlinkHistoryViewerContact:
            blink_contact = self.contact.presence_contact
            if not isinstance(blink_contact, BlinkPresenceContact):
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)

        elif type(self.contact) is HistoryBlinkContact:
            blink_contact = self.contact.contact
            if not isinstance(blink_contact, BlinkPresenceContact):
                return
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif isinstance(self.contact, BlinkPresenceContact):
            blink_contact = self.contact
            if not blink_contact.contact.presence.subscribe:
                return
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is BonjourBlinkContact:
            account = BonjourAccount()
            if not account.presence.enabled:
                return
            blink_contact = self.contact
            status = presence_status_for_contact(blink_contact)
        elif type(self.contact) is SystemAddressBookBlinkContact:
            return
        elif type(self.contact) is LdapSearchResultContact:
            return
        elif type(self.contact) is SearchResultContact:
            return

        if not status:
            return
        try:
            icon = presence_status_icons[status]
        except KeyError:
            pass

        has_locations = None
        if isinstance(self.contact,
                      (BlinkOnlineContact, BlinkPresenceContact)):
            try:
                has_locations = any(device['location'] for device in list(
                    self.contact.presence_state['devices'].values())
                                    if device['location'] is not None)
            except KeyError:
                pass

        frame = self.frame
        frame.origin.y -= 17
        #if has_locations:
        #    left = self.view.frame().size.width - 22
        #    self.drawIcon(self.locationIcon, left, self.frame.origin.y +14, 16, 16)

        # presence bar
        frame.size.width = 5
        if type(self.contact) in (BlinkConferenceContact,
                                  BlinkMyselfConferenceContact):
            frame.size.height = 14
            frame.origin.y += 15
        frame.origin.x = self.view.frame().size.width - 6

        rect = NSInsetRect(frame, 0, 0)

        if status == 'available':
            NSColor.greenColor().set()
        elif status == 'away':
            NSColor.yellowColor().set()
        elif status == 'busy':
            NSColor.redColor().set()
        else:
            NSColor.whiteColor().set()

        border = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
            rect, 2.0, 2.0)
        border.setLineWidth_(0.08)
        border.fill()
        NSColor.blackColor().set()
        border.stroke()

        # sleep icon
        if isinstance(self.contact,
                      (BlinkOnlineContact, BlinkPresenceContact)):
            if self.contact.presence_state['time_offset'] is not None:
                ctime = datetime.datetime.utcnow(
                ) + self.contact.presence_state['time_offset']
                hour = int(ctime.strftime("%H"))
                if hour > 21 or hour < 7:
                    left = self.view.frame().size.width - 26
                    self.drawIcon(self.nightIcon, left,
                                  self.frame.origin.y + 14, 16, 16)

    @objc.python_method
    def drawIcon(self, icon, origin_x, origin_y, size_x, size_y):
        size = icon.size()
        if not size or not size.height:
            return
        rect = NSMakeRect(0, 0, size.width, size.height)
        trect = NSMakeRect(origin_x, origin_y,
                           (size_y / size.height) * size.width, size_x)
        icon.drawInRect_fromRect_operation_fraction_respectFlipped_hints_(
            trect, rect, NSCompositeSourceOver, 1.0, True, None)
Exemplo n.º 54
0
    def __init__(self, sessionController):

        self.notification_center = NotificationCenter()
        self.notification_center.add_observer(
            self, name='CFGSettingsObjectDidChange')

        self.sessionController = None
        self.audio_stream = None
        self.video_stream = None
        self.chat_stream = None

        self.add_session(sessionController)
        self.add_audio_stream()
        self.add_video_stream()
        self.add_chat_stream()

        self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
            1.0, self, "updateTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer,
                                                     NSModalPanelRunLoopMode)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer,
                                                     NSDefaultRunLoopMode)
        NSBundle.loadNibNamed_owner_("SessionInfoPanel", self)

        sessionBoxTitle = NSAttributedString.alloc(
        ).initWithString_attributes_(
            NSLocalizedString("SIP Session", "Label"),
            NSDictionary.dictionaryWithObject_forKey_(
                NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.sessionBox.setTitle_(sessionBoxTitle)

        audioBoxTitle = NSAttributedString.alloc().initWithString_attributes_(
            NSLocalizedString("Audio Stream", "Label"),
            NSDictionary.dictionaryWithObject_forKey_(
                NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.audioBox.setTitle_(audioBoxTitle)

        videoBoxTitle = NSAttributedString.alloc().initWithString_attributes_(
            NSLocalizedString("Video Stream", "Label"),
            NSDictionary.dictionaryWithObject_forKey_(
                NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.videoBox.setTitle_(videoBoxTitle)

        chatBoxTitle = NSAttributedString.alloc().initWithString_attributes_(
            NSLocalizedString("Chat Stream", "Label"),
            NSDictionary.dictionaryWithObject_forKey_(
                NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.chatBox.setTitle_(chatBoxTitle)

        settings = SIPSimpleSettings()

        self.audio_rtt_graph.setLineWidth_(1.0)
        self.audio_rtt_graph.setLineSpacing_(1.0)
        self.audio_rtt_graph.setAboveLimit_(
            settings.gui.rtt_threshold)  # if higher show red color
        self.audio_rtt_graph.setMinimumHeigth_(settings.gui.rtt_threshold)

        self.audio_packet_loss_rx_graph.setLineWidth_(1.0)
        self.audio_packet_loss_rx_graph.setLineSpacing_(1.0)
        self.audio_packet_loss_rx_graph.setAboveLimit_(
            3)  # if higher than 3% show red color
        self.audio_packet_loss_rx_graph.setLineColor_(NSColor.greenColor())
        self.audio_packet_loss_rx_graph.setMinimumHeigth_(5)

        self.audio_packet_loss_tx_graph.setLineWidth_(1.0)
        self.audio_packet_loss_tx_graph.setLineSpacing_(1.0)
        self.audio_packet_loss_tx_graph.setAboveLimit_(
            3)  # if higher than 3% show red color
        self.audio_packet_loss_tx_graph.setLineColor_(NSColor.greenColor())
        self.audio_packet_loss_tx_graph.setMinimumHeigth_(5)

        self.rx_speed_graph.setLineWidth_(1.0)
        self.rx_speed_graph.setLineSpacing_(0.0)
        self.rx_speed_graph.setLineColor_(NSColor.greenColor())
        self.rx_speed_graph.setMinimumHeigth_(100000)
        self.rx_speed_graph.setAboveLimit_(120000)

        self.tx_speed_graph.setLineWidth_(1.0)
        self.tx_speed_graph.setLineSpacing_(0.0)
        self.tx_speed_graph.setLineColor_(NSColor.blueColor())
        self.tx_speed_graph.setMinimumHeigth_(100000)
        self.tx_speed_graph.setAboveLimit_(120000)

        self.video_rx_speed_graph.setLineWidth_(1.0)
        self.video_rx_speed_graph.setLineSpacing_(0.0)
        self.video_rx_speed_graph.setLineColor_(NSColor.greenColor())
        self.video_rx_speed_graph.setMinimumHeigth_(100000)
        self.video_rx_speed_graph.setAboveLimit_(99999999)

        self.video_tx_speed_graph.setLineWidth_(1.0)
        self.video_tx_speed_graph.setLineSpacing_(0.0)
        self.video_tx_speed_graph.setLineColor_(NSColor.blueColor())
        self.video_tx_speed_graph.setMinimumHeigth_(100000)
        self.video_tx_speed_graph.setAboveLimit_(99999999)

        self.resetSession()
        self.updatePanelValues()