Example #1
0
    def new_cell_block(self):
        """A new CellBlock at the end of self.textView.textStorage()"""

        return CellBlock(
            NSMakeRange(self.textView.textStorage().length(),
                        0),  #len(self.input_prompt())),
            NSMakeRange(
                self.textView.textStorage().length(
                ),  # + len(self.input_prompt()),
                0))
Example #2
0
    def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(
            self, central, peripheral, advertisement_data, rssi):
        global player
        print "Found a Tile: identifier: ", peripheral.identifier()
        if peripheral.name() != 'Tile':
            return
        print "Found a Tile: identifier: ", peripheral.identifier()

        ad_data = advertisement_data.get(
            CBAdvertisementDataManufacturerDataKey, None)
        if ad_data != None:
            companyIDRange = NSMakeRange(0, 2)
            companyIdentifier = ad_data.getBytes_range_(None, companyIDRange)
            if (ord(companyIdentifier[0]) == 0x4C):
                # print "1. got compIdentifier 0x4C"
                dataTypeRange = NSMakeRange(2, 1)
                dataType = ad_data.getBytes_range_(None, dataTypeRange)
                if (ord(dataType) == 0x02):
                    # print "2. got dataType 0x02"
                    dataLengthRange = NSMakeRange(3, 1)
                    dataLength = ad_data.getBytes_range_(None, dataLengthRange)
                    #print "dataLength: %s" % ord(dataLength)
                    if (ord(dataLength) == 0x15):
                        # print "3. got dataLength 0x15"
                        uuidRange = NSMakeRange(4, 16)
                        ad_bytes = ad_data.getBytes_range_(None, uuidRange)
                        # print ad_bytes
                        proximityUUID = NSUUID.alloc().initWithUUIDBytes_(
                            ad_bytes)
                        print "proximityUUID: %s" % proximityUUID
                        # ^ uncomment this one to see beacons when you trigger them
                        #if str(proximityUUID) in approved_UUIDs:
                        if str(proximityUUID):
                            # Tile is in beacon mode; ie the button was
                            # double-clicked
                            #print "You clicked it.\n"
                            screen_status = Quartz.CGSessionCopyCurrentDictionary(
                            )
                            screen_locked = screen_status.get(
                                'CGSSessionScreenIsLocked', 0)
                            if screen_locked == 0:
                                self.screen_lock_time = time.time()
                                lock_player.play()
                                result = SACLockScreenImmediate()
                                time.sleep(2)
                                lock_player.stop()
                            else:
                                if time.time() - self.screen_lock_time > 10:
                                    warn_player.play()
                                    time.sleep(5)
                                    warn_player.stop()
Example #3
0
 def replace_current_block_with_string(self, textView, string):
     textView.replaceCharactersInRange_withString_(
         self.current_block_range().inputRange, string)
     self.current_block_range().inputRange.length = len(string)
     r = NSMakeRange(textView.textStorage().length(), 0)
     textView.scrollRangeToVisible_(r)
     textView.setSelectedRange_(r)
Example #4
0
    def render_pidf(self):
        if not self.contact:
            return
        has_locations = False
        status_label = ''
        if self.contact.presence_state['devices']:
            has_locations = any(device['location'] for device in list(self.contact.presence_state['devices'].values()) if device['location'] is not None)
            count = len(self.contact.presence_state['devices'])
            if count == 1:
                status_label = NSLocalizedString("One device available", "Label")
            elif count > 1:
                status_label = NSLocalizedString("%d devices available" % count, "Label")

        splitViewFrame = self.splitView.frame()
        mapViewFrame = self.mapViewSplitView.frame()
        pidfViewFrame = self.pidfView.frame()

        if has_locations:
            if mapViewFrame.size.height == 0:
                mapViewFrame.size.height = SPLITTER_HEIGHT
                self.mapViewSplitView.setFrame_(mapViewFrame)
                pidfViewFrame.size.height -= SPLITTER_HEIGHT
                self.pidfView.setFrame_(pidfViewFrame)
            self.mapView.setContact(self.contact)
            nr_countries = len(self.mapView.selectedCountries)
            if nr_countries == 1:
                status_label += NSLocalizedString(" in one country", "Label")
            elif nr_countries > 1:
                status_label +=  NSLocalizedString(" in %d countries" % nr_countries, "Label")
        else:
            mapViewFrame.size.height = 0
            self.mapViewSplitView.setFrame_(mapViewFrame)
            pidfViewFrame.size.height = splitViewFrame.size.height
            self.pidfView.setFrame_(pidfViewFrame)

        self.statusLabel.setStringValue_(status_label)

        text = ''
        for pidf in self.contact.pidfs:
            text += self.build_pidf_text(pidf) + '\n\n'

        if self.contact.presence_state['pending_authorizations']:
            text += "Pending authorizations:\n"

        pending_authorizations = self.contact.presence_state['pending_authorizations']
        for key in list(pending_authorizations.keys()):
            text += "    Subscription to %s from account %s\n" % (sip_prefix_pattern.sub('', key), pending_authorizations[key])

        self.presenceText.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.presenceText.textStorage().length()))
        astring = NSAttributedString.alloc().initWithString_(text)
        self.presenceText.textStorage().appendAttributedString_(astring)

        image = presence_status_for_contact(self.contact)
        if image:
            icon = NSImage.imageNamed_(image)
            icon.setScalesWhenResized_(True)
            icon.setSize_(NSMakeSize(12,12))
            self.presence_icon.setImage_(icon)
