Reputation: 3596
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.
Upvotes: 0
Views: 590
Reputation: 253
This can be done by:
Define
NSFont *newFont;
Give a font that is default and then when the font manager opens, choose your selection and then create a button action and also its outlet
And then,
NSFont* oldFont = [NSFont fontWithName:@"Times" size:14];
NSFont* newFont;
newFont = [sender convertFont:oldFont];
NSLog(@">>>>>>>>>>>: %@", newFont.fontName);
Upvotes: 0
Reputation: 2590
The value associated with the key kAXFontTextAttribute
seems to be a CFDictionaryRef
. See AXTextAttributedString documentation.
Upvotes: 1