Введение
Механизм межпроцессного взаимодействия на основе сообщений в Mac OS.
Система программных сообщений Apple.
Apple events – это механизм межпроцессного взаимодействия на основе сообщений в Mac OS, впервые представленный в System 7 и поддерживаемый каждой версией классической Mac OS с тех пор, а также macOS. События Apple описывают события «высокого уровня», такие как «открыть документ» или «напечатать файл», в то время как более ранние ОС поддерживали гораздо более простые события, а именно «щелчок» и «нажатие клавиши». События Apple составляют основу системы скриптов Mac OS, Open Scripting Architecture (основной язык которой – AppleScript). Отправной точкой является динамически типизированный, расширяемый формат дескриптора, называемый AEDesc, который представляет собой просто код OSType, определяющий тип данных, вместе с блоком данных, зависящим от типа. Например, код OSType inte указывает, что данные являются четырехбайтовым целым числом со знаком в формате big endian. Помимо предварительно определенных кодов типов для различных распространенных простых типов, существуют два предварительно определенных структурированных типа дескрипторов: AERecord с типом данных reco (запись) и AEList с типом list (список или массив). Внутренняя структура этих типов содержит рекурсивно вложенные AEDescs, а AERecord также связывает каждый элемент с уникальным идентификатором поля записи, который является OSType. Apple Event Manager предоставляет вызовы API для создания этих структур, а также для извлечения их содержимого и запроса типа содержащихся в них данных. Apple Event Manager также поддерживает приведение типов (coercions), которое преобразует AEDescs из одного типа данных в другой. В дополнение к стандартным приведениям типов, например, между целыми и вещественными типами, приложения могут устанавливать собственные обработчики приведения типов, которые обрабатывают преобразования в пользовательские типы данных и из них. Событие Apple – это AERecord с полями, зависящими от назначения события. Кроме того, оно имеет атрибуты (которые отличаются от полей записи, которые теперь называются параметрами события) из набора, предварительно определенного Apple Event Manager. Они определяют, что должно делать событие (через класс события и идентификатор события), целевой адрес, на который должно быть отправлено событие (который может быть процессом на локальной или удаленной машине), и различные другие параметры обработки. Изначально удаленные машины должны были подключаться через AppleTalk, но Mac OS 9 добавила возможность подключения через TCP/IP. После отправки события Apple в целевой процесс, отправляющий процесс может выбрать получение ответа на событие Apple. Этот ответ может содержать различные фрагменты информации, возвращаемые целевым процессом об обработке исходного события, включая код ошибки, указывающий на успех или неудачу, любую информацию, запрошенную исходным событием, и/или другую соответствующую информацию. События Apple являются основой AppleEvent Object Model, которая, в свою очередь, является основой OSA и AppleScript. По состоянию на 2016 год официальная реализация API Apple Event Manager доступна на языке C и его производных, включая C++. Официальные привязки также предоставляются для Objective-C и Swift через Cocoa API. Неофициальные привязки также существуют для других языков (с различной степенью ограничений), включая Perl, UserTalk, Ruby и Python.
Apple's software messaging system
Apple events are the message based interprocess communication mechanism in Mac OS, first making an appearance in System 7 and supported by every version of the classic Mac OS since then and by macOS. Apple events describe "high level" events such as "open document" or "print file", whereas earlier OSs had supported much more basic events, namely "click" and "keypress". Apple events form the basis of the Mac OS scripting system, the Open Scripting Architecture (the primary language of such being AppleScript). The starting point is a dynamically typed, extensible descriptor format called an AEDesc, which is just an OSType code specifying the data type, together with a block of type dependent data. For instance, the OSType code inte indicates that the data was a four byte signed integer in big endian format. Besides predefined type codes for various common simple types, there are two predefined structured descriptor types: an AERecord, which has data type reco (record), and AEList with type list (list or array). The internal structure of these contain recursively nested AEDescs, while the AERecord also associates each element with a unique record field ID, which is an OSType. The Apple Event Manager provides API calls to construct these structures, as well as extract their contents and query the type of contents they hold. The Apple Event Manager also supports coercions, which converts AEDescs from one data type to another. In addition to standard coercions, for instance between integer and real types, applications can install their own coercion handler callbacks, which handle conversions to and from custom data types. An Apple event proper is an AERecord with fields that depended on the purpose of the event. In addition, it has attributes (which are distinct from record fields, which are now called the parameters of the event) from a set predefined by the Apple Event Manager. These specify what the event is supposed to do (through event class and event ID), the target address to which the event is to be sent (which could be a process on the local or a remote machine), and various other options for handling it. Remote machines initially had to be connected via AppleTalk, but Mac OS 9 added the option for connections via TCP/IP. After sending an Apple event to its target process, the sending process can elect to receive a reply to an Apple event. This can contain various bits of information returned from the target about the processing of the original event, including an error code indicating success/failure, any information requested by the original event, and/or other appropriate information. Apple events are the foundation of the AppleEvent Object Model, which in turn is the foundation of the OSA and AppleScript. as of 2016, the official implementation of the Apple Event Manager API is available in C and its descendants, including C++. Official bindings are also provided for Objective C and Swift through the Cocoa API. Unofficial bindings also exist for other languages (with varying degrees of limitation), including Perl, UserTalk, Ruby and Python.
Мост сценария
Scripting Bridge — это фреймворк macOS, который позволяет приложениям взаимодействовать друг с другом без использования промежуточного языка сценариев, такого как AppleScript. Подобно AppleScript, Scripting Bridge использует события Apple для межпроцессного взаимодействия. Scripting Bridge обычно используется с Objective-C и PyObjC.