Example #5
0
 def render_error(self, failure):
     print failure
     blockID = failure.blockID
     inputRange = self.blockRanges[blockID].inputRange
     self.insert_text('\n' + self.output_prompt() + '\n' +
                      failure.getErrorMessage() + '\n\n',
                      textRange=NSMakeRange(
                          inputRange.location + inputRange.length, 0))
     self.start_new_block()
     return failure
Example #6
0
    def render_result(self, result):
        blockID = result['blockID']
        inputRange = self.blockRanges[blockID].inputRange
        del self.blockRanges[blockID]

        #print inputRange,self.current_block_range()
        self.insert_text('\n' + self.output_prompt(number=result['number']) +
                         result.get('display', {}).get('pprint', '') + '\n\n',
                         textRange=NSMakeRange(
                             inputRange.location + inputRange.length, 0))
        return result
    def calculateLines(self):
        view = self.clientView()
        if not isinstance(view, NSTextView):
            return

        text = view.string()
        textLength = text.length()

        if not textLength:
            self._lineIndices = [1]
            return

        lineIndices = []

        index = 0
        numberOfLines = 0
        while index < textLength:
            lineIndices.append(index)
            index = NSMaxRange(text.lineRangeForRange_(NSMakeRange(index, 0)))
            numberOfLines += 1

        lineStart, lineEnd, contentEnd = text.getLineStart_end_contentsEnd_forRange_(
            None, None, None, NSMakeRange(lineIndices[-1], 0))

        if contentEnd < lineEnd:
            lineIndices.append(index)

        self._lineIndices = lineIndices

        oldThickness = self.ruleThickness()
        newThickness = self.requiredThickness()

        if abs(oldThickness - newThickness) > 0:
            invocation = NSInvocation.invocationWithMethodSignature_(
                self.methodSignatureForSelector_("setRuleThickness:"))
            invocation.setSelector_("setRuleThickness:")
            invocation.setTarget_(self)
            invocation.setArgument_atIndex_(newThickness, 2)
            invocation.performSelector_withObject_afterDelay_(
                "invoke", None, 0)
Example #8
0
    def insert_text(self, string=None, textRange=None, scrollToVisible=True):
        """Insert text into textView at textRange, updating blockRanges 
        as necessary
        """
        if (textRange == None):
            #range for end of text
            textRange = NSMakeRange(self.textView.textStorage().length(), 0)

        self.textView.replaceCharactersInRange_withString_(textRange, string)

        for r in self.blockRanges.itervalues():
            r.update_ranges_for_insertion(string, textRange)

        self.textView.setSelectedRange_(textRange)
        if (scrollToVisible):
            self.textView.scrollRangeToVisible_(textRange)
 def readSelectionFromPasteboard_type_(self, pboard, type):
     self.owner.textWasPasted = True
     if self.maxLength:
         content = pboard.stringForType_(type)
         if content:
             if self.textStorage().length() - self.rangeForUserTextChange(
             ).length + len(content) > self.maxLength:
                 content = content.substringWithRange_(
                     NSMakeRange(
                         0, self.maxLength -
                         (self.textStorage().length() -
                          self.rangeForUserTextChange().length)))
             self.textStorage().replaceCharactersInRange_withString_(
                 self.rangeForUserTextChange(), content)
             self.didChangeText()
             return True
         return False
     else:
         return NSTextView.readSelectionFromPasteboard_type_(
             self, pboard, type)
