iosswiftmacosnstextviewnsparagraphstyle

NSTextView is too slow to update while changing the attributes with different NSParagraphStyles


I want NSTextView object to react to Tab key hit by changing NSParagraphStyle spacing. And it does but EXTREMELY slow!!! In fact if I do this changes too quick (hit Tab key too fast), I eventually got glitches that sometimes even lead to crash. Here's the video: https://drive.google.com/open?id=0B4aMQXnlIOvCUXNjWTVXVkR3NHc. And another one: https://drive.google.com/open?id=0B4aMQXnlIOvCUDJjSEN0bFdqQXc

Fragment of code from my NSTextStorage subclass:

override func attributesAtIndex(index: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] {
    return storage.attributesAtIndex(index, effectiveRange: range)
}


override func replaceCharactersInRange(range: NSRange, withString str: String) {
    let delta = str.characters.count - range.length
    beginEditing()
    storage.replaceCharactersInRange(range, withString:str)
    edited([.EditedCharacters, .EditedAttributes], range: range, changeInLength: delta)
    endEditing()
}


override func setAttributes(attrs: [String : AnyObject]!, range: NSRange) {
    beginEditing()
    storage.setAttributes(attrs, range: range)
    edited(.EditedAttributes, range: range, changeInLength: 0)
    endEditing()
}

Fragment of code from my NSTextView subclass:

override func shouldChangeTextInRange(affectedCharRange: NSRange, replacementString: String?) -> Bool {
    super.shouldChangeTextInRange(affectedCharRange, replacementString: replacementString)
    guard replacementString != nil else { return true }

    if replacementString == "\t" {
        defer {
            let selectedRangesValues = self.selectedRanges
            var selectedRanges = [NSRange]()
            for value in selectedRangesValues {
                selectedRanges.append(value.rangeValue)
            }
            textController.switchToAltAttributesInRange(selectedRanges)
        }
        return false
    }
    return true
}

Fragment of code from my TextController which creates and applies alternative attributes:

func switchToAltAttributesInRange(ranges : [NSRange]) {
    // get paragraph indexes from the ranges
    var indexes = [Int]()
    for range in ranges {
        for idx in textStorage.paragraphsInRange(range) {
            indexes.append(idx)
        }
    }

    // change attributes for all the paragraphs in those ranges
    for index in indexes {
        let paragraphRange = textStorage.paragraphRangeAtIndex(index)
        let element = elementAtIndex(index)
        let altElementType = altElementTypeForElementType(element.type)

        // change the attributes
        let newAttributes = paragraphAttributesForElement(type: altElementType.rawValue)
        self.textStorage.beginUpdates()
        self.textStorage.setAttributes(newAttributes, range: paragraphRange)
        self.textStorage.endUpdates()
    }
}

func paragraphAttributesForElement(type typeString: String) -> [String : AnyObject] {
    let elementPreset = elementPresetForType(elementType)

    // set font
    let font = NSFont (name: elementPreset.font, size: CGFloat(elementPreset.fontSize))!

    // set attributes
    let elementAttributes = [NSFontAttributeName: font,
                  NSParagraphStyleAttributeName : paragraphStyleForElementPreset(elementPreset, font: font),
                  NSForegroundColorAttributeName: NSColor.colorFromHexValue(elementPreset.color),
                  NSUnderlineStyleAttributeName : elementPreset.underlineStyle,
              ElementAttribute.AllCaps.rawValue : elementPreset.allCaps]

    return elementAttributes
}

func paragraphStyleForElementPreset(elementPreset : TextElementPreset, font : NSFont) -> NSParagraphStyle {
    let sceneParagraphStyle = NSMutableParagraphStyle()

    let spacing = elementPreset.spacing
    let spacingBefore = elementPreset.spacingBefore
    let headIndent = elementPreset.headIndent
    let tailIndent = elementPreset.tailIndent

    let cFont = CTFontCreateWithName(font.fontName, font.pointSize, nil)
    let fontHeight = CTFontGetDescent(cFont) + CTFontGetAscent(cFont) + CTFontGetLeading(cFont)

    sceneParagraphStyle.paragraphSpacingBefore = CGFloat(spacingBefore)
    sceneParagraphStyle.paragraphSpacing = fontHeight * CGFloat(spacing)
    sceneParagraphStyle.headIndent = ScreenMetrics.pointsFromInches(CGFloat(headIndent))
    sceneParagraphStyle.tailIndent = ScreenMetrics.pointsFromInches(CGFloat(tailIndent))
    sceneParagraphStyle.firstLineHeadIndent = sceneParagraphStyle.headIndent
    sceneParagraphStyle.lineBreakMode = .ByWordWrapping
    return sceneParagraphStyle
}

Time Profiler instrument shows a high peak when I press the Tab key. It says that NSTextStorage attributesAtIndex takes up to 40 ms each time I press the Tab key.

I checked: if I remove NSParagraphStyle changes, everything becomes normal. So the question is: how should I update paragraph styles?


Solution

  • Hmm... Didn't found such a solution neither in Apple docs or in Google... Just have experimented and turns out if I add textView.display() after call of self.textStorage.setAttributes, everything works fine!

    UPDATE: setNeedsDisplay(invalidRect) does a much better job because you might redraw just a dirty portion of text view's visible rect