[Pythonmac-SIG] AE/PyObjC: how to use event loops to process AE

has hengist.podd at virgin.net
Wed May 10 19:41:32 CEST 2006


Daniel Lord wrote:

>A PyObjC application using Appkit starts and event loop in AppHelper
>thus:
>
>	AppHelper.runEventLoop()
>
>But, the examples I have seen using Apple Events in Python (not
>PyObjC) install their own handlers and then call the event loop:
>
>	CarbonEvt.RunApplicationEventLoop()
>
>Unfortunately and unsurprisingly, trying to inject the handlers from
>different methods in my PyObjC class inheriting from
>NibClassBuilder.AutoBaseClass and then expecting them to be called
>doesn't seem to work.

Makes no difference if your app uses a Carbon or Cocoa event loop. You should be able to install your own Apple event handlers without any problem. You can use NSAppleEventManager, aemreceive or Cocoa Scripting; even Carbon.AE if you want (although there's no real reason to do so). Examples:

1. Using NSAppleEventManager (you'll need to do your own packing and unpacking of event descriptors, mind):

from AppKit import *
from PyObjCTools import NibClassBuilder, AppHelper
import struct

NibClassBuilder.extractClasses('MainMenu.nib')

def aeKeyword(fourCharCode):
	return struct.unpack('L', fourCharCode)[0]


class MyAppDelegate(NibClassBuilder.AutoBaseClass):

	def applicationWillFinishLaunching_(self, aNotification):
		aem = NSAppleEventManager.sharedAppleEventManager()
		aem.setEventHandler_andSelector_forEventClass_andEventID_(
			self, 'someEvent:reply:', aeKeyword('Some'), aeKeyword('Evnt'))
	
	def someEvent_reply_(self, event, reply):
		result = NSAppleEventDescriptor.descriptorWithInt32_(42)
		reply.setParamDescriptor_forKeyword_(result, aeKeyword('----'))
	
if __name__ == '__main__':
	AppHelper.runEventLoop()


2. Using aemreceive (you need to put function wrappers around PyObjC method calls, otherwise aemreceive's magic clashes with PyObjC's magic):

from AppKit import *
from PyObjCTools import NibClassBuilder, AppHelper
import aemreceive

NibClassBuilder.extractClasses('MainMenu.nib')


class MyAppDelegate(NibClassBuilder.AutoBaseClass):

	def applicationWillFinishLaunching_(self, aNotification):
		aemreceive.installeventhandler(
			lambda:self.someEvent(),
			'SomeEvnt')
	
	def someEvent(self):
		return 42

if __name__ == '__main__':
	AppHelper.runEventLoop()


For doing it with Cocoa Scripting, follow Apple's documentation on implementing scriptability in Cocoa apps, translating to PyObjC as necessary. And remember to add any Info.plist settings and terminology resources as needed, of course.

has
-- 
http://freespace.virgin.net/hamish.sanderson/


More information about the Pythonmac-SIG mailing list