mh taqia mh taqia - 5 months ago 44
Objective-C Question

Programmatically obtain font name of selected text in TextEdit

After trying for two months I find out how to obtain AttributedString from any text range of TextEdit (or any NSTextView). my code is as:

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement,
kAXFocusedUIElementAttribute, (CFTypeRef*)&focussedElement);
if (error != kAXErrorSuccess) {
println("Could not get focussed element");
}
else {
AXValueRef selectedRangeValue = NULL;
AXError getSelectedRangeError =
AXUIElementCopyAttributeValue(focussedElement,
kAXSelectedTextRangeAttribute, (CFTypeRef*)&selectedRangeValue);
if (getSelectedRangeError == kAXErrorSuccess) {
CFRange selectedRange;
AXValueGetValue(selectedRangeValue, kAXValueCFRangeType,
&selectedRange);
AXValueRef attributedString = NULL;
AXError getAttrStrError =
AXUIElementCopyParameterizedAttributeValue(focussedElement,
kAXAttributedStringForRangeParameterizedAttribute, selectedRangeValue,
(CFTypeRef*)&attributedString);
CFRelease(selectedRangeValue);

if (getAttrStrError == kAXErrorSuccess)
{
CFAttributedStringRef attrStr = (CFAttributedStringRef)attributedString;

CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);

println("value: %X", value); // value is not NULL, but I can't obtain font name from it.

CFRelease(attributedString);
}
else
{
println("Could not get attributed string for selected range");
}
}
else {
println("Could not get selected range");
}
}
if (focussedElement != NULL)
CFRelease(focussedElement);
CFRelease(systemWideElement);


I properly obtained CFAttributedStringRef (I can get length or plain text from it), but I can not obtain font name.

Note:

the value returned form below code is not NULL:

CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);


The value can not be assumed as CTFontRef or CGFontRef, ATSFontRef, ... (causes exception).

Also I try kCTFontAttributeName instead kAXFontTextAttribute, but returns NULL.

Thanks a lot.

Answer

The value associated with the key kAXFontTextAttribute seems to be a CFDictionaryRef. See AXTextAttributedString documentation.

Comments