[Pyobjc-dev] Re: [Pythonmac-SIG] pyobjc / cocoa
Michael J. Barber
mjb@uma.pt
Fri, 18 Oct 2002 16:09:33 +0100
On Wednesday, October 16, 2002, at 04:25 PM, Jack Jansen wrote:
> Something else that might be worthwhile is a helper command that
> translates ObjC calls to Python. You would then copy [obj setObject:
> value forKey: key], paste it in your Python script (where it will stay
> selected) and select the "ObjC methodcall to Python" command to turn it
> into obj.setObjectForKey(value, key). The only question is how we could
> get this into Project Builder (into the Python IDE would be easy).
Sounds like a nice thing to do as a service or as a script. Getting it
into Project Builder is then automatic.
Since I don't know how to write a service, I wrote a basic AppleScript
for that. And I do mean basic: testing was minimal, nested method calls
aren't handled correctly, and string arguments containing ":" will cause
big problems. But, it's a starting point which someone might find
useful, and doing it correctly would basically require a mini-parser for
Objective-C, which there's no way I'm going to write in AppleScript! ;)
Might be quite nice done in Python using Plex, though.
If anyone is interested in using it, copy the Objective C method call
you want to convert, then run this script. The text will be converted to
a Pythonic method call on the clipboard, which you can paste as usual.
Be careful of spurious line breaks in the script when you first save it.
Here it is:
on run
-- get an Objective C message from the clipboard
set objcText to the clipboard
if objcText starts with "[" and objcText ends with "]" then
set objcText to items 2 through -2 of objcText as string
end if
set the tokens to split of the objcText at ":"
set objectName to the first word of the first item of the tokens
set methodName to {second word of the first item of the tokens}
set methodArgs to {}
repeat with tok in items 2 through -2 of tokens
set namePiece to the last word of the tok
copy namePiece to the end of the methodName
copy (items 1 through -(1 + (length of namePiece)) of tok as
string) to the end of methodArgs
end repeat
copy last item of tokens to the end of methodArgs
--return {tokens, objectName, methodName, methodArgs}
set the clipboard to objectName & "." & (join of methodName
by "_") & "(" & (join of methodArgs by ",") & ")"
end run
on split of str at delim
set oldTIDs to the text item delimiters of AppleScript
set the text item delimiters of AppleScript to delim
set tokens to the text items of the str
set the text item delimiters of AppleScript to oldTIDs
return the tokens
end split
on join of tokens by delim
set oldTIDs to the text item delimiters of AppleScript
set the text item delimiters of AppleScript to delim
set str to the tokens as string
set the text item delimiters of AppleScript to oldTIDs
return the str
end join