Сравнивайте с английским: нажмите на абзац — оригинал откроется в окне. Кнопка EN под абзацем показывает его прямо в тексте.
Содержание
Введение
Resource fork – это форк файла в операционной системе Apple macOS, используемый для хранения структурированных данных. Это один из двух форков файла, наряду с форком данных, который хранит данные, рассматриваемые операционной системой как неструктурированные. Resource fork хранит информацию в определенном формате, включая такие детали, как растровые изображения значков, формы окон, определения меню и их содержимое, а также код приложений (машинный код). Например, файл текстового процессора может хранить свой текст в форке данных, а встроенные изображения – в resource fork того же файла. Resource fork в основном используется исполняемыми файлами, но любой файл может иметь resource fork. В технической заметке 1986 года компания Apple настоятельно рекомендовала разработчикам не помещать произвольные данные в resource fork файла. По мнению Apple, некоторые компоненты системного программного обеспечения полагаются на то, что resource fork содержит только корректную информацию Resource Manager. Resource fork был разработан и реализован программистом Apple Брюсом Хорном.
A resource fork is a fork of a file on Apple's macOS operating system that is used to store structured data. It is one of the two forks of a file, along with the data fork, which stores data that the operating system treats as unstructured. A resource fork stores information in a specific form, containing details such as icon bitmaps, the shapes of windows, definitions of menus and their contents, and application code (machine code). For example, a word processing file might store its text in the data fork, while storing any embedded images in the same file's resource fork. The resource fork is used mostly by executables, but any file can have a resource fork. In a 1986 technical note, Apple strongly recommended that developers do not put general data into the resource fork of a file. According to Apple, there are parts of the system software that rely on resource forks having only valid Resource Manager information in them. The resource fork was conceived and implemented by Apple programmer Bruce Horn.
Идентификаторы ресурсов
Каждый ресурс имеет идентификатор OSType (четырехбайтовое значение), ID (знаковое 16-битное слово) и необязательное имя. Существуют стандартизированные типы ресурсов для диалоговых окон (DITL), изображений (PICT), звуков (snd) и исполняемых двоичных файлов (CODE), которые до появления процессора PowerPC без исключения хранились в ресурсной вилке. Подпрограммы для отрисовки окон хранятся в ресурсах своего типа (WDEF), а подпрограммы для отрисовки меню – в ресурсах другого типа (MDEF). Такая организация позволяла пользователям легко настраивать не только отдельные приложения, но и саму операционную систему, используя инструменты вроде ResEdit для изменения ресурсов файла приложения или любого из системных файлов. В приложении или другом коде ресурсы можно загружать, используя комбинацию их типа, ID или имени, не заботясь о том, как и где они хранятся в ресурсной вилке. Клиент получает дескриптор к загруженному ресурсу, к которому затем можно обращаться как к любым другим данным, размещенным в куче. Компонент ОС, обеспечивающий эту функциональность, – это Менеджер ресурсов. Помимо абстрагирования деталей хранения данных, Менеджер ресурсов также организует наборы открытых ресурсных вилок в стек, при этом последний открытый файл находится наверху. При попытке загрузить ресурс он сначала ищет в верхней части стека (например, в ресурсной вилке текущего документа), затем в следующей ниже (в ресурсной вилке приложения), затем в следующей (в системных ресурсных вилках). Эта организация очень эффективна: она позволяет локальным ресурсам переопределять более глобальные, расположенные ниже, например, приложение может предоставлять собственные значки или шрифты вместо стандартных системных. Она также позволяет приложению загружать ресурсы из системы, используя тот же API, что и для любых других ресурсов, не заботясь о том, где и как этот ресурс хранится; для приложения все ресурсы одинаково доступны и просты в использовании. Система резервирует определенный диапазон ID ресурсов, чтобы избежать конфликтов, которые могут возникнуть из-за этого. API Менеджера ресурсов позволяет программисту манипулировать стеком и изменять логику поиска.
Each resource has an OSType identifier (a four byte value), an ID (a signed 16 bit word), and an optional name. There are standardized resource types for dialog boxes (DITL), images (PICT), sounds (snd ) and executable binaries (CODE) which, until the advent of the PowerPC processor, were without exception stored in the resource fork. Subroutines for rendering windows are stored in their own type of resources (WDEF), and subroutines for rendering menus in theirs (MDEF). This arrangement enabled users to easily customize not only individual applications but also the operating system itself, using tools such as ResEdit to modify the resources of an application file or any of the system files. Within an application or other code, resources can be loaded simply using a combination of their type, ID or name, without regard to how and where they are stored in the resource fork. The client is returned a handle to the loaded resource which can then be accessed like any other heap based data. The OS component that facilitates this is the Resource Manager. In addition to abstracting the details of the data storage from the data, the Resource Manager also arranges sets of open resource forks into a stack, with the most recently opened file on top. When trying to load a resource, it will look in the top of the stack first, (perhaps the current document's resource fork), then the next one down (the application's resource fork), then the next one (system resource forks). This arrangement is very powerful it permits local resources to override more global ones lower down so an application can provide its own icons or fonts in place of the standard system ones, for example. It also allows an application to load resources from the system using the same API as any other resource, without regard to where or how that resource is stored to the application, all resources are equally available and easy to use. The system reserves resource IDs in a certain range to help avoid resource conflicts arising from this. Resource Manager APIs allow the programmer to manipulate the stack and modify the search behaviour.
Редактирование
Поскольку ресурсный вилок можно редактировать с помощью редактора ресурсов, такого как ResEdit, он может использоваться для локализации и настройки программного обеспечения. Кроме того, большинство редакторов ресурсов позволяют визуально редактировать данные. В macOS ресурсы можно использовать при разработке приложения. Однако, если приложение может потребоваться использовать в UFS, можно также настроить его так, чтобы вся вилка ресурсов была перемещена в вилку данных, используя настройку Raw Resource File. Интегрированные среды разработки, распространяемые бесплатно компанией Apple Inc., включая MPW и Apple Developer's Tools, включают компилятор под названием Rez. Для этого используется специальный язык, также называемый Rez, который можно использовать для создания ресурсной вилки путем компиляции исходного кода. Также включен декомпилятор DeRez, который можно использовать для преобразования ресурсной вилки обратно в код Rez. В структуре ресурсной вилки есть фрагмент данных, называемый «картой ресурсов», который хранит позиции элементов данных ресурсов. Это позволяет осуществлять произвольный доступ к данным ресурсов на основе определенных идентификаторов и имен. Ресурсный вилок можно рассматривать как состоящий, по сути, из двух объектов: карты ресурсов и самих данных ресурсов, но на самом деле каждый тип данных представляет собой иерархическую структуру, хранящую несколько элементов данных. Формат, в котором хранится информация в данных ресурсов, определяется на основе типов информации, известных как «типы ресурсов». Данные ресурсов часто содержат ссылки на другие типы данных. В macOS форки называются file/namedfork/forkname, например, ресурсный вилок файла IMG 0593.jpg – IMG 0593.jpg/namedfork/rsrc. Команда ls поддерживает опцию l@, которая выводит список форков файла.
As the resource fork can be edited with a resource editor such as ResEdit, it can be used to localize and customize software. In addition, most resource editors allow visual editing of data. In macOS, it is possible to use resources when developing an application. However, if the application may need to be used in UFS, it is also possible to configure it so that the entire resource fork is moved to the data fork, using the Raw Resource File setting. The integrated development environments distributed for free by Apple Inc., which include MPW and Apple Developer's Tools, include a compiler called Rez. This uses a dedicated language, also called Rez, which can be used to create a resource fork by compiling source code. A decompiler, DeRez, which can be used to change a resource fork back into Rez code is also included. In the structure of the resource fork, there is a piece of data called a "resource map" which stores the positions of resource data items. This can be used to allow random access to resource data based on the defined IDs and names. The resource fork can be thought of as consisting of essentially two objects, the resource map and the resource data itself, but in fact each data type is a hierarchical structure which stores multiple items of data. The format in which the information in the resource data is stored is defined based on the types of information, which are known as "resource types." Resource data often makes references to other types of data. In macOS, forks are named file/ namedfork/forkname, e. g., the resource fork of the file IMG 0593. jpg is IMG 0593. jpg/ namedfork/rsrc. The ls command supports a l@ option which lists a file's forks.
Типы данных
Самые маленькие элементы, составляющие ресурсную вилку, называются типами данных. Существует несколько типов данных. После доступа к ресурсной вилке, её содержимое можно получить, прочитав его в соответствии с заранее определёнными типами данных. Размещение определений внутри программы, указывающих, как следует обрабатывать данные, также позволяет хранить ресурсы, называемые TMPL-ресурсами. Использование этого метода повышает наглядность данных при просмотре в программе, такой как ResEdit, что упрощает последующее редактирование. Поскольку платформа Macintosh изначально создавалась для процессоров Motorola (68k и PPC), данные сериализуются на диск в формате big endian. Ниже приведён список основных типов данных в алфавитном порядке.
The smallest elements making up a resource fork are called data types. There are several data types. After a resource fork is accessed, its contents can be found by reading it in as appropriate for the data types defined in advance. Placing definitions inside the program stating how data is to be treated makes it possible to store resources called TMPL resources as well. Using this method increases the visibility of the data when viewed with a program such as ResEdit, making later editing simpler. As the Macintosh platform originated with Motorola based processors (68k and PPC), the data is serialized to disk in big endian format. The following is a list of the major data types, in alphabetical order. Data type actual name Description BBIT binary bitRepresents a single boolean bit (true or false). Normally the number of BBITs must be a multiple of 8. BOOL booleanRepresents a boolean value. It consists of 2 bytes; 256 is true, and 0 is false. CHAR characterRepresents a one byte character. CSTR C stringRepresents a string of the form used in the C programming language: a null terminated string of bytes. DLNG decimal long word integerA decimal long word (4 byte integer). Represents values between approximately − 2.1 billion and 2.1 billion. HEXD hex dumpIndicates that the data from this position to the end is hexadecimal. This is used to represent code resources or compressed data. HLNG long word hexadecimalThis data is treated as a 4 byte hexadecimal value. It is used, among other things, to represent integers greater than 2.1 billion, such as unsigned long values in C. PSTR Pascal stringRepresents a Pascal string, with the first byte giving the length of the string. TNAM type nameA string representing a value such as a creator code, which is always 4 bytes long. RECT rectangleRepresents the coordinates of the corners of a rectangle (top, left, bottom, right). Always 8 bytes long.
Имя типа данных | Описание
---|---
BBIT | binary bit – Представляет один логический бит (истина или ложь). Обычно количество BBIT должно быть кратно восьми.
BOOL | boolean – Представляет логическое значение. Состоит из 2 байтов: 256 – истина, 0 – ложь.
CHAR | character – Представляет однобайтовый символ.
CSTR | C string – Представляет строку, используемую в языке программирования C: строку байтов, завершающуюся нулевым символом.
DLNG | decimal long word integer – Десятичное длинное слово (4-байтовое целое число). Представляет значения в диапазоне примерно от -2,1 миллиарда до 2,1 миллиарда.
HEXD | hex dump – Указывает, что данные от этой позиции до конца представлены в шестнадцатеричном формате. Используется для представления ресурсов кода или сжатых данных.
HLNG | long word hexadecimal – Эти данные интерпретируются как 4-байтовое шестнадцатеричное значение. Используется, в частности, для представления целых чисел, превышающих 2,1 миллиарда, таких как беззнаковые длинные значения в C.
PSTR | Pascal string – Представляет строку Pascal, где первый байт указывает длину строки.
TNAM | type name – Строка, представляющая значение, например, код создателя, который всегда имеет длину 4 байта.
RECT | rectangle – Представляет координаты углов прямоугольника (верхний, левый, нижний, правый). Всегда занимает 8 байтов.
The smallest elements making up a resource fork are called data types. There are several data types. After a resource fork is accessed, its contents can be found by reading it in as appropriate for the data types defined in advance. Placing definitions inside the program stating how data is to be treated makes it possible to store resources called TMPL resources as well. Using this method increases the visibility of the data when viewed with a program such as ResEdit, making later editing simpler. As the Macintosh platform originated with Motorola based processors (68k and PPC), the data is serialized to disk in big endian format. The following is a list of the major data types, in alphabetical order. Data type actual name Description BBIT binary bitRepresents a single boolean bit (true or false). Normally the number of BBITs must be a multiple of 8. BOOL booleanRepresents a boolean value. It consists of 2 bytes; 256 is true, and 0 is false. CHAR characterRepresents a one byte character. CSTR C stringRepresents a string of the form used in the C programming language: a null terminated string of bytes. DLNG decimal long word integerA decimal long word (4 byte integer). Represents values between approximately − 2.1 billion and 2.1 billion. HEXD hex dumpIndicates that the data from this position to the end is hexadecimal. This is used to represent code resources or compressed data. HLNG long word hexadecimalThis data is treated as a 4 byte hexadecimal value. It is used, among other things, to represent integers greater than 2.1 billion, such as unsigned long values in C. PSTR Pascal stringRepresents a Pascal string, with the first byte giving the length of the string. TNAM type nameA string representing a value such as a creator code, which is always 4 bytes long. RECT rectangleRepresents the coordinates of the corners of a rectangle (top, left, bottom, right). Always 8 bytes long.
Типы
Коды типов, представленные ниже, как и вышеуказанные типы данных, используются в качестве идентификаторов типов не только для самих форков ресурсов, но и для идентификации файлов, описания данных в буфере обмена и многого другого. Типы должны быть длиной 4 байта, поэтому типы, такие как snd и STR, фактически имеют пробел (0x20) в конце.
The type codes below, like the above datatypes, are used as type identifiers for more than resource forks themselves: they are used to identify file themselves, to describe data in the clipboard, and much more. Types must be 4 bytes long, so types like snd and STR actually have a space (0x20) at the end. Name of resource type actual name Description alis aliasStores an alias to another file, in a resource fork of a file whose "alias" attribute bit is set ALRT alertDefines the shape of an application alert box APPL applicationStores application information BNDL bundleDefines data such as a file type icon used in an application cicn color iconDefines a color icon used in data clut color look up tableDefines a color palette used in data CNTL controlDefines the details of a component positioned in a window CODE code resourceStores the machine code for the program CURS cursorDefines the shape of a monochrome cursor (8 × 8 bit square) DITL dialog item listDefines a component of a window DLOG dialogDefines the shape of a dialog box for an application FREF file referenceDefines a file type handled by an application hfdr icon balloon helpDefines the contents and shape of the balloon help displayed when the cursor hovers over the file in the Finder icl8 8 bit icon listDefines an icon displayed in the Finder icns 32 bit icon listDefines an icon displayed in the Finder ICON iconDefines a monochrome item used in data kind file descriptionDefines a description of a file type MBAR menu barDefines a menu and menu bar for an application MDEF menu definitionDefines a menu for an application. Can also be used to define menus with complex shapes such as color palettes. MENU menuDefines the menu items in an application MooV movieStores a QuickTime movie open openDefines a file type which the application can open PICT pictureStores a PICT image contained in the file PREF preferenceStores the environment settings for an application snd soundStores a sound used in the file STR stringStores a string or hexadecimal data used in the file STR# string listStores multiple strings used in the file styl styleDefines style information, such as the font, color and size of text TEXT textStores text TMPL templateDefines the format for the resource data vers versionDefines the version or region of use of the file WDEF window definitionDefines a window for the application. Windows of an unspecified shape can also be defined. WIND windowDefines the shape of an application window
alis – alias Хранит ссылку на другой файл в форке ресурсов файла, у которого установлен атрибут "alias".
ALRT – alert Определяет внешний вид окна предупреждения приложения.
APPL – application Хранит информацию о приложении.
BNDL – bundle Определяет данные, такие как значок типа файла, используемый в приложении.
cicn – color icon Определяет цветной значок, используемый в данных.
clut – color look up table Определяет цветовую палитру, используемую в данных.
CNTL – control Определяет детали компонента, расположенного в окне.
CODE – code resource Хранит машинный код программы.
CURS – cursor Определяет форму монохромного курсора (квадрат 8 × 8 бит).
DITL – dialog item list Определяет компонент окна.
DLOG – dialog Определяет внешний вид диалогового окна приложения.
FREF – file reference Определяет тип файла, обрабатываемый приложением.
hfdr – icon balloon help Определяет содержимое и внешний вид всплывающей подсказки, отображаемой при наведении курсора на файл в Finder.
icl8 – 8 bit icon list Определяет значок, отображаемый в Finder.
icns – 32 bit icon list Определяет значок, отображаемый в Finder.
ICON – icon Определяет монохромный элемент, используемый в данных.
kind – file description Определяет описание типа файла.
MBAR – menu bar Определяет меню и строку меню для приложения.
MDEF – menu definition Определяет меню для приложения. Может также использоваться для определения меню со сложной структурой, например, цветовых палитр.
MENU – menu Определяет элементы меню в приложении.
MooV – movie Хранит QuickTime movie.
open – open Определяет тип файла, который приложение может открыть.
PICT – picture Хранит PICT изображение, содержащееся в файле.
PREF – preference Хранит настройки среды для приложения.
snd – sound Хранит звук, используемый в файле.
STR – string Хранит строку или шестнадцатеричные данные, используемые в файле.
STR# – string list Хранит несколько строк, используемых в файле.
styl – style Определяет информацию о стиле, такую как шрифт, цвет и размер текста.
TEXT – text Хранит текст.
TMPL – template Определяет формат данных ресурса.
vers – version Определяет версию или область использования файла.
WDEF – window definition Определяет окно для приложения. Окна неопределенной формы также могут быть определены.
WIND – window Определяет форму окна приложения.
The type codes below, like the above datatypes, are used as type identifiers for more than resource forks themselves: they are used to identify file themselves, to describe data in the clipboard, and much more. Types must be 4 bytes long, so types like snd and STR actually have a space (0x20) at the end. Name of resource type actual name Description alis aliasStores an alias to another file, in a resource fork of a file whose "alias" attribute bit is set ALRT alertDefines the shape of an application alert box APPL applicationStores application information BNDL bundleDefines data such as a file type icon used in an application cicn color iconDefines a color icon used in data clut color look up tableDefines a color palette used in data CNTL controlDefines the details of a component positioned in a window CODE code resourceStores the machine code for the program CURS cursorDefines the shape of a monochrome cursor (8 × 8 bit square) DITL dialog item listDefines a component of a window DLOG dialogDefines the shape of a dialog box for an application FREF file referenceDefines a file type handled by an application hfdr icon balloon helpDefines the contents and shape of the balloon help displayed when the cursor hovers over the file in the Finder icl8 8 bit icon listDefines an icon displayed in the Finder icns 32 bit icon listDefines an icon displayed in the Finder ICON iconDefines a monochrome item used in data kind file descriptionDefines a description of a file type MBAR menu barDefines a menu and menu bar for an application MDEF menu definitionDefines a menu for an application. Can also be used to define menus with complex shapes such as color palettes. MENU menuDefines the menu items in an application MooV movieStores a QuickTime movie open openDefines a file type which the application can open PICT pictureStores a PICT image contained in the file PREF preferenceStores the environment settings for an application snd soundStores a sound used in the file STR stringStores a string or hexadecimal data used in the file STR# string listStores multiple strings used in the file styl styleDefines style information, such as the font, color and size of text TEXT textStores text TMPL templateDefines the format for the resource data vers versionDefines the version or region of use of the file WDEF window definitionDefines a window for the application. Windows of an unspecified shape can also be defined. WIND windowDefines the shape of an application window
Редакторы
ResEdit Распространяется бесплатно компанией Apple. Может использоваться для визуального редактирования ресурсных данных. Если структура данных известна, он может отображать различные типы данных в визуальном формате. Не работает на современных версиях macOS. Resorcerer Дорогой, но популярный, поскольку позволяет визуально редактировать гораздо больше типов данных, чем ResEdit. HexEdit Бинарный редактор, который чаще всего используется для редактирования форка данных, а не ресурсного форка. ResKnife Редактор с открытым исходным кодом для Mac OS X, разработка которого больше не ведется. Rezycle Инструмент для macOS, извлекающий ресурсы из ресурсного форка в отдельные двоичные файлы и преобразующий многие типы в форматы, подходящие для современной разработки. resource dasm Инструмент для извлечения ресурсов с открытым исходным кодом для macOS и Linux, также способный преобразовывать многие ресурсы в современные форматы. ResForge Редактор ресурсов для macOS, позволяющий редактировать классические файлы ресурсного форка и связанные с ними форматы. Совместим с macOS 10.14 и более поздними версиями. Работает непосредственно на 64-битных процессорах Intel и Apple Silicon.
ResEdit Distributed free of charge by Apple. Can be used for visual editing of resource data. If the structure of data is known, it can display a range of different types of data in a visual format. Does not run on modern macOS. Resorcerer Expensive, but popular, as it can be used for visual editing of many more types of data than ResEdit. HexEdit A binary editor, which in fact is normally used more for editing the data fork rather than the resource fork. ResKnife Open source editor for Mac OS X; no longer maintained. Rezycle A macOS tool that extracts resources from a resource fork into separate binary files while converting many types into formats suitable for modern development. resource dasm An open source resource extractor for macOS and Linux, also capable of converting many resources into modern formats. ResForge resource editor for macOS, capable of editing classic resource fork files and related formats. Compatible with macOS 10.14 or later. Runs natively on both 64 bit Intel and Apple Silicon.
Совместимость
Сложность программирования с ресурсными вилками привела к проблемам совместимости при доступе к другим файловым системам через протоколы совместного использования файлов, такие как AFP, SMB, NFS и FTP, при хранении на не-HFS томах или при передаче файлов другим системам другими способами (например, по электронной почте). Протокол AFP изначально поддерживает ресурсные вилки, поэтому они обычно передаются на эти тома без изменений и хранятся сервером прозрачно для клиентов. Протокол SMB поддерживает систему метаданных файлов, аналогичную форкам Macintosh, известную как альтернативные потоки данных (далее – ADSes). macOS не поддерживала хранение ресурсных вилок в ADSes на SMB-томах по умолчанию до Mac OS X v10.6. В предыдущих версиях ОС, включая обновленные версии 10.6, эту функцию можно включить, изменив параметр или создав специальный файл. Сетевые протоколы обмена файлами, такие как NFSv3 и FTP, не имеют понятия метаданных файлов, поэтому не существует способа хранения ресурсных вилок. Это также справедливо при записи на определенные типы локальных файловых систем, включая UFS, и на SMB-тома, где поддержка альтернативных потоков данных не включена. В этих случаях macOS хранит метаданные и ресурсные вилки, используя технику AppleDouble, при которой форк данных записывается как один файл, а ресурсный форк и метаданные – как совершенно отдельный файл, начинающийся с символа «.». Например: ExampleFile.psd будет содержать форк данных, а ExampleFile.psd – ресурсный форк и метаданные. Проблемы совместимости могут возникать, поскольку macOS по-разному обрабатывает хранение ресурсных вилок в зависимости от версии macOS, настроек и типа файловой системы. Например, в сети SMB с клиентами версий 10.5 и 10.6. Свежеустановленный клиент 10.6 будет искать и хранить ресурсные вилки на SMB-томе в ADSes, а клиент 10.5 (по умолчанию) будет игнорировать ADSes и использовать формат AppleDouble для обработки вилок. Если файловый сервер поддерживает как AFP, так и NFS, то клиенты, использующие NFS, будут хранить файлы в формате AppleDouble, а пользователи AFP – ресурсный форк в нативном формате. В этих случаях совместимость иногда можно обеспечить, принудительно заставляя клиентов использовать или не использовать формат AppleDouble. Многие файловые серверы, предоставляющие поддержку AFP, не поддерживают ресурсные вилки на своих локальных файловых системах. В этих случаях вилки могут храниться особыми способами, например, в специально названных файлах, специальных каталогах или даже в альтернативных потоках данных. Другая проблема заключается в сохранении ресурсных вилок при передаче файлов с использованием приложений, не учитывающих ресурсные вилки, или определенных методов передачи, включая электронную почту и FTP. Для этого были созданы такие форматы файлов, как MacBinary и BinHex. Инструменты командной строки SplitForks и FixupResourceForks позволяют вручную «сглаживать» и объединять ресурсные вилки. Кроме того, файловый сервер, стремящийся предоставить файловые системы клиентам Macintosh, должен учитывать как ресурсный форк, так и форк данных файлов; UNIX-серверы, предоставляющие поддержку AFP, обычно реализуют это с помощью скрытых каталогов. У старых приложений, написанных с использованием Carbon API, может возникнуть проблема при переносе на современные Intel Mac. Хотя Resource Manager и операционная система знают, как правильно десериализовать данные для общих ресурсов, таких как 'snd' или 'moov', ресурсы, созданные с использованием ресурсов TMPL, необходимо вручную менять местами байтами, чтобы обеспечить совместимость файлов между версиями приложения на базе PPC и Intel. (Хотя карта ресурсов и другие детали реализации используют порядок байтов big-endian, сам Resource Manager не имеет информации о содержимом общего ресурса и поэтому не может автоматически выполнять обмен байтами.) До появления Mac OS X v10.4 стандартные утилиты командной строки UNIX в macOS (такие как cp и mv) не учитывали ресурсные вилки. Чтобы скопировать файлы с ресурсными вилками, необходимо было использовать ditto или CpMac и MvMac.
The complexity of programming with resource forks has led to compatibility problems when accessing other file systems via file sharing protocols such as AFP, SMB, NFS and FTP, when storing to non HFS volumes, or when transmitting files to other systems in other ways (such as via email). The AFP protocol natively supports Resource Forks, and so resource forks are typically transmitted to these volumes as is, and stored by the server transparently to clients. The SMB protocol supports a file metadata system similar to Macintosh forks known as Alternate Data Streams (ADSes hereafter). macOS did not support storing resource forks in ADSes on SMB volumes by default until Mac OS X v10.6. In previous versions of the OS, including upgraded versions of 10.6, this feature can be enabled with a param change or by creating a special file. Networked file sharing protocols such as NFSv3 and FTP do not have a concept of file metadata, and so there is no way to natively store resource forks. This is also true when writing to certain types of local file systems, including UFS, and on SMB volumes where Alternate Data Stream support is not enabled. In those cases, macOS stores metadata and resource forks using a technique called AppleDouble, in which the data fork is written as one file, and the resource fork and metadata are written as an entirely separate file preceded by a ". " naming convention. For example: ExampleFile. psd would contain the data fork, and ExampleFile. psd would contain the resource fork and metadata. Compatibility problems can arise because macOS will handle storage of resource forks differently, depending on macOS version, settings, and file system type. For example, on an SMB network with a mixture of 10.5 and 10.6 clients. A freshly installed 10.6 client will look for and store resource forks on an SMB volume in ADSes, but the 10.5 client will (by default) ignore ADSes and use AppleDouble format to handle forks. If a fileserver supports both AFP and NFS, then clients using NFS will store files in AppleDouble format, whereas AFP users will stored the resource fork natively. In those cases, compatibility can sometimes be maintained by forcing clients to use, or not use, AppleDouble format. Many fileservers providing AFP support do not natively support resource forks on their local file systems. In those cases the forks may be stored in special ways, such as specially named files, special directories, or even Alternate Data Streams. Another challenge is preserving resource forks when transmitting files using non resource fork aware applications or with certain transfer methods, including email and FTP. A number of file formats, such as MacBinary and BinHex, have been created to handle this. Command line system tools SplitForks and FixupResourceForks allow manual flattening and merging of resource forks. In addition, a file server seeking to present file systems to Macintosh clients must accommodate the resource fork as well as the data fork of files; UNIX servers providing AFP support usually implement this with hidden directories. Older applications written with the Carbon API have a potential issue when being ported to the current Intel Macs. While the Resource Manager and operating system know how to deserialize data correctly for common resources like 'snd ' or 'moov', resources created using TMPL resources have to be byte swapped manually to ensure file interoperability between PPC and Intel based versions of an application. (While the resource map and other implementation details are big endian, the Resource Manager by itself does not have any knowledge of the contents of a generic resource, and so cannot perform the byte swapping automatically.) Until the advent of Mac OS X v10.4, the standard UNIX command line utilities in macOS (such as cp and mv) did not respect resource forks. To copy files with resource forks, one had to use ditto or CpMac and MvMac.
Другие операционные системы
Концепция менеджера ресурсов для графических объектов, призванная экономить память, возникла в пакете OOZE на Xerox Alto в Smalltalk 76. Эта концепция сейчас широко распространена во всех современных операционных системах. Однако концепция ресурсной вилки остаётся уникальной для Macintosh. Большинство операционных систем используют двоичный файл, содержащий ресурсы, который затем "присоединяется" к концу существующего файла программы. Это решение используется, например, в Microsoft Windows, и аналогичные решения применяются в X Window System, хотя ресурсы часто хранятся в отдельном файле. Windows NT NTFS поддерживает форки (и, следовательно, может выступать в качестве файлового сервера для файлов Mac), а встроенная функция, обеспечивающая такую поддержку, называется потоком альтернативных данных. Функции операционной системы Windows (например, стандартная вкладка "Сведения" на странице "Свойства" для файлов, не относящихся к Office) и приложения Windows используют их, и Microsoft разрабатывала файловую систему следующего поколения, в которой эта функция является основой. Ранние версии BeOS реализовали базу данных в файловой системе, которую можно было использовать аналогично ресурсной вилке. Проблемы с производительностью привели к переходу в более поздних версиях к системе сложных атрибутов файловой системы. В этой системе ресурсы обрабатывались способом, несколько более похожим на Mac. AmigaOS не использует форкированные файлы. Его исполняемые файлы внутренне разделены на модульную структуру, состоящую из крупных блоков (чанков), способных хранить код, данные и дополнительную информацию. Аналогично, файлы данных и проектов имеют структуру блоков, кодифицированную в стандарте IFF. Другие типы файлов хранятся аналогично другим операционным системам. Хотя AmigaOS и не использует ресурсную вилку, она хранит метаданные в файлах, известных как информационные файлы. Информационные файлы можно идентифицировать по расширению .info; например, при сохранении проекта на диск будут сохранены два файла: MyProject и MyProject.info. MyProject будет содержать фактические данные проекта, а MyProject.info – иконку проекта, информацию о том, какая программа необходима для открытия проекта (поскольку в AmigaOS нет привязки приложений), специальные параметры проекта и любые комментарии пользователей. Информационные файлы невидимы на рабочем столе Amiga (Workbench). Иконка на рабочем столе, взятая из самого информационного файла, является метафорой интерфейса, через которую пользователь взаимодействует как с самим проектом, так и с его связанным информационным файлом. Диалоговое окно, доступное по щелчку правой кнопкой мыши на иконке, позволяет пользователю просматривать и изменять метаданные, содержащиеся в информационном файле. Информационные файлы можно рассматривать как отдельные файлы в интерфейсе командной строки или в файловом менеджере. Современные клоны AmigaOS (AROS, MorphOS и AOS4) наследуют структуру (вместе с метаданными) информационных файлов старых версий AmigaOS и также могут принимать стандартные графические файлы PNG в качестве растровых изображений иконок в своих информационных файлах. Операционные системы NeXT NeXTSTEP и OPENSTEP, их преемник macOS, и другие системы, такие как RISC OS, реализовали другое решение. В этих системах ресурсы остаются в исходном формате, например, изображения включаются в виде полных файлов TIFF вместо кодирования в какой-либо контейнер. Затем эти ресурсы помещаются в каталог вместе с исполняемым кодом и "сырыми данными". Каталог (называемый "пакетом" или "каталогом приложения") затем представляется пользователю как само приложение. Это решение обеспечивает ту же функциональность, что и ресурсная вилка, но позволяет легко манипулировать ресурсами из любого приложения – не требуется "редактор ресурсов" (например, ResEdit). В интерфейсе командной строки пакет выглядит как обычный каталог. Такой подход был невозможен в классической Mac OS, поскольку файловая система (MFS) не поддерживала отдельные каталоги каталогов. Когда поддержка каталоговых файлов была включена в Mac OS с файловой системой HFS, ресурсная вилка была сохранена. macOS сохраняет классический API-интерфейс Resource Manager в составе своих библиотек Carbon для обратной совместимости. Однако сами ресурсы теперь могут храниться в отдельных файлах данных в файловой системе, и Resource Manager скрывает это изменение реализации от клиентского кода.
The concept of a resource manager for graphics objects, to save memory, originated in the OOZE package on the Xerox Alto in Smalltalk 76. The concept is now largely universal in all modern operating systems. However, the concept of the resource fork remains peculiar to the Macintosh. Most operating systems used a binary file containing resources, which is then "tacked onto" the end of an existing program file. This solution is used on Microsoft Windows for instance, and similar solutions are used with the X Window System, although the resources are often left as a separate file. The Windows NT NTFS can support forks (and so can be a file server for Mac files), the native feature providing that support is called an alternate data stream. Windows operating system features (such as the standard Summary tab in the Properties page for non Office files) and Windows applications use them and Microsoft was developing a next generation file system that has this sort of feature as basis. Early versions of the BeOS implemented a database within the file system, which could be used in a manner analogous to a resource fork. Performance issues led to a change in later releases to a system of complex file system attributes. Under this system resources were handled in a fashion somewhat more analogous to the Mac. AmigaOS does not use forked files. Its executable files are internally divided into a modular structure of large pieces (hunk) capable of storing code, data, and additional information. Similarly, data and project files have a chunk structure codified in the IFF standard. Other file types are stored similarly to other operating systems. Though not strictly a resource fork, AmigaOS stores meta data in files known as info files. info files can be identified by the info extension; for example, if you save a project to a disk, two files will be saved, MyProject and MyProject. info. MyProject would be the actual project data and MyProject. info would contain the project icon, information regarding which program is needed to open the project (since there is no application binding in AmigaOS), special project options and any user comments. info files are invisible on the Amiga's desktop (Workbench). The icon on the desktop, taken from the info itself, is the interface metaphor through which the user interacts both with the project itself and its associated info file. A dialog box accessible by right clicking the icon allows the user to see and modify the metadata present in the info file. info files can be seen as individual files in the command line interface or a File manager. Modern AmigaOS clones (AROS, MorphOS and AOS4) inherit the structure (complete with metadata) of the info files of older AmigaOS versions, and can also accept standard PNG graphic files as icon bitmaps in their info files. NeXT operating systems NeXTSTEP and OPENSTEP, their successor, macOS, and other systems like RISC OS implemented another solution. Under these systems the resources are left in an original format, for instance, pictures are included as complete TIFF files instead of being encoded into some sort of container. These resources are then placed in a directory along with the executable code and "raw data". The directory (called a "bundle" or "application directory") is then presented to the user as the application itself. This solution provides all of the same functionality as the resource fork, but allows the resources to be easily manipulated by any application a "resource editor" (like ResEdit) is not needed. From the command line interface, the bundle appears to be a normal directory. This approach was not an option on the classic Mac OS, since the file system (MFS) did not support separate catalog directories. When catalog file support was included in Mac OS, with the HFS filesystem, the resource fork was retained. macOS does retain the classic Resource Manager API as part of its Carbon libraries for backward compatibility. However, the resources themselves can now be stored in separate data files within the file system the Resource Manager now hides this implementation change from the client code.