Example #10
0
    def textView_doCommandBySelector_(self, textView, selector):
        assert (textView == self.textView)
        NSLog("textView_doCommandBySelector_: " + selector)

        if (selector == 'insertNewline:'):
            indent = self.current_indent_string()
            if (indent):
                line = indent + self.current_line()
            else:
                line = self.current_line()

            if (self.is_complete(self.current_block())):
                self.execute(self.current_block(), blockID=self.currentBlockID)
                self.start_new_block()

                return True

            return False

        elif (selector == 'moveUp:'):
            prevBlock = self.get_history_previous(self.current_block())
            if (prevBlock != None):
                self.replace_current_block_with_string(textView, prevBlock)
            else:
                NSBeep()
            return True

        elif (selector == 'moveDown:'):
            nextBlock = self.get_history_next()
            if (nextBlock != None):
                self.replace_current_block_with_string(textView, nextBlock)
            else:
                NSBeep()
            return True

        elif (selector == 'moveToBeginningOfParagraph:'):
            textView.setSelectedRange_(
                NSMakeRange(self.current_block_range().inputRange.location, 0))
            return True
        elif (selector == 'moveToEndOfParagraph:'):
            textView.setSelectedRange_(NSMakeRange(
                            self.current_block_range().inputRange.location + \
                            self.current_block_range().inputRange.length, 0))
            return True
        elif (selector == 'deleteToEndOfParagraph:'):
            if(textView.selectedRange().location <= \
                self.current_block_range().location):
                raise NotImplemented()

            return False  # don't actually handle the delete

        elif (selector == 'insertTab:'):
            if (len(self.current_line().strip()) == 0):  #only white space
                return False
            else:
                self.textView.complete_(self)
                return True

        elif (selector == 'deleteBackward:'):
            #if we're at the beginning of the current block, ignore
            if(textView.selectedRange().location == \
                self.current_block_range().inputRange.location):
                return True
            else:
                for r in self.blockRanges.itervalues():
                    deleteRange = textView.selectedRange
                    if (deleteRange.length == 0):
                        deleteRange.location -= 1
                        deleteRange.length = 1
                    r.update_ranges_for_deletion(deleteRange)
                return False
        return False
    def drawHashMarksAndLabelsInRect_(self, rect):
        bounds = self.bounds()
        view = self.clientView()

        rulerBackgroundColor = self.rulerBackgroundColor()
        if rulerBackgroundColor is not None:
            rulerBackgroundColor.set()
            NSRectFill(bounds)

        if not isinstance(view, NSTextView):
            return

        layoutManager = view.layoutManager()
        container = view.textContainer()
        text = view.string()
        nullRange = NSMakeRange(NSNotFound, 0)
        yinset = view.textContainerInset().height
        visibleRect = self.scrollView().contentView().bounds()
        textAttributes = self.textAttributes()

        lines = self.lineIndices()

        glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_(
            visibleRect, container)
        _range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_(
            glyphRange, None)[0]
        _range.length += 1

        count = len(lines)
        index = 0

        lineNumber = self.lineNumberForCharacterIndex_inText_(
            _range.location, text)

        for line in range(lineNumber, count):
            index = lines[line]
            if NSLocationInRange(index, _range):
                rects, rectCount = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_(
                    NSMakeRange(index, 0), nullRange, container, None)
                if rectCount > 0:
                    ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect)
                    labelText = NSString.stringWithString_("%s" % (line + 1))
                    stringSize = labelText.sizeWithAttributes_(textAttributes)

                    x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN
                    y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0
                    w = NSWidth(bounds) - self.RULER_MARGIN * 2.0
                    h = NSHeight(rects[0])

                    labelText.drawInRect_withAttributes_(
                        NSMakeRect(x, y, w, h), textAttributes)

            if index > NSMaxRange(_range):
                break

        path = NSBezierPath.bezierPath()
        path.moveToPoint_(
            (bounds.origin.x + bounds.size.width, bounds.origin.y))
        path.lineToPoint_((bounds.origin.x + bounds.size.width,
                           bounds.origin.y + bounds.size.height))
        NSColor.grayColor().set()
        path.stroke()