texts
stringlengths
0
715k
names
stringlengths
8
91
StdApi ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdApi; IMPORT Views; PROCEDURE CloseDialog (OUT closedView: Views.View); PROCEDURE OpenAux (file, title: ARRAY OF CHAR; OUT v: Views.View); PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR; OUT v: Views.View); PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR; OUT v: Views.View); PROCEDURE OpenCopyOf (file: ARRAY OF CHAR; OUT v: Views.View); PROCEDURE OpenDoc (file: ARRAY OF CHAR; OUT v: Views.View); PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR; OUT v: Views.View); END StdApi. StdApi это программный интерфейс для ряда средств модуля StdCmds. Команды последнего предназначены для использования в меню, гиперссылках и т.д. Модуль StdApi предоставляет точно такие же функции, но в виде более пригодном для использования в программах. PROCEDURE CloseDialog (OUT closedView: Views.View) Команда закрывает окно, находящееся в данный момент в фокусе. Если окно является окном документа, и его содержимое изменено (окно грязное), то будет выдано сообщение об ошибке. Корневая вьюшка закрытого окна будет возвращена в параметре closedView. Если CloseDialog терпит неудачу, возвращается NIL. PROCEDURE OpenAux (file, title: ARRAY OF CHAR; OUT v: Views.View) Получает спецификацию файла документа Блэкбокса (file) и заголовок окна (title), затем открывает вспомогательное (Aux) окно с указанным загловком. Параметр file должен быть именем пути к файлу. Корневая вьюшка открытого окна возвращается в v. Если OpenAux терпит неудачу, то v возвращает NIL. Вспомогательные окна используются для предъявления временных данных, допускающих правку. PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR; OUT v: Views.View) Получает спецификацию файла документа Блэкбокса (file) и заголовок окна (title), затем открывает диалоговое окно с заданным документом. Диалог открывается как вспомогательное окно. Параметр file должен быть именем пути к файлу. Корневая вьюшка открытого окна возвращается в v. Если OpenAuxDialog терпит неудачу, то v возвращает NIL. Вспомогательные диалоги используются для самодостаточных диалогов, то есть масок ввода данных или параметров для команд. В отличие от OpenAux, OpenAuxDialog переводит открываемый документ в режим маски, если это контейнер, и открывает его в диалоговом окне, если операционная среда, в которой работает Блэкбокс, различает окна документов и диалогов (например, как в Windows). PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR; OUT v: Views.View) Получает спецификацию файла документа Блэкбокса (file) и заголовок окна (title), затем открывает указанный документ во вспомогательном окне. Содержимое окна нельзя править, но в нем можно выделять фрагменты. Параметр file должен быть именем пути к файлу. Корневая вьюшка открытого окна возвращается в v. Если OpenBrowser терпит неудачу, то v возвращает NIL. Окна, открываемые таким образом, используют для документации. В содержимом окна можно выделять фрагменты и копировать их. Можно применять команды поиска, команду Info->Interface и т.д. PROCEDURE OpenCopyOf (file: ARRAY OF CHAR; OUT v: Views.View) Открывает новый документ, являющийся копией документа, заданного параметром file. В случае успеха в v возвращается корневая вьюшка нового документа, иначе возвращается NIL. PROCEDURE OpenDoc (file: ARRAY OF CHAR; OUT v: Views.View) Получает спецификацию файла документа Блэкбокса (file) и открывает документ в окне документа. Параметр file должен быть именем пути к файлу. Если такой файл уже открыт в некотором окне документа, то это окно выводится наверх вместо открытия нового. Корневая вьюшка открытого окна (или старого окна) возвращается в v. Если OpenDoc терпит неудачу, то в v возвращается NIL. Окна документов используются для показа редактируемых данных, предназначенных для хранения. PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR; OUT v: Views.View) Получает спецификацию файла документа Блэкбокса (file) и заголовок окна (title), затем открывает диалог с указанным документом. Диалог открывается как инструментальное окно. Параметр file должен быть именем пути к файлу. Корневая вьюшка открытого окна возвращается в v. Если OpenToolDialog терпит неудачу, то v возвращает NIL. Инструментальные диалоги используются для диалогов, которые работают с окнами документов под ними, например, диалог поиска и замены, который работает с текстом под собой. В остальном все идентично OpenAuxDialog.
Std/Docu/ru/Api.odc
StdCFrames Это приватный модуль системы Блэкбокс. Его наличие необходимо для правильной работы BlackBox.
Std/Docu/ru/CFrames.odc
StdClocks ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdClocks; IMPORT Views; PROCEDURE Deposit; PROCEDURE New (): Views.View; END StdClocks. Модуль реализует простые вьюшки, изображающие часы. Типичные команды меню: "Insert Clock" "" "StdClocks.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard" PROCEDURE New (): Views.View Фабричная функция для стандартных часов PROCEDURE Deposit Стандартная команда, помещающая новую вьюшку-часы, в глобальную очередь.
Std/Docu/ru/Clocks.odc
StdCmds ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdCmds; IMPORT Dialog, Ports, Fonts; VAR allocator: Dialog.String; layout: RECORD wType, hType: INTEGER; width, height: REAL END; size: RECORD size: INTEGER END; PROCEDURE Bold; PROCEDURE BoldGuard (VAR par: Dialog.Par); PROCEDURE CaretGuard (VAR par: Dialog.Par); PROCEDURE Clear; PROCEDURE CloseDialog; PROCEDURE Color (color: Ports.Color); PROCEDURE ColorGuard (color: INTEGER; VAR par: Dialog.Par); PROCEDURE ContainerGuard (VAR par: Dialog.Par); PROCEDURE CopyProp; PROCEDURE DefaultFont; PROCEDURE DefaultFontGuard (VAR par: Dialog.Par); PROCEDURE DefaultOnDoubleClick (op, from, to: INTEGER); PROCEDURE DeselectAll; PROCEDURE Font (typeface: Fonts.Typeface); PROCEDURE HeightGuard (VAR par: Dialog.Par); PROCEDURE InitLayoutDialog; PROCEDURE InitSizeDialog; PROCEDURE Italic; PROCEDURE ItalicGuard (VAR par: Dialog.Par); PROCEDURE ModelViewGuard (VAR par: Dialog.Par); PROCEDURE New; PROCEDURE NewWindow; PROCEDURE Open; PROCEDURE OpenAsAuxDialog; PROCEDURE OpenAsToolDialog; PROCEDURE OpenAux (file, title: ARRAY OF CHAR); PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR); PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR); PROCEDURE OpenDoc (file: ARRAY OF CHAR); PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR); PROCEDURE PasteCharGuard (VAR par: Dialog.Par); PROCEDURE PasteLCharGuard (VAR par: Dialog.Par); PROCEDURE PasteProp; PROCEDURE PasteView; PROCEDURE PasteViewGuard (VAR par: Dialog.Par); PROCEDURE Plain; PROCEDURE PlainGuard (VAR par: Dialog.Par); PROCEDURE ReadOnlyGuard (VAR par: Dialog.Par); PROCEDURE RecalcAllSizes; PROCEDURE RecalcFocusSize; PROCEDURE Redo; PROCEDURE RedoGuard (VAR par: Dialog.Par); PROCEDURE RestoreAll; PROCEDURE SelectAll; PROCEDURE SelectAllGuard (VAR par: Dialog.Par); PROCEDURE SelectDocument; PROCEDURE SelectNextView; PROCEDURE SelectionGuard (VAR par: Dialog.Par); PROCEDURE SetBrowserMode; PROCEDURE SetBrowserModeGuard (VAR par: Dialog.Par); PROCEDURE SetEditMode; PROCEDURE SetEditModeGuard (VAR par: Dialog.Par); PROCEDURE SetLayout; PROCEDURE SetLayoutMode; PROCEDURE SetLayoutModeGuard (VAR par: Dialog.Par); PROCEDURE SetMaskMode; PROCEDURE SetMaskModeGuard (VAR par: Dialog.Par); PROCEDURE SetSize; PROCEDURE ShowProp; PROCEDURE ShowPropGuard (VAR par: Dialog.Par); PROCEDURE SingletonGuard (VAR par: Dialog.Par); PROCEDURE Size (size: INTEGER); PROCEDURE SizeGuard (size: INTEGER; VAR par: Dialog.Par); PROCEDURE Strikeout; PROCEDURE StrikeoutGuard (VAR par: Dialog.Par); PROCEDURE ToggleNoFocus; PROCEDURE ToggleNoFocusGuard (VAR par: Dialog.Par); PROCEDURE TypeNotifier (op, from, to: INTEGER); PROCEDURE TypefaceGuard (VAR par: Dialog.Par); PROCEDURE Underline; PROCEDURE UnderlineGuard (VAR par: Dialog.Par); PROCEDURE Undo; PROCEDURE UndoGuard (VAR par: Dialog.Par); PROCEDURE UpdateAll; PROCEDURE WidthGuard (VAR par: Dialog.Par); PROCEDURE WindowGuard (VAR par: Dialog.Par); END StdCmds. Модуль StdCmds содержит много команд и процедур охраны, которые обычно используются в меню (см. модуль StdMenuTool) или в гиперссылках (см. StdLinks). Кроме того, модуль экпортирует несколько процедур, здесь не описанных; это команды и охраны стандартных меню ОС Windows. См. текст Menus, где можно увидеть, как эти команды используются (только под Windows; под MacOS стандартные команды в спецификациях меню явно не задаются). VAR allocator: Dialog.String Литерная цепочка, содержащая последовательность команд, которая выполняется, когда пользователь использует команду File->New (Файлы->Новый). Значение по умолчанию: "TextViews.Deposit; StdCmds.Open". Эта цепочка может быть изменена в модуле Config. VAR layout: RECORD Интерактор диалога Tools->Document Size... (Инструменты->Размер документа...) для управления размерами корневого, то есть самого внешнего объекта отрисовки (вьюшки) в окне. Эти размеры могут задаваться несколькими различными способами. Он равен либо размеру окна, либо размеру бумаги минус ширина полей, заданных в диалоге Page Setup (Разметка страницы), либо некоторому конкретному фиксированному размеру. Вертикальный и горизонтальный размеры настраиваются отдельно. wType, hType: INTEGER wType IN {0..2} & hType IN {0..2} Определяют, является ли размер (ширина/w высота/h) корневой объект отрисовки фиксированным (0), установленным диалогом Page Setup/Разметка страницы (1) или равным размеру окна (2). width, height: REAL имеют смысл, если и только если wType/hType = 1 Ширина/высота корневого объекта отрисовки в сантиметрах. VAR size: RECORD Интерактор для установки размера шрифта. size: INTEGER size >= 6 Размер шрифта в пунктах (см. модуль Fonts). PROCEDURE Bold PROCEDURE BoldGuard (VAR par: Dialog.Par) PROCEDURE CaretGuard (VAR par: Dialog.Par) Отключает пункт меню, если объект отрисовки в фокусе не имеет текстового курсора. PROCEDURE Clear PROCEDURE CloseDialog Эту команду можно вызвать из элемента управления, чтобы закрыть окно, в котором внедрен этот элемент. Её можно использовать только в качестве реакции на воздействия пользователя на элемент управления, то есть при клике по нему или когда он принимает ввод с клавиатуры. Если в окне показывается документ и окно грязное, то будет показано сообщение об ошибке. Предусловие должна вызываться при взаимодействии с элементом управления 20 PROCEDURE Color (color: Ports.Color) Присваивает выделенному фрагменту указанный цвет (см. Ports.Color). PROCEDURE ColorGuard (color: INTEGER; VAR par: Dialog.Par) Охрана для команды Color. PROCEDURE CopyProp Запоминает в специальном буфере свойства выделенного фрагмента, чтобы можно было их использовать для вставки. PROCEDURE ContainerGuard (VAR par: Dialog.Par) Охрана, проверяющая, что объект отрисовки, находящийся в фокусе, является контейнером (см. Container.View). PROCEDURE DefaultFont Присваивает выделенному фрагменту текста гарнитуру шрифта по умолчанию. PROCEDURE DefaultFontGuard (VAR par: Dialog.Par) Охрана для команды DefaultFont. PROCEDURE DefaultOnDoubleClick (op, from, to: INTEGER) Стандартный уведомитель, который программно выполняет клик по кнопке-по-умолчанию при двойном клике по элементу управления. Обычно используется в списках выбора или выпадающих списках. PROCEDURE DeselectAll Снимает выделение фрагмента в объекте отрисовки, находящемся в фокусе. PROCEDURE Font (typeface: Fonts.Typeface) PROCEDURE HeightGuard (VAR par: Dialog.Par) Охрана, выставляющая par.readOnly, если layout.hType # 0, то есть если высота не фиксирована. PROCEDURE InitLayoutDialog Команда инициализации для интерактора layout. PROCEDURE InitSizeDialog Команда инициализации для интерактора size. PROCEDURE Italic Присваивает выделенному фрагменту стиль курсив. PROCEDURE ItalicGuard (VAR par: Dialog.Par) Охрана для команды Italic. PROCEDURE ModelViewGuard (VAR par: Dialog.Par) Охрана для команды NewWindow (проверяет, что метод ThisModel объекта отрисовки в фокусе возвращает значение, не равное NIL). PROCEDURE New Открыть новый безымянный документ, используя последовательность команд из переменной allocator. PROCEDURE NewWindow Охрана: ModelViewGuard Открывает еще одно окно для документа в переднем окне. PROCEDURE Open Охрана: в глобальную очередь помещен объект отрисовки Берет этот объект из глобальной очереди и открывает его в новом окне. PROCEDURE OpenAsAuxDialog Открывает еще одно окно на документ в переднем окне; новое окно функционирует как вспомогательный диалог. PROCEDURE OpenAsToolDialog Открывает еще одно окно на документ в переднем окне; новое окно функционирует как инструментальный диалог. PROCEDURE OpenAux (file, title: ARRAY OF CHAR) Получает спецификацию файла с документом Блэкбокса (file) и заголовок окна (title), затем открывает документ во вспомогательном окне с указанным загловком. Параметр file должен быть именем пути к файлу. Вспомогательные (Aux) окна используются для представления временных данных, допускающих правку. Например: "StdCmds.OpenAux('Form/Rsrc/Menus', 'Form Menus')" PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR) Получает спецификацию файла с документом Блэкбокса (file) и заголовок окна (title), затем открывает диалоговое окно с заданным документом. Диалог открывается как вспомогательное окно. Параметр file должен быть именем пути к файлу. Вспомогательные (Aux) диалоги используются для самодостаточных диалогов, то есть для масок ввода данных или параметров для команд. В отличие от OpenAux, OpenAuxDialog переводит открываемый документ в режим маски, если это контейнер (см. модуль Containers), и открывает его в диалоговом окне, если операционная среда, в которой работает Блэкбокс, различает окна документов и диалогов (например, как в Windows). Пример: "StdCmds.OpenAuxDialog('Form/Rsrc/Cmds', 'New Form')" PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR) Получает спецификацию файла с документом Блэкбокса (file) и заголовок окна (title), затем открывает указанный документ во вспомогательном окне. Содержимое окна нельзя править, но в нем можно выделять фрагменты. Параметр file должен быть именем пути к файлу. Окна браузера используются для показа документации. Содержимое окна браузера можно выделять и копировать. Можно выполнять команды поиска, команды Info->Inteface (справки по интерфейсам модулей) и т.д. Пример: "StdCmds.OpenBrowser('Form/Docu/Models', 'FormModels Docu')" PROCEDURE OpenDoc (file: ARRAY OF CHAR) Получает спецификацию файла документа BlackBox и открывает документ в окне документа. Параметр file должен быть именем пути к файлу. Если такой файл уже открыт в окне документа, это окно выводится наверх вместо открытия нового. Окна документов используются для показа редактируемых данных, предназначенных для хранения. Пример: "StdCmds.OpenDoc('System/Rsrc/Menus')" PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR) Получает спецификацию файла с документом Блэкбокса (file) и заголовок окна (title), затем открывает диалог с указанным документом. Диалог открывается как инструментальное (Tool) окно. Параметр file должен быть именем пути к файлу. Инструментальные диалоги работают с окнами документов под ними, например, диалог поиска и замены, который работает с текстом. В остальном все идентично OpenAuxDialog. Пример: "DevInspector.InitDialog; StdCmds.OpenToolDialog('Dev/Rsrc/Inspect', 'Inspect')" PROCEDURE PasteCharGuard (VAR par: Dialog.Par) Отключает пункт меню, если ввод литеры в данный момент невозможен. PROCEDURE PasteLCharGuard (VAR par: Dialog.Par) Устаревшая процедура. PROCEDURE PasteProp Охрана: в специальном буфере были запомнены свойства (см. CopyProp) Применяет эти свойства к выделенному фрагменту. PROCEDURE PasteView Охрана: в глобальную очередь помещен объект отрисовки. Этот объект забирается из очереди и вставляется в объект отрисовки, находящийся в фокусе. PROCEDURE PasteViewGuard (VAR par: Dialog.Par) Отключает пункт меню, если вставка объекта отрисовки сейчас невозможна. PROCEDURE Plain Присваивает выделенному фрагменту атрибуты простого текста (не курсив, не полужирный, не подчеркнутый). PROCEDURE PlainGuard Охрана для команды Plain. PROCEDURE ReadOnlyGuard (VAR par: Dialog.Par) Делает элемент управления доступным только для чтения, устанавливая par.readOnly в TRUE. PROCEDURE RecalcAllSizes Пересчитывает размеры всех видимых объектов отрисовки. Должен вызываться после изменения метрик шрифтов. PROCEDURE RecalcFocusSize Пересчитывает размер объекта отрисовки, находящегося в фокусе. PROCEDURE Redo Повторить последнюю отмененную команду. PROCEDURE RedoGuard Охрана для команды Redo. PROCEDURE RestoreAll Форсирует отрисовку всех видимых вьюшек. PROCEDURE SelectAll Выделяет всё содержимое вьюшки в фокусе. PROCEDURE SelectAllGuard Охрана для команды SelectAll. PROCEDURE SelectDocument Выделяет корневую вьюшку (самый внешний контейнер) в переднем окне. PROCEDURE SelectNextView Если в контейнере выделена одиночная вьюшка, то эта команда находит и выделяет следующую вьюшку в контейнере (в циклическом порядке). PROCEDURE SelectionGuard (VAR par: Dialog.Par) Отключает пункт меню, если нет выделенного фрагмента. PROCEDURE SetBrowserMode Охрана: SetBrowserModeGuard Переводит выделенный контейнер в режим просмотра. Если нет выделенного контейнера, в режим просмотра переводится самый внешний контейнер. Этот режим обычно используется для документации. PROCEDURE SetBrowserModeGuard (VAR par: Dialog.Par) Охрана для процедуры SetBrowserMode. Устанавливает par.checked, если это уместно. PROCEDURE SetEditMode Охрана: SetEditModeGuard Переводит выделенный контейнер в режим правки. Если нет выделенного контейнера, в режим правки переводится самый внешний контейнер. Этот режим является основным для текстов, допускающих правку. PROCEDURE SetEditModeGuard (VAR par: Dialog.Par) Охрана для процедуры SetEditMode. Устанавливает par.checked, если это уместно. PROCEDURE SetLayout Применяет значения интерактора layout. Чтобы применить эти значения к выделенной вьюшке, необходимо сначала вызвать InitLayoutDialog. PROCEDURE SetLayoutMode Охрана: SetLayoutModeGuard Переводит выделенный контейнер в режим разметки. Если нет выделенного контейнера, то в режим разметки переводится самый внешний контейнер. Этот режим обычно используется при работе с диалоговыми формами, допускающими правку. PROCEDURE SetLayoutModeGuard (VAR par: Dialog.Par) Охрана для процедуры SetLayoutMode. Устанавливает par.checked, если это уместно. PROCEDURE SetMaskMode Охрана: SetMaskModeGuard Переводит выделенный контейнер в режим маски. Если нет выделенного контейнера, в режим маски переводится самый внешний контейнер. В этот режим обычно переводятся формы, используемые в качестве диалоговых окон. PROCEDURE SetMaskModeGuard (VAR par: Dialog.Par) Охрана для процедуры SetMaskMode. Устанавливает par.checked, если это уместно. PROCEDURE SetSize Команда для установки выделенного фрагмента в размер (кегль), заданный в интеракторе size. PROCEDURE ShowProp Показывает свойства фрагмента, выделенного в объекте отрисовки, находящемся в фокусе. PROCEDURE ShowPropGuard Охрана для команды ShowProp. PROCEDURE SingletonGuard (VAR par: Dialog.Par) Отключает пункт меню, если нет выделенного фрагмента, состоящего в точности из одной внедренной вьюшки. PROCEDURE Size (size: INTEGER) Присваивает выделенному фрагменту указанный кегль (размер) в пунктах (см. Fonts). PROCEDURE SizeGuard (size: INTEGER; VAR par: Dialog.Par) Охрана для команды Size. PROCEDURE Strikeout Присваивает выделенному фрагменту зачеркнутый стиль. PROCEDURE StrikeoutGuard (VAR par: Dialog.Par) Охрана для команды Strikeout. PROCEDURE ToggleNoFocus Переключает режим контейнера с фокусируемый на нефокусируемый и обратно (см. Контейнеры). PROCEDURE ToggleNoFocusGuard (VAR par: Dialog.Par) Охрана для команды ToggleNoFocus. PROCEDURE TypeNotifier (op, from, to: INTEGER) PROCEDURE TypefaceGuard (VAR par: Dialog.Par) Охрана для команды Font. PROCEDURE Underline Присваивает выделенному фрагменту подчеркнутый стиль. PROCEDURE UnderlineGuard (VAR par: Dialog.Par) Охрана для команды Underline. PROCEDURE Undo Отменяет самую последнюю команду. PROCEDURE UndoGuard (VAR par: Dialog.Par) Охрана для команды Undo. PROCEDURE UpdateAll PROCEDURE WidthGuard (VAR par: Dialog.Par) Охрана, выставляющая par.readOnly, если layout.hType # 0, то есть если ширина не фиксирована. PROCEDURE WindowGuard (VAR par: Dialog.Par)
Std/Docu/ru/Cmds.odc
StdCoder ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdCoder; IMPORT TextModels, Views, Dialog; TYPE ParList = RECORD list: Dialog.Selection; storeAs: Dialog.String END; VAR par: ParList; PROCEDURE CloseDialog; PROCEDURE Decode; PROCEDURE DecodeAllFromText (text: TextModels.Model; beg: INTEGER; ask: BOOLEAN); PROCEDURE EncodeDocument; PROCEDURE EncodeFile; PROCEDURE EncodeFileList; PROCEDURE EncodeFocus; PROCEDURE EncodeSelection; PROCEDURE EncodedInText (text: TextModels.Model; beg: INTEGER): TextModels.Model; PROCEDURE EncodedView (v: Views.View): TextModels.Model; PROCEDURE ListEncodedMaterial; PROCEDURE Select (op, from, to: INTEGER); PROCEDURE StoreAll; PROCEDURE StoreSelection; PROCEDURE StoreSelectionGuard (VAR p: Dialog.Par); PROCEDURE StoreSingle; PROCEDURE StoreSingleGuard (VAR p: Dialog.Par); END StdCoder. StdCoder (или просто Coder) может быть использован для кодирования в текстовую форму документа, вьюшки, фрагмента текста или файлов. В кодировке используются символы, которые гарантировано не будут изменены никакой почтовой системой. Белые символы (пробелы, табуляции, символы новой строки и т.п.) могут добавляться или удаляться как угодно, поскольку они игнорируются при декодировании. После декодирования документа или фрагмента текста будет открыто новое окно. Файлы сохраняются на диск. Cледующие пункты меню являются стандартными для меню Инструменты (Tools): "Кодировать документ" "" "StdCoder.EncodeDocument" "StdCmds.WindowGuard" "Кодировать выделение" "" "StdCoder.EncodeSelection" "TextCmds.SelectionGuard" "Кодировать файл..." "" "StdCoder.EncodeFile" "" "Кодировать список файлов..." "" "StdCoder.EncodeFileList" "TextCmds.SelectionGuard" "Декодировать..." "" "StdCoder.Decode" "TextCmds.FocusGuard" "О закодированном материале..." "" "StdCoder.ListEncodedMaterial" "TextCmds.FocusGuard" PROCEDURE EncodeDocument Охрана: StdCmds.WindowGuard Кодирует документ, находящийся в переднем окне, и открывает новое окно со сгенерированным кодом. PROCEDURE EncodeSelection Охрана: TextCmds.SelectionGuard Кодирует выделенный фрагмент текста и открывает новое окно со сгенерированным кодом. PROCEDURE EncodeFile Кодирует один файл, указанный через стандартный диалог открытия файла, и открывает новое окно со сгенерированным кодом. PROCEDURE EncodeFileList Охрана: TextCmds.SelectionGuard Кодирует несколько файлов и открывает новое окно со сгенерированным кодом. Должен быть выделен список корректных имен файлов. Имена файлов должны быть заданы их полным именем пути относительно директории Блэкбокса. Используйте литеру "/" для разделения отдельных частей имени пути. (Пример: Std/Code/Coder.) Имя пути сохраняется вместе с пакетом, чтобы упростить декодирование пакетов, состоящих из многих файлов. Однако иногда файл хранится в другом месте, чем то, куда его нужно будет установить. В таком случае можно задать имя пути для его места назначения. Имя пути, которое будет использовано при декодировании, указывается после стрелки "=>". Пример: NewStd/Code/NewCoder => Std/Code/Coder указывает для кодирования файл NewCoder в директории NewStd/Code, но для декодирования будет использовано имя Std/Code/Coder. PROCEDURE Decode Охрана: TextCmds.FocusGuard Декодирует информацию из закодированного материала в переднем окне. Команда ищет цепочку литер "StdCoder.Decode", которую считает началом кода. Это означает, что самому коду могут предшествовать заголовки электронной почты и т.п. Если в переднем окне выделен текст, сканирование начинается с начала выделенного фрагмента. В зависимости от типа закодированных данных, т.е. от команды, использованной для кодирования, произойдет одно из следующих действий: - Если закодирован документ (EncodeDocument, EncodeSelection), он будет открыт в новом окне. - Если закодирован отдельный файл (EncodeFile), будет открыт стандартный диалог сохранения, позволяющий пользователю сохранить файл. - Если закодирован список файлов (EncodeFileList), будет открыт специальный диалог, позводяющий пользователю выбрать файлы для декодирования. Имена путей, включенные во время кодирования, показаны в списке. В нем можно выбрать один или несколько файлов. После нажатия командной кнопки выбранные файлы будут декодированы. Если выбран только один файл, имя пути может быть изменено или может быть использован стандартный диалог сохранения для показа иерархии директорий. Другой командной кнопкой все файлы могут быть декодированы и сохранены под указанными в списке именами, независимо от выделения. Примечание: Диалог следует всегда закрывать, используя кнопку отмены, чтобы позволить модулю StdCoder освободить ресурсы, временно выделенные для организации диалога. PROCEDURE ListEncodedMaterial Охрана: TextCmds.FocusGuard Открывает текст с информацией о том, что закодировано в тексте, который находится в переднем окне. Подобно Decode, команда ищет тег, обозначающий начало кода. В программном интерфейсе доступны еще две процедуры: PROCEDURE DecodeAllFromText (text: TextModels.Model; beg: INTEGER; ask: BOOLEAN); Работает подобно Decode, но вместо фокуса использует текст, переданный в параметре text. Поиск тега начинается с позиции beg. Подобно Decode, закодированые документы открываются в окнах, а одиночные файлы сохраняются с помощью стандартного диалога. Если код генерировался командой EncodeFileList, поведение определяется значением параметра ask. Если передано TRUE, открывается диалог, и управление передается пользователю. Если передано FALSE, диалог не открывается, а все файлы декодируются и устанавливаются под именами, сохраненными в коде. Такое поведение соответствует нажатию кнопки "Decode All" в диалоге. PROCEDURE EncodedView (v: Views.View): TextModels.Model; Генерирует текст, кодирующий переданную вьюшку. PROCEDURE EncodedInText (text: TextModels.Model; beg: INTEGER): TextModels.Model; Генерирует текст с информацией о материале, закодированном в тексте text.
Std/Docu/ru/Coder.odc
StdDebug ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdDebug; END StdDebug. Для распространяемых версий приложений Блэкбокса или компонентов используйте эту ограниченную версию отладчика. Запрещается распространять полный отладчик (DevDebug). <Прим. перев.: начиная с версии 1.5, BlackBox распространяется в исходниках. Ознакомьтесь с лицензией от Oberon Microsystems для получения подробной информации.> Эта ограниченная версия не позволяет бродить по указателям и т.п., здесь только создается пассивное сообщение о состоянии при ошибке. Текстовый документ можно сохранить, что позволяет пользователю отсылать разработчику информацию об ошибке (например, с помощью StdCoder). StdDebug устанавливается при запуске Блэкбокса, если не найден полный DevDebug.
Std/Docu/ru/Debug.odc
StdETHConv ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdETHConv; IMPORT Files, Stores, TextModels; PROCEDURE ImportETHDoc (f: Files.File; OUT s: Stores.Store); PROCEDURE ImportOberon (f: Files.File): TextModels.Model; END StdETHConv. Модуль StdETHConv предоставляет конвертер для текстовых файлов ETHOberonV4. PROCEDURE ImportETHDoc (f: Files.File; OUT s: Stores.Store) Импортер текстовых файлов OberonV4. Может быть зарегистрирован в модуле Config с помощью следующих инструкций: Windows: Converters.Register("StdETHConv.ImportETHDoc", "", "TextViews.View", ".ETH", {}) Mac OS: Converters.Register("StdETHConv.ImportETHDoc", "", "TextViews.View", ".Ob.", {}) PROCEDURE ImportOberon (f: Files.File): TextModels.Model Напрямую преобразует текстовый файл OberonV4 в текст Блэкбокса без использования механизма конвертеров модуля Converters.
Std/Docu/ru/ETHConv.odc
StdFolds ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdFolds; IMPORT TextModels, Views, Dialog; CONST expanded = FALSE; collapsed = TRUE; TYPE Label = ARRAY 32 OF CHAR; Fold = POINTER TO RECORD (Views.View) leftSide-, collapsed-: BOOLEAN; label-: Label; (fold: Fold) Flip, NEW; (fold: Fold) FlipNested, NEW; (fold: Fold) HiddenText (): TextModels.Model, NEW; (fold: Fold) MatchingFold (): Fold, NEW END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) New (collapsed: BOOLEAN; label: Label; hiddenText: TextModels.Model): Fold, NEW, ABSTRACT END; VAR foldData: RECORD nested, all: BOOLEAN; findLabel, newLabel: Label END; dir-, stdDir-: Directory; PROCEDURE CollapseFolds (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR); PROCEDURE ExpandFolds (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR); PROCEDURE Collapse; PROCEDURE Expand; PROCEDURE ZoomOut; PROCEDURE ZoomIn; PROCEDURE Overlaps (text: TextModels.Model; beg, end: INTEGER): BOOLEAN; PROCEDURE Insert (text: TextModels.Model; label: Label; beg, end: INTEGER; collapsed: BOOLEAN); PROCEDURE CreateGuard (VAR par: Dialog.Par); PROCEDURE Create (state: INTEGER); PROCEDURE SetDir (d: Directory); PROCEDURE FindFirstFold; PROCEDURE FindNextFold; PROCEDURE CollapseLabel; PROCEDURE ExpandLabel; PROCEDURE SetLabel; PROCEDURE SetLabelGuard (VAR p: Dialog.Par); PROCEDURE FindLabelGuard (VAR par: Dialog.Par); END StdFolds. Складка это пара специальных объектов отрисовки (вьюшек; будем называть их левой и правой вьюшками складки; в оригинале сами эти вьюшки тоже называются складками/fold, что иногда неудобно прим. ред.). Такие вьюшки имеют смысл только при вставке парой в текст. Пара ограничивает один (видимый) фрагмент текста, скрывая в себе другой (скрытый). Клик по фрагменту текста между правой и левой вьюшкой складки делает видимый фрагмент скрытым и наоборот. При повторном клике складка возвращается в исходное состояние. Поскольку изначальное назначение складок скрывать длинные фрагменты текста, заменяя их более короткими заголовками, говорят, что складки развернуты или свернуты. Попробуйте! Это фрагмент текста, спрятанный в складкетекст между вьюшками свёрнутой складки Складки могут быть вложенными, но фрагменты разных складок не должны перекрываться частично. Иерархически вложенные складки часто используются в текстах программ. Если скрывать последовательности операторов в складках, оставляя видимыми короткие комментарии, то получающийся программный текст может исследоваться интерактивно по принципу сверху-вниз. Попробуйте этот пример! PROCEDURE Enter (id: INTEGER; name: TextMappers.String; value: REAL); VAR n, h, p: Node; BEGIN NEW(n); n.id := id; n.name := name; n.value := value;создание нового узла n h := list; p := NIL; WHILE (h # NIL) & (h.id <= id) DO p := h; h := h.next END;поиск позиции в списке IF p # NIL THEN p.next := nвставка между p и h ELSE list := nвставка в начало END; n.next := hвставка в список END Enter;ввод нового значения в список Избежать многократных кликов при исследовании глубокой иерархии складок можно, прижимая при клике клавишу Ctrl(Windows)/Option(Mac). Тогда разворачиваются или сворачиваются все вложенные складки. К работе со складками имеют отношение следующие пункты меню. Create Fold (Создать складку) в меню Tools (Инструменты) вставляет новую пару вьюшек складки вокруг выделенного текста. Развернуть все (Expand All) в том же меню разворачивает все складки в тексте, находящемся в фокусе. Аналогично, Свернуть все (Collapse All) сворачивает все складки в тексте, находящемся в фокусе. Команда Fold... (Складка...) в меню Tools (Инструменты) открывает диалог-инспектор, позволяющий управлять складками в тексте, находящемся в фокусе. Инспектор выглядит так: Find First ищет в тексте первое вхождение складок. Если отмечена опция All, то будет найдена и выделена самая первая складка в тексте. Иначе ищется складка с меткой, равной цепочке литер в поле Find. Find Next ищет следующую складку по тем же критериям, что и Find First. Collapse сворачивает все складки в тексте, находящемся в фокусе, которые отвечают критериям поиска, заданным элементами All и Find. Если отмечена опция Nested, то ищутся и вложенные складки, и они тоже сворачиваются. Expand разворачивает складки, ипользуя опции All, Find, Nested аналогично команде Collapse. Когда складка найдена или выделена пользователем, ее метка показывается в поле около кнопки SetLabel. Можно изменить метку, введя в поле новую и нажав SetLabel. Для описания пред- и постусловий процедур, экпортируемых из StdFolds, ниже используются следующие псевдопроцедуры: Pos(f) позиция вьюшки складки f в содержащем ее тексте. 0 <= Pos(f) < text.Length(). Stretch(p1, p2) фрагмент текста [p1,p2), если p1<p2, иначе фрагмент текста [p2, p1). Flipped(f) обозначает складку в состоянии, противоположном текущему: f.state = collapsed <=> Flipped(f).state = expanded. Типичные команды меню (в стандартной конфигурации Блэкбокса от поставщика в меню Tools (Инструменты) некоторые команды могут быть опущены): MENU "Create Fold" "" "StdFolds.Create(1)" "StdFolds.CreateGuard" "Expand All" "" "StdFolds.Expand" "" "Collapse All" "" "StdFolds.Collapse" "" "Fold..." "" "StdCmds.OpenToolDialog('Std/Rsrc/Folds', 'Zoom')" "" END CONST collapsed, expanded Возможные значения поля Fold.collapsed. TYPE Label Тип литерных цепочек для значений метки. TYPE Fold (Views.View) Тип вьюшек складки. leftSide-: BOOLEAN Сообщает, является ли вьюшка левой в своей паре или правой. collapsed-: BOOLEAN Сообщает, свернута складка или нет. label-: Label Литерная цепочка, показывающая метку складки. Если у складки метки нет, то label = "". PROCEDURE (fold: Fold) Flip NEW Изменяет состояние складки. Фрагмент текста S между вьюшкой fold и fold.MatchingFold() заменяется скрытым текстом fold.HiddenText(). Фрагмент S становится новым скрытым текстом. Предусловие fold # NIL 20 Постусловие (fold.MatchingFold() # NIL) & fold.collapsed' ~fold.collapsed (fold.MatchingFold() # NIL) & ~fold.collapsed' fold.collapsed fold.MatchingFold() = NIL no effect PROCEDURE (fold: Fold) FlipNested NEW Изменяет состояние этой складки и всех таких складок f между fold и fold.MatchingFold(), для которых f.state=fold.state. Предусловие fold # NIL 20 Постусловие (fold.MatchingFold() # NIL) & fold.collapsed' ~fold.collapsed For all folds f between fold and fold.MatchingFold(): ~f.collapsed (fold.MatchingFold() # NIL) & ~fold.collapsed' fold.collapsed For all folds f between fold and fold.MatchingFold(): f.collapsed fold.MatchingFold() = NIL no effect PROCEDURE (fold: Fold) HiddenText (): TextModels.Model NEW Возвращает фрагмент текста, скрытый в данный момент скрыт парой (fold, fold.MatchingFold()). Текст нельзя изменять. Если скрытый текст имеет нулевую длину, возвращается NIL. Предусловие fold # NIL 20 Постусловие fold.MatchingFold() # NIL [ let p1 := Pos(Flipped(fold)), p2 := Pos(Flipped(fold).MatchingFold() ] ABS(p2 - p1) = 1 => result = NIL ABS(p2 - p1) > 1 => result = Stretch(p1, p2) fold.MatchingFold() = NIL result = NIL PROCEDURE (fold: Fold) MatchingFold (): Fold NEW Возвращает вьюшку, парную для fold, или NIL, если таковой не найдено. Предусловие fold # NIL 20 Постусловие ~(fold.context IS TextModels.Context) result = NIL fold.context IS TextModels.Context (fold.kind = left) & (result.kind = right) & Pos(fold) < Pos(result) & (For all folds f with Pos(fold) < Pos(f) < Pos(result): (f.MatchingFold() # NIL) & (Pos(fold) < Pos(f.MatchingFold() < Pos(result)) OR (fold.kind = right) & (result.kind = left) & (Pos(fold) > Pos(result) & (For all folds f with Pos(result) < Pos(f) < Pos(fold): (f.Matching # NIL) & (Pos(result) < Pos(f.MatchingFold() < Pos(fold)) OR result = NIL TYPE Directory ABSTRACT Фабричныйобъект для складочных вьюшек. PROCEDURE (d: Directory) New (collapsed: BOOLEAN; IN label: Label; hiddenText: TextModels.Model): Fold NEW, ABSTRACT Создает новую складочную вьюшку в состоянии collapsed, c меткой label, и со скрытым текстом hiddenText. Если hiddenText = NIL, создается правая вьюшка, иначе левая. Постусловие result.leftSide = (hiddenText # NIL) result.collapsed = collapsed result.label = label result.HiddenText() = hiddenText PROCEDURE CollapseFolds (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR) Если nested истинно и label="", то все развернутые складки в тексте text будут свернуты. Если ~nested, то свернуты будут только самые внешние складки в иерархиях вложеннных складок. Если label#"", то будут свернуты только складки с меткой label. Предусловие text # NIL 20 PROCEDURE ExpandFolds (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR) Если nested истинно и label="", то все свернутые складки в тексте text будут развернуты. Если ~nested, то развернуты будут только самые внешние складки в иерархиях вложеннных складок. Если label#"", то будут развернуты только складки с меткой label. Предусловие text # NIL 20 PROCEDURE Collapse Охрана: TextCmds.FocusGuard Сворачивает все вьюшки складок в тексте, находящемся в фокусе. PROCEDURE Expand Охрана: TextCmds.FocusGuard Разворачивает все вьюшки складок в тексте, находящемся в фокусе. PROCEDURE ZoomOut Охрана: TextCmds.FocusGuard Сворачивает все самые внешние развернутые складки в тексте, находящемся в фокусе. PROCEDURE ZoomIn Охрана: TextCmds.FocusGuard Разворачивает все самые внешние свернутые складки в тексте, находящемся в фокусе. PROCEDURE Overlaps (text: TextModels.Model; beg, end: INTEGER): BOOLEAN Возвращает TRUE, если фрагмент [beg,end) текста text частично перекрывает пару вьюшек некоторой складки. Предусловие text # NIL 20 (beg >= 0) & (end <= text.Length()) & (beg <= end) 21 PROCEDURE Insert (text: TextModels.Model; IN label: Label; beg, end: INTEGER; collapsed: BOOLEAN) Вставляет в текст text вокруг фрагмент [beg,end) новую пару (f1, f2) вьюшек, образующих складку. Флаг collapsed определяет, будет ли складка создана в свернутом или развернутом состоянии. Предусловие text # NIL 20 (beg >= 0) & (end <= text.Length()) & (beg <= end) 21 Постусловие фрагмент текста [beg,end) не перекрывает частично пару складок Pos(f1) = beg Pos(f2) = end+1 f1.MatchingFold() = f2 f1.collapsed = f2.collapsed f1.HiddenText() = NIL фрагмент текста [beg,end) частично перекрывает пару складок ничего не происходит PROCEDURE CreateGuard (VAR par: Dialog.Par) Устанавливает par.disabled в TRUE , когда выделенный фрагмент в тексте, находящемся в фокусе, частично перекрывает пару (f, Matching(f)) вьюшек складки. Кроме того, par.disabled устанавливается в TRUE, если текст, находящийся в фокусе, открыт в режимах просмотра или маски, то есть если текст нельзя править. PROCEDURE Create (state: INTEGER) Если охрана CreateGuard допускает, то создает новую пару вьюшек складки и вставляет их в текст, находящийся в фокусе, вокруг выделенного фрагмента или вокрут текстового курсора. Вызывает Insert(FocusText,selBeg,selEnd,state). При state = 0 создается свернутая складка, при state = 1 развернутая. Предусловие state IN {0, 1) Постусловие state = 0 result.collapsed state = 1 ~result.collapsed PROCEDURE SetDir (d: Directory) Устанавливает фабричный объект. Следующие переменные и процедуры используются только диалогом-инспектором для вьюшек типа StdFolds.View: VAR foldData: RECORD nested, all: BOOLEAN; findLabel, newLabel: Label END; PROCEDURE FindFirstFold; PROCEDURE FindNextFold; PROCEDURE CollapseLabel; PROCEDURE ExpandLabel; PROCEDURE SetLabel; PROCEDURE SetLabelGuard (VAR p: Dialog.Par); PROCEDURE FindLabelGuard (VAR par: Dialog.Par);
Std/Docu/ru/Folds.odc
StdHeaders ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-30 DEFINITION StdHeaders; IMPORT Dialog, Views, Fonts, Properties; CONST alternate = 0; number = 1; head = 2; foot = 3; showFoot = 4; TYPE Prop = POINTER TO RECORD (Properties.Property) alternate: BOOLEAN; showFoot: BOOLEAN; number: NumberInfo; head, foot: Banner END; Banner = RECORD left, right: ARRAY 128 OF CHAR; gap: INTEGER END; NumberInfo = RECORD new: BOOLEAN; first: INTEGER END; VAR dialog: RECORD alternate, showFoot: BOOLEAN; number: NumberInfo; head, foot: Banner END; PROCEDURE New (p: Prop; f: Fonts.Font): Views.View; PROCEDURE Deposit; PROCEDURE InitDialog; PROCEDURE NewNumberGuard (VAR par: Dialog.Par); PROCEDURE AlternateGuard (VAR par: Dialog.Par); PROCEDURE HeaderGuard (VAR par: Dialog.Par); PROCEDURE Set; END StdHeaders. Этот модуль реализует объекты отрисовки (вьюшки), которые можно вставлять в текстовые документы Блэкбокса, чтобы задать верхний и нижний колонтитулы для печати. Обычная команда меню: "Insert Header" "" "StdHeaders.Deposit; StdCmds.PasteView" "TextCmds.FocusGuard" Вьюшки колонтитулов в тексте обычно невидимы; увидеть их можно в режиме Text->Show Marks (Текст->Показать разметку). Выделив вьюшку и выполнив команду Edit->Object Properties... (Правка->Свойства объекта...), можно открыть список свойств, в котором можно сделать следующие настройки: - "alternate" ("чередовать"): если выбрана эта настройка, то для правых и левых страницы можно задать разные колонтитулы. - "Show Foot" ("Показывать нижний"): если выбрана эта настройка, то вьюшка соответствует нижнему колонтитулу, в противном случае - верхнему (когда он вообще видим). - "Start with new page number" ("Продолжать нумерацию с"): если выбрана эта настройка, то пользователь может ввести номер для страницы, на которой оказалась вьюшка. Это позволяет изменить нумерацию страниц в пределах документа. - "Right Head", "Right Foot", "Left Head", "Left Foot" ("Правый верхний", "Правый нижний", "Левый верхний", "Левый нижний"): эти свойства относятся к правым/левым верхним/нижним колонтитулам. Это литерные цепочки в одну строку. Они могут содержать макросы, описанные ниже. - "Head gap", "Foot gap" ("Отбивка верхнего", "Отбивка нижнего"): задает отбивку (расстояние) верхнего/нижнего колонтитула от основного текста, в пунктах. - "Font..." ("Шрифт"): позволяет выбирать шрифт для колонтитулов. В литерных цепочках "Right Head" и т.д. можно использовать следующие макросы: &p - заменяется номером текущей страницы в арабской нотации &r - заменяется номером текущей страницы в римской нотации &R - то же, но заглавными буквами &a - заменяется буквой латинского алфавита, соответствующей номеру, если номер <= 26, и обычным номером в арабской нотации в противном случае &A - то же, но используются заглавные буквы &d - заменяется датой распечатки &t - заменяется временем распечатки && - заменяется литерой & &; - задает точку разрыва (split point) &f - имя файла с путем/заголовком Эти макросы вычисляются при печати (или при просмотре, когда колонтитулы видны на экране). Макрос "&;" указывает точку разрыва, которая представляет собой позицию в литерной цепочке, где ее нужно как бы раздвинуть в стороны. Например, для цепочки "Левое поле&;Правое поле" часть "Левое поле" прижмется к левому краю, а часть "Правое поле" к правому краю страницы. Точка разрыва играет роль пружины, раздвигающей левую и правую части в стороны. CONST alternate, number, head, foot, showFoot Номера свойств для свойств, которые поддерживаются вьюшками колонтитулов. TYPE Prop (Properties.Property) Дескриптор свойств для вьюшек колонтитулов. alternate: BOOLEAN Определяет, являются ли разными колонтитулы у левых и правых страниц. showFoot: BOOLEAN Определяет, печатать ли нижний колонтитул. number: NumberInfo Определяет формат номеров страниц. head, foot: Banner Определяет, как печатаются верхние и нижние колонтитулы. TYPE Banner Задает верхний или нижний колонтитул страницы (или пары страниц, если выбрано "alternate"). left, right: ARRAY 128 OF CHAR Цепочки литер для левого и правого колонтитула (верхнего или нижнего). Цепочки могут содержать макросы, описанные выше. gap: INTEGER gap >= 0 Отбивка (расстояние) колонтитула от основного текста. TYPE NumberInfo Задает способ нумерации страниц. new: BOOLEAN Указывает, что нумерация страниц начинается заново, с номера first. first: INTEGER first >= 0 Начальный номер, который используется для страницы, в текст которой вставлена вьюшка колонтитула. VAR dialog Запись для организации обмена данными с редактором свойств (см. interactor, propertysheet). alternate: BOOLEAN Определяет, являются ли разными колонтитулы у левых и правых страниц. showFoot: BOOLEAN Определяет, является ли эта вьюшка нижним колонтитулом. number: NumberInfo Определяет формат номеров страниц. head, foot: Banner Определяет, как печатаются верхние и нижние колонтитулы. PROCEDURE New (p: Prop; f: Fonts.Font): Views.View Создает новую вьюшку-колонтитул с заданными свойствами. PROCEDURE Deposit Помещает новую вьюшку колонтитула в глобальную очередь (обычно перед вставкой в документ). Следующие процедуры используются в диалоге редактора свойств (диалоговая форма Std/Rsrc/Headers): PROCEDURE InitDialog PROCEDURE NewNumberGuard (VAR par: Dialog.Par) PROCEDURE AlternateGuard (VAR par: Dialog.Par) PROCEDURE HeaderGuard (VAR par: Dialog.Par) PROCEDURE Set
Std/Docu/ru/Headers.odc
StdInterpreter ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-18. DEFINITION StdInterpreter; END StdInterpreter. Модуль StdInterpreter предоставляет в Блэкбоксе дополнительный сервис: вызов последовательностей некоторых типов процедур Компонентного Паскаля, которые (последовательности) заданы в виде литерных цепочек. Допустимы инструкции следующих видов: Proc = PROCEDURE ProcI = PROCEDURE (x: INTEGER) ProcII = PROCEDURE (x, y: INTEGER) ProcS = PROCEDURE (s: ARRAY OF CHAR) ProcSI = PROCEDURE (s: ARRAY OF CHAR; x: INTEGER) ProcSII = PROCEDURE (s: ARRAY OF CHAR; x, y: INTEGER) ProcSS = PROCEDURE (s, t: ARRAY OF CHAR) ProcSSI = PROCEDURE (s, t: ARRAY OF CHAR; x: INTEGER) ProcSSII = PROCEDURE (s, t: ARRAY OF CHAR; x, y: INTEGER) ProcR = PROCEDURE (IN s: ARRAY OF CHAR); ProcRI = PROCEDURE (IN s: ARRAY OF CHAR; x: INTEGER); ProcRII = PROCEDURE (IN s: ARRAY OF CHAR; x, y: INTEGER); ProcRS = PROCEDURE (IN s: ARRAY OF CHAR; t: ARRAY OF CHAR); ProcRSI = PROCEDURE (IN s: ARRAY OF CHAR; t: ARRAY OF CHAR; x: INTEGER); ProcRSII = PROCEDURE (IN s: ARRAY OF CHAR; t: ARRAY OF CHAR; x, y: INTEGER); ProcSR = PROCEDURE (s: ARRAY OF CHAR; IN t: ARRAY OF CHAR); ProcSRI = PROCEDURE (s: ARRAY OF CHAR; IN t: ARRAY OF CHAR; x: INTEGER); ProcSRII = PROCEDURE (s: ARRAY OF CHAR; IN t: ARRAY OF CHAR; x, y: INTEGER); ProcRR = PROCEDURE (IN s, t: ARRAY OF CHAR); ProcRRI = PROCEDURE (IN s, t: ARRAY OF CHAR; x: INTEGER); ProcRRII = PROCEDURE (IN s, t: ARRAY OF CHAR; x, y: INTEGER); Например, вызов процедуры типа ProcII с последующим вызовом процедуры типа Proc может быть представлен такой литерной цепочкой: "TurtleDraw.GotoPos(35, 587); TurtleDraw.ShowPen". Такие последовательности инструкций в основном используются в документах, описывающих меню, и при определении элементов управления. Модуль StdInterpreter активируется при запуске Блэкбокса, и его сервис предоставляется через посредство процедуры Dialog.Call.
Std/Docu/ru/Interpreter.odc
StdLinks ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-30 DEFINITION StdLinks; IMPORT Dialog, Views; TYPE Link = POINTER TO RECORD (Views.View) leftSide-: BOOLEAN; (v: Link) GetCmd (OUT cmd: ARRAY OF CHAR), NEW END; Target = POINTER TO RECORD (Views.View) leftSide-: BOOLEAN; (t: Target) GetIdent (OUT ident: ARRAY OF CHAR), NEW END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) NewLink (IN cmd: ARRAY OF CHAR): Link, NEW, ABSTRACT; (d: Directory) NewTarget (IN ident: ARRAY OF CHAR): Target, NEW, ABSTRACT END; VAR par-: Link; dir-, stdDir-: Directory; PROCEDURE CreateGuard (VAR par: Dialog.Par); PROCEDURE CreateLink; PROCEDURE CreateTarget; PROCEDURE ShowTarget (ident: ARRAY OF CHAR); PROCEDURE SetDir (d: Directory); END StdLinks. Ссылка это пара специальных объектов отрисовки (вьюшек; в оригинале сами эти вьюшки тоже называются ссылками/links, что иногда неудобно прим. ред.), имеющих смысл только в тексте, ограничивающих фрагмент этого текста и содержащих некоторую команду. Вот пример ссылки: Ссылканаруководствопользователя Если слева и справа от синего фрагмента ничего особенного не видно, то нужно выполнить команду Text->Show Marks (Текст->Показать разметку). Если кликнуть по левой или правой вьюшке ссылки, то будет выполнена команда, связанная со ссылкой. Более того, активен также и фрагмент текста между парой вьюшек. Указатель мыши меняет свой вид над активным фрагментом. Если при клике по ссылке прижимать клавишу-модификатор, то две вьюшки преобразуются к исходной текстовой спецификации: <StdCmds.OpenBrowser('System/Docu/ru/User-Man', 'User Manual')>Ссылканаруководствопользователя <> Синтаксис такой: "<" последовательность команд ">" фрагмент текста "<" ">". Последовательность команд обычно состоит из единственной команды StdCmds.OpenBrowser. Однако можно использовать любые команды, например, такие: <Dialog.Beep; Dialog.Beep>beepbeep<> Чтобы превратить эту спецификацию в активную ссылку, нужно выделить ее (начиная от первой литеры "<" и включая последней ">") и затем выполнить Tools->Create Link (Инструменты->Создать ссылку). Понятно, что название ссылка отражает всего лишь наиболее типичное применение таких вьюшек. По сути они пригодны не только для организации ссылок на тексты. Их поведение полностью задается их командной последовательностью. Чтобы использовать ссылочные вьюшки для организации гиперссылок, нужны команды, которые могут открыть заданный текст. Стандартная команда для этого StdCmds.OpenBrowser. Например, команда "StdCmds.OpenBrowser('Obx/Docu/ru/Sys-Map','Карта подсистемы Obx')" открывает оглавление подсистемы Obx в режиме просмотра. Иногда полезно иметь команду, которая прокручивает в окне текст до нужного фрагмента-цели. Цель ограничивается парой специальных вьюшек, которые создаются подобно ссылочным вьюшкам, а команда называется ShowTarget. Чтобы можно было указать фрагмент-цель, который нужно показать, каждому такому фрагменту дают идентифицирующее имя. Например, ссылочные вьюшки, созданные из спецификации <StdLinks.ShowTarget('first target')>показатьцель<> создают ссылку на цель, заданную спецификацией <first target>это первая цель<> MENU "Create Link" "" "StdLinks.CreateLink" "StdLinks.CreateGuard" "Create Target" "" "StdLinks.CreateTarget" "StdLinks.CreateGuard" END TYPE Link (Views.View) Тип ссылочных вьюшек. leftSide-: BOOLEAN Указывает, является ли ссылочная вьюшка левой. PROCEDURE (v: Link) GetCmd (OUT cmd: ARRAY OF CHAR) NEW Возвращает команду, связанную со ссылкой. Предусловие leftSide = (cmd # "") TYPE Target (Views.View) Тип вьюшек для оформления целей. leftSide-: BOOLEAN Указывает, является ли вьюшка левой или правой. PROCEDURE (t: Target) GetIdent (OUT ident: ARRAY OF CHAR) NEW Возвращает идентификатор цели. Предусловие leftSide = (ident # "") TYPE Directory ABSTRACT Тип фабричногообъекта для создания вьюшек, оформляющих ссылки/цели. PROCEDURE (d: Directory) NewLink (IN cmd: ARRAY OF CHAR): Link NEW, ABSTRACT Создает новую ссылочную вьюшку с cmd в качестве командной строки. Если cmd # "", то создается левая вьюшка, иначе правая. PROCEDURE (d: Directory) NewTarget (IN ident: ARRAY OF CHAR): Target NEW, ABSTRACT Создает новую вьюшку для оформления цели с идентификатором ident. Если ident # "", то создается левая вьюшка, иначе правая. VAR par-: Link par # NIL в точности в течение выполнения команды ссылки Через эту переменную команда в ссылке может получить доступ к ее (левой) вьюшке и, следовательно, к ее контексту. VAR dir-, stdDir-: Directory Фабричные объекты для вьюшек, оформляющих ссылки/цели. PROCEDURE CreateGuard (VAR par: Dialog.Par) Процедура охраны меню, используется для CreateLink и CreateTarget. par.disabled устанавливается в FALSE (то есть пункт меню остается активным), если соблюдается следующее: в фокусе находится текстовая вьюшка, и текущий выделенный фрагмент в точности соответствует синтаксису: "<" текст ">" текст "<>". PROCEDURE CreateLink Создает ссылку в тексте, находящемся в фокусе. Для создания ссылки должен быть выделен фрагмент текста со следующим синтаксисом: "<" последовательность команд ">" произвольный текст "<>". Последовательность команд не должна содержать литеры ">". Фрагмент "<" последовательность команд ">" заменяется на левую ссылочную вьюшку. Фрагмент "<>" на правую. Вьюшки, оформляющие ссылку, могут быть показаны/скрыты командами Text>ShowMarks и Text>HideMarks (Текст->Показать разметку и Текст->Скрыть разметку) соответственно. Для редактирования командной последовательности, связанной со ссылкой, нужно кликнуть по ссылке при нажатой клавише модификатора. Это заменит ссылку ее текстовой спецификацией. PROCEDURE CreateTarget Создает фрагмент-цель в тексте, находящемся в фокусе. Для этого должен быть выделен фрагмент текста со следующим синтаксисом: "<" идентификатор цели ">" произвольный текст "<>". Идентификатор цели не должен содержать литеры ">". Фрагмент "<" идентификатор цели ">" заменяется на левую вьюшку. Фрагмент "<>" - на правую. Вьюшки оформления целей могут быть скрыты/показаны командами Text>ShowMarks и Text>HideMarks (Текст->Показать разметку и Текст->Скрыть разметку) соответственно. Для редактирования идентификатора цели нужно кликнуть по одной из ее вьюшек при нажатой клавише-модификаторе. Это заменит цель ее текстовой спецификацией. PROCEDURE ShowTarget (ident: ARRAY OF CHAR) В тексте, находящемся в фокусе, ищет первую вьюшку, оформляющую цель с идентификатором ident. Если цель найдена, текст прокручивается так, чтобы она была видна в первой строке окна, причем фрагмент-цель выделяется. (Примечание: если текст открыт в режиме маски, то выделенный фрагмент не виден.) PROCEDURE SetDir (d: Directory) Устанавливает фабричный объект для вьюшек оформления ссылок/целей.
Std/Docu/ru/Links.odc
StdLoader Этот модуль предназначен только для внутреннего использования в Блэкбоксе.
Std/Docu/ru/Loader.odc
StdLog Редакция перевода: Ф.В.Ткачев, 2010-09-30 DEFINITION StdLog; IMPORT TextViews, Views, TextRulers, TextModels; CONST charCode = -1; decimal = 10; hexadecimal = -2; hideBase = FALSE; showBase = TRUE; VAR buf-: TextModels.Model; defruler-: TextRulers.Ruler; dir-: TextViews.Directory; text-: TextModels.Model; PROCEDURE Bool (x: BOOLEAN); PROCEDURE Char (ch: CHAR); PROCEDURE Int (i: INTEGER); PROCEDURE IntForm (x: LONGINT; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN); PROCEDURE Real (x: REAL); PROCEDURE RealForm (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR); PROCEDURE Set (x: SET); PROCEDURE String (IN str: ARRAY OF CHAR); PROCEDURE ParamMsg (IN msg, p0, p1, p2: ARRAY OF CHAR); PROCEDURE Msg (IN msg: ARRAY OF CHAR); PROCEDURE Tab; PROCEDURE Para; PROCEDURE Ln; PROCEDURE View (v: Views.View); PROCEDURE ViewForm (v: Views.View; w, h: INTEGER); PROCEDURE New; PROCEDURE Open; PROCEDURE Clear; PROCEDURE NewView (): TextViews.View; PROCEDURE SetDefaultRuler (ruler: TextRulers.Ruler); PROCEDURE SetDir (d: TextViews.Directory); END StdLog. Модуль StdLog предоставляет доступ к тексту Рабочего журнала и к процедурам, которые упрощают вывод данных в него. Обычно журнал используется только в процессе разработки программ, пользователи готовых программ обычно с журналом не имеют дела. Окно журнала открывается следующим оператором в процедуре Config.Setup: Dialog.Call("StdLog.Open", "", res) CONST charCode Возможное значение параметра base для процедуры IntForm; задаёт форматирование целых чисел в соответствии с синтаксисом числового представления явных литерных констант Компонентного Паскаля. (Например, 0DX код для line, а 37X код для "7".) CONST decimal Возможное значение параметра base для процедуры IntForm; задаёт форматирование целых чисел как явных десятичных констант. CONST hexadecimal Возможное значение параметра base для процедуры IntForm; задаёт форматирование целых чисел как явных шестнадцатиричных констант. CONST hideBase Возможное значение параметра showBase для процедуры IntForm, требует не показывать индикатор основания. CONST showBase Возможное значение параметра showBase для процедуры IntForm; задаёт вывод индикатора основания. PROCEDURE Bool (x: BOOLEAN) Записывает в журнал значение типа Boolean. За исключением быстродействия эквивалентно следующему фрагменту: IF x THEN String("$TRUE") ELSE String("$FALSE") END PROCEDURE Char (ch: CHAR) Записывает в журнал литерное значение. Для управляющих символов будет записана явная числовая константа (например, 9X для символа табуляции). Для записи в журнал более одной литеры эффективней использовать процедуру String. PROCEDURE Int (i: INTEGER) Записывает в журнал целое значение. За исключением быстродействия эквивалентно следующему фрагменту: IntForm(x, decimal, 0, digitspace, showBase) где digitspace = 8FX. PROCEDURE IntForm (x: LONGINT; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN) Записывает в журнал целое число x. Последовательность цифр, формируемая для представления числа, соответствует основанию base. Полное представление будет состоять из не менее чем minWidth литер, причём избыточные позиции заполняются, если это требуется, слева литерами fillCh. В недесятичном случае можно потребовать включить в представление основание, если указано showBase. Для специального значения base=charCode выводится суффикс основания "X", для base=hexadecimal выводится суффикс "H". Все другие недесятичные основания представляются приписыванием в конце литеры "%", за которой следует десятичное число, соответствующее основанию. Недесятичное представление отрицательных чисел формируется в дополнительном коде по основанию base шириной minWidth литер. Например, x=-3 для base=16 и minWidth=2 выводится как "FD". Предусловие (base = charCode) OR (base = hexadecimal) OR ((base >= 2) & (base <= 16)) 20 minWidth >= 0 22 PROCEDURE Real (x: REAL) Выводит в журнал действительное значение. За исключением быстродействия эквивалентно слеующему фрагменту: WriteRealForm(x, 16, 0, 0, digitspace) где digitspace = 8FX. PROCEDURE RealForm (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR) Выводит в журнал действительное число x. Используется либо представление с фиксированной точкой, либо в научном формате, в зависимости от expW. precision задаёт число допустимых десятичных позиций (обычно 7 для коротких вещественных чисел и 16 для обычных вещественных). minW обозначает минимальную длину представления в литерах. Если необходимо, представление дополняется слева литерами fillCh. Числа всегда округляются до последнего значимого и видимого разряда. expW > 0: научный формат с не менее чем expW разрядами в показателе экспоненты. expW = 0: формат с фиксированной или плавающей точкой в зависимости от x. expW < 0: формат с фиксированной точкой с -expW разрядами после десятичной точки. Подробности см. в описании процедуры Strings.RealToStringForm. Предусловие precision > 0 20 0 <= minW 21 expW <= 3 22 PROCEDURE Set (x: SET) Выводит в журнал значение типа SET (множество). За исключением быстродействия эквивалентно следующему фрагменту: VAR i: INTEGER; Char("{"); i := MIN(SET); WHILE x # {} DO IF i IN x THEN Int(i); EXCL(x, i); IF (i + 2 <= MAX(SET)) & (i + 1 IN x) & (i + 2 IN x) THEN String(".."); x := x - {i + 1, i + 2}; INC(i, 3); WHILE (i <= MAX(SET)) & (i IN x) DO EXCL(x, i); INC(i) END; Int(i - 1) END; IF x # {} THEN String(", ") END END; INC(i) END; Char("}") PROCEDURE String (IN str: ARRAY OF CHAR) Записывает в журнал цепочку литер. PROCEDURE ParamMsg (IN msg, p0, p1, p2: ARRAY OF CHAR) Записывает в журнал параметризованную цепочку литер, транслированную с помощью Dialog.MapParamString. PROCEDURE Msg (IN msg: ARRAY OF CHAR) Записывает в журнал цепочку литер, транслированную с помощью Dialog.MapParamString. За исключением быстродействия эквивалентно следующему фрагменту: ParamMsg(msg, "", "", "") PROCEDURE Tab Записывает в журнал символ табуляции (9X). PROCEDURE Para Записывает в журнал символ абзаца (0EX). После этого обеспечивается, чтобы конец текста журнала был виден пользователю. PROCEDURE Ln Записывает в журнал символ возврата каретки (0DX). После этого обеспечивается, чтобы конец текста журнала был виден пользователю. PROCEDURE View (v: Views.View) Записывает в журнал вьюшку (объект изображения). Размер вьюшки устанавливается в результате взаимодействия текста-контейнера и самой вьюшки. PROCEDURE ViewForm (v: Views.View; w, h: INTEGER) Записывает в журнал вьюшку, принудительно устанавливая её размер равным w и h в универсальных единицах. PROCEDURE New Для внутреннего использования. PROCEDURE Open Открывает окно журнала, если оно не открыто, иначе выводит его поверх других окон. PROCEDURE Clear Очищает текст журнала. PROCEDURE NewView (): TextViews.View Для внутреннего использования. PROCEDURE SetDefaultRuler (ruler: TextRulers.Ruler) Устанавливает линейку по умолчанию. Предусловие ruler # NIL 20 Постусловие defruler = ruler PROCEDURE SetDir (d: TextViews.Directory) Определяет фабричный объект для порождения текстовых вьюшек журнала. Предусловие d # NIL 20 Постусловие dir = d VAR buf-: TextModels.Model Буфер используется каркасом Блэкбокса для минимизации обновлений экрана. VAR defruler-: TextRulers.Ruler Линейка по умолчанию для текста журнала. VAR dir-: TextViews.Directory Для внутреннего использования. VAR text-: TextModels.Model Текст журнала.
Std/Docu/ru/Log.odc
StdLogos Для внутреннего использования (отображения логотипа компании Oberon Microsystems).
Std/Docu/ru/Logos.odc
StdMenuTool ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-24 DEFINITION StdMenuTool; IMPORT TextModels; PROCEDURE UpdateFromText (text: TextModels.Model); PROCEDURE UpdateMenus; PROCEDURE UpdateAllMenus; PROCEDURE ListAllMenus; PROCEDURE ThisMenu; END StdMenuTool. Процедуры данного модуля используются при запуске Блэкбокса для установки меню. Типичные пункты меню: MENU "&Menus" "" "StdCmds.OpenDoc('System/Rsrc/Menus')" "" "&All Menus" "" "StdMenuTool.ListAllMenus" "" "&Update Menus" "" "StdMenuTool.UpdateMenus" "TextCmds.FocusGuard" "U&pdate All Menus" "" "StdMenuTool.UpdateAllMenus" "" END PROCEDURE UpdateFromText (text: TextModels.Model) Очищает все меню и строит новую строку меню в соответствии со спецификацией в параметре text. PROCEDURE UpdateMenus Охрана: TextCmds.FocusGuard Очищает все меню и строит новую строку меню в соответствии со спецификацией в тексте, находящемся в фокусе PROCEDURE UpdateAllMenus Очищает все меню и строит новую строку меню в соответствии со спецификацией в документе System/Rsrc/Menus. PROCEDURE ListAllMenus Строит текст с гиперссылками на все доступные тексты конфигурации меню, то есть к текстам /Rsrc/Menus всех подсистем. PROCEDURE ThisMenu Для внутреннего использования (в гиперссылках инструкций INCLUDE).
Std/Docu/ru/MenuTool.odc
StdScrollers ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-31 DEFINITION StdScrollers; IMPORT Dialog, Properties; CONST horBar = 0; verBar = 1; horHide = 2; verHide = 3; width = 4; height = 5; savePos = 7; showBorder = 6; TYPE Prop = POINTER TO RECORD (Properties.Property) horBar, verBar, horHide, verHide: BOOLEAN; width, height: INTEGER; showBorder, savePos: BOOLEAN END; VAR dialog: RECORD horizontal, vertical: RECORD mode: INTEGER; adapt: BOOLEAN; size: REAL END; showBorder, savePos: BOOLEAN END; PROCEDURE AddScroller; PROCEDURE RemoveScroller; PROCEDURE InitDialog; PROCEDURE Set; PROCEDURE DialogGuard (VAR par: Dialog.Par); PROCEDURE HeightGuard (VAR par: Dialog.Par); PROCEDURE WidthGuard (VAR par: Dialog.Par); PROCEDURE HorAdaptGuard (VAR par: Dialog.Par); PROCEDURE VerAdaptGuard (VAR par: Dialog.Par); END StdScrollers. Модуль StdScrollers предоставляет объекты прокрутки (scroller), представляющие собой вьюшки-обертки (wrapper), которые могут быть обернуты вокруг любого другого объекта отрисовки, чтобы снабдить его горизонтальной и/или вертикальной полоской прокрутки. Например, текстовая вьюшка, вставленная в диалоговую форму, может быть обернута таким объектом прокрутки, чтобы можно было просматривать текст, который целиком не помещается в видимой области. CONST horBar, verBar, horHide, verHide, width, height, savePos, showBorder Элементы свойств для дескриптора Prop. TYPE Prop (Properties.Property) Свойства, описывающие атрибуты объекта прокрутки. horBar: BOOLEAN Имеется ли горизонтальная полоса прокрутки? verBar: BOOLEAN Имеется ли вертикальная полоса прокрутки? horHide: BOOLEAN horHide -> horBar Имеет смысл, только если horBar. Тогда остаются три варианта: ~horBar полоса прокрутки невидима никогда horBar & horHide полоса прокрутки показывается в случае необходимости автоматически horBar & ~horHide полоса прокрутки видна все время verHide: BOOLEAN verHide -> verBar Имеет смысл, только если verBar. Тогда остаются три варианта: ~verBar полоса прокрутки невидима никогда verBar & verHide полоса прокрутки показывается в случае необходимости автоматически verBar & ~verHide полоса прокрутки видна все время width, height: INTEGER width >= 0 & height >= 0 [в универсальных единицах] Размер оборачиваемой вьюшки. Значение 0 означает, что оборачиваемая вьюшка автоматически адаптируется к размеру вьюшки-обертки. Другие значения соответствуют фиксированным размерам. showBorder: BOOLEAN Показывать рамку вокруг оборачиваемой вьюшки. savePos: BOOLEAN Задает сохранение текущей позиции прокрутки при сохранении объекта прокрутки на диск, а также делает прокрутку отменяемой. VAR dialog: RECORD Запись-интерактор для настройки свойств объекта прокрутки для выделенной одиночной вьюшки. horizontal, vertical: RECORD Записи, описывающие поведение полосок прокрутки для обоих направлений. mode: INTEGER mode IN {0, 1, 2} 0: нет полосы прокрутки 1: автоматический показ полосы прокрутки 2: постоянный показ полосы прокрутки adapt: BOOLEAN adapt: установить размер (ширину или высоту) в 0 ~adapt: rсохранить фиксированный размер size: REAL размер в сантиметрах (Dialog.metricSystem) или в дюймах (~Dialog.metricSystem) showBorder, savePos: BOOLEAN Значения, соответствующие дескриптору свойств. PROCEDURE AddScroller Охрана: StdCmds.SingletonGuard Оборачивает выделенную вьюшку объектом прокрутки. PROCEDURE RemoveScroller Охрана: StdCmds.SingletonGuard Удаляет объект прокрутки с обернутой вьюшки (если выделена вьюшка, обернутая таким объектом). PROCEDURE InitDialog Инициализирует запись dialog в соответствии с выделенным объектом прокрутки. PROCEDURE Set Применяет вновь заданные свойства к выделенному объекту прокрутки. PROCEDURE DialogGuard (VAR par: Dialog.Par) PROCEDURE HeightGuard (VAR par: Dialog.Par) PROCEDURE WidthGuard (VAR par: Dialog.Par) PROCEDURE HorAdaptGuard (VAR par: Dialog.Par) PROCEDURE VerAdaptGuard (VAR par: Dialog.Par) Охраны для диалога Std/Rsrc/Scrollers.
Std/Docu/ru/Scrollers.odc
StdStamps ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-31 DEFINITION StdStamps; PROCEDURE Deposit; ...plus some other items used internally... END StdStamps. Вьюшки-штампы показывают дату, когда документ, содержащий такой штамп, был сохранен в последний раз. PROCEDURE Deposit Deposit command for standard stamps. Команда постановки новой стандартной вьюшки-штампа в глобальную очередь (для последующей вставки в документ). ...плюс некоторые другие элементы для внутреннего использования в Блэкбоксе... Клик по вьюшке-штампу показывает историю сохранений документа. Клик при нажатой клавише-модификаторе открывает диалоговое окно, в котором можно редактировать комментарий для текущей сессии.
Std/Docu/ru/Stamps.odc
Карта подсистемы Std ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-31 StdApi API для StdCmds StdClocks аналоговые часы StdCmds команды стандартных меню StdCoder кодировщик ASCII StdDebug минимальный отладчик StdFolds складки StdHeaders верхние / нижние колонтитулы StdLinks гиперссылки StdLog стандартный вывод StdMenuTool инструменты меню StdStamps штампы StdTables элемент управления Таблица StdTabViews объекты закладок StdViewSizer установка размера вьюшки StdETHConv конвертер ETH OberonV4 StdInterpreter служба интерпретатора StdScrollers полосы прокрутки
Std/Docu/ru/Sys-Map.odc
StdTables ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-31. DEFINITION StdTables; IMPORT Ports, Dialog, Views, Properties, Controls; CONST line = 0DX; deselect = -1; select = -2; changed = -3; layoutEditable = 0; dataEditable = 1; selectionStyle = 2; noSelect = 0; cellSelect = 1; rowSelect = 2; colSelect = 3; crossSelect = 4; TYPE Table = RECORD rows-, cols-: INTEGER; (VAR tab: Table) SetSize (rows, cols: INTEGER), NEW; (VAR tab: Table) SetItem (row, col: INTEGER; item: Dialog.String), NEW; (VAR tab: Table) GetItem (row, col: INTEGER; OUT item: Dialog.String), NEW; (VAR tab: Table) SetLabel (col: INTEGER; label: Dialog.String), NEW; (VAR tab: Table) GetLabel (col: INTEGER; OUT label: Dialog.String), NEW; (VAR tab: Table) HasSelection (): BOOLEAN, NEW; (VAR tab: Table) GetSelection (OUT row, col: INTEGER), NEW; (VAR tab: Table) Select (row, col: INTEGER), NEW; (VAR tab: Table) Deselect, NEW; (VAR tab: Table) SetAttr (l, t, r, b: INTEGER; style: SET; weight: INTEGER; color: Ports.Color), NEW; (VAR tab: Table) GetAttr (row, col: INTEGER; OUT style: SET; OUT weight: INTEGER; OUT color: Ports.Color), NEW END; Prop = POINTER TO RECORD (Properties.Property) layoutEditable, dataEditable: BOOLEAN; selectionStyle: INTEGER; (p: Prop) IntersectWith (q: Properties.Property; OUT equal: BOOLEAN) END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) NewControl (p: Controls.Prop): Views.View, ABSTRACT, NEW END; VAR dir-, stdDir-: Directory; text: Dialog.String; dlg: RECORD layoutEditable, dataEditable: BOOLEAN; selectionStyle: Dialog.List END; PROCEDURE InitDialog; PROCEDURE Set; PROCEDURE Guard (idx: INTEGER; VAR par: Dialog.Par); PROCEDURE Notifier (idx, op, from, to: INTEGER); PROCEDURE SetDir (d: Directory); PROCEDURE DepositControl; END StdTables. Модуль StdTables реализует простой элемент управления табличного вида (grid view). Для создания новых таблиц экспортируется фабричныйобъект (StdTables.dir). В качестве интеракторов для таблиц используются записи типа StdTables.Table. Типичная команды меню: "Insert Table" "" "StdTables.DepositControl; StdCmds.PasteView" "StdCmds.PasteViewGuard" Редактор свойств для StdTables такой же, как и для обычных элементов управления. Поля Link, Label, Guard и Notifier используются как обычно. В дополнение к редактору свойств для таблиц имеется специальный диалог, где можно выбрать способ визуализации выделения в таблице. Кроме того, там можно задать, будет ли формат таблицы (ширина столбцов) редактируемым, и будут ли доступны для редактирования данные в ячейках. CONST line Символ новой строки для заголовков столбцов, если заголовок должен быть в несколько строк. CONST deselect Код операции для процедуры-уведомителя. Указывает, что было снято выделение с ячейки в позиции row (ряд) =from и column (столбец)=to. CONST select Код операции для процедуры-уведомителя. Указывает, что пользователь выделил ячейку в позиции row (ряд)=from и column (столбец)=to. CONST changed Код операции для процедуры-уведомителя. Указывает, что пользователь изменил содержимое ячейки в позиции row (ряд)=from и column (столбец) =to. CONST layoutEditable Элемент из множества valid свойства элемента управления (см. поле Prop.valid прим. ред.). Определяет, справедливо ли свойство формат редактируем. CONST dataEditable Элемент из множества valid для некоторого свойства элемента управления. Определяет, справедливо ли свойство данные редактируемы. CONST selectionStyle Элемент из множества valid для некоторого свойства элемента управления. Определяет, справедливо ли свойство стиль выделения. CONST noSelect, cellSelect, rowSelect, colSelect, crossSelect Константы (возможные значения) для свойства стиль выделения. TYPE Table Интеракторы для табличных элементов управления. rows-, cols-: INTEGER (rows >= 0) & (cols >= 0) Количество рядов и столбцов в таблице. PROCEDURE (VAR tab: Table) SetSize (rows, cols: INTEGER), NEW Устанавливает размер таблицы. Предусловие 20 (rows >= 0) & (cols >= 0) 21 ((cols > 0) OR ((cols = 0) & (rows = 0)) PROCEDURE (VAR tab: Table) SetItem (row, col: INTEGER; item: Dialog.String), NEW Устанавливает содержимое ячейки в ряду row и столбце col в значение item. Предусловие 20 Ранее должна была быть вызвана процедура SetSize PROCEDURE (VAR tab: Table) GetItem (row, col: INTEGER; OUT item: Dialog.String), NEW Возвращает содержимое ячейки в ряду row и столбце col. Предусловие 20 Ранее должна была быть вызвана процедура SetSize PROCEDURE (VAR tab: Table) SetLabel (col: INTEGER; label: Dialog.String), NEW Устанавливает заголовок столбца col. Каждое вхождение в label символа StdTables.line начинает новую строку. Предусловие 20 Ранее должна была быть вызвана процедура SetSize PROCEDURE (VAR tab: Table) GetLabel (col: INTEGER; OUT label: Dialog.String), NEW Возвращает заголовок столбца col. Предусловие 20 Ранее должна была быть вызвана процедура SetSize PROCEDURE (VAR tab: Table) HasSelection (): BOOLEAN, NEW Сообщает, есть ли в таблице выделенная ячейка. PROCEDURE (VAR tab: Table) GetSelection (OUT row, col: INTEGER), NEW Возвращает координаты (строку и столбец) выделенной ячейки таблицы. Предусловие 20 Ранее должна была быть вызвана процедура SetSize 21 tab.HasSelection() PROCEDURE (VAR tab: Table) Select (row, col: INTEGER), NEW Выделить позицию row, col. Предусловие 20 Ранее должна была быть вызвана процедура SetSize Постусловие tab.HasSelection() = TRUE PROCEDURE (VAR tab: Table) Deselect, NEW Remove current selection in table, if any. Снимает в таблице текущее выделение, если оно есть. Предусловие 20 Ранее должна была быть вызвана процедура SetSize Постусловие tab.HasSelection() = FALSE PROCEDURE (VAR tab: Table) SetAttr (l, t, r, b: INTEGER; style: SET; weight: INTEGER; color: Ports.Color), NEW Устанавливает атрибуты для диапазона ячеек. style и weight влияют на шрифт текста в ячейке, а color это цвет текста в ячейке. (Подробнее о параметрах style и weight см. Fonts.Font.) Диапазон ячеек задается следующим образом: колонка l и ряд t позиция верхней левой ячейки, колонка r и ряд b позиция нижней правой ячейки диапазона. PROCEDURE (VAR tab: Table) GetAttr (row, col: INTEGER; OUT style: SET; OUT weight: INTEGER; OUT color: Ports.Color), NEW Возвращает текущие значения атрибутов для ячейки таблицы в позиции row, col. Предусловие 20 Ранее должна была быть вызвана процедура SetSize TYPE Prop Свойства, специфичные для таблиц. layoutEditable, dataEditable: BOOLEAN Ширина колонок может редактироваться пользователем; данные в ячейках таблицы могут редактироваться пользователем. selectionStyle: INTEGER Визуальный стиль выделения: noSelect: нет визуального выделения cellSelect: подсвечена выделенная ячейка rowSelect: подсвечены все ячейки в выделенном ряду colSelect: подсвечены все ячейки в выделенном столбце crossSelect: подсвечены все ячейки в выделенных ряду и столбце PROCEDURE (p: Prop) IntersectWith (q: Properties.Property; OUT equal: BOOLEAN) Заменяет свойства p на пересечение свойств p и q. Если они равны, equal устанавливается в TRUE. TYPE Directory Новые таблицы могут создаваться с помощью фабричного объекта StdTables.dir. PROCEDURE (d: Directory) NewControl (p: Controls.Prop): Views.View, ABSTRACT, NEW Создает новую таблицу, используя свойства p. VAR dir-, stdDir-: Directory dir # NIL, stdDir # NIL, stable stdDir = d Фабричный объект и стандартный фабричный объект для таблиц. VAR text: Dialog.String имеет смысл только при редактировании ячейки Содержимое ячейки, редактируемой в данный момент. VAR dlg: RECORD Интерактор для диалога свойств таблицы. PROCEDURE InitDialog Инициализировать диалог свойств таблицы. PROCEDURE Set Применить к таблице свойства, выбранные в диалоге свойств таблицы. PROCEDURE Guard (idx: INTEGER; VAR par: Dialog.Par) Охрана для диалога свойств таблицы. CASE idx OF 0: флаг Разметка редактируема 1: флаг Данные редактируемы 2: список Стиль выделения END PROCEDURE Notifier (idx, op, from, to: INTEGER) Уведомитель для диалога свойств таблицы. CASE idx OF 0: флаг Разметка редактируема 1: флаг Данные редактируемы 2: список Стиль выделения END PROCEDURE SetDir (d: Directory) Установить фабричный объект. Предусловие d # NIL 20 Постусловие stdDir' = NIL stdDir = d dir = d PROCEDURE DepositControl Команда, ставящая новую таблицу в глобальную очередь.
Std/Docu/ru/Tables.odc
StdTabViews ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-31 DEFINITION StdTabViews; IMPORT Views, Dialog, StdCFrames; CONST noTab = -1; TYPE Directory = POINTER TO ABSTRACT RECORD (d: Directory) New (): View, NEW, ABSTRACT END; Frame = POINTER TO ABSTRACT RECORD (StdCFrames.Frame) (f: Frame) GetDispSize (OUT x, y, w, h: INTEGER), NEW, ABSTRACT; (f: Frame) InDispArea (x, y: INTEGER): BOOLEAN, NEW, ABSTRACT; (f: Frame) SetIndex (i: INTEGER), NEW END; FrameDirectory = POINTER TO ABSTRACT RECORD (d: FrameDirectory) GetTabSize (VAR w, h: INTEGER), NEW, ABSTRACT; (d: FrameDirectory) New (): Frame, NEW, ABSTRACT END; View = POINTER TO LIMITED RECORD (Views.View) (tv: View) GetItem (i: INTEGER; OUT label: Dialog.String; OUT v: Views.View), NEW; (tv: View) GetNewFrame (VAR frame: Views.Frame); (tv: View) GetNotifier (OUT notifier: Dialog.String), NEW; (tv: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View); (tv: View) Index (): INTEGER, NEW; (tv: View) Neutralize; (tv: View) NofTabs (): INTEGER, NEW; (tv: View) Restore (f: Views.Frame; l, t, r, b: INTEGER); (tv: View) SetIndex (i: INTEGER), NEW; (tv: View) SetItem (i: INTEGER; label: Dialog.String; v: Views.View), NEW; (tv: View) SetNofTabs (nofTabs: INTEGER), NEW; (tv: View) SetNotifier (IN notifier: ARRAY OF CHAR), NEW END; NotifierProc = PROCEDURE (tv: View; from, to: INTEGER); VAR dir-: Directory; dlg: RECORD name, notifier: Dialog.String; opt: INTEGER END; frameDir-: FrameDirectory; frameStdDir-: FrameDirectory; setFocus: BOOLEAN; stdDir-: Directory; PROCEDURE AddTab; PROCEDURE BeginChanges (tv: View); PROCEDURE Delete; PROCEDURE DeleteGuard (VAR par: Dialog.Par); PROCEDURE Deposit; PROCEDURE EndChanges (tv: View); PROCEDURE Focus (): View; PROCEDURE InitDialog; PROCEDURE LabelGuard (VAR par: Dialog.Par); PROCEDURE LayoutModeGuard (VAR par: Dialog.Par); PROCEDURE Left; PROCEDURE MaskModeGuard (VAR par: Dialog.Par); PROCEDURE ModeNotifier (op, from, to: INTEGER); PROCEDURE NewGuard (VAR par: Dialog.Par); PROCEDURE NotifierGuard (VAR par: Dialog.Par); PROCEDURE Rename; PROCEDURE RenameGuard (VAR par: Dialog.Par); PROCEDURE Right; PROCEDURE SetDir (d: Directory); PROCEDURE SetFrameDir (d: FrameDirectory); PROCEDURE SetGuard (VAR par: Dialog.Par); PROCEDURE SetNotifier; PROCEDURE This (v: Views.View): View; END StdTabViews. Объект отрисовки типа StdTabViews.View предъявляет пользователю набор закладок. Каждая закладка состоит из заголовка и некоторой вьюшки. Когда пользователь кликает по заголовку, показывается содержимое соответствующей вьюшки (ниже такая закладка будет называться передней прим. ред.). Попробуйте проделать это здесь: В этом примере использованы вьюшки FormViews, но можно было бы использовать любой объект типа Views.View. Есть два способа создания StdTabViews: программно или интерактивно, используя графический интерфейс. В большинстве случаев достаточно средств графического интерфейса. Для более сложных случаев предусмотрен программный интерфейс, описанный далее. Чтобы воспользоваться графическим интерфейсом, нужно в документ или на форму вставить StdTabViews.View. Это делается командой меню Controls -> Insert Tab View (Формы -> Вставить закладки). Новый объект StdTabViews.View содержит две закладки, названные Tab1 и Tab2, и с каждой из них связана (пустая) диалоговая форма FormViews.View. Вновь созданные закладки выглядят так: Этот пример полностью функционален, хотя и не слишком интересен. Если StdTabViews.View находится в фокусе, то каждую закладку можно редактировать как обычную диалоговую форму. Можно мышкой бросать на нее элементы управления и перемещать их, а также менять их свойства. В этом можно убедиться, экспериментируя с объектом выше. Чтобы добавить, удалить или изменить имя закладки, нужно открыть редактор свойств для типа StdTabViews. Для этого нужно выделить объект закладок и выполнить Edit->Object Properties... (Правка->Свойства объекта...). Редактор свойств выглядит так: Кнопки и поля имеют следующие значения: <- Клик по этой кнопке перемещает переднюю закладку на одну позицию влево. То есть меняется порядок закладок. -> Клик по этой кнопке перемещает переднюю закладку на одну позицию вправо. То есть меняется порядок закладок. Label Показывает заголовок передней закладки. Rename Меняет заголовок передней закладки на текст, введенный в поле Label. Пустой заголовок не допускается. New Tab Добавляет новую закладку. Ее заголовком будет текст в поле Label. Если там пусто, новой закладки создано не будет. Delete Удаляет переднюю закладку. Notifier Показывает имя процедуры-уведомителя, которая связана с объектом закладок. Set Использует имя в поле Notifier для установки процедуры-уведомителя объекта закладок. All tabs in Layout Mode Переводит все закладки в режим разметки. Это один из режимов работы с контейнерами, в нем допускается редактирование. Подробнее о режимах контейнеров см. ниже раздел О режимах контейнеров. All tabs in Mask Mode Переводит все закладки в режим маски. Это один из режимов работы с контейнерами, в нем невозможно выделить вьюшки, содержащиеся в контейнере. Подробнее о режимах контейнеров см. ниже раздел О режимах контейнеров. О процедурах-уведомителях Уведомители для StdTabViews отличаются от уведомителей для обычных элементов управления Controls, но работают похожим образом. Отличается сигнатура (см. тип StdTabViews.NotifierProc), и посылается только один тип уведомления. Уведомитель вызывается, только когда другая закладка становится передней. При вызове параметр tv содержит объект закладок StdTabViews.View, который послал уведомление, from и to старая и новая передняя закладка соответственно. При сохранении объекта закладок сохраняется и номер передней закладки, так что когда объект закладок вновь загружается, передняя закладка устанавливается в соответствии с сохраненным значением индекса. Это позволяет проектировщику диалога управлять тем, какая из закладок окажется передней при открытии диалога. Это также дает способ найти в диалоге объект закладок StdTabViews.View. Когда при загрузке первый раз устанавливает передняя закладка, вызывается обработчик с параметром tv, равным новому StdTabViews.View, параметру from присваивается константа noTab и параметру to присваивается индекс передней закладки, сохраненный при выгрузке. Это означает, что каждый раз при открытии документа с объектом StdTabViews.View будет вызываться уведомитель, и это позволяет приложению при необходимости связаться с StdTabViews.View. Это простой способ получить доступ к программному интерфейсу, описанному ниже. О режимах контейнеров Контейнеры могут иметь различные режимы. FormViews.View является контейнером и может, например, быть переведен в режим разметки или в режим маски. В режиме разметки можно выделять вьюшки, содержащиеся в контейнере, такие как элементы управления, и перемещать их. С другой стороны, в режиме маски нельзя выделять или перемещать вьюшки, содержащиеся в контейнере. Режимы контейнера могут переключаться с помощью меню Dev (Программирование), но обычно это не нужно. Обычный способ сохранить документ в режиме редактирования или разметки, а затем открыть его в требуемом режиме командами из StdCmds. Например, диалоги обычно сохраняются в режиме разметки и затем открываются в режиме маски командой StdCmds.OpenAuxDialog. Проблема в том, что StdTabViews нарушает эту схему: ведь каждая закладка может содержать свой собственный контейнер в его собственном режиме. Поэтому необходимо использовать меню Dev (Программирование), чтобы перевести закладки в правильный режим перед сохранением диалога. Чтобы использовать режимы контейнера и меню Dev (Программирование), нужно кое-что знать о контейнерах. Чтобы обойти это препятствие, предусмотрены переключатели "All tabs in Layout Mode" ("Все закладки в режиме разметки") и "All tabs in Mask Mode" ("Все закладки в режиме маски"). Эти кнопки позволяют установить все закладки в режим маски перед сохранением диалога или все закладки в режим разметки для правки диалога, что избавляет от необходимости обращаться к меню Dev (Программирование). CONST noTab Константа используется для присваивания параметру from в при вызове процедуры-уведомителя, когда загружается StdTabViews.View. TYPE View = POINTER TO LIMITED RECORD (Views.View) Позволяет пользователю выбирать различные вьюшки, кликая по закладкам. PROCEDURE (tv: View) SetItem (i: INTEGER; label: Dialog.String; v: Views.View) NEW Добавляет новую закладку в tv. Новая закладка получает label в качестве заголовка и v в качестве своей вьюшки. i указывает позицию закладки среди других закладок. Если i больше чем tv.NofTabs(), то количество закладок в tv увеличивается, если нет, то старая закладка в позиции i заменяется на новую. Перед добавлением в tv делается глубокая копия v. Предусловие i >= 0 label # "" v # NIL PROCEDURE (tv: View) GetItem (i: INTEGER; OUT label: Dialog.String; OUT v: Views.View) NEW Возвращает заголовок и вьюшку i-й закладки. Предусловие i >= 0 i < tv.NofTabs() PROCEDURE (tv: View) SetNofTabs (nofTabs: INTEGER) NEW Обеспечивает наличие в tv в точности nofTabs закладок. Отметим, что SetItem тоже увеличивает количество закладок в View при необходимости, так что вызывать SetNofTabs реально нужно только для уменьшения числа закладок. Предусловие nofTabs >= 0 Постусловие tv.NofTabs() = nofTabs PROCEDURE (tv: View) NofTabs (): INTEGER, NEW; NEW Возвращает количество закладок в tv. Постусловие Возвращаемое значение >= 0 PROCEDURE (tv: View) SetIndex (i: INTEGER) NEW Делает i-ю закладку в tv передней, и отрисовывает tv. Когда закладки переключаются вызовом SetIndex, уведомитель не вызывается. Предусловие i >= 0 i < tv.NofTabs() Постусловие tv.Index() = i PROCEDURE (tv: View) Index (): INTEGER NEW Возвращает номер передней закладки. Номер изменяется, когда пользователь кликает по закладке или когда вызвается SetIndex. Постусловие Возвращаемое значение >= 0 и < tv.NofTabs() PROCEDURE (tv: View) SetNotifier (IN notifier: ARRAY OF CHAR) NEW Устанавливает уведомитель для tv в соответствии с notifier . Допускается notifier=""; это трактуется как отсутствие у tv уведомителя. См. выше Об уведомителях. PROCEDURE (tv: View) GetNotifier (OUT notifier: Dialog.String) NEW Возвращает в параметре notifier уведомитель для tv. Если tv не имеет уведомителя, то возвращается пустая строка. TYPE Directory ABSTRACT Тип фабричного объекта для StdTabViews.View. PROCEDURE (d: Directory) New (): View NEW, ABSTRACT Размещает и возвращает новый View. TYPE NotifierProc = PROCEDURE (tv: View; from, to: INTEGER) Сигнатура процедур-уведомителей для StdTabViews. Вызовы уведомителей позволяют оповестить приложение о переключении пользователем закладок StdTabViews.View. Параметры имеют следующий смысл: tv = объект StdTabViews.View, в котором была переключена закладка from = передняя закладка до переключения. Имеет значение noTab, если уведомитель вызван при загрузке to = новая передняя закладка VAR dir-, stdDir-: Directory dir # NIL & stdDir # NIL Фабричные объекты для создания StdTabViews.View. PROCEDURE SetDir (d: Directory) Установить фабричный объект. PROCEDURE Deposit Размещает новый View, используя dir.New, добавляет две закладки и ставит его в глобальную очередь (см. deposit). PROCEDURE This (v: Views.View): View Проверяет саму вьюшку v, а если это контейнер, то все внедренные в нее вьюшки (если таковые есть) и возвращает первый найденный объект типа StdTabViews.View. Если StdTabViews.View не найден, то возвращается NIL. Предусловие v # NIL PROCEDURE Focus (): View Ищет в фокусе объект типа StdTabViews.View. Если таковой найден, он возвращается, иначе возвращается NIL. Если в фокусе более одного такого объекта, то не определено, какой из них будет возвращен. PROCEDURE BeginChanges (tv: View) Приостанавливает отрисовку объекта закладок tv, пока не произойдет вызова EndChanges. Каждый вызов BeginChanges должен быть закрыт вызовом EndChanges, иначе произойдет аварийная остановка (Trap в StdTabViews.BalanceAction.Do). Вызовы могут быть вложенными. BeginChanges и EndChanges дают возможность вносить сразу несколько изменений в StdTabViews.View без немедленной отрисовки после каждого. Предусловие Количество вызовов BeginChanges >= количества вызовов EndChanges, 20 PROCEDURE EndChanges (tv: View) Возобновляет отрисовку для tv после вызова BeginChanges. Предусловие Количество вызовов BeginChanges >= количества вызовов EndChanges, 20 Следующие типы, переменные и процедуры используются только внутри Блэкбокса для управления фреймами вьюшек типа StdTabViews: TYPE Frame = POINTER TO ABSTRACT RECORD (StdCFrames.Frame) TYPE FrameDirectory = POINTER TO ABSTRACT RECORD VAR frameDir-, frameStdDir-: FrameDirectory PROCEDURE SetFrameDir (d: FrameDirectory) PROCEDURE (f: Frame) GetDispSize (OUT x, y, w, h: INTEGER), NEW, ABSTRACT PROCEDURE (f: Frame) InDispArea (x, y: INTEGER): BOOLEAN, NEW, ABSTRACT PROCEDURE (f: Frame) SetIndex (i: INTEGER), NEW PROCEDURE (d: FrameDirectory) GetTabSize (VAR w, h: INTEGER), NEW, ABSTRACT PROCEDURE (d: FrameDirectory) New (): Frame, NEW, ABSTRACT Следующие типы, переменные и процедуры используются только редактором свойств для объектов типа StdTabViews.View: VAR dlg: RECORD name, notifier: Dialog.String; opt: INTEGER END; PROCEDURE AddTab PROCEDURE Delete PROCEDURE DeleteGuard (VAR par: Dialog.Par) PROCEDURE InitDialog PROCEDURE LabelGuard (VAR par: Dialog.Par) PROCEDURE LayoutModeGuard (VAR par: Dialog.Par); PROCEDURE Left PROCEDURE MaskModeGuard (VAR par: Dialog.Par); PROCEDURE ModeNotifier (op, from, to: INTEGER); PROCEDURE NewGuard (VAR par: Dialog.Par) PROCEDURE NotifierGuard (VAR par: Dialog.Par) PROCEDURE Rename PROCEDURE RenameGuard (VAR par: Dialog.Par) PROCEDURE Right PROCEDURE SetGuard (VAR par: Dialog.Par) PROCEDURE SetNotifier Следующая переменная предназначена только для внутреннего использования в каркасе Блэкбокса: VAR setFocus: BOOLEAN
Std/Docu/ru/TabViews.odc
StdViewSizer ENGLISH Редакция перевода: Ф.В.Ткачев, 2010-10-31 DEFINITION StdViewSizer; IMPORT Dialog; VAR size: RECORD typeName-: Dialog.String; w, h: REAL END; PROCEDURE InitDialog; PROCEDURE SetViewSize; PROCEDURE SizeGuard (VAR par: Dialog.Par); PROCEDURE UnitGuard (VAR par: Dialog.Par); END StdViewSizer. StdViewSizer это пакет команд, позволяющий пользователю изменять размер объектов отрисовки (вьюшек), содержащихся в контейнерах, указывая ширину и высоту в численном виде. Это полезно в тех случаях, когда манипулирование границ вьюшки мышью не дает требуемой точности. Пакет может работать с любой вьюшкой-одиночкой (singleton). Для пункта меню рекомендуется следующая строка: "View Size..." "" "StdViewSizer.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/ViewSizer', 'View Size')" "StdCmds.SingletonGuard" VAR size: RECORD Интерактор для установки размера отображения. typeName-: Dialog.String Тип текущей вьюшки-одиночки. w: INTEGER Ширина вьюшки в сантиметрах или дюймах, в зависимости от Dialog.metricSystem. h: INTEGER Высота вьюшки в сантиметрах или дюймах, в зависимости от Dialog.metricSystem. PROCEDURE InitDialog Команда инициализации для интерактора size. PROCEDURE SetViewSize Применяет значения размеров из size. Чтобы связать size с выделенной вьюшкой, нужно предварительно вызвать InitDialog. PROCEDURE SizeGuard (VAR par: Dialog.Par) Охрана, которая гарантирует, что интерактор size соответствует текущей выделенной вьюшке-одиночке. Если таковой нет, то охрана обеспечивает деактивацию (пункта меню и т.п.). PROCEDURE UnitGuard (VAR par: Dialog.Par) Охрана, которая устанавливает par.label в "cm" или "inch" соответственно, в зависимости от значения Dialog.metricSystem.
Std/Docu/ru/ViewSizer.odc
MODULE StdApi; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Kernel, Views, Files, Dialog, Converters, Windows, Sequencers, Stores, Meta, Containers, StdDialog, Documents; (* Auxiliary procedures *) PROCEDURE CheckQualident (VAR str, mod, name: ARRAY OF CHAR); VAR i, j: INTEGER; ch: CHAR; BEGIN i := 0; REPEAT ch := str[i]; mod[i] := ch; INC(i) UNTIL (i = LEN(str)) OR (i = LEN(mod)) OR (ch < "0") OR (ch > "9") & (CAP(ch) < "A") OR (CAP(ch) > "Z"); IF ch = "." THEN mod[i - 1] := 0X; j := 0; REPEAT ch := str[i]; name[j] := ch; INC(i); INC(j) UNTIL (i = LEN(str)) OR (j = LEN(name)) OR (ch < "0") OR (ch > "9") & (CAP(ch) < "A") OR (CAP(ch) > "Z"); IF ch # 0X THEN mod[0] := 0X; name[0] := 0X END ELSE mod[0] := 0X; name[0] := 0X END END CheckQualident; PROCEDURE PathToSpec (VAR path: ARRAY OF CHAR; VAR loc: Files.Locator; VAR name: Files.Name); VAR i, j: INTEGER; ch: CHAR; BEGIN i := 0; j := 0; loc := Files.dir.This(""); WHILE (loc.res = 0) & (i < LEN(path) - 1) & (j < LEN(name) - 1) & (path[i] # 0X) DO ch := path[i]; INC(i); IF (j > 0) & ((ch = "/") OR (ch = "\")) THEN name[j] := 0X; j := 0; IF name = "*" THEN IF Dialog.language # "" THEN loc := loc.This(Dialog.language) END ELSE loc := loc.This(name) END ELSE name[j] := ch; INC(j) END END; IF path[i] = 0X THEN name[j] := 0X ELSE loc.res := 1; name := "" END END PathToSpec; PROCEDURE ThisDialog (dialog: ARRAY OF CHAR): Views.View; VAR fname, submod, sub, mod: Files.Name; canCreate: BOOLEAN; conv: Converters.Converter; loc: Files.Locator; file: Files.File; v: Views.View; s: Stores.Store; var: Meta.Item; BEGIN ASSERT(dialog # "", 20); v := NIL; file := NIL; canCreate := FALSE; CheckQualident(dialog, submod, fname); IF submod # "" THEN (* is qualident *) Meta.LookupPath(dialog, var); IF var.obj = Meta.varObj THEN (* variable exists *) canCreate := TRUE; Kernel.SplitName(submod, sub, mod); loc := Files.dir.This(sub); IF loc # NIL THEN Kernel.MakeFileName(fname, ""); loc := loc.This("Rsrc"); IF loc # NIL THEN file := Files.dir.Old(loc, fname, Files.shared) END; IF (file = NIL) & (sub = "") THEN loc := Files.dir.This("System"); ASSERT(loc # NIL, 100); IF loc # NIL THEN loc := loc.This("Rsrc"); IF loc # NIL THEN file := Files.dir.Old(loc, fname, Files.shared) END END END END END END; IF (file = NIL) & ~canCreate THEN (* try file name *) PathToSpec(dialog, loc, fname); IF loc.res = 0 THEN Kernel.MakeFileName(fname, ""); file := Files.dir.Old(loc, fname, Files.shared) END END; IF file # NIL THEN Kernel.MakeFileName(fname, ""); conv := NIL; Converters.Import(loc, fname, conv, s); IF s # NIL THEN v := s(Views.View) END ELSE Dialog.ShowParamMsg("#System:FileNotFound", dialog, "", "") END; RETURN v END ThisDialog; PROCEDURE ThisMask (param: ARRAY OF CHAR): Views.View; VAR v: Views.View; c: Containers.Controller; BEGIN v := ThisDialog(param); IF v # NIL THEN WITH v: Containers.View DO c := v.ThisController(); IF c # NIL THEN c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection}) ELSE Dialog.ShowMsg("#System:NotEditable") END ELSE Dialog.ShowMsg("#System:ContainerExpected") END END; RETURN v END ThisMask; (* Interface procedures *) PROCEDURE CloseDialog* (OUT closedView: Views.View); CONST canClose = {Windows.neverDirty, Windows.isTool, Windows.isAux}; VAR w: Windows.Window; msg: Sequencers.CloseMsg; BEGIN closedView := NIL; w := Windows.dir.First(); IF w # NIL THEN IF w.sub THEN closedView := w.frame.view; Windows.dir.Close(w); ELSIF (w.flags * canClose = {}) & w.seq.Dirty() THEN Dialog.ShowMsg("#System:CannotCloseDirtyWindow") ELSE msg.sticky := FALSE; w.seq.Notify(msg); IF ~msg.sticky THEN closedView := w.frame.view; Windows.dir.Close(w) END END END END CloseDialog; PROCEDURE OpenAux* (file, title: ARRAY OF CHAR; OUT v: Views.View); VAR loc: Files.Locator; name: Files.Name; t: Views.Title; BEGIN PathToSpec(file, loc, name); IF loc.res = 0 THEN loc.res := 77; v := Views.OldView(loc, name); loc.res := 0; IF v # NIL THEN t := title$; Views.OpenAux(v, t) ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END END OpenAux; PROCEDURE OpenAuxDialog* (file, title: ARRAY OF CHAR; OUT v: Views.View); VAR t0: Views.Title; done: BOOLEAN; BEGIN Dialog.MapString(title, t0); Windows.SelectByTitle(NIL, {Windows.isAux}, t0, done); IF ~done THEN v := ThisMask(file); IF v # NIL THEN StdDialog.Open(v, title, NIL, "", NIL, FALSE, TRUE, TRUE, FALSE, TRUE) END END END OpenAuxDialog; PROCEDURE OpenBrowser* (file, title: ARRAY OF CHAR; OUT v: Views.View); VAR loc: Files.Locator; name: Files.Name; t: Views.Title; c: Containers.Controller; BEGIN PathToSpec(file, loc, name); IF loc.res = 0 THEN loc.res := 77; v := Views.OldView(loc, name); loc.res := 0; IF v # NIL THEN WITH v: Containers.View DO c := v.ThisController(); IF c # NIL THEN c.SetOpts(c.opts - {Containers.noFocus, Containers.noSelection} + {Containers.noCaret}) END ELSE END; t := title$; StdDialog.Open(v, t, NIL, "", NIL, FALSE, TRUE, FALSE, TRUE, FALSE) ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END END OpenBrowser; PROCEDURE OpenDoc* (file: ARRAY OF CHAR; OUT v: Views.View); VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter; BEGIN PathToSpec(file, loc, name); IF loc.res = 0 THEN conv := NIL; v := Views.Old(Views.dontAsk, loc, name, conv); IF loc.res = 78 THEN loc := NIL; name := "" END; (* stationery *) IF v # NIL THEN Views.Open(v, loc, name, conv) ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END END OpenDoc; PROCEDURE OpenCopyOf* (file: ARRAY OF CHAR; OUT v: Views.View); VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter; BEGIN PathToSpec(file, loc, name); IF loc.res = 0 THEN conv := NIL; v := Views.Old(Views.dontAsk, loc, name, conv); IF loc.res = 78 THEN loc := NIL; name := "" END; (* stationary *) IF v # NIL THEN IF v.context # NIL THEN v := Views.CopyOf(v.context(Documents.Context).ThisDoc(), Views.deep); Stores.InitDomain(v) ELSE v := Views.CopyOf(v, Views.deep) END; Views.Open(v, NIL, "", conv) ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "") END END OpenCopyOf; PROCEDURE OpenToolDialog* (file, title: ARRAY OF CHAR; OUT v: Views.View); VAR t0: Views.Title; done: BOOLEAN; BEGIN Dialog.MapString(title, t0); Windows.SelectByTitle(NIL, {Windows.isTool}, t0, done); IF ~done THEN v := ThisMask(file); IF v # NIL THEN StdDialog.Open(v, title, NIL, "", NIL, TRUE, FALSE, TRUE, FALSE, TRUE) END END END OpenToolDialog; END StdApi.
Std/Mod/Api.odc
MODULE StdCFrames; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Fonts, Ports, Views, Dates, Dialog; CONST lineUp* = 0; lineDown* = 1; pageUp* = 2; pageDown* = 3; TYPE Frame* = POINTER TO ABSTRACT RECORD (Views.Frame) disabled*, undef*, readOnly*, noRedraw*: BOOLEAN; font*: Fonts.Font END; PushButton* = POINTER TO ABSTRACT RECORD (Frame) label*: ARRAY 256 OF CHAR; default*, cancel*: BOOLEAN; Do*: PROCEDURE (f: PushButton) END; CheckBox* = POINTER TO ABSTRACT RECORD (Frame) label*: ARRAY 256 OF CHAR; Get*: PROCEDURE (f: CheckBox; OUT on: BOOLEAN); Set*: PROCEDURE (f: CheckBox; on: BOOLEAN) END; RadioButton* = POINTER TO ABSTRACT RECORD (Frame) label*: ARRAY 256 OF CHAR; Get*: PROCEDURE (f: RadioButton; OUT on: BOOLEAN); Set*: PROCEDURE (f: RadioButton; on: BOOLEAN) END; ScrollBar* = POINTER TO ABSTRACT RECORD (Frame) Track*: PROCEDURE (f: ScrollBar; dir: INTEGER; VAR pos: INTEGER); Get*: PROCEDURE (f: ScrollBar; OUT size, sect, pos: INTEGER); Set*: PROCEDURE (f: ScrollBar; pos: INTEGER) END; Field* = POINTER TO ABSTRACT RECORD (Frame) maxLen*: INTEGER; (* max num of characters in field (w/o 0X) *) left*, right*, multiLine*, password*: BOOLEAN; Get*: PROCEDURE (f: Field; OUT string: ARRAY OF CHAR); Set*: PROCEDURE (f: Field; IN string: ARRAY OF CHAR); Equal*: PROCEDURE (f: Field; IN s1, s2: ARRAY OF CHAR): BOOLEAN END; UpDownField* = POINTER TO ABSTRACT RECORD (Frame) min*, max*, inc*: INTEGER; Get*: PROCEDURE (f: UpDownField; OUT val: INTEGER); Set*: PROCEDURE (f: UpDownField; val: INTEGER) END; DateField* = POINTER TO ABSTRACT RECORD (Frame) Get*: PROCEDURE (f: DateField; OUT date: Dates.Date); Set*: PROCEDURE (f: DateField; IN date: Dates.Date); GetSel*: PROCEDURE (f: DateField; OUT sel: INTEGER); SetSel*: PROCEDURE (f: DateField; sel: INTEGER) END; TimeField* = POINTER TO ABSTRACT RECORD (Frame) Get*: PROCEDURE (f: TimeField; OUT date: Dates.Time); Set*: PROCEDURE (f: TimeField; IN date: Dates.Time); GetSel*: PROCEDURE (f: TimeField; OUT sel: INTEGER); SetSel*: PROCEDURE (f: TimeField; sel: INTEGER) END; ColorField* = POINTER TO ABSTRACT RECORD (Frame) Get*: PROCEDURE (f: ColorField; OUT col: INTEGER); Set*: PROCEDURE (f: ColorField; col: INTEGER) END; ListBox* = POINTER TO ABSTRACT RECORD (Frame) sorted*: BOOLEAN; Get*: PROCEDURE (f: ListBox; OUT i: INTEGER); Set*: PROCEDURE (f: ListBox; i: INTEGER); GetName*: PROCEDURE (f: ListBox; i: INTEGER; VAR name: ARRAY OF CHAR) END; SelectionBox* = POINTER TO ABSTRACT RECORD (Frame) sorted*: BOOLEAN; Get*: PROCEDURE (f: SelectionBox; i: INTEGER; OUT in: BOOLEAN); Incl*: PROCEDURE (f: SelectionBox; from, to: INTEGER); Excl*: PROCEDURE (f: SelectionBox; from, to: INTEGER); Set*: PROCEDURE (f: SelectionBox; from, to: INTEGER); GetName*: PROCEDURE (f: SelectionBox; i: INTEGER; VAR name: ARRAY OF CHAR) END; ComboBox* = POINTER TO ABSTRACT RECORD (Frame) sorted*: BOOLEAN; Get*: PROCEDURE (f: ComboBox; OUT string: ARRAY OF CHAR); Set*: PROCEDURE (f: ComboBox; IN string: ARRAY OF CHAR); GetName*: PROCEDURE (f: ComboBox; i: INTEGER; VAR name: ARRAY OF CHAR) END; Caption* = POINTER TO ABSTRACT RECORD (Frame) label*: ARRAY 256 OF CHAR; left*, right*: BOOLEAN; END; Group* = POINTER TO ABSTRACT RECORD (Frame) label*: ARRAY 256 OF CHAR END; TreeFrame* = POINTER TO ABSTRACT RECORD (Frame) sorted*, haslines*, hasbuttons*, atroot*, foldericons*: BOOLEAN; NofNodes*: PROCEDURE (f: TreeFrame): INTEGER; Child*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode): Dialog.TreeNode; Parent*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode): Dialog.TreeNode; Next*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode): Dialog.TreeNode; Select*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode); Selected*: PROCEDURE (f: TreeFrame): Dialog.TreeNode; SetExpansion*: PROCEDURE (f: TreeFrame; tn: Dialog.TreeNode; expanded: BOOLEAN) END; Directory* = POINTER TO ABSTRACT RECORD END; VAR setFocus*: BOOLEAN; defaultFont*, defaultLightFont*: Fonts.Font; dir-, stdDir-: Directory; (** Frame **) PROCEDURE (f: Frame) MouseDown* (x, y: INTEGER; buttons: SET), NEW, EMPTY; PROCEDURE (f: Frame) WheelMove* (x, y: INTEGER; op, nofLines: INTEGER; VAR done: BOOLEAN), NEW, EMPTY; PROCEDURE (f: Frame) KeyDown* (ch: CHAR), NEW, EMPTY; PROCEDURE (f: Frame) Restore* (l, t, r, b: INTEGER), NEW, ABSTRACT; PROCEDURE (f: Frame) UpdateList*, NEW, EMPTY; PROCEDURE (f: Frame) Mark* (on, focus: BOOLEAN), NEW, EMPTY; PROCEDURE (f: Frame) Edit* (op: INTEGER; VAR v: Views.View; VAR w, h: INTEGER; VAR singleton, clipboard: BOOLEAN), NEW, EMPTY; PROCEDURE (f: Frame) GetCursor* (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER), NEW, EMPTY; PROCEDURE (f: Frame) Update*, NEW, EXTENSIBLE; VAR l, t, r, b: INTEGER; root: Views.RootFrame; BEGIN l := f.l + f.gx; t := f.t + f.gy; r := f.r + f.gx; b := f.b + f.gy; root := Views.RootOf(f); Views.UpdateRoot(root, l, t, r, b, Views.keepFrames); Views.ValidateRoot(root) END Update; PROCEDURE (f: Frame) DblClickOk* (x, y: INTEGER): BOOLEAN, NEW, EXTENSIBLE; BEGIN RETURN TRUE END DblClickOk; (** Field **) PROCEDURE (f: Field) Idle* (), NEW, ABSTRACT; PROCEDURE (f: Field) Select* (from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: Field) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: Field) Length* (): INTEGER, NEW, ABSTRACT; PROCEDURE (f: Field) GetCursor* (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER), EXTENSIBLE; BEGIN cursor := Ports.textCursor END GetCursor; (** UpDownField **) PROCEDURE (f: UpDownField) Idle*, NEW, ABSTRACT; PROCEDURE (f: UpDownField) Select* (from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: UpDownField) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: UpDownField) GetCursor* (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER), EXTENSIBLE; BEGIN cursor := Ports.textCursor END GetCursor; (** SelectionBox **) PROCEDURE (f: SelectionBox) Select* (from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: SelectionBox) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: SelectionBox) UpdateRange* (op, from, to: INTEGER), NEW, EXTENSIBLE; BEGIN f.Update END UpdateRange; (** ComboBox **) PROCEDURE (f: ComboBox) Idle* (), NEW, ABSTRACT; PROCEDURE (f: ComboBox) Select* (from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: ComboBox) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT; PROCEDURE (f: ComboBox) Length* (): INTEGER, NEW, ABSTRACT; (* TreeFrame **) PROCEDURE (f: TreeFrame) GetSize* (OUT w, h: INTEGER), NEW, ABSTRACT; (** Directory **) PROCEDURE (d: Directory) GetPushButtonSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetCheckBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetRadioButtonSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetScrollBarSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetFieldSize* (max: INTEGER; VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetUpDownFieldSize* (max: INTEGER; VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetDateFieldSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetTimeFieldSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetColorFieldSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetListBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetSelectionBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetComboBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetCaptionSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetGroupSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) GetTreeFrameSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: Directory) NewPushButton* (): PushButton, NEW, ABSTRACT; PROCEDURE (d: Directory) NewCheckBox* (): CheckBox, NEW, ABSTRACT; PROCEDURE (d: Directory) NewRadioButton* (): RadioButton, NEW, ABSTRACT; PROCEDURE (d: Directory) NewScrollBar* (): ScrollBar, NEW, ABSTRACT; PROCEDURE (d: Directory) NewField* (): Field, NEW, ABSTRACT; PROCEDURE (d: Directory) NewUpDownField* (): UpDownField, NEW, ABSTRACT; PROCEDURE (d: Directory) NewDateField* (): DateField, NEW, ABSTRACT; PROCEDURE (d: Directory) NewTimeField* (): TimeField, NEW, ABSTRACT; PROCEDURE (d: Directory) NewColorField* (): ColorField, NEW, ABSTRACT; PROCEDURE (d: Directory) NewListBox* (): ListBox, NEW, ABSTRACT; PROCEDURE (d: Directory) NewSelectionBox* (): SelectionBox, NEW, ABSTRACT; PROCEDURE (d: Directory) NewComboBox* (): ComboBox, NEW, ABSTRACT; PROCEDURE (d: Directory) NewCaption* (): Caption, NEW, ABSTRACT; PROCEDURE (d: Directory) NewGroup* (): Group, NEW, ABSTRACT; PROCEDURE (d: Directory) NewTreeFrame* (): TreeFrame, NEW, ABSTRACT; PROCEDURE SetDir* (d: Directory); BEGIN ASSERT(d # NIL, 20); dir := d; IF stdDir = NIL THEN stdDir := d END END SetDir; BEGIN setFocus := FALSE END StdCFrames.
Std/Mod/CFrames.odc
MODULE StdClocks; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Dates, Math, Domains := Stores, Ports, Stores, Models, Views, Services, Properties, TextModels; CONST minSize = 25 * Ports.point; niceSize = 42 * Ports.point; minVersion = 0; maxVersion = 0; TYPE StdView = POINTER TO RECORD (Views.View) time: Dates.Time END; TickAction = POINTER TO RECORD (Services.Action) END; Msg = RECORD (Models.Message) consumed: BOOLEAN; time: Dates.Time END; VAR clockTime: Dates.Time; action: TickAction; actionIsAlive: BOOLEAN; PROCEDURE Cos (r, g: INTEGER): INTEGER; BEGIN RETURN SHORT(ENTIER(r * Math.Cos(2 * Math.Pi() * g / 60) + 0.5)) END Cos; PROCEDURE Sin (r, g: INTEGER): INTEGER; BEGIN RETURN SHORT(ENTIER(r * Math.Sin(2 * Math.Pi() * g / 60) + 0.5)) END Sin; PROCEDURE (a: TickAction) Do; VAR msg: Msg; time: Dates.Time; BEGIN Dates.GetTime(time); IF clockTime.second = time.second THEN Services.DoLater(action, Services.Ticks() + Services.resolution DIV 2) ELSE clockTime := time; msg.consumed := FALSE; msg.time := time; Views.Omnicast(msg); IF msg.consumed THEN Services.DoLater(action, Services.Ticks() + Services.resolution DIV 2) ELSE actionIsAlive := FALSE END END END Do; (* View *) PROCEDURE DrawTick (f: Views.Frame; m, d0, d1, s, g: INTEGER; c: Ports.Color); BEGIN f.DrawLine(m + Sin(d0, g), m - Cos(d0, g), m + Sin(d1, g), m - Cos(d1, g), s, c) END DrawTick; PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer); BEGIN v.Externalize^(wr); wr.WriteVersion(maxVersion); wr.WriteByte(9) END Externalize; PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader); VAR thisVersion: INTEGER; format: BYTE; BEGIN v.Internalize^(rd); IF ~rd.cancelled THEN rd.ReadVersion(minVersion, maxVersion, thisVersion); IF ~rd.cancelled THEN rd.ReadByte(format); v.time.second := -1 END END END Internalize; PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View); BEGIN WITH source: StdView DO v.time.second := -1 END END CopyFromSimpleView; PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR c: Models.Context; a: TextModels.Attributes; color: Ports.Color; time: Dates.Time; i, m, d, u, hs, hd1, ms, md1, ss, sd0, sd1, w, h: INTEGER; BEGIN IF ~actionIsAlive THEN actionIsAlive := TRUE; Services.DoLater(action, Services.now) END; IF v.time.second = -1 THEN Dates.GetTime(v.time) END; c := v.context; c.GetSize(w, h); WITH c: TextModels.Context DO a := c.Attr(); color := a.color ELSE color := Ports.defaultColor END; u := f.unit; d := h DIV u * u; IF ~ODD(d DIV u) THEN DEC(d, u) END; m := (h - u) DIV 2; IF d >= niceSize - 2 * Ports.point THEN hs := 3 * u; ms := 3 * u; ss := u; hd1 := m * 4 DIV 6; md1 := m * 5 DIV 6; sd0 := -(m DIV 6); sd1 := m - 4 * u; i := 0; WHILE i < 12 DO DrawTick(f, m, m * 11 DIV 12, m, u, i * 5, color); INC(i) END ELSE hd1 := m * 2 DIV 4; hs := u; ms := u; ss := u; md1 := m * 3 DIV 4; sd0 := 0; sd1 := 3 * u END; time := v.time; f.DrawOval(0, 0, d, d, u, color); DrawTick(f, m, 0, m * 4 DIV 6, hs, time.hour MOD 12 * 5 + time.minute DIV 12, color); DrawTick(f, m, 0, md1, ms, time.minute, color); DrawTick(f, m, sd0, sd1, ss, time.second, color) END Restore; PROCEDURE (v: StdView) HandleModelMsg (VAR msg: Models.Message); VAR w, h: INTEGER; BEGIN WITH msg: Msg DO msg.consumed := TRUE; IF v.time.second # msg.time.second THEN (* execute only once per view *) Views.Update(v, Views.keepFrames); v.time := msg.time END ELSE END END HandleModelMsg; PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref); BEGIN IF (p.w > Views.undefined) & (p.h > Views.undefined) THEN Properties.ProportionalConstraint(1, 1, p.fixedW, p.fixedH, p.w, p.h); IF p.w < minSize THEN p.w := minSize; p.h := minSize END ELSE p.w := niceSize; p.h := niceSize END END SizePref; PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message); BEGIN WITH msg: Properties.Preference DO WITH msg: Properties.SizePref DO SizePref(v, msg) ELSE END ELSE END END HandlePropMsg; (** allocation **) PROCEDURE New* (): Views.View; VAR v: StdView; BEGIN NEW(v); v.time.second := -1; RETURN v END New; PROCEDURE Deposit*; BEGIN Views.Deposit(New()) END Deposit; BEGIN clockTime.second := -1; NEW(action); actionIsAlive := FALSE CLOSE IF actionIsAlive THEN Services.RemoveAction(action) END END StdClocks.
Std/Mod/Clocks.odc
MODULE StdCmds; (* SP410 *) (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - 20111211, Fyodor Tkachov, switched from National to i21sysCharacters - 20080215, Fyodor Tkachov, reviewed - 20050626, Fyodor Tkachov, russification edited - 20050430, Ivan Goryachev, russification - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Fonts, Ports, Services, Stores, Sequencers, Models, Views, Controllers, Containers, Properties, Dialog, Documents, Windows, Strings, StdDialog, StdApi, i21sysCharacters; CONST illegalSizeKey = "#System:IllegalFontSize"; defaultAllocator = "TextViews.Deposit; StdCmds.Open"; (* wType, hType *) fix = 0; page = 1; window = 2; VAR size*: RECORD size*: INTEGER END; layout*: RECORD wType*, hType*: INTEGER; width*, height*: REAL; doc: Documents.Document; u: INTEGER END; allocator*: Dialog.String; propEra: INTEGER; (* (propEra, props) form cache for StdProps() *) props: Properties.StdProp; (* valid iff propEra = Props.era *) prop: Properties.Property; (* usef for copy/paste properties *) (* auxiliary procedures *) PROCEDURE StdProp (): Properties.StdProp; BEGIN IF propEra # Properties.era THEN Properties.CollectStdProp(props); propEra := Properties.era END; RETURN props END StdProp; PROCEDURE Append (VAR s: ARRAY OF CHAR; t: ARRAY OF CHAR); VAR len, i, j: INTEGER; ch: CHAR; BEGIN len := LEN(s); i := 0; WHILE s[i] # 0X DO INC(i) END; j := 0; REPEAT ch := t[j]; s[i] := ch; INC(j); INC(i) UNTIL (ch = 0X) OR (i = len); s[len - 1] := 0X END Append; (* standard commands *) PROCEDURE OpenAuxDialog* (file, title: ARRAY OF CHAR); VAR v: Views.View; BEGIN StdApi.OpenAuxDialog(file, title, v) END OpenAuxDialog; PROCEDURE OpenToolDialog* (file, title: ARRAY OF CHAR); VAR v: Views.View; BEGIN StdApi.OpenToolDialog(file, title, v) END OpenToolDialog; PROCEDURE OpenDoc* (file: ARRAY OF CHAR); VAR v: Views.View; BEGIN StdApi.OpenDoc(file, v) END OpenDoc; PROCEDURE OpenCopyOf* (file: ARRAY OF CHAR); VAR v: Views.View; BEGIN StdApi.OpenCopyOf(file, v) END OpenCopyOf; PROCEDURE OpenAux* (file, title: ARRAY OF CHAR); VAR v: Views.View; BEGIN StdApi.OpenAux(file, title, v) END OpenAux; PROCEDURE OpenBrowser* (file, title: ARRAY OF CHAR); VAR v: Views.View; BEGIN StdApi.OpenBrowser(file, title, v) END OpenBrowser; PROCEDURE CloseDialog*; VAR v: Views.View; BEGIN StdApi.CloseDialog(v) END CloseDialog; PROCEDURE Open*; VAR i: INTEGER; v: Views.View; BEGIN i := Views.Available(); IF i > 0 THEN Views.Fetch(v); Views.OpenView(v) ELSE Dialog.ShowMsg("#System:DepositExpected") END END Open; PROCEDURE PasteView*; VAR i: INTEGER; v: Views.View; BEGIN i := Views.Available(); IF i > 0 THEN Views.Fetch(v); Controllers.PasteView(v, Views.undefined, Views.undefined, FALSE) ELSE Dialog.ShowMsg("#System:DepositExpected") END END PasteView; (* file menu commands *) PROCEDURE New*; VAR res: INTEGER; BEGIN Dialog.Call(allocator, " ", res) END New; (* edit menu commands *) PROCEDURE Undo*; VAR w: Windows.Window; BEGIN w := Windows.dir.Focus(Controllers.frontPath); IF w # NIL THEN w.seq.Undo END END Undo; PROCEDURE Redo*; VAR w: Windows.Window; BEGIN w := Windows.dir.Focus(Controllers.frontPath); IF w # NIL THEN w.seq.Redo END END Redo; PROCEDURE CopyProp*; BEGIN Properties.CollectProp(prop) END CopyProp; PROCEDURE PasteProp*; BEGIN Properties.EmitProp(NIL, prop) END PasteProp; PROCEDURE Clear*; (** remove the selection of the current focus **) VAR msg: Controllers.EditMsg; BEGIN msg.op := Controllers.cut; msg.view := NIL; msg.clipboard := FALSE; Controllers.Forward(msg) END Clear; PROCEDURE SelectAll*; (** select whole content of current focus **) VAR msg: Controllers.SelectMsg; BEGIN msg.set := TRUE; Controllers.Forward(msg) END SelectAll; PROCEDURE DeselectAll*; (** select whole content of current focus **) VAR msg: Controllers.SelectMsg; BEGIN msg.set := FALSE; Controllers.Forward(msg) END DeselectAll; PROCEDURE SelectDocument*; (** select whole document **) VAR w: Windows.Window; c: Containers.Controller; BEGIN w := Windows.dir.Focus(Controllers.path); IF w # NIL THEN c := w.doc.ThisController(); IF (c # NIL) & ~(Containers.noSelection IN c.opts) & (c.Singleton() = NIL) THEN c.SetSingleton(w.doc.ThisView()) END END END SelectDocument; PROCEDURE SelectNextView*; VAR c: Containers.Controller; v: Views.View; BEGIN c := Containers.Focus(); IF (c # NIL) & ~(Containers.noSelection IN c.opts) THEN IF c.HasSelection() THEN v := c.Singleton() ELSE v := NIL END; IF v = NIL THEN c.GetFirstView(Containers.any, v) ELSE c.GetNextView(Containers.any, v); IF v = NIL THEN c.GetFirstView(Containers.any, v) END END; c.SelectAll(FALSE); IF v # NIL THEN c.SetSingleton(v) END ELSE Dialog.ShowMsg("#Dev:NoTargetFocusFound") END END SelectNextView; (** font menu commands **) PROCEDURE Font* (typeface: Fonts.Typeface); (** set the selection to the given font family **) VAR p: Properties.StdProp; BEGIN NEW(p); p.valid := {Properties.typeface}; p.typeface := typeface; Properties.EmitProp(NIL, p) END Font; PROCEDURE DefaultFont*; (** set the selection to the default font family **) VAR p: Properties.StdProp; BEGIN NEW(p); p.valid := {Properties.typeface}; p.typeface := Fonts.default; Properties.EmitProp(NIL, p) END DefaultFont; (** attributes menu commands **) PROCEDURE Plain*; (** reset the font attribute "weight" and all font style attributes of the selection **) VAR p: Properties.StdProp; BEGIN NEW(p); p.valid := {Properties.style, Properties.weight}; p.style.val := {}; p.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout}; p.weight := Fonts.normal; Properties.EmitProp(NIL, p) END Plain; PROCEDURE Bold*; (** change the font attribute "weight" in the selection; if the selection has a homogeneously bold weight: toggle to normal, else force to bold **) VAR p, p0: Properties.StdProp; BEGIN Properties.CollectStdProp(p0); NEW(p); p.valid := {Properties.weight}; IF (Properties.weight IN p0.valid) & (p0.weight # Fonts.normal) THEN p.weight := Fonts.normal ELSE p.weight := Fonts.bold END; Properties.EmitProp(NIL, p) END Bold; PROCEDURE Italic*; (** change the font style attribute "italic" in the selection; if the selection is homogeneous wrt this attribute: toggle, else force to italic **) VAR p, p0: Properties.StdProp; BEGIN Properties.CollectStdProp(p0); NEW(p); p.valid := {Properties.style}; p.style.mask := {Fonts.italic}; IF (Properties.style IN p0.valid) & (Fonts.italic IN p0.style.val) THEN p.style.val := {} ELSE p.style.val := {Fonts.italic} END; Properties.EmitProp(NIL, p) END Italic; PROCEDURE Underline*; (** change the font style attribute "underline" in the selection; if the selection is homogeneous wrt this attribute: toggle, else force to underline **) VAR p, p0: Properties.StdProp; BEGIN Properties.CollectStdProp(p0); NEW(p); p.valid := {Properties.style}; p.style.mask := {Fonts.underline}; IF (Properties.style IN p0.valid) & (Fonts.underline IN p0.style.val) THEN p.style.val := {} ELSE p.style.val := {Fonts.underline} END; Properties.EmitProp(NIL, p) END Underline; PROCEDURE Strikeout*; (** change the font style attribute "strikeout" in the selection, without changing other attributes; if the selection is homogeneous wrt this attribute: toggle, else force to strikeout **) VAR p, p0: Properties.StdProp; BEGIN Properties.CollectStdProp(p0); NEW(p); p.valid := {Properties.style}; p.style.mask := {Fonts.strikeout}; IF (Properties.style IN p0.valid) & (Fonts.strikeout IN p0.style.val) THEN p.style.val := {} ELSE p.style.val := {Fonts.strikeout} END; Properties.EmitProp(NIL, p) END Strikeout; PROCEDURE Size* (size: INTEGER); (** set the selection to the given font size **) VAR p: Properties.StdProp; BEGIN NEW(p); p.valid := {Properties.size}; p.size := size * Ports.point; Properties.EmitProp(NIL, p) END Size; PROCEDURE SetSize*; VAR p: Properties.StdProp; BEGIN IF (0 <= size.size) & (size.size < 32768) THEN NEW(p); p.valid := {Properties.size}; p.size := size.size * Fonts.point; Properties.EmitProp(NIL, p) ELSE Dialog.ShowMsg(illegalSizeKey) END END SetSize; PROCEDURE InitSizeDialog*; VAR p: Properties.StdProp; BEGIN Properties.CollectStdProp(p); IF Properties.size IN p.valid THEN size.size := p.size DIV Fonts.point END END InitSizeDialog; PROCEDURE Color* (color: Ports.Color); (** set the color attributes of the selection **) VAR p: Properties.StdProp; BEGIN NEW(p); p.valid := {Properties.color}; p.color.val := color; Properties.EmitProp(NIL, p) END Color; PROCEDURE UpdateAll*; (* for HostCmds.Toggle *) VAR w: Windows.Window; pw, ph: INTEGER; dirty: BOOLEAN; msg: Models.UpdateMsg; BEGIN w := Windows.dir.First(); WHILE w # NIL DO IF ~w.sub THEN dirty := w.seq.Dirty(); Models.Domaincast(w.doc.Domain(), msg); IF ~dirty THEN w.seq.SetDirty(FALSE) END (* not perfect: "undoable dirt" ... *) END; w.port.GetSize(pw, ph); w.Restore(0, 0, pw, ph); w := Windows.dir.Next(w) END END UpdateAll; PROCEDURE RestoreAll*; VAR w: Windows.Window; pw, ph: INTEGER; BEGIN w := Windows.dir.First(); WHILE w # NIL DO w.port.GetSize(pw, ph); w.Restore(0, 0, pw, ph); w := Windows.dir.Next(w) END END RestoreAll; (** document layout dialog **) PROCEDURE SetLayout*; VAR opts: SET; l, t, r, b, r0, b0: INTEGER; c: Containers.Controller; script: Stores.Operation; BEGIN c := layout.doc.ThisController(); opts := c.opts - {Documents.pageWidth..Documents.winHeight}; IF layout.wType = page THEN INCL(opts, Documents.pageWidth) ELSIF layout.wType = window THEN INCL(opts, Documents.winWidth) END; IF layout.hType = page THEN INCL(opts, Documents.pageHeight) ELSIF layout.hType = window THEN INCL(opts, Documents.winHeight) END; layout.doc.PollRect(l, t, r, b); r0 := r; b0 := b; IF layout.wType = fix THEN r := l + SHORT(ENTIER(layout.width * layout.u)) END; IF layout.hType = fix THEN b := t + SHORT(ENTIER(layout.height * layout.u)) END; IF (opts # c.opts) OR (r # r0) OR (b # b0) THEN Views.BeginScript(layout.doc, "#System:ChangeLayout", script); c.SetOpts(opts); layout.doc.SetRect(l, t, r, b); Views.EndScript(layout.doc, script) END END SetLayout; PROCEDURE InitLayoutDialog*; (* guard: WindowGuard *) VAR w: Windows.Window; c: Containers.Controller; l, t, r, b: INTEGER; BEGIN w := Windows.dir.First(); IF w # NIL THEN layout.doc := w.doc; c := w.doc.ThisController(); IF Documents.pageWidth IN c.opts THEN layout.wType := page ELSIF Documents.winWidth IN c.opts THEN layout.wType := window ELSE layout.wType := fix END; IF Documents.pageHeight IN c.opts THEN layout.hType := page ELSIF Documents.winHeight IN c.opts THEN layout.hType := window ELSE layout.hType := fix END; IF Dialog.metricSystem THEN layout.u := Ports.mm * 10 ELSE layout.u := Ports.inch END; w.doc.PollRect(l, t, r, b); layout.width := (r - l) DIV (layout.u DIV 100) / 100; layout.height := (b - t) DIV (layout.u DIV 100) / 100 END END InitLayoutDialog; PROCEDURE WidthGuard* (VAR par: Dialog.Par); BEGIN IF layout.wType # fix THEN par.readOnly := TRUE END END WidthGuard; PROCEDURE HeightGuard* (VAR par: Dialog.Par); BEGIN IF layout.hType # fix THEN par.readOnly := TRUE END END HeightGuard; PROCEDURE TypeNotifier* (op, from, to: INTEGER); VAR w, h, l, t, r, b: INTEGER; d: BOOLEAN; BEGIN layout.doc.PollRect(l, t, r, b); IF layout.wType = page THEN layout.doc.PollPage(w, h, l, t, r, b, d) ELSIF layout.wType = window THEN layout.doc.context.GetSize(w, h); r := w - l END; layout.width := (r - l) DIV (layout.u DIV 100) / 100; layout.doc.PollRect(l, t, r, b); IF layout.hType = page THEN layout.doc.PollPage(w, h, l, t, r, b, d) ELSIF layout.hType = window THEN layout.doc.context.GetSize(w, h); b := h - t END; layout.height := (b - t) DIV (layout.u DIV 100) / 100; Dialog.Update(layout) END TypeNotifier; (** window menu command **) PROCEDURE NewWindow*; (** guard ModelViewGuard **) VAR win: Windows.Window; doc: Documents.Document; v: Views.View; title: Views.Title; seq: ANYPTR; clean: BOOLEAN; BEGIN win := Windows.dir.Focus(Controllers.frontPath); IF win # NIL THEN v := win.doc.ThisView(); IF v.Domain() # NIL THEN seq := v.Domain().GetSequencer() ELSE seq := NIL END; clean := (seq # NIL) & ~seq(Sequencers.Sequencer).Dirty(); doc := win.doc.DocCopyOf(v); (* Stores.InitDomain(doc, v.Domain()); *) ASSERT(doc.Domain() = v.Domain(), 100); win.GetTitle(title); Windows.dir.OpenSubWindow(Windows.dir.New(), doc, win.flags, title); IF clean THEN seq(Sequencers.Sequencer).SetDirty(FALSE) END END END NewWindow; (* properties *) PROCEDURE GetCmd (name: ARRAY OF CHAR; OUT cmd: ARRAY OF CHAR); VAR i, j: INTEGER; ch, lch: CHAR; key: ARRAY 256 OF CHAR; BEGIN i := 0; ch := name[0]; key[0] := "#"; j := 1; REPEAT key[j] := ch; INC(j); lch := ch; INC(i); ch := name[i] UNTIL (ch = 0X) OR (ch = ".") OR (i21sysCharacters.IsCap(ch) & ~i21sysCharacters.IsCap(lch)); IF ch = "." THEN key := "#System:" + name ELSE key[j] := ":"; INC(j); key[j] := 0X; j := 0; WHILE ch # 0X DO name[j] := ch; INC(i); INC(j); ch := name[i] END; name[j] := 0X; key := key + name END; Dialog.MapString(key, cmd); IF cmd = name THEN cmd := "" END END GetCmd; PROCEDURE SearchCmd (call: BOOLEAN; OUT found: BOOLEAN); VAR p: Properties.Property; std: BOOLEAN; v: Views.View; cmd: ARRAY 256 OF CHAR; pos, res: INTEGER; BEGIN Controllers.SetCurrentPath(Controllers.targetPath); v := Containers.FocusSingleton(); found := FALSE; IF v # NIL THEN Services.GetTypeName(v, cmd); GetCmd(cmd, cmd); IF cmd # "" THEN found := TRUE; IF call THEN Dialog.Call(cmd, "", res) END END END; std := FALSE; Properties.CollectProp(p); WHILE p # NIL DO IF p IS Properties.StdProp THEN std := TRUE ELSE Services.GetTypeName(p, cmd); GetCmd(cmd, cmd); IF cmd # "" THEN found := TRUE; IF call THEN Dialog.Call(cmd, "", res) END ELSE Services.GetTypeName(p, cmd); Strings.Find(cmd, "Desc", LEN(cmd$)-4, pos); IF LEN(cmd$)-4 = pos THEN cmd[pos] := 0X; GetCmd(cmd, cmd); IF cmd # "" THEN found := TRUE; IF call THEN Dialog.Call(cmd, "", res) END END END END END; p := p.next END; IF std & ~found THEN Dialog.MapString("#Host:Properties.StdProp", cmd); IF cmd # "Properties.StdProp" THEN found := TRUE; IF call THEN Dialog.Call(cmd, "", res) END END END; IF ~found THEN Dialog.MapString("#System:ShowProp", cmd); IF cmd # "ShowProp" THEN found := TRUE; IF call THEN Dialog.Call(cmd, "", res) END END END; Controllers.ResetCurrentPath END SearchCmd; PROCEDURE ShowProp*; VAR found: BOOLEAN; BEGIN SearchCmd(TRUE, found) END ShowProp; PROCEDURE ShowPropGuard* (VAR par: Dialog.Par); VAR found: BOOLEAN; BEGIN SearchCmd(FALSE, found); IF ~found THEN par.disabled := TRUE END END ShowPropGuard; (* container commands *) PROCEDURE ActFocus (): Containers.Controller; VAR c: Containers.Controller; v: Views.View; BEGIN c := Containers.Focus(); IF c # NIL THEN v := c.ThisView(); IF v IS Documents.Document THEN v := v(Documents.Document).ThisView(); IF v IS Containers.View THEN c := v(Containers.View).ThisController() ELSE c := NIL END END END; RETURN c END ActFocus; PROCEDURE ToggleNoFocus*; VAR c: Containers.Controller; v: Views.View; BEGIN c := ActFocus(); IF c # NIL THEN v := c.ThisView(); IF ~((v IS Documents.Document) OR (Containers.noSelection IN c.opts)) THEN IF Containers.noFocus IN c.opts THEN c.SetOpts(c.opts - {Containers.noFocus}) ELSE c.SetOpts(c.opts + {Containers.noFocus}) END END END END ToggleNoFocus; PROCEDURE OpenAsAuxDialog*; (** create a new sub-window onto the focus view shown in the top window, mask mode **) VAR win: Windows.Window; doc: Documents.Document; v, u: Views.View; title: Views.Title; c: Containers.Controller; BEGIN v := Controllers.FocusView(); IF (v # NIL) & (v IS Containers.View) & ~(v IS Documents.Document) THEN win := Windows.dir.Focus(Controllers.frontPath); ASSERT(win # NIL, 100); doc := win.doc.DocCopyOf(v); u := doc.ThisView(); c := u(Containers.View).ThisController(); c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection}); IF v # win.doc.ThisView() THEN c := doc.ThisController(); c.SetOpts(c.opts - {Documents.pageWidth, Documents.pageHeight} + {Documents.winWidth, Documents.winHeight}) END; (* Stores.InitDomain(doc, v.Domain()); already done in DocCopyOf *) win.GetTitle(title); Windows.dir.OpenSubWindow(Windows.dir.New(), doc, {Windows.isAux, Windows.neverDirty, Windows.noResize, Windows.noHScroll, Windows.noVScroll}, title) ELSE Dialog.Beep END END OpenAsAuxDialog; PROCEDURE OpenAsToolDialog*; (** create a new sub-window onto the focus view shown in the top window, mask mode **) VAR win: Windows.Window; doc: Documents.Document; v, u: Views.View; title: Views.Title; c: Containers.Controller; BEGIN v := Controllers.FocusView(); IF (v # NIL) & (v IS Containers.View) & ~(v IS Documents.Document) THEN win := Windows.dir.Focus(Controllers.frontPath); ASSERT(win # NIL, 100); doc := win.doc.DocCopyOf(v); u := doc.ThisView(); c := u(Containers.View).ThisController(); c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection}); IF v # win.doc.ThisView() THEN c := doc.ThisController(); c.SetOpts(c.opts - {Documents.pageWidth, Documents.pageHeight} + {Documents.winWidth, Documents.winHeight}) END; (* Stores.InitDomain(doc, v.Domain()); already done in DocCopyOf *) win.GetTitle(title); Windows.dir.OpenSubWindow(Windows.dir.New(), doc, {Windows.isTool, Windows.neverDirty, Windows.noResize, Windows.noHScroll, Windows.noVScroll}, title) ELSE Dialog.Beep END END OpenAsToolDialog; PROCEDURE RecalcFocusSize*; VAR c: Containers.Controller; v: Views.View; bounds: Properties.BoundsPref; BEGIN c := Containers.Focus(); IF c # NIL THEN v := c.ThisView(); bounds.w := Views.undefined; bounds.h := Views.undefined; Views.HandlePropMsg(v, bounds); v.context.SetSize(bounds.w, bounds.h) END END RecalcFocusSize; PROCEDURE RecalcAllSizes*; VAR w: Windows.Window; BEGIN w := Windows.dir.First(); WHILE w # NIL DO StdDialog.RecalcView(w.doc.ThisView()); w := Windows.dir.Next(w) END END RecalcAllSizes; PROCEDURE SetMode(opts: SET); VAR c: Containers.Controller; v: Views.View; gm: Containers.GetOpts; sm: Containers.SetOpts; w: Windows.Window; BEGIN c := Containers.Focus(); gm.valid := {}; IF (c # NIL) & (c.Singleton() # NIL) THEN v := c.Singleton(); Views.HandlePropMsg(v, gm); END; IF gm.valid = {} THEN w := Windows.dir.Focus(Controllers.path); IF (w # NIL) & (w.doc.ThisView() IS Containers.View) THEN v := w.doc.ThisView() ELSE v := NIL END END; IF v # NIL THEN sm.valid := {Containers.noSelection, Containers.noFocus, Containers.noCaret}; sm.opts := opts; Views.HandlePropMsg(v, sm); END; END SetMode; PROCEDURE GetMode(OUT found: BOOLEAN; OUT opts: SET); VAR c: Containers.Controller; gm: Containers.GetOpts; w: Windows.Window; BEGIN c := Containers.Focus(); gm.valid := {}; IF (c # NIL) & (c.Singleton() # NIL) THEN Views.HandlePropMsg(c.Singleton(), gm); END; IF gm.valid = {} THEN w := Windows.dir.Focus(Controllers.path); IF (w # NIL) & (w.doc.ThisView() IS Containers.View) THEN Views.HandlePropMsg(w.doc.ThisView(), gm); END END; found := gm.valid # {}; opts := gm.opts END GetMode; PROCEDURE SetMaskMode*; (* Guard: SetMaskGuard *) BEGIN SetMode({Containers.noSelection, Containers.noCaret}) END SetMaskMode; PROCEDURE SetEditMode*; (* Guard: SetEditGuard *) BEGIN SetMode({}) END SetEditMode; PROCEDURE SetLayoutMode*; (* Guard: SetLayoutGuard *) BEGIN SetMode({Containers.noFocus}) END SetLayoutMode; PROCEDURE SetBrowserMode*; (* Guard: SetBrowserGuard *) BEGIN SetMode({Containers.noCaret}) END SetBrowserMode; (* standard guards *) PROCEDURE ToggleNoFocusGuard* (VAR par: Dialog.Par); VAR c: Containers.Controller; v: Views.View; BEGIN c := ActFocus(); IF c # NIL THEN v := c.ThisView(); IF ~((v IS Documents.Document) OR (Containers.noSelection IN c.opts)) THEN IF Containers.noFocus IN c.opts THEN par.label := "#System:AllowFocus" ELSE par.label := "#System:PreventFocus" END ELSE par.disabled := TRUE END ELSE par.disabled := TRUE END END ToggleNoFocusGuard; PROCEDURE ReadOnlyGuard* (VAR par: Dialog.Par); BEGIN par.readOnly := TRUE END ReadOnlyGuard; PROCEDURE WindowGuard* (VAR par: Dialog.Par); VAR w: Windows.Window; BEGIN w := Windows.dir.First(); IF w = NIL THEN par.disabled := TRUE END END WindowGuard; PROCEDURE ModelViewGuard* (VAR par: Dialog.Par); VAR w: Windows.Window; BEGIN w := Windows.dir.Focus(Controllers.frontPath); par.disabled := (w = NIL) OR (w.doc.ThisView().ThisModel() = NIL) END ModelViewGuard; PROCEDURE SetMaskModeGuard* (VAR par: Dialog.Par); CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret}; VAR opts: SET; found: BOOLEAN; BEGIN GetMode(found, opts); IF found THEN par.checked := opts * mode = {Containers.noSelection, Containers.noCaret} ELSE par.disabled := TRUE END END SetMaskModeGuard; PROCEDURE SetEditModeGuard* (VAR par: Dialog.Par); CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret}; VAR opts: SET; found: BOOLEAN; BEGIN GetMode(found, opts); IF found THEN par.checked := opts * mode = {} ELSE par.disabled := TRUE END END SetEditModeGuard; PROCEDURE SetLayoutModeGuard* (VAR par: Dialog.Par); CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret}; VAR opts: SET; found: BOOLEAN; BEGIN GetMode(found, opts); IF found THEN par.checked := opts * mode = {Containers.noFocus} ELSE par.disabled := TRUE END END SetLayoutModeGuard; PROCEDURE SetBrowserModeGuard* (VAR par: Dialog.Par); CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret}; VAR opts: SET; found: BOOLEAN; BEGIN GetMode(found, opts); IF found THEN par.checked := opts * mode = {Containers.noCaret} ELSE par.disabled := TRUE END END SetBrowserModeGuard; PROCEDURE SelectionGuard* (VAR par: Dialog.Par); VAR ops: Controllers.PollOpsMsg; BEGIN Controllers.PollOps(ops); IF ops.valid * {Controllers.cut, Controllers.copy} = {} THEN par.disabled := TRUE END END SelectionGuard; PROCEDURE SingletonGuard* (VAR par: Dialog.Par); VAR ops: Controllers.PollOpsMsg; BEGIN Controllers.PollOps(ops); IF ops.singleton = NIL THEN par.disabled := TRUE END END SingletonGuard; PROCEDURE SelectAllGuard* (VAR par: Dialog.Par); VAR ops: Controllers.PollOpsMsg; BEGIN Controllers.PollOps(ops); IF ~ops.selectable THEN par.disabled := TRUE END END SelectAllGuard; PROCEDURE CaretGuard* (VAR par: Dialog.Par); VAR ops: Controllers.PollOpsMsg; BEGIN Controllers.PollOps(ops); IF ops.valid * {Controllers.pasteChar .. Controllers.paste} = {} THEN par.disabled := TRUE END END CaretGuard; PROCEDURE PasteCharGuard* (VAR par: Dialog.Par); VAR ops: Controllers.PollOpsMsg; BEGIN Controllers.PollOps(ops); IF ~(Controllers.pasteChar IN ops.valid) THEN par.disabled := TRUE END END PasteCharGuard; PROCEDURE PasteLCharGuard* (VAR par: Dialog.Par); VAR ops: Controllers.PollOpsMsg; BEGIN Controllers.PollOps(ops); IF ~(Controllers.pasteChar IN ops.valid) THEN par.disabled := TRUE END END PasteLCharGuard; PROCEDURE PasteViewGuard* (VAR par: Dialog.Par); VAR ops: Controllers.PollOpsMsg; BEGIN Controllers.PollOps(ops); IF ~(Controllers.paste IN ops.valid) THEN par.disabled := TRUE END END PasteViewGuard; PROCEDURE ContainerGuard* (VAR par: Dialog.Par); BEGIN IF Containers.Focus() = NIL THEN par.disabled := TRUE END END ContainerGuard; PROCEDURE UndoGuard* (VAR par: Dialog.Par); VAR f: Windows.Window; opName: Stores.OpName; BEGIN Dialog.MapString("#System:Undo", par.label); f := Windows.dir.Focus(Controllers.frontPath); IF (f # NIL) & f.seq.CanUndo() THEN f.seq.GetUndoName(opName); Dialog.MapString(opName, opName); Append(par.label, " "); Append(par.label, opName) ELSE par.disabled := TRUE END END UndoGuard; PROCEDURE RedoGuard* (VAR par: Dialog.Par); VAR f: Windows.Window; opName: Stores.OpName; BEGIN Dialog.MapString("#System:Redo", par.label); f := Windows.dir.Focus(Controllers.frontPath); IF (f # NIL) & f.seq.CanRedo() THEN f.seq.GetRedoName(opName); Dialog.MapString(opName, opName); Append(par.label, " "); Append(par.label, opName) ELSE par.disabled := TRUE END END RedoGuard; PROCEDURE PlainGuard* (VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF props.known * {Properties.style, Properties.weight} # {} THEN par.checked := (Properties.style IN props.valid) & (props.style.val = {}) & ({Fonts.italic, Fonts.underline, Fonts.strikeout} - props.style.mask = {}) & (Properties.weight IN props.valid) & (props.weight = Fonts.normal) ELSE par.disabled := TRUE END END PlainGuard; PROCEDURE BoldGuard* (VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF Properties.weight IN props.known THEN par.checked := (Properties.weight IN props.valid) & (props.weight = Fonts.bold) ELSE par.disabled := TRUE END END BoldGuard; PROCEDURE ItalicGuard* (VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF Properties.style IN props.known THEN par.checked := (Properties.style IN props.valid) & (Fonts.italic IN props.style.val) ELSE par.disabled := TRUE END END ItalicGuard; PROCEDURE UnderlineGuard* (VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF Properties.style IN props.known THEN par.checked := (Properties.style IN props.valid) & (Fonts.underline IN props.style.val) ELSE par.disabled := TRUE END END UnderlineGuard; PROCEDURE StrikeoutGuard* (VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF Properties.style IN props.known THEN par.checked := (Properties.style IN props.valid) & (Fonts.strikeout IN props.style.val) ELSE par.disabled := TRUE END END StrikeoutGuard; PROCEDURE SizeGuard* (size: INTEGER; VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF Properties.size IN props.known THEN par.checked := (Properties.size IN props.valid) & (size = props.size DIV Ports.point) ELSE par.disabled := TRUE END END SizeGuard; PROCEDURE ColorGuard* (color: INTEGER; VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF Properties.color IN props.known THEN par.checked := (Properties.color IN props.valid) & (color = props.color.val) ELSE par.disabled := TRUE END END ColorGuard; PROCEDURE DefaultFontGuard* (VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF Properties.typeface IN props.known THEN par.checked := (Properties.typeface IN props.valid) & (props.typeface = Fonts.default) ELSE par.disabled := TRUE END END DefaultFontGuard; PROCEDURE TypefaceGuard* (VAR par: Dialog.Par); VAR props: Properties.StdProp; BEGIN props := StdProp(); IF ~(Properties.typeface IN props.known) THEN par.disabled := TRUE END END TypefaceGuard; (* standard notifiers *) PROCEDURE DefaultOnDoubleClick* (op, from, to: INTEGER); VAR msg: Controllers.EditMsg; c: Containers.Controller; BEGIN IF (op = Dialog.pressed) & (from = 1) THEN Controllers.SetCurrentPath(Controllers.frontPath); c := Containers.Focus(); Controllers.ResetCurrentPath; IF {Containers.noSelection, Containers.noCaret} - c.opts = {} THEN msg.op := Controllers.pasteChar; msg.char := 0DX; msg.modifiers := {}; Controllers.ForwardVia(Controllers.frontPath, msg) END END END DefaultOnDoubleClick; PROCEDURE Init; BEGIN allocator := defaultAllocator; propEra := -1 END Init; BEGIN Init END StdCmds.
Std/Mod/Cmds.odc
MODULE StdCoder; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Kernel, Files, Converters, Stores, Views, Controllers, Dialog, Documents, Windows, TextModels, TextViews, TextControllers, TextMappers, StdCmds; CONST N = 16384; LineLength = 74; OldVersion = 0; ThisVersion = 1; Tag = "StdCoder.Decode"; (* first letter of Tag must not to appear within Tag again *) Separator = "/"; View = 1; File = 2; List = 3; TYPE FileList = POINTER TO RECORD next: FileList; file: Files.File; type: Files.Type; name:Dialog.String END; ParList* = RECORD list*: Dialog.Selection; storeAs*: Dialog.String; files: FileList END; VAR par*: ParList; code: ARRAY 64 OF CHAR; revCode: ARRAY 256 OF BYTE; table: ARRAY N OF BYTE; stdDocuType: Files.Type; PROCEDURE NofSelections(IN list: Dialog.Selection): INTEGER; VAR i, n: INTEGER; BEGIN i := 0; n := 0; WHILE i # list.len DO IF list.In(i) THEN INC(n) END; INC(i) END; RETURN n END NofSelections; PROCEDURE ShowError(n: INTEGER; par: ARRAY OF CHAR); BEGIN Dialog.Beep; CASE n OF 1: Dialog.ShowParamMsg("#Std:bad characters", par, "", "") | 2: Dialog.ShowParamMsg("#Std:checksum error", par, "", "") | 3: Dialog.ShowParamMsg("#Std:incompatible version", par, "", "") | 4: Dialog.ShowParamMsg("#Std:filing error", par, "", "") | 5: Dialog.ShowParamMsg("#Std:directory ^0 not found", par, "", "") | 6: Dialog.ShowParamMsg("#Std:file ^0 not found", par, "", "") | 7: Dialog.ShowParamMsg("#Std:illegal path", par, "", "") | 8: Dialog.ShowParamMsg("#Std:no tag", par, "", "") | 9: Dialog.ShowParamMsg("#Std:disk write protected", par, "", "") | 10: Dialog.ShowParamMsg("#Std:io error", par, "", "") END END ShowError; PROCEDURE ShowSizeMsg(x: INTEGER); VAR i, j: INTEGER; ch: CHAR; s: ARRAY 20 OF CHAR; BEGIN ASSERT(x >= 0, 20); i := 0; REPEAT s[i] := CHR(ORD("0") + x MOD 10); INC(i); x := x DIV 10 UNTIL x = 0; s[i] := 0X; DEC(i); j := 0; WHILE j < i DO ch := s[j]; s[j] := s[i]; s[i] := ch; INC(j); DEC(i) END; Dialog.ShowParamStatus("#Std:^0 characters coded", s, "", "") END ShowSizeMsg; PROCEDURE Write(dest: TextModels.Writer; x: INTEGER; VAR n: INTEGER); BEGIN dest.WriteChar(code[x]); INC(n); IF n = LineLength THEN dest.WriteChar(0DX); dest.WriteChar(" "); n := 0 END END Write; PROCEDURE WriteHeader(dest: TextModels.Writer; VAR n: INTEGER; name: ARRAY OF CHAR; type: BYTE ); VAR byte, bit, i: INTEGER; ch: CHAR; tag: ARRAY 16 OF CHAR; BEGIN tag := Tag; i := 0; ch := tag[0]; WHILE ch # 0X DO dest.WriteChar(ch); INC(n); INC(i); ch := tag[i] END; dest.WriteChar(" "); INC(n); bit := 0; byte := 0; i := 0; REPEAT ch := name[i]; INC(byte, ASH(ORD(ch), bit)); INC(bit, 8); WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END; INC(i) UNTIL ch = 0X; IF bit # 0 THEN Write(dest, byte, n) END; Write(dest, ThisVersion, n); Write(dest, type, n) END WriteHeader; PROCEDURE WriteFileType(dest: TextModels.Writer; VAR n: INTEGER; t: Files.Type); VAR byte, bit, i: INTEGER; ch: CHAR; BEGIN IF t = Kernel.docType THEN t := stdDocuType END; bit := 0; byte := 0; i := 0; dest.WriteChar(" "); REPEAT ch := t[i]; INC(byte, ASH(ORD(ch), bit)); INC(bit, 8); WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END; INC(i) UNTIL ch = 0X; IF bit # 0 THEN Write(dest, byte, n) END END WriteFileType; PROCEDURE WriteFile(dest: TextModels.Writer; VAR n: INTEGER; f: Files.File); VAR hash, byte, bit, i, j, sum, len: INTEGER; src: Files.Reader; b: BYTE; BEGIN len := f.Length(); j := len; i := 6; WHILE i # 0 DO Write(dest, j MOD 64, n); j := j DIV 64; DEC(i) END; i := 0; REPEAT table[i] := 0; INC(i) UNTIL i = N; hash := 0; bit := 0; byte := 0; sum := 0; src := f.NewReader(NIL); WHILE len # 0 DO src.ReadByte(b); DEC(len); sum := (sum + b MOD 256) MOD (16 * 1024); IF table[hash] = b THEN INC(bit) (* 0 bit for correct prediction *) ELSE (* Incorrect prediction -> 1'xxxx'xxxx bits *) table[hash] := b; INC(byte, ASH(1, bit)); INC(bit); INC(byte, ASH(b MOD 256, bit)); INC(bit, 8) END; WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END; hash := (16 * hash + b MOD 256) MOD N END; IF bit # 0 THEN Write(dest, byte, n) END; i := 6; WHILE i # 0 DO Write(dest, sum MOD 64, n); sum := sum DIV 64; DEC(i) END; IF n # 0 THEN dest.WriteChar(0DX); n := 0 END END WriteFile; PROCEDURE Read(src: TextModels.Reader; VAR x: INTEGER; VAR res: INTEGER); VAR ch: CHAR; BEGIN IF res = 0 THEN REPEAT src.ReadChar(ch); x := revCode[ORD(ch)] UNTIL (x >= 0) OR src.eot; IF src.eot THEN res := 1 END END; IF res # 0 THEN x := 0 END END Read; PROCEDURE ReadHeader(src: TextModels.Reader; VAR res: INTEGER; VAR name: ARRAY OF CHAR; VAR type: BYTE ); VAR x, bit, i, j: INTEGER; ch: CHAR; tag: ARRAY 16 OF CHAR; BEGIN tag := Tag; i := 0; WHILE ~src.eot & (tag[i] # 0X) DO src.ReadChar(ch); IF ch = tag[i] THEN INC(i) ELSIF ch = tag[0] THEN i := 1 ELSE i := 0 END END; IF ~src.eot THEN res := 0; i := 0; bit := 0; x := 0; REPEAT WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END; IF res = 0 THEN ch := CHR(x MOD 256); x := x DIV 256; DEC(bit, 8); name[i] := ch; INC(i) END UNTIL (res # 0) OR (ch = 0X); Read(src, j, res); IF res = 0 THEN IF (j = ThisVersion) OR (j = OldVersion) THEN Read(src, j, res); type := SHORT(SHORT(j)) ELSE res := 3 END END ELSE res := 8 END END ReadHeader; PROCEDURE ReadFileType(src: TextModels.Reader; VAR res: INTEGER; VAR ftype: Files.Type); VAR x, bit, i, j: INTEGER; ch: CHAR; BEGIN res := 0; i := 0; bit := 0; x := 0; REPEAT WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END; IF res = 0 THEN ch := CHR(x MOD 256); x := x DIV 256; DEC(bit, 8); ftype[i] := ch; INC(i) END UNTIL (res # 0) OR (ch = 0X); IF ftype = stdDocuType THEN ftype := Kernel.docType END END ReadFileType; PROCEDURE ReadFile(src: TextModels.Reader; VAR res: INTEGER; f: Files.File); VAR hash, x, bit, i, j, len, sum, s: INTEGER; byte: BYTE; dest: Files.Writer; BEGIN res := 0; i := 0; len := 0; REPEAT Read(src, x, res); len := len + ASH(x, 6 * i); INC(i) UNTIL (res # 0) OR (i = 6); i := 0; REPEAT table[i] := 0; INC(i) UNTIL i = N; bit := 0; hash := 0; sum := 0; dest := f.NewWriter(NIL); WHILE (res = 0) & (len # 0) DO IF bit = 0 THEN Read(src, x, res); bit := 6 END; IF ODD(x) THEN (* Incorrect prediction -> 1'xxxx'xxxx *) x := x DIV 2; DEC(bit); WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END; i := x MOD 256; IF i > MAX(BYTE) THEN i := i - 256 END; byte := SHORT(SHORT(i)); x := x DIV 256; DEC(bit, 8); table[hash] := byte ELSE byte := table[hash]; x := x DIV 2; DEC(bit) (* correct prediction *) END; hash := (16 * hash + byte MOD 256) MOD N; dest.WriteByte(byte); sum := (sum + byte MOD 256) MOD (16 * 1024); DEC(len) END; IF res = 0 THEN i := 0; s := 0; REPEAT Read(src, x, res); s := s + ASH(x, 6 * i); INC(i) UNTIL (res # 0) OR (i = 6); IF (res = 0) & (s # sum) THEN res := 2 END END END ReadFile; PROCEDURE ShowText (t: TextModels.Model); VAR l: INTEGER; v: Views.View; wr: TextMappers.Formatter; conv: Converters.Converter; BEGIN l := t.Length(); wr.ConnectTo(t); wr.SetPos(l); wr.WriteString(" --- end of encoding ---"); ShowSizeMsg(l); v := TextViews.dir.New(t); conv := Converters.list; WHILE (conv # NIL) & (conv.imp # "HostTextConv.ImportText") DO conv := conv.next END; Views.Open(v, NIL, "", conv); Views.SetDirty(v) END ShowText; PROCEDURE EncodedView*(v: Views.View): TextModels.Model; VAR n: INTEGER; f: Files.File; wrs: Stores.Writer; t: TextModels.Model; wr: TextModels.Writer; BEGIN f := Files.dir.Temp(); wrs.ConnectTo(f); Views.WriteView(wrs, v); t := TextModels.dir.New(); wr := t.NewWriter(NIL); n := 0; WriteHeader(wr, n, "", View); WriteFileType(wr, n, f.type); WriteFile(wr, n, f); RETURN t END EncodedView; PROCEDURE EncodeDocument*; VAR v: Views.View; w: Windows.Window; BEGIN w := Windows.dir.First(); IF w # NIL THEN v := w.doc.OriginalView(); IF (v.context # NIL) & (v.context IS Documents.Context) THEN v := v.context(Documents.Context).ThisDoc() END; IF v # NIL THEN ShowText(EncodedView(v)) END END END EncodeDocument; PROCEDURE EncodeFocus*; VAR v: Views.View; BEGIN v := Controllers.FocusView(); IF v # NIL THEN ShowText(EncodedView(v)) END END EncodeFocus; PROCEDURE EncodeSelection*; VAR beg, end: INTEGER; t: TextModels.Model; c: TextControllers.Controller; BEGIN c := TextControllers.Focus(); IF (c # NIL) & c.HasSelection() THEN c.GetSelection(beg, end); t := TextModels.CloneOf(c.text); t.InsertCopy(0, c.text, beg, end); ShowText(EncodedView(TextViews.dir.New(t))) END END EncodeSelection; PROCEDURE EncodeFile*; VAR n: INTEGER; loc: Files.Locator; name: Files.Name; f: Files.File; t: TextModels.Model; wr: TextModels.Writer; BEGIN Dialog.GetIntSpec("", loc, name); IF loc # NIL THEN f := Files.dir.Old(loc, name, TRUE); IF f # NIL THEN t := TextModels.dir.New(); wr := t.NewWriter(NIL); n := 0; WriteHeader(wr, n, name, File); WriteFileType(wr, n, f.type); WriteFile(wr, n, f); ShowText(t) END END END EncodeFile; PROCEDURE GetFile(VAR path: ARRAY OF CHAR; VAR loc: Files.Locator; VAR name: Files.Name); VAR i, j: INTEGER; ch: CHAR; BEGIN i := 0; ch := path[0]; loc := Files.dir.This(""); WHILE (ch # 0X) & (loc # NIL) DO j := 0; WHILE (ch # 0X) & (ch # Separator) DO name[j] := ch; INC(j); INC(i); ch := path[i] END; name[j] := 0X; IF ch = Separator THEN loc := loc.This(name); INC(i); ch := path[i] END; IF loc.res # 0 THEN loc := NIL END END; path[i] := 0X END GetFile; PROCEDURE ReadPath(rd: TextModels.Reader; VAR path: ARRAY OF CHAR; VAR len: INTEGER); VAR i, l: INTEGER; ch: CHAR; BEGIN i := 0; l := LEN(path) - 1; REPEAT rd.ReadChar(ch) UNTIL rd.eot OR (ch > " "); WHILE ~rd.eot & (ch > " ") & (i < l) DO path[i] := ch; INC(i); rd.ReadChar(ch) END; path[i] := 0X; len := i END ReadPath; PROCEDURE WriteString(w: Files.Writer; IN str: ARRAY OF CHAR; len: INTEGER); VAR i: INTEGER; BEGIN i := 0; WHILE i < len DO IF ORD(str[i]) > MAX(BYTE) THEN w.WriteByte(SHORT(SHORT(ORD(str[i]) - 256))) ELSE w.WriteByte(SHORT(SHORT(ORD(str[i])))) END; INC(i) END END WriteString; PROCEDURE EncodeFileList*; TYPE FileList = POINTER TO RECORD next: FileList; f: Files.File END; VAR beg, end, i, j, n: INTEGER; err: BOOLEAN; files, last: FileList; list, f: Files.File; w: Files.Writer; loc: Files.Locator; rd: TextModels.Reader; wr: TextModels.Writer; t: TextModels.Model; c: TextControllers.Controller; name: Files.Name; path, next: ARRAY 2048 OF CHAR; BEGIN c := TextControllers.Focus(); IF (c # NIL) & c.HasSelection() THEN c.GetSelection(beg, end); rd := c.text.NewReader(NIL); rd.SetPos(beg); err := FALSE; list := Files.dir.Temp(); w := list.NewWriter(NIL); files := NIL; last := NIL; ReadPath(rd, path, i); WHILE (path # "") & (rd.Pos() - i < end) & ~err DO GetFile(path, loc, name); IF loc # NIL THEN f := Files.dir.Old(loc, name, TRUE); err := f = NIL; IF ~err THEN IF last = NIL THEN NEW(last); files := last ELSE NEW(last.next); last := last.next END; last.f := f; ReadPath(rd, next, j); IF (next = "=>") & (rd.Pos() - j < end) THEN ReadPath(rd, next, j); IF next # "" THEN WriteString(w, next, j + 1); ReadPath(rd, next, j) ELSE err := TRUE END ELSE WriteString(w, path, i + 1) END; path := next; i := j END ELSE err := TRUE END END; IF ~err & (files # NIL) THEN t := TextModels.dir.New(); wr := t.NewWriter(NIL); n := 0; WriteHeader(wr, n, "", List); WriteFileType(wr, n, list.type); WriteFile(wr, n, list); WHILE files # NIL DO WriteFileType(wr, n, files.f.type); WriteFile(wr, n, files.f); files := files.next END; ShowText(t) ELSIF err THEN IF path = "" THEN ShowError(7, path) ELSIF loc # NIL THEN ShowError(6, path) ELSE ShowError(5, path) END END END END EncodeFileList; PROCEDURE DecodeView(rd: TextModels.Reader; name: Files.Name); VAR res: INTEGER; f: Files.File; ftype: Files.Type; rds: Stores.Reader; v: Views.View; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN f := Files.dir.Temp(); ReadFile(rd, res, f); IF res = 0 THEN rds.ConnectTo(f); Views.ReadView(rds, v); Views.Open(v, NIL, name, NIL); Views.SetDirty(v) ELSE ShowError(res, "") END ELSE ShowError(res, "") END END DecodeView; PROCEDURE DecodeFile(rd: TextModels.Reader; name: Files.Name); VAR res: INTEGER; ftype: Files.Type; loc: Files.Locator; f: Files.File; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN Dialog.GetExtSpec(name, ftype, loc, name); IF loc # NIL THEN f := Files.dir.New(loc, Files.ask); IF f # NIL THEN ReadFile(rd, res, f); IF res = 0 THEN f.Register(name, ftype, Files.ask, res); IF res # 0 THEN ShowError(4, "") END ELSE ShowError(res, "") END ELSIF loc.res = 4 THEN ShowError(9, "") ELSIF loc.res = 5 THEN ShowError(10, "") END END ELSE ShowError(res, "") END END DecodeFile; PROCEDURE DecodeFileList (rd: TextModels.Reader; VAR files: FileList; VAR len, res: INTEGER); VAR i, n: INTEGER; b: BYTE; p: FileList; ftype: Files.Type; f: Files.File; frd: Files.Reader; path: Dialog.String; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN f := Files.dir.Temp(); ReadFile(rd, res, f); IF res = 0 THEN files := NIL; p := NIL; n := 0; frd := f.NewReader(NIL); frd.ReadByte(b); WHILE ~frd.eof & (res = 0) DO INC(n); i := 0; WHILE ~frd.eof & (b # 0) DO path[i] := CHR(b MOD 256); INC(i); frd.ReadByte(b) END; IF (i > 4) & (path[i - 4] = ".") & (CAP(path[i - 3]) = "O") & (CAP(path[i - 2]) = "D") & (CAP(path[i - 1]) = "C") THEN path[i - 4] := 0X ELSE path[i] := 0X END; IF ~frd.eof THEN IF p = NIL THEN NEW(p); files := p ELSE NEW(p.next); p := p.next END; p.name := path; frd.ReadByte(b) ELSE res := 1 END END; p := files; len := n; WHILE (res = 0) & (p # NIL) DO ReadFileType(rd, res, p.type); IF res = 0 THEN p.file := Files.dir.Temp(); ReadFile(rd, res, p.file) END; p := p.next END END END END DecodeFileList; PROCEDURE OpenDialog(files: FileList; len: INTEGER); VAR i: INTEGER; p: FileList; BEGIN par.files := files; par.list.SetLen(len); p := files; i := 0; WHILE p # NIL DO par.list.SetItem(i, p.name); INC(i); p := p.next END; par.storeAs := ""; Dialog.Update(par); Dialog.UpdateList(par.list); StdCmds.OpenAuxDialog("Std/Rsrc/Coder", "Decode") END OpenDialog; PROCEDURE CloseDialog*; BEGIN par.files := NIL; par.list.SetLen(0); par.storeAs := ""; Dialog.UpdateList(par.list); Dialog.Update(par) END CloseDialog; PROCEDURE Select*(op, from, to: INTEGER); VAR p: FileList; i: INTEGER; BEGIN IF (op = Dialog.included) OR (op = Dialog.excluded) OR (op = Dialog.set) THEN IF NofSelections(par.list) = 1 THEN i := 0; p := par.files; WHILE ~par.list.In(i) DO INC(i); p := p.next END; par.storeAs := p.name ELSE par.storeAs := "" END; Dialog.Update(par) END END Select; PROCEDURE CopyFile(from: Files.File; loc: Files.Locator; name: Files.Name; type: Files.Type); CONST BufSize = 4096; VAR res, k, l: INTEGER; f: Files.File; r: Files.Reader; w: Files.Writer; buf: ARRAY BufSize OF BYTE; BEGIN f := Files.dir.New(loc, Files.ask); IF f # NIL THEN r := from.NewReader(NIL); w := f.NewWriter(NIL); l := from.Length(); WHILE l # 0 DO IF l <= BufSize THEN k := l ELSE k := BufSize END; r.ReadBytes(buf, 0, k); w.WriteBytes(buf, 0, k); l := l - k END; f.Register(name, type, Files.ask, res); IF res # 0 THEN ShowError(4, "") END ELSIF loc.res = 4 THEN ShowError(9, "") ELSIF loc.res = 5 THEN ShowError(10, "") END END CopyFile; PROCEDURE StoreSelection*; VAR i, n: INTEGER; p: FileList; loc: Files.Locator; name: Files.Name; BEGIN n := NofSelections(par.list); IF n > 1 THEN i := 0; p := par.files; WHILE n # 0 DO WHILE ~par.list.In(i) DO INC(i); p := p.next END; GetFile(p.name, loc, name); CopyFile(p.file, loc, name, p.type); DEC(n); INC(i); p := p.next END ELSIF (n = 1) & (par.storeAs # "") THEN i := 0; p := par.files; WHILE ~par.list.In(i) DO INC(i); p := p.next END; GetFile(par.storeAs, loc, name); CopyFile(p.file, loc, name, p.type) END END StoreSelection; PROCEDURE StoreSelectionGuard*(VAR p: Dialog.Par); VAR n: INTEGER; BEGIN n := NofSelections(par.list); p.disabled := (n = 0) OR ((n = 1) & (par.storeAs = "")) END StoreSelectionGuard; PROCEDURE StoreSingle*; VAR i: INTEGER; p: FileList; loc: Files.Locator; name: Files.Name; BEGIN IF NofSelections(par.list) = 1 THEN i := 0; p := par.files; WHILE ~par.list.In(i) DO INC(i); p := p.next END; GetFile(p.name, loc, name); Dialog.GetExtSpec(name, p.type, loc, name); IF loc # NIL THEN CopyFile(p.file, loc, name, p.type) END END END StoreSingle; PROCEDURE StoreSingleGuard*(VAR p: Dialog.Par); BEGIN p.disabled := NofSelections(par.list) # 1 END StoreSingleGuard; PROCEDURE StoreAllFiles(files: FileList); VAR loc: Files.Locator; name: Files.Name; BEGIN WHILE files # NIL DO GetFile(files.name, loc, name); CopyFile(files.file, loc, name, files.type); files := files.next END END StoreAllFiles; PROCEDURE StoreAll*; BEGIN StoreAllFiles(par.files) END StoreAll; PROCEDURE DecodeAllFromText*(text: TextModels.Model; beg: INTEGER; ask: BOOLEAN); VAR res, i: INTEGER; type: BYTE; name: Files.Name; rd: TextModels.Reader; files: FileList; BEGIN CloseDialog; rd := text.NewReader(NIL); rd.SetPos(beg); ReadHeader(rd, res, name, type); i := 0; WHILE name[i] # 0X DO INC(i) END; IF (i > 4) & (name[i - 4] = ".") & (CAP(name[i - 3]) = "O") & (CAP(name[i - 2]) = "D") & (CAP(name[i - 1]) = "C") THEN name[i - 4] := 0X END; IF res = 0 THEN IF type = View THEN DecodeView(rd, name) ELSIF type = File THEN DecodeFile(rd, name) ELSIF type = List THEN DecodeFileList(rd, files, i, res); IF res = 0 THEN IF ask THEN OpenDialog(files, i) ELSE StoreAllFiles(files) END ELSE ShowError(res, "") END ELSE ShowError(3, "") END ELSE ShowError(res, "") END END DecodeAllFromText; PROCEDURE Decode*; VAR beg, end: INTEGER; c: TextControllers.Controller; BEGIN CloseDialog; c := TextControllers.Focus(); IF c # NIL THEN IF c.HasSelection() THEN c.GetSelection(beg, end) ELSE beg := 0 END; DecodeAllFromText(c.text, beg, TRUE) END END Decode; PROCEDURE ListFiles(rd: TextModels.Reader; VAR wr: TextMappers.Formatter); VAR i, n, res: INTEGER; b: BYTE; ftype: Files.Type; f: Files.File; frd: Files.Reader; path: Dialog.String; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN f := Files.dir.Temp(); ReadFile(rd, res, f); IF res = 0 THEN n := 0; frd := f.NewReader(NIL); frd.ReadByte(b); WHILE ~frd.eof & (res = 0) DO INC(n); i := 0; WHILE ~frd.eof & (b # 0) DO path[i] := CHR(b MOD 256); INC(i); frd.ReadByte(b) END; IF (i > 4) & (path[i - 4] = ".") & (CAP(path[i - 3]) = "O") & (CAP(path[i - 2]) = "D") & (CAP(path[i - 1]) = "C") THEN path[i - 4] := 0X ELSE path[i] := 0X END; IF ~frd.eof THEN wr.WriteString(path); wr.WriteLn; frd.ReadByte(b) ELSE res := 1 END END ELSE ShowError(res, "") END ELSE ShowError(res, "") END END ListFiles; PROCEDURE ListSingleton(type, name: ARRAY OF CHAR; VAR wr: TextMappers.Formatter); BEGIN wr.WriteString(type); IF name # "" THEN wr.WriteString(": '"); wr.WriteString(name); wr.WriteChar("'") END; wr.WriteLn END ListSingleton; PROCEDURE EncodedInText*(text: TextModels.Model; beg: INTEGER): TextModels.Model; VAR res, i: INTEGER; type: BYTE; name: Files.Name; rd: TextModels.Reader; report: TextModels.Model; wr: TextMappers.Formatter; BEGIN report := TextModels.dir.New(); wr.ConnectTo(report); rd := text.NewReader(NIL); rd.SetPos(beg); ReadHeader(rd, res, name, type); i := 0; WHILE name[i] # 0X DO INC(i) END; IF (i > 4) & (name[i - 4] = ".") & (CAP(name[i - 3]) = "O") & (CAP(name[i - 2]) = "D") & (CAP(name[i - 1]) = "C") THEN name[i - 4] := 0X END; IF res = 0 THEN IF type = View THEN ListSingleton("View", name, wr) ELSIF type = File THEN ListSingleton("File", name, wr) ELSIF type = List THEN ListFiles(rd, wr) ELSE ShowError(3, "") END ELSE ShowError(res, "") END; RETURN report END EncodedInText; PROCEDURE ListEncodedMaterial*; VAR beg, end: INTEGER; c: TextControllers.Controller; BEGIN c := TextControllers.Focus(); IF c # NIL THEN IF c.HasSelection() THEN c.GetSelection(beg, end) ELSE beg := 0 END; Views.OpenView(TextViews.dir.New(EncodedInText(c.text, beg))) END END ListEncodedMaterial; PROCEDURE InitCodes; VAR i: BYTE; j: INTEGER; BEGIN j := 0; WHILE j # 256 DO revCode[j] := -1; INC(j) END; code[0] := "."; revCode[ORD(".")] := 0; code[1] := ","; revCode[ORD(",")] := 1; i := 2; j := ORD("0"); WHILE j <= ORD("9") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END; j := ORD("A"); WHILE j <= ORD("Z") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END; j := ORD("a"); WHILE j <= ORD("z") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END; ASSERT(i = 64, 60) END InitCodes; BEGIN InitCodes; stdDocuType[0] := 3X; stdDocuType[1] := 3X; stdDocuType[2] := 3X; stdDocuType[3] := 0X END StdCoder.
Std/Mod/Coder.odc
MODULE StdDebug; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT SYSTEM, Kernel, Strings, Fonts, Services, Ports, Views, Properties, Dialog, Containers, StdFolds, TextModels, TextMappers, TextViews, TextRulers; CONST refViewSize = 9 * Ports.point; heap = 1; source = 2; module = 3; modules = 4; (* RefView types *) TYPE Name = Kernel.Name; ArrayPtr = POINTER TO RECORD last, t, first: INTEGER; (* gc header *) len: ARRAY 16 OF INTEGER (* dynamic array length table *) END; RefView = POINTER TO RefViewDesc; RefViewDesc = RECORD type: SHORTINT; command: SHORTINT; back: RefView; adr: INTEGER; desc: Kernel.Type; ptr: ArrayPtr; name: Name END; Action = POINTER TO RECORD (Services.Action) text: TextModels.Model END; Cluster = POINTER TO RECORD [untagged] (* must correspond to Kernel.Cluster *) size: INTEGER; next: Cluster END; VAR out: TextMappers.Formatter; path: ARRAY 4 OF Ports.Point; empty: Name; PROCEDURE NewRuler (): TextRulers.Ruler; CONST mm = Ports.mm; VAR r: TextRulers.Ruler; BEGIN r := TextRulers.dir.New(NIL); TextRulers.SetRight(r, 140 * mm); TextRulers.AddTab(r, 4 * mm); TextRulers.AddTab(r, 34 * mm); TextRulers.AddTab(r, 80 * mm); RETURN r END NewRuler; PROCEDURE OpenViewer (t: TextModels.Model; title: Views.Title; ruler:TextRulers.Ruler); VAR v: TextViews.View; c: Containers.Controller; BEGIN Dialog.MapString(title, title); v := TextViews.dir.New(t); v.SetDefaults(ruler, TextViews.dir.defAttr); c := v.ThisController(); IF c # NIL THEN c.SetOpts(c.opts - {Containers.noFocus, Containers.noSelection} + {Containers.noCaret}) END; Views.OpenAux(v, title) END OpenViewer; PROCEDURE OpenFold (hidden: ARRAY OF CHAR); VAR fold: StdFolds.Fold; t: TextModels.Model; w: TextMappers.Formatter; BEGIN Dialog.MapString(hidden, hidden); t := TextModels.dir.New(); w.ConnectTo(t); w.WriteString(hidden); fold := StdFolds.dir.New(StdFolds.expanded, "", t); out.WriteView(fold) END OpenFold; PROCEDURE CloseFold (collaps: BOOLEAN); VAR fold: StdFolds.Fold; m: TextModels.Model; BEGIN fold := StdFolds.dir.New(StdFolds.expanded, "", NIL); out.WriteView(fold); IF collaps THEN fold.Flip(); m := out.rider.Base(); out.SetPos(m.Length()) END END CloseFold; PROCEDURE WriteHex (n: INTEGER); BEGIN out.WriteIntForm(n, TextMappers.hexadecimal, 9, "0", TextMappers.showBase) END WriteHex; PROCEDURE WriteString (adr, len, base: INTEGER; zterm: BOOLEAN); CONST beg = 0; char = 1; code = 2; VAR ch: SHORTCHAR; val, mode: SHORTINT; str: ARRAY 16 OF CHAR; BEGIN mode := beg; IF base = 2 THEN SYSTEM.GET(adr, val) ELSE SYSTEM.GET(adr, ch); val := ORD(ch) END; IF zterm & (val = 0) THEN out.WriteSString('""') ELSE REPEAT IF (val >= ORD(" ")) & (val < 7FH) OR (val > 0A0H) & (val < 256) THEN IF mode # char THEN IF mode = code THEN out.WriteSString(", ") END; out.WriteChar(22X); mode := char END; out.WriteChar(SHORT(CHR(val))) ELSE IF mode = char THEN out.WriteChar(22X) END; IF mode # beg THEN out.WriteSString(", ") END; mode := code; Strings.IntToStringForm(val, Strings.hexadecimal, 1, "0", FALSE, str); IF str[0] > "9" THEN out.WriteChar("0") END; out.WriteString(str); out.WriteChar("X") END; INC(adr, base); DEC(len); IF base = 2 THEN SYSTEM.GET(adr, val) ELSE SYSTEM.GET(adr, ch); val := ORD(ch) END UNTIL (len = 0) OR zterm & (val = 0) END; IF mode = char THEN out.WriteChar(22X) END END WriteString; PROCEDURE OutString (s: ARRAY OF CHAR); VAR str: Dialog.String; BEGIN Dialog.MapString(s, str); out.WriteString(str) END OutString; (* ------------------- variable display ------------------- *) PROCEDURE FormOf (t: Kernel.Type): SHORTCHAR; BEGIN IF SYSTEM.VAL(INTEGER, t) DIV 256 = 0 THEN RETURN SHORT(CHR(SYSTEM.VAL(INTEGER, t))) ELSE RETURN SHORT(CHR(16 + t.id MOD 4)) END END FormOf; PROCEDURE LenOf (t: Kernel.Type; ptr: ArrayPtr): INTEGER; BEGIN IF t.size # 0 THEN RETURN t.size ELSIF ptr # NIL THEN RETURN ptr.len[t.id DIV 16 MOD 16 - 1] ELSE RETURN 0 END END LenOf; PROCEDURE SizeOf (t: Kernel.Type; ptr: ArrayPtr): INTEGER; BEGIN CASE FormOf(t) OF | 0BX: RETURN 0 | 1X, 2X, 4X: RETURN 1 | 3X, 5X: RETURN 2 | 8X, 0AX: RETURN 8 | 11X: RETURN t.size | 12X: RETURN LenOf(t, ptr) * SizeOf(t.base[0], ptr) ELSE RETURN 4 END END SizeOf; PROCEDURE WriteName (t: Kernel.Type; ptr: ArrayPtr); VAR name: Kernel.Name; f: SHORTCHAR; BEGIN f := FormOf(t); CASE f OF | 0X: OutString("#Dev:Unknown") | 1X: out.WriteSString("BOOLEAN") | 2X: out.WriteSString("SHORTCHAR") | 3X: out.WriteSString("CHAR") | 4X: out.WriteSString("BYTE") | 5X: out.WriteSString("SHORTINT") | 6X: out.WriteSString("INTEGER") | 7X: out.WriteSString("SHORTREAL") | 8X: out.WriteSString("REAL") | 9X: out.WriteSString("SET") | 0AX: out.WriteSString("LONGINT") | 0BX: out.WriteSString("ANYREC") | 0CX: out.WriteSString("ANYPTR") | 0DX: out.WriteSString("POINTER") | 0EX: out.WriteSString("PROCEDURE") | 0FX: out.WriteSString("STRING") | 10X..13X: Kernel.GetTypeName(t, name); IF name = "!" THEN IF f = 11X THEN out.WriteSString("RECORD") ELSIF f = 12X THEN out.WriteSString("ARRAY") ELSE OutString("#Dev:Unknown") END ELSIF (t.id DIV 256 # 0) & (t.mod.refcnt >= 0) THEN out.WriteSString(t.mod.name); out.WriteChar("."); out.WriteSString(name) ELSIF f = 11X THEN out.WriteSString(t.mod.name); out.WriteSString(".RECORD") ELSIF f = 12X THEN out.WriteSString("ARRAY "); out.WriteInt(LenOf(t, ptr)); t := t.base[0]; WHILE (FormOf(t) = 12X) & ((t.id DIV 256 = 0) OR (t.mod.refcnt < 0)) DO out.WriteSString(", "); out.WriteInt(LenOf(t, ptr)); t := t.base[0] END; out.WriteSString(" OF "); WriteName(t, ptr) ELSIF f = 13X THEN out.WriteSString("POINTER") ELSE out.WriteSString("PROCEDURE") END | 20X: out.WriteSString("COM.IUnknown") | 21X: out.WriteSString("COM.GUID") | 22X: out.WriteSString("COM.RESULT") ELSE OutString("#Dev:UnknownFormat"); out.WriteInt(ORD(f)) END END WriteName; PROCEDURE WriteGuid (a: INTEGER); PROCEDURE Hex (a: INTEGER); VAR x: SHORTCHAR; BEGIN SYSTEM.GET(a, x); out.WriteIntForm(ORD(x), TextMappers.hexadecimal, 2, "0", FALSE) END Hex; BEGIN out.WriteChar("{"); Hex(a + 3); Hex(a + 2); Hex(a + 1); Hex(a); out.WriteChar("-"); Hex(a + 5); Hex(a + 4); out.WriteChar("-"); Hex(a + 7); Hex(a + 6); out.WriteChar("-"); Hex(a + 8); Hex(a + 9); out.WriteChar("-"); Hex(a + 10); Hex(a + 11); Hex(a + 12); Hex(a + 13); Hex(a + 14); Hex(a + 15); out.WriteChar("}") END WriteGuid; PROCEDURE^ ShowVar (ad, ind: INTEGER; f, c: SHORTCHAR; desc: Kernel.Type; ptr: ArrayPtr; back: RefView; VAR name, sel: Name); PROCEDURE ShowRecord (a, ind: INTEGER; desc: Kernel.Type; back: RefView; VAR sel: Name); VAR dir: Kernel.Directory; obj: Kernel.Object; name: Kernel.Name; i, j, n: INTEGER; base: Kernel.Type; BEGIN WriteName(desc, NIL); out.WriteTab; IF desc.mod.refcnt >= 0 THEN OpenFold("#Dev:Fields"); n := desc.id DIV 16 MOD 16; j := 0; WHILE j <= n DO base := desc.base[j]; IF base # NIL THEN dir := base.fields; i := 0; WHILE i < dir.num DO obj := SYSTEM.VAL(Kernel.Object, SYSTEM.ADR(dir.obj[i])); Kernel.GetObjName(base.mod, obj, name); ShowVar(a + obj.offs, ind, FormOf(obj.struct), 1X, obj.struct, NIL, back, name, sel); INC(i) END END; INC(j) END; out.WriteSString(" "); CloseFold((ind > 1) OR (sel # "")) ELSE OutString("#Dev:Unloaded") END END ShowRecord; PROCEDURE ShowArray (a, ind: INTEGER; desc: Kernel.Type; ptr: ArrayPtr; back: RefView; VAR sel: Name); VAR f: SHORTCHAR; i, n, m, size, len: INTEGER; name: Kernel.Name; eltyp, t: Kernel.Type; vi: SHORTINT; vs: BYTE; str: Dialog.String; BEGIN WriteName(desc, ptr); out.WriteTab; len := LenOf(desc, ptr); eltyp := desc.base[0]; f := FormOf(eltyp); size := SizeOf(eltyp, ptr); IF (f = 2X) OR (f = 3X) THEN (* string *) n := 0; m := len; IF f = 2X THEN REPEAT SYSTEM.GET(a + n, vs); INC(n) UNTIL (n = 32) OR (n = len) OR (vs = 0); REPEAT DEC(m); SYSTEM.GET(a + m, vs) UNTIL (m = 0) OR (vs # 0) ELSE REPEAT SYSTEM.GET(a + n * 2, vi); INC(n) UNTIL (n = 32) OR (n = len) OR (vi = 0); REPEAT DEC(m); SYSTEM.GET(a + m * 2, vi) UNTIL (m = 0) OR (vi # 0) END; WriteString(a, n, size, TRUE); INC(m, 2); IF m > len THEN m := len END; IF m > n THEN out.WriteSString(" "); OpenFold("..."); out.WriteLn; WriteString(a, m, size, FALSE); IF m < len THEN out.WriteSString(", ..., 0X") END; out.WriteSString(" "); CloseFold(TRUE) END ELSE t := eltyp; WHILE FormOf(t) = 12X DO t := t.base[0] END; IF FormOf(t) # 0X THEN OpenFold("#Dev:Elements"); i := 0; WHILE i < len DO Strings.IntToString(i, str); name := "[" + SHORT(str$) + "]"; ShowVar(a, ind, f, 1X, eltyp, ptr, back, name, sel); INC(i); INC(a, size) END; out.WriteSString(" "); CloseFold(TRUE) END END END ShowArray; PROCEDURE ShowProcVar (a: INTEGER); VAR vli, n, ref: INTEGER; m: Kernel.Module; name: Kernel.Name; BEGIN SYSTEM.GET(a, vli); Kernel.SearchProcVar(vli, m, vli); IF m = NIL THEN IF vli = 0 THEN out.WriteSString("NIL") ELSE WriteHex(vli) END ELSE IF m.refcnt >= 0 THEN out.WriteSString(m.name); ref := m.refs; REPEAT Kernel.GetRefProc(ref, n, name) UNTIL (n = 0) OR (vli < n); IF vli < n THEN out.WriteChar("."); out.WriteSString(name) END ELSE OutString("#Dev:ProcInUnloadedMod"); out.WriteSString(m.name); out.WriteSString(" !!!") END END END ShowProcVar; PROCEDURE ShowPointer (a: INTEGER; f: SHORTCHAR; desc: Kernel.Type; back: RefView; VAR sel: Name); VAR adr, x: INTEGER; ptr: ArrayPtr; c: Cluster; btyp: Kernel.Type; BEGIN SYSTEM.GET(a, adr); IF f = 13X THEN btyp := desc.base[0] ELSE btyp := NIL END; IF adr = 0 THEN out.WriteSString("NIL") ELSIF f = 20X THEN out.WriteChar("["); WriteHex(adr); out.WriteChar("]"); out.WriteChar(" "); c := SYSTEM.VAL(Cluster, Kernel.Root()); WHILE (c # NIL) & ((adr < SYSTEM.VAL(INTEGER, c)) OR (adr >= SYSTEM.VAL(INTEGER, c) + c.size)) DO c := c.next END; IF c # NIL THEN ptr := SYSTEM.VAL(ArrayPtr, adr) END ELSE IF (f = 13X) OR (f = 0CX) THEN x := adr - 4 ELSE x := adr END; IF ((adr < -4) OR (adr >= 65536)) & Kernel.IsReadable(x, adr + 16) THEN out.WriteChar("["); WriteHex(adr); out.WriteChar("]"); IF (f = 13X) OR (f = 0CX) THEN out.WriteChar(" "); c := SYSTEM.VAL(Cluster, Kernel.Root()); WHILE (c # NIL) & ((adr < SYSTEM.VAL(INTEGER, c)) OR (adr >= SYSTEM.VAL(INTEGER, c) + c.size)) DO c := c.next END; IF c # NIL THEN ptr := SYSTEM.VAL(ArrayPtr, adr); IF (f = 13X) & (FormOf(btyp) = 12X) THEN (* array *) adr := SYSTEM.ADR(ptr.len[btyp.id DIV 16 MOD 16]) END ELSE OutString("#Dev:IllegalPointer") END END ELSE OutString("#Dev:IllegalAddress"); WriteHex(adr) END END END ShowPointer; PROCEDURE ShowSelector (ref: RefView); VAR b: RefView; n: SHORTINT; a, a0: TextModels.Attributes; BEGIN b := ref.back; n := 1; IF b # NIL THEN WHILE (b.name = ref.name) & (b.back # NIL) DO INC(n); b := b.back END; ShowSelector(b); IF n > 1 THEN out.WriteChar("(") END; out.WriteChar(".") END; out.WriteSString(ref.name); IF ref.type = heap THEN out.WriteChar("^") END; IF n > 1 THEN out.WriteChar(")"); a0 := out.rider.attr; a := TextModels.NewOffset(a0, 2 * Ports.point); out.rider.SetAttr(a); out.WriteInt(n); out.rider.SetAttr(a0) END END ShowSelector; PROCEDURE ShowVar (ad, ind: INTEGER; f, c: SHORTCHAR; desc: Kernel.Type; ptr: ArrayPtr; back: RefView; VAR name, sel: Name); VAR i, j, vli, a: INTEGER; tsel: Name; a0: TextModels.Attributes; vc: SHORTCHAR; vsi: BYTE; vi: SHORTINT; vr: SHORTREAL; vlr: REAL; vs: SET; BEGIN out.WriteLn; out.WriteTab; i := 0; WHILE i < ind DO out.WriteSString(" "); INC(i) END; a := ad; i := 0; j := 0; IF sel # "" THEN WHILE sel[i] # 0X DO tsel[i] := sel[i]; INC(i) END; IF (tsel[i-1] # ":") & (name[0] # "[") THEN tsel[i] := "."; INC(i) END END; WHILE name[j] # 0X DO tsel[i] := name[j]; INC(i); INC(j) END; tsel[i] := 0X; a0 := out.rider.attr; IF c = 3X THEN (* varpar *) SYSTEM.GET(ad, a); out.rider.SetAttr(TextModels.NewStyle(a0, {Fonts.italic})) END; IF name[0] # "[" THEN out.WriteChar(".") END; out.WriteSString(name); out.rider.SetAttr(a0); out.WriteTab; IF (c = 3X) & (a >= 0) & (a < 65536) THEN out.WriteTab; out.WriteSString("NIL VARPAR") ELSIF f = 11X THEN Kernel.GetTypeName(desc, name); IF (c = 3X) & (name[0] # "!") THEN SYSTEM.GET(ad + 4, desc) END; (* dynamic type *) ShowRecord(a, ind + 1, desc, back, tsel) ELSIF (c = 3X) & (f = 0BX) THEN (* VAR anyrecord *) SYSTEM.GET(ad + 4, desc); ShowRecord(a, ind + 1, desc, back, tsel) ELSIF f = 12X THEN IF (desc.size = 0) & (ptr = NIL) THEN SYSTEM.GET(ad, a) END; (* dyn array val par *) IF ptr = NIL THEN ptr := SYSTEM.VAL(ArrayPtr, ad - 8) END; ShowArray(a, ind + 1, desc, ptr, back, tsel) ELSE IF desc = NIL THEN desc := SYSTEM.VAL(Kernel.Type, ORD(f)) END; WriteName(desc, NIL); out.WriteTab; CASE f OF | 0X: (* SYSTEM.GET(a, vli); WriteHex(vli) *) | 1X: SYSTEM.GET(a, vc); IF vc = 0X THEN out.WriteSString("FALSE") ELSIF vc = 1X THEN out.WriteSString("TRUE") ELSE OutString("#Dev:Undefined"); out.WriteInt(ORD(vc)) END | 2X: WriteString(a, 1, 1, FALSE) | 3X: WriteString(a, 1, 2, FALSE) | 4X: SYSTEM.GET(a, vsi); out.WriteInt(vsi) | 5X: SYSTEM.GET(a, vi); out.WriteInt(vi) | 6X: SYSTEM.GET(a, vli); out.WriteInt(vli) | 7X: SYSTEM.GET(a, vr); out.WriteReal(vr) | 8X: SYSTEM.GET(a, vlr); out.WriteReal(vlr) | 9X: SYSTEM.GET(a, vs); out.WriteSet(vs) | 0AX: SYSTEM.GET(a, vli); SYSTEM.GET(a + 4, i); IF (vli >= 0) & (i = 0) OR (vli < 0) & (i = -1) THEN out.WriteInt(vli) ELSE out.WriteIntForm(i, TextMappers.hexadecimal, 8, "0", TextMappers.hideBase); WriteHex(vli) END | 0CX, 0DX, 13X, 20X: ShowPointer(a, f, desc, back, tsel) | 0EX, 10X: ShowProcVar(a) | 0FX: WriteString(a, 256, 1, TRUE) | 21X: WriteGuid(a) | 22X: SYSTEM.GET(a, vli); WriteHex(vli) ELSE END END END ShowVar; PROCEDURE ShowStack; VAR ref, end, i, j, x, a, b, c: INTEGER; m, f: SHORTCHAR; mod: Kernel.Module; name, sel: Kernel.Name; d: Kernel.Type; BEGIN a := Kernel.pc; b := Kernel.fp; c := 100; REPEAT mod := Kernel.modList; WHILE (mod # NIL) & ((a < mod.code) OR (a >= mod.code + mod.csize)) DO mod := mod.next END; IF mod # NIL THEN DEC(a, mod.code); IF mod.refcnt >= 0 THEN out.WriteChar(" "); out.WriteSString(mod.name); ref := mod.refs; REPEAT Kernel.GetRefProc(ref, end, name) UNTIL (end = 0) OR (a < end); IF a < end THEN out.WriteChar("."); out.WriteSString(name); sel := mod.name$; i := 0; WHILE sel[i] # 0X DO INC(i) END; sel[i] := "."; INC(i); j := 0; WHILE name[j] # 0X DO sel[i] := name[j]; INC(i); INC(j) END; sel[i] := ":"; sel[i+1] := 0X; out.WriteSString(" ["); WriteHex(a); out.WriteSString("] "); i := Kernel.SourcePos(mod, 0); IF name # "$$" THEN Kernel.GetRefVar(ref, m, f, d, x, name); WHILE m # 0X DO IF name[0] # "@" THEN ShowVar(b + x, 0, f, m, d, NIL, NIL, name, sel) END; Kernel.GetRefVar(ref, m, f, d, x, name) END END; out.WriteLn ELSE out.WriteSString(".???"); out.WriteLn END ELSE out.WriteChar("("); out.WriteSString(mod.name); out.WriteSString(") (pc="); WriteHex(a); out.WriteSString(", fp="); WriteHex(b); out.WriteChar(")"); out.WriteLn END ELSE out.WriteSString("<system> (pc="); WriteHex(a); out.WriteSString(", fp="); WriteHex(b); out.WriteChar(")"); out.WriteLn END; IF (b >= Kernel.fp) & (b < Kernel.stack) THEN SYSTEM.GET(b+4, a); (* stacked pc *) SYSTEM.GET(b, b); (* dynamic link *) DEC(a); DEC(c) ELSE c := 0 END UNTIL c = 0 END ShowStack; PROCEDURE (a: Action) Do; (* delayed trap window open *) BEGIN Kernel.SetTrapGuard(TRUE); OpenViewer(a.text, "#Dev:Trap", NewRuler()); Kernel.SetTrapGuard(FALSE); END Do; PROCEDURE GetTrapMsg(OUT msg: ARRAY OF CHAR); VAR ref, end, a: INTEGER; mod: Kernel.Module; name: Kernel.Name; head, tail, errstr: ARRAY 32 OF CHAR; key: ARRAY 128 OF CHAR; BEGIN a := Kernel.pc; mod := Kernel.modList; WHILE (mod # NIL) & ((a < mod.code) OR (a >= mod.code + mod.csize)) DO mod := mod.next END; IF mod # NIL THEN DEC(a, mod.code); ref := mod.refs; REPEAT Kernel.GetRefProc(ref, end, name) UNTIL (end = 0) OR (a < end); IF a < end THEN Kernel.SplitName (mod.name$, head, tail); IF head = "" THEN head := "System" END; Strings.IntToString(Kernel.err, errstr); key := tail + "." + name + "." + errstr; Dialog.MapString("#" + head + ":" + key, msg); (* IF key # msg THEN out.WriteString(" " + msg) END; *) IF key = msg THEN msg := "" END; END END END GetTrapMsg; PROCEDURE Trap; VAR a0: TextModels.Attributes; action: Action; msg: ARRAY 512 OF CHAR; BEGIN out.ConnectTo(TextModels.dir.New()); a0 := out.rider.attr; out.rider.SetAttr(TextModels.NewWeight(a0, Fonts.bold)); IF Kernel.err = 129 THEN out.WriteSString("invalid WITH") ELSIF Kernel.err = 130 THEN out.WriteSString("invalid CASE") ELSIF Kernel.err = 131 THEN out.WriteSString("function without RETURN") ELSIF Kernel.err = 132 THEN out.WriteSString("type guard") ELSIF Kernel.err = 133 THEN out.WriteSString("implied type guard") ELSIF Kernel.err = 134 THEN out.WriteSString("value out of range") ELSIF Kernel.err = 135 THEN out.WriteSString("index out of range") ELSIF Kernel.err = 136 THEN out.WriteSString("string too long") ELSIF Kernel.err = 137 THEN out.WriteSString("stack overflow") ELSIF Kernel.err = 138 THEN out.WriteSString("integer overflow") ELSIF Kernel.err = 139 THEN out.WriteSString("division by zero") ELSIF Kernel.err = 140 THEN out.WriteSString("infinite real result") ELSIF Kernel.err = 141 THEN out.WriteSString("real underflow") ELSIF Kernel.err = 142 THEN out.WriteSString("real overflow") ELSIF Kernel.err = 143 THEN out.WriteSString("undefined real result") ELSIF Kernel.err = 144 THEN out.WriteSString("not a number") ELSIF Kernel.err = 200 THEN out.WriteSString("keyboard interrupt") ELSIF Kernel.err = 201 THEN out.WriteSString("NIL dereference") ELSIF Kernel.err = 202 THEN out.WriteSString("illegal instruction: "); out.WriteIntForm(Kernel.val, TextMappers.hexadecimal, 5, "0", TextMappers.showBase) ELSIF Kernel.err = 203 THEN IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN out.WriteSString("NIL dereference (read)") ELSE out.WriteSString("illegal memory read (ad = "); WriteHex(Kernel.val); out.WriteChar(")") END ELSIF Kernel.err = 204 THEN IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN out.WriteSString("NIL dereference (write)") ELSE out.WriteSString("illegal memory write (ad = "); WriteHex(Kernel.val); out.WriteChar(")") END ELSIF Kernel.err = 205 THEN IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN out.WriteSString("NIL procedure call") ELSE out.WriteSString("illegal execution (ad = "); WriteHex(Kernel.val); out.WriteChar(")") END ELSIF Kernel.err = 257 THEN out.WriteSString("out of memory") ELSIF Kernel.err = 10001H THEN out.WriteSString("bus error") ELSIF Kernel.err = 10002H THEN out.WriteSString("address error") ELSIF Kernel.err = 10007H THEN out.WriteSString("fpu error") ELSIF Kernel.err < 0 THEN out.WriteSString("Exception "); out.WriteIntForm(-Kernel.err, TextMappers.hexadecimal, 3, "0", TextMappers.showBase) ELSE out.WriteSString("TRAP "); out.WriteInt(Kernel.err); IF Kernel.err = 126 THEN out.WriteSString(" (not yet implemented)") ELSIF Kernel.err = 125 THEN out.WriteSString(" (call of obsolete procedure)") ELSIF Kernel.err >= 100 THEN out.WriteSString(" (invariant violated)") ELSIF Kernel.err >= 60 THEN out.WriteSString(" (postcondition violated)") ELSIF Kernel.err >= 20 THEN out.WriteSString(" (precondition violated)") END END; GetTrapMsg(msg); IF msg # "" THEN out.WriteLn; out.WriteString(msg) END; out.WriteLn; out.rider.SetAttr(a0); out.WriteLn; ShowStack; NEW(action); action.text := out.rider.Base(); Services.DoLater(action, Services.now); out.ConnectTo(NIL) END Trap; BEGIN Kernel.InstallTrapViewer(Trap); empty := ""; path[0].x := refViewSize DIV 2; path[0].y := 0; path[1].x := refViewSize; path[1].y := refViewSize DIV 2; path[2].x := refViewSize DIV 2; path[2].y := refViewSize; path[3].x := 0; path[3].y := refViewSize DIV 2; END StdDebug.
Std/Mod/Debug.odc
MODULE StdDialog; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Kernel, Meta, Strings, Files, Fonts, Printers, Stores, Models, Sequencers, Views, Controllers, Containers, Dialog, Properties, Documents, Converters, Windows; TYPE Item* = POINTER TO EXTENSIBLE RECORD next*: Item; item-, string-, filter-: POINTER TO ARRAY OF CHAR; shortcut-: ARRAY 8 OF CHAR; privateFilter-, failed, trapped: BOOLEAN; (* filter call failed, caused a trap *) res: INTEGER (* result code of failed filter *) END; FilterProcVal = RECORD (Meta.Value) p: Dialog.GuardProc END; FilterProcPVal = RECORD (Meta.Value) p: PROCEDURE(n: INTEGER; VAR p: Dialog.Par) END; ViewHook = POINTER TO RECORD (Views.ViewHook) END; VAR curItem-: Item; (** IN parameter for item filters **) PROCEDURE GetSubLoc* (mod: ARRAY OF CHAR; cat: Files.Name; OUT loc: Files.Locator; OUT name: Files.Name); VAR sub: Files.Name; file: Files.File; type: Files.Type; BEGIN IF (cat[0] = "S") & (cat[1] = "y") & (cat[2] = "m") THEN type := Kernel.symType ELSIF (cat[0] = "C") & (cat[1] = "o") & (cat[2] = "d") & (cat[3] = "e") THEN type := Kernel.objType ELSE type := "" END; Kernel.SplitName(mod, sub, name); Kernel.MakeFileName(name, type); loc := Files.dir.This(sub); file := NIL; IF loc # NIL THEN loc := loc.This(cat); IF sub = "" THEN IF loc # NIL THEN file := Files.dir.Old(loc, name, Files.shared); IF file = NIL THEN loc := NIL END END; IF loc = NIL THEN loc := Files.dir.This("System"); IF loc # NIL THEN loc := loc.This(cat) END END END END END GetSubLoc; PROCEDURE Len (VAR str: ARRAY OF CHAR): INTEGER; VAR i: INTEGER; BEGIN i := 0; WHILE str[i] # 0X DO INC(i) END; RETURN i END Len; PROCEDURE AddItem* (i: Item; item, string, filter, shortcut: ARRAY OF CHAR); VAR j: INTEGER; ch: CHAR; BEGIN ASSERT(i # NIL, 20); NEW(i.item, Len(item) + 1); NEW(i.string, Len(string) + 1); NEW(i.filter, Len(filter) + 1); ASSERT((i.item # NIL) & (i.string # NIL) & (i.filter # NIL), 100); i.item^ := item$; i.string^ := string$; i.filter^ := filter$; i.shortcut := shortcut$; j := 0; ch := filter[0]; WHILE (ch # ".") & (ch # 0X) DO INC(j); ch := filter[j] END; i.privateFilter := (j > 0) & (ch = 0X); i.failed := FALSE; i.trapped := FALSE END AddItem; PROCEDURE ClearGuards* (i: Item); BEGIN i.failed := FALSE; i.trapped := FALSE END ClearGuards; PROCEDURE StripEllipsis (VAR s: ARRAY OF CHAR); CONST ELLIPSIS = 0C9X; VAR i: INTEGER; BEGIN i := 0; WHILE s[i] # 0X DO INC(i) END; WHILE (i > 0) & (s[i-1] = ".") OR (s[i-1] = ELLIPSIS) DO DEC(i); s[i] := 0X END END StripEllipsis; PROCEDURE GetGuardProc (name: ARRAY OF CHAR; VAR i: Meta.Item; VAR par: BOOLEAN; VAR n: INTEGER); VAR j, k, x: INTEGER; num: ARRAY 32 OF CHAR; BEGIN j := 0; WHILE (name[j] # 0X) & (name[j] # "(") DO INC(j) END; IF name[j] = "(" THEN x := 0; name[j] := 0X; INC(j); k := 0; WHILE (name[j] # 0X) & (name[j] # ")") DO num[k] := name[j]; INC(j); INC(k) END; IF (name[j] = ")") & (name[j+1] = 0X) THEN num[k] := 0X; Strings.StringToInt(num, n, k); IF k = 0 THEN Meta.LookupPath(name, i); par := TRUE ELSE Meta.Lookup("", i) END ELSE Meta.Lookup("", i) END ELSE Meta.LookupPath(name, i); par := FALSE END END GetGuardProc; PROCEDURE CheckFilter* (i: Item; VAR failed, ok: BOOLEAN; VAR par: Dialog.Par); VAR x: Meta.Item; v: FilterProcVal; vp: FilterProcPVal; p: BOOLEAN; n: INTEGER; BEGIN IF ~i.failed THEN curItem := i; par.disabled := FALSE; par.checked := FALSE; par.label := i.item$; par.undef := FALSE; par.readOnly := FALSE; i.failed := TRUE; i.trapped := TRUE; GetGuardProc(i.filter^, x, p, n); IF (x.obj = Meta.procObj) OR (x.obj = Meta.varObj) & (x.typ = Meta.procTyp) THEN IF p THEN x.GetVal(vp, ok); IF ok THEN vp.p(n, par) END ELSE x.GetVal(v, ok); IF ok THEN v.p(par) END END ELSE ok := FALSE END; IF ok THEN i.res := 0 ELSE i.res := 1 END; i.trapped := FALSE; i.failed := ~ok END; failed := i.failed END CheckFilter; PROCEDURE HandleItem* (i: Item); VAR res: INTEGER; BEGIN IF ~i.failed THEN Views.ClearQueue; res := 0; Dialog.Call(i.string^, " ", res) ELSIF (i # NIL) & i.failed THEN IF i.trapped THEN Dialog.ShowParamMsg("#System:ItemFilterTrapped", i.string^, i.filter^, ""); ELSE Dialog.ShowParamMsg("#System:ItemFilterNotFound", i.string^, i.filter^, "") END END END HandleItem; PROCEDURE RecalcView* (v: Views.View); (* recalc size of all subviews of v, then v itself *) VAR m: Models.Model; v1: Views.View; c: Containers.Controller; minW, maxW, minH, maxH, w, h, w0, h0: INTEGER; BEGIN IF v IS Containers.View THEN c := v(Containers.View).ThisController(); IF c # NIL THEN v1 := NIL; c.GetFirstView(Containers.any, v1); WHILE v1 # NIL DO RecalcView(v1); c.GetNextView(Containers.any, v1) END END END; IF v.context # NIL THEN m := v.context.ThisModel(); IF (m # NIL) & (m IS Containers.Model) THEN m(Containers.Model).GetEmbeddingLimits(minW, maxW, minH, maxH); v.context.GetSize(w0, h0); w := w0; h := h0; Properties.PreferredSize(v, minW, maxW, minH, maxH, w, h, w, h); IF (w # w0) OR (h # h0) THEN v.context.SetSize(w, h) END END END END RecalcView; PROCEDURE Open* (v: Views.View; title: ARRAY OF CHAR; loc: Files.Locator; name: Files.Name; conv: Converters.Converter; asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN); VAR t: Views.Title; flags, opts: SET; done: BOOLEAN; d: Documents.Document; i: INTEGER; m: Models.Model; win: Windows.Window; c: Containers.Controller; f: Files.File; seq: ANYPTR; BEGIN IF conv = NIL THEN conv := Converters.list END; (* use document converter *) ASSERT(v # NIL, 20); flags := {}; done := FALSE; IF noResize THEN flags := flags + {Windows.noResize, Windows.noHScroll, Windows.noVScroll} END; IF asTool THEN INCL(flags, Windows.isTool) END; IF asAux THEN INCL(flags, Windows.isAux) END; IF neverDirty THEN INCL(flags, Windows.neverDirty) END; i := 0; WHILE (i < LEN(t) - 1) & (title[i] # 0X) DO t[i] := title[i]; INC(i) END; t[i] := 0X; IF ~allowDuplicates THEN IF ~asTool & ~asAux THEN IF (loc # NIL) & (name # "") THEN Windows.SelectBySpec(loc, name, conv, done) END ELSE IF title # "" THEN Windows.SelectByTitle(v, flags, t, done) END END ELSE INCL(flags, Windows.allowDuplicates) END; IF ~done THEN IF v IS Documents.Document THEN IF v.context # NIL THEN d := Documents.dir.New( Views.CopyOf(v(Documents.Document).ThisView(), Views.shallow), Views.undefined, Views.undefined) ELSE d := v(Documents.Document) END; ASSERT(d.context = NIL, 22); v := d.ThisView(); ASSERT(v # NIL, 23) ELSIF v.context # NIL THEN ASSERT(v.context IS Documents.Context, 24); d := v.context(Documents.Context).ThisDoc(); IF d.context # NIL THEN d := Documents.dir.New(Views.CopyOf(v, Views.shallow), Views.undefined, Views.undefined) END; ASSERT(d.context = NIL, 25) (*IF d.Domain() = NIL THEN Stores.InitDomain(d, v.Domain()) END (for views opened via Views.Old *) ELSE d := Documents.dir.New(v, Views.undefined, Views.undefined) END; IF asTool OR asAux THEN c := d.ThisController(); c.SetOpts(c.opts + {Containers.noSelection}); END; ASSERT(d.Domain() = v.Domain(), 100); ASSERT(d.Domain() # NIL, 101); seq := d.Domain().GetSequencer(); IF neverDirty & (seq # NIL) THEN ASSERT(seq IS Sequencers.Sequencer, 26); seq(Sequencers.Sequencer).SetDirty(FALSE) END; IF neverDirty THEN (* change "fit to page" to "fit to window" in secondary windows *) c := d.ThisController(); opts := c.opts; IF Documents.pageWidth IN opts THEN opts := opts - {Documents.pageWidth} + {Documents.winWidth} END; IF Documents.pageHeight IN opts THEN opts := opts - {Documents.pageHeight} + {Documents.winHeight} END; c.SetOpts(opts) END; win := Windows.dir.New(); IF seq # NIL THEN Windows.dir.OpenSubWindow(win, d, flags, t) ELSE Windows.dir.Open(win, d, flags, t, loc, name, conv) END END END Open; PROCEDURE (h: ViewHook) Open (v: Views.View; title: ARRAY OF CHAR; loc: Files.Locator; name: Files.Name; conv: Converters.Converter; asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN); BEGIN Open(v, title, loc, name, conv, asTool, asAux, noResize, allowDuplicates, neverDirty) END Open; PROCEDURE (h: ViewHook) OldView (loc: Files.Locator; name: Files.Name; VAR conv: Converters.Converter): Views.View; VAR w: Windows.Window; s: Stores.Store; c: Converters.Converter; BEGIN ASSERT(loc # NIL, 20); ASSERT(name # "", 21); Kernel.MakeFileName(name, ""); s := NIL; IF loc.res # 77 THEN w := Windows.dir.First(); c := conv; IF c = NIL THEN c := Converters.list END; (* use document converter *) WHILE (w # NIL) & ((w.loc = NIL) OR (w.name = "") OR (w.loc.res = 77) OR ~Files.dir.SameFile(loc, name, w.loc, w.name) OR (w.conv # c)) DO w := Windows.dir.Next(w) END; IF w # NIL THEN s := w.doc.ThisView() END END; IF s = NIL THEN Converters.Import(loc, name, conv, s); IF s # NIL THEN RecalcView(s(Views.View)) END END; IF s # NIL THEN RETURN s(Views.View) ELSE RETURN NIL END; END OldView; PROCEDURE (h: ViewHook) RegisterView (v: Views.View; loc: Files.Locator; name: Files.Name; conv: Converters.Converter); BEGIN ASSERT(v # NIL, 20); ASSERT(loc # NIL, 21); ASSERT(name # "", 22); Kernel.MakeFileName(name, ""); Converters.Export(loc, name, conv, v) END RegisterView; PROCEDURE Init; VAR h: ViewHook; BEGIN NEW(h); Views.SetViewHook(h); END Init; BEGIN Init END StdDialog.
Std/Mod/Dialog.odc
MODULE StdETHConv; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Fonts, Files, Stores, Ports, Views, TextModels, TextRulers, TextViews, Stamps := StdStamps, Clocks := StdClocks, StdFolds; CONST V2Tag = -4095; (* 01 F0 *) V4Tag = 496; (* F0 01 *) TYPE FontDesc = RECORD typeface: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER END; VAR default: Fonts.Font; PROCEDURE Split (name: ARRAY OF CHAR; VAR d: FontDesc); VAR i: INTEGER; ch: CHAR; BEGIN i := 0; ch := name[0]; WHILE (ch < "0") OR (ch >"9") DO d.typeface[i] := ch; INC(i); ch := name[i] END; d.typeface[i] := 0X; d.size := 0; WHILE ("0" <= ch) & (ch <= "9") DO d.size := d.size * 10 + (ORD(ch) - 30H); INC(i); ch := name[i] END; CASE ch OF "b": d.style := {}; d.weight := Fonts.bold | "i": d.style := {Fonts.italic}; d.weight := Fonts.normal | "j": d.style := {Fonts.italic}; d.weight := Fonts.bold | "m": d.style := {}; d.weight := Fonts.bold ELSE d.style := {}; d.weight := Fonts.normal (* unknown style *) END END Split; PROCEDURE ThisFont (name: ARRAY OF CHAR): Fonts.Font; VAR d: FontDesc; BEGIN Split(name, d); IF d.typeface = "Syntax" THEN d.typeface := default.typeface END; IF d.size = 10 THEN d.size := default.size ELSE d.size := (d.size - 2) * Ports.point END; RETURN Fonts.dir.This(d.typeface, d.size, d.style, d.weight) END ThisFont; PROCEDURE ThisChar (ch: CHAR): CHAR; BEGIN CASE ORD(ch) OF 80H: ch := 0C4X | 81H: ch := 0D6X | 82H: ch := 0DCX | 83H: ch := 0E4X | 84H: ch := 0F6X | 85H: ch := 0FCX | 86H: ch := 0E2X | 87H: ch := 0EAX | 88H: ch := 0EEX | 89H: ch := 0F4X | 8AH: ch := 0FBX | 8BH: ch := 0E0X | 8CH: ch := 0E8X | 8DH: ch := 0ECX | 8EH: ch := 0F2X | 8FH: ch := 0F9X | 90H: ch := 0E9X | 91H: ch := 0EBX | 92H: ch := 0EFX | 93H: ch := 0E7X | 94H: ch := 0E1X | 95H: ch := 0F1X | 9BH: ch := TextModels.hyphen | 9FH: ch := TextModels.nbspace | 0ABH: ch := 0DFX ELSE ch := 0BFX (* use inverted question mark for unknown character codes *) END; RETURN ch END ThisChar; PROCEDURE ^ LoadTextBlock (r: Stores.Reader; t: TextModels.Model); PROCEDURE StdFold (VAR r: Stores.Reader): Views.View; CONST colLeft = 0; colRight = 1; expRight = 2; expLeft = 3; VAR k: BYTE; state: BOOLEAN; hidden: TextModels.Model; fold: StdFolds.Fold; BEGIN r.ReadByte(k); CASE k MOD 4 OF | colLeft: state := StdFolds.collapsed | colRight: state := StdFolds.collapsed | expRight: state := StdFolds.expanded | expLeft: state := StdFolds.expanded END; IF (k MOD 4 IN {colLeft, expLeft}) & (k < 4) THEN hidden := TextModels.dir.New(); LoadTextBlock(r, hidden); ELSE hidden := NIL; END; fold := StdFolds.dir.New(state, "", hidden); RETURN fold; END StdFold; PROCEDURE LoadTextBlock (r: Stores.Reader; t: TextModels.Model); VAR r0: Stores.Reader; wr: TextModels.Writer; org, len: INTEGER; en, ano, i, n: BYTE; col, voff, ch: CHAR; tag: INTEGER; fname: ARRAY 32 OF CHAR; attr: ARRAY 32 OF TextModels.Attributes; mod, proc: ARRAY 32 OF ARRAY 32 OF CHAR; PROCEDURE ReadNum (VAR n: INTEGER); VAR s: BYTE; ch: CHAR; y: INTEGER; BEGIN s := 0; y := 0; r.ReadXChar(ch); WHILE ch >= 80X DO INC(y, ASH(ORD(ch)-128, s)); INC(s, 7); r.ReadXChar(ch) END; n := ASH((ORD(ch) + 64) MOD 128 - 64, s) + y END ReadNum; PROCEDURE ReadSet (VAR s: SET); VAR x: INTEGER; BEGIN ReadNum(x); s := BITS(x) END ReadSet; PROCEDURE Elem (VAR r: Stores.Reader; span: INTEGER); VAR v: Views.View; end, ew, eh, n, indent: INTEGER; eno, version: BYTE; p: TextRulers.Prop; opts: SET; BEGIN r.ReadInt(ew); r.ReadInt(eh); r.ReadByte(eno); IF eno > en THEN en := eno; r.ReadXString(mod[eno]); r.ReadXString(proc[eno]) END; end := r.Pos() + span; IF (mod[eno] = "ParcElems") OR (mod[eno] = "StyleElems") THEN r.ReadByte(version); NEW(p); p.valid := {TextRulers.first .. TextRulers.tabs}; ReadNum(indent); ReadNum(p.left); p.first := p.left + indent; ReadNum(n); p.right := p.left + n; ReadNum(p.lead); ReadNum(p.grid); ReadNum(p.dsc); p.asc := p.grid - p.dsc; ReadSet(opts); p.opts.val := {}; IF ~(0 IN opts) THEN p.grid := 1 END; IF 1 IN opts THEN INCL(p.opts.val, TextRulers.leftAdjust) END; IF 2 IN opts THEN INCL(p.opts.val, TextRulers.rightAdjust) END; IF 3 IN opts THEN INCL(p.opts.val, TextRulers.pageBreak) END; INCL(p.opts.val, TextRulers.rightFixed); p.opts.mask := {TextRulers.leftAdjust .. TextRulers.pageBreak, TextRulers.rightFixed}; ReadNum(n); p.tabs.len := SHORT(n); i := 0; WHILE i < p.tabs.len DO ReadNum(p.tabs.tab[i].stop); INC(i) END; v := TextRulers.dir.NewFromProp(p); wr.WriteView(v, ew, eh) ELSIF mod[eno] = "StampElems" THEN v := Stamps.New(); wr.WriteView(v, ew, eh) ELSIF mod[eno] = "ClockElems" THEN v := Clocks.New(); wr.WriteView(v, ew, eh) ELSIF mod[eno] = "FoldElems" THEN v := StdFold(r); wr.WriteView(v, ew, eh); END; r.SetPos(end) END Elem; BEGIN (* skip inner text tags (legacy from V2) *) r.ReadXInt(tag); IF tag # V2Tag THEN r.SetPos(r.Pos()-2) END; (* load text block *) org := r.Pos(); r.ReadInt(len); INC(org, len - 2); r0.ConnectTo(r.rider.Base()); r0.SetPos(org); wr := t.NewWriter(NIL); wr.SetPos(0); n := 0; en := 0; r.ReadByte(ano); WHILE ano # 0 DO IF ano > n THEN n := ano; r.ReadXString(fname); attr[n] := TextModels.NewFont(wr.attr, ThisFont(fname)) END; r.ReadXChar(col); r.ReadXChar(voff); r.ReadInt(len); wr.SetAttr(attr[ano]); IF len > 0 THEN WHILE len # 0 DO r0.ReadXChar(ch); IF ch >= 80X THEN ch := ThisChar(ch) END; IF (ch >= " ") OR (ch = TextModels.tab) OR (ch = TextModels.line) THEN wr.WriteChar(ch) END; DEC(len) END ELSE Elem(r, -len); r0.ReadXChar(ch) END; r.ReadByte(ano) END; r.ReadInt(len); r.SetPos(r.Pos() + len); END LoadTextBlock; PROCEDURE ImportOberon* (f: Files.File): TextModels.Model; VAR r: Stores.Reader; t: TextModels.Model; tag: INTEGER; BEGIN r.ConnectTo(f); r.SetPos(0); r.ReadXInt(tag); IF tag = ORD("o") + 256 * ORD("B") THEN (* ignore file header of Oberon for Windows and DOSOberon files *) r.SetPos(34); r.ReadXInt(tag) END; ASSERT((tag = V2Tag) OR (tag = V4Tag), 100); t := TextModels.dir.New(); LoadTextBlock(r, t); RETURN t; END ImportOberon; PROCEDURE ImportETHDoc* (f: Files.File; OUT s: Stores.Store); VAR t: TextModels.Model; BEGIN ASSERT(f # NIL, 20); t := ImportOberon(f); IF t # NIL THEN s := TextViews.dir.New(t) END END ImportETHDoc; BEGIN default := Fonts.dir.Default() END StdETHConv.
Std/Mod/ETHConv.odc
MODULE StdFolds; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Domains := Stores, Ports, Stores, Containers, Models, Views, Controllers, Fonts, Properties,Controls, TextModels, TextViews, TextControllers, TextSetters, Dialog, Services; CONST expanded* = FALSE; collapsed* = TRUE; minVersion = 0; currentVersion = 0; collapseFoldKey = "#Std:Collapse Fold"; expandFoldKey = "#Std:Expand Fold"; zoomInKey = "#Std:Zoom In"; zoomOutKey = "#Std:Zoom Out"; expandFoldsKey = "#Std:Expand Folds"; collapseFoldsKey = "#Std:Collapse Folds"; insertFoldKey = "#Std:Insert Fold"; setLabelKey = "#Std:Set Label"; TYPE Label* = ARRAY 32 OF CHAR; Fold* = POINTER TO RECORD (Views.View) leftSide-: BOOLEAN; collapsed-: BOOLEAN; label-: Label; (* valid iff leftSide *) hidden: TextModels.Model (* valid iff leftSide; NIL if no hidden text *) END; Directory* = POINTER TO ABSTRACT RECORD END; StdDirectory = POINTER TO RECORD (Directory) END; FlipOp = POINTER TO RECORD (Domains.Operation) text: TextModels.Model; (* containing text *) leftpos, rightpos: INTEGER (* position of left and right Fold *) END; SetLabelOp = POINTER TO RECORD (Domains.Operation) text: TextModels.Model; (* containing text *) pos: INTEGER; (* position of fold in text *) oldlabel: Label END; Action = POINTER TO RECORD (Services.Action) END; VAR dir-, stdDir-: Directory; foldData*: RECORD nested*: BOOLEAN; all*: BOOLEAN; findLabel*: Label; newLabel*: Label END; iconFont: Fonts.Typeface; leftExp, rightExp, leftColl, rightColl: ARRAY 8 OF SHORTCHAR; coloredBackg: BOOLEAN; action: Action; fingerprint: INTEGER; (* for the property inspector *) PROCEDURE (d: Directory) New* (collapsed: BOOLEAN; label: Label; hiddenText: TextModels.Model): Fold, NEW, ABSTRACT; PROCEDURE GetPair (fold: Fold; VAR l, r: Fold); VAR c: Models.Context; text: TextModels.Model; rd: TextModels.Reader; v: Views.View; nest: INTEGER; BEGIN c := fold.context; l := NIL; r := NIL; WITH c: TextModels.Context DO text := c.ThisModel(); rd := text.NewReader(NIL); IF fold.leftSide THEN l := fold; rd.SetPos(c.Pos()+1); nest := 1; REPEAT rd.ReadView(v); IF (v # NIL) & (v IS Fold) THEN IF v(Fold).leftSide THEN INC(nest) ELSE DEC(nest) END END UNTIL (v = NIL) OR (nest = 0); IF v # NIL THEN r := v(Fold) ELSE r := NIL END ELSE r := fold; rd.SetPos(c.Pos()); nest := 1; REPEAT rd.ReadPrevView(v); IF (v # NIL) & (v IS Fold) THEN IF ~v(Fold).leftSide THEN INC(nest) ELSE DEC(nest) END END UNTIL (v = NIL) OR (nest = 0); IF v # NIL THEN l := v(Fold) ELSE l := NIL END END ELSE (* fold not embedded in a text *) END; ASSERT((l = NIL) OR l.leftSide & (l.hidden # NIL), 100); ASSERT((r = NIL) OR ~r.leftSide & (r.hidden = NIL), 101) END GetPair; PROCEDURE (fold: Fold) HiddenText* (): TextModels.Model, NEW; VAR l, r: Fold; BEGIN IF fold.leftSide THEN RETURN fold.hidden ELSE GetPair(fold, l, r); IF l # NIL THEN RETURN l.hidden ELSE RETURN NIL END END END HiddenText; PROCEDURE (fold: Fold) MatchingFold* (): Fold, NEW; VAR l, r: Fold; BEGIN GetPair(fold, l, r); IF l # NIL THEN IF fold = l THEN RETURN r ELSE RETURN l END ELSE RETURN NIL END END MatchingFold; PROCEDURE GetIcon (fold: Fold; VAR icon: ARRAY OF SHORTCHAR); BEGIN IF fold.leftSide THEN IF fold.collapsed THEN icon := leftColl$ ELSE icon := leftExp$ END ELSE IF fold.collapsed THEN icon := rightColl$ ELSE icon := rightExp$ END END END GetIcon; PROCEDURE CalcSize (f: Fold; VAR w, h: INTEGER); VAR icon: ARRAY 8 OF SHORTCHAR; c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; asc, dsc, fw: INTEGER; BEGIN GetIcon(f, icon); c := f.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := c(TextModels.Context).Attr(); font := Fonts.dir.This(iconFont, a.font.size, {}, Fonts.normal) ELSE font := Fonts.dir.Default() END; w := font.SStringWidth(icon); font.GetBounds(asc, dsc, fw); h := asc + dsc END CalcSize; PROCEDURE Update (f: Fold); VAR w, h: INTEGER; BEGIN CalcSize(f, w, h); f.context.SetSize(w, h); Views.Update(f, Views.keepFrames) END Update; PROCEDURE FlipPair (l, r: Fold); VAR text, hidden: TextModels.Model; cl, cr: Models.Context; lpos, rpos: INTEGER; BEGIN IF (l # NIL) & (r # NIL) THEN ASSERT(l.leftSide, 100); ASSERT(~r.leftSide, 101); ASSERT(l.hidden # NIL, 102); ASSERT(r.hidden = NIL, 103); cl := l.context; cr := r.context; text := cl(TextModels.Context).ThisModel(); lpos := cl(TextModels.Context).Pos() + 1; rpos := cr(TextModels.Context).Pos(); ASSERT(lpos <= rpos, 104); hidden := TextModels.CloneOf(text); hidden.Insert(0, text, lpos, rpos); text.Insert(lpos, l.hidden, 0, l.hidden.Length()); l.hidden := hidden; Stores.Join(l, hidden); l.collapsed := ~l.collapsed; r.collapsed := l.collapsed; Update(l); Update(r); TextControllers.SetCaret(text, lpos) END END FlipPair; PROCEDURE (op: FlipOp) Do; VAR rd: TextModels.Reader; left, right: Views.View; BEGIN rd := op.text.NewReader(NIL); rd.SetPos(op.leftpos); rd.ReadView(left); rd.SetPos(op.rightpos); rd.ReadView(right); FlipPair(left(Fold), right(Fold)); op.leftpos := left.context(TextModels.Context).Pos(); op.rightpos := right.context(TextModels.Context).Pos() END Do; PROCEDURE (op: SetLabelOp) Do; VAR rd: TextModels.Reader; fold: Views.View; left, right: Fold; lab: Label; BEGIN rd := op.text.NewReader(NIL); rd.SetPos(op.pos); rd.ReadView(fold); WITH fold: Fold DO GetPair(fold, left, right); IF left # NIL THEN lab := fold.label; left.label := op.oldlabel; op.oldlabel := lab; right.label := left.label END END END Do; PROCEDURE SetProp (fold: Fold; p : Properties.Property); VAR op: SetLabelOp; left, right: Fold; BEGIN WHILE p # NIL DO WITH p: Controls.Prop DO IF (Controls.label IN p.valid) & (p.label # fold.label) THEN GetPair(fold, left, right); IF left # NIL THEN NEW(op); op.oldlabel := p.label$; op.text := fold.context(TextModels.Context).ThisModel(); op.pos := fold.context(TextModels.Context).Pos(); Views.Do(fold, setLabelKey, op) END END ELSE END; p := p.next END END SetProp; PROCEDURE (fold: Fold) Flip*, NEW; VAR op: FlipOp; left, right: Fold; BEGIN ASSERT(fold # NIL, 20); NEW(op); GetPair(fold, left, right); IF (left # NIL) & (right # NIL) THEN op.text := fold.context(TextModels.Context).ThisModel(); op.leftpos := left.context(TextModels.Context).Pos(); op.rightpos := right.context(TextModels.Context).Pos(); Views.BeginModification(Views.clean, fold); IF ~left.collapsed THEN Views.Do(fold, collapseFoldKey, op) ELSE Views.Do(fold, expandFoldKey, op) END; Views.EndModification(Views.clean, fold) END END Flip; PROCEDURE ReadNext (rd: TextModels.Reader; VAR fold: Fold); VAR v: Views.View; BEGIN REPEAT rd.ReadView(v) UNTIL rd.eot OR (v IS Fold); IF ~rd.eot THEN fold := v(Fold) ELSE fold := NIL END END ReadNext; PROCEDURE (fold: Fold) FlipNested*, NEW; VAR text: TextModels.Model; rd: TextModels.Reader; l, r: Fold; level: INTEGER; op: Domains.Operation; BEGIN ASSERT(fold # NIL, 20); GetPair(fold, l, r); IF (l # NIL) & (l.context # NIL) & (l.context IS TextModels.Context) THEN text := l.context(TextModels.Context).ThisModel(); Models.BeginModification(Models.clean, text); rd := text.NewReader(NIL); rd.SetPos(l.context(TextModels.Context).Pos()); IF l.collapsed THEN Models.BeginScript(text, expandFoldsKey, op); ReadNext(rd, fold); level := 1; WHILE (fold # NIL) & (level > 0) DO IF fold.leftSide & fold.collapsed THEN fold.Flip END; ReadNext(rd, fold); IF fold.leftSide THEN INC(level) ELSE DEC(level) END END ELSE (* l.state = expanded *) Models.BeginScript(text, collapseFoldsKey, op); level := 0; REPEAT ReadNext(rd, fold); IF fold.leftSide THEN INC(level) ELSE DEC(level) END; IF (fold # NIL) & ~fold.leftSide & ~fold.collapsed THEN fold.Flip; rd.SetPos(fold.context(TextModels.Context).Pos()+1) END UNTIL (fold = NIL) OR (level = 0) END; Models.EndScript(text, op); Models.EndModification(Models.clean, text) END END FlipNested; PROCEDURE (fold: Fold) HandlePropMsg- (VAR msg: Properties.Message); VAR prop: Controls.Prop; c: Models.Context; a: TextModels.Attributes; asc, w: INTEGER; BEGIN WITH msg: Properties.SizePref DO CalcSize(fold, msg.w, msg.h) | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: Properties.FocusPref DO msg.hotFocus := TRUE | msg: Properties.PollMsg DO NEW(prop); prop.known := {Controls.label}; prop.valid := {Controls.label}; prop.readOnly := {}; prop.label := fold.label$; msg.prop := prop | msg: Properties.SetMsg DO SetProp(fold, msg.prop) | msg: TextSetters.Pref DO c := fold.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := c(TextModels.Context).Attr(); a.font.GetBounds(asc, msg.dsc, w) END ELSE END END HandlePropMsg; PROCEDURE Track (fold: Fold; f: Views.Frame; x, y: INTEGER; buttons: SET; VAR hit: BOOLEAN); VAR a: TextModels.Attributes; font: Fonts.Font; c: Models.Context; w, h, asc, dsc, fw: INTEGER; isDown, in, in0: BOOLEAN; modifiers: SET; BEGIN c := fold.context; hit := FALSE; WITH c: TextModels.Context DO a := c.Attr(); font := a.font; c.GetSize(w, h); in0 := FALSE; in := (0 <= x) & (x < w) & (0 <= y) & (y < h); REPEAT IF in # in0 THEN f.MarkRect(0, 0, w, h, Ports.fill, Ports.hilite, FALSE); in0 := in END; f.Input(x, y, modifiers, isDown); in := (0 <= x) & (x < w) & (0 <= y) & (y < h) UNTIL ~isDown; IF in0 THEN hit := TRUE; font.GetBounds(asc, dsc, fw); f.MarkRect(0, 0, w, asc + dsc, Ports.fill, Ports.hilite, FALSE) END ELSE END END Track; PROCEDURE (fold: Fold) HandleCtrlMsg* (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View); VAR hit: BOOLEAN; pos: INTEGER; l, r: Fold; context: TextModels.Context; text: TextModels.Model; BEGIN WITH msg: Controllers.TrackMsg DO IF fold.context IS TextModels.Context THEN Track(fold, f, msg.x, msg.y, msg.modifiers, hit); IF hit THEN IF Controllers.modify IN msg.modifiers THEN fold.FlipNested ELSE fold.Flip; context := fold.context(TextModels.Context); text := context.ThisModel(); IF TextViews.FocusText() = text THEN GetPair(fold, l, r); pos := context.Pos(); IF fold = l THEN TextControllers.SetCaret(text, pos + 1) ELSE TextControllers.SetCaret(text, pos) END; TextViews.ShowRange(text, pos, pos + 1, TRUE) END END END END | msg: Controllers.PollCursorMsg DO msg.cursor := Ports.refCursor ELSE END END HandleCtrlMsg; PROCEDURE (fold: Fold) Restore* (f: Views.Frame; l, t, r, b: INTEGER); VAR a: TextModels.Attributes; color: Ports.Color; c: Models.Context; font: Fonts.Font; icon: ARRAY 8 OF SHORTCHAR; w, h: INTEGER; asc, dsc, fw: INTEGER; BEGIN GetIcon(fold, icon); c := fold.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := fold.context(TextModels.Context).Attr(); font := Fonts.dir.This(iconFont, a.font.size, {}, Fonts.normal); color := a.color ELSE font := Fonts.dir.Default(); color := Ports.black END; IF coloredBackg THEN fold.context.GetSize(w, h); f.DrawRect(f.l, f.dot, f.r, h-f.dot, Ports.fill, Ports.grey50); color := Ports.white END; font.GetBounds(asc, dsc, fw); f.DrawSString(0, asc, color, icon, font) END Restore; PROCEDURE (fold: Fold) CopyFromSimpleView- (source: Views.View); BEGIN (* fold.CopyFrom^(source); *) WITH source: Fold DO ASSERT(source.leftSide = (source.hidden # NIL), 100); fold.leftSide := source.leftSide; fold.collapsed := source.collapsed; fold.label := source.label; IF source.hidden # NIL THEN fold.hidden := TextModels.CloneOf(source.hidden); Stores.Join(fold.hidden, fold); fold.hidden.InsertCopy(0, source.hidden, 0, source.hidden.Length()) END END END CopyFromSimpleView; PROCEDURE (fold: Fold) Internalize- (VAR rd: Stores.Reader); VAR version: INTEGER; store: Stores.Store; xint: INTEGER; BEGIN fold.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minVersion, currentVersion, version); IF rd.cancelled THEN RETURN END; rd.ReadXInt(xint);fold.leftSide := xint = 0; rd.ReadXInt(xint); fold.collapsed := xint = 0; rd.ReadXString(fold.label); rd.ReadStore(store); IF store # NIL THEN fold.hidden := store(TextModels.Model); Stores.Join(fold.hidden, fold) ELSE fold.hidden := NIL END; fold.leftSide := store # NIL END Internalize; PROCEDURE (fold: Fold) Externalize- (VAR wr: Stores.Writer); VAR xint: INTEGER; BEGIN fold.Externalize^(wr); wr.WriteVersion(currentVersion); IF fold.hidden # NIL THEN xint := 0 ELSE xint := 1 END; wr.WriteXInt(xint); IF fold.collapsed THEN xint := 0 ELSE xint := 1 END; wr.WriteXInt(xint); wr.WriteXString(fold.label); wr.WriteStore(fold.hidden) END Externalize; (* --------------------- expanding and collapsing in focus text ------------------------ *) PROCEDURE ExpandFolds* (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR); VAR op: Domains.Operation; fold, l, r: Fold; rd: TextModels.Reader; BEGIN ASSERT(text # NIL, 20); Models.BeginModification(Models.clean, text); IF nested THEN Models.BeginScript(text, expandFoldsKey, op) ELSE Models.BeginScript(text, zoomInKey, op) END; rd := text.NewReader(NIL); rd.SetPos(0); ReadNext(rd, fold); WHILE ~rd.eot DO IF fold.leftSide & fold.collapsed THEN IF (label = "") OR (label = fold.label) THEN fold.Flip; IF ~nested THEN GetPair(fold, l, r); rd.SetPos(r.context(TextModels.Context).Pos()) END END END; ReadNext(rd, fold) END; Models.EndScript(text, op); Models.EndModification(Models.clean, text) END ExpandFolds; PROCEDURE CollapseFolds* (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR); VAR op: Domains.Operation; fold, r, l: Fold; rd: TextModels.Reader; BEGIN ASSERT(text # NIL, 20); Models.BeginModification(Models.clean, text); IF nested THEN Models.BeginScript(text, collapseFoldsKey, op) ELSE Models.BeginScript(text, zoomOutKey, op) END; rd := text.NewReader(NIL); rd.SetPos(0); ReadNext(rd, fold); WHILE ~rd.eot DO IF ~fold.leftSide & ~fold.collapsed THEN GetPair(fold, l, r); IF (label = "") OR (label = l.label) THEN fold.Flip; GetPair(l, l, r); rd.SetPos(r.context(TextModels.Context).Pos()+1); IF ~nested THEN REPEAT ReadNext(rd, fold) UNTIL rd.eot OR fold.leftSide ELSE ReadNext(rd, fold) END ELSE ReadNext(rd, fold) END ELSE ReadNext(rd, fold) END END; Models.EndScript(text, op); Models.EndModification(Models.clean, text) END CollapseFolds; PROCEDURE ZoomIn*; VAR text: TextModels.Model; BEGIN text := TextViews.FocusText(); IF text # NIL THEN ExpandFolds(text, FALSE, "") END END ZoomIn; PROCEDURE ZoomOut*; VAR text: TextModels.Model; BEGIN text := TextViews.FocusText(); IF text # NIL THEN CollapseFolds(text, FALSE, "") END END ZoomOut; PROCEDURE Expand*; VAR text: TextModels.Model; BEGIN text := TextViews.FocusText(); IF text # NIL THEN ExpandFolds(text, TRUE, "") END END Expand; PROCEDURE Collapse*; VAR text: TextModels.Model; BEGIN text := TextViews.FocusText(); IF text # NIL THEN CollapseFolds(text, TRUE, "") END END Collapse; (* ---------------------- foldData dialogbox --------------------------- *) PROCEDURE FindLabelGuard* (VAR par: Dialog.Par); BEGIN par.disabled := (TextViews.Focus() = NIL) OR foldData.all END FindLabelGuard; PROCEDURE SetLabelGuard* ( VAR p : Dialog.Par ); VAR v: Views.View; BEGIN Controllers.SetCurrentPath(Controllers.targetPath); v := Containers.FocusSingleton(); p.disabled := (v = NIL) OR ~(v IS Fold) OR ~v(Fold).leftSide; Controllers.ResetCurrentPath() END SetLabelGuard; PROCEDURE ExpandLabel*; VAR text: TextModels.Model; BEGIN IF foldData.all & (foldData.findLabel # "") THEN foldData.findLabel := ""; Dialog.Update(foldData) END; text := TextViews.FocusText(); IF text # NIL THEN IF ~foldData.all THEN ExpandFolds(text, foldData.nested, foldData.findLabel) ELSE ExpandFolds(text, foldData.nested, "") END END END ExpandLabel; PROCEDURE CollapseLabel*; VAR text: TextModels.Model; BEGIN IF foldData.all & (foldData.findLabel # "") THEN foldData.findLabel := ""; Dialog.Update(foldData) END; text := TextViews.FocusText(); IF text # NIL THEN IF ~foldData.all THEN CollapseFolds(text, foldData.nested, foldData.findLabel) ELSE CollapseFolds(text, foldData.nested, "") END END END CollapseLabel; PROCEDURE FindFold(first: BOOLEAN); VAR c : TextControllers.Controller; r: TextModels.Reader; v : Views.View; pos, i : INTEGER; BEGIN c := TextControllers.Focus(); IF c # NIL THEN IF first THEN pos := 0 ELSE pos := c.CaretPos(); IF pos = TextControllers.none THEN c.GetSelection(i, pos); IF pos = i THEN pos := 0 ELSE INC(pos) END; pos := MIN(pos, c.text.Length()-1) END END; r := c.text.NewReader(NIL); r.SetPos(pos); REPEAT r.ReadView(v) UNTIL r.eot OR ((v IS Fold) & v(Fold).leftSide) & (foldData.all OR (v(Fold).label$ = foldData.findLabel$)); IF r.eot THEN c.SetCaret(0); Dialog.Beep ELSE pos := r.Pos(); c.view.ShowRange(pos-1, pos, FALSE); c.SetSelection(pos-1, pos); IF LEN(v(Fold).label) > 0 THEN foldData.newLabel := v(Fold).label END; Dialog.Update(foldData) END ELSE Dialog.Beep END END FindFold; PROCEDURE FindNextFold*; BEGIN FindFold(FALSE) END FindNextFold; PROCEDURE FindFirstFold*; BEGIN FindFold(TRUE) END FindFirstFold; PROCEDURE SetLabel*; VAR v: Views.View; BEGIN Controllers.SetCurrentPath(Controllers.targetPath); v := Containers.FocusSingleton(); IF (v # NIL) & (v IS Fold) & (LEN(foldData.newLabel) > 0) THEN v(Fold).label := foldData.newLabel ELSE Dialog.Beep END; Controllers.ResetCurrentPath() END SetLabel; PROCEDURE (a: Action) Do; VAR v: Views.View; fp: INTEGER; BEGIN Controllers.SetCurrentPath(Controllers.targetPath); v := Containers.FocusSingleton(); IF (v = NIL) OR ~(v IS Fold) THEN fingerprint := 0; foldData.newLabel := "" ELSE fp := Services.AdrOf(v); IF fp # fingerprint THEN foldData.newLabel := v(Fold).label; fingerprint := fp; Dialog.Update(foldData) END END; Controllers.ResetCurrentPath(); Services.DoLater(action, Services.Ticks() + Services.resolution DIV 2) END Do; (* ------------------------ inserting folds ------------------------ *) PROCEDURE Overlaps* (text: TextModels.Model; beg, end: INTEGER): BOOLEAN; VAR n, level: INTEGER; rd: TextModels.Reader; v: Views.View; BEGIN ASSERT(text # NIL, 20); ASSERT((beg >= 0) & (end <= text.Length()) & (beg <= end), 21); rd := text.NewReader(NIL); rd.SetPos(beg); n := 0; level := 0; REPEAT rd.ReadView(v); IF ~rd.eot & (rd.Pos() <= end) THEN WITH v: Fold DO INC(n); IF v.leftSide THEN INC(level) ELSE DEC(level) END ELSE END END UNTIL rd.eot OR (level < 0) OR (rd.Pos() >= end); RETURN (level # 0) OR ODD(n) END Overlaps; PROCEDURE InsertionAttr (text: TextModels.Model; pos: INTEGER): TextModels.Attributes; VAR rd: TextModels.Reader; ch: CHAR; BEGIN rd := text.NewReader(NIL); rd.SetPos(pos); rd.ReadChar(ch); RETURN rd.attr END InsertionAttr; PROCEDURE Insert* (text: TextModels.Model; label: Label; beg, end: INTEGER; collapsed: BOOLEAN); VAR w: TextModels.Writer; fold: Fold; insop: Domains.Operation; a: TextModels.Attributes; BEGIN ASSERT(text # NIL, 20); ASSERT((beg >= 0) & (end <= text.Length()) & (beg <= end), 21); a := InsertionAttr(text, beg); w := text.NewWriter(NIL); w.SetPos(beg); IF a # NIL THEN w.SetAttr(a) END; NEW(fold); fold.leftSide := TRUE; fold.collapsed := collapsed; fold.hidden := TextModels.CloneOf(text); Stores.Join(fold, fold.hidden); fold.label := label$; Models.BeginScript(text, insertFoldKey, insop); w.WriteView(fold, 0, 0); w.SetPos(end+1); a := InsertionAttr(text, end+1); IF a # NIL THEN w.SetAttr(a) END; NEW(fold); fold.leftSide := FALSE; fold.collapsed := collapsed; fold.hidden := NIL; fold.label := ""; w.WriteView(fold, 0, 0); Models.EndScript(text, insop) END Insert; PROCEDURE CreateGuard* (VAR par: Dialog.Par); VAR c: TextControllers.Controller; beg, end: INTEGER; BEGIN c := TextControllers.Focus(); IF (c # NIL) & ~(Containers.noCaret IN c.opts) THEN IF c.HasSelection() THEN c.GetSelection(beg, end); IF Overlaps(c.text, beg, end) THEN par.disabled := TRUE END END ELSE par.disabled := TRUE END END CreateGuard; PROCEDURE Create* (state: INTEGER); (* menu cmd parameters don't accept Booleans *) VAR c: TextControllers.Controller; beg, end: INTEGER; collapsed: BOOLEAN; BEGIN collapsed := state = 0; c := TextControllers.Focus(); IF (c # NIL) & ~(Containers.noCaret IN c.opts) THEN IF c.HasSelection() THEN c.GetSelection(beg, end); IF ~Overlaps(c.text, beg, end) THEN Insert(c.text, "", beg, end, collapsed) END ELSE beg := c.CaretPos(); Insert(c.text, "", beg, beg, collapsed) END END END Create; PROCEDURE InitIcons; VAR font: Fonts.Font; PROCEDURE DefaultAppearance; BEGIN font := Fonts.dir.Default(); iconFont := font.typeface$; leftExp := ">"; rightExp := "<"; leftColl := "=>"; rightColl := "<="; coloredBackg := TRUE END DefaultAppearance; BEGIN IF Dialog.platform = Dialog.linux THEN (* Linux *) DefaultAppearance; coloredBackg := FALSE ELSIF Dialog.platform DIV 10 = 1 THEN (* Windows *) iconFont := "Wingdings"; font := Fonts.dir.This(iconFont, 10*Fonts.point (*arbitrary*), {}, Fonts.normal); IF font.IsAlien() THEN DefaultAppearance ELSE leftExp[0] := SHORT(CHR(240)); leftExp[1] := 0X; rightExp[0] := SHORT(CHR(239)); rightExp[1] := 0X; leftColl[0] := SHORT(CHR(232)); leftColl[1] := 0X; rightColl[0] := SHORT(CHR(231)); rightColl[1] := 0X; coloredBackg := FALSE END ELSIF Dialog.platform DIV 10 = 2 THEN (* Mac *) iconFont := "Chicago"; font := Fonts.dir.This(iconFont, 10*Fonts.point (*arbitrary*), {}, Fonts.normal); IF font.IsAlien() THEN DefaultAppearance ELSE leftExp := ">"; rightExp := "<"; leftColl := ""; rightColl := ""; coloredBackg := TRUE END ELSE DefaultAppearance END END InitIcons; PROCEDURE (d: StdDirectory) New (collapsed: BOOLEAN; label: Label; hiddenText: TextModels.Model): Fold; VAR fold: Fold; BEGIN NEW(fold); fold.leftSide := hiddenText # NIL; fold.collapsed := collapsed; fold.label := label; fold.hidden := hiddenText; IF hiddenText # NIL THEN Stores.Join(fold, fold.hidden) END; RETURN fold END New; PROCEDURE SetDir* (d: Directory); BEGIN ASSERT(d # NIL, 20); dir := d END SetDir; PROCEDURE InitMod; VAR d: StdDirectory; BEGIN foldData.all := TRUE; foldData.nested := FALSE; foldData.findLabel := ""; foldData.newLabel := ""; NEW(d); dir := d; stdDir := d; InitIcons; NEW(action); Services.DoLater(action, Services.now); END InitMod; BEGIN InitMod END StdFolds.
Std/Mod/Folds.odc
MODULE StdHeaders; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) (* headers / footers support the following macros: &p - replaced by current page number as arabic numeral &r - replaced by current page number as roman numeral &R - replaced by current page number as capital roman numeral &a - replaced by current page number as alphanumeric character &A - replaced by current page number as capital alphanumeric character &d - replaced by printing date &t - replaced by printing time &&- replaced by & character &; - specifies split point &f - filename with path/title *) IMPORT Stores, Ports, Models, Views, Properties, Printing, TextModels, Fonts, Dialog, TextViews, Dates, Windows, Controllers, Containers; CONST minVersion = 0; maxVersion = 2; mm = Ports.mm; point = Ports.point; maxWidth = 10000 * mm; alternate* = 0; number* = 1; head* = 2; foot* = 3; showFoot* = 4; TYPE Banner* = RECORD left*, right*: ARRAY 128 OF CHAR; gap*: INTEGER END; NumberInfo* = RECORD new*: BOOLEAN; first*: INTEGER END; View = POINTER TO RECORD (Views.View) alternate: BOOLEAN; (* alternate left/right *) number: NumberInfo; (* new page number *) head, foot: Banner; font: Fonts.Font; showFoot: BOOLEAN; END; Prop* = POINTER TO RECORD (Properties.Property) alternate*, showFoot*: BOOLEAN; number*: NumberInfo; head*, foot*: Banner END; ChangeFontOp = POINTER TO RECORD (Stores.Operation) header: View; font: Fonts.Font END; ChangeAttrOp = POINTER TO RECORD (Stores.Operation) header: View; alternate, showFoot: BOOLEAN; number: NumberInfo; head, foot: Banner END; VAR dialog*: RECORD view: View; alternate*, showFoot*: BOOLEAN; number*: NumberInfo; head*, foot*: Banner; END; PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN); VAR valid: SET; PROCEDURE Equal(IN b1, b2: Banner): BOOLEAN; BEGIN RETURN (b1.left = b2.left) & (b1.right = b2.right) & (b1.gap = b2.gap) END Equal; BEGIN WITH q: Prop DO valid := p.valid * q.valid; equal := TRUE; IF p.alternate # q.alternate THEN EXCL(valid, alternate) END; IF p.showFoot # q.showFoot THEN EXCL(valid, showFoot) END; IF (p.number.new # q.number.new) OR (p.number.first # q.number.first) THEN EXCL(valid, number) END; IF ~Equal(p.head, q.head) THEN EXCL(valid, head) END; IF ~Equal(p.foot, q.foot) THEN EXCL(valid, foot) END; IF p.valid # valid THEN p.valid := valid; equal := FALSE END END END IntersectWith; (* SetAttrOp *) PROCEDURE (op: ChangeFontOp) Do; VAR v: View; font: Fonts.Font; asc, dsc, w: INTEGER; c: Models.Context; BEGIN v := op.header; font := op.font; op.font := v.font; v.font := font; font.GetBounds(asc, dsc, w); c := v.context; c.SetSize(maxWidth, asc + dsc + 2*point); Views.Update(v, Views.keepFrames) END Do; PROCEDURE DoChangeFontOp (v: View; font: Fonts.Font); VAR op: ChangeFontOp; BEGIN IF v.font # font THEN NEW(op); op.header := v; op.font := font; Views.Do(v, "#System:SetProp", op) END END DoChangeFontOp; PROCEDURE (op: ChangeAttrOp) Do; VAR v: View; alternate, showFoot: BOOLEAN; number: NumberInfo; head, foot: Banner; BEGIN v := op.header; alternate := op.alternate; showFoot := op.showFoot; number := op.number; head := op.head; foot := op.foot; op.alternate := v.alternate; op.showFoot := v.showFoot; op.number := v.number; op.head := v.head; op.foot := v.foot; v.alternate := alternate; v.showFoot := showFoot; v.number := number; v.head := head; v.foot := foot; Views.Update(v, Views.keepFrames) END Do; PROCEDURE DoChangeAttrOp (v: View; alternate, showFoot: BOOLEAN; number: NumberInfo; head, foot: Banner); VAR op: ChangeAttrOp; BEGIN NEW(op); op.header := v; op.alternate := alternate; op.showFoot := showFoot; op.number := number; op.head := head; op.foot := foot; Views.Do(v, "#Std:HeaderChange", op) END DoChangeAttrOp; PROCEDURE (v: View) CopyFromSimpleView (source: Views.View); BEGIN WITH source: View DO v.alternate := source.alternate; v.number.new := source.number.new; v.number.first := source.number.first; v.head := source.head; v.foot := source.foot; v.font := source.font; v.showFoot := source.showFoot END END CopyFromSimpleView; PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer); BEGIN v.Externalize^(wr); wr.WriteVersion(maxVersion); wr.WriteString(v.head.left); wr.WriteString(v.head.right); wr.WriteInt(v.head.gap); wr.WriteString(v.foot.left); wr.WriteString(v.foot.right); wr.WriteInt(v.foot.gap); wr.WriteString(v.font.typeface); wr.WriteInt(v.font.size); wr.WriteSet(v.font.style); wr.WriteInt(v.font.weight); wr.WriteBool(v.alternate); wr.WriteBool(v.number.new); wr.WriteInt(v.number.first); wr.WriteBool(v.showFoot); END Externalize; PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader); VAR version: INTEGER; typeface: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER; BEGIN v.Internalize^(rd); IF ~rd.cancelled THEN rd.ReadVersion(minVersion, maxVersion, version); IF ~rd.cancelled THEN IF version = 0 THEN rd.ReadXString(v.head.left); rd.ReadXString(v.head.right); v.head.gap := 5*mm; rd.ReadXString(v.foot.left); rd.ReadXString(v.foot.right); v.foot.gap := 5*mm; rd.ReadXString(typeface); rd.ReadXInt(size); v.font := Fonts.dir.This(typeface, size * point, {}, Fonts.normal); rd.ReadXInt(v.number.first); rd.ReadBool(v.number.new); rd.ReadBool(v.alternate) ELSE rd.ReadString(v.head.left); rd.ReadString(v.head.right); rd.ReadInt(v.head.gap); rd.ReadString(v.foot.left); rd.ReadString(v.foot.right); rd.ReadInt(v.foot.gap); rd.ReadString(typeface); rd.ReadInt(size); rd.ReadSet(style); rd.ReadInt(weight); v.font := Fonts.dir.This(typeface, size, style, weight); rd.ReadBool(v.alternate); rd.ReadBool(v.number.new); rd.ReadInt(v.number.first); IF version = 2 THEN rd.ReadBool(v.showFoot) ELSE v.showFoot := FALSE END END END END END Internalize; PROCEDURE SetProp(v: View; msg: Properties.SetMsg); VAR p: Properties.Property; typeface: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER; alt, sf: BOOLEAN; num: NumberInfo; h, f: Banner; BEGIN p := msg.prop; WHILE p # NIL DO WITH p: Properties.StdProp DO IF Properties.typeface IN p.valid THEN typeface := p.typeface ELSE typeface := v.font.typeface END; IF Properties.size IN p.valid THEN size := p.size ELSE size := v.font.size END; IF Properties.style IN p.valid THEN style := p.style.val ELSE style := v.font.style END; IF Properties.weight IN p.valid THEN weight := p.weight ELSE weight := v.font.weight END; DoChangeFontOp (v, Fonts.dir.This(typeface, size, style, weight) ); | p: Prop DO IF alternate IN p.valid THEN alt := p.alternate ELSE alt := v.alternate END; IF showFoot IN p.valid THEN sf := p.showFoot ELSE sf := v.showFoot END; IF number IN p.valid THEN num := p.number ELSE num := v.number END; IF head IN p.valid THEN h := p.head ELSE h := v.head END; IF foot IN p.valid THEN f := p.foot ELSE f := v.foot END; DoChangeAttrOp(v, alt, sf, num, h, f) ELSE END; p := p.next END END SetProp; PROCEDURE PollProp(v: View; VAR msg: Properties.PollMsg); VAR sp: Properties.StdProp; p: Prop; BEGIN NEW(sp); sp.known := {Properties.size, Properties.typeface, Properties.style, Properties.weight}; sp.valid := sp.known; sp.size := v.font.size; sp.typeface := v.font.typeface; sp.style.val := v.font.style; sp.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout}; sp.weight := v.font.weight; Properties.Insert(msg.prop, sp); NEW(p); p.known := {alternate, number, head, foot, showFoot}; p.valid := p.known; p.head := v.head; p.foot := v.foot; p.alternate := v.alternate; p.showFoot := v.showFoot; p.number := v.number; Properties.Insert(msg.prop, p) END PollProp; PROCEDURE PageMsg(v: View; msg: TextViews.PageMsg); BEGIN IF Printing.par # NIL THEN Dialog.MapString(v.head.left, Printing.par.header.left); Dialog.MapString(v.head.right, Printing.par.header.right); Dialog.MapString(v.foot.left, Printing.par.footer.left); Dialog.MapString(v.foot.right, Printing.par.footer.right); Printing.par.header.font := v.font; Printing.par.footer.font := v.font; Printing.par.page.alternate := v.alternate; IF v.number.new THEN Printing.par.page.first := v.number.first - msg.current END; Printing.par.header.gap := 5*Ports.mm; Printing.par.footer.gap := 5*Ports.mm END END PageMsg; PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR d, w, h: INTEGER; (*line: Line; *)asc, dsc, x0, x1, y: INTEGER; win: Windows.Window; title: Views.Title; dec: BOOLEAN; pw, ph: INTEGER; date: Dates.Date; time: Dates.Time; pageInfo: Printing.PageInfo; banner: Printing.Banner; BEGIN IF Views.IsPrinterFrame(f) THEN (* am drucken *) END; v.font.GetBounds(asc, dsc, w); win := Windows.dir.First(); WHILE (win # NIL) & (win.doc.Domain() # v.Domain()) DO win := Windows.dir.Next(win) END; IF win = NIL THEN title := "(" + Dialog.appName + ")" ELSE win.GetTitle(title) END; d := f.dot; v.context.GetSize(w, h); win.doc.PollPage(pw, ph, l, t, r, b, dec); w := r - l; f.DrawRect(0, 0, w, h, Ports.fill, Ports.grey25); f.DrawRect(0, 0, w, h, 0, Ports.black); x0 := d; x1 := w-2*d; y := asc + d; Dates.GetDate(date); Dates.GetTime(time); pageInfo.alternate := FALSE; pageInfo.title := title; banner.font := v.font; IF v.showFoot THEN banner.gap := v.foot.gap; Dialog.MapString(v.foot.left, banner.left); Dialog.MapString(v.foot.right, banner.right) ELSE banner.gap := v.head.gap; Dialog.MapString(v.head.left, banner.left); Dialog.MapString(v.head.right, banner.right) END; Printing.PrintBanner(f, pageInfo, banner, date, time, x0, x1, y) END Restore; PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message); VAR asc, dsc, w: INTEGER; BEGIN WITH msg: Properties.SizePref DO msg.w := maxWidth; IF msg.h = Views.undefined THEN v.font.GetBounds(asc, dsc, w); msg.h := asc + dsc + 2*point END | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: TextModels.Pref DO msg.opts := {TextModels.hideable} | msg: Properties.PollMsg DO PollProp(v, msg) | msg: Properties.SetMsg DO SetProp(v, msg) | msg: TextViews.PageMsg DO PageMsg(v, msg) ELSE END END HandlePropMsg; PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN WITH msg: Properties.EmitMsg DO Views.HandlePropMsg(v, msg.set) | msg: Properties.CollectMsg DO Views.HandlePropMsg(v, msg.poll) ELSE END END HandleCtrlMsg; PROCEDURE New*(p: Prop; f: Fonts.Font): Views.View; VAR v: View; BEGIN NEW(v); v.head := p.head; v.foot := p.foot; v.number := p.number; v.alternate := p.alternate; v.font := f; v.showFoot := FALSE; RETURN v; END New; PROCEDURE Deposit*; VAR v: View; BEGIN NEW(v); v.head.left := ""; v.head.right := "&d&;&p"; v.head.gap := 5*mm; v.foot.left := ""; v.foot.right := ""; v.foot.gap := 5*mm; v.font := Fonts.dir.Default(); v.number.first := 1; v.number.new := FALSE; v.alternate := FALSE; v.showFoot := FALSE; Views.Deposit(v) END Deposit; (* property dialog *) PROCEDURE InitDialog*; VAR p: Properties.Property; BEGIN Properties.CollectProp(p); WHILE p # NIL DO WITH p: Properties.StdProp DO | p: Prop DO dialog.alternate := p.alternate; dialog.showFoot := p.showFoot; dialog.number := p.number; dialog.head := p.head; dialog.head.gap := dialog.head.gap DIV point; dialog.foot := p.foot; dialog.foot.gap := dialog.foot.gap DIV point; Dialog.Update(dialog) ELSE END; p := p.next END END InitDialog; PROCEDURE Set*; VAR p: Prop; BEGIN NEW(p); p.valid := {alternate, number, head, foot, showFoot}; p.alternate := dialog.alternate; p.showFoot := dialog.showFoot; p.number := dialog.number; p.head := dialog.head; p.head.gap := p.head.gap * point; p.foot := dialog.foot; p.foot.gap := p.foot.gap * point; Properties.EmitProp(NIL, p) END Set; PROCEDURE HeaderGuard* (VAR par: Dialog.Par); VAR v: Views.View; BEGIN v := Containers.FocusSingleton(); IF (v # NIL) & (v IS View) THEN par.disabled := FALSE; IF (dialog.view = NIL) OR (dialog.view # v) THEN dialog.view := v(View); InitDialog END ELSE par.disabled := TRUE; dialog.view := NIL END END HeaderGuard; PROCEDURE AlternateGuard* (VAR par: Dialog.Par); BEGIN HeaderGuard(par); IF ~par.disabled THEN par.disabled := ~ dialog.alternate END END AlternateGuard; PROCEDURE NewNumberGuard* (VAR par: Dialog.Par); BEGIN HeaderGuard(par); IF ~par.disabled THEN par.disabled := ~ dialog.number.new END END NewNumberGuard; END StdHeaders.
Std/Mod/Headers.odc
MODULE StdInterpreter; (* SP410 *) (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - 20111211, Fyodor Tkachov, switched from National to i21sysCharacters - 20080215, Fyodor Tkachov, reviewed - 20050626, Fyodor Tkachov, russification edited - 20050430, Ivan Goryachev, russification - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Kernel, Meta, Strings, Views, Dialog, i21sysCharacters; TYPE (* command procedure types *) Proc = PROCEDURE; ProcI = PROCEDURE(x: INTEGER); ProcII = PROCEDURE(x, y: INTEGER); ProcS = PROCEDURE(s: ARRAY OF CHAR); ProcSI = PROCEDURE(s: ARRAY OF CHAR; x: INTEGER); ProcSII = PROCEDURE(s: ARRAY OF CHAR; x, y: INTEGER); ProcSS = PROCEDURE(s, t: ARRAY OF CHAR); ProcSSI = PROCEDURE(s, t: ARRAY OF CHAR; x: INTEGER); ProcSSII = PROCEDURE(s, t: ARRAY OF CHAR; x, y: INTEGER); ProcR = PROCEDURE(IN s: ARRAY OF CHAR); ProcRI = PROCEDURE(IN s: ARRAY OF CHAR; x: INTEGER); ProcRII = PROCEDURE(IN s: ARRAY OF CHAR; x, y: INTEGER); ProcRS = PROCEDURE(IN s: ARRAY OF CHAR; t: ARRAY OF CHAR); ProcRSI = PROCEDURE(IN s: ARRAY OF CHAR; t: ARRAY OF CHAR; x: INTEGER); ProcRSII = PROCEDURE(IN s: ARRAY OF CHAR; t: ARRAY OF CHAR; x, y: INTEGER); ProcSR = PROCEDURE(s: ARRAY OF CHAR; IN t: ARRAY OF CHAR); ProcSRI = PROCEDURE(s: ARRAY OF CHAR; IN t: ARRAY OF CHAR; x: INTEGER); ProcSRII = PROCEDURE(s: ARRAY OF CHAR; IN t: ARRAY OF CHAR; x, y: INTEGER); ProcRR = PROCEDURE(IN s, t: ARRAY OF CHAR); ProcRRI = PROCEDURE(IN s, t: ARRAY OF CHAR; x: INTEGER); ProcRRII = PROCEDURE(IN s, t: ARRAY OF CHAR; x, y: INTEGER); (* corresponding meta values *) ProcVal = RECORD (Meta.Value) p: Proc END; ProcIVal = RECORD (Meta.Value) p: ProcI END; ProcIIVal = RECORD (Meta.Value) p: ProcII END; ProcSVal = RECORD (Meta.Value) p: ProcS END; ProcSIVal = RECORD (Meta.Value) p: ProcSI END; ProcSIIVal = RECORD (Meta.Value) p: ProcSII END; ProcSSVal = RECORD (Meta.Value) p: ProcSS END; ProcSSIVal = RECORD (Meta.Value) p: ProcSSI END; ProcSSIIVal = RECORD (Meta.Value) p: ProcSSII END; ProcRVal = RECORD (Meta.Value) p: ProcR END; ProcRIVal = RECORD (Meta.Value) p: ProcRI END; ProcRIIVal = RECORD (Meta.Value) p: ProcRII END; ProcRSVal = RECORD (Meta.Value) p: ProcRS END; ProcRSIVal = RECORD (Meta.Value) p: ProcRSI END; ProcRSIIVal = RECORD (Meta.Value) p: ProcRSII END; ProcSRVal = RECORD (Meta.Value) p: ProcSR END; ProcSRIVal = RECORD (Meta.Value) p: ProcSRI END; ProcSRIIVal = RECORD (Meta.Value) p: ProcSRII END; ProcRRVal = RECORD (Meta.Value) p: ProcRR END; ProcRRIVal = RECORD (Meta.Value) p: ProcRRI END; ProcRRIIVal = RECORD (Meta.Value) p: ProcRRII END; CallHook = POINTER TO RECORD (Dialog.CallHook) END; PROCEDURE (hook: CallHook) Call (IN proc, errorMsg: ARRAY OF CHAR; VAR res: INTEGER); TYPE Ident = ARRAY 32 OF CHAR; CONST modNotFound = 10; procNotFound = 11; identExpected = 12; unknownIdent = 13; depositExpected = 14; noDepositExpected = 15; syntaxError = 16; lparenExpected = 17; rparenExpected = 18; containerExpected = 19; quoteExpected = 20; fileNotFound = 21; noController = 22; noDialog = 23; cannotUnload = 24; commaExpected = 25; incompParList = 26; CONST ident = 0; dot = 1; semicolon = 2; eot = 3; lparen = 4; rparen = 5; quote = 6; comma = 7; int = 8; parI = 1; parII = 2; parS = 3; parSI = 4; parSII = 5; parSS = 6; parSSI = 7; parSSII = 8; VAR i, type: INTEGER; ch: CHAR; id: Ident; e, f, g: ARRAY 64 OF CHAR; x: INTEGER; s0, s1: Dialog.String; i0, i1: INTEGER; (* variable param lists *) par0: Dialog.String; par1: Views.Title; (* fix param lists *) PROCEDURE Concat (a, b: ARRAY OF CHAR; VAR c: ARRAY OF CHAR); VAR i, j: INTEGER; ch: CHAR; BEGIN IF a = " " THEN Dialog.MapString("#System:CommandError", c) ELSE c := a$ END; i := 0; WHILE c[i] # 0X DO INC(i) END; c[i] := " "; INC(i); j := 0; ch := b[0]; WHILE ch # 0X DO c[i] := ch; INC(i); INC(j); ch := b[j] END; c[i] := 0X END Concat; PROCEDURE Error (n: INTEGER; msg, par0, par1: ARRAY OF CHAR); VAR e, f: ARRAY 256 OF CHAR; BEGIN IF res = 0 THEN res := n; IF errorMsg # "" THEN Dialog.MapString(errorMsg, e); Dialog.MapParamString(msg, par0, par1, "", f); Concat(e, f, f); Dialog.ShowMsg(f) END END END Error; PROCEDURE Init (VAR s: ARRAY OF CHAR); VAR i: INTEGER; BEGIN i := 0; WHILE i < LEN(s) DO s[i] := 0X; INC(i) END END Init; PROCEDURE CallProc (mod, proc: Ident; parType: INTEGER); VAR mn, pn: Meta.Name; i: Meta.Item; ok, a, b, c: BOOLEAN; v: ProcVal; vi: ProcIVal; vii: ProcIIVal; vs: ProcSVal; vsi: ProcSIVal; vsii: ProcSIIVal; vss: ProcSSVal; vssi: ProcSSIVal; vssii: ProcSSIIVal; vr: ProcRVal; vri: ProcRIVal; vrii: ProcRIIVal; vrs: ProcRSVal; vrsi: ProcRSIVal; vrsii: ProcRSIIVal; vsr: ProcSRVal; vsri: ProcSRIVal; vsrii: ProcSRIIVal; vrr: ProcRRVal; vrri: ProcRRIVal; vrrii: ProcRRIIVal; res: INTEGER; importing, imported, object: ARRAY 256 OF CHAR; BEGIN (* prevent from parasitic anchors on stack *) Init(mn); Init(pn); ok := FALSE; a := FALSE; b := FALSE; c := FALSE; mn := mod$; pn := proc$; Meta.Lookup(mn, i); IF i.obj = Meta.modObj THEN i.Lookup(pn, i); IF i.obj = Meta.procObj THEN CASE parType OF | 0: i.GetVal(v, ok); IF ok THEN v.p() END | parI: i.GetVal(vi, ok); IF ok THEN vi.p(i0) END | parII: i.GetVal(vii, ok); IF ok THEN vii.p(i0, i1) END | parS: i.GetVal(vs, ok); IF ok THEN vs.p(s0) ELSE i.GetVal(vr, ok); IF ok THEN vr.p(s0) END END | parSI: i.GetVal(vsi, ok); IF ok THEN vsi.p(s0, i0) ELSE i.GetVal(vri, ok); IF ok THEN vri.p(s0, i0) END END | parSII: i.GetVal(vsii, ok); IF ok THEN vsii.p(s0, i0, i1) ELSE i.GetVal(vrii, ok); IF ok THEN vrii.p(s0, i0, i1) END END | parSS: i.GetVal(vss, ok); IF ok THEN vss.p(s0, s1) ELSE i.GetVal(vrr, ok); IF ok THEN vrr.p(s0, s1) ELSE i.GetVal(vsr, ok); IF ok THEN vsr.p(s0, s1) ELSE i.GetVal(vrs, ok); IF ok THEN vrs.p(s0, s1) END END END END | parSSI: i.GetVal(vssi, ok); IF ok THEN vssi.p(s0, s1, i0) ELSE i.GetVal(vrri, ok); IF ok THEN vrri.p(s0, s1, i0) ELSE i.GetVal(vsri, ok); IF ok THEN vsri.p(s0, s1, i0) ELSE i.GetVal(vrsi, ok); IF ok THEN vrsi.p(s0, s1, i0) END END END END | parSSII: i.GetVal(vssii, ok); IF ok THEN vssii.p(s0, s1, i0, i1) ELSE i.GetVal(vrrii, ok); IF ok THEN vrrii.p(s0, s1, i0, i1) ELSE i.GetVal(vsrii, ok); IF ok THEN vsrii.p(s0, s1, i0, i1) ELSE i.GetVal(vrsii, ok); IF ok THEN vrsii.p(s0, s1, i0, i1) END END END END END; IF ~ok THEN Error(incompParList, "#System:IncompatibleParList", mod, proc) END ELSE Error(Kernel.commNotFound, "#System:CommandNotFoundIn", proc, mod) END ELSE Kernel.GetLoaderResult(res, importing, imported, object); CASE res OF | Kernel.fileNotFound: Error(Kernel.fileNotFound, "#System:CodeFileNotFound", imported, "") | Kernel.syntaxError: Error(Kernel.syntaxError, "#System:CorruptedCodeFileFor", imported, "") | Kernel.objNotFound: Error(Kernel.objNotFound, "#System:ObjNotFoundImpFrom", imported, importing) | Kernel.illegalFPrint: Error(Kernel.illegalFPrint, "#System:ObjInconsImpFrom", imported, importing) | Kernel.cyclicImport: Error(Kernel.cyclicImport, "#System:CyclicImpFrom", imported, importing) | Kernel.noMem: Error(Kernel.noMem, "#System:NotEnoughMemoryFor", imported, "") ELSE Error(res, "#System:CannotLoadModule", mod, "") END END END CallProc; PROCEDURE GetCh; BEGIN IF i < LEN(proc) THEN ch := proc[i]; INC(i) ELSE ch := 0X END END GetCh; PROCEDURE Scan; VAR j: INTEGER; num: ARRAY 32 OF CHAR; r: INTEGER; BEGIN IF res = 0 THEN WHILE (ch # 0X) & (ch <= " ") DO GetCh END; IF ch = 0X THEN type := eot ELSIF ch = "." THEN type := dot; GetCh ELSIF ch = ";" THEN type := semicolon; GetCh ELSIF ch = "(" THEN type := lparen; GetCh ELSIF ch = ")" THEN type := rparen; GetCh ELSIF ch = "'" THEN type := quote; GetCh ELSIF ch = "," THEN type := comma; GetCh ELSIF (ch >= "0") & (ch <= "9") OR (ch = "-") THEN type := int; j := 0; REPEAT num[j] := ch; INC(j); GetCh UNTIL (ch < "0") OR (ch > "9") & (ch < "A") OR (ch > "H"); num[j] := 0X; Strings.StringToInt(num, x, r) ELSIF i21sysCharacters.IsFirstIdentChar(ch) THEN type := ident; id[0] := ch; j := 1; GetCh; WHILE (ch # 0X) & (i < LEN(proc)) & i21sysCharacters.IsIdentChar(ch) DO id[j] := ch; INC(j); GetCh END; id[j] := 0X ELSE Error(syntaxError, "#System:SyntaxError", "", "") END END END Scan; PROCEDURE String (VAR s: ARRAY OF CHAR); VAR j: INTEGER; BEGIN IF type = quote THEN j := 0; WHILE (ch # 0X) & (ch # "'") & (j < LEN(s) - 1) DO s[j] := ch; INC(j); GetCh END; s[j] := 0X; IF ch = "'" THEN GetCh; Scan ELSE Error(quoteExpected, "#System:QuoteExpected", "", "") END ELSE Error(quoteExpected, "#System:QuoteExpected", "", "") END END String; PROCEDURE ParamList (VAR parType: INTEGER); BEGIN parType := 0; IF type = lparen THEN Scan; IF type = quote THEN String(s0); IF type= comma THEN Scan; IF type = quote THEN String(s1); IF type = comma THEN Scan; IF type = int THEN i0 := x; Scan; IF type = comma THEN Scan; IF type = int THEN i1 := x; parType := parSSII; Scan ELSE Error(syntaxError, "#System:SyntaxError", "", "") END ELSE parType := parSSI END ELSE Error(syntaxError, "#System:SyntaxError", "", "") END ELSE parType := parSS END ELSIF type = int THEN i0 := x; Scan; IF type = comma THEN Scan; IF type = int THEN i1 := x; parType := parSII; Scan ELSE Error(syntaxError, "#System:SyntaxError", "", "") END ELSE parType := parSI END ELSE Error(syntaxError, "#System:SyntaxError", "", "") END ELSE parType := parS END ELSIF type = int THEN i0 := x; Scan; IF type = comma THEN Scan; IF type = int THEN i1 := x; parType := parII; Scan ELSE Error(syntaxError, "#System:SyntaxError", "", "") END ELSE parType := parI END END; IF type = rparen THEN Scan ELSE Error(rparenExpected, "#System:RParenExpected", "", "") END END END ParamList; PROCEDURE Command; VAR left, right: Ident; ptype: INTEGER; BEGIN (* protect from parasitic anchors on stack *) Init(left); Init(right); ptype := 0; left := id; Scan; IF type = dot THEN (* Oberon command *) Scan; IF type = ident THEN right := id; Scan; ParamList(ptype); CallProc(left, right, ptype) ELSE Error(identExpected, "#System:IdentExpected", "", "") END ELSE Error(unknownIdent, "#System:UnknownIdent", id, "") END END Command; BEGIN (* protect from parasitic anchors on stack *) i := 0; type := 0; Init(id); Init(e); Init(f); Init(g); x := 0; Init(s0); Init(s1); i0 := 0; i1 := 0; Init(par0); Init(par1); Views.ClearQueue; res := 0; i := 0; GetCh; Scan; IF type = ident THEN Command; WHILE (type = semicolon) & (res = 0) DO Scan; Command END; IF type # eot THEN Error(syntaxError, "#System:SyntaxError", "", "") END ELSE Error(syntaxError, "#System:SyntaxError", "", "") END; IF (res = 0) & (Views.Available() > 0) THEN Error(noDepositExpected, "#System:NoDepositExpected", "", "") END; Views.ClearQueue END Call; PROCEDURE Init; VAR hook: CallHook; BEGIN NEW(hook); Dialog.SetCallHook(hook) END Init; BEGIN Init END StdInterpreter.
Std/Mod/Interpreter.odc
MODULE StdLinks; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Kernel, Services, Stores, Ports, Fonts, Models, Views, Controllers, Properties, Dialog, Containers, TextModels, TextMappers, TextViews, TextControllers, TextSetters, TextRulers, Strings, StdCmds; CONST kind* = 0; cmd* = 1; close* = 2; (* constants for Prop.valid *) always* = 0; ifShiftDown* = 1; never* = 2; (* constants for close attrubute *) minLinkVersion = 0; maxLinkVersion = 1; minTargVersion = 0; maxTargVersion = 0; TYPE Directory* = POINTER TO ABSTRACT RECORD END; Link* = POINTER TO RECORD (Views.View) leftSide-: BOOLEAN; cmd: POINTER TO ARRAY OF CHAR; close: INTEGER END; Target* = POINTER TO RECORD (Views.View) leftSide-: BOOLEAN; ident: POINTER TO ARRAY OF CHAR END; Prop* = POINTER TO RECORD (Properties.Property) cmd*: POINTER TO ARRAY OF CHAR; link-: BOOLEAN; close*: INTEGER END; ChangeAttrOp = POINTER TO RECORD (Stores.Operation) v: Views.View; cmd: POINTER TO ARRAY OF CHAR; close: INTEGER; valid: SET END; StdDirectory = POINTER TO RECORD (Directory) END; TrapCleaner = POINTER TO RECORD (Kernel.TrapCleaner) END; VAR dir-, stdDir-: Directory; par-: Link; iconFont: Fonts.Typeface; linkLeft, linkRight, targetLeft, targetRight: ARRAY 8 OF SHORTCHAR; coloredBackg: BOOLEAN; cleaner: TrapCleaner; dialog*: RECORD cmd*: ARRAY 512 OF CHAR; type-: ARRAY 32 OF CHAR; close*: Dialog.List; known, valid: SET; END; fingerprint: INTEGER; (** Cleaner **) PROCEDURE (c: TrapCleaner) Cleanup; BEGIN par := NIL END Cleanup; (** Properties **) PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN); VAR valid: SET; BEGIN WITH q: Prop DO valid := p.valid * q.valid; equal := TRUE; IF (cmd IN valid) & (p.cmd^ # q.cmd^) THEN EXCL(valid, cmd) END; IF (kind IN valid) & (p.link # q.link) THEN EXCL(valid, kind) END; IF (close IN valid) & (p.close # q.close) THEN EXCL (valid, close) END; IF p.valid # valid THEN p.valid := valid; equal := FALSE END END END IntersectWith; PROCEDURE (op: ChangeAttrOp) Do; VAR v: Views.View; s: POINTER TO ARRAY OF CHAR; c: INTEGER; BEGIN v := op.v; WITH | v: Link DO IF cmd IN op.valid THEN s := op.cmd; op.cmd := v.cmd; v.cmd := s END; IF close IN op.valid THEN c := op.close; op.close := v.close; v.close := c END | v: Target DO IF cmd IN op.valid THEN s := op.cmd; op.cmd := v.ident; v.ident := s END END END Do; PROCEDURE DoChangeAttrOp (v: Views.View; s: POINTER TO ARRAY OF CHAR; c: INTEGER; valid: SET); VAR op: ChangeAttrOp; BEGIN NEW(op); op.v := v; op.valid := valid; IF close IN valid THEN op.close := c END; IF cmd IN valid THEN NEW(op.cmd, LEN(s)+1); op.cmd^ := s$ END; Views.Do(v, "#Std:LinkChange", op) END DoChangeAttrOp; PROCEDURE SetProp(v: Views.View; msg: Properties.SetMsg); VAR p: Properties.Property; BEGIN p := msg.prop; WHILE p # NIL DO WITH p: Prop DO IF (cmd IN p.valid) OR (close IN p.valid) THEN DoChangeAttrOp(v, p.cmd, p.close, p.valid) END ELSE END; p := p.next END END SetProp; PROCEDURE PollProp(v: Views.View; VAR msg: Properties.PollMsg); VAR p: Prop; BEGIN NEW(p); WITH v: Link DO p.known := {kind, cmd, close}; p.link := TRUE; p.cmd := v.cmd; p.close := v.close | v: Target DO p.known := {kind, cmd}; p.link := FALSE; p.cmd := v.ident ELSE END; p.valid := p.known; Properties.Insert(msg.prop, p) END PollProp; PROCEDURE InitDialog*; VAR p: Properties.Property; BEGIN dialog.cmd := ""; dialog.type := ""; dialog.close.index := -1; dialog.known := {}; dialog.valid := {}; Properties.CollectProp(p); WHILE p # NIL DO WITH p: Prop DO dialog.valid := p.valid; dialog.known := p.known; IF cmd IN p.valid THEN dialog.cmd := p.cmd$ END; IF kind IN p.valid THEN IF p.link THEN Dialog.MapString("#Std:Link", dialog.type) ELSE Dialog.MapString("#Std:Target", dialog.type) END END; IF close IN p.valid THEN dialog.close.index := p.close END ELSE END; p := p.next END; Dialog.Update(dialog) END InitDialog; PROCEDURE Set*; VAR p: Prop; BEGIN NEW(p); p.valid := dialog.valid; IF cmd IN p.valid THEN NEW(p.cmd, LEN(dialog.cmd) + 1); p.cmd^ := dialog.cmd$ END; p.close := dialog.close.index; Properties.EmitProp(NIL, p); fingerprint := 0 (* force actualization of fields *) END Set; PROCEDURE CmdGuard* (VAR par: Dialog.Par); VAR c: Containers.Controller; v: Views.View; fp: INTEGER; BEGIN IF ~(cmd IN dialog.known) THEN par.disabled := TRUE ELSIF ~(cmd IN dialog.valid) THEN par.undef := TRUE END; Controllers.SetCurrentPath(Controllers.targetPath); fp := 0; c := Containers.Focus(); IF c # NIL THEN c.GetFirstView(Containers.selection, v); WHILE v # NIL DO fp := fp + Services.AdrOf(v); c.GetNextView(TRUE, v) END END; IF fp # fingerprint THEN fingerprint := fp; InitDialog END; Controllers.ResetCurrentPath() END CmdGuard; PROCEDURE CloseGuard* (VAR par: Dialog.Par); BEGIN IF ~(close IN dialog.known) THEN par.disabled := TRUE ELSIF ~(close IN dialog.valid) THEN par.undef := TRUE END; END CloseGuard; PROCEDURE Notifier* (idx, op, from, to: INTEGER); BEGIN IF op = Dialog.changed THEN INCL(dialog.valid, idx) END END Notifier; PROCEDURE (d: Directory) NewLink* (IN cmd: ARRAY OF CHAR): Link, NEW, ABSTRACT; PROCEDURE (d: Directory) NewTarget* (IN ident: ARRAY OF CHAR): Target, NEW, ABSTRACT; PROCEDURE InFrame (f: Views.Frame; x, y: INTEGER): BOOLEAN; BEGIN RETURN (f.l <= x) & (x < f.r) & (f.t <= y) & (y < f.b) END InFrame; PROCEDURE Mark (f: Views.Frame; show: BOOLEAN); BEGIN f.MarkRect(f.l, f.t, f.r, f.b, Ports.fill, Ports.hilite, show) END Mark; PROCEDURE ThisPos (v: TextViews.View; f: Views.Frame; x, y: INTEGER): INTEGER; (* "corrected" v.ThisPos: does not adjust position when crossing 50% boundary of characters *) VAR loc: TextViews.Location; pos: INTEGER; BEGIN pos := v.ThisPos(f, x, y); v.GetThisLocation(f, pos, loc); IF (loc.y <= y) & (y < loc.y + loc.asc + loc.dsc) & (x < loc.x) THEN DEC(pos) END; RETURN pos END ThisPos; PROCEDURE GetLinkPair (this: Link; VAR l, r: Link); (* POST: BalancedPair(l, r) & (l # r) & (l = this OR r = this) OR (l = r = NIL) *) VAR t: TextModels.Model; rd: TextModels.Reader; v: Views.View; level: INTEGER; BEGIN l := NIL; r := NIL; level := 1; IF (this.context # NIL) & (this.context IS TextModels.Context) THEN t := this.context(TextModels.Context).ThisModel(); rd := t.NewReader(NIL); IF this.leftSide THEN rd.SetPos(this.context(TextModels.Context).Pos() + 1); REPEAT rd.ReadView(v); IF (v # NIL) & (v IS Link) THEN IF v(Link).leftSide THEN INC(level) ELSE DEC(level) END END UNTIL (v = NIL) OR (level = 0); IF v # NIL THEN l := this; r := v(Link) END ELSE rd.SetPos(this.context(TextModels.Context).Pos()); REPEAT rd.ReadPrevView(v); IF (v # NIL) & (v IS Link) THEN IF v(Link).leftSide THEN DEC(level) ELSE INC(level) END END UNTIL (v = NIL) OR (level = 0); IF v # NIL THEN l := v(Link); r := this END END END END GetLinkPair; PROCEDURE GetTargetPair (this: Target; VAR l, r: Target); (* POST: BalancedPair(l, r) & (l # r) & (l = this OR r = this) OR (l = r = NIL) *) VAR t: TextModels.Model; rd: TextModels.Reader; v: Views.View; level: INTEGER; BEGIN l := NIL; r := NIL; level := 1; IF (this.context # NIL) & (this.context IS TextModels.Context) THEN t := this.context(TextModels.Context).ThisModel(); rd := t.NewReader(NIL); IF this.leftSide THEN rd.SetPos(this.context(TextModels.Context).Pos() + 1); REPEAT rd.ReadView(v); IF (v # NIL) & (v IS Target) THEN IF v(Target).leftSide THEN INC(level) ELSE DEC(level) END END UNTIL (v = NIL) OR (level = 0); IF v # NIL THEN l := this; r := v(Target) END ELSE rd.SetPos(this.context(TextModels.Context).Pos()); REPEAT rd.ReadPrevView(v); IF (v # NIL) & (v IS Target) THEN IF v(Target).leftSide THEN DEC(level) ELSE INC(level) END END UNTIL (v = NIL) OR (level = 0); IF v # NIL THEN l := v(Target); r := this END END END END GetTargetPair; PROCEDURE GetRange (l, r: Link; VAR beg, end: INTEGER); BEGIN beg := l.context(TextModels.Context).Pos(); end := r.context(TextModels.Context).Pos() + 1 END GetRange; PROCEDURE MarkRange (v: TextViews.View; f: Views.Frame; beg, end: INTEGER; show: BOOLEAN); VAR b, e: TextViews.Location; r, t: INTEGER; BEGIN ASSERT(beg < end, 20); v.GetThisLocation(f, beg, b); v.GetThisLocation(f, end, e); IF (b.pos < e.pos) OR (b.pos = e.pos) & (b.x < e.x) THEN IF b.start # e.start THEN r := f.r; t := b.y + b.asc + b.dsc; f.MarkRect(b.x, b.y, r, t, Ports.fill, Ports.hilite, show); IF t < e.y THEN f.MarkRect(0, t, r, e.y, Ports.fill, Ports.hilite, show) END; b.x := f.l; b.y := e.y END; f.MarkRect(b.x, b.y, e.x, e.y + e.asc + e.dsc, Ports.fill, Ports.hilite, show) END END MarkRange; PROCEDURE Reveal (left, right: Views.View; str: ARRAY OF CHAR; opname: Stores.OpName); VAR con: TextModels.Context; t: TextModels.Model; pos: INTEGER; w: TextMappers.Formatter; op: Stores.Operation; BEGIN con := left.context(TextModels.Context); t := con.ThisModel(); pos := con.Pos(); w.ConnectTo(t); w.SetPos(pos); IF con.Attr() # NIL THEN w.rider.SetAttr(con.Attr()) END; Models.BeginScript(t, opname, op); t.Delete(pos, pos + 1); w.WriteChar("<"); IF str # "" THEN w.WriteString(str) END; w.WriteChar(">"); con := right.context(TextModels.Context); pos := con.Pos(); w.SetPos(pos); IF con.Attr() # NIL THEN w.rider.SetAttr(con.Attr()) END; t.Delete(pos, pos + 1); w.WriteString("<>"); Models.EndScript(t, op) END Reveal; PROCEDURE RevealCmd (v: Link); VAR left, right: Link; BEGIN GetLinkPair(v, left, right); IF left # NIL THEN IF v.cmd # NIL THEN Reveal(left, right, v.cmd^, "#StdLinks:Reveal Link Command") ELSE Reveal(left, right, "", "#StdLinks:Reveal Link Command") END END END RevealCmd; PROCEDURE RevealTarget (targ: Target); VAR left, right: Target; BEGIN GetTargetPair(targ, left, right); IF left # NIL THEN IF left.ident # NIL THEN Reveal(left, right, left.ident^, "#SdtLinks:Reveal Target Ident") ELSE Reveal(left, right, "", "#SdtLinks:Reveal Target Ident") END END END RevealTarget; PROCEDURE CallCmd (v: Link; close: BOOLEAN); VAR res: INTEGER; BEGIN Kernel.PushTrapCleaner(cleaner); par := v; IF v.cmd^ # "" THEN IF close & (v.close = ifShiftDown) OR (v.close = always) THEN StdCmds.CloseDialog END; Dialog.Call(v.cmd^, "#StdLinks:Link Call Failed", res) END; par := NIL; Kernel.PopTrapCleaner(cleaner) END CallCmd; PROCEDURE TrackSingle (f: Views.Frame; VAR in: BOOLEAN); VAR x, y: INTEGER; modifiers: SET; in0, isDown: BOOLEAN; BEGIN in := FALSE; REPEAT f.Input(x, y, modifiers, isDown); in0 := in; in := InFrame(f, x, y); IF in # in0 THEN Mark(f, in) END UNTIL ~isDown; IF in THEN Mark(f, FALSE) END END TrackSingle; PROCEDURE TrackRange (v: TextViews.View; f: Views.Frame; l, r: Link; x, y: INTEGER; VAR in: BOOLEAN); VAR pos, beg, end: INTEGER; modifiers: SET; in0, isDown: BOOLEAN; BEGIN in := FALSE; GetRange(l, r, beg, end); pos := ThisPos(v, f, x, y); IF (beg <= pos) & (pos < end) THEN REPEAT f.Input(x, y, modifiers, isDown); pos := ThisPos(v, f, x, y); in0 := in; in := (beg <= pos) & (pos < end); IF in # in0 THEN MarkRange(v, f, beg, end, in) END UNTIL ~isDown; IF in THEN MarkRange(v, f, beg, end, FALSE) END END END TrackRange; PROCEDURE Track (v: Link; f: Views.Frame; c: TextControllers.Controller; x, y: INTEGER; modifiers: SET); (* PRE: (c # NIL) & (f.view.ThisModel() = v.context.ThisModel()) OR (c = NIL) & (f.view = v) *) VAR l, r: Link; in: BOOLEAN; BEGIN GetLinkPair(v, l, r); IF l # NIL THEN IF c # NIL THEN TrackRange(c.view, f, l, r, x, y, in) ELSE TrackSingle(f, in) END; IF in THEN IF (Controllers.modify IN modifiers) & ((c = NIL) OR ~(Containers.noCaret IN c.opts)) THEN RevealCmd(l) ELSE CallCmd(l, Controllers.extend IN modifiers) END END END END Track; PROCEDURE TrackTarget (targ: Target; f: Views.Frame; modifiers: SET); VAR in: BOOLEAN; BEGIN TrackSingle(f, in); IF in & (Controllers.modify IN modifiers) THEN RevealTarget(targ) END END TrackTarget; PROCEDURE (v: Link) CopyFromSimpleView- (source: Views.View); BEGIN WITH source: Link DO ASSERT(source.leftSide = (source.cmd # NIL), 100); v.leftSide := source.leftSide; v.close := source.close; IF source.cmd # NIL THEN NEW(v.cmd, LEN(source.cmd^)); v.cmd^ := source.cmd^$ ELSE v.cmd := NIL END END END CopyFromSimpleView; PROCEDURE (t: Target) CopyFromSimpleView- (source: Views.View); BEGIN WITH source: Target DO ASSERT(source.leftSide = (source.ident # NIL), 100); t.leftSide := source.leftSide; IF source.ident # NIL THEN NEW(t.ident, LEN(source.ident^)); t.ident^ := source.ident^$ ELSE t.ident := NIL END END END CopyFromSimpleView; PROCEDURE (v: Link) Internalize- (VAR rd: Stores.Reader); VAR len: INTEGER; version: INTEGER; pos: INTEGER; BEGIN v.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minLinkVersion, maxLinkVersion, version); IF rd.cancelled THEN RETURN END; rd.ReadBool(v.leftSide); rd.ReadInt(len); IF len = 0 THEN v.cmd := NIL ELSE NEW(v.cmd, len); rd.ReadXString(v.cmd^) END; v.leftSide := v.cmd # NIL; IF v.leftSide THEN IF version = 1 THEN rd.ReadInt(v.close) ELSE Strings.Find(v.cmd, "StdLinks.ShowTarget", 0, pos); IF (pos # 0) THEN v.close := ifShiftDown ELSE v.close := never END END END END Internalize; PROCEDURE (v: Link) Externalize- (VAR wr: Stores.Writer); VAR pos, version: INTEGER; BEGIN v.Externalize^(wr); IF v.leftSide THEN Strings.Find(v.cmd, "StdLinks.ShowTarget", 0, pos); IF (pos = 0) & (v.close = never) OR (v.close = ifShiftDown) THEN version := 0 ELSE version := 1 END ELSE version := 0 END; wr.WriteVersion(version); wr.WriteBool(v.cmd # NIL); IF v.cmd = NIL THEN wr.WriteInt(0) ELSE wr.WriteInt(LEN(v.cmd^)); wr.WriteXString(v.cmd^) END; IF version = 1 THEN wr.WriteInt(v.close) END END Externalize; PROCEDURE (t: Target) Internalize- (VAR rd: Stores.Reader); VAR len: INTEGER; version: INTEGER; BEGIN t.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minTargVersion, maxTargVersion, version); IF rd.cancelled THEN RETURN END; rd.ReadBool(t.leftSide); rd.ReadInt(len); IF len = 0 THEN t.ident := NIL ELSE NEW(t.ident, len); rd.ReadXString(t.ident^) END; t.leftSide := t.ident # NIL END Internalize; PROCEDURE (t: Target) Externalize- (VAR wr: Stores.Writer); BEGIN t.Externalize^(wr); wr.WriteVersion(maxTargVersion); wr.WriteBool(t.ident # NIL); IF t.ident = NIL THEN wr.WriteInt(0) ELSE wr.WriteInt(LEN(t.ident^)); wr.WriteXString(t.ident^) END END Externalize; PROCEDURE RestoreView (v: Views.View; f: Views.Frame; icon: ARRAY OF SHORTCHAR); VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; color: Ports.Color; asc, dsc, w: INTEGER; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := c(TextModels.Context).Attr(); font := Fonts.dir.This(iconFont, a.font.size, {}, Fonts.normal); color := a.color ELSE font := Fonts.dir.Default(); color := Ports.black END; IF coloredBackg THEN f.DrawRect(f.l, f.t, f.r, f.b, Ports.fill, Ports.grey25) END; font.GetBounds(asc, dsc, w); f.DrawSString(1*Ports.mm DIV 2, asc, color, icon, font) END RestoreView; PROCEDURE (v: Link) Restore* (f: Views.Frame; l, t, r, b: INTEGER); BEGIN IF v.leftSide THEN RestoreView(v, f, linkLeft) ELSE RestoreView(v, f, linkRight) END END Restore; PROCEDURE (targ: Target) Restore* (f: Views.Frame; l, t, r, b: INTEGER); BEGIN IF targ.leftSide THEN RestoreView(targ, f, targetLeft) ELSE RestoreView(targ, f, targetRight) END END Restore; PROCEDURE SizePref (v: Views.View; icon: ARRAY OF SHORTCHAR; VAR msg: Properties.SizePref); VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; asc, dsc, w: INTEGER; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := c(TextModels.Context).Attr(); font := Fonts.dir.This(iconFont, a.font.size, {}, Fonts.normal) ELSE font := Fonts.dir.Default() END; msg.w := font.SStringWidth(icon) + 1*Ports.mm; font.GetBounds(asc, dsc, w); msg.h := asc + dsc END SizePref; PROCEDURE (v: Link) HandlePropMsg- (VAR msg: Properties.Message); VAR a: TextModels.Attributes; c: Models.Context; asc, dsc, w: INTEGER; l, r: Link; BEGIN WITH msg: Properties.SizePref DO IF v.leftSide THEN SizePref(v, linkLeft, msg) ELSE SizePref(v, linkRight, msg) END | msg: Properties.FocusPref DO msg.hotFocus := TRUE | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: TextModels.Pref DO msg.opts := {TextModels.hideable} | msg: TextControllers.FilterPref DO msg.filter := TRUE | msg: TextSetters.Pref DO c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := c(TextModels.Context).Attr(); a.font.GetBounds(asc, dsc, w); msg.dsc := dsc END | msg: Properties.PollMsg DO IF v.leftSide THEN PollProp(v, msg) ELSE GetLinkPair(v, l, r); IF l # NIL THEN PollProp(l, msg) END END | msg: Properties.SetMsg DO IF v.leftSide THEN SetProp(v, msg) ELSE GetLinkPair(v, l, r); SetProp(l, msg) END ELSE END END HandlePropMsg; PROCEDURE (targ: Target) HandlePropMsg- (VAR msg: Properties.Message); VAR a: TextModels.Attributes; c: Models.Context; asc, dsc, w: INTEGER; l, r: Target; BEGIN WITH msg: Properties.SizePref DO IF targ.leftSide THEN SizePref(targ, targetLeft, msg) ELSE SizePref(targ, targetRight, msg) END | msg: Properties.FocusPref DO msg.hotFocus := TRUE | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: TextModels.Pref DO msg.opts := {TextModels.hideable} | msg: TextSetters.Pref DO c := targ.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := c(TextModels.Context).Attr(); a.font.GetBounds(asc, dsc, w); msg.dsc := dsc END | msg: Properties.PollMsg DO IF targ.leftSide THEN PollProp(targ, msg) ELSE GetTargetPair(targ, l, r); IF l # NIL THEN PollProp(l, msg) END END | msg: Properties.SetMsg DO IF targ.leftSide THEN SetProp(targ, msg) ELSE GetTargetPair(targ, l, r); SetProp(l, msg) END ELSE END END HandlePropMsg; PROCEDURE (v: Link) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); PROCEDURE isHot(c: TextControllers.Controller; x, y: INTEGER; mod: SET): BOOLEAN; VAR pos, beg, end: INTEGER; BEGIN (* ignore alt, cmd, and middle clicks in edit mode *) IF ~(Containers.noCaret IN c.opts) & (mod * {17, 27, 28} # {}) THEN RETURN FALSE END; pos := ThisPos(c.view, f, x, y); (* ignore clicks in selection *) c.GetSelection(beg, end); IF (end > beg) & (pos >= beg) & (pos <= end) THEN RETURN FALSE END; IF v.leftSide THEN RETURN pos >= v.context(TextModels.Context).Pos() ELSE RETURN pos < v.context(TextModels.Context).Pos() END END isHot; BEGIN WITH msg: Controllers.PollCursorMsg DO msg.cursor := Ports.refCursor | msg: TextControllers.FilterPollCursorMsg DO IF isHot(msg.controller, msg.x, msg.y, {}) THEN msg.cursor := Ports.refCursor; msg.done := TRUE END | msg: Controllers.TrackMsg DO Track(v, f, NIL, msg.x, msg.y, msg.modifiers) | msg: TextControllers.FilterTrackMsg DO IF isHot(msg.controller, msg.x, msg.y, msg.modifiers) THEN Track(v, f, msg.controller, msg.x, msg.y, msg.modifiers); msg.done := TRUE END ELSE END END HandleCtrlMsg; PROCEDURE (targ: Target) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN WITH msg: Controllers.TrackMsg DO TrackTarget(targ, f, msg.modifiers) ELSE END END HandleCtrlMsg; PROCEDURE (v: Link) GetCmd* (OUT cmd: ARRAY OF CHAR), NEW; BEGIN ASSERT(v.leftSide, 20); ASSERT(v.cmd # NIL, 100); cmd := v.cmd$ END GetCmd; PROCEDURE (t: Target) GetIdent* (OUT ident: ARRAY OF CHAR), NEW; BEGIN ASSERT(t.leftSide, 20); ASSERT(t.ident # NIL, 100); ident := t.ident$ END GetIdent; (* --------------- create commands and menu guards ------------------------ *) PROCEDURE GetParam (c: TextControllers.Controller; VAR param: ARRAY OF CHAR; VAR lbrBeg, lbrEnd, rbrBeg, rbrEnd: INTEGER); VAR rd: TextModels.Reader; i, beg, end: INTEGER; ch0, ch1, ch2: CHAR; BEGIN param[0] := 0X; IF (c # NIL) & c.HasSelection() THEN c.GetSelection(beg, end); IF end - beg > 4 THEN rd := c.text.NewReader(NIL); rd.SetPos(beg); rd.ReadChar(ch0); rd.SetPos(end-2); rd.ReadChar(ch1); rd.ReadChar(ch2); IF (ch0 = "<") & (ch1 = "<") & (ch2 = ">") THEN rd.SetPos(beg+1); rd.ReadChar(ch0); i := 0; WHILE ~rd.eot & (ch0 # ">") DO IF i < LEN(param) - 1 THEN param[i] := ch0; INC(i) END; rd.ReadChar(ch0) END; param[i] := 0X; lbrBeg := beg; lbrEnd := rd.Pos(); rbrBeg := end -2; rbrEnd := end END END END END GetParam; PROCEDURE CreateGuard* (VAR par: Dialog.Par); VAR param: ARRAY 512 OF CHAR; lbrBeg, lbrEnd, rbrBeg, rbrEnd: INTEGER; BEGIN GetParam(TextControllers.Focus(), param, lbrBeg, lbrEnd, rbrBeg, rbrEnd); par.disabled := param = "" END CreateGuard; PROCEDURE InsertionAttr (c: TextControllers.Controller; pos: INTEGER): TextModels.Attributes; VAR rd: TextModels.Reader; r: TextRulers.Ruler; a: TextModels.Attributes; ch: CHAR; BEGIN rd := c.text.NewReader(NIL); a := NIL; rd.SetPos(pos); rd.ReadChar(ch); a := rd.attr; IF a = NIL THEN c.view.PollDefaults(r, a) END; RETURN a END InsertionAttr; PROCEDURE CreateLink*; VAR lbrBeg, lbrEnd, rbrBeg, rbrEnd: INTEGER; left, right: Link; c: TextControllers.Controller; cmd: ARRAY 512 OF CHAR; op: Stores.Operation; w: TextModels.Writer; a: TextModels.Attributes; BEGIN c := TextControllers.Focus(); GetParam(TextControllers.Focus(), cmd, lbrBeg, lbrEnd, rbrBeg, rbrEnd); IF cmd # "" THEN w := c.text.NewWriter(NIL); Models.BeginScript(c.text, "#StdLinks:Create Link", op); a := InsertionAttr(c, rbrBeg); c.text.Delete(rbrBeg, rbrEnd); right := dir.NewLink(""); w.SetPos(rbrBeg); IF a # NIL THEN w.SetAttr(a) END; w.WriteView(right, 0, 0); a := InsertionAttr(c, lbrBeg); c.text.Delete(lbrBeg, lbrEnd); left := dir.NewLink(cmd); w.SetPos(lbrBeg); IF a # NIL THEN w.SetAttr(a) END; w.WriteView(left, 0, 0); Models.EndScript(c.text, op) END END CreateLink; PROCEDURE CreateTarget*; VAR lbrBeg, lbrEnd, rbrBeg, rbrEnd: INTEGER; left, right: Target; c: TextControllers.Controller; ident: ARRAY 512 OF CHAR; op: Stores.Operation; w: TextModels.Writer; a: TextModels.Attributes; BEGIN c := TextControllers.Focus(); GetParam(TextControllers.Focus(), ident, lbrBeg, lbrEnd, rbrBeg, rbrEnd); IF ident # "" THEN w := c.text.NewWriter(NIL); Models.BeginScript(c.text, "#StdLinks:Create Target", op); a := InsertionAttr(c, rbrBeg); c.text.Delete(rbrBeg, rbrEnd); right := dir.NewTarget(""); w.SetPos(rbrBeg); IF a # NIL THEN w.SetAttr(a) END; w.WriteView(right, 0, 0); a := InsertionAttr(c, lbrBeg); c.text.Delete(lbrBeg, lbrEnd); left := dir.NewTarget(ident); w.SetPos(lbrBeg); IF a # NIL THEN w.SetAttr(a) END; w.WriteView(left, 0, 0); Models.EndScript(c.text, op) END END CreateTarget; PROCEDURE ShowTarget* (IN ident: ARRAY OF CHAR); VAR c: TextControllers.Controller; rd: TextModels.Reader; v: Views.View; left, right: Target; beg, end: INTEGER; BEGIN c := TextControllers.Focus(); IF c # NIL THEN rd := c.text.NewReader(NIL); REPEAT rd.ReadView(v) UNTIL rd.eot OR (v # NIL) & (v IS Target) & v(Target).leftSide & (v(Target).ident^ = ident); IF ~rd.eot THEN GetTargetPair(v(Target), left, right); IF (left # NIL) & (right # NIL) THEN beg := left.context(TextModels.Context).Pos(); end := right.context(TextModels.Context).Pos() + 1; c.SetSelection(beg, end); c.view.SetOrigin(beg, 0) ELSE Dialog.ShowParamMsg("target '^0' not found", ident, "", "") END ELSE Dialog.ShowParamMsg("target '^0' not found", ident, "", "") END END END ShowTarget; (* programming interface *) PROCEDURE (d: StdDirectory) NewLink (IN cmd: ARRAY OF CHAR): Link; VAR link: Link; i: INTEGER; BEGIN NEW(link); link.leftSide := cmd # ""; IF link.leftSide THEN i := 0; WHILE cmd[i] # 0X DO INC(i) END; NEW(link.cmd, i + 1); link.cmd^ := cmd$ ELSE link.cmd := NIL END; link.close := ifShiftDown; RETURN link END NewLink; PROCEDURE (d: StdDirectory) NewTarget (IN ident: ARRAY OF CHAR): Target; VAR t: Target; i: INTEGER; BEGIN NEW(t); t.leftSide := ident # ""; IF t.leftSide THEN i := 0; WHILE ident[i] # 0X DO INC(i) END; NEW(t.ident, i + 1); t.ident^ := ident$ ELSE t.ident := NIL END; RETURN t END NewTarget; PROCEDURE SetDir* (d: Directory); BEGIN ASSERT(d # NIL, 20); dir := d END SetDir; PROCEDURE Init; VAR font: Fonts.Font; d: StdDirectory; PROCEDURE DefaultAppearance; BEGIN font := Fonts.dir.Default(); iconFont := font.typeface; linkLeft := "Link"; linkRight := "~"; targetLeft := "Targ"; targetRight := "~"; coloredBackg := TRUE END DefaultAppearance; BEGIN NEW(d); dir := d; stdDir := d; IF Dialog.platform DIV 10 = 1 THEN (* Windows *) iconFont := "Wingdings"; font := Fonts.dir.This(iconFont, 10*Fonts.point (*arbitrary*), {}, Fonts.normal); IF font.IsAlien() THEN DefaultAppearance ELSE linkLeft[0] := SHORT(CHR(246)); linkLeft[1] := 0X; linkRight[0] := SHORT(CHR(245)); linkRight[1] := 0X; targetLeft[0] := SHORT(CHR(164)); targetLeft[1] := 0X; targetRight[0] := SHORT(CHR(161)); targetRight[1] := 0X; coloredBackg := FALSE END ELSIF Dialog.platform DIV 10 = 2 THEN (* Mac *) DefaultAppearance ELSE DefaultAppearance END; NEW(cleaner); dialog.close.SetResources("#Std:links") END Init; BEGIN Init END StdLinks.
Std/Mod/Links.odc
MODULE StdLoader; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT S := SYSTEM, Kernel, Files; CONST done = Kernel.done; fileNotFound = Kernel.fileNotFound; syntaxError = Kernel.syntaxError; objNotFound = Kernel.objNotFound; illegalFPrint = Kernel.illegalFPrint; cyclicImport = Kernel.cyclicImport; noMem = Kernel.noMem; commNotFound = Kernel.commNotFound; commSyntaxError = Kernel.commSyntaxError; descNotFound = -1; OFdir = "Code"; SYSdir = "System"; initMod = "Init"; OFtag = 6F4F4346H; (* meta interface consts *) mConst = 1; mTyp = 2; mVar = 3; mProc = 4; mField = 5; mBool = 1; mChar = 2; mLChar = 3; mSInt = 4; mInt = 5; mLInt = 6; mReal = 7; mLReal = 8; mSet = 9; mString = 10; mLString = 11; mRecord = 1; mArray = 2; mPointer = 3; mProctyp = 4; mInternal = 1; mReadonly = 2; mPrivate = 3; mExported = 4; (* fixup types *) absolute = 100; relative = 101; copy = 102; table = 103; tableend = 104; deref = 105; halfword = 106; TYPE Name = ARRAY 256 OF CHAR; ModSpec = POINTER TO RECORD next, link, imp: ModSpec; name: Name; file: Files.File; mod: Kernel.Module; hs, ms, ds, cs, vs, mad, dad: INTEGER END; Hook = POINTER TO RECORD (Kernel.LoaderHook) END; VAR res-: INTEGER; importing-, imported-, object-: Name; inp: Files.Reader; m: Kernel.Module; PROCEDURE Error (r: INTEGER; impd, impg: ModSpec); BEGIN res := r; imported := impd.name$; IF impg # NIL THEN importing := impg.name$ END; END Error; PROCEDURE Append (VAR s: ARRAY OF CHAR; t: ARRAY OF CHAR); VAR len, i, j: INTEGER; ch: CHAR; BEGIN len := LEN(s); i := 0; WHILE s[i] # 0X DO INC(i) END; j := 0; REPEAT ch := t[j]; s[i] := ch; INC(j); INC(i) UNTIL (ch = 0X) OR (i = len); s[len - 1] := 0X END Append; PROCEDURE ThisObjFile (VAR name: ARRAY OF CHAR): Files.File; VAR f: Files.File; loc: Files.Locator; dir, fname: Files.Name; BEGIN Kernel.SplitName(name, dir, fname); Kernel.MakeFileName(fname, Kernel.objType); loc := Files.dir.This(dir); loc := loc.This(OFdir); f := Files.dir.Old(loc, fname, TRUE); IF (f = NIL) & (dir = "") THEN loc := Files.dir.This(SYSdir); loc := loc.This(OFdir); f := Files.dir.Old(loc, fname, TRUE) END; RETURN f END ThisObjFile; PROCEDURE RWord (VAR x: INTEGER); VAR b: BYTE; y: INTEGER; BEGIN inp.ReadByte(b); y := b MOD 256; inp.ReadByte(b); y := y + 100H * (b MOD 256); inp.ReadByte(b); y := y + 10000H * (b MOD 256); inp.ReadByte(b); x := y + 1000000H * b END RWord; PROCEDURE RNum (VAR x: INTEGER); VAR b: BYTE; s, y: INTEGER; BEGIN s := 0; y := 0; inp.ReadByte(b); WHILE b < 0 DO INC(y, ASH(b + 128, s)); INC(s, 7); inp.ReadByte(b) END; x := ASH((b + 64) MOD 128 - 64, s) + y END RNum; PROCEDURE RName (VAR name: ARRAY OF CHAR); VAR b: BYTE; i, n: INTEGER; BEGIN i := 0; n := LEN(name) - 1; inp.ReadByte(b); WHILE (i < n) & (b # 0) DO name[i] := CHR(b MOD 256); INC(i); inp.ReadByte(b) END; WHILE b # 0 DO inp.ReadByte(b) END; name[i] := 0X END RName; PROCEDURE Fixup (adr: INTEGER; mod: ModSpec); VAR link, offset, linkadr, t, n, x, low, hi: INTEGER; BEGIN RNum(link); WHILE link # 0 DO RNum(offset); WHILE link # 0 DO IF link > 0 THEN linkadr := mod.mad + mod.ms + link ELSE link := -link; IF link < mod.ms THEN linkadr := mod.mad + link ELSE linkadr := mod.dad + link - mod.ms END END; S.GET(linkadr, x); t := x DIV 1000000H; n := (x + 800000H) MOD 1000000H - 800000H; IF t = absolute THEN x := adr + offset ELSIF t = relative THEN x := adr + offset - linkadr - 4 ELSIF t = copy THEN S.GET(adr + offset, x) ELSIF t = table THEN x := adr + n; n := link + 4 ELSIF t = tableend THEN x := adr + n; n := 0 ELSIF t = deref THEN S.GET(adr+2, x); INC(x, offset); ELSIF t = halfword THEN x := adr + offset; low := (x + 8000H) MOD 10000H - 8000H; hi := (x - low) DIV 10000H; S.GET(linkadr + 4, x); S.PUT(linkadr + 4, x DIV 10000H * 10000H + low MOD 10000H); x := x * 10000H + hi MOD 10000H ELSE Error(syntaxError, mod, NIL) END; S.PUT(linkadr, x); link := n END; RNum(link) END END Fixup; PROCEDURE ReadHeader (mod: ModSpec); VAR n, p: INTEGER; name: Name; imp, last: ModSpec; BEGIN mod.file := ThisObjFile(mod.name); IF (mod.file = NIL) & (mod.link # NIL) THEN (* try closing importing obj file *) mod.link.file.Close; mod.link.file := NIL; mod.file := ThisObjFile(mod.name) END; IF mod.file # NIL THEN inp := mod.file.NewReader(inp); IF inp # NIL THEN inp.SetPos(0); RWord(n); RWord(p); IF (n = OFtag) & (p = Kernel.processor) THEN RWord(mod.hs); RWord(mod.ms); RWord(mod.ds); RWord(mod.cs); RWord(mod.vs); RNum(n); RName(name); IF name = mod.name THEN mod.imp := NIL; last := NIL; WHILE n > 0 DO NEW(imp); RName(imp.name); IF last = NIL THEN mod.imp := imp ELSE last.next := imp END; last := imp; imp.next := NIL; DEC(n) END ELSE Error(fileNotFound, mod, NIL) END ELSE Error(syntaxError, mod, NIL) END ELSE Error(noMem, mod, NIL) END ELSE Error(fileNotFound, mod, NIL) END END ReadHeader; PROCEDURE ReadModule (mod: ModSpec); TYPE BlockPtr = POINTER TO ARRAY [1] 1000000H OF BYTE; VAR imptab, x, fp, ofp, opt, a: INTEGER; name: Name; dp, mp: BlockPtr; imp: ModSpec; obj: Kernel.Object; in, n: Kernel.Name; BEGIN IF mod.file = NIL THEN mod.file := ThisObjFile(mod.name) END; inp := mod.file.NewReader(inp); IF inp # NIL THEN inp.SetPos(mod.hs); Kernel.AllocModMem(mod.ds, mod.ms + mod.cs + mod.vs, mod.dad, mod.mad); IF (mod.dad # 0) & (mod.mad # 0) THEN dp := S.VAL(BlockPtr, mod.dad); mp := S.VAL(BlockPtr, mod.mad); inp.ReadBytes(mp^, 0, mod.ms); inp.ReadBytes(dp^, 0, mod.ds); inp.ReadBytes(mp^, mod.ms, mod.cs); mod.mod := S.VAL(Kernel.Module, mod.dad); Fixup(S.ADR(Kernel.NewRec), mod); Fixup(S.ADR(Kernel.NewArr), mod); Fixup(mod.mad, mod); Fixup(mod.dad, mod); Fixup(mod.mad + mod.ms, mod); Fixup(mod.mad + mod.ms + mod.cs, mod); imp := mod.imp; imptab := S.VAL(INTEGER, mod.mod.imports); WHILE (res = done) & (imp # NIL) DO RNum(x); WHILE (res <= done) & (x # 0) DO RName(name); RNum(fp); opt := 0; IF imp.mod # NIL THEN IF name = "" THEN obj := Kernel.ThisDesc(imp.mod, fp) ELSE n := SHORT(name$); obj := Kernel.ThisObject(imp.mod, n) END; IF (obj # NIL) & (obj.id MOD 16 = x) THEN ofp := obj.fprint; IF x = mTyp THEN RNum(opt); IF ODD(opt) THEN ofp := obj.offs END; IF (opt > 1) & (obj.id DIV 16 MOD 16 # mExported) THEN Error(objNotFound, imp, mod); object := name$ END; Fixup(S.VAL(INTEGER, obj.struct), mod) ELSIF x = mVar THEN Fixup(imp.mod.varBase + obj.offs, mod) ELSIF x = mProc THEN Fixup(imp.mod.procBase + obj.offs, mod) END; IF ofp # fp THEN Error(illegalFPrint, imp, mod); object := name$ END ELSIF name # "" THEN Error(objNotFound, imp, mod); object := name$ ELSE Error(descNotFound, imp, mod); (* proceed to find failing named object *) RNum(opt); Fixup(0, mod) END ELSE (* imp is dll *) IF x IN {mVar, mProc} THEN in := SHORT(imp.name$); n := SHORT(name$); a := Kernel.ThisDllObj(x, fp, in, n); IF a # 0 THEN Fixup(a, mod) ELSE Error(objNotFound, imp, mod); object := name$ END ELSIF x = mTyp THEN RNum(opt); RNum(x); IF x # 0 THEN Error(objNotFound, imp, mod); object := name$ END END END; RNum(x) END; S.PUT(imptab, imp.mod); INC(imptab, 4); imp := imp.next END; IF res # done THEN Kernel.DeallocModMem(mod.ds, mod.ms + mod.cs + mod.vs, mod.dad, mod.mad); mod.mod := NIL END ELSE Error(noMem, mod, NIL) END ELSE Error(noMem, mod, NIL) END; mod.file.Close; mod.file := NIL END ReadModule; PROCEDURE LoadMod (mod: ModSpec); VAR i: ModSpec; ok: BOOLEAN; j: INTEGER; n: Kernel.Name; BEGIN importing := ""; imported := ""; object := ""; i := mod; WHILE (i.link # NIL) & (i.link.name # mod.name) DO i := i.link END; IF i.link = NIL THEN ReadHeader(mod) ELSE Error(cyclicImport, i, i.link) END; i := mod.imp; WHILE (res = done) & (i # NIL) DO (* get imported module *) IF i.name = "$$" THEN i.name := "Kernel" END; IF i.name[0] = "$" THEN (* dll *) j := 1; WHILE i.name[j] # 0X DO i.name[j - 1] := i.name[j]; INC(j) END; i.name[j - 1] := 0X; n := SHORT(i.name$); Kernel.LoadDll(n, ok); IF ~ok THEN Error(fileNotFound, i, NIL) END ELSE n := SHORT(i.name$); i.mod := Kernel.ThisLoadedMod(n); (* loaded module *) IF i.mod = NIL THEN i.link := mod; LoadMod(i) END (* new module *) END; i := i.next END; IF res = done THEN n := SHORT(mod.name$); mod.mod := Kernel.ThisLoadedMod(n); (* guaranties uniqueness *) IF mod.mod = NIL THEN ReadModule(mod); IF res = done THEN Kernel.RegisterMod(mod.mod); res := done END END END; IF res = descNotFound THEN res := objNotFound; object := "<TypeDesc>" END; IF object # "" THEN Append(imported, "."); Append(imported, object); object := "" END END LoadMod; PROCEDURE (h: Hook) ThisMod (IN name: ARRAY OF SHORTCHAR): Kernel.Module; VAR m: Kernel.Module; ms: ModSpec; BEGIN res := done; m := Kernel.ThisLoadedMod(name); IF m = NIL THEN NEW(ms); ms.link := NIL; ms.name := name$; LoadMod(ms); m := ms.mod; inp := NIL (* free last file *) END; h.res := res; h.importing := importing$; h.imported := imported$; h.object := object$; RETURN m END ThisMod; PROCEDURE Init; VAR h: Hook; BEGIN NEW(h); Kernel.SetLoaderHook(h) END Init; BEGIN Init; m := Kernel.ThisMod("Init"); IF res # 0 THEN CASE res OF | fileNotFound: Append(imported, ": code file not found") | syntaxError: Append(imported, ": corrupted code file") | objNotFound: Append(imported, " not found") | illegalFPrint: Append(imported, ": wrong fingerprint") | cyclicImport: Append(imported, ": cyclic import") | noMem: Append(imported, ": not enough memory") ELSE Append(imported, ": loader error") END; IF res IN {objNotFound, illegalFPrint, cyclicImport} THEN Append(imported, " (imported from "); Append(imported, importing); Append(imported, ")") END; Kernel.FatalError(res, imported) END END StdLoader.
Std/Mod/Loader.odc
MODULE StdLog; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Log, Fonts, Ports, Stores, Models, Views, Dialog, HostDialog, StdDialog, TextModels, TextMappers, TextRulers, TextViews, TextControllers; CONST (** IntForm base **) charCode* = TextMappers.charCode; decimal* = TextMappers.decimal; hexadecimal* = TextMappers.hexadecimal; (** IntForm showBase **) hideBase* = TextMappers.hideBase; showBase* = TextMappers.showBase; mm = Ports.mm; TYPE ShowHook = POINTER TO RECORD (Dialog.ShowHook) END; LogHook = POINTER TO RECORD (Log.Hook) END; VAR logAlerts: BOOLEAN; text-, buf-: TextModels.Model; defruler-: TextRulers.Ruler; dir-: TextViews.Directory; out, subOut: TextMappers.Formatter; showHook: ShowHook; PROCEDURE Flush; BEGIN text.Append(buf); Views.RestoreDomain(text.Domain()) END Flush; PROCEDURE Char* (ch: CHAR); BEGIN out.WriteChar(ch); Flush END Char; PROCEDURE Int* (i: LONGINT); BEGIN out.WriteChar(" "); out.WriteInt(i); Flush END Int; PROCEDURE Real* (x: REAL); BEGIN out.WriteChar(" "); out.WriteReal(x); Flush END Real; PROCEDURE String* (IN str: ARRAY OF CHAR); BEGIN out.WriteString(str); Flush END String; PROCEDURE Bool* (x: BOOLEAN); BEGIN out.WriteChar(" "); out.WriteBool(x); Flush END Bool; PROCEDURE Set* (x: SET); BEGIN out.WriteChar(" "); out.WriteSet(x); Flush END Set; PROCEDURE IntForm* (x: LONGINT; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN); BEGIN out.WriteIntForm(x, base, minWidth, fillCh, showBase); Flush END IntForm; PROCEDURE RealForm* (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR); BEGIN out.WriteRealForm(x, precision, minW, expW, fillCh); Flush END RealForm; PROCEDURE Tab*; BEGIN out.WriteTab; Flush END Tab; PROCEDURE Ln*; BEGIN out.WriteLn; Flush; TextViews.ShowRange(text, text.Length(), text.Length(), TextViews.any) END Ln; PROCEDURE Para*; BEGIN out.WritePara; Flush; TextViews.ShowRange(text, text.Length(), text.Length(), TextViews.any) END Para; PROCEDURE View* (v: Views.View); BEGIN out.WriteView(v); Flush END View; PROCEDURE ViewForm* (v: Views.View; w, h: INTEGER); BEGIN out.WriteViewForm(v, w, h); Flush END ViewForm; PROCEDURE ParamMsg* (IN msg, p0, p1, p2: ARRAY OF CHAR); BEGIN out.WriteParamMsg(msg, p0, p1, p2); Flush END ParamMsg; PROCEDURE Msg* (IN msg: ARRAY OF CHAR); BEGIN out.WriteMsg(msg); Flush END Msg; PROCEDURE^ Open*; PROCEDURE (hook: ShowHook) ShowParamMsg (IN s, p0, p1, p2: ARRAY OF CHAR); BEGIN IF Dialog.showsStatus THEN Dialog.ShowParamStatus(s, p0, p1, p2); IF logAlerts THEN ParamMsg(s, p0, p1, p2); Ln END ELSE IF logAlerts THEN Open; ParamMsg(s, p0, p1, p2); Ln ELSE HostDialog.ShowParamMsg(s, p0, p1, p2) END END END ShowParamMsg; PROCEDURE (hook: ShowHook) ShowParamStatus (IN s, p0, p1, p2: ARRAY OF CHAR); BEGIN HostDialog.ShowParamStatus(s, p0, p1, p2) END ShowParamStatus; PROCEDURE NewView* (): TextViews.View; VAR v: TextViews.View; BEGIN Flush; Dialog.SetShowHook(showHook); (* attach alert dialogs *) v := dir.New(text); v.SetDefaults(TextRulers.CopyOf(defruler, Views.deep), dir.defAttr); RETURN v END NewView; PROCEDURE New*; BEGIN Views.Deposit(NewView()) END New; PROCEDURE SetDefaultRuler* (ruler: TextRulers.Ruler); BEGIN defruler := ruler END SetDefaultRuler; PROCEDURE SetDir* (d: TextViews.Directory); BEGIN ASSERT(d # NIL, 20); dir := d END SetDir; PROCEDURE Open*; VAR v: Views.View; pos: INTEGER; BEGIN v := NewView(); StdDialog.Open(v, "#Dev:Log", NIL, "", NIL, FALSE, TRUE, FALSE, FALSE, TRUE); Views.RestoreDomain(text.Domain()); pos := text.Length(); TextViews.ShowRange(text, pos, pos, TextViews.any); TextControllers.SetCaret(text, pos) END Open; PROCEDURE Clear*; BEGIN Models.BeginModification(Models.notUndoable, text); text.Delete(0, text.Length()); buf.Delete(0, buf.Length()); Models.EndModification(Models.notUndoable, text) END Clear; (* Sub support *) PROCEDURE* Guard (o: ANYPTR): BOOLEAN; BEGIN RETURN (o # NIL) & ~( (o IS TextModels.Model) & (o = text) OR (o IS Stores.Domain) & (o = text.Domain()) OR (o IS TextViews.View) & (o(TextViews.View).ThisModel() = text) ) END Guard; PROCEDURE* ClearBuf; VAR subBuf: TextModels.Model; BEGIN subBuf := subOut.rider.Base(); subBuf.Delete(0, subBuf.Length()) END ClearBuf; PROCEDURE* FlushBuf; VAR buf: TextModels.Model; BEGIN buf := subOut.rider.Base(); IF buf.Length() > 0 THEN IF ~Log.synch THEN Open() END; text.Append(buf) END END FlushBuf; PROCEDURE* SubFlush; BEGIN IF Log.synch THEN FlushBuf; IF Log.force THEN Views.RestoreDomain(text.Domain()) END END; END SubFlush; PROCEDURE (log: LogHook) Guard* (o: ANYPTR): BOOLEAN; BEGIN RETURN Guard(o) END Guard; PROCEDURE (log: LogHook) ClearBuf*; BEGIN ClearBuf END ClearBuf; PROCEDURE (log: LogHook) FlushBuf*; BEGIN FlushBuf END FlushBuf; PROCEDURE (log: LogHook) Beep*; BEGIN Dialog.Beep END Beep; PROCEDURE (log: LogHook) Char* (ch: CHAR); BEGIN subOut.WriteChar(ch); SubFlush END Char; PROCEDURE (log: LogHook) Int* (n: INTEGER); BEGIN subOut.WriteChar(" "); subOut.WriteInt(n); SubFlush END Int; PROCEDURE (log: LogHook) Real* (x: REAL); BEGIN subOut.WriteChar(" "); subOut.WriteReal(x); SubFlush END Real; PROCEDURE (log: LogHook) String* (IN str: ARRAY OF CHAR); BEGIN subOut.WriteString(str); SubFlush END String; PROCEDURE (log: LogHook) Bool* (x: BOOLEAN); BEGIN subOut.WriteChar(" "); subOut.WriteBool(x); SubFlush END Bool; PROCEDURE (log: LogHook) Set* (x: SET); BEGIN subOut.WriteChar(" "); subOut.WriteSet(x); SubFlush END Set; PROCEDURE (log: LogHook) IntForm* (x: INTEGER; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN); BEGIN subOut.WriteIntForm(x, base, minWidth, fillCh, showBase); SubFlush END IntForm; PROCEDURE (log: LogHook) RealForm* (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR); BEGIN subOut.WriteRealForm(x, precision, minW, expW, fillCh); SubFlush END RealForm; PROCEDURE (log: LogHook) Tab*; BEGIN subOut.WriteTab; SubFlush END Tab; PROCEDURE (log: LogHook) Ln*; BEGIN subOut.WriteLn; SubFlush; IF Log.synch THEN Views.RestoreDomain(text.Domain()) END END Ln; PROCEDURE (log: LogHook) Para*; BEGIN subOut.WritePara; SubFlush; IF Log.synch THEN Views.RestoreDomain(text.Domain()) END END Para; PROCEDURE (log: LogHook) View* (v: ANYPTR); BEGIN IF (v # NIL) & (v IS Views.View) THEN subOut.WriteView(v(Views.View)); SubFlush END END View; PROCEDURE (log: LogHook) ViewForm* (v: ANYPTR; w, h: INTEGER); BEGIN ASSERT(v # NIL, 20); IF (v # NIL) & (v IS Views.View) THEN subOut.WriteViewForm(v(Views.View), w, h); SubFlush END END ViewForm; PROCEDURE (log: LogHook) ParamMsg* (IN s, p0, p1, p2: ARRAY OF CHAR); VAR msg: ARRAY 256 OF CHAR; i: INTEGER; ch: CHAR; BEGIN IF logAlerts THEN IF Log.synch THEN Open END; Dialog.MapParamString(s, p0, p1, p2, msg); i := 0; ch := msg[0]; WHILE ch # 0X DO IF ch = TextModels.line THEN subOut.WriteLn ELSIF ch = TextModels.para THEN subOut.WritePara ELSIF ch = TextModels.tab THEN subOut.WriteTab ELSIF ch >= " " THEN subOut.WriteChar(ch) END; INC(i); ch := msg[i]; END; subOut.WriteLn; SubFlush ELSE HostDialog.ShowParamMsg(s, p0, p1, p2) END END ParamMsg; PROCEDURE AttachSubLog; VAR h: LogHook; BEGIN subOut.ConnectTo(TextModels.dir.New()); NEW(h); Log.SetHook(h); END AttachSubLog; PROCEDURE DetachSubLog; BEGIN Log.SetHook(NIL); END DetachSubLog; PROCEDURE Init; VAR font: Fonts.Font; p: TextRulers.Prop; x: INTEGER; i: INTEGER; BEGIN logAlerts := TRUE; (* logReports := FALSE; *) text := TextModels.dir.New(); buf := TextModels.CloneOf(text); out.ConnectTo(buf); font := TextModels.dir.attr.font; defruler := TextRulers.dir.New(NIL); TextRulers.SetRight(defruler, 80*mm); dir := TextViews.dir; NEW(showHook) END Init; BEGIN Init; AttachSubLog CLOSE DetachSubLog; END StdLog.
Std/Mod/Log.odc
MODULE StdLogos; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Ports, Stores, Views, Controllers, Properties; CONST W = 4; baseSize = 24 * Ports.point; colBase = 00202020H; changeColorKey = "#System:ChangeColor"; minVersion = 0; maxVersion = 0; TYPE View = POINTER TO RECORD (Views.View) c: Ports.Color END; ChangeSizeOp = POINTER TO RECORD (Stores.Operation) view: View; size: INTEGER; END; ChangeColorOp = POINTER TO RECORD (Stores.Operation) view: View; color: Ports.Color END; (* curve painting *) PROCEDURE Paint (f: Views.Frame; size: INTEGER; col, bgnd: Ports.Color); VAR i, d, s, g, m, a, b, l, l0, rl, rt, rr, rb: INTEGER; c: Ports.Color; BEGIN s := size DIV 10; d := size DIV 2; g := d DIV 8; m := size * W DIV 2; f.DrawOval(0, s * 2, size * W, size, Ports.fill, col); f.DrawOval(s * W, s * 11 DIV 4, (size - s) * W, size - s * 3 DIV 4, Ports.fill, bgnd); a := m; b := m + d; c := 7 * colBase; i := 0; WHILE i < 4 DO f.DrawOval(a, 0, b, d, Ports.fill, c); INC(a, g); DEC(b, g); DEC(c, colBase); INC(i) END; f.rider.GetRect(rl, rt, rr, rb); l0 := rl; l := (f.gx + m + d DIV 2) DIV f.unit; IF l < rr THEN f.rider.SetRect(l, rt, rr, rb); a := m; b := m + d; c := 0; i := 0; WHILE i < 4 DO f.DrawOval(a, 0, b, d, Ports.fill, c); INC(a, g); DEC(b, g); INC(c, colBase); INC(i) END; f.rider.SetRect(l0, rt, rr, rb) END END Paint; (* ChangeOp *) PROCEDURE (op: ChangeSizeOp) Do; VAR v: View; size, w: INTEGER; BEGIN v := op.view; size := op.size; v.context.GetSize(w, op.size); v.context.SetSize(size * W, size); Views.Update(v, Views.keepFrames) END Do; PROCEDURE (op: ChangeColorOp) Do; VAR v: View; color: Ports.Color; BEGIN v := op.view; color := op.color; op.color := v.c; v.c := color; Views.Update(v, Views.keepFrames) END Do; (* View *) PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader); VAR thisVersion: INTEGER; BEGIN v.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minVersion, maxVersion, thisVersion); IF rd.cancelled THEN RETURN END; rd.ReadInt(v.c) END Internalize; PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer); BEGIN v.Externalize^(wr); wr.WriteVersion(maxVersion); wr.WriteInt(v.c) END Externalize; PROCEDURE (v: View) CopyFromSimpleView (source: Views.View); BEGIN WITH source: View DO v.c := source.c END END CopyFromSimpleView; PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR w, h: INTEGER; bgnd: Ports.Color; g: Views.Frame; BEGIN g := f; REPEAT g := Views.HostOf(g); bgnd := Views.transparent; g.view.GetBackground(bgnd) UNTIL bgnd # Views.transparent; v.context.GetSize(w, h); Paint(f, h, v.c, bgnd) END Restore; PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN WITH msg: Properties.CollectMsg DO Views.HandlePropMsg(v, msg.poll) | msg: Properties.EmitMsg DO Views.HandlePropMsg(v, msg.set) ELSE (* ignore other messages *) END END HandleCtrlMsg; PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message); VAR q: Properties.Property; p: Properties.StdProp; cop: ChangeColorOp; BEGIN WITH msg: Properties.SizePref DO IF (msg.w > Views.undefined) & (msg.h > Views.undefined) THEN (* constrain proposed size *) Properties.ProportionalConstraint(W, 1, msg.fixedW, msg.fixedH, msg.w, msg.h) ELSE (* return default size *) msg.w := W * baseSize; msg.h := baseSize END | msg: Properties.PollMsg DO NEW(p); p.known := {Properties.color}; p.valid := p.known; p.color.val := v.c; msg.prop := p | msg: Properties.SetMsg DO q := msg.prop; WHILE q # NIL DO WITH q: Properties.StdProp DO IF Properties.color IN q.valid THEN NEW(cop); cop.view := v; cop.color := q.color.val; Views.Do(v, changeColorKey, cop) END; ELSE END; q :=q.next END ELSE END END HandlePropMsg; PROCEDURE Deposit*; VAR v: View; BEGIN NEW(v); v.c := Ports.grey50; Views.Deposit(v) END Deposit; END StdLogos.
Std/Mod/Logos.odc
MODULE StdMenuTool; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Kernel, Files, Fonts, Ports, Models, Views, Dialog, Properties, Containers, Documents, HostMenus, StdLinks, StdCmds, TextModels, TextMappers, TextViews, TextControllers; CONST char = TextMappers.char; string = TextMappers.string; keyword = 100; menuFile = "Menus"; rsrcDir = "Rsrc"; sysDir = "System"; TYPE LangNotifier = POINTER TO RECORD (Dialog.LangNotifier) END; VAR noerr, showerr, gen: BOOLEAN; includes: Files.LocInfo; langNotifier: LangNotifier; PROCEDURE Scan (VAR s: TextMappers.Scanner); VAR ch: CHAR; p: INTEGER; BEGIN s.Scan; IF s.type = string THEN p := s.rider.Pos() - 1; IF ~s.rider.eot THEN DEC(p) END; s.rider.SetPos(p); s.rider.ReadChar(ch); s.rider.Read; IF ch # '"' THEN s.type := keyword END END END Scan; PROCEDURE Comp (IN s1, s2: ARRAY OF CHAR): INTEGER; VAR i: INTEGER; a, b: CHAR; BEGIN i := 0; a := s1[0]; b := s2[0]; WHILE (a # 0X) & ((a = b) OR (a >= "A") & (a <= "Z") & (a = CAP(b)) OR (b >= "A") & (b <= "Z") & (b = CAP(a))) DO INC(i); a := s1[i]; b := s2[i] END; RETURN ORD(a) - ORD(b) END Comp; PROCEDURE Sort (VAR list: Files.LocInfo); VAR inc, last, i1, i2: Files.LocInfo; BEGIN inc := list; list := NIL; WHILE inc # NIL DO i1 := inc; inc := inc.next; i2 := list; last := NIL; WHILE (i2 # NIL) & (Comp(i1.name, i2.name) > 0) DO last := i2; i2 := i2.next END; IF last = NIL THEN i1.next := list; list := i1 ELSE i1.next := last.next; last.next := i1 END END END Sort; PROCEDURE ParseMenus (VAR s: TextMappers.Scanner; view: Views.View; loc: Files.Locator; name: Files.Name); VAR menu, category: Dialog.String; n: INTEGER; PROCEDURE Error (VAR s: TextMappers.Scanner; err: ARRAY OF CHAR); VAR end: INTEGER; BEGIN IF noerr & showerr THEN IF loc # NIL THEN Views.Open(view, loc, name, NIL) END; end := MAX(s.rider.Pos() - 1, s.start + 1); end := MIN(end, s.rider.Base().Length()); TextControllers.SetSelection(s.rider.Base(), s.start, end); TextViews.ShowRange(s.rider.Base(), s.start, end, TextViews.focusOnly); Dialog.ShowMsg(err) END; noerr := FALSE END Error; PROCEDURE Category (VAR s: TextMappers.Scanner; VAR c: ARRAY OF CHAR); BEGIN IF (s.type = char) & (s.char = "(") THEN Scan(s); IF s.type # string THEN Error(s, "string expected") END; c := s.string$; Scan(s); IF (s.type # char) OR (s.char # ")") THEN Error(s, ") expected") END; Scan(s) ELSE c := "" END END Category; PROCEDURE Item (VAR s: TextMappers.Scanner); VAR item, str, shortcut, filter: Dialog.String; BEGIN IF s.type = keyword THEN IF gen THEN HostMenus.AddSeparator END; Scan(s) ELSE IF s.len < LEN(item) THEN item := s.string$ ELSE item := ""; Error(s, "string too long") END; IF item = "" THEN Error(s, "nonempty string expected") END; Scan(s); shortcut := ""; IF s.type = string THEN IF s.len < 8 THEN shortcut := s.string$ ELSE Error(s, "string too long") END ELSE Error(s, "string expected") END; Scan(s); IF s.type # string THEN Error(s, "string expected") END; IF s.len < LEN(str) THEN str := s.string$ ELSE str := ""; Error(s, "string too long") END; IF str = "" THEN Error(s, "nonempty string expected") END; Scan(s); IF s.type # string THEN Error(s, "string expected") END; IF s.len < LEN(str) THEN filter := s.string$ ELSE filter := ""; Error(s, "string too long") END; IF gen THEN HostMenus.AddItem(item, str, shortcut, filter) END; Scan(s) END END Item; PROCEDURE IncludeSub (sub: ARRAY OF CHAR); VAR loc: Files.Locator; view: Views.View; t: TextModels.Model; s: TextMappers.Scanner; BEGIN loc := Files.dir.This(sub); IF loc = NIL THEN RETURN END; loc := loc.This(rsrcDir); IF loc = NIL THEN RETURN END; view := Views.OldView(loc, menuFile); IF (view # NIL) & (view IS TextViews.View) THEN t := view(TextViews.View).ThisModel(); IF t # NIL THEN s.ConnectTo(t); Scan(s); ParseMenus(s, view, loc, menuFile) END END END IncludeSub; PROCEDURE Include (sub: ARRAY OF CHAR); VAR inc, last: Files.LocInfo; BEGIN IF sub = "*" THEN (* wildcard include *) IF ~gen THEN (* first pass: generate complete list *) IF includes # NIL THEN Error(s, "only one wildcard include allowed") END; includes := Files.dir.LocList(Files.dir.This("")) ELSE (* second pass: sort reduced list *) Sort(includes) END; inc := includes; WHILE (inc # NIL) & noerr DO IF Comp(inc.name, sysDir) # 0 THEN IncludeSub(inc.name) END; inc := inc.next END ELSE (* spedific includes *) IncludeSub(sub); inc := includes; last := NIL; WHILE (inc # NIL) & (Comp(inc.name, sub) # 0) DO last := inc; inc := inc.next END; IF inc # NIL THEN (* remove from wilcard list *) IF last = NIL THEN includes := inc.next ELSE last.next := inc.next END END END END Include; BEGIN n := 0; WHILE noerr & (s.type = keyword) & ((s.string = "MENU") OR (s.string = "INCLUDE")) DO IF s.string = "INCLUDE" THEN Scan(s); IF s.type # string THEN Error(s, "string expected") END; Include(s.string); Scan(s); INC(n) ELSE INC(n); Scan(s); IF s.type # string THEN Error(s, "string expected") END; menu := s.string$; IF menu = "" THEN Error(s, "nonempty string expected") END; Scan(s); Category(s, category); IF gen THEN HostMenus.Open(menu, category) END; WHILE noerr & ((s.type = string) OR (s.type = keyword) & (s.string = "SEPARATOR")) DO Item(s) END; IF (s.type # keyword) OR (s.string # "END") THEN Error(s, "END expected") END; IF gen THEN HostMenus.Close END; Scan(s) END END; IF (s.type # TextMappers.eot) OR (n = 0) THEN Error(s, "MENU expected") END; END ParseMenus; PROCEDURE InitNotifier; BEGIN IF langNotifier = NIL THEN NEW(langNotifier); Dialog.RegisterLangNotifier(langNotifier) END END InitNotifier; PROCEDURE UpdateFromText* (text: TextModels.Model); VAR s: TextMappers.Scanner; BEGIN InitNotifier; ASSERT(text # NIL, 20); s.ConnectTo(text); s.SetPos(0); Scan(s); noerr := TRUE; showerr := FALSE; gen := FALSE; ParseMenus(s, NIL, NIL, ""); IF noerr THEN s.SetPos(0); Scan(s); gen := TRUE; HostMenus.DeleteAll; ParseMenus(s, NIL, NIL, ""); HostMenus.InitMenus END; includes := NIL END UpdateFromText; PROCEDURE UpdateMenus*; VAR t: TextModels.Model; s: TextMappers.Scanner; BEGIN InitNotifier; t := TextViews.FocusText(); IF t # NIL THEN s.ConnectTo(t); s.SetPos(0); Scan(s); noerr := TRUE; showerr := TRUE; gen := FALSE; ParseMenus(s, NIL, NIL, ""); IF noerr THEN s.SetPos(0); Scan(s); gen := TRUE; HostMenus.DeleteAll; ParseMenus(s, NIL, NIL, ""); HostMenus.InitMenus END END; includes := NIL END UpdateMenus; PROCEDURE UpdateAllMenus*; VAR view: Views.View; t: TextModels.Model; s: TextMappers.Scanner; loc: Files.Locator; BEGIN InitNotifier; loc := Files.dir.This(sysDir); IF loc = NIL THEN RETURN END; loc := loc.This(rsrcDir); IF loc = NIL THEN RETURN END; view := Views.OldView(loc, menuFile); IF (view # NIL) & (view IS TextViews.View) THEN t := view(TextViews.View).ThisModel(); IF t # NIL THEN s.ConnectTo(t); Scan(s); noerr := TRUE; showerr := TRUE; gen := FALSE; ParseMenus(s, view, loc, menuFile); IF noerr THEN s.SetPos(0); Scan(s); gen := TRUE; HostMenus.DeleteAll; ParseMenus(s, NIL, NIL, ""); HostMenus.InitMenus ELSE Dialog.ShowMsg("errors detected in menu file"); END END ELSE Dialog.ShowMsg("cannot open menu file") END; includes := NIL END UpdateAllMenus; PROCEDURE InsertLink (VAR w: TextMappers.Formatter; path: ARRAY OF CHAR); VAR a0: TextModels.Attributes; cmd: ARRAY 256 OF CHAR; BEGIN a0 := w.rider.attr; w.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.underline})); w.rider.SetAttr(TextModels.NewColor(w.rider.attr, Ports.blue)); cmd := "StdCmds.OpenDoc('" + path + "')"; w.WriteView(StdLinks.dir.NewLink(cmd)); w.WriteString(path); w.WriteView(StdLinks.dir.NewLink("")); w.rider.SetAttr(a0); END InsertLink; PROCEDURE ListAllMenus*; VAR sub: Files.LocInfo; loc: Files.Locator; f: Files.File; t: TextModels.Model; w: TextMappers.Formatter; path: Files.Name; v: Views.View; c: Containers.Controller; p: Properties.BoundsPref; BEGIN t := TextModels.dir.New(); w.ConnectTo(t); w.WriteString("Menu Files:"); w.WriteLn; w.WriteLn; path := sysDir + "/" + rsrcDir + "/" + menuFile; InsertLink(w, path); w.WriteLn; w.WriteLn; sub := Files.dir.LocList(Files.dir.This("")); Sort(sub); WHILE sub # NIL DO IF Comp(sub.name, sysDir) # 0 THEN loc := Files.dir.This(sub.name); loc := loc.This(rsrcDir); IF loc # NIL THEN path := menuFile; Kernel.MakeFileName(path, ""); f := Files.dir.Old(loc, path, Files.shared); IF f # NIL THEN path := sub.name + "/" + rsrcDir + "/" + menuFile; InsertLink(w, path); w.WriteLn; END END END; sub := sub.next END; v := TextViews.dir.New(t); c := v(Containers.View).ThisController(); c.SetOpts(c.opts + {Containers.noCaret}); p.w := Views.undefined; p.h := Views.undefined; Views.HandlePropMsg(v, p); v := Documents.dir.New(v, p.w, p.h); Views.OpenAux(v, "All Menus") END ListAllMenus; PROCEDURE ThisMenu*; VAR s: TextMappers.Scanner; c: Models.Context; v: Views.View; name: ARRAY 256 OF CHAR; BEGIN IF StdLinks.par # NIL THEN c := StdLinks.par.context; WITH c: TextModels.Context DO s.ConnectTo(c.ThisModel()); s.SetPos(c.Pos() + 1); s.rider.ReadView(v); (* right link view *) s.Scan; IF s.type = string THEN IF s.string = "*" THEN ListAllMenus ELSE name := s.string + "/" + rsrcDir + "/" + menuFile; StdCmds.OpenDoc(name) END END ELSE END END END ThisMenu; PROCEDURE (n: LangNotifier) Notify; BEGIN UpdateAllMenus END Notify; END StdMenuTool.
Std/Mod/MenuTool.odc
MODULE StdScrollers; (* SP410 *) (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - 20080215, Fyodor Tkachov, reviewed - 20061215, Ily Ermakov, corrections in HandleCtrlMsg, to prevent memory leakage - 20050715, mf, corrections in InnerFrame and its clients " issues = " - ... " **) IMPORT Dialog, Ports, Services, Stores, Models, Views, Properties, Controllers, StdCFrames; CONST (* properties & options *) horBar* = 0; verBar* = 1; horHide* = 2; verHide* = 3; width* = 4; height* = 5; showBorder* = 6; savePos* = 7; TYPE Prop* = POINTER TO RECORD (Properties.Property) horBar*, verBar*: BOOLEAN; horHide*, verHide*: BOOLEAN; width*, height*: INTEGER; showBorder*: BOOLEAN; savePos*: BOOLEAN END; ScrollBar = POINTER TO RECORD (Views.View) v: View; ver: BOOLEAN END; InnerView = POINTER TO RECORD (Views.View) v: View END; View = POINTER TO RECORD (Views.View); view: Views.View; sbW: INTEGER; orgX, orgY: INTEGER; w, h: INTEGER; (* = 0: adapt to container *) opts: SET; (* not persistent *) hor, ver: ScrollBar; inner: InnerView; rgap, bgap: INTEGER; (* = 0: no scrollbar *) border: INTEGER; update: Action END; Context = POINTER TO RECORD (Models.Context) v: View; type: INTEGER END; Action = POINTER TO RECORD (Services.Action) v: View END; Op = POINTER TO RECORD (Stores.Operation) v: View; p: Prop END; SOp = POINTER TO RECORD (Stores.Operation) v: View; x, y: INTEGER END; UpdateMsg = RECORD (Views.Message) changed: BOOLEAN END; VAR dialog*: RECORD horizontal*, vertical*: RECORD mode*: INTEGER; adapt*: BOOLEAN; size*: REAL END; showBorder*: BOOLEAN; savePos*: BOOLEAN; valid, readOnly: SET END; (* tools *) PROCEDURE CheckPos (v: View; VAR x, y: INTEGER); VAR w, h: INTEGER; BEGIN v.context.GetSize(w, h); DEC(w, v.rgap + 2 * v.border); DEC(h, v.bgap + 2 * v.border); IF x > v.w - w THEN x := v.w - w END; IF x < 0 THEN x := 0 END; IF y > v.h - h THEN y := v.h - h END; IF y < 0 THEN y := 0 END END CheckPos; PROCEDURE InnerFrame (v: View; f: Views.Frame): Views.Frame; VAR g, h: Views.Frame; BEGIN g := Views.ThisFrame(f, v.inner); IF g = NIL THEN Views.InstallFrame(f, v.inner, v.border, v.border, 0, TRUE); g := Views.ThisFrame(f, v.inner) END; IF g # NIL THEN h := Views.ThisFrame(g, v.view); IF h = NIL THEN Views.InstallFrame(g, v.view, -v.orgX, -v.orgY, 0, TRUE); h := Views.ThisFrame(g, v.view) END END; RETURN h END InnerFrame; PROCEDURE Scroll (v: View; dir: INTEGER; ver: BOOLEAN; p: INTEGER; OUT pos: INTEGER); VAR x, y: INTEGER; last: Stores.Operation; op: SOp; BEGIN x := v.orgX; y := v.orgY; IF ver THEN pos := y ELSE pos := x END; IF dir = StdCFrames.lineUp THEN DEC(pos, 10 * Ports.mm) ELSIF dir = StdCFrames.lineDown THEN INC(pos, 10 * Ports.mm) ELSIF dir = StdCFrames.pageUp THEN DEC(pos, 40 * Ports.mm) ELSIF dir = StdCFrames.pageDown THEN INC(pos, 40 * Ports.mm) ELSIF dir = Controllers.gotoPos THEN pos := p END; IF ver THEN CheckPos(v, x, pos); y := pos ELSE CheckPos(v, pos, y); x := pos END; IF (x # v.orgX) OR (y # v.orgY) THEN last := Views.LastOp(v); IF ~(savePos IN v.opts) OR (last # NIL) & (last IS SOp) THEN v.orgX := x; v.orgY := y; Views.Update(v.view, Views.keepFrames) ELSE NEW(op); op.v := v; op.x := x; op.y := y; Views.Do(v, "#System:Scrolling", op) END END END Scroll; PROCEDURE PollSection (v: View; ver: BOOLEAN; OUT size, sect, pos: INTEGER); VAR w, h: INTEGER; BEGIN v.context.GetSize(w, h); IF ver THEN size := v.h; sect := h - v.bgap - 2 * v.border; pos := v.orgY ELSE size := v.w; sect := w - v.rgap - 2 * v.border; pos := v.orgX END END PollSection; (* SOp *) PROCEDURE (op: SOp) Do; VAR x, y: INTEGER; BEGIN x := op.x; op.x := op.v.orgX; op.v.orgX := x; y := op.y; op.y := op.v.orgY; op.v.orgY := y; Views.Update(op.v.view, Views.keepFrames) END Do; (* properties *) PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN); VAR valid: SET; BEGIN WITH q: Prop DO valid := p.valid * q.valid; equal := TRUE; IF p.horBar # q.horBar THEN EXCL(valid, horBar) END; IF p.verBar # q.verBar THEN EXCL(valid, verBar) END; IF p.horHide # q.horHide THEN EXCL(valid, horHide) END; IF p.verHide # q.verHide THEN EXCL(valid, verHide) END; IF p.width # q.width THEN EXCL(valid, width) END; IF p.height # q.height THEN EXCL(valid, height) END; IF p.showBorder # q.showBorder THEN EXCL(valid, showBorder) END; IF p.savePos # q.savePos THEN EXCL(valid, savePos) END; IF p.valid # valid THEN p.valid := valid; equal := FALSE END END END IntersectWith; PROCEDURE SetProp (v: View; p: Properties.Property); VAR op: Op; BEGIN WITH p: Prop DO NEW(op); op.v := v; op.p := p; Views.Do(v, "#System:SetProp", op) END END SetProp; PROCEDURE PollProp (v: View; OUT prop: Prop); VAR p: Prop; BEGIN NEW(p); p.valid := {horBar, verBar, horHide, verHide, width, height, showBorder, savePos}; p.readOnly := {width, height} - v.opts; p.horBar := horBar IN v.opts; p.verBar := verBar IN v.opts; p.horHide := horHide IN v.opts; p.verHide := verHide IN v.opts; p.width := v.w; p.height := v.h; p.showBorder := showBorder IN v.opts; p.savePos := savePos IN v.opts; p.known := p.valid; prop := p END PollProp; (* Op *) PROCEDURE (op: Op) Do; VAR p: Prop; v: View; valid: SET; BEGIN v := op.v; p := op.p; PollProp(v, op.p); op.p.valid := p.valid; valid := p.valid * ({horBar, verBar, horHide, verHide, showBorder, savePos} + v.opts * {width, height}); IF horBar IN valid THEN IF p.horBar THEN INCL(v.opts, horBar) ELSE EXCL(v.opts, horBar) END END; IF verBar IN valid THEN IF p.verBar THEN INCL(v.opts, verBar) ELSE EXCL(v.opts, verBar) END END; IF horHide IN valid THEN IF p.horHide THEN INCL(v.opts, horHide) ELSE EXCL(v.opts, horHide) END END; IF verHide IN valid THEN IF p.verHide THEN INCL(v.opts, verHide) ELSE EXCL(v.opts, verHide) END END; IF width IN valid THEN v.w := p.width END; IF height IN valid THEN v.h := p.height END; IF showBorder IN valid THEN IF p.showBorder THEN INCL(v.opts, showBorder); v.border := 2 * Ports.point ELSE EXCL(v.opts, showBorder); v.border := 0 END END; IF savePos IN valid THEN IF p.savePos THEN INCL(v.opts, savePos) ELSE EXCL(v.opts, savePos) END END; Views.Update(v, Views.rebuildFrames) END Do; (* Action *) PROCEDURE (a: Action) Do; VAR msg: UpdateMsg; BEGIN msg.changed := FALSE; Views.Broadcast(a.v, msg); IF msg.changed THEN Views.Update(a.v, Views.keepFrames) ELSE Views.Broadcast(a.v.hor, msg); Views.Broadcast(a.v.ver, msg) END END Do; (* ScrollBars *) PROCEDURE TrackSB (f: StdCFrames.ScrollBar; dir: INTEGER; VAR pos: INTEGER); VAR s: ScrollBar; msg: Controllers.ScrollMsg; pmsg: Controllers.PollSectionMsg; host, inner: Views.Frame; BEGIN s := f.view(ScrollBar); host := Views.HostOf(f); msg.focus := FALSE; msg.vertical := s.ver; msg.op := dir; msg.done := FALSE; inner := InnerFrame(s.v, host); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END; IF msg.done THEN pmsg.focus := FALSE; pmsg.vertical := s.ver; pmsg.valid := FALSE; pmsg.done := FALSE; inner := InnerFrame(s.v, host); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, pmsg) END; IF pmsg.done THEN pos := pmsg.partPos END ELSE Scroll(s.v, dir, s.ver, 0, pos); Views.ValidateRoot(Views.RootOf(host)) END END TrackSB; PROCEDURE SetSB (f: StdCFrames.ScrollBar; pos: INTEGER); VAR s: ScrollBar; msg: Controllers.ScrollMsg; p: INTEGER; host, inner: Views.Frame; BEGIN s := f.view(ScrollBar); host := Views.HostOf(f); msg.focus := FALSE; msg.vertical := s.ver; msg.op := Controllers.gotoPos; msg.pos := pos; msg.done := FALSE; inner := InnerFrame(s.v, host); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END; IF ~msg.done THEN Scroll(s.v, Controllers.gotoPos, s.ver, pos, p); Views.ValidateRoot(Views.RootOf(host)) END END SetSB; PROCEDURE GetSB (f: StdCFrames.ScrollBar; OUT size, sect, pos: INTEGER); VAR s: ScrollBar; msg: Controllers.PollSectionMsg; host, inner: Views.Frame; BEGIN s := f.view(ScrollBar); host := Views.HostOf(f); msg.focus := FALSE; msg.vertical := s.ver; msg.wholeSize := 1; msg.partSize := 0; msg.partPos := 0; msg.valid := FALSE; msg.done := FALSE; inner := InnerFrame(s.v, host); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END; IF msg.done THEN IF msg.valid THEN size := msg.wholeSize; sect := msg.partSize; pos := msg.partPos ELSE size := 1; sect := 1; pos := 0 END ELSE PollSection(s.v, s.ver, size, sect, pos) END END GetSB; PROCEDURE (s: ScrollBar) GetNewFrame (VAR frame: Views.Frame); VAR f: StdCFrames.ScrollBar; BEGIN f := StdCFrames.dir.NewScrollBar(); f.disabled := FALSE; f.undef := FALSE; f.readOnly := FALSE; f.Track := TrackSB; f.Get := GetSB; f.Set := SetSB; frame := f END GetNewFrame; PROCEDURE (s: ScrollBar) Restore (f: Views.Frame; l, t, r, b: INTEGER); BEGIN WITH f: StdCFrames.Frame DO f.Restore(l, t, r, b) END END Restore; PROCEDURE (s: ScrollBar) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN WITH f: StdCFrames.Frame DO WITH msg: Controllers.PollCursorMsg DO f.GetCursor(msg.x, msg.y, msg.modifiers, msg.cursor) | msg: Controllers.TrackMsg DO f.MouseDown(msg.x, msg.y, msg.modifiers) ELSE END END END HandleCtrlMsg; PROCEDURE (s: ScrollBar) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message); BEGIN WITH msg: UpdateMsg DO WITH f: StdCFrames.Frame DO f.Update() END ELSE END END HandleViewMsg; (* View *) PROCEDURE Update (v: View; f: Views.Frame); VAR msg: Controllers.PollSectionMsg; w, h: INTEGER; depends: BOOLEAN; inner: Views.Frame; BEGIN v.bgap := 0; v.rgap := 0; depends := FALSE; v.context.GetSize(w, h); DEC(w, 2 * v.border); DEC(h, 2 * v.border); IF horBar IN v.opts THEN IF horHide IN v.opts THEN msg.focus := FALSE; msg.vertical := FALSE; msg.wholeSize := 1; msg.partSize := 0; msg.partPos := 0; msg.valid := FALSE; msg.done := FALSE; inner := InnerFrame(v, f); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END; IF msg.done THEN IF msg.valid THEN v.bgap := v.sbW END ELSIF v.w > 0 THEN IF w < v.w THEN v.bgap := v.sbW ELSIF w - v.sbW < v.w THEN depends := TRUE END END ELSE v.bgap := v.sbW END END; IF verBar IN v.opts THEN IF verHide IN v.opts THEN msg.focus := FALSE; msg.vertical := TRUE; msg.wholeSize := 1; msg.partSize := 0; msg.partPos := 0; msg.valid := FALSE; msg.done := FALSE; inner := InnerFrame(v, f); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END; IF msg.done THEN IF msg.valid THEN v.rgap := v.sbW END ELSIF v.h > 0 THEN IF h - v.bgap < v.h THEN v.rgap := v.sbW END END ELSE v.rgap := v.sbW END END; IF depends & (v.rgap > 0) THEN v.bgap := v.sbW END; CheckPos(v, v.orgX, v.orgY) END Update; PROCEDURE Init (v: View; newView: BOOLEAN); CONST min = 2 * Ports.mm; max = MAX(INTEGER); default = 50 * Ports.mm; VAR c: Context; x: INTEGER; msg: Properties.ResizePref; BEGIN IF newView THEN v.opts := v.opts + {horBar, verBar, horHide, verHide}; StdCFrames.dir.GetScrollBarSize(x, v.sbW); IF v.view.context # NIL THEN v.view.context.GetSize(v.w, v.h); v.view := Views.CopyOf(v.view, Views.shallow) ELSE v.w := Views.undefined; v.h := Views.undefined; Properties.PreferredSize(v.view, min, max, min, max, default, default, v.w, v.h) END; msg.fixed := FALSE; msg.horFitToWin := FALSE; msg.verFitToWin := FALSE; msg.horFitToPage := FALSE; msg.verFitToPage := FALSE; Views.HandlePropMsg(v.view, msg); IF ~msg.fixed THEN INCL(v.opts, width); INCL(v.opts, height); IF msg.horFitToWin OR msg.horFitToPage THEN v.w := 0 END; IF msg.verFitToWin OR msg.verFitToPage THEN v.h := 0 END END END; v.rgap := 0; v.bgap := 0; IF showBorder IN v.opts THEN v.border := 2 * Ports.point ELSE v.border := 0 END; NEW(v.inner); v.inner.v := v; NEW(c); c.v := v; c.type := 3; v.inner.InitContext(c); NEW(v.hor); v.hor.ver := FALSE; v.hor.v := v; NEW(c); c.v := v; c.type := 2; v.hor.InitContext(c); NEW(v.ver); v.ver.ver := TRUE; v.ver.v := v; NEW(c); c.v := v; c.type := 1; v.ver.InitContext(c); NEW(v.update); v.update.v := v; Stores.Join(v, v.view); Stores.Join(v, v.inner); Stores.Join(v, v.hor); Stores.Join(v, v.ver); Services.DoLater(v.update, Services.now) END Init; PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader); VAR thisVersion: INTEGER; BEGIN v.Internalize^(rd); IF ~rd.cancelled THEN rd.ReadVersion(0, 0, thisVersion); IF ~rd.cancelled THEN Views.ReadView(rd, v.view); rd.ReadInt(v.sbW); rd.ReadInt(v.orgX); rd.ReadInt(v.orgY); rd.ReadInt(v.w); rd.ReadInt(v.h); rd.ReadSet(v.opts); Init(v, FALSE) END END END Internalize; PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer); BEGIN v.Externalize^(wr); wr.WriteVersion(0); Views.WriteView(wr, v.view); wr.WriteInt(v.sbW); IF savePos IN v.opts THEN wr.WriteInt(v.orgX); wr.WriteInt(v.orgY) ELSE wr.WriteInt(0); wr.WriteInt(0) END; wr.WriteInt(v.w); wr.WriteInt(v.h); wr.WriteSet(v.opts); END Externalize; PROCEDURE (v: View) ThisModel(): Models.Model; BEGIN RETURN v.view.ThisModel() END ThisModel; PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model); BEGIN WITH source: View DO IF model = NIL THEN v.view := Views.CopyOf(source.view, Views.deep) ELSE v.view := Views.CopyWithNewModel(source.view, model) END; v.sbW := source.sbW; v.orgX := source.orgX; v.orgY := source.orgY; v.w := source.w; v.h := source.h; v.opts := source.opts; END; Init(v, FALSE) END CopyFromModelView; PROCEDURE (v: View) InitContext (context: Models.Context); VAR c: Context; BEGIN v.InitContext^(context); IF v.view.context = NIL THEN NEW(c); c.v := v; c.type := 0; v.view.InitContext(c) END END InitContext; PROCEDURE (v: View) Neutralize; BEGIN v.view.Neutralize END Neutralize; PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR w, h: INTEGER; BEGIN v.context.GetSize(w, h); IF showBorder IN v.opts THEN v.border := 2 * f.dot; f.DrawRect(0, f.dot, w, v.border, Ports.fill, Ports.black); f.DrawRect(f.dot, 0, v.border, h, Ports.fill, Ports.black); f.DrawRect(0, h - v.border, w, h - f.dot, Ports.fill, Ports.grey25); f.DrawRect(w - v.border, 0, w - f.dot, h, Ports.fill, Ports.grey25); f.DrawRect(0, 0, w, f.dot, Ports.fill, Ports.grey50); f.DrawRect(0, 0, f.dot, h, Ports.fill, Ports.grey50); f.DrawRect(0, h - f.dot, w, h, Ports.fill, Ports.white); f.DrawRect(w - f.dot, 0, w, h, Ports.fill, Ports.white) END; Views.InstallFrame(f, v.inner, v.border, v.border, 0, TRUE); IF v.bgap > 0 THEN Views.InstallFrame(f, v.hor, v.border, h - v.border - v.bgap, 0, FALSE) END; IF v.rgap > 0 THEN Views.InstallFrame(f, v.ver, w - v.border - v.rgap, v.border, 0, FALSE) END END Restore; PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); VAR w, h, p, n: INTEGER;smsg: Controllers.ScrollMsg; inner: Views.Frame; BEGIN WITH msg: Controllers.WheelMsg DO smsg.focus := FALSE; smsg.op := msg.op; smsg.pos := 0; smsg.done := FALSE; n := msg.nofLines; IF (v.rgap > 0) OR (v.bgap > 0) THEN smsg.vertical := v.rgap > 0; REPEAT smsg.done := FALSE; inner := InnerFrame(v, f); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, smsg) END; IF ~smsg.done THEN Scroll(v, smsg.op, smsg.vertical, 0, p); Views.ValidateRoot(Views.RootOf(f)) END; DEC(n) UNTIL n <= 0; msg.done := TRUE ELSE focus := v.inner END | msg: Controllers.CursorMessage DO v.context.GetSize(w, h); IF msg.x > w - v.border - v.rgap THEN IF msg.y <= h - v.border - v.bgap THEN focus := v.ver END ELSIF msg.y > h - v.border - v.bgap THEN focus := v.hor ELSE focus := v.inner END | msg: Controllers.PollSectionMsg DO inner := InnerFrame(v, f); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END; IF ~msg.done THEN PollSection(v, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos); msg.valid := msg.partSize < msg.wholeSize; msg.done := TRUE END | msg: Controllers.ScrollMsg DO inner := InnerFrame(v, f); IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END; IF ~msg.done THEN Scroll(v, msg.op, msg.vertical, msg.pos, p); Views.ValidateRoot(Views.RootOf(f)); msg.done := TRUE END ELSE focus := v.inner END; (* I.E.: Do not update if message has poll semantic, in order to prevent waste... *) IF ~((msg IS Controllers.TickMsg) OR (msg IS Controllers.PollCursorMsg) OR (msg IS Controllers.PollOpsMsg) OR (msg IS Controllers.PollFocusMsg)) THEN Services.DoLater(v.update, Services.now) END END HandleCtrlMsg; PROCEDURE (v: View) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message); VAR b, r: INTEGER; BEGIN WITH msg: UpdateMsg DO b := v.bgap; r := v.rgap; Update(v, f); IF (v.bgap # b) OR (v.rgap # r) THEN msg.changed := TRUE END ELSE END END HandleViewMsg; PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message); VAR w, h: INTEGER; p: Properties.Property; prop: Prop; fv: Views.View; BEGIN WITH msg: Properties.FocusPref DO v.context.GetSize(w, h); Views.HandlePropMsg(v.view, msg); IF msg.atLocation THEN IF (msg.x > w - v.border - v.rgap) & (msg.y > h - v.border - v.bgap) THEN msg.hotFocus := FALSE; msg.setFocus := FALSE ELSIF ((msg.x > w - v.border - v.rgap) OR (msg.y > h - v.border - v.bgap)) & ~msg.setFocus THEN msg.hotFocus := TRUE END END | msg: Properties.SizePref DO IF (v.w > 0) & (v.h > 0) THEN IF msg.w = Views.undefined THEN msg.w := 50 * Ports.mm END; IF msg.h = Views.undefined THEN msg.h := 50 * Ports.mm END ELSE IF msg.w > v.rgap THEN DEC(msg.w, v.rgap + 2 * v.border) END; IF msg.h > v.bgap THEN DEC(msg.h, v.bgap + 2 * v.border) END; Views.HandlePropMsg(v.view, msg); IF msg.w > 0 THEN INC(msg.w, v.rgap + 2 * v.border) END; IF msg.h > 0 THEN INC(msg.h, v.bgap + 2 * v.border) END END; IF msg.w < 3 * v.sbW THEN msg.w := 3 * v.sbW END; IF msg.h < 3 * v.sbW THEN msg.h := 3 * v.sbW END | msg: Properties.ResizePref DO Views.HandlePropMsg(v.view, msg); IF v.w > 0 THEN msg.fixed := FALSE; msg.horFitToWin := TRUE; msg.horFitToPage := FALSE END; IF v.h > 0 THEN msg.fixed := FALSE; msg.verFitToWin := TRUE; msg.verFitToPage := FALSE END | msg: Properties.BoundsPref DO Views.HandlePropMsg(v.view, msg); INC(msg.w, 2 * v.border); INC(msg.h, 2 * v.border); IF (horBar IN v.opts) & ~(horHide IN v.opts) THEN INC(msg.w, v.sbW) END; IF (verBar IN v.opts) & ~(verHide IN v.opts) THEN INC(msg.h, v.sbW) END | msg: Properties.PollMsg DO Views.HandlePropMsg(v.view, msg); PollProp(v, prop); Properties.Insert(msg.prop, prop) | msg: Properties.SetMsg DO p := msg.prop; WHILE (p # NIL) & ~(p IS Prop) DO p := p.next END; IF p # NIL THEN SetProp(v, p) END; Views.HandlePropMsg(v.view, msg); | msg: Properties.ControlPref DO fv := msg.focus; IF fv = v THEN msg.focus := v.view END; Views.HandlePropMsg(v.view, msg); msg.focus := fv ELSE Views.HandlePropMsg(v.view, msg); END; END HandlePropMsg; (* InnerView *) PROCEDURE (v: InnerView) GetBackground (VAR color: Ports.Color); BEGIN color := Ports.background END GetBackground; PROCEDURE (v: InnerView) Restore (f: Views.Frame; l, t, r, b: INTEGER); BEGIN Views.InstallFrame(f, v.v.view, -v.v.orgX, -v.v.orgY, 0, TRUE) END Restore; PROCEDURE (v: InnerView) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN focus := v.v.view END HandleCtrlMsg; (* Context *) PROCEDURE (c: Context) MakeVisible (l, t, r, b: INTEGER); VAR w, h, x, y: INTEGER; BEGIN IF ~(savePos IN c.v.opts) THEN c.v.context.GetSize(w, h); x := c.v.orgX; y := c.v.orgY; IF c.v.w > 0 THEN DEC(w, c.v.rgap + 2 * c.v.border); IF r > x + w - Ports.point THEN x := r - w + Ports.point END; IF l < x + Ports.point THEN x := l - Ports.point END; END; IF c.v.h > 0 THEN DEC(h, c.v.bgap + 2 * c.v.border); IF b > y + h - Ports.point THEN y := b - h + Ports.point END; IF t < y + Ports.point THEN y := t - Ports.point END; END; IF (x # c.v.orgX) OR (y # c.v.orgY) THEN CheckPos(c.v, x, y); c.v.orgX := x; c.v.orgY := y; Views.Update(c.v.view, Views.keepFrames) END; Services.DoLater(c.v.update, Services.now) END END MakeVisible; PROCEDURE (c: Context) Consider (VAR p: Models.Proposal); BEGIN c.v.context.Consider(p) END Consider; PROCEDURE (c: Context) Normalize (): BOOLEAN; BEGIN RETURN ~(savePos IN c.v.opts) END Normalize; PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER); BEGIN c.v.context.GetSize(w, h); DEC(w, c.v.rgap + 2 * c.v.border); DEC(h, c.v.bgap + 2 * c.v.border); IF c.type = 0 THEN IF c.v.w > 0 THEN w := c.v.w END; IF c.v.h > 0 THEN h := c.v.h END ELSIF c.type = 1 THEN w := c.v.rgap ELSIF c.type = 2 THEN h := c.v.bgap END END GetSize; PROCEDURE (c: Context) SetSize (w, h: INTEGER); VAR w0, h0, w1, h1: INTEGER; BEGIN ASSERT(c.type = 0, 100); c.v.context.GetSize(w0, h0); w1 := w0; h1 := h0; IF c.v.w > 0 THEN c.v.w := w ELSE w1 := w + c.v.rgap + 2 * c.v.border END; IF c.v.h > 0 THEN c.v.h := h ELSE h1 := h + c.v.bgap + 2 * c.v.border END; IF (w1 # w0) OR (h1 # h0) THEN c.v.context.SetSize(w1, h1) END END SetSize; PROCEDURE (c: Context) ThisModel (): Models.Model; BEGIN RETURN NIL END ThisModel; (* dialog *) PROCEDURE InitDialog*; VAR p: Properties.Property; u: INTEGER; BEGIN Properties.CollectProp(p); WHILE (p # NIL) & ~(p IS Prop) DO p := p.next END; IF p # NIL THEN WITH p: Prop DO IF Dialog.metricSystem THEN u := Ports.mm DIV 10 ELSE u := Ports.inch DIV 100 END; dialog.valid := p.valid; dialog.readOnly := p.readOnly; IF ~p.horBar THEN dialog.horizontal.mode := 0 ELSIF p.horHide THEN dialog.horizontal.mode := 1 ELSE dialog.horizontal.mode := 2 END; IF ~p.verBar THEN dialog.vertical.mode := 0 ELSIF p.verHide THEN dialog.vertical.mode := 1 ELSE dialog.vertical.mode := 2 END; dialog.horizontal.size := p.width DIV u / 100; dialog.vertical.size := p.height DIV u / 100; dialog.horizontal.adapt := p.width = 0; dialog.vertical.adapt := p.height = 0; dialog.showBorder := p.showBorder; dialog.savePos := p.savePos END END END InitDialog; PROCEDURE Set*; VAR p: Prop; u: INTEGER; BEGIN IF Dialog.metricSystem THEN u := 10 * Ports.mm ELSE u := Ports.inch END; NEW(p); p.valid := dialog.valid; p.horBar := dialog.horizontal.mode # 0; p.verBar := dialog.vertical.mode # 0; p.horHide := dialog.horizontal.mode = 1; p.verHide := dialog.vertical.mode = 1; IF ~dialog.horizontal.adapt THEN p.width := SHORT(ENTIER(dialog.horizontal.size * u)) END; IF ~dialog.vertical.adapt THEN p.height := SHORT(ENTIER(dialog.vertical.size * u)) END; p.showBorder := dialog.showBorder; p.savePos := dialog.savePos; Properties.EmitProp(NIL, p) END Set; PROCEDURE DialogGuard* (VAR par: Dialog.Par); VAR p: Properties.Property; BEGIN Properties.CollectProp(p); WHILE (p # NIL) & ~(p IS Prop) DO p := p.next END; IF p = NIL THEN par.disabled := TRUE END END DialogGuard; PROCEDURE HorAdaptGuard* (VAR par: Dialog.Par); BEGIN IF width IN dialog.readOnly THEN par.readOnly := TRUE END END HorAdaptGuard; PROCEDURE VerAdaptGuard* (VAR par: Dialog.Par); BEGIN IF height IN dialog.readOnly THEN par.readOnly := TRUE END END VerAdaptGuard; PROCEDURE WidthGuard* (VAR par: Dialog.Par); BEGIN IF dialog.horizontal.adapt THEN par.disabled := TRUE ELSIF width IN dialog.readOnly THEN par.readOnly := TRUE END END WidthGuard; PROCEDURE HeightGuard* (VAR par: Dialog.Par); BEGIN IF dialog.vertical.adapt THEN par.disabled := TRUE ELSIF height IN dialog.readOnly THEN par.readOnly := TRUE END END HeightGuard; (* commands *) PROCEDURE AddScroller*; VAR poll: Controllers.PollOpsMsg; v: View; replace: Controllers.ReplaceViewMsg; BEGIN Controllers.PollOps(poll); IF (poll.singleton # NIL) & ~(poll.singleton IS View) THEN NEW(v); v.view := poll.singleton; Init(v, TRUE); replace.old := poll.singleton; replace.new := v; Controllers.Forward(replace) ELSE Dialog.Beep END END AddScroller; PROCEDURE RemoveScroller*; VAR poll: Controllers.PollOpsMsg; replace: Controllers.ReplaceViewMsg; BEGIN Controllers.PollOps(poll); IF (poll.singleton # NIL) & (poll.singleton IS View) THEN replace.old := poll.singleton; replace.new := Views.CopyOf(poll.singleton(View).view, Views.shallow); Controllers.Forward(replace) ELSE Dialog.Beep END END RemoveScroller; END StdScrollers.
Std/Mod/Scrollers.odc
MODULE StdStamps; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) (* StdStamps are used to keep track of document changes, in particular program texts. StdStamps carry a sequence number and a fingerprint of the document with them. Each time the document (and therefore its fingerprint) is changed and stored, the sequence number is incremented. (When determining the fingerprint of the document, whitespace is ignored, except in string literals.) Each StdStamp also keeps track of the history of most recent changes. For the last maxHistoryEntries sequence numbers, the date and time, and an optional one-line comment is stored. To avoid too many entries in the history while working on a module, the most recent history entry is overwritten upon the generation of a new sequence number if the current date is the same as the date in the history entry. *) IMPORT SYSTEM, (* SYSTEM.ROT only, for fingerprint calculation *) Strings, Dates, StdCmds, Ports, Models, Stores, Containers, Properties, Views, Controllers, Fonts, TextModels, TextSetters, TextMappers, TextViews, TextRulers; CONST setCommentKey = "#Std:Set Comment"; maxHistoryEntries = 25; minVersion = 0; origStampVersion = 0; thisVersion = 2; TYPE History = ARRAY maxHistoryEntries OF RECORD fprint, snr: INTEGER; (* fingerprint, sequence number *) date: INTEGER; (* days since 1/1/1 *) time: INTEGER; (* min + 64 * hour *) comment: POINTER TO ARRAY OF CHAR; (* nil if no comment *) END; StdView = POINTER TO RECORD (Views.View) (*--snr: LONGINT;*) nentries: INTEGER; (* number of entries in history *) history: History; (* newest entry in history[0] *) cache: ARRAY 64 OF CHAR; END; SetCmtOp = POINTER TO RECORD (Stores.Operation) stamp: StdView; oldcomment: POINTER TO ARRAY OF CHAR; END; VAR comment*: RECORD s*: ARRAY 64 OF CHAR; END; PROCEDURE (op: SetCmtOp) Do; VAR temp: POINTER TO ARRAY OF CHAR; BEGIN temp := op.stamp.history[0].comment; op.stamp.history[0].comment := op.oldcomment; op.oldcomment := temp; END Do; PROCEDURE Format (v: StdView); VAR s: ARRAY 64 OF CHAR; d: Dates.Date; t: INTEGER; BEGIN t := v.history[0].time; Dates.DayToDate(v.history[0].date, d); Dates.DateToString(d, Dates.plainAbbreviated, s); v.cache := s$; Strings.IntToStringForm(v.history[0].snr, Strings.decimal, 4, "0", FALSE, s); v.cache := v.cache + " (" + s + ")" END Format; PROCEDURE FontContext (v: StdView): Fonts.Font; VAR c: Models.Context; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN RETURN c(TextModels.Context).Attr().font; ELSE RETURN Fonts.dir.Default() END; END FontContext; PROCEDURE CalcFP (t: TextModels.Model): INTEGER; CONST sglQuote = "'"; dblQuote = '"'; VAR fp: INTEGER; rd: TextModels.Reader; ch, quoteChar: CHAR; BEGIN quoteChar := 0X; fp := 0; rd := t.NewReader(NIL); rd.ReadChar(ch); WHILE ~rd.eot DO IF ch = quoteChar THEN quoteChar := 0X; ELSIF (quoteChar = 0X) & ((ch = dblQuote) OR (ch = sglQuote)) THEN quoteChar := ch; END; IF (quoteChar = 0X) & (21X <= ch) & (ch # 8BX) & (ch # 8FX) & (ch # 0A0X) (* not in string literal *) OR (quoteChar # 0X) & (20X <= ch) (* within string literal *) THEN fp := SYSTEM.ROT(fp, 1) + 13 * ORD(ch); END; rd.ReadChar(ch); END; RETURN fp; END CalcFP; PROCEDURE Update (v: StdView; forcenew: BOOLEAN); VAR fp: INTEGER; i: INTEGER; ndays: INTEGER; d: Dates.Date; t: Dates.Time; BEGIN IF (v.context # NIL) & (v.context IS TextModels.Context) THEN fp := CalcFP(v.context(TextModels.Context).ThisModel()); IF (fp # v.history[0].fprint) OR forcenew THEN Dates.GetDate(d); Dates.GetTime(t); ndays := Dates.Day(d); IF (ndays # v.history[0].date) OR forcenew THEN (* move down entries in history list *) i := maxHistoryEntries-1; WHILE i > 0 DO v.history[i] := v.history[i-1]; DEC(i); END; v.history[0].comment := NIL; END; IF v.nentries < maxHistoryEntries THEN INC(v.nentries) END; INC(v.history[0].snr); v.history[0].fprint := fp; v.history[0].date := ndays; v.history[0].time := t.minute + t.hour*64; Format(v); Views.Update(v, Views.keepFrames); END; END; END Update; PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer); VAR i, len: INTEGER; BEGIN Update(v, FALSE); v.Externalize^(wr); wr.WriteVersion(thisVersion); (*--wr.WriteLInt(v.snr);*) wr.WriteXInt(v.nentries); FOR i := 0 TO v.nentries-1 DO wr.WriteInt(v.history[i].fprint); wr.WriteInt(v.history[i].snr); wr.WriteInt(v.history[i].date); wr.WriteXInt(v.history[i].time); IF v.history[i].comment # NIL THEN len := SHORT(LEN(v.history[i].comment$)); wr.WriteXInt(len); wr.WriteXString(v.history[i].comment^); ELSE wr.WriteXInt(0); END END; END Externalize; PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader); VAR version: INTEGER; format: BYTE; i, len: INTEGER; d: Dates.Date; t: Dates.Time; BEGIN v.Internalize^(rd); IF ~rd.cancelled THEN rd.ReadVersion(minVersion, thisVersion, version); IF ~rd.cancelled THEN IF version = origStampVersion THEN (* deal with old StdStamp format *) (* would like to calculate fingerprint, but hosting model not available at this time *) v.history[0].fprint := 0; v.history[0].snr := 1; v.nentries := 1; rd.ReadXInt(d.year); rd.ReadXInt(d.month); rd.ReadXInt(d.day); rd.ReadXInt(t.hour); rd.ReadXInt(t.minute); rd.ReadXInt(t.second); rd.ReadByte(format); (* format not used anymore *) v.history[0].date := Dates.Day(d); v.history[0].time := t.minute + t.hour*64; ELSE IF version = 1 THEN rd.ReadInt(v.history[0].snr) END; (* red text: to be removed soon *) rd.ReadXInt(v.nentries); FOR i := 0 TO v.nentries-1 DO rd.ReadInt(v.history[i].fprint); IF version > 1 THEN rd.ReadInt(v.history[i].snr) ELSIF (* (version = 1) & *) i > 0 THEN v.history[i].snr := v.history[i-1].snr - 1; END; (* red text: to be removed soon *) rd.ReadInt(v.history[i].date); rd.ReadXInt(v.history[i].time); rd.ReadXInt(len); IF len > 0 THEN NEW(v.history[i].comment, len + 1); rd.ReadXString(v.history[i].comment^); ELSE v.history[i].comment := NIL; END END; END; Format(v); END END END Internalize; PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View); VAR i: INTEGER; BEGIN (* v.CopyFrom^(source); *) WITH source: StdView DO (*--v.snr := source.snr;*) v.nentries := source.nentries; v.history := source.history; v.cache := source.cache; FOR i := 0 TO v.nentries - 1 DO IF source.history[i].comment # NIL THEN NEW(v.history[i].comment, LEN(source.history[i].comment$) + 1); v.history[i].comment^ := source.history[i].comment^$; END END END END CopyFromSimpleView; PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR a: TextModels.Attributes; color: Ports.Color; c: Models.Context; font: Fonts.Font; asc, dsc, fw: INTEGER; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := v.context(TextModels.Context).Attr(); font := a.font; color := a.color; ELSE font := Fonts.dir.Default(); color := Ports.black; END; font.GetBounds(asc, dsc, fw); f.DrawLine(f.l, asc + f.dot, f.r, asc + f.dot, 1, Ports.grey25 ); f.DrawString(0, asc, color, v.cache, font); END Restore; PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref); VAR font: Fonts.Font; asc, dsc, w: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR; BEGIN font := FontContext(v); font.GetBounds(asc, dsc, w); d.day := 28; d.month := 1; d.year := 2222; p.w := 0; WHILE d.month <= 12 DO Dates.DateToString(d, Dates.plainAbbreviated, s); s := s + " (0000)"; w := font.StringWidth(s); IF w > p.w THEN p.w := w END; INC(d.month) END; p.h := asc + dsc; END SizePref; PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message); VAR font: Fonts.Font; asc, w: INTEGER; BEGIN WITH msg: Properties.Preference DO WITH msg: Properties.SizePref DO SizePref(v, msg) | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: Properties.FocusPref DO msg.hotFocus := TRUE | msg: TextSetters.Pref DO font := FontContext(v); font.GetBounds(asc, msg.dsc, w); ELSE END ELSE END END HandlePropMsg; PROCEDURE NewRuler (): TextRulers.Ruler; CONST mm = Ports.mm; VAR r: TextRulers.Ruler; BEGIN r := TextRulers.dir.New(NIL); TextRulers.SetRight(r, 140 * mm); TextRulers.AddTab(r, 15 * mm); TextRulers.AddTab(r, 35 * mm); TextRulers.AddTab(r, 75 * mm); RETURN r END NewRuler; PROCEDURE ShowHistory (v: StdView); VAR text: TextModels.Model; f: TextMappers.Formatter; i: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR; tv: TextViews.View; attr: TextModels.Attributes; BEGIN text := TextModels.dir.New(); f.ConnectTo(text); attr := f.rider.attr; f.rider.SetAttr(TextModels.NewStyle(attr, {Fonts.italic})); f.WriteString("seq nr."); f.WriteTab; f.WriteString("fingerprint"); f.WriteTab; f.WriteString("date and time"); f.WriteTab; f.WriteString("comment"); f.WriteLn; f.rider.SetAttr(attr); f.WriteLn; (*--n := v.snr;*) FOR i := 0 TO v.nentries-1 DO f.WriteIntForm(v.history[i].snr, 10, 4, "0", FALSE); (*--DEC(n);*) f.WriteTab; f.WriteIntForm(v.history[i].fprint, TextMappers.hexadecimal, 8, "0", FALSE); f.WriteTab; Dates.DayToDate(v.history[i].date, d); Dates.DateToString(d, Dates.plainAbbreviated, s); f.WriteString(s); f.WriteString(" "); f.WriteIntForm(v.history[i].time DIV 64, 10, 2, "0", FALSE); f.WriteString(":"); f.WriteIntForm(v.history[i].time MOD 64, 10, 2, "0", FALSE); IF v.history[i].comment # NIL THEN f.WriteTab; f.WriteString( v.history[i].comment^); END; f.WriteLn; END; tv := TextViews.dir.New(text); tv.SetDefaults(NewRuler(), TextViews.dir.defAttr); tv.ThisController().SetOpts({Containers.noFocus, Containers.noCaret}); Views.OpenAux(tv, "History"); END ShowHistory; PROCEDURE Track (v: StdView; f: Views.Frame; x, y: INTEGER; buttons: SET); VAR c: Models.Context; w, h: INTEGER; isDown, in, in0: BOOLEAN; m: SET; BEGIN c := v.context; c.GetSize(w, h); in0 := FALSE; in := TRUE; REPEAT IF in # in0 THEN f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.show); in0 := in END; f.Input(x, y, m, isDown); in := (0 <= x) & (x < w) & (0 <= y) & (y < h) UNTIL ~isDown; IF in0 THEN f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.hide); IF Controllers.modify IN m THEN IF v.history[0].comment # NIL THEN comment.s := v.history[0].comment^$; ELSE comment.s := ""; END; StdCmds.OpenToolDialog("Std/Rsrc/Stamps", "Comment"); ELSE ShowHistory(v); END END END Track; PROCEDURE (v: StdView) HandleCtrlMsg ( f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN WITH msg: Controllers.TrackMsg DO Track(v, f, msg.x, msg.y, msg.modifiers) | msg: Controllers.PollCursorMsg DO msg.cursor := Ports.refCursor ELSE END END HandleCtrlMsg; (* ------------ programming interface: ---------------------- *) PROCEDURE GetFirstInText* (t: TextModels.Model): Views.View; VAR r: TextModels.Reader; v: Views.View; BEGIN IF t # NIL THEN r := t.NewReader(NIL); REPEAT r.ReadView(v) UNTIL (v = NIL) OR (v IS StdView); RETURN v; ELSE RETURN NIL; END; END GetFirstInText; PROCEDURE IsStamp* (v: Views.View): BOOLEAN; BEGIN RETURN v IS StdView; END IsStamp; PROCEDURE GetInfo* (v: Views.View; VAR snr, historylen: INTEGER); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO snr := v.history[0].snr; historylen := v.nentries; END END GetInfo; PROCEDURE GetData* (v: Views.View; entryno: INTEGER; VAR fprint: INTEGER; VAR date: Dates.Date; VAR time: Dates.Time); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO IF entryno <= v.nentries THEN fprint := v.history[entryno].fprint; Dates.DayToDate(v.history[entryno].date, date); time.minute := v.history[entryno].time MOD 64; time.minute := v.history[entryno].time DIV 64; time.second := 0; END END END GetData; (** Insert new history entry with comment in v. *) PROCEDURE Stamp* (v: Views.View; comment: ARRAY OF CHAR); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO Update(v, TRUE); NEW(v.history[0].comment, LEN(comment$) + 1); v.history[0].comment^ := comment$; END END Stamp; PROCEDURE New* (): Views.View; VAR v: StdView; d: Dates.Date; t: Dates.Time; BEGIN NEW(v); v.history[0].snr := 0; v.nentries := 0; v.history[0].fprint := 0; Dates.GetDate(d); Dates.GetTime(t); v.history[0].date := Dates.Day(d); v.history[0].time := t.minute + t.hour*64; Format(v); RETURN v; END New; PROCEDURE SetComment*; VAR v: Views.View; op: SetCmtOp; BEGIN v := GetFirstInText(TextViews.FocusText()); IF v # NIL THEN WITH v: StdView DO NEW(op); op.stamp := v; NEW(op.oldcomment, LEN(comment.s$) + 1); op.oldcomment^ := comment.s$; Views.Do(v, setCommentKey, op); END END END SetComment; PROCEDURE Deposit*; BEGIN Views.Deposit(New()) END Deposit; END StdStamps.
Std/Mod/Stamps.odc
MODULE StdTables; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Services, Fonts, Ports, Dialog, Meta, Stores, Models, Views, Controllers, Containers, Properties, Controls, TextModels, TextViews, HostPorts; CONST minVersion = 0; tabVersion = 2; maxCol = 256; defColW = 30 * Ports.mm; left = -1; right = -2; center = -3; (* adjustment modes *) move = 1; adjust = 2; field = 3; (* cursor modes *) tab = 09X; ltab = 0AX; lineChar = 0DX; esc = 1BX; line* = 0DX; (* line feed characher for labels *) deselect* = -1; select* = -2; changed* = -3; (* notifier op-values *) layoutEditable* = 0; dataEditable* = 1; selectionStyle* = 2; (* values for property validity in Prop *) noSelect* = 0; cellSelect* = 1; rowSelect* = 2; colSelect* = 3; crossSelect* = 4; (* selection style values *) TYPE Table* = RECORD rows-, cols-: INTEGER; selection: Selection; labels: POINTER TO ARRAY OF Dialog.String; data: POINTER TO ARRAY OF ARRAY OF Dialog.String; weights: POINTER TO ARRAY OF ARRAY OF INTEGER; styles: POINTER TO ARRAY OF ARRAY OF SET; colors: POINTER TO ARRAY OF ARRAY OF Ports.Color END; Selection = POINTER TO RECORD on: BOOLEAN; row, col: INTEGER (** only valid if on = TRUE **) END; Prop* = POINTER TO RECORD (Properties.Property) layoutEditable*, dataEditable*: BOOLEAN; selectionStyle*: INTEGER END; Control = POINTER TO RECORD (Controls.Control) (* persistent *) sprop: Properties.StdProp; (* font attributes *) tprop: Prop; (* table attributes *) columns: INTEGER; (* width[0..columns-1] and mode[0..columns-1] are defined *) width: ARRAY maxCol OF INTEGER; mode: ARRAY maxCol OF INTEGER; (* not persistent *) fldFont, titFont: Fonts.Font; (* cell fonts *) rowHeight, labelHeight, baseOff: INTEGER; (* height of rows, height of the label row and offset for font *) orgRow, orgX: INTEGER; (* scroll state, orgX in coordinates, orgRow in rows *) selRow, selCol: INTEGER; (* selected field *) showSelection: BOOLEAN; hasSelection: BOOLEAN; (* control has a selected field *) x, y, w, h: INTEGER; field: Views.View (* textfield used to enter cell content *) END; Directory* = POINTER TO ABSTRACT RECORD END; StdDirectory = POINTER TO RECORD (Directory) END; PropOp = POINTER TO RECORD (Stores.Operation) (* typeface, style and size *) tab: Control; sprop: Properties.StdProp; tprop: Prop END; FormatOp = POINTER TO RECORD (Stores.Operation) (* cell format *) tab: Control; col, width, mode: INTEGER END; TableValue = RECORD (Meta.Value) t: Table END; Context = POINTER TO RECORD (Models.Context) w, h: INTEGER; base: Views.View END; Action = POINTER TO RECORD (Services.Action) END; VAR dir-, stdDir-: Directory; text*: Dialog.String; (* used to edit cell. Only one cell can be active at once *) dlg*: RECORD layoutEditable*, dataEditable*: BOOLEAN; selectionStyle*: Dialog.List; fingerprint: INTEGER; known, valid: SET END; action: Action; PROCEDURE CountLines (IN s: Dialog.String): INTEGER; VAR i, r, l: INTEGER; BEGIN r := 1; l := LEN(s$); FOR i := 0 TO l - 1 DO IF s[i] = line THEN INC(r) END END; RETURN r END CountLines; (* Prop *) PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN); VAR valid: SET; p0: Prop; BEGIN p0 := q(Prop); valid := p.valid * p0.valid; equal := TRUE; IF p.layoutEditable # p0.layoutEditable THEN EXCL(valid, layoutEditable) END; IF p.dataEditable # p0.dataEditable THEN EXCL(valid, dataEditable) END; IF p.selectionStyle # p0.selectionStyle THEN EXCL(valid, selectionStyle) END; IF valid # p.valid THEN p.valid := valid; equal := FALSE END END IntersectWith; (* Table *) PROCEDURE (VAR tab: Table) SetSize* (rows, cols: INTEGER), NEW; VAR i, j, fr, fc: INTEGER; labels: POINTER TO ARRAY OF Dialog.String; data: POINTER TO ARRAY OF ARRAY OF Dialog.String; weights: POINTER TO ARRAY OF ARRAY OF INTEGER; styles: POINTER TO ARRAY OF ARRAY OF SET; colors: POINTER TO ARRAY OF ARRAY OF Ports.Color; BEGIN ASSERT((rows >= 0) & (cols >= 0), 20); ASSERT((cols > 0) OR ((cols = 0) & (rows = 0)), 21); tab.rows := rows; tab.cols := cols; IF rows > 0 THEN data := tab.data; NEW(tab.data, rows, cols); weights := tab.weights; NEW(tab.weights, rows, cols); styles := tab.styles; NEW(tab.styles, rows, cols); colors := tab.colors; NEW(tab.colors, rows, cols); IF data # NIL THEN FOR i := 0 TO MIN(rows, LEN(data, 0)) - 1 DO FOR j := 0 TO MIN(cols, LEN(data, 1)) - 1 DO tab.data[i, j] := data[i, j]; tab.weights[i, j] := weights[i, j]; tab.styles[i, j] := styles[i, j]; tab.colors[i, j] := colors[i, j] END END END; (* set defaults *) IF data = NIL THEN fr := 0; fc := 0 ELSE fr := LEN(data, 0); fc := LEN(data, 1) END; FOR i := fr TO LEN(tab.data, 0) - 1 DO FOR j := fc TO LEN(tab.data, 1) - 1 DO tab.weights[i, j] := Fonts.normal; tab.styles[i, j] := {}; tab.colors[i, j] := Ports.black END END ELSE tab.data := NIL END; IF cols > 0 THEN labels := tab.labels; NEW(tab.labels, cols); IF labels # NIL THEN FOR i := 0 TO MIN(cols, LEN(labels)) - 1 DO tab.labels[i] := labels[i] END END ELSE tab.labels := NIL END; IF tab.selection = NIL THEN NEW(tab.selection) ELSE tab.selection.on := FALSE END END SetSize; PROCEDURE (VAR tab: Table) SetItem* (row, col: INTEGER; (*IN*) item: Dialog.String), NEW; BEGIN ASSERT(tab.data # NIL, 20); tab.data[row, col] := item END SetItem; PROCEDURE (VAR tab: Table) GetItem* (row, col: INTEGER; OUT item: Dialog.String), NEW; BEGIN ASSERT(tab.data # NIL, 20); item := tab.data[row, col] END GetItem; PROCEDURE (VAR tab: Table) SetLabel* (col: INTEGER; (*IN*)label: Dialog.String), NEW; BEGIN ASSERT(tab.labels # NIL, 20); tab.labels[col] := label END SetLabel; PROCEDURE (VAR tab: Table) GetLabel* (col: INTEGER; OUT label: Dialog.String), NEW; BEGIN ASSERT(tab.labels # NIL, 20); label := tab.labels[col] END GetLabel; PROCEDURE (VAR tab: Table) HasSelection* (): BOOLEAN, NEW; BEGIN RETURN (tab.selection # NIL) & (tab.selection.on) END HasSelection; PROCEDURE (VAR tab: Table) GetSelection* (OUT row, col: INTEGER), NEW; BEGIN ASSERT(tab.selection # NIL, 20); ASSERT(tab.selection.on, 21); row := tab.selection.row; col := tab.selection.col END GetSelection; PROCEDURE (VAR tab: Table) Select* (row, col: INTEGER), NEW; BEGIN ASSERT(tab.selection # NIL, 20); tab.selection.on := TRUE; tab.selection.row := row; tab.selection.col := col END Select; PROCEDURE (VAR tab: Table) Deselect*, NEW; BEGIN ASSERT(tab.selection # NIL, 20); tab.selection.on := FALSE END Deselect; PROCEDURE (VAR tab: Table) SetAttr* (l, t, r, b: INTEGER; style: SET; weight: INTEGER; color: Ports.Color), NEW; VAR i, j: INTEGER; BEGIN ASSERT(tab.data # NIL, 20); FOR i := t TO b DO FOR j := l TO r DO tab.weights[i, j] := weight; tab.styles[i, j] := style; tab.colors[i, j] := color END END END SetAttr; PROCEDURE (VAR tab: Table) GetAttr* (row, col: INTEGER; OUT style: SET; OUT weight: INTEGER; OUT color: Ports.Color), NEW; BEGIN ASSERT(tab.data # NIL, 20); weight := tab.weights[row, col]; style := tab.styles[row, col]; color := tab.colors[row, col] END GetAttr; (* Context *) PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER); BEGIN w := c.w; h := c.h END GetSize; PROCEDURE (c: Context) Normalize (): BOOLEAN; BEGIN RETURN c.base.context.Normalize() END Normalize; PROCEDURE (c: Context) Consider (VAR p: Models.Proposal); BEGIN c.base.context.Consider(p) END Consider; PROCEDURE (c: Context) ThisModel (): Models.Model; BEGIN RETURN NIL END ThisModel; PROCEDURE NewField(t: Control; col, w, h: INTEGER): Views.View; VAR c: Context; p: Controls.Prop; v: Views.View; prop: Properties.StdProp; setMsg: Properties.SetMsg; BEGIN NEW(p); p.link := "StdTables.text"; IF t.mode[col] = left THEN p.opt[Controls.left] := TRUE ELSIF t.mode[col] = right THEN p.opt[Controls.right] := TRUE END; (* bug in controls, thus adjusting has to be set to left mode *) p.opt[Controls.left] := TRUE; p.opt[Controls.right] := FALSE; v := Controls.dir.NewField(p); NEW(c); c.w := w; c.h := h; c.base := t; v.InitContext(c); NEW(prop); prop.typeface := t.fldFont.typeface; prop.size := t.fldFont.size - Fonts.point; prop.style.val := t.fldFont.style; prop.style.mask := t.fldFont.style; prop.weight := t.fldFont.weight; prop.valid := {Properties.typeface..Properties.weight}; prop.known := prop.valid; setMsg.prop := prop; Views.HandlePropMsg(v, setMsg); RETURN v END NewField; PROCEDURE SendNotifyMsg (c: Control); VAR msg: Views.NotifyMsg; BEGIN msg.id0 := c.item.adr; msg.id1 := msg.id0 + c.item.Size(); msg.opts := {2, 4}; (* update, guardcheck *) Views.Omnicast(msg) END SendNotifyMsg; PROCEDURE GetSize(c: Control; OUT rows, cols: INTEGER); VAR item: Meta.Item; BEGIN IF c.item.Valid() THEN item := c.item; c.item.Lookup("rows", item); rows := item.IntVal(); c.item.Lookup("cols", item); cols := item.IntVal() ELSE rows := 0; cols := 0 END END GetSize; PROCEDURE GetLabel(c: Control; col: INTEGER; OUT val: Dialog.String; OUT ok: BOOLEAN); VAR t: TableValue; BEGIN ASSERT(c.item.Valid(), 20); c.item.GetVal(t, ok); t.t.GetLabel(col, val) END GetLabel; PROCEDURE GetAttr(c: Control; row, col: INTEGER; OUT style: SET; OUT weight: INTEGER; OUT color: Ports.Color; OUT ok: BOOLEAN); VAR t: TableValue; BEGIN ASSERT(c.item.Valid(), 20); c.item.GetVal(t, ok); t.t.GetAttr(row, col, style, weight, color) END GetAttr; PROCEDURE GetText(c: Control; row, col: INTEGER; OUT val: Dialog.String; OUT ok: BOOLEAN); VAR t: TableValue; BEGIN ASSERT(c.item.Valid(), 20); c.item.GetVal(t, ok); t.t.GetItem(row, col, val) END GetText; PROCEDURE SetText(c: Control; f: Views.Frame; row, col: INTEGER; IN val: Dialog.String; OUT ok: BOOLEAN); VAR t: TableValue; BEGIN ASSERT(c.item.Valid(), 20); c.item.GetVal(t, ok); IF ok THEN t.t.SetItem(row, col, val); (* Notify(c, row, col, {}, changed); *) SendNotifyMsg(c); Controls.Notify(c, f, changed, row, col) END END SetText; PROCEDURE GetSelection(c: Control; OUT on: BOOLEAN; OUT row, col: INTEGER; OUT ok: BOOLEAN); VAR t: TableValue; BEGIN ASSERT(c.item.Valid(), 20); c.item.GetVal(t, ok); IF ok THEN on := t.t.HasSelection(); IF on THEN t.t.GetSelection(row, col) ELSE row := -1; col := -1 END END END GetSelection; PROCEDURE SetSelection(c: Control; f: Views.Frame; on: BOOLEAN; row, col: INTEGER; OUT ok: BOOLEAN); VAR t: TableValue; BEGIN ASSERT(c.item.Valid(), 20); c.item.GetVal(t, ok); IF ok THEN IF on THEN t.t.Select(row, col); Controls.Notify(c, f, select, row, col) ELSE t.t.Deselect; Controls.Notify(c, f, deselect, row, col) END; SendNotifyMsg(c) END END SetSelection; PROCEDURE SetupControl (t: Control); VAR i, asc, dsc, w: INTEGER; BEGIN t.fldFont := Fonts.dir.This(t.sprop.typeface, t.sprop.size, t.sprop.style.val, Fonts.normal); t.titFont := Fonts.dir.This(t.sprop.typeface, t.sprop.size, t.sprop.style.val, Fonts.bold); t.rowHeight := 3 * t.sprop.size DIV 2; t.fldFont.GetBounds(asc, dsc, w); t.rowHeight := asc + dsc + 4 * Ports.point; t.baseOff := (t.rowHeight - asc - dsc) DIV 2 + asc; i := t.columns; WHILE i < maxCol DO t.width[i] := defColW; t.mode[i] := center; INC(i) END; IF t.field # NIL THEN t.field.context(Context).h := t.rowHeight END; t.labelHeight := t.rowHeight END SetupControl; (** Directory **) PROCEDURE (d: Directory) NewControl* (p: Controls.Prop): Views.View, NEW, ABSTRACT; (* PropOp *) PROCEDURE (op: PropOp) Do; VAR c: Control; sprop: Properties.StdProp; tprop: Prop; BEGIN ASSERT((op.sprop # NIL) OR (op.tprop # NIL), 20); c := op.tab; IF op.sprop # NIL THEN sprop := Properties.CopyOf(c.sprop)(Properties.StdProp); sprop.valid := op.sprop.valid; (* fields to be restored *) IF Properties.typeface IN sprop.valid THEN c.sprop.typeface := op.sprop.typeface END; IF Properties.size IN sprop.valid THEN c.sprop.size := op.sprop.size END; IF Properties.style IN sprop.valid THEN c.sprop.style.mask := c.sprop.style.mask + op.sprop.style.mask; c.sprop.style.val := c.sprop.style.val - op.sprop.style.mask + op.sprop.style.val END; IF sprop.valid # {} THEN SetupControl(c) END; op.sprop := sprop END; IF op.tprop # NIL THEN tprop := Properties.CopyOf(c.tprop)(Prop); tprop.valid := op.tprop.valid; (* fields to be restored *) IF layoutEditable IN tprop.valid THEN c.tprop.layoutEditable := op.tprop.layoutEditable END; IF dataEditable IN tprop.valid THEN c.tprop.dataEditable := op.tprop.dataEditable END; IF selectionStyle IN tprop.valid THEN c.tprop.selectionStyle := op.tprop.selectionStyle END; op.tprop := tprop END; Views.Update(c, Views.rebuildFrames) END Do; (* FormatOp *) PROCEDURE (op: FormatOp) Do; VAR t: Control; c, w, m: INTEGER; BEGIN t := op.tab; c := op.col; w := op.width; m := op.mode; op.width := t.width[c]; op.mode := t.mode[c]; t.width[c] := w; t.mode[c] := m; IF c >= t.columns THEN t.columns := c + 1 END; Views.Update(t, Views.keepFrames) END Do; (* properties *) PROCEDURE PollProp (c: Control; VAR list: Properties.Property); VAR p: Properties.Property; BEGIN p := Properties.CopyOf(c.sprop); p.valid := {Properties.typeface, Properties.size, Properties.style, Properties.weight}; p.known := p.valid; p.readOnly := {Properties.weight}; Properties.Insert(list, p); p := Properties.CopyOf(c.tprop); p.valid := {layoutEditable, dataEditable, selectionStyle}; p.known := p.valid; p.readOnly := {}; Properties.Insert(list, p) END PollProp; PROCEDURE SetProp (c: Control; p: Properties.Property); VAR op: PropOp; valid: SET; BEGIN op := NIL; WHILE p # NIL DO WITH p: Properties.StdProp DO valid := p.valid * {Properties.typeface, Properties.size, Properties.style}; IF valid # {} THEN IF op = NIL THEN NEW(op); op.tab := c END; op.sprop := Properties.CopyOf(p)(Properties.StdProp); op.sprop.valid := valid END | p: Prop DO valid := p.valid * {layoutEditable, dataEditable, selectionStyle}; IF valid # {} THEN IF op = NIL THEN NEW(op); op.tab := c END; op.tprop := Properties.CopyOf(p)(Prop); op.tprop.valid := valid END ELSE END; p := p.next END; IF op # NIL THEN Views.Do(c, "#System:SetProp", op) END END SetProp; (* Control *) PROCEDURE DrawBorder (f: Views.Frame; x, y, w, h: INTEGER); BEGIN f.DrawRect(x, y, x+f.dot, y+h, Ports.fill, Ports.white); f.DrawRect(x+f.dot, y+0, x+2 * f.dot, y+ h, Ports.fill, Ports.grey25); f.DrawRect(x+0, y+0, x+w, y+f.dot, Ports.fill, Ports.white); f.DrawRect(x+f.dot, y+f.dot, x+w, y+2 * f.dot, Ports.fill, Ports.grey25); f.DrawRect(x+w - f.dot, y+0, x+w, y+h, Ports.fill, Ports.grey50); f.DrawRect(x+w - 2 * f.dot, y+f.dot, x+w - f.dot, y+h - f.dot, Ports.fill, Ports.black); f.DrawRect(x+0, y+h - f.dot, x+w, y+h, Ports.fill, Ports.grey50); f.DrawRect(x+f.dot, y+h - 2 * f.dot, x+w - f.dot, y+h - f.dot, Ports.fill, Ports.black) END DrawBorder; PROCEDURE DrawLabel (f: Views.Frame; x, y, w, x0, y0, w0, h0, mode: INTEGER; VAR is: ARRAY OF CHAR; font: Fonts.Font; rowHeight: INTEGER); VAR dx, i, j, si, sw, rw: INTEGER; s: Dialog.String; BEGIN DEC(w, 4 * f.dot); INC(x, 2 * f.dot); j := 0; y := y - rowHeight; WHILE is[j] # 0X DO si := 0; WHILE (is[j] # 0X) & (is[j] # line) DO s[si] := is[j]; INC(si); INC(j) END; IF is[j] = line THEN INC(j) END; s[si] := 0X; y := y + rowHeight; sw := font.StringWidth(s); IF sw > w THEN rw := w - font.StringWidth("..."); IF (rw >= 0) & (LEN(s) >= 4) THEN i := f.CharIndex(0, rw, s, font); IF i > 0 THEN DEC(i) END; IF i > LEN(s) - 4 THEN i := LEN(s) - 4 END; s[i] := "."; s[i+1] := "."; s[i+2] := "."; s[i+3] := 0X; sw := font.StringWidth(s) ELSE sw := 0 END END; IF sw > 0 THEN dx := x; IF mode = center THEN dx := x + (w - sw) DIV 2 ELSIF mode = right THEN dx := x + w - sw END; f.DrawString(dx, y, Ports.black, s, font) END END; DrawBorder(f, x0, y0, w0, h0) END DrawLabel; PROCEDURE DrawField (f: Views.Frame; x, y, w, mode: INTEGER; VAR s: ARRAY OF CHAR; font: Fonts.Font; color: Ports.Color); VAR i, sw, rw: INTEGER; BEGIN DEC(w, 4 * f.dot); INC(x, 2 * f.dot); sw := font.StringWidth(s); IF sw > w THEN rw := w - font.StringWidth("..."); IF (rw >= 0) & (LEN(s) >= 4) THEN i := f.CharIndex(0, rw, s, font); IF i > 0 THEN DEC(i) END; IF i > LEN(s) - 4 THEN i := LEN(s) - 4 END; s[i] := "."; s[i+1] := "."; s[i+2] := "."; s[i+3] := 0X; sw := font.StringWidth(s) ELSE sw := 0 END END; IF sw > 0 THEN IF mode = center THEN INC(x, (w - sw) DIV 2) ELSIF mode = right THEN INC(x, w - sw) END; f.DrawString(x, y, color, s, font) END END DrawField; PROCEDURE GetRect(t: Control; f: Views.Frame; row, col: INTEGER; OUT x, y, w, h: INTEGER; OUT visible: BOOLEAN); VAR c: INTEGER; BEGIN c := 0; x := 2 * f.dot - t.orgX; WHILE c < col DO INC(x, t.width[c]); INC(c) END; IF row >= t.orgRow THEN visible := TRUE; IF row = -1 THEN h := t.labelHeight ELSE h := t.rowHeight END; y := (row - t.orgRow) * t.rowHeight + t.labelHeight + 3 * f.dot; w := t.width[col] ELSE visible := FALSE END END GetRect; PROCEDURE DrawSelection (tab: Control; f: Views.Frame; selRow, selCol: INTEGER; show: BOOLEAN); VAR c, l, t, r, b, cols, rows: INTEGER; BEGIN IF (selRow >= tab.orgRow) OR (tab.tprop.selectionStyle IN {colSelect, crossSelect}) THEN GetSize(tab, rows, cols); IF (0 <= selRow) & (selRow < rows) & (0 <= selCol) & (selCol < cols) THEN IF tab.tprop.selectionStyle = cellSelect THEN (* mark selected cell *) l := 2 * f.dot - tab.orgX; c := 0; WHILE c < selCol DO INC(l, tab.width[c]); INC(c) END; r := l + tab.width[selCol]; t := (selRow - tab.orgRow) * tab.rowHeight + tab.labelHeight + 3 * f.dot; b := t + tab.rowHeight; f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show) ELSIF tab.tprop.selectionStyle = rowSelect THEN (* mark selected row *) l := 2 * f.dot - tab.orgX; r := l; c := 0; WHILE c < cols DO INC(r, tab.width[c]); INC(c) END; t := (selRow - tab.orgRow) * tab.rowHeight + tab.labelHeight + 3 * f.dot; b := t + tab.rowHeight; f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show) ELSIF tab.tprop.selectionStyle = colSelect THEN (* mark selected column *) l := 2 * f.dot - tab.orgX; c := 0; WHILE c < selCol DO INC(l, tab.width[c]); INC(c) END; r := l + tab.width[selCol]; t := tab.labelHeight + 3 * f.dot; b := t + tab.rowHeight * (rows - tab.orgRow); f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show) ELSIF tab.tprop.selectionStyle = crossSelect THEN (* mark both the row and column *) IF selRow >= tab.orgRow THEN l := 2 * f.dot - tab.orgX; r := l; c := 0; t := (selRow - tab.orgRow) * tab.rowHeight + tab.labelHeight + 3 * f.dot; b := t + tab.rowHeight; IF selCol > 0 THEN WHILE c < selCol DO INC(r, tab.width[c]); INC(c) END; f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show) END; IF selCol + 1 < cols THEN r := r + tab.width[selCol]; l := r; c := selCol + 1; WHILE c < cols DO INC(r, tab.width[c]); INC(c) END; f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show) END END; l := 2 * f.dot - tab.orgX; c := 0; WHILE c < selCol DO INC(l, tab.width[c]); INC(c) END; r := l + tab.width[selCol]; t := tab.labelHeight + 3 * f.dot; b := t + tab.rowHeight * (rows - tab.orgRow); f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show) END END END END DrawSelection; PROCEDURE Select (c: Control; f: Views.Frame; on: BOOLEAN); VAR ok: BOOLEAN; BEGIN IF on # c.hasSelection THEN c.hasSelection := on; c.showSelection := on; SetSelection(c, f, on, c.selRow, c.selCol, ok) END END Select; PROCEDURE ViewFromSelection (t: Control): Views.View; VAR str: Dialog.String; ok: BOOLEAN; BEGIN IF t.hasSelection & t.showSelection THEN GetText(t, t.selRow, t.selCol, str, ok); IF ok THEN RETURN TextViews.dir.New(TextModels.dir.NewFromString(str)) ELSE RETURN NIL END ELSE RETURN NIL END END ViewFromSelection; PROCEDURE GetControlSize (t: Control; dot: INTEGER; OUT w, h: LONGINT); VAR r, c, i: INTEGER; BEGIN IF ~t.disabled & t.item.Valid() THEN w := 0; h := 0; GetSize(t, r, c); i := 0; WHILE (i < c) & (i < maxCol) DO INC(w, t.width[i]); INC(i) END; INC(w, 3 * dot); h := LONG(r - t.orgRow) * t.rowHeight + t.labelHeight ELSE w := Views.undefined; h := Views.undefined END END GetControlSize; PROCEDURE CheckPos (t: Control; x, y, dot: INTEGER; VAR col, type, p: INTEGER); VAR c, a: INTEGER; w, h: LONGINT; BEGIN GetControlSize(t, dot, w, h); INC(x, t.orgX); IF (x >= 0) & (x <= w) & (y >= 0) & (y <= h) THEN c := 0; w := 0; type := 0; INC(x, dot); WHILE (c < maxCol) & (x >= w + t.width[c]) DO INC(w, t.width[c]); INC(c) END; IF (x <= w + 3 * dot) & (c > 0) THEN col := c - 1; p := SHORT(w) + dot - t.orgX; type := move ELSIF y - dot < t.labelHeight THEN type := adjust; col := c; a := t.width[c] DIV 3; IF x < w + a THEN p := left ELSIF x > w + a * 2 THEN p := right ELSE p := center END ELSE col := c; p := (y - t.labelHeight - dot) DIV t.rowHeight + t.orgRow - 1 + 1; type := field END ELSE type := 0 END END CheckPos; PROCEDURE MoveLine (t: Control; f: Views.Frame; col, x0: INTEGER); VAR w, h, x, y, x1, limit: INTEGER; m: SET; isDown: BOOLEAN; op: FormatOp; BEGIN t.context.GetSize(w, h); x := x0; limit := x0 - t.width[col] + 2 * f.dot; REPEAT f.Input(x1, y, m, isDown); IF x1 < limit THEN x1 := limit END; IF x1 # x THEN f.MarkRect(x, 0, x + f.dot, h, Ports.fill, Ports.invert, FALSE); x := x1; f.MarkRect(x, 0, x + f.dot, h, Ports.fill, Ports.invert, TRUE) END UNTIL ~isDown; NEW(op); op.tab := t; op.col := col; op.width := t.width[col] + x - x0; op.mode := t.mode[col]; Views.Do(t, "#System:SetLayout", op) END MoveLine; PROCEDURE ChangeAdjust (t: Control; col, mode: INTEGER); VAR op: FormatOp; BEGIN NEW(op); op.tab := t; op.col := col; op.width := t.width[col]; op.mode := mode; Views.Do(t, "#System:SetLayout", op) END ChangeAdjust; PROCEDURE ControlSections (t: Control; f: Views.Frame; vertical: BOOLEAN; OUT size, part, pos: INTEGER); VAR r, c, w, max: INTEGER; BEGIN size := 0; part := 0; pos := 0; GetSize(t, r, c); IF vertical THEN size := r; part := (f.b - (f.t + t.labelHeight + 3*f.dot)) DIV t.rowHeight; pos := t.orgRow ELSE w := 0; max := MIN(c, maxCol); c := 0; WHILE (c < max) DO INC(w, t.width[c]); INC(c) END; size := w + 3 * f.dot; part := f.r - f.l; pos := t.orgX END END ControlSections; PROCEDURE ScrollControl (t: Control; f: Views.Frame; op, pos: INTEGER; vertical: BOOLEAN); VAR size, part, p, delta, l, t0, r, b: INTEGER; BEGIN IF vertical THEN ControlSections(t, f, TRUE, size, part, p); delta := part - 1; IF delta < 1 THEN delta := 1 END; CASE op OF | Controllers.decLine: DEC(p) | Controllers.incLine: INC(p) | Controllers.decPage: DEC(p, delta) | Controllers.incPage: INC(p, delta) | Controllers.gotoPos: p := pos END; IF p > size - part THEN p := size - part END; IF p < 0 THEN p := 0 END; delta := (f.gy + t.labelHeight + 3 * f.dot) DIV f.unit; f.rider.GetRect(l, t0, r, b); IF b > delta THEN IF t0 < delta THEN f.rider.SetRect(l, delta, r, b) END; Views.Scroll(t, 0, (t.orgRow - p) * t.rowHeight); IF f.rider # NIL THEN f.rider.SetRect(l, t0, r, b) END END; t.orgRow := p ELSE ControlSections(t, f, FALSE, size, part, p); delta := part - defColW; IF delta < defColW THEN delta := defColW END; CASE op OF | Controllers.decLine: DEC(p, defColW) | Controllers.incLine: INC(p, defColW) | Controllers.decPage: DEC(p, delta) | Controllers.incPage: INC(p, delta) | Controllers.gotoPos: p := pos END; IF p >= size - part THEN p := size - part END; IF p < 0 THEN p := 0 END; Views.Scroll(t, t.orgX - p, 0); t.orgX := p END END ScrollControl; PROCEDURE HandleChar (t: Control; f: Views.Frame; ch: CHAR); BEGIN CASE ch OF | 10X: ScrollControl(t, f, Controllers.decPage, 0, FALSE) | 11X: ScrollControl(t, f, Controllers.incPage, 0, FALSE) | 12X: ScrollControl(t, f, Controllers.decPage, 0, TRUE) | 13X: ScrollControl(t, f, Controllers.incPage, 0, TRUE) | 14X: ScrollControl(t, f, Controllers.gotoPos, 0, FALSE) | 15X: ScrollControl(t, f, Controllers.gotoPos, MAX(INTEGER), FALSE) | 16X: ScrollControl(t, f, Controllers.gotoPos, 0, TRUE) | 17X: ScrollControl(t, f, Controllers.gotoPos, MAX(INTEGER), TRUE) | 1CX: ScrollControl(t, f, Controllers.decLine, 0, FALSE) | 1DX: ScrollControl(t, f, Controllers.incLine, 0, FALSE) | 1EX: ScrollControl(t, f, Controllers.decLine, 0, TRUE) | 1FX: ScrollControl(t, f, Controllers.incLine, 0, TRUE) | 07X, 08X, 1BX: Select(t, f, FALSE) (* rdel, del, esc *) ELSE END END HandleChar; PROCEDURE (t: Control) Internalize2 (VAR rd: Stores.Reader); VAR thisVersion, i: INTEGER; lockedLayout, lockedData, markRow, markCol: BOOLEAN; BEGIN rd.ReadVersion(minVersion, tabVersion, thisVersion); IF ~rd.cancelled THEN IF thisVersion = tabVersion THEN (* current table version *) NEW(t.tprop); rd.ReadBool(t.tprop.layoutEditable); rd.ReadBool(t.tprop.dataEditable); rd.ReadInt(t.tprop.selectionStyle) ELSIF thisVersion = 1 THEN (* intermediate Table version (after 1.4 Beta, before 1.4 final) *) rd.ReadBool(lockedLayout); rd.ReadBool(lockedData); rd.ReadBool(markRow); rd.ReadBool(markCol); NEW(t.tprop); t.tprop.layoutEditable := ~lockedLayout; t.tprop.dataEditable := ~lockedData; IF markRow THEN IF markCol THEN t.tprop.selectionStyle := noSelect ELSE t.tprop.selectionStyle := rowSelect END ELSE IF markCol THEN t.tprop.selectionStyle := colSelect ELSE t.tprop.selectionStyle := cellSelect END END ELSE (* old version, 1.4 Beta *) t.tprop.layoutEditable := TRUE; t.tprop.dataEditable := TRUE; t.tprop.selectionStyle := cellSelect END; NEW(t.sprop); rd.ReadString(t.sprop.typeface); rd.ReadInt(t.sprop.size); rd.ReadSet(t.sprop.style.val); t.sprop.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout}; t.sprop.weight := Fonts.normal; rd.ReadInt(t.columns); i := 0; WHILE i < t.columns DO rd.ReadInt(t.width[i]); rd.ReadInt(t.mode[i]); INC(i) END; SetupControl(t) END END Internalize2; PROCEDURE (t: Control) Externalize2 (VAR wr: Stores.Writer); VAR i: INTEGER; BEGIN wr.WriteVersion(tabVersion); wr.WriteBool(t.tprop.layoutEditable); wr.WriteBool(t.tprop.dataEditable); wr.WriteInt(t.tprop.selectionStyle); wr.WriteString(t.sprop.typeface); wr.WriteInt(t.sprop.size); wr.WriteSet(t.sprop.style.val); wr.WriteInt(t.columns); i := 0; WHILE i < t.columns DO wr.WriteInt(t.width[i]); wr.WriteInt(t.mode[i]); INC(i) END END Externalize2; PROCEDURE (t: Control) CopyFromSimpleView2 (source: Controls.Control); BEGIN WITH source: Control DO t.sprop := Properties.CopyOf(source.sprop)(Properties.StdProp); t.tprop := Properties.CopyOf(source.tprop)(Prop); t.columns := source.columns; t.width := source.width; t.mode := source.mode; SetupControl(t) END END CopyFromSimpleView2; PROCEDURE (t: Control) GetBackground (VAR color: Ports.Color); BEGIN color := Ports.background END GetBackground; PROCEDURE Paint (c: Control; f: Views.Frame; l, t, r, b: INTEGER); VAR width, w, h, rows, cols, row, col, x, y, rowHeight, dl, weight: INTEGER; font: Fonts.Font; str: Dialog.String; ok: BOOLEAN;style: SET; color: Ports.Color; BEGIN c.context.GetSize(w, h); IF ~c.disabled & c.item.Valid() THEN GetSize(c, rows, cols); DEC(c.rowHeight, c.rowHeight MOD f.unit); row := -1; y := 2 * f.dot; font := c.titFont; WHILE (row < rows) & (y < b) DO IF row = - 1 THEN rowHeight := 1; FOR col := 0 TO cols - 1 DO GetLabel(c, col, str, ok); dl := CountLines(str); IF dl > rowHeight THEN rowHeight := dl END END; rowHeight := rowHeight * c.rowHeight; c.labelHeight := rowHeight ELSE rowHeight := c.rowHeight END; IF ~Views.IsPrinterFrame(f) OR (y + rowHeight < b) THEN col := 0; x := 2 * f.dot - c.orgX; WHILE (col < cols) & (col < maxCol) & (x < r) DO width := c.width[col]; IF x + width >= 0 THEN f.DrawRect(x - f.dot, y, x, y + rowHeight, Ports.fill, Ports.black); (* left vertical separation line *) IF ~Views.IsPrinterFrame(f) OR (x + width < r) THEN IF row = -1 THEN GetLabel(c, col, str, ok); f.DrawRect(x, y, x + width - f.dot, y + rowHeight - f.dot, Ports.fill, Ports.grey25); (* background *) DrawLabel(f, x, y + c.baseOff, width - f.dot, x, y, width, rowHeight, c.mode[col], str, font, c.rowHeight) ELSE GetText(c, row, col, str, ok); GetAttr(c, row, col, style, weight, color, ok); f.DrawRect(x, y, x + width - f.dot, y + rowHeight - f.dot, Ports.fill, Ports.white); (* background *) DrawField(f, x, y + c.baseOff, width - f.dot, c.mode[col], str, Fonts.dir.This(font.typeface, font.size, style, weight), color) END END END; INC(col); INC(x, width) END; f.DrawRect(x - f.dot, y, x, y + rowHeight, Ports.fill, Ports.black); (* right vertical separator line *) IF Views.IsPrinterFrame(f) & (x >= r) THEN DEC(x, width) END; IF row = -1 THEN row := c.orgRow; font := c.fldFont; INC(y, f.dot) ELSE INC(row) END END; INC(y, rowHeight); f.DrawRect(f.dot - c.orgX, y - f.dot, x, y, Ports.fill, Ports.black) (* bottom line *) END; IF f.dot - c.orgX < x THEN f.DrawRect(f.dot - c.orgX, f.dot, x, 2 * f.dot, Ports.fill, Ports.black); f.DrawRect(f.dot - c.orgX, c.labelHeight + f.dot, x, c.labelHeight + 2 * f.dot, Ports.fill, Ports.black) END ELSE f.DrawRect(f.dot, f.dot, w - f.dot, h - f.dot, Ports.fill, Ports.grey25); f.DrawRect(0, 0, w, h, f.dot, Ports.black) END END Paint; PROCEDURE (c: Control) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR visible: BOOLEAN; g: Views.Frame; BEGIN Paint(c, f, l, t, r, b); IF c.field # NIL THEN GetRect(c, f, c.selRow, c.selCol, c.x, c.y, c.w, c.h, visible); IF visible THEN Views.InstallFrame(f, c.field, c.x, c.y, 0, TRUE) ELSE g := Views.ThisFrame(f, c.field); IF g # NIL THEN Views.RemoveFrame(f, g) END END END END Restore; PROCEDURE (c: Control) Update (f: Views.Frame; op, from, to: INTEGER); BEGIN Views.Update(c, Views.keepFrames) END Update; PROCEDURE (c: Control) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER); VAR row, col: INTEGER; ok, on: BOOLEAN; BEGIN IF c.item.Valid() THEN GetSelection(c, on, row, col, ok); IF ok THEN c.hasSelection := on; IF on THEN c.selRow := row; c.selCol := col; c.showSelection := c.field = NIL; IF c.showSelection THEN DrawSelection(c, f, c.selRow, c.selCol, TRUE) END END END END END RestoreMarks; PROCEDURE AddEditField (t: Control; f: Views.Frame; row, col: INTEGER); VAR g: Views.Frame; mMsg: Controllers.MarkMsg; ok, visible: BOOLEAN; BEGIN GetRect(t, f, row, col, t.x, t.y, t.w, t.h, visible); IF visible THEN GetText(t, row, col, text, ok); t.field := NewField(t, col, t.w, t.h); Stores.Join(t, t.field); Views.InstallFrame(f, t.field, t.x, t.y, 0, TRUE); mMsg.show := TRUE; mMsg.focus := TRUE; g := Views.ThisFrame(f, t.field); IF g # NIL THEN Views.ForwardCtrlMsg(g, mMsg) END END END AddEditField; PROCEDURE DisableEditField (t: Control; f: Views.Frame; update: BOOLEAN); VAR g: Views.Frame; mMsg: Controllers.MarkMsg; ok: BOOLEAN; BEGIN IF t.field # NIL THEN mMsg.show := FALSE; mMsg.focus := FALSE; g := Views.ThisFrame(f, t.field); IF g # NIL THEN Views.ForwardCtrlMsg(g, mMsg); Views.RemoveFrame(f, g) END; t.field := NIL; IF update THEN SetText(t, f, t.selRow, t.selCol, text, ok) END; t.showSelection := TRUE END END DisableEditField; PROCEDURE MoveEditField (t: Control; f: Views.Frame; right: BOOLEAN); VAR rows, cols: INTEGER; ok: BOOLEAN; BEGIN DisableEditField(t, f, TRUE); GetSize(t, rows, cols); Select(t, f, FALSE); IF right THEN t.selCol := (t.selCol + 1) MOD cols; IF t.selCol = 0 THEN t.selRow := (t.selRow + 1) MOD rows END ELSE t.selCol := (t.selCol - 1) MOD cols; IF t.selCol = cols - 1 THEN t.selRow := (t.selRow - 1) MOD rows END END; t.hasSelection := TRUE; t.showSelection := FALSE; SetSelection(t, f, TRUE, t.selRow, t.selCol, ok); AddEditField(t, f, t.selRow, t.selCol) END MoveEditField; PROCEDURE TrackMouse (t: Control; f: Views.Frame; VAR r, c, type: INTEGER); VAR x, y, selr, selc: INTEGER; m: SET; isDown, sel: BOOLEAN; BEGIN selr := t.selRow; selc := t.selCol; sel := t.hasSelection; REPEAT f.Input(x, y, m, isDown); CheckPos(t, x, y, f.dot, c, type, r); IF sel & ((type # field) OR (selr # r) OR (selc # c)) THEN DrawSelection(t, f, selr, selc, FALSE) END; IF (type = field) & (~sel OR (selr # r) OR (selc # c)) THEN DrawSelection(t, f, r, c, TRUE) END; sel := type = field; selr := r; selc := c UNTIL ~isDown; IF ~sel & t.hasSelection THEN DrawSelection(t, f, t.selRow, t.selCol, TRUE) END END TrackMouse; PROCEDURE (t: Control) HandleCtrlMsg2 (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); VAR p, col, type: INTEGER; x, y: INTEGER; m: SET; isDown: BOOLEAN; ok, rebuild: BOOLEAN; c, w, size, part, pos: INTEGER; BEGIN IF ~t.disabled & t.item.Valid() THEN WITH msg: Controllers.PollOpsMsg DO IF t.field # NIL THEN focus := t.field ELSIF t.hasSelection THEN msg.valid := {Controllers.copy} END | msg: Controllers.PollCursorMsg DO IF (t.field # NIL) & (msg.x >= t.x) & (msg.x <= t.x + t.w) & (msg.y >= t.y) & (msg.y <= t.y + t.h) THEN focus := t.field ELSE CheckPos(t, msg.x, msg.y, f.dot, col, type, p); IF (type = move) & t.tprop.layoutEditable THEN msg.cursor := HostPorts.resizeHCursor ELSIF (type = adjust) & t.tprop.layoutEditable THEN msg.cursor := Ports.refCursor ELSIF ~t.readOnly & (type = field) THEN msg.cursor := Ports.tableCursor END END | msg: Controllers.MarkMsg DO IF t.field # NIL THEN DisableEditField(t, f, TRUE); Views.Update(t, Views.rebuildFrames) END | msg: Controllers.SelectMsg DO IF t.field # NIL THEN focus := t.field ELSIF ~msg.set THEN Select(t, f, FALSE) END | msg: Controllers.EditMsg DO IF t.field # NIL THEN IF msg.op = Controllers.pasteChar THEN IF (msg.char = lineChar) OR (msg.char = esc) THEN DisableEditField(t, f, msg.char # esc); Views.Update(t, Views.rebuildFrames) ELSIF (msg.char = tab) OR (msg.char = ltab) THEN MoveEditField(t, f, msg.char = tab); Views.Update(t, Views.rebuildFrames) ELSE focus := t.field END ELSE focus := t.field END ELSE IF (msg.op = Controllers.pasteChar) & (msg.char = lineChar) & (t.tprop.selectionStyle = cellSelect) & t.hasSelection THEN t.showSelection := FALSE; SetSelection(t, f, TRUE, t.selRow, t.selCol, ok); AddEditField(t, f, t.selRow, t.selCol); Views.Update(t, Views.keepFrames) ELSIF msg.op = Controllers.pasteChar THEN HandleChar(t, f, msg.char) ELSIF msg.op = Controllers.copy THEN msg.view := ViewFromSelection(t); msg.w := 0; msg.h := 0; msg.isSingle := FALSE END END | msg: Controllers.TrackMsg DO IF (t.field # NIL) & (msg.x >= t.x) & (msg.x <= t.x + t.w) & (msg.y >= t.y) & (msg.y <= t.y + t.h) THEN focus := t.field ELSE rebuild := t.field # NIL; DisableEditField(t, f, TRUE); (* update below after notifications *) CheckPos(t, msg.x, msg.y, f.dot, col, type, p); IF type = move THEN IF t.tprop.layoutEditable THEN MoveLine(t, f, col, p) END ELSIF type = adjust THEN IF t.tprop.layoutEditable THEN ChangeAdjust(t, col, p); REPEAT f.Input(x, y, m, isDown) UNTIL ~isDown END ELSIF ~t.readOnly & (type = field) THEN TrackMouse(t, f, p, col, type); IF type = field THEN IF ~t.readOnly & t.tprop.dataEditable & ((Controllers.doubleClick IN msg.modifiers) OR (t.tprop.selectionStyle = noSelect)) THEN Select(t, f, FALSE); t.selRow := p; t.selCol := col; t.hasSelection := TRUE; t.showSelection := FALSE; SetSelection(t, f, TRUE, t.selRow, t.selCol, ok); AddEditField(t, f, p, col); Views.Update(t, Views.keepFrames) ELSE IF (t.selRow # p) OR (t.selCol # col) OR ~t.hasSelection THEN Select(t, f, FALSE); t.selRow := p; t.selCol := col; Select(t, f, TRUE) ELSIF t.tprop.selectionStyle = cellSelect THEN Select(t, f, FALSE) END END END END; IF rebuild THEN Views.Update(t, Views.rebuildFrames) END END | msg: Controllers.PollSectionMsg DO ControlSections(t, f, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos); IF (msg.partPos > 0) & (msg.partPos > msg.wholeSize - msg.partSize) THEN ScrollControl(t, f, Controllers.gotoPos, msg.wholeSize - msg.partSize, msg.vertical); ControlSections(t, f, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos) END; msg.valid := msg.partSize < msg.wholeSize; msg.done := TRUE | msg: Controllers.ScrollMsg DO ScrollControl(t, f, msg.op, msg.pos, msg.vertical); msg.done := TRUE | msg: Controllers.PageMsg DO IF msg.op IN {Controllers.nextPageY, Controllers.gotoPageY} THEN (* vertical *) ControlSections(t, f, TRUE, size, part, pos); IF msg.op = Controllers.nextPageY THEN t.orgRow := pos + part ELSE t.orgRow := msg.pageY * part END; msg.done := TRUE; msg.eoy :=t.orgRow >= size ELSE (* horizontal *) ControlSections(t, f, FALSE, size, part, pos); IF msg.op = Controllers.nextPageX THEN t.orgX := pos + part ELSE t.orgX := msg.pageX * part END; IF (t.orgX > 0) & (t.orgX < size) THEN c := 0; w := 0; WHILE w < t.orgX DO INC(w, t.width[c]); INC(c) END; t.orgX := w - t.width[c-1] + 1*f.dot END; msg.done := TRUE; msg.eox :=t.orgX >= size END ELSE END END END HandleCtrlMsg2; PROCEDURE (t: Control) HandlePropMsg2 (VAR msg: Properties.Message); VAR w, h: LONGINT; BEGIN WITH msg: Properties.FocusPref DO IF ~t.disabled THEN msg.setFocus := TRUE END | msg: Properties.SizePref DO IF (msg.w = Views.undefined) & (msg.h = Views.undefined) THEN GetControlSize(t, Ports.point, w, h); msg.w := SHORT(MIN(w, MAX(INTEGER))); msg.h := SHORT(MIN(h, MAX(INTEGER))) END; IF msg.w = Views.undefined THEN msg.w := 80 * Ports.mm END; IF msg.h = Views.undefined THEN msg.h := 30 * Ports.mm END | msg: Properties.ResizePref DO msg.horFitToWin := TRUE; msg.verFitToWin := TRUE | msg: Controls.PropPref DO msg.valid := {Controls.link, Controls.label, Controls.guard, Controls.notifier} | msg: Properties.PollMsg DO PollProp(t, msg.prop) | msg: Properties.SetMsg DO SetProp(t, msg.prop) | msg: Properties.ControlPref DO IF (t.field # NIL) & ((msg.char = lineChar) OR (msg.char = esc) OR (msg.char = tab) OR (msg.char = ltab)) OR (t.field = NIL) & (t.tprop.selectionStyle = cellSelect) & t.hasSelection & (msg.char = lineChar) THEN msg.accepts := TRUE END ELSE IF t.field # NIL THEN Views.HandlePropMsg(t.field, msg) END END END HandlePropMsg2; PROCEDURE (c: Control) CheckLink (VAR ok: BOOLEAN); VAR item: Meta.Item; mod: Meta.Name; name: Meta.Name; BEGIN item := c.item; IF (item.typ = Meta.recTyp) THEN item.GetTypeName(mod, name); IF (mod = "StdTables") & (name = "Table") THEN ok := TRUE ELSE ok := FALSE END ELSE ok := FALSE END END CheckLink; (* Property Dialog *) PROCEDURE PollPropForDlg; VAR q: Properties.Property; p: Prop; BEGIN dlg.layoutEditable := TRUE; dlg.dataEditable := TRUE; dlg.selectionStyle.index := cellSelect; dlg.known := {}; dlg.valid := {}; Properties.CollectProp(q); WHILE (q # NIL) & ~(q IS Prop) DO q := q.next END; IF q # NIL THEN p := q(Prop); dlg.known := p.known; dlg.valid := p.valid; IF layoutEditable IN p.valid THEN dlg.layoutEditable := p.layoutEditable END; IF dataEditable IN p.valid THEN dlg.dataEditable := p.dataEditable END; IF selectionStyle IN p.valid THEN dlg.selectionStyle.index := p.selectionStyle END END; Dialog.Update(dlg) END PollPropForDlg; PROCEDURE SetPropFromDlg; VAR p: Prop; BEGIN NEW(p); p.known := dlg.known; p.valid := dlg.valid; p.layoutEditable := dlg.layoutEditable; p.dataEditable := dlg.dataEditable; p.selectionStyle := dlg.selectionStyle.index; Properties.EmitProp(NIL, p) END SetPropFromDlg; PROCEDURE (a: Action) Do; VAR c: Containers.Controller; v: Views.View; fp: INTEGER; BEGIN Controllers.SetCurrentPath(Controllers.targetPath); c := Containers.Focus(); fp := 0; IF c # NIL THEN c.GetFirstView(Containers.selection, v); WHILE v # NIL DO fp := fp + Services.AdrOf(v); c.GetNextView(Containers.selection, v) END END; IF fp # dlg.fingerprint THEN PollPropForDlg; dlg.fingerprint := fp END; Controllers.ResetCurrentPath(); Services.DoLater(a, Services.Ticks() + Services.resolution DIV 2) END Do; PROCEDURE InitDialog*; BEGIN IF action = NIL THEN NEW(action); Services.DoLater(action, Services.now) END; Controllers.SetCurrentPath(Controllers.targetPath); PollPropForDlg; Controllers.ResetCurrentPath() END InitDialog; PROCEDURE Set*; BEGIN Controllers.SetCurrentPath(Controllers.targetPath); SetPropFromDlg; PollPropForDlg; Controllers.ResetCurrentPath() END Set; PROCEDURE Guard* (idx: INTEGER; VAR par: Dialog.Par); BEGIN IF ~(idx IN dlg.known) THEN par.disabled := TRUE ELSIF ~(idx IN dlg.valid) THEN par.undef := TRUE END END Guard; PROCEDURE Notifier* (idx, op, from, to: INTEGER); BEGIN IF op = Dialog.changed THEN INCL(dlg.valid, idx) END END Notifier; (* StdDirectory *) PROCEDURE InitStdProp (OUT p: Properties.StdProp); VAR f: Fonts.Font; BEGIN NEW(p); f := Fonts.dir.Default(); p.typeface := f.typeface; p.size := f.size; p.style.val := f.style; p.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout}; p.weight := Fonts.normal END InitStdProp; PROCEDURE InitTableProp (OUT p: Prop); BEGIN NEW(p); p.layoutEditable := TRUE; p.dataEditable := TRUE; p.selectionStyle := cellSelect END InitTableProp; PROCEDURE (d: StdDirectory) NewControl (p: Controls.Prop): Views.View; VAR c: Control; BEGIN NEW(c); Controls.OpenLink(c, p); InitStdProp(c.sprop); InitTableProp(c.tprop); SetupControl(c); RETURN c END NewControl; PROCEDURE SetDir* (d: Directory); BEGIN ASSERT(d # NIL, 20); dir := d END SetDir; PROCEDURE DepositControl*; VAR p: Controls.Prop; BEGIN NEW(p); p.link := ""; p.label := ""; p.guard := ""; p.notifier := ""; p.level := 0; p.opt[Controls.sorted] := FALSE; Views.Deposit(dir.NewControl(p)) END DepositControl; PROCEDURE SetupSelectionStyleList (VAR l: Dialog.List); BEGIN l.SetLen(5); l.SetItem(noSelect, "No Selection"); l.SetItem(cellSelect, "Select Cell"); l.SetItem(rowSelect, "Select Row"); l.SetItem(colSelect, "Select Column"); l.SetItem(crossSelect, "Select Row & Column") END SetupSelectionStyleList; PROCEDURE Init; VAR d: StdDirectory; BEGIN NEW(d); stdDir := d; dir := d; SetupSelectionStyleList(dlg.selectionStyle) END Init; BEGIN Init CLOSE Services.RemoveAction(action) END StdTables.
Std/Mod/Tables.odc
MODULE StdTabViews; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Kernel, Dialog, FormViews, StdCFrames, Stores, Views, Controllers, Ports, Properties, Containers, Services, Models, Fonts, Meta; CONST minVersion = 1; maxVersion = 1; noTab* = -1; TYPE Directory* = POINTER TO ABSTRACT RECORD END; StdDirectory = POINTER TO RECORD (Directory) END; TabInfo = RECORD label: Dialog.String; view: Views.View END; Tabs = POINTER TO ARRAY OF TabInfo; View* = POINTER TO LIMITED RECORD (Views.View) dispX, dispY, dispW, dispH: INTEGER; deposited: BOOLEAN; tabs: Tabs; font: Fonts.Font; index, nofTabs, scriptLevel: INTEGER; notifier: Dialog.String; ba: BalanceAction; tc: TrapCleaner END; TabContext = POINTER TO RECORD (Models.Context) w, h: INTEGER END; Frame* = POINTER TO ABSTRACT RECORD (StdCFrames.Frame) END; FrameDirectory* = POINTER TO ABSTRACT RECORD END; FocusMsg = RECORD (Controllers.Message) view: View END; SetItemOp = POINTER TO RECORD (Stores.Operation) tv: View; label: Dialog.String; v: Views.View; i, oldLen: INTEGER; set: BOOLEAN END; DeleteOp = POINTER TO RECORD (Stores.Operation) tv: View; label: Dialog.String; v: Views.View; i: INTEGER; set: BOOLEAN END; FontOp = POINTER TO RECORD (Stores.Operation) v: View; font: Fonts.Font END; SetNotifierOp = POINTER TO RECORD (Stores.Operation) notifier: Dialog.String; v: View END; NotifyProc = RECORD (Meta.Value) p*: PROCEDURE (tv: View; from, to: INTEGER) END; BalanceAction = POINTER TO RECORD (Services.Action) v: View END; TrapCleaner = POINTER TO RECORD (Kernel.TrapCleaner) v: View END; NotifierProc* = PROCEDURE (tv: View; from, to: INTEGER); VAR dir-, stdDir-: Directory; d: StdDirectory; setFocus*: BOOLEAN; frameDir-, frameStdDir-: FrameDirectory; dlg*: RECORD name*, notifier*: Dialog.String; opt*, index: INTEGER; tab, ntab: View END; nv: View; PROCEDURE^ (tv: View) SetIndex* (i : INTEGER), NEW; (* Auxiliary procedures *) PROCEDURE LayoutMode(view: Views.View); VAR c: Containers.Controller; BEGIN WITH view: Containers.View DO c := view.ThisController(); (* set view in layout mode *) c.SetOpts(c.opts - {Containers.noSelection, Containers.noCaret} + {Containers.noFocus} ) ELSE END END LayoutMode; PROCEDURE MaskMode(view: Views.View); VAR c: Containers.Controller; BEGIN WITH view: Containers.View DO c := view.ThisController(); (* set view in mask mode *) c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noSelection, Containers.noCaret}) ELSE END END MaskMode; PROCEDURE ExecNotifier (from, to, nop: INTEGER); VAR i: Meta.Item; p: NotifyProc; ok: BOOLEAN; BEGIN ASSERT(nv # NIL, 20); Meta.LookupPath(nv.notifier, i); IF i.obj # Meta.undef THEN i.GetVal(p, ok); IF ok THEN p.p(nv, from, to) ELSE Dialog.ShowParamMsg("#System:HasWrongType", nv.notifier, "", "") END ELSE Dialog.ShowMsg(nv.notifier + ' is not a valid notifier for StdTabViews.View') END END ExecNotifier; PROCEDURE CallNotifier (tv: View; from, to: INTEGER); BEGIN IF tv.notifier # "" THEN nv := tv; Kernel.Try(ExecNotifier, from, to, 0); nv := NIL END END CallNotifier; (* Frame *) PROCEDURE (f: Frame) InDispArea* (x, y: INTEGER): BOOLEAN, NEW, ABSTRACT; PROCEDURE (f: Frame) GetDispSize* (OUT x, y, w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (f: Frame) SetIndex* (i: INTEGER), NEW; VAR from: INTEGER; tv: View; BEGIN tv := f.view(View); from := tv.index; tv.SetIndex(i); CallNotifier(tv, from, i) END SetIndex; (** FrameDirectory **) PROCEDURE (d: FrameDirectory) GetTabSize* (VAR w, h: INTEGER), NEW, ABSTRACT; PROCEDURE (d: FrameDirectory) New* (): Frame, NEW, ABSTRACT; PROCEDURE SetFrameDir* (d: FrameDirectory); BEGIN ASSERT(d # NIL, 20); frameDir := d; IF frameStdDir = NIL THEN frameStdDir := d END END SetFrameDir; (* View *) PROCEDURE (tv: View) Update (), NEW; BEGIN IF tv.scriptLevel = 0 THEN Views.Update(tv, Views.rebuildFrames) END END Update; PROCEDURE (tv: View) Reset (), NEW; BEGIN tv.scriptLevel := 0; IF tv.tc # NIL THEN Kernel.PopTrapCleaner(tv.tc); tv.tc := NIL END; IF tv.ba # NIL THEN Services.RemoveAction(tv.ba); tv.ba := NIL END; tv.Update END Reset; PROCEDURE (tv: View) SetNofTabs* (nofTabs: INTEGER), NEW; VAR i: INTEGER; nt: Tabs; BEGIN ASSERT(nofTabs >= 0, 20); IF nofTabs = 0 THEN tv.nofTabs := 0; tv.tabs := NIL; tv.index := 0 ELSE NEW(nt, nofTabs); IF tv.tabs # NIL THEN FOR i := 0 TO MIN(nofTabs, tv.nofTabs) - 1 DO nt[i].label := tv.tabs[i].label; nt[i].view := tv.tabs[i].view END END; tv.tabs := nt; tv.nofTabs := nofTabs; tv.index := MIN(tv.index, tv.nofTabs - 1) END; tv.Update END SetNofTabs; PROCEDURE (tv: View) NofTabs* (): INTEGER, NEW; BEGIN IF tv.tabs = NIL THEN RETURN 0 END; RETURN MAX(0, tv.nofTabs) END NofTabs; PROCEDURE (tv: View) Index* (): INTEGER, NEW; BEGIN RETURN MAX(0, MIN(tv.index, tv.NofTabs() - 1)) END Index; PROCEDURE (tv: View) SetItem* (i: INTEGER; label: Dialog.String; v: Views.View), NEW; VAR sop: SetItemOp; BEGIN ASSERT(i >= 0, 20); ASSERT(label # "", 21); ASSERT(v # NIL, 22); NEW(sop); sop.tv := tv; sop.i := i; sop.v := v; sop.label := label; sop.set := TRUE; Views.Do(tv, "#Std:TabSetItem", sop) END SetItem; PROCEDURE (tv: View) GetItem* (i: INTEGER; OUT label: Dialog.String; OUT v: Views.View), NEW; BEGIN ASSERT((i >= 0) & (i < tv.NofTabs()), 21); label := tv.tabs[i].label; v := tv.tabs[i].view END GetItem; PROCEDURE (tv: View) View (i: INTEGER): Views.View, NEW; BEGIN ASSERT((i >= 0) & (i < tv.NofTabs()), 20); RETURN tv.tabs[i].view END View; PROCEDURE (tv: View) SetIndex* (i : INTEGER), NEW; BEGIN ASSERT((i >= 0) & (i < tv.NofTabs()), 20); tv.index := i; tv.Update END SetIndex; PROCEDURE (tv: View) SetNotifier* (IN notifier: ARRAY OF CHAR), NEW; VAR o: SetNotifierOp; BEGIN NEW(o); o.v := tv; o.notifier := notifier$; Views.Do(tv, "Set Notifier", o) END SetNotifier; PROCEDURE (tv: View) GetNotifier* (OUT notifier: Dialog.String), NEW; BEGIN notifier := tv.notifier END GetNotifier; PROCEDURE (tv: View) Externalize- (VAR wr: Stores.Writer); VAR l: Dialog.String; i: INTEGER; v: Views.View; BEGIN tv.Externalize^(wr); wr.WriteVersion(maxVersion); wr.WriteInt(tv.NofTabs()); wr.WriteInt(tv.Index()); wr.WriteString(tv.notifier); FOR i := 0 TO tv.NofTabs() - 1 DO tv.GetItem(i, l, v); wr.WriteString(l); Views.WriteView(wr, v) END; wr.WriteString(tv.font.typeface$); wr.WriteInt(tv.font.size); wr.WriteSet(tv.font.style); wr.WriteInt(tv.font.weight) END Externalize; PROCEDURE (tv: View) Internalize- (VAR rd: Stores.Reader); VAR thisVersion, i, size, weight: INTEGER; l: Dialog.String; v: Views.View; face: Fonts.Typeface; style: SET; BEGIN ASSERT(frameStdDir # NIL, 20); tv.Internalize^(rd); rd.ReadVersion(minVersion, maxVersion, thisVersion); IF (thisVersion >= minVersion) & (thisVersion <= maxVersion) THEN rd.ReadInt(i); tv.SetNofTabs(i); rd.ReadInt(tv.index); rd.ReadString(tv.notifier); FOR i := 0 TO tv.NofTabs() -1 DO rd.ReadString(l); Views.ReadView(rd, v); tv.SetItem(i, l, v) END; rd.ReadString(face); rd.ReadInt(size); rd.ReadSet(style); rd.ReadInt(weight); tv.font := Fonts.dir.This(face, size, style, weight); CallNotifier(tv, noTab, tv.index) END END Internalize; PROCEDURE (tv: View) CopyFromSimpleView- (source: Views.View); VAR l: Dialog.String; v: Views.View; i: INTEGER; BEGIN WITH source: View DO tv.notifier := source.notifier; tv.SetNofTabs(source.NofTabs()); FOR i := 0 TO tv.NofTabs() - 1 DO source.GetItem(i, l, v); v := Views.CopyOf(v, Views.deep); tv.SetItem(i, l, v) END; tv.font := Fonts.dir.This(source.font.typeface, source.font.size, source.font.style, source.font.weight); tv.SetIndex(source.Index()) END END CopyFromSimpleView; PROCEDURE (tv: View) GetNewFrame* (VAR frame: Views.Frame); VAR f: Frame; BEGIN f := frameDir.New(); f.font := tv.font; frame := f END GetNewFrame; PROCEDURE (tv: View) Restore* (f: Views.Frame; l, t, r, b: INTEGER); VAR v: Views.View; BEGIN WITH f: Frame DO IF (~f.InDispArea(l,t) OR ~f.InDispArea(r,b)) THEN (* redraw is not completely within the display area so the control itself also needs to be restored *) f.UpdateList(); f.Restore(l , t , r, b) END; f.GetDispSize(tv.dispX, tv.dispY, tv.dispW, tv.dispH); IF tv.NofTabs() > 0 THEN v := tv.View(tv.Index()); v.context.SetSize(tv.dispW, tv.dispH); Views.InstallFrame(f, v, tv.dispX, tv.dispY, 0, TRUE) END END END Restore; PROCEDURE (tv: View) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); VAR sp: Properties.SizeProp; BEGIN WITH f: Frame DO WITH msg: Controllers.TrackMsg DO IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN focus := tv.View(tv.Index()) ELSE f.MouseDown(msg.x, msg.y, msg.modifiers) END | msg: FocusMsg DO msg.view := tv | msg: Properties.PollPickMsg DO msg.dest := f; IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN focus := tv.View(tv.Index()) END | msg: Properties.PickMsg DO NEW(sp); sp.known := {Properties.width, Properties.height}; sp.valid := sp.known; tv.context.GetSize(sp.width, sp.height); Properties.Insert(msg.prop, sp); IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN focus := tv.View(tv.Index()) END |msg: Controllers.PollCursorMsg DO IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN focus := tv.View(tv.Index()) ELSE f.GetCursor(msg.x, msg.y, msg.modifiers, msg.cursor) END ELSE IF tv.NofTabs() > 0 THEN focus := tv.View(tv.Index()) ELSE WITH msg: Controllers.PollOpsMsg DO msg.valid := {Controllers.pasteChar} | msg: Controllers.MarkMsg DO f.Mark(msg.show, msg.focus) ELSE END END END END END HandleCtrlMsg; PROCEDURE BeginChanges* (tv: View); BEGIN ASSERT(tv.scriptLevel >= 0, 20); IF tv.tc = NIL THEN NEW(tv.tc); tv.tc.v := tv; Kernel.PushTrapCleaner(tv.tc) END; IF tv.ba = NIL THEN NEW(tv.ba); tv.ba.v := tv; Services.DoLater(tv.ba, Services.now) END; INC(tv.scriptLevel) END BeginChanges; PROCEDURE EndChanges* (tv: View); BEGIN ASSERT(tv.scriptLevel > 0, 20); DEC(tv.scriptLevel); IF tv.scriptLevel = 0 THEN tv.Reset END END EndChanges; (* TrapCleaner *) PROCEDURE (t: TrapCleaner) Cleanup; BEGIN t.v.Reset END Cleanup; (* Actions and Operations *) PROCEDURE (a: BalanceAction) Do-; BEGIN a.v.Reset(); HALT(100) (* Unbalanced call to BeginChanges/EndChanges *) END Do; PROCEDURE (o: SetNotifierOp) Do; VAR old: Dialog.String; BEGIN old := o.v.notifier; o.v.notifier := o.notifier; o.notifier := old END Do; PROCEDURE (o: FontOp) Do; VAR f: Fonts.Font; BEGIN f := o.v.font; o.v.font := o.font; o.font := f; o.v.Update END Do; PROCEDURE (o: SetItemOp) Do; VAR tc: TabContext; label: Dialog.String; view: Views.View; BEGIN IF o.set THEN o.set := FALSE; o.oldLen := o.tv.NofTabs(); view := Views.CopyOf(o.v, Views.deep); Stores.Join(o.tv, view); label := o.label; IF o.i >= o.oldLen THEN o.tv.SetNofTabs(o.i + 1) ELSE o.tv.GetItem(o.i, o.label, o.v) END; NEW(tc); view.InitContext(tc); o.tv.tabs[o.i].label := label; o.tv.tabs[o.i].view := view ELSE o.set := TRUE; IF o.i >= o.oldLen THEN o.tv.SetNofTabs(o.oldLen) ELSE view := o.v; label := o.label; o.tv.GetItem(o.i, o.label, o.v); o.tv.tabs[o.i].label := label; o.tv.tabs[o.i].view := view END END; o.tv.Update END Do; PROCEDURE (o: DeleteOp) Do; VAR j: INTEGER; BEGIN IF o.set THEN ASSERT(o.i < o.tv.NofTabs(), 20); o.set := FALSE; o.tv.GetItem(o.i, o.label, o.v); FOR j := o.i TO o.tv.NofTabs() - 2 DO o.tv.tabs[j].label := o.tv.tabs[j + 1].label; o.tv.tabs[j].view := o.tv.tabs[j + 1].view END; o.tv.SetNofTabs(o.tv.NofTabs() - 1) ELSE ASSERT(o.i <= o.tv.NofTabs(), 21); o.set := TRUE; o.tv.SetNofTabs(o.tv.NofTabs() + 1); FOR j := o.tv.NofTabs() - 1 TO o.i + 1 BY - 1 DO o.tv.tabs[j].label := o.tv.tabs[j - 1].label; o.tv.tabs[j].view := o.tv.tabs[j - 1].view END; o.tv.tabs[o.i].label := o.label; o.tv.tabs[o.i].view := o.v END; o.tv.Update END Do; PROCEDURE (tv: View) HandlePropMsg- (VAR msg: Properties.Message); VAR stp: Properties.StdProp; p: Properties.Property; face: Fonts.Typeface; size, weight, i, w, h, asc, dsc: INTEGER; style: SET; smsg: Properties.SizePref; fo: FontOp; BEGIN WITH msg: Properties.ControlPref DO IF tv.NofTabs() = 0 THEN IF msg.getFocus THEN msg.getFocus := StdCFrames.setFocus END ELSE msg.focus := tv.View(tv.Index()); Views.HandlePropMsg(msg.focus, msg) END | msg: Properties.FocusPref DO IF (tv.NofTabs() = 0) OR (msg.atLocation & (msg.y < tv.dispY)) THEN msg.hotFocus := TRUE ELSE IF msg.atLocation THEN msg.x := msg.x - tv.dispX; msg.y := msg.y - tv.dispY END; Views.HandlePropMsg(tv.View(tv.Index()), msg) END | msg: Properties.SizePref DO IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN IF tv.deposited OR (tv.NofTabs() = 0) THEN frameDir.GetTabSize(msg.w, msg.h) ELSE w := 0; h:= 0; FOR i := 0 TO tv.NofTabs() - 1 DO smsg.w := Views.undefined; smsg.h := Views.undefined; Views.HandlePropMsg(tv.View(i), smsg); w := MAX(smsg.w, w); h := MAX(smsg.h, h) END; IF (w = 0) OR (h = 0) THEN frameDir.GetTabSize(msg.w, msg.h) ELSE (* add some constants to compensate for the tab view itself. *) msg.w := w + 2 * Ports.mm; tv.font.GetBounds(asc, dsc, w); msg.h := h + asc + dsc + 4 * Ports.mm END END END | msg: Properties.ResizePref DO msg.horFitToWin := TRUE; msg.verFitToWin := TRUE | msg: Properties.PollMsg DO NEW(stp); stp.valid := {Properties.typeface..Properties.weight}; stp.known := stp.valid; stp.typeface := tv.font.typeface; stp.size := tv.font.size; stp.style.val := tv.font.style; stp.weight := tv.font.weight; stp.style.mask := {Fonts.italic, Fonts.strikeout, Fonts.underline}; Properties.Insert(msg.prop, stp) | msg: Properties.SetMsg DO p := msg.prop; WHILE (p # NIL) DO WITH p: Properties.StdProp DO IF (p.valid * {Properties.typeface..Properties.weight}) # {} THEN face := tv.font.typeface$; size := tv.font.size; style := tv.font.style; weight := tv.font.weight; IF Properties.typeface IN p.valid THEN face := p.typeface$; IF face = Fonts.default THEN face := StdCFrames.defaultFont.typeface END END; IF Properties.size IN p.valid THEN size := p.size END; IF Properties.style IN p.valid THEN style := (p.style.val * p.style.mask) + (style - p.style.mask) END; IF Properties.weight IN p.valid THEN weight := p.weight END; NEW(fo); fo.v := tv; fo.font := Fonts.dir.This(face, size, style, weight); Views.Do(tv, "#System:SetProp", fo) END ELSE END; p := p.next END | msg: Containers.DropPref DO msg.okToDrop := TRUE ELSE IF tv.NofTabs() > 0 THEN Views.HandlePropMsg(tv.View(tv.Index()), msg) END END END HandlePropMsg; PROCEDURE (tv: View) Neutralize*; BEGIN IF tv.NofTabs() > 0 THEN tv.View(tv.Index()).Neutralize END END Neutralize; (* Tab context *) PROCEDURE (c: TabContext) ThisModel (): Models.Model; BEGIN RETURN NIL END ThisModel; PROCEDURE (c: TabContext) GetSize (OUT w, h: INTEGER); BEGIN w := c.w; h := c.h END GetSize; PROCEDURE (c: TabContext) SetSize (w, h: INTEGER); BEGIN c.w := w; c.h := h END SetSize; PROCEDURE (c: TabContext) Normalize (): BOOLEAN; BEGIN RETURN FALSE END Normalize; (* Directory *) PROCEDURE (d: Directory) New* (): View, NEW, ABSTRACT; PROCEDURE SetDir* (d: Directory); BEGIN ASSERT(d # NIL, 20); dir := d END SetDir; (* StdDirectory *) PROCEDURE (d: StdDirectory) New (): View; VAR tv: View; BEGIN ASSERT(frameStdDir # NIL, 20); NEW(tv); tv.deposited := FALSE; tv.scriptLevel := 0; tv.nofTabs := 0; tv.index :=0; tv.notifier := ""; tv.ba := NIL; tv.tc := NIL; tv.font := StdCFrames.defaultFont; RETURN tv END New; PROCEDURE Deposit*; VAR tv: View; fv: FormViews.View; BEGIN tv := dir.New(); tv.deposited := TRUE; fv := FormViews.New(); LayoutMode(fv); tv.SetItem(0, "Tab1", fv); fv := FormViews.New(); LayoutMode(fv); tv.SetItem(1, "Tab2", fv); Views.Deposit(tv) END Deposit; (* Procedures to find tab views *) PROCEDURE This* (v: Views.View): View; VAR c: Containers.Controller; v0: Views.View; v1: View; BEGIN ASSERT (v # NIL, 20); IF v IS View THEN RETURN v(View) ELSIF v IS Containers.View THEN c := v(Containers.View).ThisController(); ASSERT(c # NIL, 100); c.GetFirstView(Containers.any, v0); IF v0 # NIL THEN v1 := This(v0) END; WHILE (v0 # NIL) & (v1 = NIL) DO c.GetNextView(Containers.any, v0); IF v0 # NIL THEN v1 := This(v0) END END; RETURN v1 ELSE RETURN NIL END END This; PROCEDURE Focus* (): View; VAR msg: FocusMsg; BEGIN msg.view := NIL; Controllers.Forward(msg); RETURN msg.view END Focus; (* The property editor *) PROCEDURE SingleView() : View; VAR v: Views.View; BEGIN v := Containers.FocusSingleton(); IF v = NIL THEN v := Focus() END; IF (v # NIL) & (v IS View) THEN RETURN v(View) ELSE RETURN NIL END END SingleView; PROCEDURE Right*; VAR label1, label2: Dialog.String; v1, v2: Views.View; iv: View; script: Stores.Operation; BEGIN iv := SingleView(); IF (iv # NIL) & (iv.Index() < (iv.NofTabs() - 1)) THEN Views.BeginScript(iv, "Shift tab right", script); iv.GetItem(iv.Index() , label1, v1); iv.GetItem(iv.Index() + 1 , label2, v2); iv.SetItem(iv.Index(), label2, v2); iv.SetItem(iv.Index() + 1, label1, v1); Views.EndScript(iv, script); iv.SetIndex(iv.Index() + 1); Dialog.Update(iv) END END Right; PROCEDURE Left*; VAR label1, label2: Dialog.String; v1, v2: Views.View; iv: View; BEGIN iv := SingleView(); IF (iv # NIL) & (iv.Index() > 0) THEN iv.GetItem(iv.Index() , label1, v1); iv.GetItem(iv.Index() - 1 , label2, v2); iv.SetItem(iv.Index(), label2, v2); iv.SetItem(iv.Index() - 1, label1, v1); iv.SetIndex(iv.Index() - 1); Dialog.Update(iv) END END Left; PROCEDURE AddTab*; VAR v: View; fv: FormViews.View; BEGIN ASSERT(dlg.name # "", 20); v := SingleView(); IF v # NIL THEN fv := FormViews.New(); LayoutMode(fv); v.SetItem(v.NofTabs(), dlg.name, fv) END END AddTab; PROCEDURE Rename*; VAR v: View; BEGIN ASSERT(dlg.name # "", 20); v := SingleView(); IF (v # NIL) & (v.NofTabs() > 0) THEN v.SetItem(v.Index(), dlg.name, v.View(v.Index())) END END Rename; PROCEDURE Delete*; VAR v: View; dop: DeleteOp; BEGIN v := SingleView(); IF (v # NIL) & (v.NofTabs() > 0) THEN NEW(dop); dop.tv := v; dop.i := v.Index(); dop.set := TRUE; Views.Do(v, "#Std:TabDeleteItem", dop) END END Delete; PROCEDURE ModeNotifier* (op, from, to: INTEGER); VAR tv: View; i: INTEGER; BEGIN IF op IN {Dialog.changed} THEN tv := SingleView(); IF (tv # NIL) & (tv.NofTabs() > 0) THEN IF to = 0 THEN FOR i := 0 TO tv.NofTabs() - 1 DO LayoutMode(tv.View(i)) END ELSE FOR i := 0 TO tv.NofTabs() - 1 DO MaskMode(tv.View(i)) END END END END END ModeNotifier; PROCEDURE SetNotifier*; VAR v: View; o: SetNotifierOp; BEGIN v := SingleView(); IF v # NIL THEN NEW(o); o.v := v; o.notifier := dlg.notifier; Views.Do(v, "Set Notifier", o) END END SetNotifier; PROCEDURE NewGuard* (VAR par: Dialog.Par); VAR v: View; BEGIN v := SingleView(); par.disabled := (v = NIL) OR (dlg.name = "") END NewGuard; PROCEDURE RenameGuard* (VAR par: Dialog.Par); VAR v: View; BEGIN v := SingleView(); par.disabled := (v = NIL) OR (dlg.name = "") END RenameGuard; PROCEDURE DeleteGuard* (VAR par: Dialog.Par); VAR v: View; BEGIN v := SingleView(); par.disabled := (v = NIL) OR (v.NofTabs() < 1) END DeleteGuard; PROCEDURE LabelGuard* (VAR par: Dialog.Par); VAR v: View; vv: Views.View; BEGIN v := SingleView(); IF v # NIL THEN IF (v # dlg.tab) OR (v.Index() # dlg.index) THEN par.disabled := FALSE; v.GetItem(v.Index(), dlg.name, vv); dlg.tab := v; dlg.index := v.Index(); Dialog.Update(dlg) END ELSE dlg.tab := NIL; dlg.index := -1; par.label := ""; par.disabled := TRUE END END LabelGuard; PROCEDURE NotifierGuard* (VAR par: Dialog.Par); VAR v: View; BEGIN v := SingleView(); IF v # NIL THEN IF v # dlg.ntab THEN par.disabled := FALSE; dlg.notifier := v.notifier; dlg.ntab := v; Dialog.Update(dlg) END ELSE dlg.ntab := NIL; par.label := ""; par.disabled := TRUE END END NotifierGuard; PROCEDURE SetGuard* (VAR par: Dialog.Par); VAR v: View; BEGIN v := SingleView(); par.disabled := v = NIL END SetGuard; PROCEDURE ModeGuard (VAR par: Dialog.Par; layout: BOOLEAN); CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret}; VAR tv: View; i, l, m: INTEGER; c: Containers.Controller; BEGIN tv := SingleView(); IF (tv # NIL) & (tv.NofTabs() > 0) THEN l := 0; m := 0; FOR i := 0 TO tv.NofTabs() - 1 DO IF tv.View(i) IS Containers.View THEN c := tv.View(i)(Containers.View).ThisController(); IF c.opts * mode = {Containers.noFocus} THEN INC(l) ELSIF c.opts * mode = {Containers.noSelection, Containers.noCaret} THEN INC(m) END END END; IF ((m # 0) & (l # 0)) OR ((m + l) < tv.NofTabs()) THEN par.undef := TRUE; dlg.opt := -1 ELSIF layout & (m = 0) THEN dlg.opt := 0 ELSIF ~layout & (l = 0) THEN dlg.opt := 1 END ELSE par.disabled := TRUE END END ModeGuard; PROCEDURE LayoutModeGuard*(VAR par: Dialog.Par); BEGIN ModeGuard(par, TRUE) END LayoutModeGuard; PROCEDURE MaskModeGuard*(VAR par: Dialog.Par); BEGIN ModeGuard(par, FALSE) END MaskModeGuard; PROCEDURE InitDialog*; BEGIN dlg.tab := NIL; dlg.index := -1 END InitDialog; PROCEDURE Init; VAR res: INTEGER; BEGIN setFocus := FALSE; dlg.tab := NIL; dlg.index := -1; NEW(d); stdDir := d; dir := d; Dialog.Call('HostTabFrames.Init', 'Could not load HostTabFrames', res) END Init; BEGIN Init END StdTabViews.
Std/Mod/TabViews.odc
MODULE StdViewSizer; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT Services, Ports, Dialog, Views, Containers, Properties; CONST width = 1; height = 2; VAR size*: RECORD typeName-: Dialog.String; w*, h*: REAL; proportional*, fixedW, fixedH: BOOLEAN; unit, scaleW, scaleH, lastChanged: INTEGER; unitText: ARRAY 6 OF CHAR; view: Views.View; container: Containers.Controller END; PROCEDURE ConnectDialog (v: Views.View; c: Containers.Controller); VAR pref: Properties.ResizePref; BEGIN IF (v # NIL) & (v.context # NIL) THEN IF Dialog.metricSystem THEN size.unit := Ports.mm * 10; size.unitText := "cm" ELSE size.unit := Ports.inch; size.unitText := "inch" END; size.view := v; size.container := c; Services.GetTypeName(v, size.typeName); v.context.GetSize(size.scaleW, size.scaleH); size.w := size.scaleW / size.unit; size.h := size.scaleH / size.unit; pref.fixed := FALSE; pref.horFitToPage := FALSE; pref.verFitToPage := FALSE; pref.horFitToWin := FALSE; pref.verFitToWin := FALSE; Views.HandlePropMsg(v, pref); size.fixedW := pref.fixed; size.fixedH := pref.fixed; size.proportional := FALSE ELSE size.view := NIL; size.container := c; size.typeName := "" END; Dialog.Update(size) END ConnectDialog; PROCEDURE SetViewSize*; BEGIN IF size.view # NIL THEN size.view.context.SetSize(SHORT(ENTIER(size.w * size.unit + 0.5)), SHORT(ENTIER(size.h * size.unit + 0.5))); IF size.container # NIL THEN size.container.SetSingleton(size.view) END; ConnectDialog(size.view, size.container) ELSE Dialog.Beep END END SetViewSize; PROCEDURE InitDialog*; VAR v: Views.View; c: Containers.Controller; BEGIN c := Containers.Focus(); IF c # NIL THEN v := c.Singleton() ELSE v := NIL END; IF (v # size.view) OR (c # size.container) THEN ConnectDialog(v, c) END END InitDialog; PROCEDURE ResetDialog*; VAR proportional: BOOLEAN; v: Views.View; BEGIN proportional := size.proportional; v := size.view; size.view := NIL; InitDialog; IF proportional & (v = size.view) THEN size.proportional := TRUE; Dialog.Update(size) END END ResetDialog; PROCEDURE WidthGuard* (VAR par: Dialog.Par); BEGIN InitDialog; par.disabled := size.view = NIL; par.readOnly := size.fixedW END WidthGuard; PROCEDURE HeightGuard* (VAR par: Dialog.Par); BEGIN InitDialog; par.disabled := size.view = NIL; par.readOnly := size.fixedH END HeightGuard; PROCEDURE ProportionGuard* (VAR par: Dialog.Par); BEGIN par.disabled := (size.view = NIL) OR size.fixedW OR size.fixedH OR (size.scaleW = 0) OR (size.scaleH = 0) END ProportionGuard; PROCEDURE UnitGuard* (VAR par: Dialog.Par); BEGIN IF size.view # NIL THEN par.label := size.unitText$ ELSE par.label := "" END END UnitGuard; PROCEDURE AdjustDialogToPref (fixedW, fixedH: BOOLEAN); VAR w, h: INTEGER; w0, h0: REAL; pref: Properties.SizePref; BEGIN w := SHORT(ENTIER(size.w * size.unit + 0.5)); h := SHORT(ENTIER(size.h * size.unit + 0.5)); IF size.proportional & (w > 0) & (h > 0) & (size.scaleW > 0) & (size.scaleH > 0) THEN Properties.ProportionalConstraint(size.scaleW, size.scaleH, fixedW, fixedH, w, h) END; pref.w := w; pref.h := h; pref.fixedW := fixedW; pref.fixedH := fixedH; Views.HandlePropMsg(size.view, pref); IF ~fixedW THEN w0 := pref.w / size.unit ELSE w0 := size.w END; IF ~fixedH THEN h0 := pref.h / size.unit ELSE h0 := size.h END; IF (w0 # size.w) OR (h0 # size.h) THEN size.w := w0; size.h := h0; Dialog.Update(size) END END AdjustDialogToPref; PROCEDURE WNotifier* (op, from, to: INTEGER); BEGIN IF size.w > 0 THEN AdjustDialogToPref(TRUE, FALSE); size.lastChanged := width ELSIF size.w # 0 THEN Dialog.Beep END END WNotifier; PROCEDURE HNotifier* (op, from, to: INTEGER); BEGIN IF size.h > 0 THEN AdjustDialogToPref(FALSE, TRUE); size.lastChanged := height ELSIF size.h # 0 THEN Dialog.Beep END END HNotifier; PROCEDURE ProportionNotifier* (op, from, to: INTEGER); BEGIN IF (op = Dialog.changed) & size.proportional THEN IF size.lastChanged = width THEN AdjustDialogToPref(TRUE, FALSE) ELSIF size.lastChanged = height THEN AdjustDialogToPref(FALSE, TRUE) END END END ProportionNotifier; END StdViewSizer.
Std/Mod/ViewSizer.odc
Std/Rsrc/Cmds.odc
Std/Rsrc/Cmds1.odc
Std/Rsrc/Coder.odc
Std/Rsrc/Folds.odc
Std/Rsrc/Headers.odc
Std/Rsrc/Links.odc
Std/Rsrc/Scroller.odc
Std/Rsrc/Stamps.odc
STRINGS OK, Apply, Close, Cancel see System/Rsrc/Strings (Std)ViewSizer (Std)ViewSizer &Width: Ширина: &Height: Высота: &Keep proportions Сохранить пропорции &Reset Сброс (Std)Links (Std)Links Type: Тип: Link: Связано с: Close: Закрывать: (Std)Scroller (Std)Scroller Horizontal Scrollbar Horizontal Scrollbar Vertical Scrollbar Vertical Scrollbar View Width View Width View Height View Height Never Никогда Automatic Автоматически Always Всегда Fix: Fix: Adapted Adapted Show 3d border Show 3d border Save position Save position (Std)Tables (Std)Tables Selection Style: Selection Style: Layout Editable Layout Editable Data Editable Data Editable (Std)TabViews (Std)TabViews Move Передвинуть Tabs Закладки &New Tab Новая &Rename Переименовать &Delete Удалить Label: Ярлык: Notifier Notifier Set Установить All tabs in Layout Mode Все закладки в режиме разметки All tabs in Mask Mode Все закладки в режиме маски <- -> (Std)Cmds (Std)Cmds &Size: Кегль: &Size Кегль (Std)Cmds1 (Std)Cmds1 Width Ширина Height Высота Fixed Фиксированная Page Width В ширину страницы Window Width В ширину окна Page Height В высоту страницы Window Height В высоту окна (Std)Coder (Std)Coder Decode &All Раскодировать всё &Browse Открыть диалог &Decode Раскодировать &F &F &Use Name: Использовать имя: &U &U (Std)Folds (Std)Folds Find: Найти: All Все Find First Найти первую Find Next Найти следующую Collapse Свернуть Expand Развернуть Nested Вложенные Set Label: Задать ярлык: (Std)Stamps (Std)Stamps Comment Комментарий к текущей версии документа: (Std)Headers (Std)Headers Headers Колонтитулы alternate чередовать Start with new page number Продолжать нумерацию с Right Head Правый верхний Right Foot Правый нижний Left Head Левый верхний Left Foot Левый нижний &Font... Шрифт... Head gap Отбивка верхнего Foot gap Отбивка нижнего Show Foot показать нижний bad characters плохие символы в коде! checksum error ошибка контрольной суммы! incompatible version Код был создан несовместимой версией Кодировщика! filing error Не удалось сохранить файл! directory ^0 not found Папка ^0 не существует! file ^0 not found Файл ^0 не существует! illegal path '^0' не является правильным именем пути! no tag Не найден тэг кодировщика! ^0 characters coded Документ закодирован в ^0 литер. Install all? Инсталлировать все закодированные файлы? Старые версии могут быть утеряны! Install individual? Инсталлировать некоторые из закодированных файлов индивидуально? Info Info StdETHConv.ImportETHDoc ETH V4 Oberon StdClocks.StdViewDesc StdClocks view StdLogos.ViewDesc StdLogos view StdStamps.StdViewDesc StdStamps view HeaderChange Header Change links[0] всегда links[1] если нажата клавиша Shift links[2] никогда Scrollers.Prop StdScrollers.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Scroller', 'Scroller') Headers.Prop StdHeaders.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Headers', 'Headers') Folds.Prop StdCmds.OpenToolDialog('Std/Rsrc/Folds','Zoom') Links.Prop StdLinks.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Links', 'Links & Targets') TabViews.View StdTabViews.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/TabViews','Tab View Inspector') TabSetItem Set Item TabDeleteItem Delete Item Tables.Prop StdTables.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Tables', 'Tables') Location Местонахождение Count Count NoMatchFound Не найдено Searching Поиск
Std/Rsrc/Strings.odc
Std/Rsrc/Tables.odc
Std/Rsrc/TabViews.odc
Std/Rsrc/ViewSizer.odc
ADVAPI32 This module is obsolete; use the Win subsystem instead.
System/Docu/ADVAPI32.odc
COMDLG32 This module is obsolete; use the Win subsystem instead.
System/Docu/COMDLG32.odc
Config DEFINITION Config; PROCEDURE Setup; END Config. BlackBox attempts to call the command Config.Setup during start-up. The call allows to customize the configuration of BlackBox. Module Config is provided in source form and can be changed by the programmer arbitrarily. The default implementation looks like this: MODULE Config; IMPORT Dialog; PROCEDURE Setup*; VAR res: INTEGER; BEGIN (* ... various file and clipboard converters are installed here ... *) Dialog.Call("StdLog.Open", "", res) END Setup; END Config. This configuration causes the log window to be opened upon startup. The command is called after the complete BlackBox library, framework, and standard subsystems are loaded. Config may import any BlackBox module. If it isn't needed, module Config can be deleted. CurrentConfiguration PROCEDURE Setup This procedure can be implemented in order to customize the initial BlackBox configuration after start-up. It is called after all standard services and menus have been installed. Implementing Setup is optional. Example for the implementation of Config.Setup: PROCEDURE Setup*; VAR res: INTEGER; BEGIN Dialog.Call("StdCmds.OpenAuxDialog('System/Rsrc/About', 'Splash Screen')", "", res) END Setup; If Config.Setup need not be implemented, the module (in particular its code file) may be deleted entirely. Note that similar to Config, there may (but need not) be a module Startup with a command Setup. It has a similar purpose as Config, but is called before the higher levels (text subsystem, form subsystem, etc.) are loaded. Consequently, Startup may not import the higher levels of BlackBox. Normally, Startup does not exist. It is only used under special circumstances, e.g., to overwrite the variable Dialog.appName.
System/Docu/Config.odc
Containers DEFINITION Containers; IMPORT Controllers, Stores, Views, Models, Properties; CONST noSelection = 0; noFocus = 1; noCaret = 2; mask = {noSelection, noCaret}; layout = {noFocus}; deselect = FALSE; select = TRUE; any = FALSE; selection = TRUE; hide = FALSE; show = TRUE; TYPE Model = POINTER TO ABSTRACT RECORD (Models.Model) (m: Model) GetEmbeddingLimits (OUT minW, maxW, minH, maxH: INTEGER), NEW, ABSTRACT; (m: Model) ReplaceView (old, new: Views.View), NEW, ABSTRACT; (m: Model) InitFrom- (source: Model), NEW, EMPTY END; View = POINTER TO ABSTRACT RECORD (Views.View) (v: View) CopyFromModelView2- (source: Views.View; model: Models.Model), NEW, EMPTY; (v: View) Externalize2- (VAR rd: Stores.Writer), NEW, EMPTY; (v: View) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View), NEW, EMPTY; (v: View) HandleModelMsg2- (VAR msg: Models.Message), NEW, EMPTY; (v: View) HandlePropMsg2- (VAR p: Views.PropMessage), NEW, EMPTY; (v: View) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY; (v: View) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY; (v: View) InitModel (m: Model), NEW; (v: View) InitModel2- (m: Model), NEW, EMPTY; (v: View) AcceptableModel- (m: Model): BOOLEAN, NEW, ABSTRACT; (v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER), NEW, ABSTRACT; (v: View) ThisModel (): Model, EXTENSIBLE; (v: View) SetController (c: Controller), NEW; (v: View) ThisController (): Controller, NEW, EXTENSIBLE; (v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER), NEW, ABSTRACT; (v: View) CatchModelMsg (VAR msg: Models.Message), NEW, EMPTY; (v: View) CatchViewMsg (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY; (v: View) CatchCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View), NEW, EMPTY; (v: View) CatchPropMsg (VAR msg: Views.PropMessage), NEW, EMPTY END; Controller = POINTER TO ABSTRACT RECORD (Controllers.Controller) opts-: SET; (c: Controller) ThisView (): View, EXTENSIBLE; (c: Controller) SetOpts (opts: SET), NEW, EXTENSIBLE; (c: Controller) GetContextType (OUT type: Stores.TypeName), NEW, ABSTRACT; (c: Controller) GetValidOps (OUT valid: SET), NEW, ABSTRACT; (c: Controller) NativeModel (m: Models.Model): BOOLEAN, NEW, ABSTRACT; (c: Controller) NativeView (v: Views.View): BOOLEAN, NEW, ABSTRACT; (c: Controller) NativeCursorAt (f: Views.Frame; x, y: INTEGER): INTEGER, NEW, ABSTRACT; (c: Controller) PickNativeProp (f: Views.Frame; x, y: INTEGER; VAR p: Properties.Property), NEW, EMPTY; (c: Controller) PollNativeProp (selection: BOOLEAN; VAR p: Properties.Property; VAR truncated: BOOLEAN), NEW, EMPTY; (c: Controller) SetNativeProp (selection: BOOLEAN; old, p: Properties.Property), NEW, EMPTY; (c: Controller) MakeViewVisible (v: Views.View), NEW, EMPTY; (c: Controller) GetFirstView (selection: BOOLEAN; OUT v: Views.View), NEW, ABSTRACT; (c: Controller) GetNextView (selection: BOOLEAN; VAR v: Views.View), NEW, ABSTRACT; (c: Controller) GetPrevView (selection: BOOLEAN; VAR v: Views.View), NEW, EXTENSIBLE; (c: Controller) CanDrop (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, EXTENSIBLE; (c: Controller) MarkDropTarget (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; type: Stores.TypeName; isSingle, show: BOOLEAN), NEW, EMPTY; (c: Controller) Drop (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; view: Views.View; isSingle: BOOLEAN), NEW, ABSTRACT; (c: Controller) MarkPickTarget (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER; show: BOOLEAN), NEW, EMPTY; (c: Controller) TrackMarks (f: Views.Frame; x, y: INTEGER; units, extend, add: BOOLEAN), NEW, ABSTRACT; (c: Controller) Resize (view: Views.View; l, t, r, b: INTEGER), NEW, ABSTRACT; (c: Controller) GetSelectionBounds (f: Views.Frame; OUT x, y, w, h: INTEGER), NEW, EXTENSIBLE; (c: Controller) DeleteSelection, NEW, ABSTRACT; (c: Controller) MoveLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER), NEW, ABSTRACT; (c: Controller) CopyLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER), NEW, ABSTRACT; (c: Controller) SelectionCopy (): Model, NEW, ABSTRACT; (c: Controller) NativePaste (m: Models.Model; f: Views.Frame), NEW, ABSTRACT; (c: Controller) ArrowChar (f: Views.Frame; ch: CHAR; units, select: BOOLEAN), NEW, ABSTRACT; (c: Controller) ControlChar (f: Views.Frame; ch: CHAR), NEW, ABSTRACT; (c: Controller) PasteChar (ch: CHAR), NEW, ABSTRACT; (c: Controller) PasteView (f: Views.Frame; v: Views.View; w, h: INTEGER), NEW, ABSTRACT; (c: Controller) HasSelection (): BOOLEAN, NEW, EXTENSIBLE; (c: Controller) Selectable (): BOOLEAN, NEW, ABSTRACT; (c: Controller) Singleton (): Views.View, NEW; (c: Controller) SetSingleton (s: Views.View), NEW, EXTENSIBLE; (c: Controller) SelectAll (select: BOOLEAN), NEW, ABSTRACT; (c: Controller) InSelection (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, ABSTRACT; (c: Controller) MarkSelection (f: Views.Frame; show: BOOLEAN), NEW, EXTENSIBLE; (c: Controller) SetFocus (focus: Views.View), NEW; (c: Controller) HasCaret (): BOOLEAN, NEW, ABSTRACT; (c: Controller) MarkCaret (f: Views.Frame; show: BOOLEAN), NEW, ABSTRACT; (c: Controller) Mark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN), NEW, EXTENSIBLE END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) New (): Controller, NEW, EXTENSIBLE; (d: Directory) NewController (opts: SET): Controller, NEW, ABSTRACT END; DropPref = RECORD (Properties.Preference) mode-: SET; okToDrop: BOOLEAN END; GetOpts = RECORD (Views.PropMessage) valid, opts: SET END; SetOpts = RECORD (Views.PropMessage) valid, opts: SET END; PROCEDURE Focus (): Controller; PROCEDURE FocusSingleton (): Views.View; PROCEDURE MarkSingleton (c: Controller; f: Views.Frame; show: BOOLEAN); PROCEDURE FadeMarks (c: Controller; show: BOOLEAN); END Containers. Containers are views which may contain other (embedded) views. Typically, containers belong to one of two categories. The first category contains containers with a fixed structure and fixed types of the embedded views. For example, an e-mail container view may consist of exactly two views: a toolbar view at the top, and a text view below. The layout of these views typically cannot be edited. Such views are called static containers. The second category of containers can embed arbitrary numbers of views, which can be of arbitrary types. Text views and form views are typical examples of such dynamic container views. Only this second category of container views, called dynamic containers, is supported by module Containers, and it is the topic of this text. Dynamic containers consist of a variable number of embedded views, plus some intrinsic contents. Text views for example have text as their intrinsic contents, but also allow to let arbitrary views (i.e., non-intrinsic contents) flow along in the text. Form views are degenerated in the sense that they provide no intrinsic contents of their own. Different compound document standards (OLE, OpenDoc) differ in the way they treat selections and the focus. The focus is the currently edited view, the view which receives keyboard events, the view which determines the currently available menus, the view which contains the currently relevant selection, caret, or other mark. Containers provides the building blocks for container views, including special container models and container controllers. Other than most BlackBox modules, Containers exports several partially implemented types, rather than pure interface types. What is implemented is provided in a form suitable for the used platform, i.e. user interface differences are hidden by the implementation of Containers. In particular, Containers fully implements singleton selections, i.e., selections which cover exactly one view and no intrinsic contents. Such selections are subject to special operations and require platform-dependent treatment. Also, Containers implements the focus concept: a single embedded view within a controller's model that is picked by the user as current focus. Example: Formsubsystemmap CONST noSelection, noFocus, noCaret Possible elements of Controller.opt. noSelection denotes that selections should be switched off, noFocus denotes that no embedded view should be allowed to become focus, and noCaret denotes that the caret (insertion mark) and thus the possibility to type or paste should be switched off. CONST mask, layout Two particularly useful subsets of Controller.opt. A mask prevents editing of the container's intrinsic contents, but enables focusing and thereby editing of the contained objects; for example, this allows to use a form without changing the form itself. A layout does just the opposite: focusing and therefore editing of contained objects is inhibited, but the container's intrinsic contents may be freely edited; for example, this is useful when editing a form without wanting to actually activate, say, a button, while editing its position in the form. CONST deselect, select Possible values of the select parameter of Controller.SelectAll. CONST any, selection Possible values of the selection parameters of Controller.GetFirstView, Controller.GetNextView, Controller.GetPrevView, Controller.PollNativeProp, and Controller.SetNativeProp. Controls whether the range of the operation is the current selection or the whole container contents. CONST hide, show Possible values of the show parameter of FadeMarks, MarkSingleton, Controller.Mark, Controller.MarkCaret, Controller.MarkDropTarget, Controller.MarkPickTarget, and Controller.MarkSelections. Controls whether the respective mark is to be hidden or shown. TYPE Model (Models.Model) ABSTRACT Models for containers. PROCEDURE (m: Model) GetEmbeddingLimits (OUT minW, maxW, minH, maxH: INTEGER) NEW, ABSTRACT Return minimum (minW, minH) and maximum (maxW, maxH) bounds on view sizes to be embedded in model m. If it is tried to embed a view into m with width < minW, width >= maxW, height < minH, or height >= maxH, then m should (but is not absolutely required to) modify the size of the embedded view in order to make it fit. Post 0 <= minW <= maxW 0 <= minH <= maxH PROCEDURE (m: Model) ReplaceView (old, new: Views.View) NEW, ABSTRACT In-place substitution of view old which must be embedded in m by view new which must not yet be embedded anywhere. As a result, new gets embedded in m, but old retains its context which it then shares with new. Replacing a view inђplace allows wrapping of views: A new view takes place of an existing one, adds some new properties, but still can hold a reference to the old view and delegate requests to the old view. Since the old view has maintained its context, it will continue to function as if it where directly embedded in m. Pre old # NIL old.context.ThisModel() = m EmbeddedIn(old, m) new # NIL new.context = NIL Post NotEmbedded(old) new.context.ThisModel() = m new.context = old.context PROCEDURE (m: Model) InitFrom- (source: Model) NEW, EMPTY Initialize model m, which has been newly allocated as an object of the same type as source. In some (rare) cases, it may be useful to share some internal data structures between m and source. Pre source # NIL Type(m) = Type(source) TYPE View (Views.View) ABSTRACT Views for containers. PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader) Clarification of inherited procedure Fully implements internalization for views without intrinsic persistent state by handling internalization of the container view's model and controller. If the model internalization fails, the view is turned into an alien and internalization of v is cancelled; otherwise the model is attached to v. If the controller internalization fails, the controller is kept for later externalization to prevent loss of information, but is otherwise not connected to the view (v.ThisController() = NIL), and the view is internalized normally (i.e., not turned into an alien). Super call at the beginning is mandatory PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer) Clarification of inherited procedure Fully implements externalization for views without intrinsic persistent state by handling externalization of the container view's model and controller. If v has been internalized before with an alien controller, and no other controller has been installed thereafter, then the alien controller will be externalized, although v.ThisController() = NIL. Super call at the beginning is mandatory Pre v.ThisModel() # NIL 20 PROCEDURE (v: View) CopyFrom (source: Stores.Store) Clarification of inherited procedure Assuming that the model of v has already been established, copy the controller and possibly other view state from source. If source holds a hidden alien controller (cf. Internalize above), a reference to it is also copied. Super call at the beginning is mandatory Pre v.ThisModel() # NIL 20 Post source.ThisController() = NIL v.ThisController() = NIL source.ThisController() # NIL v.ThisController() = source.ThisController().Clone().CopyFrom(source.ThisController()) PROCEDURE (v: View) ThisModel (): Model EXTENSIBLE Return the model of v. Covariant narrowing of function result. PROCEDURE (v: View) InitModel (m: Containers.Model) NEW Assign a model to this view. Pre (v.ThisModel() = NIL) OR (v.ThisModel() = m) 20 m # NIL 21 v.AcceptableModel(m) 22 PROCEDURE (v: View) InitModel2- (m: Containers.Model) NEW, EMPTY Extension hook called by InitModel. PROCEDURE (v: View) SetController (c: Controller) NEW, EXTENSIBLE, Operation Set the controller of v. If v holds a hidden alien controller, it is removed. Pre v.ThisModel() # NIL 20 Post v.ThisController() = c PROCEDURE (v: View) ThisController (): Controller NEW, EXTENSIBLE Return the controller of v. PROCEDURE (v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER) NEW, ABSTRACT For display in frame f, determine the bounding box of view which must be a view contained in v. Should the computation of the bounding box be too expensive, returning an approximation is acceptable. Post l <= r t<= b PROCEDURE (v: View) CatchModelMsg (VAR msg: Models.Message) NEW, EMPTY Extension hook for HandleModelMsg which has become final. PROCEDURE (v: View) CatchViewMsg (f: Views.Frame; VAR msg: Views.Message) NEW, EMPTY Extension hook for HandleViewMsg which has become final. PROCEDURE (v: View) CatchCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View) NEW, EMPTY Extension hook for HandleCtrlMsg which has become final. PROCEDURE (v: View) CatchPropMsg (VAR p: Properties.Message) NEW, EMPTY Extension hook for HandlePropMsg which has become final. PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View) Clarification of inherited procedure If v has a controller installed, calls v.ThisController().HandleCtrlMsg(f, msg, focus), then calls v.CatchCtrlMsg(f, msg, focus). That is, the controller sees the controller message msg before the view does. Additionally, a strict filter is applied to throw away unwanted messages: messages are only delegated to the controller or view if they fulfill one of the following three criteria: First, the frame f is a target or front frame. Second, the message is derived from Controllers.PollOpsMsg, Controllers.PollCursorMsg, Controllers.TransferMessage, or Controllers.PageMsg. Third, the context of v is normalizing, i.e., v.context.Normalize() holds, and the message is derived from Controllers.PollSectionMsg or Controllers.ScrollMsg. This is a standard message filtering condition making components more robust against spurious message sends. Finally, scrolling messages (derived from Controllers.PollSectionMsg or Controllers.ScrollMsg) may ask for shallow handling (~msg.focus), i.e., supression of forwarding to a possibly existing subfocus. This is generically handled by clearing focus on return in these cases. Post (msg IS Controllers.PollSectionMsg) OR (msg IS Controllers.ScrollMsg) ~msg.focus focus = NIL TYPE Controller (Controllers.Controller) ABSTRACT Controllers for containers. opts-: SET Option set of controller; used to restrict controller functionality to defined subsets. PROCEDURE (c: Controller) ThisView (): View EXTENSIBLE Return type is narrowed. PROCEDURE (c: Controller) SetOpts (opts: SET) NEW, EXTENSIBLE, Operation Set the options of c. This is only an operation after a view has been installed, i.e., c.ThisView() # NIL, otherwise it is a simple assignment of opts to c.opts. Options 0..7 are used or reserved by BlackBox, the rest may be used by extensions. Post c.opts = opts PROCEDURE (c: Controller) GetContextType (OUT type: Stores.TypeName) NEW, ABSTRACT Called by c.HandleCtrlMsg to fill in Controllers.PollOpsMsg.type. PROCEDURE (c: Controller) GetValidOps (OUT valid: SET) NEW, ABSTRACT Called by c.HandleCtrlMsg to fill in Controllers.PollOpsMsg.ops. PROCEDURE (c: Controller) NativeModel (m: Models.Model): BOOLEAN NEW, ABSTRACT Check whether m is a native model of c, i.e., a model that could be attached to a view attachable to c. PROCEDURE (c: Controller) NativeView (v: Views.View): BOOLEAN NEW, ABSTRACT Check whether v is a native view of c, i.e., a view that could be attached to c. PROCEDURE (c: Controller) NativeCursorAt (f: Views.Frame; x, y: INTEGER): INTEGER NEW, ABSTRACT The cursor that c would display in f at point (x, y), irrespective of possible embedded views at that position. PROCEDURE (c: Controller) PickNativeProp (f: Views.Frame; x, y: INTEGER; VAR p: Properties.Property) NEW, EMPTY The properties of c's native contents in f at point (x, y), irrespective of possible embedded views at that position. PROCEDURE (c: Controller) PollNativeProp (selection: BOOLEAN; VAR p: Properties.Property; VAR truncated: BOOLEAN); NEW, EMPTY The properties of c's native selected or whole contents, irrespective of possible embedded views in that range. PROCEDURE (c: Controller) SetNativeProp (selection: BOOLEAN; old, p: Properties.Property) NEW, EMPTY Set the properties of c's native selected or whole contents to p, irrespective of possible embedded views in that range. For properties also in old change only those property values of c that match the ones given in old. This allows for masked modification of properties. For example, in a colored model, all red objects could be changed to become green. PROCEDURE (c: Controller) MakeViewVisible (v: Views.View) NEW, EMPTY Make the embedded view v visible in the controller's view. Pre v is embedded in c's view 20 PROCEDURE (c: Controller) GetFirstView (selection: BOOLEAN; OUT v: Views.View) NEW, ABSTRACT Get the first view embedded in c's model, relative to the model's start or that of a possible selection. PROCEDURE (c: Controller) GetNextView (selection: BOOLEAN; VAR v: Views.View) NEW, ABSTRACT Get the next view in the specified range, which is either the selected or the whole contents of c's model. The next view of the last view in the range is NIL. PROCEDURE (c: Controller) GetPrevView (selection: BOOLEAN; VAR v: Views.View) NEW, EXTENSIBLE Get the previous view in the specified range, which is either the selected or the whole contents of c's model. The default uses GetFirstView and GetNextView to seek the previous view of v. The previous view of the first view in the range is NIL. Pre v # NIL 20 EmbeddedIn(v, c.ThisModel()) 21 PROCEDURE (c: Controller) CanDrop (f: Views.Frame; x, y: INTEGER): BOOLEAN NEW, EXTENSIBLE Return whether the material being dragged could be dropped into frame f at its local coordinate (x, y). The default is to accept any drop request, i.e., to return TRUE. PROCEDURE (c: Controller) MarkDropTarget (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; type: Stores.TypeName; isSingle, show: BOOLEAN) NEW, EMPTY Mark the drop target in destination frame dst at point (dx, dy) for a potential dropping of material from source frame src, origin (sx, sy). show determines whether the mark should be drawn or removed. isSingle determines whether the selection to be dropped is a singleton. show indicates whether the mark should be shown or removed. (rx, ry) is the reference point inside the selection, where the drag & drop operation has started. See also Controllers.PollDropMsg. PROCEDURE (c: Controller) Drop (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; view: Views.View; isSingle: BOOLEAN) NEW, ABSTRACT Drop the material being dragged from source frame src, origin (sx, sy) and encapsulated in view under control of c in destination frame dst at point (dx, dy). The default is to ignore the drop. isSingle determines whether the selection to be dropped is a singleton. (rx, ry) is the reference point inside the selection, where the drag & drop operation has started. See also Controllers.DropMsg. PROCEDURE (c: Controller) MarkPickTarget (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER; show: BOOLEAN) NEW, EMPTY Mark the drop target in destination frame dst at point (dx, dy) for a potential dropping of material from source frame src, origin (sx, sy). show determines whether the mark should be drawn or removed. The default is not to mark at all. PROCEDURE (c: Controller) TrackMarks (f: Views.Frame; x, y: INTEGER; units, extend, add: BOOLEAN) NEW, ABSTRACT Track marks in frame f starting at point (x, y) as specified by units, extend, and add. Marks are general selections and insertion points (carets). Tracking of larger logical units (e.g., words instead of characters) is requested by units. Continuous extension of an existing selection is requested by extend. Discontinuous addition to an existing selection is requested by add. Some controllers may ignore one or the other request, e.g., may not distinguish units of varying granularity, may not support multiple selected objects, or may not support discontinuous selections. PROCEDURE (c: Controller) Resize (view: Views.View; l, t, r, b: INTEGER) NEW, ABSTRACT Request to resize view, which must be embedded in c's model, to the size given by rectangle (l, t, r, b). (Typically, a controller delegates this request to its model which implements the request by using Properties.PreferredSize to negotiate the new size with view.) PROCEDURE (c: Controller) GetSelectionBounds (f: Views.Frame; OUT x, y, w, h: INTEGER) NEW, ABSTRACT Return the bounding box of the selection, by giving its top-left reference point and its width and height. The bounding box is used for giving drag & drop feedback. PROCEDURE (c: Controller) DeleteSelection NEW, ABSTRACT Delete all objects in the current selection. PROCEDURE (c: Controller) MoveLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER) NEW, ABSTRACT Move selected objects within the model of c from the origin given by source frame src and point (sx, sy) to the target given by destination frame dst and point (dx, dy). Since this is a move of material within a single model, there is no need for conversions, and the most "natural" moving semantics can be provided. PROCEDURE (c: Controller) CopyLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER) NEW, ABSTRACT Copy selected objects within the model of c from the origin given by source frame src and point (sx, sy) to the target given by destination frame dst and point (dx, dy). Since this is a copy of material within a single model, there is no need for conversions, and the most "natural" copying semantics can be provided. PROCEDURE (c: Controller) SelectionCopy (): Model NEW, ABSTRACT Return a copy of the selected objects, encapsulated in the returned model. PROCEDURE (c: Controller) NativePaste (m: Models.Model; f: Views.Frame) NEW, ABSTRACT Paste a native model into the model of c as displayed in frame f. Since the model is native, it is to be merged into the model of c rather than wrapped into a view and embedded. PROCEDURE (c: Controller) ArrowChar (f: Views.Frame; ch: CHAR; units, select: BOOLEAN) NEW, ABSTRACT Interpret the arrow character ch, i.e., one out of the following list. The interpretation is to be modified as requested by units and select. The standard interpretation of arrow characters is the modification of the current selection or the moving of the insertion point. Modifying or moving in larger units (e.g., words instead of characters) is requested by units. Establishment of a selection if requested by select. Some controllers may ignore one or the other request, e.g., may not distinguish units of varying granularity or may not support selections. Table of arrow characters: name code meaning aL 1CX arrow left aR 1DX arrow right aU 1EX arrow up aD 1FX arrow down pL 10X page left pR 11X page right pU 12X page up pD 13X page down dL 14X document left dR 15X document right dU 16X document up dD 17X document down The intention is a modification or move in the indicated direction on the smallest supported granularity ("arrow"), on the basis of "pages" as defined by the size of frame f, or on the basis of the whole "document", i.e., the far extremes of the model of c. The precise interpretation of the directions and units is left to the specific controller. PROCEDURE (c: Controller) ControlChar (f: Views.Frame; ch: CHAR) NEW, ABSTRACT Handle entry of control character ch related to the model and view of c as displayed in frame f. Table of control characters: name code meaning enter 3X enter rdel 7X right delete del 8X left delete tab 09X tabulator ltab 0AX reverse tabulator line 0DX line para 0EX paragraph esc 1BX escape PROCEDURE (c: Controller) PasteChar (ch: CHAR) NEW, ABSTRACT Paste character ch into the model of c. PROCEDURE (c: Controller) PasteView (f: Views.Frame; v: Views.View; w, h: INTEGER) NEW, ABSTRACT Paste view v with desired size (w, h) into the model of c. (Typically, a controller delegates this request to its model which implements the request by using Properties.PreferredSize to negotiate the new size with v.) PROCEDURE (c: Controller) HasSelection (): BOOLEAN NEW, EXTENSIBLE Return whether the controller currently has a selection. By default, only singleton selections are supported. To be extended to include intrinsic selections. Pre c.ThisModel() # NIL 20 PROCEDURE (c: Controller) Selectable (): BOOLEAN NEW, ABSTRACT Return whether the controller could establish a nonђempty selection. If something (or everything) is already selected, this is considered selectable. PROCEDURE (c: Controller) Singleton (): Views.View NEW If the controller currently has a singleton selection, then the selected view is returned, else NIL. PROCEDURE (c: Controller) SetSingleton (s: Views.View) NEW, EXTENSIBLE Set the controller's selection to a singleton selection covering view s. IF s = NIL, the current singleton selection is cleared. Needs to be extended to adjust intrinsic selection state accordingly. Pre c.ThisModel() # NIL 20 ~(noSelection IN c.opts) 21 s # NIL s.context # NIL 22 s.context.ThisModel() = c.ThisModel() 23 Post c.Singleton() = s PROCEDURE (c: Controller) SelectAll (select: BOOLEAN) NEW, ABSTRACT Set the selection to its maximum extent, i.e., select all intrinsic content of the controller's model plus all embedded views. For an empty model there is no visible result; for a model with only one embedded view and no intrinsic contents a singleton selection results. PROCEDURE (c: Controller) InSelection (f: Views.Frame; x, y: INTEGER): BOOLEAN NEW, ABSTRACT Test whether in frame f the point (x, y) lies within the current selection. PROCEDURE (c: Controller) MarkSelection (f: Views.Frame; show: BOOLEAN) NEW, EXTENSIBLE Depending on show, show or hide the selection's visual marking. The default handles singleton selections only. To be replaced to include intrinsic selections. PROCEDURE (c: Controller) SetFocus (focus: Views.View) NEW Sets the current subfocus to focus; if focus = NIL, the current subfocus is removed. Pre c.ThisModel() # NIL 20 focus # NIL focus.context # NIL 21 focus.context.ThisModel() = c.ThisModel() 22 Post c.ThisFocus() = focus PROCEDURE (c: Controller) HasCaret (): BOOLEAN NEW, ABSTRACT Return whether the controller has a valid caret (insertion point). PROCEDURE (c: Controller) MarkCaret (f: Views.Frame; show: BOOLEAN) NEW, ABSTRACT Depending on show, show or hide the current caret's visual marking. PROCEDURE (c: Controller) Mark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN) NEW, EXTENSIBLE Except for performance, equivalent to: MarkFocus(c, f, show); c.MarkSelection(f, show); c.MarkCaret(f, show) To be extended to cover additional intrinsic marking. PROCEDURE (c: Controller) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER) Clarification of inherited procedure Calls Mark to show all marks in (l, t, r, b), then, if no subfocus exists and c.opts indicates mask mode, tries to establish a subfocus: the first embedded view that wants to claim the focus (Properties.FocusPref.setFocus) gets it. If the new subfocus wants to start off with an initially selected contents (Properties.FocusPref.selectOnFocus), it is also fully selected. PROCEDURE (c: Controller) Neutralize Clarification of inherited procedure Remove all modal marks, including focus, selection, and caret. The default handles focus and selection. To be extended to handle caret and possibly further marks. Except for performance, the default is equivalent to: c.SetFocus(NIL); c.SelectAll(deselect) PROCEDURE (c: Controller) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View) Clarification of inherited procedure Handles Controllers.PollCursorMsg, Controllers.PollOpsMsg, Controllers.TrackMsg, Controllers.EditMsg, Controllers.TransferMessage, Controllers.SelectMsg, Controllers.MarkMsg, Controllers.ReplaceViewMsg, Properties.CollectMsg, and Properties.EmitMsg. PROCEDURE (c: Controller) HandlePropMsg (VAR p: Properties.Message) Clarification of inherited procedure The default is to handle Properties.SetMsg and Properties.PollMsg by splitting the handling of native and embedded properties and set or return the combined property list. Also, unless noSelection, noFocus, and noCaret are set in c.opts, field Properties.FocusPref.setFocus is set. Pre c.ThisModel() # NIL 20 TYPE Directory ABSTRACT Directory for controllers. PROCEDURE (d: Directory) New (): Controller NEW, EXTENSIBLE Except for performance, equivalent to: RETURN d.NewController({}) PROCEDURE (d: Directory) NewController (opts: SET): Controller NEW, ABSTRACT Return new controller with options opts. TYPE DropPref = RECORD (Properties.Preference) This message is sent to a contained view in a container when the container needs to decide if something should be dropped into the view or into the container. This message can be intercepted to allow drag and drop also when the container itself normally would catch the drop messages, i.e. when the container is in layout mode. mode-: SET The current mode of the container. okToDrop: BOOLEAN Set to TRUE if the view should recieve drop messages also in the mode given by mode. TYPE GetOpts = RECORD (Views.PropMessage) This message is sent to a selected view to ask about the container mode of this view. If a view answers this message it should set valid to the options that apply to the view and opts to the current values of these options. Whenever GetOpts is answered the SetOpts-message must also be answered. valid: SET Should be set to the options that apply to the view. opts: SET Current values of the options pointed out in valid. TYPE SetOpts = RECORD (Views.PropMessage) Sent to a view to indicate that its options should be changed to the values indicated by valid and opts. valid: SET Mask to indicate which values should be set. opts: SET Values of the options indicated by valid. PROCEDURE Focus (): Controller Returns the current focus view's container controller, if possible. PROCEDURE FocusSingleton (): Views.View Returns the current focus view's singleton selection, if possible. PROCEDURE MarkSingleton (c: Controller; f: Views.Frame; show: BOOLEAN) Used internally. PROCEDURE FadeMarks (c: Controller; show: BOOLEAN) Used internally.
System/Docu/Containers.odc
Controllers DEFINITION Controllers; IMPORT Fonts, Ports, Stores, Views; CONST frontPath = FALSE; targetPath = TRUE; decLine = 0; incLine = 1; decPage = 2; incPage = 3; gotoPos = 4; nextPageX = 0; nextPageY = 0; gotoPageX = 2; gotoPageY = 3; cut = 0; copy = 1; pasteChar = 2; paste = 4; doubleClick = 0; extend = 1; modify = 2; noMark = FALSE; mark = TRUE; hide = FALSE; show = TRUE; TYPE Controller = POINTER TO ABSTRACT RECORD (Stores.Store) END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) New (): Controller, NEW, ABSTRACT END; Forwarder = POINTER TO ABSTRACT RECORD (n: Forwarder) Forward (target: BOOLEAN; VAR msg: Message), NEW, ABSTRACT; (n: Forwarder) Transfer (VAR msg: TransferMessage), NEW, ABSTRACT END; Message = Views.CtrlMessage; PollFocusMsg = EXTENSIBLE RECORD (Message) focus: Views.Frame END; PollSectionMsg = RECORD (Message) focus, vertical: BOOLEAN wholeSize, partSize, partPos: LONGINT; valid, done: BOOLEAN END; PollOpsMsg = RECORD (Message) type: Stores.TypeName; pasteType: Stores.TypeName; singleton: Views.View; selectable: BOOLEAN; valid: SET END; ScrollMsg = RECORD (Message) focus, vertical: BOOLEAN op: INTEGER; pos: LONGINT; done: BOOLEAN END; PageMsg = RECORD (Message) op: INTEGER; pageX, pageY: INTEGER; done, eox, eoy: BOOLEAN END; TickMsg = RECORD (Message) tick: INTEGER END; MarkMsg = RECORD (Message) show, focus: BOOLEAN END; SelectMsg = RECORD (Message) set: BOOLEAN END; RequestMessage = ABSTRACT RECORD (Message) requestFocus: BOOLEAN END; EditMsg = RECORD (RequestMessage) op: INTEGER; modifiers: SET; char: CHAR; view: Views.View; w, h: INTEGER; isSingle: BOOLEAN; clipboard: BOOLEAN END; ReplaceViewMsg = RECORD (RequestMessage) old, new: Views.View END; CursorMessage = ABSTRACT RECORD (RequestMessage) x, y: INTEGER END; PollCursorMsg = RECORD (CursorMessage) cursor: INTEGER; modifiers: SET END; TrackMsg = RECORD (CursorMessage) modifiers: SET END; WheelMsg = RECORD (CursorMessage) done: BOOLEAN; op, nofLines: INTEGER END; TransferMessage = ABSTRACT RECORD (CursorMessage) source: Views.Frame; sourceX, sourceY: INTEGER END; PollDropMsg = RECORD (TransferMessage) mark: BOOLEAN; show: BOOLEAN; type: Stores.TypeName; isSingle: BOOLEAN; w, h: INTEGER; rx, ry: INTEGER; dest: Views.Frame END; DropMsg = RECORD (CursorMessage) view: Views.View; isSingle: BOOLEAN; w, h: INTEGER; rx, ry: INTEGER END; VAR path-: BOOLEAN; PROCEDURE Forward (VAR msg: Message); PROCEDURE FocusFrame (): Views.Frame; PROCEDURE FocusView (): Views.View; PROCEDURE FocusModel (): Models.Model; PROCEDURE Register (f: Forwarder); PROCEDURE Delete (f: Forwarder); PROCEDURE ForwardVia (target: BOOLEAN; VAR msg: Message); PROCEDURE SetCurrentPath (target: BOOLEAN); PROCEDURE PollSection (VAR msg: PollSectionMsg); PROCEDURE PollOps (VAR msg: PollOpsMsg); PROCEDURE PollCursor (x, y: INTEGER; OUT cursor: INTEGER); PROCEDURE Transfer (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; VAR msg: TransferMessage); PROCEDURE PollDrop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; mark, show: BOOLEAN; type: Stores.TypeName; isSingle: BOOLEAN; w, h, rx, ry: INTEGER; OUT dest: Views.Frame; OUT destX, destY: INTEGER); PROCEDURE Drop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; view: Views.View; isSingle: BOOLEAN; w, h, rx, ry: INTEGER); PROCEDURE PasteView (view: Views.View; w, h: INTEGER; clipboard: BOOLEAN); PROCEDURE ResetCurrentPath; PROCEDURE SetCurrentPath (target: BOOLEAN); END Controllers. Figure 1. Model-View-Controller Separation A controller implements the interactive behavior for a view class. It is an object which transforms controller messages into model or view transformations. A controller message is a message which is sent along exactly one path in a view hierarchy, the focus path. Every view on such a path decides for itself whether it is the terminal of this path, i.e., whether it is the current focus, or whether the message should be forwarded to one of its embedded views. BlackBox supports two focus paths, namely a target and a front focus. Both paths may fall together into one. The target path defines which view is the target of commands in dialogs. The front path defines which view is being edited, via mouse, keyboard, or menus. Figure 2. Simplified Example of Focus Hierarchy It is important to note that all controller messages which are not relevant for a particular view type can simply be ignored. CONST frontPath This value may be passed as target parameter to several procedures of this module. It lets a focus message be sent along the front focus path. CONST targetPath This value may be passed as target parameter to several procedures of this module. It lets a controller message be sent along the target focus path. CONST decLine, incLine, decPage, incPage These values can be assigned to the ScrollMsg.op field. They will cause the receiver view to scroll by increments or decrements of one line or page. It is up to the receiver to define what constitutes a "line" in its model, except that it should be smaller than a page. A page should correspond to the width/height of the focus frame. CONST gotoPos This value can be assigned to the ScrollMsg.op field. It causes the receiver view to scroll to the position given by ScrollMsg.pos. CONST nextPageX, nextPageY This value can be assigned to the PageMsg.op field. It causes the receiver view to display the next page in x resp. in y direction. CONST gotoPageX, gotoPageY This value can be assigned to the PageMsg.op field. It causes the receiver view to display a given page in x resp. in y direction. CONST cut, copy These values can be assigned to the EditMsg.op field. They should be handled by the receiver view in the following way: cut delete selection, and assign a new view containing the deleted data or a copy thereof to EditMsg.view copy copy selection, and assign a new view containing the copied data to EditMsg.view CONST pasteChar This value can be assigned to the EditMsg.op field. It denotes the input of some (Unicode or Latin-1) character. CONST paste This value can be assigned to the EditMsg.op field. The receiver view should insert a copy of the data that EditMsg.view contains. If it cannot insert the data directly because it doesn't know its type, it should insert a copy of the whole EditMsg.view into its model if it has this capability, i.e., if it is a container. CONST doubleClick This value means that a mouse button has been pressed in a way which is interpreted by the underlying user interface as a "double click". A double click is signaled to the application as a modifier; other modifiers are extend and modify. CONST extend, modify BlackBox operates with two virtual modifier keys. The extend key is used to extend or toggle selections (usually the shift key), the modify key to change the default behavior of a command (e.g., to change a drag-and-move into a drag-and-copy, using the control key (Windows) / option key (Mac OS)). The behavior of possible additional modifier keys is platform-specific (see the document on platform-specific issues for such modifiers). Modifier sets are used in Controllers.TrackMsg, Controllers.EditMsg, and Ports.Frame.Input. CONST noMark, mark Used internally. CONST hide, show These constants may be used for the PollDropMsg message and the PollDrop procedure. They determine whether target feedback during drag & drop should be drawn (show) or removed (hide). TYPE Controller (Stores.Store) ABSTRACT A controller is the third component of the model-view-controller triple. Its main purpose is to translate controller messages into model or view transformations. Simple applications can implement the controller's functionality in the view itself, thus needing no separate controller object at all. Container views usually have a separate controller. TYPE Directory ABSTRACT Usually there is a controller directory in the views module of a subsystem, since the view directory must be able to allocate an appropriate controller. Such a directory is installed by the corresponding controller module upon loading. To guarantee the loading of the corresponding controller module is loaded, the view module's body usually contains a statement of the form Dialog.Call("XYZControllers.Install, "", res). PROCEDURE (d: Directory) New (): Controller NEW, ABSTRACT Returns a new controller. Post result # NIL result.ThisView() = NIL TYPE Forwarder ABSTRACT Used internally. PROCEDURE (n: Forwarder) Forward (target: BOOLEAN; VAR msg: Message) NEW, ABSTRACT Used internally. PROCEDURE (n: Forwarder) Transfer (VAR msg: TransferMsg) NEW, ABSTRACT Used internally TYPE Message ABSTRACT Base type of all controller messages. In contrast to model and view messages, a controller message is never broadcast. Instead, it is passed along a focus path. The target and front focus paths are predefined. TYPE PollFocusMsg (Message) EXTENSIBLE This message is sent to find out the leaf view of a focus path. The message is handled by the framework itself. If your view should not give away its identity when it is focus, set focus to NIL when receiving the message. Otherwise ignore the message. focus: Views.Frame After the message returns from the traversal of a focus path, it should contain the frame of the leaf view of this path. TYPE PollSectionMsg (Message) This message is sent to poll the focus view's current scroll state. BlackBox contains a generic scrolling mechanism which scrolls simply by changing the scrolled frame's origin. Explicit handling of scrolling is only necessary for views which can become extremely large, and whose efficient implementation crucially depends on keeping frames small. focus: BOOLEAN This flag tells whether a container should forward the message to its focus or not. Non-containers obviously cannot forward to a focus. vertical: BOOLEAN Tells whether the vertical or horizontal direction is polled. wholeSize: INTEGER wholeSize >= 1 This value denotes the focus view's width or height, in coordinates which a view can freely choose, i.e., they need not necessarily be universal units. partSize: INTEGER 0 <= partSize <= wholeSize This value denotes the focus view frame's width or height, in the same coordinates as above. If partSize cannot be easily defined, it should be set to 0. partPos: INTEGER 0 <= partPos <= wholeSize - partSize This value denotes the focus view's origin, in the same coordinates as above. valid: BOOLEAN The receiving view should set this flag if it supports scrolling in the given direction. valid indicates that wholeSize, partSize, and partPos are valid indicators of the view's scroll position. done: BOOLEAN This flag should be set if the message has been interpreted, i.e., if the above output fields have been set. For some controllers this may depend on vertical, i.e., the controller only supports one scrolling direction. TYPE PollOpsMsg (Message) This message is sent to inquire which editing operations the focus view supports, depending on its current selection. type: Stores.TypeName This field denotes a context for the focus view. This context is used to determine which menus are relevant for the focus view. As a convention, a view assigns the type name of its abstract base pointer type to type, e.g., "TextViews.View". This convention guarantees globally unique context names, since module names are considered globally unique. If the view doesn't support any such context, ignore this field. pasteType: Stores.TypeName valid iff type = paste The type of the view of which a copy would be pasted, if a paste operation occurred. singleton: Views.View A container view which supports a selection should set this field to the selected view, if this view is the only contents currently selected. selectable: BOOLEAN This field should be set to TRUE if the focus view contains selectable elements, independent of whether they are currently selected or not. valid: SET valid IN {cut, copy, paste} This set denotes which edit operations are currently possible, out of the set {cut, copy, paste}. It is used by the framework to enable or disable the appropriate menu items. However, there is no guarantee that the framework will not send an edit message for cut/copy/paste even if the view returns an empty set in valid. Such a message can simply be ignored. TYPE ScrollMsg (Message) This message is sent in order to let the focus view scroll to another position. It is used only in conjunction with PollSectionMsg (cf. above). focus: BOOLEAN This flag tells whether a container should forward the message to its focus or not. Non-containers obviously cannot forward to a focus. vertical: BOOLEAN Denotes whether scrolling should occur in the vertical or in the horizontal direction. op: INTEGER op IN {decLine..gotoPos} Scroll operation to be performed. pos: INTEGER valid iff op = gotoPos pos >= 0 This denotes the position to be scrolled to, in the same coordinates that the PollSectionMsg uses. done: BOOLEAN This flag should be set if the message has been interpreted; for some controllers, this may depend on op. TYPE PageMsg (Message) A page message is similar to a scroll message, but its measures are in pages. It can be interpreted if the view should behave differently depending whether it is being printed or not. This is done e.g. in TextViews to avoid the last line on a page to become clipped, which is acceptable on screen. If this message is not interpreted for a view which cannot be printed on one page, a default printing strategy is used which decomposes the view into suitable pieces for printing. op: INTEGER op IN {nextPageX, nextPageY, gotoPageX, gotoPageY} Where to scroll to. pageX, pageY: INTEGER Current page in x and in y directions. done: BOOLEAN This flag should be set if the message has been interpreted; for some controllers, this may depend on op. eox, eoy: BOOLEAN These flags should be set when it is attempted to go beyond the last page in the x resp. in y direction. TYPE TickMsg (Message) This message is sent to the front focus view periodically. It can be used to realize effects like a blinking caret. tick: INTEGER Tick count. The difference between two ticks is given by the global variable resolution. TYPE MarkMsg (Message) This message is sent whenever the target or front focus paths change. Before the change, the message is sent along the focus path with show = FALSE, such that the focus view can switch off visible marks like the selection or the caret. After the change (e.g., another window coming to the top), a MarkMsg is sent along the focus path with show = TRUE, such that the focus view can switch on its marks again, if there are any. Behavior can be different if the focus path changes due to window reordering or due to user interaction (a user clicking in some other embedded view). In the former case, a focused view may still keep its focus state (selection, caret), even while it is temporarily in a non-focus window. When the window becomes focus again, the old focus view becomes focus again. In this case, it should show the same selection/caret state again. In the latter case, a view that becomes newly focused may behave in a special way. In particular, a control may focus its contents (e.g., a text field may select the entire text string that it contains). To detect such a situation, a field focus is provided in the MarkMsg. Wrapper views and special container views (i.e., containers not derived from the types in module Containers) have to forward the MarkMsg to their embedded views. show: BOOLEAN Tells whether the focus view's marks should be switched on or off. focus: BOOLEAN Tells whether the view is being focused or defocused. A view may use this information e.g. to select itself upon becoming focus (this is done by text field controls). This is done in the following way: IF msg.focus THEN IF msg.show THEN (* set selection on focus *) ... select contents of view ... ELSE (* remove selection on defocus *) ... remove selection ... END END TYPE SelectMsg (Message) This message is sent when the focus view should select all selectable items, or when it should deselect all selected items. Selection occurs e.g. when the Edit->Select All command is executed. set: BOOLEAN Determines whether everything should be selected (set = TRUE) or whether everything should be deselected (set = FALSE). TYPE RequestMessage (Message) ABSTRACT A view (or its controller) receiving a request message can indicate, by setting requestFocus to TRUE, that it wants to become focus afterwards, if it isn't already. requestFocus: BOOLEAN Set this flag to TRUE if receiver should become/remain focus after the message has been handled. TYPE EditMsg (RequestMessage) This message is sent when a key was pressed, or when a cut/copy/paste operation was invoked. The following operations can be supported (for every supported operation except pasting of characters, the corresponding flag in PollOpsMsg.valid should be set when receiving a PollOpsMsg): cut Create a clone of the focus view, with a copy of its selection as contents. Assign this clone to EditMsg.view and delete the focus' selection. There is one exception: if the selection consists of exactly one view (a singleton), this view's clone should be copied to EditMsg.view, not a clone of its container. copy Create a clone of the focus view, with a copy of the focus' selection as contents. Assign this clone to EditMsg.view. If the selection consists of exactly one view (a singleton), this view's clone should be copied to EditMsg.view. pasteChar Interpret EditMsg.char, e.g., insert it into a text model. char may be a control character. For control characters, check field modifiers also. paste Insert EditMsg.view view into the focus view's contents. If the receiver is a container: If EditMsg.isSingle: It should insert the view as a complete view, independent of its type. This means that merging of contents is not permitted, even if this were possible. If ~EditMsg.isSingle: If it knows the contents of EditMsg.view, it should insert it, otherwise the complete view. If the receiver is not a container: If it knows the contents of EditMsg.view, it should insert it, otherwise it should do nothing. op: INTEGER op IN {cut .. paste} Operation to be performed. modifiers: SET valid iff op= pasteChar Modifier keys. char: CHAR valid iff op = pasteChar Character to be pasted, or to be interpreted in the case of control characters. view: Views.View valid iff op IN {paste, cut, copy} & view # NIL & view.context = NIL If op = paste: (IN parameter) View which should be pasted. If op IN {cut, copy}: (OUT parameter) View which should be assigned by the message handler. w, h: INTEGER valid iff op IN {paste, cut, copy} w >= Views.undefined & h >= Views.undefined [units] If op = paste: (IN parameter) The desired width and height of the pasted view. These values can be treated as hints. If they are not suitable, others can be used. The value Views.undefined should be handled also. If op IN {cut, copy}: (OUT parameter) Current width and height of the view. isSingle: BOOLEAN valid iff op IN {paste, cut, copy} If op = paste: (IN parameter) Tells whether the pasted view should be inserted as singleton, i.e., not be merged even if this were possible. If op IN {cut, copy}: (OUT parameter) The message handler should set this flag if the cut/copied view is selected as a singleton. clipboard: BOOLEAN valid iff op IN {cut, copy, paste} This input parameter tells whether the cut/copied view will be transferred to the system clipboard, or whether the pasted view comes from the system clipboard. TYPE ReplaceViewMsg (RequestMessage) A container should check whether it contains old. If so, it should replace old by new, without modifying the view's context in any way. old, new: Views.View old # NIL & new # NIL old should be replaced by new. TYPE CursorMessage (RequestMessage) ABSTRACT The base type of all messages which denote some interaction that depends on the current cursor position. The cursor position is always measured in units relative to the view's top-left corner. x, y: INTEGER [units] Current cursor position. TYPE PollCursorMsg (CursorMessage) This message is sent regularly to inquire which cursor the focus view currently desires. cursor: INTEGER cursor IN {Ports.arrowCursor .. Ports.refCursor} This field can be set to the cursor appropriate for the focus view. modifiers: SET This is an input field that gives the current modifer state of the mouse. TYPE TrackMsg (CursorMessage) Extension This message is sent when the mouse button is pressed down. modifiers: SET Determines which modifier keys have been pressed together with the mouse button. TYPE WheelMsg (CursorMessage) Extension This message is sent when the wheel on a wheel mouse is rolled. done: BOOLEAN If a view handles this message it must set the done flag to TRUE. op: INTEGER Indicates which kind of event the mouse wheel caused. The same constants as for scrolling are used, but only the following values are valid: incPage, decPage, incLine and decLine. nofLines: INTEGER nofLines >= 1 If op is either incLine or decLine then nofLines indicates how many lines should be scrolled. For incPage and decPage this value is undefined. TYPE TransferMessage (CursorMessage) ABSTRACT This is the base type of all messages which denote an interaction between several views, e.g., for drag and drop. source: Views.Frame The frame from which the interaction started, e.g., where the mouse button has been clicked for dragging. sourceX, sourceY: INTEGER The position in the source frame where the mouse button has been clicked, e.g., when starting to drag. TYPE PollDropMsg (TransferMessage) While an item is being dragged around, PollDropMsgs are sent to enable feedback about the drop target. mark: BOOLEAN A container which supports drop feedback should show (hide) its feedback mark when mark is set (cleared). You don't need to deal with the view's border mark (the rectangular outline of the view which is drawn while you are dragging over a view), this is handled completely by BlackBox itself. show: BOOLEAN valid iff mark Indicates whether the mark should be drawn or removed. type: Stores.TypeName The type of the view to be dropped. The same naming convention as for the PollOpsMsg is used. Based on type, the message handler can determine whether the view to be dropped can be accepted. Note that if drag & drop happens completely within BlackBox, the inherited message field source may also be used for this test. However, source may be NIL if OLE drag & drop occurs. isSingle: BOOLEAN Tells whether the view to be dropped is a singleton selection. w, h: INTEGER Size of the view to be dropped. May be equal to Views.undefined. rx, ry: INTEGER rx >= 0 & ry >= 0 The reference point inside the selection where drag & drop started. dest: Views.Frame (OUT parameter) The receiver should set dest to its own frame, if it would accept a drop. TYPE DropMsg (CursorMessage) This message is used if a view should be dragged and dropped to the cursor location. view: Views.View view # NIL The view which is dropped. It is a copy of the original, and ready to be inserted at the drop destination. isSingle: BOOLEAN Tells whether the view to be dropped is a singleton selection. w, h: INTEGER [units] The size of the dropped view. One or both sizes may have the value Views.undefined. rx, ry: INTEGER The reference point inside the selection where drag & drop started. VAR path-: BOOLEAN Used internally. PROCEDURE Forward (VAR msg: Message) Send msg to to current focus. PROCEDURE FocusFrame (): Views.Frame Returns the current focus frame, if there is any. PROCEDURE FocusView (): Views.View Returns the current focus view, if there is any. PROCEDURE FocusModel (): Models.Model Returns the current focus view's model, if there is any. The following procedures are used internally: PROCEDURE Register (f: Forwarder) Add forwarder f to the list of forwarders. If f is already registered, Register(f) does nothing. Pre f # NIL 20 PROCEDURE Delete (f: Forwarder) Remove f from the list of forwarders. If f is not registered, nothing happens. Pre f # NIL 20 PROCEDURE ForwardVia (target: BOOLEAN; VAR msg: FocusMessage) Send msg to either target or front focus. PROCEDURE SetCurrentPath (target: BOOLEAN) Set path to target. Must be balanced by a call to ResetCurrentPath, otherwise a trap will occur (in Controllers.BalanceCheckActions.Do). PROCEDURE PollSection (VAR msg: PollSectionMsg) Poll the current focus view's scroll state. PROCEDURE PollOps (VAR msg: PollOpsMsg) Poll the current focus view's currently valid editing operations. PROCEDURE PollCursor (x, y: INTEGER; OUT cursor: INTEGER) Poll the current focus view's currently desired cursor. PROCEDURE Transfer (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; VAR msg: TransferMessage) PROCEDURE PollDrop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; mark, show: BOOLEAN; type: Stores.TypeName; isSingle: BOOLEAN; w, h, rx, ry: INTEGER; OUT dest: Views.Frame; OUT destX, destY: INTEGER) PROCEDURE Drop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; view: Views.View; isSingle: BOOLEAN; w, h, rx, ry: INTEGER) PROCEDURE PasteView (view: Views.View; w, h: INTEGER; clipboard: BOOLEAN) PROCEDURE ResetCurrentPath PROCEDURE SetCurrentPath (target: BOOLEAN)
System/Docu/Controllers.odc
Controls DEFINITION Controls; IMPORT Meta, Dialog, Views, Properties; CONST opt0 = 0; opt1 = 1; opt2 = 2; opt3 = 3; opt4 = 4; link = 5; label = 6; guard = 7; notifier = 8; level = 9; default = opt0; cancel = opt1; left = opt0; right = opt1; multiLine = opt2; password = opt3; sorted = opt0; haslines = opt1; hasbuttons = opt2; atroot = opt3; foldericons = opt4; TYPE Control = POINTER TO ABSTRACT RECORD (Views.View) item-: Meta.Item; disabled-, undef-, readOnly-, customFont-: BOOLEAN; font-: Fonts.Font; label-: Dialog.String; prop-: Prop; (c: Control) Internalize- (VAR rd: Stores.Reader); (c: Control) Externalize- (VAR wr: Stores.Writer); (c: Control) CopyFromSimpleView- (source: Views.View); (c: Control) HandleViewMsg- (f: Views.Frame; VAR msg: Views.Message); (c: Control) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View); (c: Control) HandlePropMsg- (VAR msg: Views.PropMessage); (c: Control) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY; (c: Control) Externalize2- (VAR wr: Stores.Writer), NEW, EMPTY; (c: Control) CopyFromSimpleView2- (source: Control), NEW, EMPTY; (c: Control) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY; (c: Control) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View), NEW, EMPTY; (c: Control) HandlePropMsg2- (VAR p: Views.PropMessage), NEW, EMPTY; (c: Control) CheckLink- (VAR ok: BOOLEAN), NEW, EMPTY; (c: Control) Update- (f: Views.Frame; op, from, to: INTEGER), NEW, EMPTY; (c: Control) UpdateList- (f: Views.Frame), NEW, EMPTY END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) NewPushButton (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewCheckBox (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewRadioButton (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewListBox (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewSelectionBox (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewField (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewUpDownField (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewDateField (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewTimeField (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewTreeControl (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewColorField (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewComboBox (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewCaption (p: Prop): Control, NEW, ABSTRACT; (d: Directory) NewGroup (p: Prop): Control, NEW, ABSTRACT END; Prop = POINTER TO RECORD (Properties.Property) opt: ARRAY 5 OF BOOLEAN; link, label, guard, notifier: Dialog.String; level: INTEGER; (p: Prop) IntersectWith (q: Properties.Property; OUT equal: BOOLEAN) END; DefaultsPref = RECORD (Properties.Preference) disabled, undef, readOnly: BOOLEAN END; PropPref = RECORD (Properties.Preference) valid: SET END; VAR dir-, stdDir-: Directory; par-: Views.View; PROCEDURE Notify (c: Control; f: Views.Frame; op, from, to: INTEGER); PROCEDURE OpenLink (c: Control; p: Prop); PROCEDURE Relink; PROCEDURE DepositPushButton; PROCEDURE DepositCheckBox; PROCEDURE DepositRadioButton; PROCEDURE DepositListBox; PROCEDURE DepositSelectionBox; PROCEDURE DepositField; PROCEDURE DepositUpDownField; PROCEDURE DepositDateField; PROCEDURE DepositTimeField; PROCEDURE DepositTreeControl; PROCEDURE DepositColorField; PROCEDURE DepositComboBox; PROCEDURE DepositCaption; PROCEDURE DepositGroup; PROCEDURE DepositCancelButton; PROCEDURE SetDir (d: Directory); END Controls. Module Controls provides a variety of standard user interface elements, so-called controls. In BlackBox, a control is an extended view. As every view, a control can be embedded in any general container (-> Containers), such as forms (-> FormModels) but also texts (-> TextModels). Usually, controls are put into forms. The standard controls provided by BlackBox are: command buttons (push buttons), check boxes, radio buttons, list boxes, selection boxes, (text, date, time and color) fields, combo boxes, tree controls, captions, and groups. Unlike other views, these BlackBox controls can be linked to a program variable, or more exactly: to any field accessible through a globally declared variable. When the control is opened, BlackBox tries to link the control to its variable, using the advanced metaprogramming capabilities of the BlackBox Meta module. In this way, the link between control and variable can be built up automatically when a dialog is newly created or loaded from a file, and correct linking (i.e., correct typing) can be guaranteed even after a dialog layout had been edited or otherwise manipulated. Controls may take on different states at run-time. Depending on the control and on the underlying user interface, these states may be represented in visually distinct ways: enabled/disabled Only enabled controls may be modified interactively. To disable a control, its guard should set par.disabled to TRUE. A control which cannot be linked to its variable is always disabled. defined/undefined Illegal or otherwise undefined values may be hilighted as such. To mark a control as undefined, its guard should set par.undef to TRUE. normal/read-only Controls may be denoted as read-only, i.e., under program control only. To mark a control as read-only, its guard should set par.readOnly to TRUE. Controls which are linked to read-only variables are always read-only. Note that the above states are temporary, i.e., determined wholly at run-time; they are never externalized or internalized. All controls have the following persistent properties, which are externalized when the controls are written to files: link This is the name of a global variable, to which the control is linked, e.g., TextCmds.find.replace. label This is the displayed string. (not applicable to (text, date, time and color) fields, list boxes, selection boxes, combo boxes) A "&" character indicates which character of the label should be underlined (For the keyboard shortcut. This is a Windows feature, and not available on Mac OS). If you want a "&" to appear, you should write a "&&". guard This optional command name denotes a guard procedure which allows to disable/enable a control selectively, and to set the undef and readOnly states as well. notifier This optional command name denotes a notifier procedure which allows to do something whenever the value of a control was changed interactively. light font A field may either be displayed in the standard font for this purpose, or in a more discreet ("light") font. On some platforms, this property may be interpreted only in fields and captions. These properties, as well as further control-specific properties (see below) can be set interactively using a suitable tool (-> DevInspector), or programmatically using the Properties.SetMsg. Command Button Pressing a command button invokes a parameterless exported Component Pascal procedure. A command button is either linked to a parameterless exported procedure. It can be either a constant (a normal procedure) or a procedure variable. Additional properties: default The button is activated when the user presses return or enter. cancel The button is activated when the user presses escape. Check Box A check box lets the user toggle between two states, checked and unchecked. A check box is linked to a BOOLEAN field or variable. Alternatively, a check box can also be linked to a SET field or variable. The level property then specifies to which entry of the set the control is linked to. The control is checked if the inspected element is in the set. A check box can also be linked to a Dialog.Selection field or variable. The level property then indicates which element of the val set of the selection is inspected. Additional property: level if a check box is linked to a set or to a Dialog.Selection variable, then the level field indicates which set element is displayed by the control. Radio Button Radio buttons let the user choose between several alternatives. Each alternative is represented as a radio button. At any time, exactly one of the radio buttons is "on", while all others are "off". All radio buttons which belong to one selection are linked to the same integer field. Each radio button is "on" for another value of the integer field. This value can be configured with the level property. Additional property: level a radio button is "on" when the value of the variable to which the button is bound is equal to the level value. List Box A list box presents a list of strings to the user. From this list, at most one entry can be selected. List boxes are linked to a Dialog.List. Selection Box A selection box presents a list of strings to the user. From this list, an arbitrary number of entries can be selected. Selection boxes are linked to a Dialog.Selection. Field A text field lets the user type in a string. Fields are either linked to ARRAY n OF CHAR, BYTE, SHORTINT, INTEGER, LONGINT, SHORTREAL, REAL, Dialog.Combo or Dialog.Currency fields. Fields perform some basic checks, such as for the maximum permissible string length, or for the permissible character set (for numbers, only digits and a few characters like "-" or "." make sense). Additional property: multi line The field linked to ARRAY n OF CHAR may display several lines. A carriage return character is accepted on input. password Don't display the characters that have been typed in. UpDownField The UpDownField is a special text field linked to a BYTE, SHORTINT, INTEGER or LONGINT variable. The value of the integer can be incremented and decremented through arrows. DateField A date field lets the user specify a date. Date fields are linked to variables of type Dates.Date. On input, date fields only allow valid dates. Time Field A time field lets the user specify a time. Time fields are linked to variables of type Dates.Time. On input, time fields only allow valid times. Tree Control A tree control presents a tree of strings to the user. From this tree, at most one node can be selected. Tree Controls are linked to a Dialog.Tree. Additional properties: Sorted Nodes with the same parent are displayed in alphabetical order rather than in the order they were added to the tree. Lines Lines are drawn between nodes in the tree. Buttons A button with a "+" or a "-" sign is drawn in front of nodes that have children. Lines/Buttons at Root Lines and buttons are drawn also at the root level in the tree. Folder Icons Icons are used to show nodes as folders or leafs. Color Field A color field lets the user specify a color. Color fields are linked to variables of type Dialog.Color or of type Ports.Color. Combo Box A combo box is a combination of a text field with a list box. Like a list box, it presents a list of strings from which can be chosen. Additionally, it provides a field in which a value may be typed in. This value may be one in the list, or another value altogether. Combo boxes are linked to a Dialog.Combo. Caption A caption is a static string, which cannot be manipulated by the user. Typically, a field is accompanied by a caption which tells what the meaning of the field is. Captions may either be unlinked, or linked to the same record field as their corresponding field. Captions are not completely passive in that they may be enabled or disabled (e.g., "greyed out") as other controls. Group A group is a rectangular frame with a label in it. It allows to logically group several controls together. Guard commands can be associated with a control. Such a command has the following signature: PROCEDURE Guard (VAR par: Dialog.Par) The main purpose of a guard command is to disable a control when necessary. This is done in the following way: PROCEDURE Guard (VAR par: Dialog.Par); BEGIN par.disabled := condition END Guard; Controls which are always enabled need no guard. Besides disabling a control, guards may also set a control to an undefined or read-only state (par.undef, par.readOnly). Notifier commands can be associated with a control. Such a command has the signature of Dialog.NotifierProc, i.e., PROCEDURE Notifier (op, from, to: INTEGER) The purpose of a notifier command is to give a program the opportunity to customize the behavior of a control when its state is being modified by the user. For example, a status message may be shown when the user clicks onto a command button, and remove again when the user releases the button again (this can be done using the Dialog.ShowStatus procedure). Or, a notifier may perform some checks after each character typed into a text field. Another example are selection boxes: for each item / item range which is selected/deselected, a notification is produced. This makes it possible to e.g. update the count of currently selected items of this selection box. Examples: ObxControlsdocu the use of guards and notifiers ObxDialogdocu the use of selection boxes and combo boxes ObxButtonsdocu control not extended from Controls.Control ђ shows how to handle control properties ObxCtrls slider control, extended from Controls.Control ObxFldCtrls special-purpose text field control, extended from Controls.Control CONST opt0, opt1, opt2, opt3, opt4 Elements of a control property's valid set. They determine whether their corresponding optN fields are valid. CONST link Element of a control property's valid set. It determines whether the link field is valid. CONST label Element of a control property's valid set. It determines whether the label field is valid. CONST guard Element of a control property's valid set. It determines whether the guard field is valid. CONST notifier Element of a control property's valid set. It determines whether the notifier field is valid. CONST level Element of a control property's valid set. It determines whether the level field is valid. CONST default, cancel Aliases of opt0 and opt1, used for command buttons. CONST left, right, multiLine, password Aliases of opt0 to opt3 used for text entry fields CONST sorted Alias of opt0 used for list-structured controls (list/selection/combo boxes/tree control). CONST haslines Alias of opt1 used for tree control. CONST hasbuttons Alias of opt2 used for tree control. CONST atroot Alias of opt3 used for tree control. CONST foldericons Alias of opt4 used for tree control. TYPE Control (Views.View) ABSTRACT Base type for controls that can be linked to global variables or procedures via metaprogramming. Such a control has no separate model, the item to which it is linked takes the role of a model. item-: Meta.Item This item describes the variable or procedure to which the control is linked. disabled-, undef-, readOnly-: BOOLEAN The current temporary state of any control. customFont-: BOOLEAN This flag determines whether the control's font is taken from the operating system configuration, or from the font variable below. font-: Fonts.Font font # NIL -> customFont The control's custom font (customFont must be TRUE when font is used, i.e., when it is not NIL). label-: Dialog.String The control's label. prop-: Prop prop # NIL The control attributes of this control. PROCEDURE (c: Control) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY; PROCEDURE (c: Control) Externalize2- (VAR wr: Stores.Writer), NEW, EMPTY; PROCEDURE (c: Control) CopyFromSimpleView2- (source: Control), NEW, EMPTY; PROCEDURE (c: Control) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message) PROCEDURE (c: Control) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View) PROCEDURE (c: Control) HandlePropMsg2- (VAR p: Views.PropMessage) NEW, EMPTY Extension hooks for Internalize, Externalize, CopyFromSimpleView, HandleCtrlMsg, HandlePropMsg, HandlePropMsg. These methods are made final, and call their new empty extension hooks. PROCEDURE (c: Control) CheckLink- (VAR ok: BOOLEAN) NEW, EMPTY This hook procedure allows a control to check whether the item to which it is linked is acceptable. For example, a checkbox control would accept a link to a Boolean item, but not to an integer item. PROCEDURE (c: Control) Update- (f: Views.Frame; op, from, to: INTEGER) NEW, EMPTY Update the display of a control. For list-structured controls, the list is not changed. PROCEDURE (c: Control) UpdateList- (f: Views.Frame) NEW, EMPTY Update the display of a list-structured control, including a rebuilding of its list elements. TYPE Directory ABSTRACT Directory type for standard controls. PROCEDURE (d: Directory) NewPushButton (p: Prop): Control NEW, ABSTRACT Allocates and returns a new command button. PROCEDURE (d: Directory) NewCheckBox (p: Prop): Control NEW, ABSTRACT Allocates and returns a new check box. PROCEDURE (d: Directory) NewRadioButton (p: Prop): Control NEW, ABSTRACT Allocates and returns a new radio button. PROCEDURE (d: Directory) NewListBox (p: Prop): Control NEW, ABSTRACT Allocates and returns a new list box. PROCEDURE (d: Directory) NewSelectionBox (p: Prop): Control NEW, ABSTRACT Allocates and returns a new selection box. PROCEDURE (d: Directory) NewField (p: Prop): Control NEW, ABSTRACT Allocates and returns a new text field. PROCEDURE (d: Directory) NewUpDownField (p: Prop): Control NEW, ABSTRACT Allocates and returns a new text field with up and down arrows. PROCEDURE (d: Directory) NewDateField (p: Prop): Control NEW, ABSTRACT Allocates and returns a new date field. PROCEDURE (d: Directory) NewTimeField (p: Prop): Control NEW, ABSTRACT Allocates and returns a new time field. PROCEDURE (d: Directory) NewTreeControl (p: Prop): Control NEW, ABSTRACT Allocates and returns a new tree control. PROCEDURE (d: Directory) NewColorField (p: Prop): Control NEW, ABSTRACT Allocates and returns a new color field. PROCEDURE (d: Directory) NewComboBox (p: Prop): Control NEW, ABSTRACT Allocates and returns a new combo box. PROCEDURE (d: Directory) NewCaption (p: Prop): Control NEW, ABSTRACT Allocates and returns a new text caption. PROCEDURE (d: Directory) NewGroup (p: Prop): Control NEW, ABSTRACT Allocates and returns a new group. TYPE Prop ABSTRACT A property object describes various attributes of a control. There are messages which allow to poll or set the control properties of a control (-> Properties, -> Controllers). opt: ARRAY 5 OF BOOLEAN; Up to five Boolean options. Their meaning depends on the control's type. link: Dialog.String Name of the field or procedure to which control is linked, e.g., "TextCmds.find.replace". label: Dialog.String String label of the control. Ignored for fields, list boxes, selection boxes, combo boxes and tree controls. guard: Dialog.String Optional name of guard command. notifier: Dialog.String Optional name of notifier command. level: INTEGER only valid for radio buttons. Determines for which value of the bound variable the control is "on". TYPE DefaultsPref (Properties.Preference) This preference message allows to override the general defaults of a control's temporary state. disabled, undef, readOnly: BOOLEAN State of the control. It is being determined in three steps: 1) general default: disabled := ~c.item.Valid() undef := FALSE readOnly := c.item.vis = Meta.readOnly 2) control-specific default: by handling the DefaultsPref message, the general default can be overwritten. For example, with buttons: disabled := link = "" 3) guard call: If there is a guard, the guard result is used, otherwise the default. TYPE PropPref (Properties.Preference) Preference message which allows to specify the valid properties of the receiving control. {link, label, guard, notifier, customFont} is the default. By handling the PropPref message, elements of the valid set can be added or removed. valid: SET VAR dir-, stdDir-: Directory dir # NIL & stdDir # NIL Directories for the lookup of standard controls. VAR par-: Control Before a control's guard or notifier procedure is called, and before any controller message is sent to it, the control is assigned to par. Afterwards, it is reset to its previous value. This variable can be used in a command to determine the currently active control. PROCEDURE Notify (c: Control; f: Views.Frame; op, from, to: INTEGER) Used internally. PROCEDURE OpenLink (c: Control; p: Prop) Try to link control c according to control property p. Pre c # NIL 20 p # NIL 21 PROCEDURE Relink Force a re-evaluation of the control's link. PROCEDURE DepositPushButton Allocate a new command button using dir.NewPushButton and deposit it. PROCEDURE DepositCheckBox Allocate a new check box using dir.NewCheckBox and deposit it. PROCEDURE DepositRadioButton Allocate a new command button using dir.NewPushButton and deposit it. PROCEDURE DepositListBox Allocate a new radio button using dir.NewRadioButton and deposit it. PROCEDURE DepositSelectionBox Allocate a new selection box using dir.NewSelectionBox and deposit it. PROCEDURE DepositField Allocate a new field using dir.NewField and deposit it. PROCEDURE DepositUpDownField Allocate a new up-down-field using dir.NewUpDownField and deposit it. PROCEDURE DepositDateField Allocate a new field using dir.NewDateField and deposit it. PROCEDURE DepositTimeField Allocate a new field using dir.NewTimeField and deposit it. PROCEDURE DepositTreeControl Allocate a new tree control using dir.NewTreeControl and deposit it. PROCEDURE DepositColorField Allocate a new field using dir.NewColorField and deposit it. PROCEDURE DepositComboBox Allocate a new combo box using dir.NewComboBox and deposit it. PROCEDURE DepositCaption Allocate a new caption using dir.NewCaption and deposit it. PROCEDURE DepositGroup Allocate a new group using dir.NewGroup and deposit it. PROCEDURE DepositCancelButton Allocate a new command button using dir.NewPushButton and deposit it. The button's link property is initialized to "StdCmds.CloseDialog" and its cancel-property is set to TRUE. PROCEDURE SetDir (d: Directory) Assigns directory. SetDir is used in configuration routines. Pre d # NIL 20 Post stdDir' = NIL stdDir = d stdDir' # NIL stdDir = stdDir' dir = d
System/Docu/Controls.odc
Converters DEFINITION Converters; IMPORT Stores, Files, Dialog; CONST importAll = 0; TYPE Importer = PROCEDURE (f: Files.File; OUT s: Stores.Store); Exporter = PROCEDURE (s: Stores.Store; f: Files.File); Converter = POINTER TO RECORD next-: Converter; imp-, exp-: Dialog.String; storeType-: Stores.TypeName; fileType-: Files.Type; opts-: SET END; VAR list-: Converter; PROCEDURE Register (imp, exp: Dialog.String; storeType: Stores.TypeName; fileType: Files.Type; opts: SET); PROCEDURE Import (loc: Files.Locator; name: Files.Name; VAR conv: Converter; OUT s: Stores.Store); PROCEDURE Export (loc: Files.Locator; name: Files.Name; conv: Converter; s: Stores.Store); END Converters. Module Converters allows the definition and registration of file converters. A file converter is an importer which translates a file into a store (usually some view type), or an exporter which translates a store into a file, or it is both an importer and an exporter simultaneously. For a given pair (file type, store type) there may be several file converters registered, e.g. a text view may be translated into an ASCII file with or without carriage returns at the end of lines. Example: ObxConvdocu CONST importAll Set element for the opts set of procedure Register. It indicates that the importer is able to import all file types (e.g., an importer that displays the file contents as a hex dump). TYPE Importer This procedure type is the signature of an importer command. An importer translates a given file f into a store s. Pre f # NIL 20 f has correct type 22 Post s # NIL TYPE Exporter This procedure type is the signature of an exporter command. An exporter translates a given store s into the contents of a file f. File f is already set up as an empty new (i.e., writable) file. Pre s # NIL 20 f # NIL 21 f.Length() = 0 22 s has correct type 23 Post f.Length() >= 0 TYPE Converter A converter object represents a file converter. It consists of an import and an export command, one of which may be empty. A converter converts between a file and a store. next-: Converter Next converter in the list. Converters are sorted by their registration time: later registration means further back in the list. imp-, exp-: Dialog.String imp # "" OR exp # "" Strings for the import/export commands, e.g., "HostTextConv.ImportText" or "HostTextConv.ExportText". storeType-: Stores.TypeName exp # "" -> storeType # "" Store type of the converter, e.g., "TextViews.TextView". fileType-: Files.Type fileType # "" File type of the converter, e.g., "TXT". opts-: SET Set of options, e.g., {} or {importAll}. VAR list-: Converter List of registered converters. Converters are sorted by their registration time: later registration means further back in the list. The first element of the list, i.e., list, is always the document converter, i.e., the converter used for standard BlackBox document files. PROCEDURE Register (imp, exp: Dialog.String; storeType: Stores.TypeName; fileType: Files.Type; opts: SET) Register an importer which translates a file of type fileType into a store of type storeType (e.g., "TextViews.View"), an exporter which translates a store of type storeType into a file of type fileType, or both. imp is the name of an importer command, which must have the signature of Importer. exp is the name of an exporter command, which must have the signature of Exporter. opts allows to express a set of options; currently only the element importAll is defined. Normally, opts is empty. Register does not yet load the modules which contain the import/export commands. They are loaded only when needed. The standard document converter is already installed by the BlackBox core. Other converters may be installed in the Config module, e.g., converters for ASCII files, Unicode files, or picture files. Config is executed upon startup of BlackBox to allow the establishment of custom configurations, such as the set of available converters. As a result of Register, a new converter is appended to list, with fields corresponding to the parameters passed. For each registered importer or exporter, there optionally may be a corresponding string mapping; to make the display of a list of importers/exporters more user-friendly. For example, the importer "HostTextConv.ImportText" could be mapped to the more telling name "Ascii" (in the standard file open dialog). The mapping is done in the Strings file in the Rsrc directory of the importer's subsystem, e.g., there may be the following lines in the Host/Rsrc/Strings text: HostTextConv.ImportText Ascii HostTextConv.ExportText Ascii Pre imp # "" OR exp # "" 20 fileType # "" 21 PROCEDURE Import (loc: Files.Locator; name: Files.Name; VAR conv: Converter; OUT s: Stores.Store) Converts the contents of the file specified by (loc, name) into store s, using converter conv. Internally it calls the converter's import command. If conv = NIL, the first suitable converter in list is used and returned in the VAR parameter. Pre loc # NIL 20 name # "" 21 conv = NIL OR conv.imp # "" 22 File type of (loc, name) = converter's file type 23 PROCEDURE Export (loc: Files.Locator; name: Files.Name; conv: Converter; s: Stores.Store) Convert store s to a new file (loc, name) using converter conv. Internally it calls the converter's export command. Success or failure is reported in the locator's res field. Pre s # NIL 20 ~ s IS Stores.Alien 21 loc # NIL 22 name # "" 23 conv = NIL OR conv.exp # "" 24 TypeOf(s) = converter's store type 25
System/Docu/Converters.odc
Dates DEFINITION Dates; CONST monday = 0; tuesday = 1; wednesday = 2; thursday = 3; friday = 4; saturday = 5; sunday = 6; short = 0; long = 1; abbreviated = 2; plainLong = 3; plainAbbreviated = 4; TYPE Date = RECORD year, month, day: INTEGER END; Time = RECORD hour, minute, second: INTEGER END; PROCEDURE ValidDate (IN d: Date): BOOLEAN; PROCEDURE ValidTime (IN t: Time): BOOLEAN; PROCEDURE GetDate (OUT d: Date); PROCEDURE GetTime (OUT t: Time); PROCEDURE GetEasterDate (year: INTEGER; OUT d: Date); PROCEDURE DayOfWeek (IN d: Date): INTEGER; PROCEDURE Day (IN d: Date): INTEGER; PROCEDURE DayToDate (n: INTEGER; OUT d: Date); PROCEDURE DateToString (IN d: Date; format: INTEGER; OUT str: ARRAY OF CHAR); PROCEDURE TimeToString (IN t: Time; OUT str: ARRAY OF CHAR); END Dates. Module Dates provides basic procedures to work with dates. It covers the Julian calendar up to 10/4/1582 and the Gregorian calendar starting at 10/15/1582. Module Dates can deal with dates from 1/1/1 up to 12/31/9999. The types Date and Time are known to the framework and can be displayed by suitable controls. CONST monday, tuesday, wednesday, thursday, friday, saturday, sunday Possible return value of procedure DayOfWeek. CONST short, long, abbreviated, longPlain, abbreviatedPlain Possible value for parameter format of DateToString to specify the format. TYPE Date Date information. year: INTEGER 0001 <= year <= 9999 month: INTEGER 1 <= month <= 12 day: INTEGER 1 <= day <= 31 TYPE Time Time information. hour: INTEGER 0 <= hour <= 23 minute: INTEGER 0 <= minute <= 59 second: INTEGER 0 <= second <= 59 PROCEDURE ValidDate (IN d: Date): BOOLEAN Test whether d is a valid date according to the Julian (before 1582) or Gregorian (after 1582) calendar. Dates between 10/5/1582 and 10/14/1582 did not exist and are not valid. PROCEDURE ValidTime (IN t: Time): BOOLEAN Test whether time t is valid. PROCEUDRE GetDate (OUT d: Date) Get the current date. PROCEDURE GetTime (OUT t: Time) Get the current time. PROCEDURE GetEasterDate (year: INTEGER; OUT d: Date) Get the Easter date of year. Pre (year > 1582) & (year < 2300) 20 PROCEDURE DayOfWeek (IN d: Date): INTEGER Return the weekday of date d. Pre ValidDate(d) (not explicitly checked) Post result IN {monday .. sunday} PROCEDURE Day (d: Date): INTEGER; For date d, return the number of days since 1/1/1. Day(1/1/1) = 1. The difference between two dates in days can be computed with Day(d2) - Day(d1). Pre ValidDate(d) (not explicitly checked) Post (result > 0) & (result < 3652062) PROCEDURE DayToDate (n: INTEGER; OUT d: Date); Convert the number of days since 1/1/1 into a date. DayToDate(Day(d1), d2) => d1=d2 Pre (n > 0) & (n < 3652062) (not explicitly checked) Post ValidDate(d) & Day(d) = n PROCEDURE DateToString (IN d: Date; format: INTEGER; OUT s: ARRAY OF CHAR); Convert the date d into string s. The format of the conversion is specified through the operation system, usually depending on country and language. format example short 01/02/92 abbreviated Thu, Jan 2, 1992 long Thursday, January 2, 1992 plainAbbreviated Jan 2, 1992 plainLong January 2, 1992 Pre ValidDate(d) (not explicitly checked) format IN {short, abbreviated, long, plainAbbreviated, longAbbreviated} 20 PROCEDURE TimeToString (IN t: Time; OUT s: ARRAY OF CHAR); Convert the time t into string s. The format of the conversion is specified through the operating system. Pre ValidTime(t) (not explicitly checked)
System/Docu/Dates.odc
Dialog DEFINITION Dialog; IMPORT Files; CONST pressed = 1; released = 2; changed = 3; included = 5; excluded = 6; set = 7; ok = 1; yes = 2; no = 3; cancel = 4; windows32s = 11; windows95 = 12; windowsNT3 = 13; windowsNT4 = 14; windows2000 = 15; windows98 = 16; macOS = 21; macOSX = 22; linux = 30; tru64 = 40; firstPos = 0; lastPos = -1; persistent = TRUE; nonPersistent = FALSE; TYPE String = ARRAY 256 OF CHAR; List = RECORD index, len-: INTEGER; (VAR l: List) GetItem (index: INTEGER; OUT item: String), NEW; (VAR l: List) SetItem (index: INTEGER; IN item: ARRAY OF CHAR), NEW; (VAR l: List) SetLen (len: INTEGER), NEW; (VAR l: List) SetResources (IN key: ARRAY OF CHAR), NEW END; Selection = RECORD len-: INTEGER; (VAR s: Selection) Excl (from, to: INTEGER), NEW; (VAR s: Selection) GetItem (index: INTEGER; OUT item: String), NEW; (VAR s: Selection) In (index: INTEGER): BOOLEAN, NEW; (VAR s: Selection) Incl (from, to: INTEGER), NEW; (VAR s: Selection) SetItem (index: INTEGER; IN item: ARRAY OF CHAR), NEW; (VAR s: Selection) SetLen (len: INTEGER), NEW; (VAR s: Selection) SetResources (IN key: ARRAY OF CHAR), NEW END; Combo = RECORD item: String; len-: INTEGER; (VAR c: Combo) GetItem (index: INTEGER; OUT item: String), NEW; (VAR c: Combo) SetItem (index: INTEGER; IN item: ARRAY OF CHAR), NEW; (VAR c: Combo) SetLen (len: INTEGER), NEW; (VAR c: Combo) SetResources (IN key: ARRAY OF CHAR), NEW END; TreeNode = POINTER TO LIMITED RECORD (tn: TreeNode) Data (): ANYPTR, NEW; (tn: TreeNode) GetName (OUT name: String), NEW; (tn: TreeNode) IsExpanded (): BOOLEAN, NEW; (tn: TreeNode) IsFolder (): BOOLEAN, NEW; (tn: TreeNode) NofChildren (): INTEGER, NEW; (tn: TreeNode) SetData (data: ANYPTR), NEW; (tn: TreeNode) SetExpansion (expanded: BOOLEAN), NEW; (tn: TreeNode) SetName (name: String), NEW; (tn: TreeNode) ViewAsFolder (isFolder: BOOLEAN), NEW END; Tree = RECORD (VAR t: Tree) Child (node: TreeNode; pos: INTEGER): TreeNode, NEW; (VAR t: Tree) Delete (node: TreeNode): INTEGER, NEW; (VAR t: Tree) DeleteAll, NEW; (VAR t: Tree) Move (node, parent: TreeNode; pos: INTEGER), NEW; (VAR t: Tree) NewChild (parent: TreeNode; pos: INTEGER; name: String): TreeNode, NEW; (VAR t: Tree) Next (node: TreeNode): TreeNode, NEW; (VAR t: Tree) NofNodes (): INTEGER, NEW; (VAR t: Tree) NofRoots (): INTEGER, NEW; (VAR t: Tree) Parent (node: TreeNode): TreeNode, NEW; (VAR t: Tree) Prev (node: TreeNode): TreeNode, NEW; (VAR t: Tree) Select (node: TreeNode), NEW; (VAR t: Tree) Selected (): TreeNode, NEW END; Color = RECORD val: INTEGER END; Currency = RECORD val: LONGINT; scale: INTEGER END; Par = RECORD disabled: BOOLEAN; checked: BOOLEAN; undef: BOOLEAN; readOnly: BOOLEAN; label: String END; GuardProc = PROCEDURE (VAR par: Par); NotifierProc = PROCEDURE (op, from, to: INTEGER); Language = ARRAY 3 OF CHAR; LangNotifier = POINTER TO ABSTRACT RECORD (n: LangNotifier) Notify-, NEW, ABSTRACT END; VAR metricSystem: BOOLEAN; showsStatus: BOOLEAN; version: INTEGER; platform: INTEGER; appName: ARRAY 32 OF CHAR; language-: Language; user: ARRAY 32 OF CHAR; thickCaret: BOOLEAN; caretPeriod: INTEGER; commandLinePars: String; PROCEDURE Update (IN x: ANYREC); PROCEDURE UpdateBool (VAR x: BOOLEAN); PROCEDURE UpdateByte (VAR x: BYTE); PROCEDURE UpdateChar (VAR x: CHAR); PROCEDURE UpdateInt (VAR x: INTEGER); PROCEDURE UpdateLInt (VAR x: LONGINT); PROCEDURE UpdateList (IN x: ANYREC); PROCEDURE UpdateReal (VAR x: REAL); PROCEDURE UpdateSChar (VAR x: SHORTCHAR); PROCEDURE UpdateSInt (VAR x: SHORTINT); PROCEDURE UpdateSReal (VAR x: SHORTREAL); PROCEDURE UpdateSString (IN x: ARRAY OF SHORTCHAR); PROCEDURE UpdateSet (VAR x: SET); PROCEDURE UpdateString (IN x: ARRAY OF CHAR); PROCEDURE MapParamString (in, p0, p1, p2: ARRAY OF CHAR; OUT out: ARRAY OF CHAR); PROCEDURE MapString (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR); PROCEDURE RegisterLangNotifier (notifier: LangNotifier); PROCEDURE RemoveLangNotifier (notifier: LangNotifier); PROCEDURE SetLanguage (lang: Language; persistent: BOOLEAN); PROCEDURE ResetLanguage; PROCEDURE ShowParamMsg (IN str, p0, p1, p2: ARRAY OF CHAR); PROCEDURE ShowMsg (IN str: ARRAY OF CHAR); PROCEDURE ShowParamStatus (IN str, p0, p1, p2: ARRAY OF CHAR); PROCEDURE ShowStatus (IN str: ARRAY OF CHAR); PROCEDURE FlushMappings; PROCEDURE GetOK (IN str, p0, p1, p2: ARRAY OF CHAR; form: SET; OUT res: INTEGER); PROCEDURE GetIntSpec (defType: Files.Type; VAR loc: Files.Locator; OUT name: Files.Name); PROCEDURE GetExtSpec (defName: Files.Name; defType: Files.Type; VAR loc: Files.Locator; OUT name: Files.Name); PROCEDURE GetColor (in: INTEGER; OUT out: INTEGER; OUT set: BOOLEAN); PROCEDURE Call (IN cmd, errorMsg: ARRAY OF CHAR; OUT res: INTEGER); PROCEDURE Beep; PROCEDURE Notify (id0, id1: INTEGER; opts: SET); END Dialog. Module Dialog provides a variety of auxiliary services to simplify user interaction of a program. In particular, the output of messages, e.g. error messages, is supported. Furthermore, various base types are provided: List, Selection, Combo, Currency, Tree, etc. These types are known to the framework (more exactly: they are known to module Controls) and can be displayed by suitable controls, i.e. views which display not a normal model, but instead a variable of one of the mentioned types. CONST pressed This value may be passed to the op field of a notifier procedure. It notifies about a mouse-down event, i.e. the primary mouse key has just been pressed. CONST released This value may be passed to the op field of a notifier procedure. It notifies about a mouse-up event, i.e. the primary mouse key has just been released. CONST changed This value may be passed to the op field of a notifier procedure. It notifies about some change of an interactor field's value. For a Selection, the more specific constants included, excluded, or set are used. CONST included This value may be passed to the op field of a notifier procedure. It notifies about an inclusion of the range [from..to] in a Selection. Before the operation, this range was not included in the set. CONST excluded This value may be passed to the op field of a notifier procedure. It notifies about an exclusion of the range [from..to] in a Selection. Before the operation, this range was included in the set. CONST set This value may be passed to the op field of a notifier procedure. It notifies about a change in a Selection or SET, resulting in a set {from..to}. Any previous selection was cleared. CONST ok This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the OK button. CONST yes This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the Yes button. CONST no This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the No button. CONST cancel This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the Cancel button. CONST windows32s This is a possible value of variable platform. It indicates that BlackBox is running on Windows 3.1 (Win32s). This platform is not supported anymore. CONST windows95 This is a possible value of variable platform. It indicates that BlackBox is running on Windows 95, Windows 98, Windows 98SE, or Windows 98 ME. CONST windowsNT3 This is a possible value of variable platform. It indicates that BlackBox is running on Windows NT 3.x. CONST windowsNT4 This is a possible value of variable platform. It indicates that BlackBox is running on Windows NT 4.x. CONST windows2000 This is a possible value of variable platform. It indicates that BlackBox is running on Windows 2000 (formerly called Windows NT 5.0). CONST windows98 This is a possible value of variable platform. It indicates that BlackBox is running on one of the Windows 98 flavors (original Windows 98, Windows 98 SE, or Windows 98 ME). CONST macOS This is a possible value of variable platform. It indicates that BlackBox is running on Mac OS 7.x, 8.x, or 9.x. This platform is not supported anymore. CONST macOSX This is a possible value of variable platform. It indicates that BlackBox is running on Mac OS X. This platform is currently not supported. CONST linux This is a possible value of variable platform. It indicates that BlackBox is running on Linux. This platform is currently not supported. CONST tru64 This is a possible value of variable platform. It indicates that BlackBox is running on Compaq Tru64 Unix. This platform is currently not supported. CONST firstPos This value may be used in calls to Tree variables. It indicates that the first child of a node is requested. CONST lastPos This value may be used in calls to Tree variables. It indicates that the last child of a node is requested. CONST persistent This value may be used in calls to SetLanguage variables. It indicates that the setting is to be stored in a persistent registry and used again when BlackBox is started the next time. CONST nonPersistent This value may be used in calls to SetLanguage variables. It indicates that the setting is not to be stored in a persistent registry and thus will not affect BlackBox the next time it is started. TYPE String String type for various names to be displayed for the user, or to be entered by the user. TYPE List A list type defines a sub range of the INTEGER type, and an item name (a string) for each element of this range. All valid names can be enumerated by indexing from 0 upwards until len - 1. index: INTEGER index >= -1 & index < len Currently selected item of the list. If index = -1 then no element of the list is selected, which may happen e.g. if len = 0. len-: INTEGER len >= 0 Number of elements in the list. PROCEDURE (VAR l: List) SetLen (len: INTEGER) NEW Makes sure that the list has at least len elements available. If len > l.len, then the size of the existing list is increased as much as necessary. Note that SetItem also increases the list size if necessary, so SetLen is strictly necessary only to shorten the list. SetLen should be called when the size of the list to be constructed is known in advance, to avoid unnecessary allocations and copying in SetItem. If len > l.len, the existing l.len elements are not affected by SetLen. Pre len >= 0 20 Post l.len = len PROCEDURE (VAR l: List) SetItem (index: INTEGER; IN item: String) NEW Given an index index, the corresponding item name is set, or overwritten if it had been set earlier. If index >= l.len then the length is increased as much as necessary Pre index >= 0 20 item # "" 21 Post index <l.len' l.len = l.len' index >= l.len' l.len = index + 1 PROCEDURE (VAR l: List) GetItem (index: INTEGER; OUT item: String) NEW Given an index index, the corresponding item name is returned. If index is outside of the valid index range, the empty string "" is returned. Post name # "" iff index is in 0 .. l.len - 1 PROCEDURE (VAR l: List) SetResources (IN key: ARRAY OF CHAR) NEW Set up the item list according to entries in a string resource file. For example, key = "#System:colors" would build up an item list (red, green, blue), assuming that resource file System/Rsrc/Strings contains the entries key[0] red key[1] green key[2] blue Pre key # "" 20 TYPE Selection A selection is similar to a List, except that not only one value can be represented, but between 0 and an arbitrary number of values instead, i.e., a selection is a potentially large set of integers. In this context, the term "list" denotes all selectable elements, not only the selected ones. len-: INTEGER len >= 0 Number of elements in the list. PROCEDURE (VAR s: Selection) SetLen (len: INTEGER) NEW Makes sure that the list has at least len elements available. If len > l.len, then the size of the existing list is increased as much as necessary. Note that SetItem also increases the list size if necessary, so SetLen is strictly necessary only to shorten the list. SetLen should be called when the size of the list to be constructed is known in advance, to avoid unnecessary allocations and copying in SetItem. If len > l.len, the existing l.len elements are not affected by SetLen. Pre len >= 0 20 Post s.len = len PROCEDURE (VAR s: Selection) SetItem (index: INTEGER; IN item: String) NEW Given an index index, the corresponding item name is set, or overwritten if it had been set earlier. If index >= s.len then the length is increased as much as necessary Pre index >= 0 20 item # "" 21 Post index <s.len' s.len = s.len' index >= s.len' s.len = index + 1 PROCEDURE (VAR s: Selection) GetItem (index: INTEGER; OUT item: String) NEW Given an index index, the corresponding item name is returned. If index is outside of the valid index range, the empty string "" is returned. Post name # "" iff index is in 0 .. s.len - 1 PROCEDURE (VAR s: Selection) SetResources (IN key: ARRAY OF CHAR) NEW Set up the item list according to entries in a string resource file. For example, key = "#System:colors" would build up an item list (red, green, blue), assuming that resource file System/Rsrc/Strings contains the entries key[0] red key[1] green key[2] blue Pre key # "" 20 PROCEDURE (VAR s: Selection) Incl (from, to: INTEGER) NEW Include the range [from..to] intersected with [0..s.len - 1] into the selection. If from > to, this is regarded as an empty range. PROCEDURE (VAR s: Selection) Excl (from, to: INTEGER) NEW Exclude the range [from..to] intersected with [0..s.len - 1] into the selection. If from > to, this is regarded as an empty range. PROCEDURE (VAR s: Selection) In (index: INTEGER): BOOLEAN NEW Determine whether element index is in the selection. If index is outside of the range [0..s.len-1], then FALSE is returned. TYPE Combo A combo is similar to a List, except that it also accepts other values than the predefined ones of a list. Typically, a combo is represented on the screen as a combo box control. Such a control is a mixture of a list box or popup box (where one of the listed values can be chosen) and a text field (in which non-standard values can be typed in). item: String Current value of the combo. len-: INTEGER len >= 0 Number of elements in the list. PROCEDURE (VAR c: Combo) SetLen (len: INTEGER) NEW Makes sure that the list has at least len elements available. If len > l.len, then the size of the existing list is increased as much as necessary. Note that SetItem also increases the list size if necessary, so SetLen is strictly necessary only to shorten the list. SetLen should be called when the size of the list to be constructed is known in advance, to avoid unnecessary allocations and copying in SetItem. If len > l.len, the existing l.len elements are not affected by SetLen. Pre len >= 0 20 Post c.len = len PROCEDURE (VAR c: Combo) SetItem (index: INTEGER; IN item: String) NEW Given an index index, the corresponding item name is set, or overwritten if it had been set earlier. If index >= c.len then the length is increased as much as necessary Pre index >= 0 20 item # "" 21 Post index <c.len' c.len = c.len' index >= c.len' c.len = index + 1 PROCEDURE (VAR c: Combo) GetItem (index: INTEGER; OUT item: String) NEW Given an index index, the corresponding item name is returned. If index is outside of the valid index range, the empty string "" is returned. Post name # "" iff index is in 0 .. c.len - 1 PROCEDURE (VAR c: Combo) SetResources (IN key: ARRAY OF CHAR) NEW Set up the item list according to entries in a string resource file. For example, key = "#System:colors" would build up an item list (red, green, blue), assuming that resource file System/Rsrc/Strings contains the entries key[0] red key[1] green key[2] blue Pre key # "" 20 TYPE TreeNode Holds information about a node in a Tree. A TreeNode is part of one and only one Tree. PROCEDURE (tn: TreeNode) SetName (name: String) NEW Sets the name of tn. This is the text that is displayed when a Tree is bound to a tree control. PROCEDURE (tn: TreeNode) GetName (OUT name: String) NEW Retrieves the name of tn. PROCEDURE (tn: TreeNode) SetData (data: ANYPTR), NEW; Associates some data with node tn. This can be used to associate some application defined data with each node in a Tree. PROCEDURE (tn: TreeNode) Data (): ANYPTR NEW Returns the data associated with the tn by an earlier call to SetData. Returns NIL if no call to SetData has been made. PROCEDURE (tn: TreeNode) NofChildren (): INTEGER NEW Returns the number of immediate children to tn, i.e. all nodes, n, in tree, t, such that t.Parent(n) = tn. PROCEDURE (tn: TreeNode) SetExpansion (expanded: BOOLEAN) NEW Marks tn as expanded or collapsed. When the tree is displayed in a Tree Control the node corresponding to tn will be expanded or collapsed according to the value of expanded. PROCEDURE (tn: TreeNode) IsExpanded (): BOOLEAN NEW Returns TRUE if tn has been expanded by a Tree Control or by an explicit call to SetExpansion. Otherwise FALSE is returned. PROCEDURE (tn: TreeNode) ViewAsFolder (isFolder: BOOLEAN) NEW When a Tree Control has the option "Folder Icons" set, it automatically displays nodes that have children as folders. If node tn should be viewed as a folder even if it has no children, tn.ViewAsFolder(TRUE) should be called. If node tn has children it will be viewed as a folder even if tn.ViewAsFolder(FALSE) is called. ViewAsFolder only provides a way to make leafs look like folders, not the other way around. PROCEDURE (tn: TreeNode) IsFolder (): BOOLEAN NEW Returns TRUE if tn has children or if tn.ViewAsFolder(TRUE) has been called, otherwise it returns FALSE. TYPE Tree Defines a tree structure for storing TreeNodes. Normally a Tree is bound to a Tree Control in the user interface. Each tree can have several roots. It is possible to navigate up and down in the tree as well as between siblings. All operations on a tree t that require a TreeNode tn have the precondition that tn was created using t.NewChild and that tn is still part of t, i.e., tn is a node in t and not in any other tree and tn has not been deleted from t. Note:Tree controls look different under Windows NT and other Windows versions. The background of a tree control is not set to gray when the control is disabled or read only under Windows NT. See PlatformSpecificIssues for more information. PROCEDURE (VAR t: Tree) NofNodes (): INTEGER NEW Returns the total number of nodes in the tree. Post Returned value is greater than or equal to 0. PROCEDURE (VAR t: Tree) NofRoots (): INTEGER NEW The total number of roots in the tree. A node, tn, is a root if tn.Parent() = NIL. Post Returned value is greater than or equal to 0. PROCEDURE (VAR t: Tree) NewChild (parent: TreeNode; pos: INTEGER; name: String): TreeNode NEW Creates a new node in a tree. The new node is inserted at positions pos among the children of parent. If parent has no children or pos = firstPos then the new node is inserted as the first child of parent. If parent has fewer children than the value of pos or pos = lastPos, then the new node is inserted as the last child of parent. If parent is NIL then the new node is added as a new root in the tree at position pos. Pre (pos >= 0) OR (pos = firstPos) OR (pos = lastPos) Post t.NofNodes() = t.NofNodes()' + 1 PROCEDURE (VAR t: Tree) Delete (node: TreeNode): INTEGER NEW Removes node and all its children from the tree. Pre node # NIL Post t.NofNodes < t.NofNodes()' PROCEDURE (VAR t: Tree) DeleteAll NEW Removes all nodes from the tree. Post t.NofNodes() = 0 t.NofRoots() = 0 PROCEDURE (VAR t: Tree) Move (node, parent: TreeNode; pos: INTEGER) NEW Moves a node in a tree from its current place to the place specified by parent and pos. The interpretation of parent and pos is the same as in NewChild. Pre node # NIL (pos >= 0) OR (pos = firstPos) OR (pos = lastPos) Post t.NofNodes() = t.NofNodes()' PROCEDURE (VAR t: Tree) Parent (node: TreeNode): TreeNode NEW Returns the parent node of node. If node is a root then NIL is returned. Pre node # NIL PROCEDURE (VAR t: Tree) Child (node: TreeNode; pos: INTEGER): TreeNode NEW Returns the child at position pos of node. If node is NIL the root at position pos is returned. The constants firstPos and lastPos can be used to retrieve the first and last child of a node. If node has no children or if it has fewer children than the value of pos, then NIL is returned. Pre (pos >= 0) OR (pos = firstPos) OR (pos = lastPos) PROCEDURE (VAR t: Tree) Next (node: TreeNode): TreeNode NEW Returns the next node at the same level and with the same parent as node i.e. If node is at position pos then the returned node is at position pos + 1. If node is the last child of its parent then NIL is returned. Pre node # NIL PROCEDURE (VAR t: Tree) Prev (node: TreeNode): TreeNode NEW Returns the previous node at the same level and with the same parent as node. If node is at position pos then the returned node is at position pos - 1. If node is the first child of its parent then NIL is returned. Pre node # NIL PROCEDURE (VAR t: Tree) Select (node: TreeNode) NEW Makes node become the selected node in the tree. If node is NIL then there is no selection in the tree. PROCEDURE (VAR t: Tree) Selected (): TreeNode NEW Returns the selected node in a tree. If no node is currently selected then NIL is returned. TYPE Color Type for colors. val: INTEGER Current color value (in the same format as Ports.Color). TYPE Currency Type for money values. val: LONGINT The fixed-point value of the currency. The true value is val / 10^scale. scale: INTEGER scale > 0 Scale factor for val. For example, val = 12475 and scale = 2 is the representation for 124.75. If the currency denotes US dollars, then scale = 2 means that values can be displayed and entered with cent precision. A value of 3 would increase precision to 1/10 of a cent. TYPE Par Values of this parameter type are used to set up the names of menu items, and to disable or check menu items. A procedure of type GuardProc has a variable parameter of type Par. disabled: BOOLEAN Initially set to FALSE, this field can be set to TRUE by guard commands, to disable a menu item or a control. checked: BOOLEAN Initially set to FALSE, this field can be set to TRUE to show a check mark for a menu item. undef: BOOLEAN Initially set to FALSE, this field can be set to TRUE to set the undef state of a control. readOnly: BOOLEAN Initially set to FALSE, this field can be set to TRUE to set the readOnly state of a control. label: String For menu items or controls which show different labels depending on the current context, the current string can be deposited here. TYPE GuardProc = PROCEDURE (VAR par: Par) Menu guard or control guard commands must have this signature (or the extended version described below). They can set the fields of the par parameter to suitable values. Guard commands are called to determine the current state (in particular to find out whether the item is currently enabled) of a menu item or a control. For menu items, the guard commands are specified in the respective subsystem's /Rsrc/Menus text, or in System/Rsrc/Menus. Menu guard commands are called after the user clicks in the menu bar, and before the menu appears. For controls, the guard commands are specified in the inspector dialog which allows to set the various control properties. Control guard commands are called after the user interactively changed the state of a control, or after a program calls the procedure Update or UpdateList (or one of the other update procedures). Note that when the user clicks in a menu bar, possibly all menu guard commands may be executed. After the contents of an interactor has been changed and Update or UpdateList (or one of the other update procedures) has been called, all control guards are executed. This means two things. First, a guard command must be efficient. And second, the module which contains the guard is loaded as soon as the guard is evaluated for the first time. In this respect, menu commands are a certain pitfall during development: when a module has been unloaded, it is reloaded as soon as the user tries to execute a menu command. Guard commands may only modify fields of their par parameters, they must not modify any other state of the system, e.g., global variables. This means that the evaluation of a guard is similar to a function call without side-effects. Avoiding side-effects is particularly important since guards may be called by the framework at relatively unpredictable times. An extended version of GuardProc can be used as an alternative, with the following signature: PROCEDURE (n: INTEGER; VAR par: Par) An actual parameter for n must be a constant. TYPE NotifierProc = PROCEDURE (op, from, to: INTEGER) A notifier procedure must have one of the following signatures: PROCEDURE (op, from, to: INTEGER) PROCEDURE (n, op, from, to: INTEGER) Through calls of notification procedures, an application can be notified of manipulations of a control. op determines the kind of manipulation: op = pressed: A mouse-down event has occurred. op = released: A mouse-up event has occurred. op = changed: The value of a control (not bound to a SET or a Selection) has been changed. op = included: Range [from..to] has been included in a SET or a Selection. It wasn't included before. op = excluded: Range [from..to] has been excluded from a SET or a Selection. It was included before. op = set: Range [from..to] has been set in a SET or a Selection after clearing the previous selection. An actual parameter for n must be a constant. TYPE LangNotifier = POINTER TO ABSTRACT RECORD END; Objects of this type can be registered and unregistered using RegisterLangNotifier and RemoveLangNotifier. PROCEDURE (n: LangNotifier) Notify- NEW, ABSTRACT This method is called for all registered LangNotifiers whenever the language is changed. The order in which the language notifiers are called is undefined. VAR metricSystem: BOOLEAN This variable indicates whether sizes should be measured in metric units or in inches. VAR showsStatus: BOOLEAN Indicates whether status messages are currently displayed. If showsStatus = FALSE, the procedures ShowParamStatus and ShowStatus will have no visible effect. VAR version: INTEGER Indicates the current major version of BlackBox. 10 = version 1.0 11 = version 1.1 12 = version 1.2 13 = version 1.3 14 = version 1.4 15 = version 1.5 VAR platform: INTEGER Indicates on which host operating system the application is running. The currently supported platforms are: windows95, windowsNT3, windowsNT4, windows2000. VAR appName: ARRAY 32 OF CHAR Gives the name of the application program which is currently running; the default is "BlackBox". VAR language-: Language Current language in ISO 639 codes. See SetLanguage for more information about language support. VAR user: ARRAY 32 OF CHAR Login name of current user. Currently not used. VAR thickCaret: BOOLEAN Determines whether the text subsystem uses a Word-like thick caret or a normal thin caret. VAR caretPeriod: INTEGER Determines the blinking period that the text subsystem uses for caret blinking. The period is given in ticks (1/1000 second). The default is 500, i.e., half a second. VAR commandLinePars: String Command line parameters that have been passed when starting BlackBox. Variable commandLinePars contains the string entered on the command line following the /PAR option. The string can be specified enclosed in either single or double quotes. Quotes may be omitted if no white space is contained in the string. If no /PAR option is present on the command line, commandLinePars contains the empty string. Examples: /PAR test /PAR "parameter string" /PAR 'A string containing a " can be entered like this' PROCEDURE Update (IN x: ANYREC) This procedure should be called after one or several fields of the interactor x have been modified by a program (it is called automatically when a field has been modified interactively via a control). It causes all controls which are bound to fields of this interactor to be updated, and then guards are evaluated. PROCEDURE UpdateList (IN x: ANYREC) For list-structured controls (list boxes, selection boxes, combo boxes, tree controls), the lists are re-created. For efficiency reasons, this is not done after a call to Update. Note that UpdateList also includes the functionality of Update, thus for efficiency reasons you shouldn't call UpdateList(rec); Update(rec). PROCEDURE UpdateBool (VAR x: BOOLEAN) Similar to Update, except that it accepts a BOOLEAN parameter. PROCEDURE UpdateByte (VAR x: BYTE) Similar to Update, except that it accepts a BYTE parameter. PROCEDURE UpdateChar (VAR x: CHAR) Similar to Update, except that it accepts a CHAR parameter. PROCEDURE UpdateInt (VAR x: INTEGER) Similar to Update, except that it accepts an INTEGER parameter. PROCEDURE UpdateLInt (VAR x: LONGINT) Similar to Update, except that it accepts a LONGINT parameter. PROCEDURE UpdateReal (VAR x: REAL) Similar to Update, except that it accepts a REAL parameter. PROCEDURE UpdateSChar (VAR x: SHORTCHAR) Similar to Update, except that it accepts a SHORTCHAR parameter. PROCEDURE UpdateSInt (VAR x: SHORTINT) Similar to Update, except that it accepts a SHORTINT parameter. PROCEDURE UpdateSReal (VAR x: SHORTREAL) Similar to Update, except that it accepts a SHORTREAL parameter. PROCEDURE UpdateSString (IN x: ARRAY OF SHORTCHAR) Similar to Update, except that it accepts an ARRAY OF SHORTCHAR parameter. PROCEDURE UpdateSet (VAR x: SET) Similar to Update, except that it accepts a SET parameter. PROCEDURE UpdateString (IN x: ARRAY OF CHAR) Similar to Update, except that it accepts an ARRAY OF CHAR parameter. PROCEDURE MapParamString (in, p0, p1, p2: ARRAY OF CHAR; OUT out: ARRAY OF CHAR) Translates string in into string out. Strings of the form "#Subsystem:message" are translated if there is a corresponding "Strings" resource file for this subsystem (in the subsystem's "Rsrc" directory). Otherwise, the "#Subsystem:" prefix is stripped away, if there is no resource file. As an example, "#System:Cancel" may be translated to "Cancel" in the USA, and to "Abbrechen" in Germany; or to "Cancel" if the resource file or the appropriate entry is missing. Three additional input parameters can be spliced into the in parameter. These parameters are inserted where "^0", "^1", or "^2" occur in in. The parameters are not mapped, but merely substituted. MapParamString allows to remove country- and language-specific strings from a program source text, while at the same time providing a default string in the program source text such that the program always works, even if string resources are missing. PROCEDURE MapString (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR) This is a simplified version of MapParamString which has no additional input parameters. Except for performance, equivalent to: MapParamString(in, "", "", "", out) PROCEDURE RegisterLangNotifier (notifier: LangNotifier) Adds notifier to the list of LangNotifiers to be called every time the language is changed. Pre notifier # NIL 20 PROCEDURE RemoveLangNotifier (notifier: LangNotifier) Removes notifier from the list of LangNotifiers called every time the language is changed. Pre notifier # NIL, 20 PROCEDURE SetLanguage (lang: ARRAY OF CHAR; persistent: BOOLEAN) Sets the current language to lang, specified in ISO 639 code. This indicates that String resources are not read from the Rsrc-directory directly but from a subdirectory within the Rsrc-directory with the same name as the language code. It also sets the value of the global variable language. For example, if lang = "de" the String resources are read from the directory "Rsrc/de". If no such directory exists or the requested resource does not exist then the resources are read from the normal Rsrc-directory. An empty string implies that no particular language has been selected and resources are read from the Rsrc-directory. The persistent parameter indicates whether the setting is being used again when BlackBox is started the next time. persistent = nonPersistent causes a non-permanent change, i.e. the change is effective for this particular instance of BlackBox only. With persistent = persistent the change is registered in a registry and the language will be set immediately when BlackBox starts up next time. For information on how to do software that needs to be notified whenever the value of the global variable language is changing, see RegisterLangNotifier. Pre (lang = "") OR (LEN(lang$) = 2) 20 PROCEDURE ResetLanguage Resets the current language to the value of the last persistent setting. See also SetLanguage. PROCEDURE ShowParamMsg (IN str, p0, p1, p2: ARRAY OF CHAR) Presents str as a message to the user. The string str is mapped. The additional input parameters p0, p1, and p2 are not mapped. This procedure is used to present urgent messages to the user, typically alerting the user that some action has failed. It shouldn't be used for casual success messages. If a log window is present it is assumed that the user prefers these kind of messages in the log. Therefore the message is printed in the log if one exists, otherwise the message is displayed in a separately opened dialog box. Pre str # NIL 20 PROCEDURE ShowMsg PROCEDURE (IN str: ARRAY OF CHAR) This is a simplified version of ShowParamMsg which has no additional input parameters. Except for performance, equivalent to: ShowParamMsg(str, "", "", "") Pre str # NIL 20 PROCEDURE ShowParamStatus (IN str, p0, p1, p2: ARRAY OF CHAR) Presents str as a message to the user. The string str is mapped. The additional input parameters p0, p1, and p2 are not mapped. In contrast to ShowParamMsg, ShowParamStatus is used for shorter-lived and less urgent messages; e.g., messages produced and updated during a lengthy process. This procedure should not be used for vital messages, because on some platforms there may be no status area to display status messages, or the message mechanism may be switched off. These conditions are indicated by the global variable showsStatus. PROCEDURE ShowStatus PROCEDURE (IN str: ARRAY OF CHAR) This is a simplified version of ShowParamStatus which has no additional input parameters. Except for performance, equivalent to: ShowParamStatus(str, "", "", "") PROCEDURE FlushMappings String mappings are cached in internal tables for efficiency reasons. This procedure flushes all string mapping tables. This forces a reload of these tables from the string resource files as soon as the mappings are performed again. PROCEDURE GetOK (IN str, p0, p1, p2: ARRAY OF CHAR; form: SET; OUT res: INTEGER) Modal dialog Presents a mapped string, with the optional parameters p0 to p2, in a modal dialog box. form indicates the set of buttons of the dialog box. Only meaningful combinations are allowed: {ok} {ok, cancel} {yes, no} {yes, no, cancel} res indicates which button has been pressed by the user. Pre ((yes IN form) = (no IN form)) & ((yes IN form) # (ok IN form)) 20 Post res IN form PROCEDURE GetIntSpec (defType: Files.Type; VAR loc: Files.Locator; OUT name: Files.Name) Modal dialog Ask the user for a file specification (loc, name). defType indicates which file type is desired ("" stands for any file type; other types are platform-specific, e.g., "txt" for Windows Ascii files or "TEXT" for Mac OS Ascii files). loc # NIL indicates a valid file specification. Mac OS: loc is ignored. Pre defType = "" OR defType is legal type name on this platform 20 PROCEDURE GetExtSpec (defName: Files.Name; defType: Files.Type; VAR loc: Files.Locator; OUT name: Files.Name) Modal dialog Ask the user for a file specification for externalizing a file. defName is the default name presented to the user. defType is the file type which should be used as default type. loc # NIL indicates a valid file specification. Mac OS: loc is ignored. Pre defType = "" OR defType is legal type name on this platform 20 PROCEDURE GetColor (in: INTEGER; OUT out: LONGINT; OUT set: BOOLEAN) Modal dialog Ask the user for a color. in is the default color presented to the user. PROCEDURE Call (IN cmd, errorMsg: ARRAY OF CHAR; OUT res: INTEGER) Call executes a sequence of BlackBox commands denoted by cmd. If the corresponding modules are not yet loaded, Call tries to load them. If some error occurs, command execution terminates and res is returned with a value # 0. If errorMsg = "", Call does not display error messages. If errorMsg # "", Call displays errorMsg in case of an error, appended with a short description of the particular error having occurred. The syntax for commands with parameters is explained in the documentation of module StdInterpreter. PROCEDURE Beep Emit a short beep sound. PROCEDURE Notify Used internally.
System/Docu/Dialog.odc
Documents This module has a private interface, it is only used internally.
System/Docu/Documents.odc
Files DEFINITION Files; CONST exclusive = FALSE; shared = TRUE; dontAsk = FALSE; ask = TRUE; readOnly = 0; hidden = 1; system = 2; archive = 3; stationery = 4; TYPE Name = ARRAY 256 OF CHAR; Type = ARRAY 16 OF CHAR; FileInfo = POINTER TO RECORD next: FileInfo; name: Name; length: INTEGER; type: Type modified: RECORD year, month, day, hour, minute, second: INTEGER END; attr: SET END; LocInfo = POINTER TO RECORD next: LocInfo; name: Name; attr: SET END; Locator = POINTER TO ABSTRACT RECORD res: INTEGER; (l: Locator) This (IN path: ARRAY OF CHAR): Locator, NEW, ABSTRACT END; File = POINTER TO ABSTRACT RECORD type-: Type; (f: File) Length (): INTEGER, NEW, ABSTRACT; (f: File) NewReader (old: Reader): Reader, NEW, ABSTRACT; (f: File) NewWriter (old: Writer): Writer, NEW, ABSTRACT; (f: File) Flush, NEW, ABSTRACT; (f: File) Register (name: Name; type: Type; ask: BOOLEAN; OUT res: INTEGER), NEW, ABSTRACT; (f: File) Close, NEW, ABSTRACT; (f: File) InitType (type: Type), NEW END; Reader = POINTER TO ABSTRACT RECORD eof: BOOLEAN; (r: Reader) Base (): File, NEW, ABSTRACT; (r: Reader) Pos (): INTEGER, NEW, ABSTRACT; (r: Reader) SetPos (pos: INTEGER), NEW, ABSTRACT; (r: Reader) ReadByte (OUT x: BYTE), NEW, ABSTRACT; (r: Reader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER), NEW, ABSTRACT END; Writer = POINTER TO ABSTRACT RECORD (w: Writer) Base (): File, NEW, ABSTRACT; (w: Writer) Pos (): INTEGER, NEW, ABSTRACT; (w: Writer) SetPos (pos: INTEGER), NEW, ABSTRACT; (w: Writer) WriteByte (x: BYTE), NEW, ABSTRACT; (w: Writer) WriteBytes (IN x: ARRAY OF BYTE; beg, len: INTEGER), NEW, ABSTRACT END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) This (IN path: ARRAY OF CHAR): Locator, NEW, ABSTRACT; (d: Directory) Temp (): File, NEW, ABSTRACT; (d: Directory) New (loc: Locator; ask: BOOLEAN): File, NEW, ABSTRACT; (d: Directory) Old (loc: Locator; name: Name; shared: BOOLEAN): File, NEW, ABSTRACT; (d: Directory) Delete (loc: Locator; name: Name), NEW, ABSTRACT; (d: Directory) Rename (loc: Locator; old, new: Name; ask: BOOLEAN), NEW, ABSTRACT; (d: Directory) SameFile (loc0: Locator; name0: Name; loc1: Locator; name1: Name): BOOLEAN, NEW, ABSTRACT; (d: Directory) FileList (loc: Locator): FileInfo, NEW, ABSTRACT; (d: Directory) LocList (loc: Locator): LocInfo, NEW, ABSTRACT; (d: Directory) GetFileName (name: Name; type: Type; OUT filename: Name), NEW, ABSTRACT END; VAR dir-, stdDir-: Directory; docType-, objType-, symType-: Type; PROCEDURE SetDir (d: Directory); END Files. Most programmers never need to deal with files directly, instead they can use readers and writers (of module -> Stores) which are set up already by BlackBox! Module Files provides the abstractions necessary to handle most aspects of a hierarchical file system. A file is a sequence of bytes. Several access paths can be open simultaneously on the same file, possibly at different positions. A file and its access paths are modeled as separate data structures, namely as File and Reader/Writer. Where a statement applies both to readers and writers, the term "rider" will be used. An open rider is never closed explicitly, and an application can create as many riders as it needs. Figure 1: File with three riders Each file resides at some location in the file hierarchy (i.e., in a subdirectory). In BlackBox, a location is described by a locator object. A directory object provides a procedure which creates a locator, given a path name in the host platform's file name syntax. Most other directory operations take a locator as parameter, to find the specific subdirectory where the operation should be performed. For temporary files, a system-specific (implicit) location is used. Temporary files are used as scratch files, and cannot be registered in the file directory. Module Dialog provides further sources for file locators, via standard file dialogs. A file itself is specified by a location and a name. The name is the file's local name at the given location, i.e., it cannot be a path name. A directory object provides three procedures to access a file: New, Temp, and Old. New creates a new file. This file already has a particular location, but is anonymous, i.e., it has no name (yet). When the file's contents are written, the file can be registered under a given name, possibly replacing an already existing file which in turn becomes anonymous itself. File registration is an atomic action, which reduces the danger that a file is replaced by a new, but incomplete or corrupted, file. Anonymous files for which no more riders exist are automatically deleted by the garbage collector, at an appropriate time. Temp creates a temporary file. Such a file is never registered, and thus remains anonymous. Old looks up and opens an existing file, given its name and location. The file may either be opened in shared or in exclusive mode. "shared" means that it may be looked up and opened by several programs simultaneously, but that none may alter it (immutable file). Even if a file has been opened, its entry in the file directory is replaced when a new file is registered at the same location and under the same name. In this case, the old file remains accessible through the existing file readers. However, looking up this file with procedure Old yields the most recently registered file version. When no more riders on an older file version exist, the disk space occupied by the file is reclaimed by the garbage collector eventually. Opening a file in shared mode is the rule in BlackBox; opening a file in exclusive mode is an infrequent exception. "exclusive" means that at most one program may open a file. As long as the file is not closed again, other programs remain locked out, i.e., Old on the same file fails. An exclusively opened file may be modified (mutable file), which is useful for simple data base applications. Registering a new file under the same name as an exclusively opened file has the same effect as for shared files, i.e., the existing file becomes anonymous, and is garbage collected eventually. A file can be opened in exclusive mode, closed, and then be opened again in shared mode, for example. However, it can never be open in exclusive and in shared mode simultaneously. Open files for which no more riders exist are automatically closed by the garbage collector at an appropriate time. For files opened in exclusive mode, it is recommended that they be closed explicitly, in order to make them accessible again to other programs as early as possible. A directory object represents all accessible files (not just one subdirectory), independent of their location in the file hierarchy. There is exactly one file hierarchy. However, every BlackBox service may implement its own file directory object. Such an object represents exactly the same file hierarchy, but may provide different ways to look up files, e.g., by applying default search paths, or it may define a current directory relative to which path names are evaluated, etc. Files are typed. This means that each file has a type attribute which is a string, typically of length 3 (Windows) or 4 (Mac OS). On some platforms, the host file system knows about file types (Mac OS), while on others file types are simulated by using file suffixes as extensions (Windows). File types are useful to tell the system which operations are permissible on files and which aren't. For example, it is possible to install file converters (-> Converters) in BlackBox which translate between file and memory data structures. Example: ObxAsciidocu CONST exclusive, shared Values which can be passed to the Directory.Old.shared parameter, to determine whether a file should be opened in shared or in exclusive mode. CONST ask, dontAsk Values which can be passed to the Directory.New, Directory.Rename, and File.Register methods. CONST readOnly Possible value for FileInfo.attr. Indicates that the file can be accessed only for reading. CONST hidden Possible value for FileInfo.attr. Indicates that the file is not displayed when the user lists the available file. CONST system Possible value for FileInfo.attr. Indicates that the file belongs to the operating system. CONST archive Possible value for FileInfo.attr. Indicates that the file is an archive. CONST stationery Possible value for FileInfo.attr. Indicates that the file is a stationery (i.e., a template). TYPE Name String type for file names. TYPE Type String type for file type names. Under Windows, file type names correspond to the three-character file name extensions, e.g., file XYZ.txt has type txt. On Mac OS, the appropriate four-character file type name is used, e.g. an ASCII file xyz has file type TEXT. TYPE Locator ABSTRACT A file locator identifies a location in the file system. File locators are used internally, and sometimes in commands which operate on non-BlackBox files. File locators are extended internally. res: INTEGER Directory operations return their results in the locator's res field. The following result codes are predefined: res = 0 no error res = 1 invalid parameter (name or locator) res = 2 location or file not found res = 3 file already exists res = 4 write-protection res = 5 io error res = 6 access denied res = 7 illegal file type res = 8 cancelled res = 80 not enough memory res = 81 not enough system resources (disk space, file handles, etc.) A particular BlackBox implementation may return additional, platform-specific, error codes. These error codes always have negative values. PROCEDURE (l: Locator) This (IN path: ARRAY OF CHAR): Locator NEW, ABSTRACT This evaluates a relative path, starting from the location specified by l. Post result # NIL l.res = 0 no error result = NIL l.res = 1 invalid name l.res = 5 io error TYPE FileInfo This record represents information about a file. next: FileInfo Next entry in the list of file descriptors. No particular ordering is defined. name: Name name # "" The file's name. length: INTEGER length >= 0 The file's length in bytes. type: Type type # "" The file's type. modified: RECORD year, month, day, hour, minute, second: INTEGER END Date and time of most recent modification of the file. attr: SET Indicates various optional attributes of a file (readOnly, hidden, system, archive, stationery). TYPE LocInfo This record represents information about a location. next: LocInfo Next entry in the list of location descriptors. No particular ordering is defined. name: Name name # "" The file's name. attr: SET Indicates various optional attributes of a location (readOnly, hidden, system, archive). TYPE File ABSTRACT A file is a carrier for a linear sequence of bytes, which typically resides on a hard disk or similar device. Files are allocated by file directories. Files are used by commands which operate on non-BlackBox files. Files are extended internally. type-: Type type # "" This file's file type. PROCEDURE (f: File) Length (): INTEGER NEW, ABSTRACT Returns the current length of the file in bytes. Post result >= 0 PROCEDURE (f: File) NewReader (old: Reader): Reader NEW, ABSTRACT Returns a reader which has the appropriate type (for this file type). If old = NIL, then a new reader is allocated. If old # NIL and old has the appropriate type, old is returned. Otherwise, a new reader is allocated. The returned reader is connected to f, its eof field is set to FALSE, and its position is somewhere on the file. If an old reader is passed as parameter, the old position will be retained if possible. If an old reader is passed as parameter, it is the application's responsibility to guarantee that it is not in use anymore. Passing an unused old reader is recommended because it avoids unnecessary allocations. Post result # NIL ~result.eof old # NIL & old.Base() = f result.Pos() = old.Pos() old = NIL OR old.Base() # f result.Pos() = 0 PROCEDURE (f: File) NewWriter (old: Writer): Writer NEW, ABSTRACT Returns a writer which has the appropriate type (for this file type). If old = NIL, then a new writer is allocated. If old # NIL and old has the appropriate type, old is returned. Otherwise, a new writer is allocated. The returned writer is connected to f, and its position is somewhere on the file. If an old writer is passed as parameter, the old position will be retained if possible. If an old writer is passed as parameter, it is the application's responsibility to guarantee that it is not in use anymore. Passing an unused old writer is recommended because it avoids unnecessary allocations. Read-only files allow no writers at all. In such cases, NewWriter returns NIL. Post result # NIL old # NIL & old.Base() = f result.Pos() = old.Pos() old = NIL OR old.Base() # f result.Pos() = f.Length() result = NIL read-only file PROCEDURE (f: File) Flush NEW, ABSTRACT To guarantee consistency of the file, Flush should be called after the last writer operation. Superfluous calls of Flush have no effect. Close may call Flush internally. PROCEDURE (f: File) Register (name: Name; type: Type; ask: BOOLEAN; OUT res: INTEGER) NEW, ABSTRACT Register makes an anonymous file permanently available. If a file with the same name at the same location already exists, it is deleted first. If the deletion does not work, i.e. when the file is write protected, the parameter ask determines whether a platform specific error message is displayed or not. Pass either the constant ask or dontAsk. Register can be considered as an atomic action. Only files opened with procedure New may be registered. Trying to register a file opened with Old results in a precondition violation error. If an already existing file is deleted during Register, only its entry in the file directory is removed. The file's contents are still available to existing file riders. The space occupied by a file is reclaimed at an unspecified time after no more riders on it exist anymore. The file f and the riders operating on file f are not valid anymore after registering f, i.e., no more file or rider operations may be performed on it. This also implies that Register may only be executed once. However, the registered file can be retrieved by procedure Old again. Register may call Flush internally, and closes the file. Each registered file has a file type, which is passed to Register in the type parameter. Pre f is anonymous and not temporary 20 name # "" 21 name is a file name 22 Post res = 0 no error res = 1 invalid parameter (name or locator) res = 2 location or file not found res = 3 file already exists res = 4 write-protection res = 5 io error res = 6 access denied res = 7 illegal file type res = 8 cancelled res = 80 not enough memory res = 81 not enough system resources (disk space, file handles, etc.) A particular BlackBox implementation may return additional, platform-specific, error codes. These error codes always have negative values. PROCEDURE (f: File) Close NEW, ABSTRACT Closes an open file. Close does nothing if the file is not open or if it has been opened in "shared" mode. If a call to New or Old is not balanced by a call to Close, the Close is later performed automatically, at an unspecified time. If it is known that a file won't be used again, it is recommended to call its Close procedure. The file f and the riders operating on file f are not valid anymore after closing f, i.e., no more file or rider operations may be performed on it. However, the closed file can be retrieved and opened again by procedure Old. Close may call Flush internally. Close should (but need not necessarily) be called explicitly after a file is not needed anymore. PROCEDURE (f: File) InitType (type: Type) Initializes the file's type field. Pre type # "" 20 f.type = "" OR f.type = type 21 TYPE Reader ABSTRACT Reading access path to a file carrier. Readers are allocated by their base files. Readers are used by commands which read non-BlackBox files and operate at the byte level. Readers are extended internally. eof: BOOLEAN Set when it has been attempted to read the byte after the end of the file (by ReadByte or ReadBytes). Reset when the reader is generated or positioned. PROCEDURE (r: Reader) Base (): File NEW, ABSTRACT Returns the file to which the reader is currently connected. Post result # NIL PROCEDURE (r: Reader) Pos (): INTEGER NEW, ABSTRACT Returns the reader's current position. Post 0 <= result <= r.Base().Length() PROCEDURE (r: Reader) SetPos (pos: INTEGER) NEW, ABSTRACT Sets the reader's current position to pos and clears the eof flag. Pre pos >= 0 20 pos <= r.Base().Length() 21 Post r.Pos() = pos ~r.eof PROCEDURE (r: Reader) ReadByte (OUT x: BYTE) NEW, ABSTRACT Attempts to read the byte after the current position. If successful, it increments the position by one. If the current position (before reading) is at the end of the available data, i.e., Pos equals the carrier data's length, then r.eof is set. ReadByte internally may call SetPos. Post r.Pos()' < r.Base().Length() r.Pos() = r.Pos()' + 1 ~r.eof x = byte after r.Pos()' r.Pos()' = r.Base().Length() r.Pos() = r.Base().Length() r.eof x = 0H PROCEDURE (r: Reader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER) NEW, ABSTRACT Attempts to read len bytes after the current position. It increments the position by the number of bytes which have been read successfully. If reading is continued beyond the file's length, then r.eof is set. The data are transferred to the array x starting at element beg. ReadBytes internally may call SetPos. Pre beg >= 0 20 len >= 0 21 beg + len <= LEN(x) 22 Post r.Pos()' <= r.Base().Length() - len r.Pos() = r.Pos()' + len ~r.eof len bytes read after r.Pos()' and transferred into x r.Pos()' > r.Base().Length() - len r.Pos() = r.Base().Length() r.eof r.Base().Length() - r.Pos()' bytes read after r.Pos()' and transferred into x TYPE Writer ABSTRACT Writing access path to a file carrier. Writers are allocated by their base files. Writers are used by commands which write non-BlackBox files and operate at the byte level. Writers are extended internally. PROCEDURE (w: Writer) Base (): File NEW, ABSTRACT Returns the file to which the writer is currently connected. Post result # NIL PROCEDURE (w: Writer) Pos (): INTEGER NEW, ABSTRACT Returns the writer's current position. Post 0 <= result <= w.Base().Length() PROCEDURE (w: Writer) SetPos (pos: INTEGER) NEW, ABSTRACT Sets the writer's current position to pos. Pre pos >= 0 20 pos <= w.Base().Length() 21 Post w.Pos() = pos PROCEDURE (w: Writer) WriteByte (x: BYTE) NEW, ABSTRACT Writes a byte after the current position, then increments the current position. If the current position is at the end of the carrier data, the writer's length is incremented also. WriteByte internally may call SetPos. Post x written at w.Pos()' w.Pos() = w.Pos()' + 1 w.Pos()' < w.Base().Length()' w.Base().Length() = w.Base().Length()' x has overwritten old value after w.Pos()' w.Pos()' = w.Base().Length()' w.Base().Length() = w.Base().Length()' + 1 x was appended PROCEDURE (w: Writer) WriteBytes (IN x: ARRAY OF BYTE; beg, len: INTEGER) NEW, ABSTRACT Writes len bytes after the current position and increments the position accordingly. If necessary the stream's length is increased. The data are transferred from array x starting with element beg. WriteBytes internally may call SetPos. Pre beg >= 0 20 len >= 0 21 beg + len <= LEN(x) 22 Post len bytes transferred from variable x to carrier w.Pos() = w.Pos()' + len w.Pos()' + len <= w.Base().Length()' w.Base().Length() = w.Base().Length()' w.Pos()' + len > w.Base().Length()' w.Base().Length() = w.Pos()' + len TYPE Directory ABSTRACT Directory for the lookup in and manipulation of file directories. File directories are allocated by BlackBox. File directories are used by commands which operate on non-BlackBox files. File directories are extended internally. PROCEDURE (d: Directory) This (IN path: ARRAY OF CHAR): Locator NEW, ABSTRACT Returns a locator, given a path name in the host platform's syntax. This may perform some validity checks, e.g., whether the syntax of the name is correct. Passing the empty string yields a default location (typically the BlackBox directory itself). Post result # NIL result.res = 0 legal locator result.res # 0 illegal locator PROCEDURE (d: Directory) Temp (): File NEW, ABSTRACT Returns a temporary file. This file is anonymous, i.e., not registered in a directory. (In host file systems where anonymous files are not directly supported, they may appear under temporary names in a suitable subdirectory.) Registration is not possible on a temporary file. A temporary file always has both read and write capabilities (mutable file). Post result # NIL PROCEDURE (d: Directory) New (loc: Locator; ask: BOOLEAN): File NEW, ABSTRACT Returns a new file object (or NIL if this is not possible). This file is anonymous, i.e., not yet registered in the directory. (In host file systems where anonymous files are not directly supported, they may appear under temporary names in subdirectory loc.) If the file is registered later, it will appear in the subdirectory specified by loc. If loc indicates a location that does not yet exist, the necessary location(s) (i.e., directories) must be created first. Parameter ask determines whether the user is asked for the permission to do so. Pass either the constant ask or dontAsk. A new file always has both read and write capabilities (mutable file). If location loc does not exist, the user may be asked whether the location should be created (loc.res = 0) or not (loc.res = 8). Pre loc # NIL 20 Post result # NIL loc.res = 0 no error result = NIL loc.res = 1 invalid name loc.res = 2 location not found loc.res = 4 write-protection loc.res = 5 io error loc.res = 8 cancelled PROCEDURE (d: Directory) Old (loc: Locator; name: Name; shared: BOOLEAN): File NEW, ABSTRACT Looks up and opens a file with name name at location loc. It returns this file (or NIL if this is not possible). Parameter shared determines whether the returned file is in shared or in exclusive mode. A shared file provides read-only access. This means that several applications may read the file simultaneously, but it may not be modified. An exclusively opened file provides exclusive read and write access. This means that both read and write access are denied to any other application. Note however, that the application may pass on the file pointer to wherever it likes. The point is, another application cannot gain access to the file solely via the file directory, without cooperation of the application which currently has access. Moreover, "exclusive" access does not imply that only one rider may be active on the file. A file is usually opened in shared mode. To change its contents, a new file is generated and then registered under the old name. If only a small part of the data is actually changed, it may be more appropriate to use the exclusive mode instead, e.g. when implementing simple data bases. In this case, the file should be closed explicitly as soon as it isn't needed anymore. Pre loc # NIL 20 name # "" 21 Post result # NIL loc.res = 0 no error result = NIL loc.res = 1 invalid name loc.res = 2 location or file not found loc.res = 6 access denied PROCEDURE (d: Directory) Delete (loc: Locator; name: Name) NEW, ABSTRACT Deletes the file specified by loc and name. Pre loc # NIL 20 Post loc.res = 0 no error loc.res = 1 invalid parameter (name or locator) loc.res = 2 location or file not found loc.res = 4 write-protection loc.res = 5 io error PROCEDURE (d: Directory) Rename (loc: Locator; old, new: Name; ask: BOOLEAN) NEW, ABSTRACT Rename the file specified by loc and new to the local name new. If a file with name new already exists, it must be deleted first. Parameter ask determines whether the user is asked for the permission to do so. Pass either the constant ask or dontAsk. Pre loc # NIL 20 Post loc.res = 0 no error loc.res = 1 invalid parameter (locator or name) loc.res = 2 location or file not found loc.res = 3 file already exists loc.res = 4 write-protection loc.res = 5 io error PROCEDURE (d: Directory) SameFile (loc0: Locator; name0: Name; loc1: Locator; name1: Name): BOOLEAN; NEW, ABSTRACT Determines whether two (locator, name) pairs denote the same file. Pre loc0 # NIL 20 name0 # "" 21 loc1 # NIL 22 name1 # "" 23 PROCEDURE (d: Directory) FileList (loc: Locator): FileInfo NEW, ABSTRACT Returns information about the files at a given location. The result is a linear list of file descriptions, in no particular order. The procedure may alter loc.res. Pre loc # NIL 20 PROCEDURE (d: Directory) LocList (loc: Locator): LocInfo NEW, ABSTRACT Returns information about subdirectories at a given location. The result is a linear list of location (subdirectory) descriptions, in no particular order. The procedure may alter loc.res. Pre loc # NIL 20 PROCEDURE (d: Directory) GetFileName (name: Name; type: Type; OUT filename: Name) NEW, ABSTRACT Make a file name out of a file and its type. Windows: filename = name + "." + type Mac OS: filename = name VAR dir-, stdDir-: Directory (dir # NIL) & (stdDir # NIL) Directories for the lookup of files. PROCEDURE SetDir (d: Directory) Assigns directory. SetDir is used in configuration routines. Pre d # NIL 20 Post stdDir' = NIL stdDir = d stdDir' # NIL stdDir = stdDir' dir = d VAR docType-, objType-, symType-: Type (docType # NIL) & (objType # NIL) & (symType # NIL) File types of BlackBox documents (docType), of BlackBox code files (objType), and of BlackBox symbol files (symType).
System/Docu/Files.odc
Fonts DEFINITION Fonts; CONST mm = 36000; point = 12700; italic = 0; underline = 1; strikeout = 2; normal = 400; bold = 700; default = "*"; TYPE Typeface = ARRAY 64 OF CHAR; TypefaceInfo = POINTER TO RECORD next: TypefaceInfo; typeface: Typeface END; Font = POINTER TO ABSTRACT RECORD typeface-: Typeface; size-: INTEGER; style-: SET; weight-: INTEGER; (f: Font) Init (typeface: Typeface; size: INTEGER; style: SET; weight: INTEGER, NEW; (f: Font) GetBounds (OUT asc, dsc, w: INTEGER), NEW, ABSTRACT; (f: Font) StringWidth (IN s: ARRAY OF CHAR): INTEGER, NEW, ABSTRACT;; (f: Font) SStringWidth (IN s: ARRAY OF SHORTCHAR): INTEGER, NEW, ABSTRACT;; (f: Font) IsAlien (): BOOLEAN, NEW, ABSTRACT; END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) This (typeface: Typeface; size: INTEGER; style: SET; weight: INTEGER): Font, NEW, ABSTRACT; (d: Directory) Default (): Font, NEW, ABSTRACT; (d: Directory) TypefaceList (): TypefaceInfo, NEW, ABSTRACT END; VAR dir-, stdDir-: Directory; PROCEDURE SetDir (d: Directory); END Fonts. A font is a collection of character glyphs, i.e., a collection of distinct visual representations of characters. Visual representations of the same character may differ in size (e.g., 12 point vs. 16 point), style (e.g., plain vs. italic), typeface (e.g., Times vs. Helvetica), and weight (e.g., bold vs. normal). In BlackBox, most distances are measured in universal units. Several important distance values in these units are defined below: um = 36 micrometer mm = 36000 millimeter cm = 10 * mm centimeter m = 1000 * mm meter inch = 914400 inch Font sizes are measured in these universal units as well. The following values are used in connection with font sizes: point = 12700 1/72 inch (desktop publishing point) pica = 12636 0.351 mm didot = 13500 0.375 mm cicero = 163800 4.55 mm However, it should be mentioned that in modern typography the millimeter is the dominating measure, followed by the point as established in desktop publishing software. Module Fonts provides an abstract type Font, which mainly allows to measure the widths of characters and strings in universal units. These measures are completely device-independent. There is no device-specific information (e.g., character bitmap) in a font object. Font objects are only used for measurements and for the identification of a font. In the latter capacity, they can be passed as parameters to output routines. These output routines generate or access (device-dependent) character bitmaps in a way not specified by BlackBox. An application need not be aware whether font bitmaps are stored permanently ("bitmapped fonts") or whether they are generated on demand (using "outline fonts"). The meanings of two important font metrics, namely ascent and descent, are illustrated in the following diagram: Figure 1. Base Line, Ascent, Descent Characters of a word are placed side by side on a so-called base line. The ascent measures how far any character of a font may extend above the base line. The descent measures how far any character of a font may extend below the base line. The line spacing is the sum of ascent and descent. In BlackBox, the ascent must be large enough to accomodate oversized characters plus the minimal required distance between lines. Thus the ascent includes "line gap", "internal leading", and "external leading" as defined in other font models. Not all character codes need to be represented in a font. A character which is not represented in a font is displayed by a special "missing" symbol, e.g., an empty rectangle. Alternatively, BlackBox may use another font to display the character. It is often desirable to display text on the screen in a way which is similar to the way it is printed on paper. This is known as WYSIWYG display (What You See Is What You Get). However, there are several factors which make true WYSIWYG display a problematic proposition. The most fundamental problem is the large difference between today's screen and printer resolutions. Screens have typical spatial resolutions of about 70 to 100 dpi (dot per inch), while laser printers have resolutions of at least 300 dpi. This large difference forces the programmer to decide whether to tune text drawing for maximal legibility on screen, and thereby giving up device-independence and reducing the quality of hard copy, or to tune text drawing for maximal precision, which results in reduced legibility on screen due to rounding effects, or to give up the strict WYSIWYG requirements to some degree. All three solutions have their merits and problems, and all three solutions can be found in commercial word processors. Another problem for pure WYSIWYG display is that not all fonts are available on every machine. This means that a document containing a particular font cannot be shown correctly on a computer where this font is not installed. In order to make it possible to open a document containing such a missing font (without converting this font permanently) a mechanism is provided in BlackBox to temporarily substitute a place holder for a missing font, a so-called "alien" font. A font can be looked up in a font directory. Module Fonts provides an abstract type Directory for this purpose. If the directory cannot find a font, it creates an alien font object. An alien font internally uses an existing font for measurements and display, such that it can be used like any other font. An application which needs a font but has no preferences should use the default font. The default font is a system- or user-made choice out of one of the available fonts. The identity of the default font may vary over time. Fonts don't know about persistence. If you need to store a font description, you can use the procedures Views.ReadFont and Views.WriteFont. CONST mm, point These are the most important font size measures in universal units. CONST italic, underline, strikeout Three standard font attributes. CONST normal, bold Two major font weights. CONST default This "pseudo typeface" is a placeholder name for the current default typeface. In BlackBox, the user can configure the default typeface to his or her needs, and may change it at run-time. TYPE Typeface String type for the typeface name of a font. TYPE TypefaceInfo This type gives the name of an available typeface. Typeface info records are connected in a linear list. No ordering is defined. next: TypefacInfo Next element of the list. typeface: Typeface typeface # "" Name of this element's typeface. TYPE Font ABSTRACT This is the base type for fonts, which allows to identify fonts and to measure font information in universal units. Fonts are allocated by font directories. Fonts are used by models which contain formatted text, by views which draw text, and by commands which operate on text. Fonts are extended by BlackBox, internally. typeface-: Typeface typeface # "" The font's typeface name. size-: INTEGER size > 0 The font's size in universal units. style-: SET subset of {italic, underline, strikeout} The set of the font's style attributes. weight-: INTEGER 0 <= weigth <= 1000 A font's weight, i.e., the thickness of the strokes. PROCEDURE (f: Font) Init (typeface: Typeface; size: INTEGER; style: SET; weight: INTEGER) NEW Initialize font fields. Init is called by BlackBox, internally. Pre f.size = 0 20 font must not be initialized yet size > 0 21 style is subset of {italic, underline, strikeout} 22 0 <= weight <= 1000 23 Post f.fingerprint = fingerprint f.typeface = typeface & f.size = size & f.style = style & f.weight = weight PROCEDURE (f: Font) GetBounds (OUT asc, dsc, w: INTEGER) NEW, ABSTRACT Get font ascent, descent, and the width of the widest character in the font. Post asc >= 0 & dsc >= 0 & w >= 0 PROCEDURE (f: Font) StringWidth (IN s: ARRAY OF CHAR): INTEGER NEW, ABSTRACT Measures the width of a string in universal units. The string may contain arbitrary Unicode characters. StringWidth is used by models or views which need to format text. Pre s is terminated by 0X index trap Post result >= 0 width of string PROCEDURE (f: Font) SStringWidth (IN s: ARRAY OF SHORTCHAR): INTEGER NEW, ABSTRACT Measures the width of a short string in universal units. The string can only contain Latin-1 characters. SStringWidth is used by models or views which need to format text. Pre s is terminated by 0X index trap Post result >= 0 width of string PROCEDURE (f: Font) IsAlien (): BOOLEAN NEW, ABSTRACT Tells whether f is an alien font. An alien font is returned upon lookup of a font which cannot be found or generated. It is used as a place holder for the missing font. Alien fonts can be displayed, but their metrics are usually not the same as the correct font's metrics and their glyphs usually differ significantly from the correct font's glyphs. IsAlien is used in commands which inform users about the existence of alien fonts in a document. TYPE Directory ABSTRACT Directory for the lookup of fonts. Font directories are allocated by BlackBox. Font directories are used in models, views, and commands which need to specify a font for later use. Font directories are extended by BlackBox, internally. PROCEDURE (d: Directory) This (typeface: Typeface; size: INTEGER; style: SET; weight: INTEGER): Font NEW, ABSTRACT Returns the font with the attributes (typeface, size, style, weight). If the font information cannot be found or generated, an alien font is returned instead. An alien font has the requested attributes, even though a different font is actually used. If a font is requested which has the same attributes as another, previously requested font, the directory attempts to return the same font object (i.e., the same pointer value) as it did before. However, if a large number of fonts is used, it may happen that another font object is returned instead. Such an object has the same attributes and provides the same metrics and identical glyphs as the older font object. This is used to look up a font when specific font attributes are given. Pre size > 0 20 Post result # NIL result.typeface = typeface result.size = size result.style = style result.weight = weight PROCEDURE (d: Directory) Default (): Font NEW, ABSTRACT Returns the current default font. Default is used when a font is needed and no specific font attributes are desired. Post result # NIL PROCEDURE (d: Directory) TypefaceList (): TypefaceInfo NEW, ABSTRACT Returns information about the available typefaces. The result is a linear list of typeface names, in no particular order. VAR dir-, stdDir-: Directory dir # NIL & stdDir # NIL Directories for the lookup of fonts. PROCEDURE SetDir (d: Directory) Assigns directory. SetDir is used in configuration routines. Pre d # NIL 20 Post stdDir' = NIL stdDir = d stdDir' # NIL stdDir = stdDir' dir = d
System/Docu/Fonts.odc
GDI32 This module is obsolete; use the Win subsystem instead.
System/Docu/GDI32.odc
In DEFINITION In; VAR Done-: BOOLEAN; PROCEDURE Open; PROCEDURE Char (OUT ch: CHAR); PROCEDURE Int (OUT i: INTEGER); PROCEDURE LongInt (OUT l: LONGINT); PROCEDURE Real (OUT x: REAL); PROCEDURE Name (OUT name: ARRAY OF CHAR); PROCEDURE String (OUT str: ARRAY OF CHAR); END In. This module is provided for compatibility with the book "Programming in Oberon" by Reiser/Wirth. It is useful when learning the language. It is not recommended for use in production programs. VAR Done This variable indicates whether the most recent input operation has succeeded. It is set to TRUE by a successful Open, and set to FALSE by the first unsuccessful input operation. Once set to FALSE, it remains FALSE until the next Open. PROCEDURE Open This procedure opens the input stream. In BlackBox, the input stream is opened onto the target focus' text. If there is no target focus, or if it doesn't contain text, Done is set to FALSE. If there is a target focus containing text, the input stream is connected to the beginning of the text if there is no selection, otherwise to the beginning of the selection. Post Done input stream was opened successfully ~Done input stream couldn't be opened PROCEDURE Char (OUT ch: CHAR) If Done holds, this procedure attempts to read a character, otherwise it does nothing. Post Done ch has been read ~Done no character could be read PROCEDURE Int (OUT i: INTEGER) If Done holds, this procedure attempts to read an integer, otherwise it does nothing. Post Done i has been read ~Done no integer could be read PROCEDURE LongInt (OUT l: LONGINT) If Done holds, this procedure attempts to read a long integer, otherwise it does nothing. Post Done l has been read ~Done no long integer could be read PROCEDURE Real (OUT x: REAL) If Done holds, this procedure attempts to read a real number, otherwise it does nothing. Post Done x has been read ~Done no real number could be read PROCEDURE Name (OUT name: ARRAY OF CHAR) If Done holds, this procedure attempts to read a name, otherwise it does nothing. A name is a sequence of legal Component Pascal identifiers concatenated by periods, e.g., "Dialog.Beep". Post Done x has been read ~Done no name could be read PROCEDURE String (OUT str: ARRAY OF CHAR) If Done holds, this procedure attempts to read a string, otherwise it does nothing. A string is a sequence of characters delimited by white space (i.e., blanks, carriage returns, tabulators) or by double quotes ("). Post Done str has been read ~Done no string could be read
System/Docu/In.odc
Init This module has a private interface, it is only used internally.
System/Docu/Init.odc
Integers DEFINITION Integers; IMPORT Files; TYPE Integer = POINTER; PROCEDURE Abs (x: Integer): Integer; PROCEDURE Compare (x, y: Integer): INTEGER; PROCEDURE ConvertFromString (IN s: ARRAY OF CHAR; OUT x: Integer); PROCEDURE ConvertToString (x: Integer; OUT s: ARRAY OF CHAR); PROCEDURE Difference (x, y: Integer): Integer; PROCEDURE Digits10Of (x: Integer): INTEGER; PROCEDURE Entier (x: REAL): Integer; PROCEDURE Externalize (w: Files.Writer; x: Integer); PROCEDURE Float (x: Integer): REAL; PROCEDURE GCD (x, y: Integer): Integer; PROCEDURE Internalize (r: Files.Reader; OUT x: Integer); PROCEDURE Long (x: LONGINT): Integer; PROCEDURE Power (x: Integer; exp: INTEGER): Integer; PROCEDURE Product (x, y: Integer): Integer; PROCEDURE QuoRem (x, y: Integer; OUT quo, rem: Integer); PROCEDURE Quotient (x, y: Integer): Integer; PROCEDURE Remainder (x, y: Integer): Integer; PROCEDURE Short (x: Integer): LONGINT; PROCEDURE Sign (x: Integer): INTEGER; PROCEDURE Sum (x, y: Integer): Integer; PROCEDURE ThisDigit10 (x: Integer; exp10: INTEGER): CHAR; END Integers. Module Integer implements an abstract data type Integer to represent arbitrary precision integer numbers. It also offers the most important arithmetical operations on such numbers and a variety of conversion operations. The arithmetical operations include summation, multiplication, powering, computations of quotients, remainders, and greatest common divisors. With respect to assignment and procedure parameters, variables of type Integers.Integer can be used in the same way as variables of the numerical types built into the language. Of course, to perform operations with such variables, special procedures have to be called. The "operators" +, -, *, DIV, MOD, etc. cannot be used . The same holds for comparisons. Note: Though the language syntax allows two variables of type Integers.Integer to be compared using the "="-operator, the result is not what you would expect. Instead of values, pointers to objects representing the values are compared. Thus, the comparison may yield the result FALSE, although the values of the variables are equal. Hence, use the Integers.Compare-function instead of the "="-operator. The individual values are represented by objects on the heap rather than the stack. Clients of module Integers will use references to these objects only. Values of existing objects cannot be changed (they are immutable). Thus, copying such values is completely safe; it is not possible to inadvertantly change a value via an alias pointer. The space needed to represent a small integer is that of the minimum object size of your Component Pascal implementation. To represent a large value, the required memory is proportional to the number of decimal digits in the value. Each of the operations offered by module Integers allocates memory necessary to represent its result, but no extra memory will be allocated beyond that (space for intermediate results is allocated on the stack). Examples of client modules: ObxFactdocu calculate factorials ObxFractdocu calculatior/simplifier for rational numbers TYPE Integer Opaque Opaque type to represent integers of arbitrary size. Values of this type are allocated on the heap. The required memory size depends on the number of decimals to be represented. The objects are immutable. PROCEDURE Long (x: LONGINT): Integer Long generates a new Integer from a LONGINT variable. PROCEDURE Entier (x: REAL): Integer Entier generates a new Integer from a REAL variable. Entier rounds similar to the ENTIER-function of the Component Pascal programming language; both implement the floor-function. PROCEDURE Short (x: Integer): LONGINT Short converts a value of type Integer into a LONGINT. Pre MIN(LONGINT) <= x <= MAX(LONGINT) PROCEDURE Float (x: Integer): REAL Float converts a value of type Integer into a REAL. Pre MIN(REAL) <= x <= MAX(REAL) PROCEDURE Sum (x, y: Integer): Integer PROCEDURE Difference (x, y: Integer): Integer PROCEDURE Product (x, y: Integer): Integer PROCEDURE Quotient (x, y: Integer): Integer PROCEDURE Remainder (x, y: Integer): Integer PROCEDURE QuoRem (x, y: Integer; VAR quo, rem: Integer) PROCEDURE Power (x: Integer; exp: INTEGER): Integer PROCEDURE GCD (x, y: Integer): Integer PROCEDURE Abs (x: Integer): Integer The arithmetic operations Sum, Difference, Product, Quotient, Remainder, Power, GCD (= greatest common divisor), and Abs (= absolute value) are defined as to be expected. In particular, Quotient and Remainder are defined according the Component Pascal rules for DIV and MOD. If both quotient and remainder need to be computed, for performance reasons the procedure QuoRem should be called instead of the individual functions Quotient and Remainder. Power requires the exponent to be non-negative. Pre (Quotient, Remainder, QuoRem) y # 0 Pre (Power) exp >= 0 PROCEDURE Compare (x, y: Integer): INTEGER Compares the values of x and y. With this function, all comparison relations can be built: to compute the value of (x op y) write (Compare(x, y) op 0), where op is one of =, #, <, <=, >, >=. Post x < y result < 0 x = y result = 0 x > y result > 0 PROCEDURE Sign (x: Integer): INTEGER The sign of x. Post x > 0 result = 1 x = 0 result = 0 x < 0 result = -1 PROCEDURE Digits10Of (x: Integer): INTEGER The number of decimal digits needed to represent x. Exception: for x = 0 the result is the value 0. PROCEDURE ThisDigit10 (x: Integer; exp10: INTEGER): CHAR This Digit10 returns a single decimal digit as a character. Pre exp10 >= 0 20 Post "0" <= result <= "9" exp10 >= Digits10Of(x) result = "0" PROCEDURE ConvertFromString (IN s: ARRAY OF CHAR; OUT x: Integer) PROCEDURE ConvertToString (x: Integer; OUT s: ARRAY OF CHAR) ConvertFromString and ConvertToString are used to read an Integer from a string resp. to write an Integer to a string. ConvertToString requires that the string is long enough to represent the Integer. Pre (ConvertToString) (Sign(x) >= 0) & (LEN(s) >= Digits10Of(x) + 1) OR (Sign(x) < 0) & (LEN(s) >= Digits10Of(x) + 2) PROCEDURE Internalize (r: Files.Reader; OUT x: Integer) PROCEDURE Externalize (w: Files.Writer; x: Integer) Internalize and Externalize are used to read from resp. to write to files.
System/Docu/Integers.odc
Kernel This module has a private interface, it is only used internally.
System/Docu/Kernel.odc
KERNEL32 This module is obsolete; use the Win subsystem instead.
System/Docu/KERNEL32.odc
Log This module has a private interface, it is only used internally.
System/Docu/Log.odc
Math DEFINITION Math; PROCEDURE Pi (): REAL; PROCEDURE Eps (): REAL; PROCEDURE Sqrt (x: REAL): REAL; PROCEDURE Exp (x: REAL): REAL; PROCEDURE Ln (x: REAL): REAL; PROCEDURE Log (x: REAL): REAL; PROCEDURE Power (x, y: REAL): REAL; PROCEDURE IntPower (x: REAL; n: INTEGER): REAL; PROCEDURE Sin (x: REAL): REAL; PROCEDURE Cos (x: REAL): REAL; PROCEDURE Tan (x: REAL): REAL; PROCEDURE ArcSin (x: REAL): REAL; PROCEDURE ArcCos (x: REAL): REAL; PROCEDURE ArcTan (x: REAL): REAL; PROCEDURE ArcTan2 (y, x: REAL): REAL; PROCEDURE Sinh (x: REAL): REAL; PROCEDURE Cosh (x: REAL): REAL; PROCEDURE Tanh (x: REAL): REAL; PROCEDURE ArcSinh (x: REAL): REAL; PROCEDURE ArcCosh (x: REAL): REAL; PROCEDURE ArcTanh (x: REAL): REAL; PROCEDURE Sign (x: REAL): REAL; PROCEDURE Floor (x: REAL): REAL; PROCEDURE Ceiling (x: REAL): REAL; PROCEDURE Trunc (x: REAL): REAL; PROCEDURE Frac (x: REAL): REAL; PROCEDURE Round (x: REAL): REAL; PROCEDURE Mantissa (x: REAL): REAL; PROCEDURE Exponent (x: REAL): INTEGER; PROCEDURE Real (m: REAL; e: INTEGER): REAL; END Math. Module Math is a basic library for numerical computations. It offers the most frequently used functions and constants. For some additional functions, a transformation in terms of functions available in module Math is given below. Constants PROCEDURE Pi (): REAL Returns an approximation of the value of pi. Post result = 3.141592... PROCEDURE Eps (): REAL Returns the machine epsilon for REAL. The machine epsilon eps is the smallest floating point number such that the sum 1.0+eps can be represented exactly in a REAL variable. Usually, the machine epsilon is 2-m where m is the number of digits used to represent the mantissa of a floating point number. Note, that Eps() is not necessarily the smallest floating point number with the property that its sum with 1.0 is greater than 1.0, and note also, that most floating point processors offer a higher internal precision than what can be represented within REAL variables. Powers and logarithms PROCEDURE Sqrt (x: REAL): REAL Returns the square root of x. Pre x >= 0.0 20 Post result >= 0.0 x = INF result = INF PROCEDURE Exp (x: REAL): REAL Returns ex. Post result > 0.0 x = INF result = INF x = -INF result = 0.0 PROCEDURE Ln (x: REAL): REAL Returns the natural logarithm of x. Pre x >= 0.0 20 Post x = 0.0 result = -INF x = INF result = INF PROCEDURE Log (x: REAL): REAL Returns the logarithm to the basis 10 of x. Pre x >= 0.0 Post x = 0.0 result = -INF x = INF result = INF PROCEDURE Power (x, y: REAL): REAL Returns xy. Pre x >= 0.0 20 x # 0.0 OR y # 0.0 21 x # INF OR y # 0.0 22 x # 1.0 OR ABS(y) # INF 23 Post x = 0.0 & y < 0.0 result = INF x = 0.0 & y > 0.0 result = 0.0 x = INF & y > 0.0 result = INF x = INF & y < 0.0 result = 0.0 x > 1.0 & y = INF result = INF x > 1.0 & y = -INF result = 0.0 x < 1.0 & y = INF result = 0.0 x < 1.0 & y = -INF result = INF PROCEDURE IntPower (x: REAL; n: INTEGER): REAL Returns xn. The procedure is optimized for integer values of n. IntPower(0, 0) yields 1. If the result is too large, INF is returned. Trigonometric and hyperbolic functions The arguments for all trigonometric and hyperbolic functions must be given in radians, and the inverse trigonometric and hyperbolic functions are calculated in radians (1 radian = 180/pi degrees). At the end of this section, a transformation table for additional trigonometric and hyperbolic functions is given which do not belong to the interface of the Math module, but which can easily be written in terms of the exported functions. PROCEDURE Sin (x: REAL): REAL Returns the sine of x. Pre ABS(x) # INF 20 Post -1.0 <= result <= 1.0 PROCEDURE Cos (x: REAL): REAL Returns the cosine of x. Pre ABS(x) # INF 20 Post -1.0 <= result <= 1.0 PROCEDURE Tan (x: REAL): REAL Returns the tangent of x. The Tan can be computed for all possible REAL arguments except INF. Pre ABS(x) # INF 20 PROCEDURE ArcSin (x: REAL): REAL Returns the arcus sine of x. Pre -1.0 <= x <= 1.0 20 Post -pi/2.0 <= result <= pi/2.0 PROCEDURE ArcCos (x: REAL): REAL Returns the arcus cosine of x. Pre -1.0 <= x <= 1.0 20 Post 0.0 <= result <= pi PROCEDURE ArcTan (x: REAL): REAL Returns the arcus tangent of x. Post -pi/2.0 <= result <= pi/2.0 x = INF result = pi/2.0 x = -INF result = -pi/2.0 PROCEDURE ArcTan2 (y, x: REAL): REAL Returns the quadrant-correct principal value of the argument of the complex number x + iy in the range (-pi, pi]. Pre y # 0 OR x # 0 20 ABS(y) # INF OR ABS(x) # INF 21 Post -pi < result <= pi ABS(y) # INF & x = INF result = 0 y = INF & ABS(x) # INF result = pi/2.0 ABS(y) # INF & x = -INF result = pi y = -INF & ABS(x) # INF result = -pi/2.0 PROCEDURE Sinh (x: REAL): REAL Returns the hyperbolic sine of x. Post x = INF result = INF x = -INF result = -INF PROCEDURE Cosh (x: REAL): REAL Returns the hyperbolic cosine of x. Post 1.0 <= result x = INF result = INF x = -INF result = INF PROCEDURE Tanh (x: REAL): REAL Returns the hyperbolic tangent of x. Post -1.0 <= result <= 1.0 x = INF result = 1.0 x = -INF result = -1.0 PROCEDURE ArcSinh (x: REAL): REAL; Returns the inverse hyperbolic sine of x. Post x = INF result = INF x = -INF result = -INF PROCEDURE ArcCosh (x: REAL): REAL; Returns the inverse hyperbolic cosine of x. Pre 1.0 <= x 20 Post 0.0 <= result x = INF result = INF PROCEDURE ArcTanh (x: REAL): REAL; Returns the inverse hyperbolic tangent of x. Pre -1.0 <= x <= 1.0 20 Post x = 1.0 result = INF x = -1.0 result = -INF Below you find the definition of additional trigonometric and hyperbolic functions in terms of the exported functions. Their pre and post conditions can be induced from the pre and post conditions of the involved functions. Cot (x) = 1.0 / Math.Tan(x) Csc (x) = 1.0 / Math.Sin(x) Sec (x) = 1.0 / Math.Cos(x) ArcCot (x) = Math.Pi() / 2.0 - Math.ArcTan(x) ArcCsc (x) = Math.ArcSin(1.0 / x) ArcSec (x) = Math.ArcCos(1.0 / x) Coth (x) = 1.0 / Math.Tanh(x) Csch (x) = 1.0 / Math.Sinh(x) Sech (x) = 1.0 / Math.Cosh(x) ArcCoth (x) = Math.ArcTanh(1.0 / x) ArcCsch (x) = Math.ArcSinh(1.0 / x) ArcSech (x) = Math.ArcCosh(1.0 / x) Miscellaneous functions You could easily implement the functions Sign, Floor, Ceiling, Trunc, Frac, and Round yourself, using the ENTIER standard function. They are provided here for convenience, and in versions which return REAL typed results, so that no conversions between reals and integers become necessary if they are used in real expressions. PROCEDURE Sign (x: REAL): REAL Returns the sign of x, that is 1.0 if x > 0.0, -1.0 if x < 0.0 and 0.0 if x = 0.0. Post result IN {-1.0, 0.0, 1.0} PROCEDURE Floor (x: REAL): REAL Returns the greatest integer less than or equal to x. This function is identical to ENTIER, except that it returns a REAL type value. Post x = INF result = INF x = -INF result = -INF PROCEDURE Ceiling (x: REAL): REAL Returns the smallest integer greater than or equal to x. Post x = INF result = INF x = -INF result = -INF PROCEDURE Trunc (x: REAL): REAL Trunc truncates its argument to the next nearest integer towards zero. Post x = INF result = INF x = -INF result = -INF PROCEDURE Frac (x: REAL): REAL Frac is the fractional part of the argument. The following equation holds: x = Trunc(x) + Frac(x). Pre x # INF & x # -INF 20 PROCEDURE Round (x: REAL): REAL Same as Floor(x + 0.5). PROCEDURE Mantissa (x: REAL): REAL Returns the mantissa of x. Post 1.0 <= ABS(result) < 2.0 OR result = 0.0 x = INF result = 1.0 x = -INF result = -1.0 x = not-a-number ABS(result) > 1.0 PROCEDURE Exponent (x: REAL): INTEGER Returns the exponent of x such that x = Mantissa(x) * 2Exponent(x). If x represents INF or if x is not-a-number, then MAX(INTEGER) is returned. PROCEDURE Real (m: REAL; e: INTEGER): REAL Returns m * 2e. If the argument e is MAX(INTEGER), then INF or not-a-number is returned where INF is returned if m = 1.0 and not-a-number otherwise. Thus for any real x the equation x = Real(Mantissa(x), Exponent(x)) holds. Note: the normal arithmetic operations of the language Component Pascal, and the other operations implemented in this module, never produce the IEEE not-a-number value. Note: Real(0, 0) = 0. Pre (1.0 <= ABS(m) < 2.0) OR (m = 0.0) 20 Post m = 0.0 result = 0.0
System/Docu/Math.odc
Mechanisms This module has a private interface, it is only used internally.
System/Docu/Mechanisms.odc
Meta DEFINITION Meta; CONST undef = 0; typObj = 2; varObj = 3; procObj = 4; fieldObj = 5; modObj = 6; boolTyp = 1; sCharTyp = 2; charTyp = 3; byteTyp = 4; sIntTyp = 5; intTyp = 6; longTyp = 10; sRealTyp = 7; realTyp = 8; setTyp = 9; anyRecTyp = 11; anyPtrTyp = 12; procTyp = 16; recTyp = 17; arrTyp = 18; ptrTyp = 19; final = 0; extensible = 1; limited = 2; abstract = 3; hidden = 1; readOnly = 2; exported = 4; TYPE Name = ARRAY 256 OF CHAR; Value = ABSTRACT RECORD END; Item = RECORD (Value) obj-, typ-, vis-, adr-: INTEGER; (VAR i: Item) Valid (): BOOLEAN, NEW; (VAR i: Item) GetTypeName (OUT mod, type: Name), NEW; (VAR i: Item) BaseTyp (): INTEGER, NEW; (VAR i: Item) Level (): INTEGER, NEW; (VAR i: Item) Size (): INTEGER, NEW; (VAR arr: Item) Len (): INTEGER, NEW; (VAR in: Item) Lookup (IN name: ARRAY OF CHAR; VAR i: Item), NEW; (VAR i: Item) GetBaseType (VAR base: Item), NEW; (VAR rec: Item) GetThisBaseType (level: INTEGER; VAR base: Item), NEW; (VAR rec: Item) Is (IN type: Value): BOOLEAN, NEW; (VAR ptr: Item) Deref (VAR ref: Item), NEW; (VAR arr: Item) Index (index: INTEGER; VAR elem: Item), NEW; (VAR proc: Item) Call (OUT ok: BOOLEAN), NEW; (VAR var: Item) GetVal (VAR x: Value; OUT ok: BOOLEAN), NEW; (VAR var: Item) PutVal (IN x: Value; OUT ok: BOOLEAN), NEW; (VAR var: Item) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW; (VAR var: Item) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW; (VAR var: Item) PutStringVal (IN x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW; (VAR var: Item) PutSStringVal (IN x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW; (VAR var: Item) PtrVal (): ANYPTR, NEW; (VAR var: Item) PutPtrVal (x: ANYPTR), NEW; (VAR var: Item) IntVal (): INTEGER, NEW; (VAR var: Item) PutIntVal (x: INTEGER), NEW; (VAR var: Item) RealVal (): REAL, NEW; (VAR var: Item) PutRealVal (x: REAL), NEW; (VAR var: Item) LongVal (): LONGINT, NEW; (VAR var: Item) PutLongVal (x: LONGINT), NEW; (VAR var: Item) CharVal (): CHAR, NEW; (VAR var: Item) PutCharVal (x: CHAR), NEW; (VAR var: Item) BoolVal (): BOOLEAN, NEW; (VAR var: Item) PutBoolVal (x: BOOLEAN), NEW; (VAR var: Item) SetVal (): SET, NEW; (VAR var: Item) PutSetVal (x: SET), NEW; (VAR type: Item) New (): ANYPTR, NEW; (VAR val: Item) Copy (): ANYPTR, NEW; (VAR rec: Item) CallWith (proc: PROCEDURE (VAR rec, par: ANYREC); VAR par: ANYREC), NEW END; Scanner = RECORD this-: Item; eos-: BOOLEAN; (VAR s: Scanner) ConnectToMods, NEW; (VAR s: Scanner) ConnectTo (IN obj: Item), NEW; (VAR s: Scanner) Scan, NEW; (VAR s: Scanner) GetObjName (OUT name: Name), NEW; (VAR s: Scanner) Level (): INTEGER, NEW END; LookupFilter = PROCEDURE (IN path: ARRAY OF CHAR; OUT i: Item; OUT done: BOOLEAN) PROCEDURE Lookup (IN name: ARRAY OF CHAR; OUT mod: Item); PROCEDURE LookupPath (IN path: ARRAY OF CHAR; OUT i: Item); PROCEDURE GetItem (obj: ANYPTR; OUT i: Item); PROCEDURE GetThisItem (IN attr: ANYREC; OUT i: Item); PROCEDURE InstallFilter (filter: LookupFilter); END Meta. Meta provides access to Component Pascal run-time type information. Meta is restricted to public information, i.e., it doesn't allow access to non-exported items of a module. Meta is safe, it doesn't allow to change data which is not exported as modifiable. Generally, Meta only allows to do with a module what could be done by a normal client module also. The difference is that Meta is more dynamic; it allows inspection and modification of data depending on run-time decisions, without static import of the inspected or modified module. Constants are not accessible via Meta, they are not represented at run-time in order to minimize space overhead. Examples: ObxCtrls slider control, extended from Controls.Control ObxFldCtrls special-purpose text field control, extended from Controls.Control How to call procedures using Meta: In order to call an arbitrary procedure (methods are not possible) whose signature is statically known, the following must be done: first, an item must be created that describes the function: Meta.Lookup(moduleName, item); IF item.obj = Meta.modObj THEN item.Lookup(procedureName, item); IF item.obj = Meta.procObj THEN item.GetVal(item0, ok); IF ok THEN item0.fun(x) ... The item item is a normal, non-extended Meta.Item item. In contrast, item0 must be an extension of Meta.Value that contains as one additional field a procedure variable of the correct type: item0: RECORD (Meta.Value) fun: PROCEDURE (x: REAL): REAL END; CONST undef Possible result code for object classes, type classes, visibility classes. CONST typObj, varObj, procObj, fieldObj, modObj Object classes. CONST boolTyp, sCharTyp, charTyp, byteTyp, sintTyp, intTyp, longTyp, sRealTyp, realTyp, setTyp, anyRecTyp, anyPtrTyp, procTyp, recTyp, arrTyp, ptrTyp Type classes. CONST final, extensible, limited, abstract Record attributes. CONST hidden, readOnly, exported Visibility classes. TYPE Name String type for meta item names. TYPE Value ABSTRACT A value may be extended exactly once, with a single field. TYPE Item (Value) obj-: INTEGER obj IN {typObj..modObj} Object class. typ-: INTEGER obj IN {boolTyp..procTyp} Object's type. vis-: INTEGER vis IN {hidden..exported} Visibility. adr-: INTEGER Memory address. PROCEDURE (VAR i: Item) Valid (): BOOLEAN NEW Determines whether the item is valid, i.e., initialized, set to a defined type, and its module is still loaded. PROCEDURE (VAR i: Item) GetTypeName (OUT mod, type: Name) NEW Get the item's type name and the name of this type's module. Pre i.Valid() 20 i.typ >= recTyp 21 module of type is still loaded 24 PROCEDURE (VAR i: Item) BaseTyp (): INTEGER NEW Returns the item's base type. Pre i.Valid() 20 i.typ IN {arrTyp, recTyp, ptrTyp} 21 PROCEDURE (VAR i: Item) Level (): INTEGER NEW Returns the item's level. Pre i.Valid() 20 i.typ IN {recTyp, arrTyp} 21 PROCEDURE (VAR i: Item) Size (): INTEGER NEW Returns the item's size in bytes. Pre i.Valid() 20 i.typ # undef 21 PROCEDURE (VAR arr: Item) Len (): INTEGER NEW Returns the array's length. Pre i.Valid() 20 i.typ = arrTyp 21 PROCEDURE (VAR in: Item) Lookup (IN name: ARRAY OF CHAR; VAR i: Item) NEW Lookup an item in a module or a field in a record. Pre in.Valid() 20 in.obj = modObj OR in.typ = recTyp 21 Post i.obj # undef lookup was successful i.obj = undef lookup was not successful PROCEDURE (VAR i: Item) GetBaseType (VAR base: Item) NEW Assign i's base type to base. Pre i.Valid() 20 i.typ IN {recTyp, arrTyp} 21 PROCEDURE (VAR rec: Item) GetThisBaseType (level: INTEGER; VAR base: Item) NEW Assign i's level-th base type to base. If the level does not exist, i.obj is set to undef. Pre i.Valid() 20 i.typ IN {recTyp, arrTyp} 21 level >= 0 & level < 16 28 PROCEDURE (VAR rec: Item) Is (IN type: Value): BOOLEAN NEW Perform a type test rec IS type. Pre rec.Valid() 20 rec.typ = recTyp 21 type IS Item type.Valid() 20 type.typ = recTyp 21 ~(type IS Item) type.Level() = 1 25 number of fields of type = 1 26 PROCEDURE (VAR ptr: Item) Deref (VAR ref: Item) NEW Dereference pointer ptr and assign the result to ref. Pre ptr.typ = ptrTyp 21 ref must be a level 1 record 25 ref must have exactly one field 26 PROCEDURE (VAR arr: Item) Index (index: INTEGER; VAR elem: Item) NEW Assign the index-th element of array arr to elem. Pre arr.Valid() 20 arr.typ = arrTyp 21 arr.obj = varObj 22 PROCEDURE (VAR proc: Item) Call (OUT ok: BOOLEAN) NEW Call a parameterless procedure. Pre proc.Valid() 20 proc.obj = procObj OR proc.obj = varObj & proc.typ = procTyp 21 PROCEDURE (VAR var: Item) GetVal (VAR x: Value; OUT ok: BOOLEAN) NEW PROCEDURE (VAR var: Item) PutVal (IN x: Value; OUT ok: BOOLEAN) NEW PROCEDURE (VAR var: Item) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN) NEW PROCEDURE (VAR var: Item) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN) NEW PROCEDURE (VAR var: Item) PtrVal (): ANYPTR NEW PROCEDURE (VAR var: Item) PutPtrVal (x: ANYPTR) NEW PROCEDURE (VAR var: Item) IntVal (): INTEGER NEW PROCEDURE (VAR var: Item) PutIntVal (x: INTEGER) NEW PROCEDURE (VAR var: Item) RealVal (): REAL NEW PROCEDURE (VAR var: Item) PutRealVal (x: REAL) NEW PROCEDURE (VAR var: Item) LongVal (): LONGINT NEW PROCEDURE (VAR var: Item) PutLongVal (x: LONGINT) NEW PROCEDURE (VAR var: Item) CharVal (): CHAR NEW PROCEDURE (VAR var: Item) PutCharVal (x: CHAR) NEW PROCEDURE (VAR var: Item) BoolVal (): BOOLEAN NEW PROCEDURE (VAR var: Item) PutBoolVal (x: BOOLEAN) NEW PROCEDURE (VAR var: Item) SetVal (): SET NEW PROCEDURE (VAR var: Item) PutSetVal (x: SET) NEW PROCEDURE (VAR type: Item) New (): ANYPTR NEW Generates a new empty heap object. The item must be a record or a pointer. The type of the new object is the same as the pointer, or a pointer to the record described by the item. PROCEDURE (VAR val: Item) Copy (): ANYPTR NEW The same as New, but also copies the contents byte by byte. PROCEDURE (VAR rec: Item) CallWith (proc: PROCEDURE (VAR rec, par: ANYREC); VAR par: ANYREC) NEW Call procedure proc with the parameters rec (i.e., the item itself, the "self" parameter) and parameter par. TYPE Scanner A scanner allows to iterate over all modules, all items in a module, or all fields in a record. this-: Item The result of the most recent Scan operation. eos-: BOOLEAN This flag tells whether the most recent Scan operation has attempted to read beyond the last item. PROCEDURE (VAR s: Scanner) ConnectToMods NEW Each invocation of s.Scan will return another module. Post s.this.obj = undef ~s.eos PROCEDURE (VAR s: Scanner) ConnectTo (IN obj: Item) NEW Connect the scanner to a particular module or record. Pre obj.Valid() 20 obj.obj = modObj OR obj.typ = recTyp 21 PROCEDURE (VAR s: Scanner) Scan Scan a new item. The result is put into s.this. If an attempt was made to scan beyond the last item, s.eos is set, otherwise it is cleared. Pre s is connected 20 PROCEDURE (VAR s: Scanner) GetObjName (OUT name: Name) NEW Get the name of the most recently scanned item. Pre s.this.Valid() 20 PROCEDURE (VAR s: Scanner) Level (): INTEGER NEW Returns the scanned record's extension level. Pre s.this.Valid() 20 s connecte to record variable 22 TYPE LookupFilter = PROCEDURE (IN path: ARRAY OF CHAR; OUT i: Item; OUT done: BOOLEAN) Type used for extension hook that allows Meta to operate remotely, for example. PROCEDURE Lookup (IN name: ARRAY OF CHAR; OUT mod: Item) Set up an item to a module. Post mod.obj = modObject lookup was successful mod.obj = undef lookup was not successful PROCEDURE LookupPath (IN path: ARRAY OF CHAR; OUT i: Item) Lookup an item via a whole designator, starting with a module name. PROCEDURE GetItem (obj: ANYPTR; OUT i: Item) Create an item out of a pointer variable. PROCEDURE GetThisItem (IN attr: ANYREC; OUT i: Item) Used internally in extension hooks (creates an item out of a record variable). Use Lookup, LookupPath, or GetItem instead. PROCEDURE InstallFilter (filter: LookupFilter) Install an extension hook.
System/Docu/Meta.odc
Models DEFINITION Models; IMPORT Stores; CONST clean = 0; notUndoable = 1; invisible = 2; TYPE Model = POINTER TO ABSTRACT RECORD (Stores.Store) PROCEDURE (m: Model) Domain (): Stores.Domain, NEW END; Context = POINTER TO ABSTRACT RECORD (c: Context) ThisModel (): Model, NEW, ABSTRACT; (c: Context) GetSize (OUT w, h: INTEGER), NEW, ABSTRACT; (c: Context) SetSize (w, h: INTEGER), NEW, EMPTY; (c: Context) Normalize (): BOOLEAN, NEW, ABSTRACT; (c: Context) Consider (VAR p: Proposal), NEW, EMPTY; (c: Context) MakeVisible (l, t, r, b: INTEGER), NEW, EMPTY END; Proposal = ABSTRACT RECORD END; Message = ABSTRACT RECORD model-: Model; era-: INTEGER END; UpdateMsg = EXTENSIBLE RECORD (Message) END; NeutralizeMsg = RECORD (Message) END; PROCEDURE CopyOf (m: Model): Model; PROCEDURE Broadcast (model: Model; VAR msg: Message); PROCEDURE Domaincast (d: Stores.Domain; VAR msg: Message); PROCEDURE BeginModification (type: INTEGER; m: Model); PROCEDURE EndModification (type: INTEGER; m: Model); PROCEDURE BeginScript (m: Model; name: Stores.OpName; OUT script: Stores.Operation); PROCEDURE EndScript (m: Model; script: Stores.Operation); PROCEDURE Do (m: Model; name: Stores.OpName; op: Stores.Operation); PROCEDURE LastOp (m: Model): Stores.Operation; PROCEDURE Bunch (m: Model); PROCEDURE StopBunching (m: Model); PROCEDURE Era (m: Model): INTEGER; END Models. Figure 1. Model-View-Controller Separation A model is one part of a Model-View-Controller triple. A model represents some data, without knowing how these data may be represented. Representation is performed by a view. There may be several views displaying the same model simultaneously, and possibly in different ways. After a model has been modified, a model message is broadcast in the domain to which this model belongs (e.g., the domain of the document of which the model is a part). Model messages are received by the appropriate views, such that these views can update the display according to the model modification which was performed. A modification of a model may be permanent, or reversible. To indicate a permanent modification, the procedures BeginModification/EndModification must be called before/after the modification(s). Reversible modifications ("undoable" operations) are implemented as Stores.Operation objects. Several operations on the same model can be combined into one (i.e., as a whole undoable/redoable) operation with the BeginScript/EndScript pair of procedures. A model may be a container, i.e., contain embedded views. An embedded view can communicate with the model in which it is embedded via a Context. A container model provides a context for each embedded view. Using its context, a view can inquire its current size, or it can try to change its size. All models in a document share the same domain, i.e., their domain fields are either NIL (when the document is not displayed in some window) or refer to the same domain. Different displayed documents have different domains. Examples: ObxLinesdocu ObxGraphsdocu ObxCapsdocu/sources compound commands (undoable scripts) CONST clean Possible value for parameter type of BeginModification/EndModification. Indicates an operation that does not make its document "dirty". Example: modifying a text in a way that is considered as "unimportant", such as collapsing or expanding a text fold (-> StdFolds). CONST invisible Possible value for parameter type of BeginModification/EndModification. Indicates an operation that "folds together" with the previous operation, i.e., does not itself become visible in the Undo/Redo menu items. Invisible operations can be used for operations that by themselves may not be expected to appear in an Undo/Redo menu. Example: setting options in a controller. When executing a Redo operation, after a (visible) operation, all invisible operations executed. When executing an Undo operation, first all invisible operations are undone and afterwards the visible operations. CONST notUndoable Possible value for parameter type of BeginModification/EndModification. Indicates an operation that cannot be reversed ("undone"). This is important for operations where the undo feature would be too expensive. TYPE Model (Stores.Store) ABSTRACT A model represents data, which may be presented by a view. Models are allocated by specific model directories, e.g., by Texts.dir. Models are used by commands which can operate on the data that is represented by the model. Models are extended whenever new kinds of displayable data need to be represented. A model's domain delineates the boundaries of the document in which it is embedded. A model's InitDomain procedure must be implemented if the model may (directly or indirectly) contain other Stores.Store objects, e.g., if the model may contain views. A model's Internalize, Externalize, and CopyFrom procedure must be implemented if the store contains persistent state. PROCEDURE (m: Model) Domain (): Stores.Domain NEW Returns the domain of the model, usually representing one document. If the domain is NIL, the model is not displayed. The domain is set up by the procedure Stores.InitDomain. TYPE Context ABSTRACT A context object is part of the model-view recursion scheme of BlackBox. A context is generated and maintained by a container model, and there is one context for every view embedded in the model. The context is carried by the view, so the view can communicate with its context (i.e., with the model in which it is embedded). A Context allows a contained view to communicate with its container. A Context is extended for every container model. PROCEDURE (c: Context) ThisModel (): Model NEW, ABSTRACT Returns the context's model. NIL may be returned if the context doesn't want to disclose its identity. ThisModel may be narrowed in an extension. PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER) NEW, ABSTRACT Returns the width and height of the contained view in its container, in universal units. Post w >= 0 & h >= 0 PROCEDURE (c: Context) SetSize (w, h: INTEGER) NEW, EMPTY Requests the container to adapt the size of c's view to the given width and height. The container may or may not grant this request. PROCEDURE (c: Context) Normalize (): BOOLEAN NEW, ABSTRACT Determines whether the contained view should normalize its persistent state upon externalization, and whether it should not make a modification of this state undoable. As an example, consider the scroll position of a text view: if the view is in a root context, i.e., in the outermost view level, it should write out position 0 (i.e., "normalized") as its current scroll position upon externalization, and it shouldn't make scroll operations undoable. However, if embedded in a non-root context, it should write out its current scroll position, and should make a scroll operation undoable. Normalize is called in a view's Externalize procedure and when it must be determined whether an operation needs to be undoable or not. PROCEDURE (c: Context) Consider (VAR p: Proposal) NEW, EMPTY If an embedded view wants its container to do something, it must ask for such a change by sending the container a Proposal via the Consider procedure. The container may, but need not, cooperate in an appropriate way. BlackBox currently doesn't predefine proposals of its own. PROCEDURE (c: Context) MakeVisible (l, t, r, b: INTEGER) NEW, EMPTY Scroll the container of c's view such that the rectangle (l, t, r, b) becomes at least partially visible. TYPE Proposal ABSTRACT Base type for all proposals. A proposal is a message which a view can send to the container (via its context object) in which it is embedded. TYPE Message ABSTRACT Base type for all model messages. Messages are used to transmit information from a model to all views which display this model, typically about changes that have occurred in a model. Messages are extended to describe specific kinds of information to be transmitted. model: Model model # NIL The model that has been changed. era-: INTEGER Used internally. TYPE UpdateMsg (Message) EXTENSIBLE All model messages which notify about a model modification must be extensions of UpdateMsg. A basic (unextended) UpdateMsg indicates that the message's model has changed in some unspecified way. UpdateMsgs are used to notify all views displaying a given model about a change of this model. UpdateMsgs are extended in order to update the display in more specific ways than to redraw the whole view (i.e., faster and with less screen flicker), i.e., to allow partial updates. TYPE NeutralizeMsg (Message) Extension This message is sent by the framework to indicate that marks (selection marks and the like) should be removed. PROCEDURE CopyOf (m: Model): Model Returns a (deep) copy of the model. Internally, it clones m and calls its CopyFrom method. Pre m # NIL 20 Post result # NIL PROCEDURE Broadcast (model: Model; VAR msg: Message) Broadcast msg for model. Before broadcasting, parameter model is assigned to the message's model-field. The broadcast is actually performed only if model.domain # NIL. Broadcast is called by models whenever models need to transmit information to the views by which they are displayed. In contrast to Domaincast, Broadcast sends msg only to the views which have model as their model. The handler of a model message may not recursively broadcast another model message. Pre model # NIL 20 no recursion 21 Post msg.model = model PROCEDURE Domaincast (d: Stores.Domain; VAR msg: Message) This procedure sends a message to a particular domain, or does nothing if the domain is NIL. Every view in the domain receives the message. Normally, you'll use Broadcast to notify only the views on a particular model. Domaincast is only necessary if the contents of one view (e.g., a text ruler) influences something outside of the view itself (e.g., the formatting of the text below the ruler). The domaincast is actually performed only if d # NIL. A domaincast may not be performed if another one is still in progress for this domain (no recursion). Pre no recursion 20 Post msg.model = NIL PROCEDURE BeginModification (type: INTEGER; m: Model) If model m is modified in a way that cannot be undone, the modification(s) must be bracketed by calls to BeginModification and EndModification with parameter type set to notUndoable. Pre m # NIL 20 type IN {clean, notUndoable, invisible} 21 PROCEDURE EndModification (type: INTEGER; m: Model) If model m is modified in a way that cannot be undone, the modification(s) must be bracketed by calls to BeginModification and EndModification with parameter type set to notUndoable. Pre m # NIL 20 type IN {clean, notUndoable, invisible} 21 PROCEDURE BeginScript (m: Model; name: Stores.OpName; OUT script: Stores.Operation) To make a sequence of undoable operations undoable as a whole, the sequence should be bracketed by calls to BeginScript and EndScript. Pre m # NIL 20 Post script # NIL PROCEDURE EndScript (m: Model; script: Stores.Operation) To make a sequence of undoable operations undoable as a whole, the sequence should be bracketed by calls to BeginScript and EndScript. The same script which has been returned in BeginScript must be passed to EndScript. Pre m # NIL 20 script # NIL 21 PROCEDURE Do (m: Model; name: Stores.OpName; op: Stores.Operation) This procedure is called to execute an operation on a model. The operation's Do procedure is called, and the operation is recorded for a later undo. Pre m # NIL 20 op # NIL 21 Post op.inUse PROCEDURE LastOp (m: Model): Stores.Operation This procedure returns the most recently executed operation on the given model. It can be used to decide whether to bunch several successive operations into one single atomic operation, e.g., if a character is typed into a text, it may be bunched with the previously inserted character; such that an undo operates on the whole text typed in, and not on one character per undo. Pre m # NIL 20 PROCEDURE Bunch (m: Model) Notify model that another action was bunched to the most recently executed operation. After it has been determined that the new operation can be merged into the most recent operation (using LastOp for the test), the previous operation can be modified (e.g., a character appended to its string of characters that were typed in) and this modification made known to the framework by calling Bunch. Pre m # NIL 20 PROCEDURE StopBunching (m: Model) Prevents any further bunching on this model's current operation. Pre m # NIL 20 PROCEDURE Era (m: Model): INTEGER Called internally. Pre m # NIL 20
System/Docu/Models.odc
ODBC32 This module is obsolete; use the Win subsystem instead.
System/Docu/ODBC32.odc
Out DEFINITION Out; PROCEDURE Open; PROCEDURE Char (ch: CHAR); PROCEDURE Ln; PROCEDURE Int (i: LONGINT; n: INTEGER); PROCEDURE Real (x: REAL; n: INTEGER); PROCEDURE String (str: ARRAY OF CHAR); END Out. This module is provided for compatibility with the book "Programming in Oberon" by Reiser/Wirth. It is useful when learning the language. It is not recommended for use in production programs. PROCEDURE Open Brings open log window to the top. If no log window is open, a new one is opened. PROCEDURE Char (ch: CHAR) Writes a character into the log. PROCEDURE Ln Writes a carriage return into the log. PROCEDURE Int (i: LONGINT; n: INTEGER) Writes an integer number into the log, with n digits. If n is too small (e.g., 0) to represent the number correctly, the necessary minimal number of digits is used. PROCEDURE Real (x: REAL; n: INTEGER) Writes a real number into the log, with n digits. If n is too small (e.g., 0) to represent the number correctly, the necessary minimal number of digits is used. PROCEDURE String (str: ARRAY OF CHAR) Writes a string into the log.
System/Docu/Out.odc
Ports DEFINITION Ports; IMPORT Fonts; CONST black = 00000000H; white = 00FFFFFFH; grey6 = 00F0F0F0H; grey12 = 00E0E0E0H; grey25 = 00C0C0C0H; grey50 = 00808080H; grey75 = 00404040H; red = 000000FFH; green = 0000FF00H; blue = 00FF0000H; defaultColor = 01000000H; mm = 36000; point = 12700; inch = 914400; fill = -1; openPoly = 0; closedPoly = 1; openBezier = 2; closedBezier = 3; invert = 0; hilite = 1; dim25 = 2; dim50 = 3; dim75 = 4; hide = FALSE; show = TRUE; arrowCursor = 0; textCursor = 1; graphicsCursor = 2; tableCursor = 3; bitmapCursor = 4; refCursor = 5; keepBuffer = FALSE; disposeBuffer = TRUE; TYPE Color = INTEGER; Point = RECORD x, y: INTEGER END; Port = POINTER TO ABSTRACT RECORD unit-: INTEGER; (p: Port) Init (unit: INTEGER; printerMode: BOOLEAN), NEW; (p: Port) GetSize (OUT w, h: INTEGER), NEW, ABSTRACT; (p: Port) SetSize (w, h: INTEGER), NEW, ABSTRACT; (p: Port) NewRider (): INTEGER, NEW, ABSTRACT; (p: Port) OpenBuffer (l, t, r, b: INTEGER), NEW, ABSTRACT; (p: Port) CloseBuffer, NEW, ABSTRACT END; Rider = POINTER TO ABSTRACT RECORD (rd: Rider) SetRect (l, t, r, b: INTEGER), NEW, ABSTRACT; (rd: Rider) GetRect (OUT l, t, r, b: INTEGER), NEW, ABSTRACT; (rd: Rider) Base (): Port, NEW, ABSTRACT; (rd: Rider) Move (dx, dy: INTEGER), NEW, ABSTRACT; (rd: Rider) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER), NEW, ABSTRACT; (rd: Rider) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN), NEW, ABSTRACT; (rd: Rider) DrawRect (l, t, r, b, s: INTEGER; col: Color), NEW, ABSTRACT; (rd: Rider) DrawOval (l, t, r, b, s: INTEGER; col: Color), NEW, ABSTRACT; (rd: Rider) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color), NEW, ABSTRACT; (rd: Rider) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color; path: INTEGER), NEW, ABSTRACT; (rd: Rider) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN), NEW, ABSTRACT; (rd: Rider) Scroll (dx, dy: INTEGER), NEW, ABSTRACT; (rd: Rider) SetCursor (cursor: INTEGER), NEW, ABSTRACT; (rd: Rider) Input (OUT x, y: INTEGER; OUT modifiers: SET; OUT isDown: BOOLEAN), NEW, ABSTRACT; (rd: Rider) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR; font: Fonts.Font), NEW, ABSTRACT; (rd: Rider) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font), NEW, ABSTRACT; (rd: Rider) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER, NEW, ABSTRACT; (rd: Rider) SCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER, NEW, ABSTRACT; (rd: Rider) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER, NEW, ABSTRACT; (rd: Rider) SCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER, NEW, ABSTRACT END; Frame = POINTER TO ABSTRACT RECORD unit-: INTEGER; dot-: INTEGER; rider-: Rider; gx-, gy-: INTEGER; (f: Frame) ConnectTo (p: Port), NEW, EXTENSIBLE; (f: Frame) SetOffset (gx, gy: INTEGER), NEW, EXTENSIBLE; (f: Frame) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER), NEW; (f: Frame) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN), NEW; (f: Frame) DrawRect (l, t, r, b, s: INTEGER; col: Color), NEW; (f: Frame) DrawOval (l, t, r, b, s: INTEGER; col: Color), NEW; (f: Frame) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color), NEW; (f: Frame) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color; path: INTEGER), NEW; (f: Frame) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN), NEW; (f: Frame) Scroll (dx, dy: INTEGER), NEW; (f: Frame) SetCursor (cursor: INTEGER), NEW; (f: Frame) Input (OUT x, y: INTEGER; OUT modifiers: SET; OUT isDown: BOOLEAN), NEW; (f: Frame) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR; font: Fonts.Font), NEW; (f: Frame) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font), NEW; (f: Frame) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER, NEW; (f: Frame) SCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER, NEW; (f: Frame) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER, NEW; (f: Frame) SCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER, NEW END; VAR background, dialogBackground: Color; PROCEDURE IsPrinterPort (p: Port): BOOLEAN; PROCEDURE RGBColor (red, green, blue: INTEGER): Color; END Ports. Ports are carriers for pixel data. Examples of ports are screen and printer ports. Riders are access paths to ports. The drawing operations of a rider are performed in a coordinate system with positive x-axis and negative y-axis, i.e., x values increase towards the right, while y values increase towards the bottom. This coordinate system is the same for every rider on a port, with the origin at the upper-left corner of the port. Points are coordinate pairs (in device coordinates) which denote the upper-left corner of a pixel: Figure 1. Drawing Plane A rider occupies a rectangle within the port area. Each rider acts as a clipping rectangle, to which all its drawing operations are clipped. Frames are port mappers, which provide port output operations and input from mouse and keyboard. Frame coordinates are scaled and translated such that they are independent of the frame's position on a port, and independent of the port's spacial resolution. For this reason, all frame operations use universal units (-> Fonts) for coordinates, while all port and rider operations use pixel coordinates. CONST black, white, grey6, grey12, grey25, grey50, grey75, red, green, blue RGB values for several important colors. CONST defaultColor This is a pseudo color which is substituted by the currently set default foreground color for drawing. CONST mm, point, inch Three important distance measures in universal units. CONST fill This value may be passed to the procedures DrawRect, DrawOval, DrawPath, and MarkRect as size parameter, to cause the drawing of a filled shape, instead of the shape's outline only. CONST openPoly, closedPoly, openBezier, closedBezier These values may be passed to the procedure DrawPath as path parameter. They causes the drawing of a polyline, a polygon, an open Bezier curve, or of a closed Bezier curve. Note that with Bezier curves, only every third point lies on the curve. Figure 2. Various Path Examples CONST invert, hilite, dim25, dim50, dim75 These values may be passed as mode-parameter to procedure MarkRect. They cause the marked rectangle to become inverted, hilighted, or dimmed. The exact interpretation of these modes is platform-dependent. In the simplest case, all three modes are implemented the same way, namely by inverting each bit in the color value which represents a pixel. Ideally, hilite should replace an area's background color with a user-selectable hilight-color, and vice versa. The three dimming modes, applied to a white background, deliver light, medium, and dark grey values, respectively. CONST hide, show These values may be passed as show-parameter of the MarkRect procedures. hide means that an existing mark should be removed, and show means that the mark should be drawn. In some implementations, the operation may be identical for hide and show, but this is not guaranteed. CONST arrowCursor The default shape of the cursor. CONST textCursor, graphicsCursor, tableCursor, bitmapCursor Cursor shapes which correspond to the type of data currently being manipulated: sequential, large shapes, regularly arranged objects, small shapes. CONST refCursor Cursor shape for indicating references, such as hyperlinks. CONST keepBuffer, disposeBuffer These constants may be passed to the dispose parameters of procedures Rider.RestoreRect and Frame.RestoreRect. TYPE Color = INTEGER A color is a four-byte value where the least significant byte (interpreted as unsigned integer) specifies the red-intensity of an RGB triple. The next byte specifies the green-intensity, the third byte represents the blue-intensity. The most significant byte must be set to zero. TYPE Point This type is used to construct paths for the DrawPath procedure. A path consists of an array of points, where points are coordinate pairs. Points are used in drawing routines that call DrawPath. x, y: INTEGER Coordinate pair. TYPE Port ABSTRACT Carrier for pixel data. Ports are allocated and used internally. Ports are implemented internally. unit-: INTEGER unit > 0 The size of a pixel in universal units. PROCEDURE (p: Port) Init (unit: INTEGER; printerMode: BOOLEAN) Sets the spacial resolution (in universal units per pixel). Parameter printerMode determines whether the port acts as a printing object. Pre p.unit = 0 OR p.unit = unit 20 unit > 0 21 Post p.unit = unit PROCEDURE (p: Port) GetSize (OUT w, h: INTEGER) NEW, ABSTRACT Get the port's current size (in pixels). Post w >= 0 h >= 0 PROCEDURE (p: Port) SetSize (w, h: INTEGER) NEW, ABSTRACT Sets the port's size (in pixels). Pre w >= 0 20 h >= 0 21 PROCEDURE (p: Port) NewRider (): Rider NEW, ABSTRACT Returns a rider that has the appropriate type for this port implementation. PROCEDURE (p: Port) OpenBuffer (l, t, r, b: INTEGER) NEW, ABSTRACT Opens an off-screen buffer for port p. The buffer is initialized with the contents of p's rectangle (l, t, r, b). OpenBuffer must be followed by a call to CloseBuffer. Calls to OpenBuffer must not be nested. Used internally, for restoring a window flicker-free in the background. Not to be used for other purposes. PROCEDURE (p: Port) CloseBuffer NEW, ABSTRACT Copy back the contents of the port's off-screen buffer, and release the buffer. OpenBuffer must have been called before. Used internally, for restoring a window flicker-free in the background. Not to be used for other purposes. TYPE Rider ABSTRACT Access path to a port (i.e., to a pixel carrier). A rider uses the same coordinate system as its port, with the origin being the upper-left corner of the port. All coordinates used for a rider are in device coordinates, i.e., in pixels. Riders also contain a clipping rectangle. Normally, it is manipulated automatically by the framework, but in special circumstances, it can be useful also for view programmers. Riders are allocated by ports. Riders are used internally (by frames, see below) and implemented internally. PROCEDURE (rd: Rider) SetRect (l, t, r, b: INTEGER) NEW, ABSTRACT Sets the rider's clipping rectangle on the port (in pixels). Normally, this method is called by the framework only. If you use it explicitly, you should restore the old clipping rectangle after you are done. The framework sets up the clipping rectangle before a view's Restore method is called (-> Views.View.Restore). This ensures that drawing never occurs outside of the drawing area that belongs to the view, as long as the clipping rectangle is not modified by the view. The clipping rectangle must never be made larger than the size set up by the framework, it may only be made smaller. Otherwise, the results are unpredictable. Pre 0 <= l <= r & 0 <= t <= b 20 PROCEDURE (rd: Rider) GetRect (OUT l, t, r, b: INTEGER) NEW, ABSTRACT Gets the rider's clipping rectangle on the port (in pixels). Post 0 <= l <= r & 0 <= t <= b PROCEDURE (rd: Rider) Base (): Port NEW, ABSTRACT Returns the port to which rd is connected. Post result # NIL PROCEDURE (rd: Rider) Move (dx, dy: INTEGER) NEW, ABSTRACT Used internally. PROCEDURE (rd: Rider) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER) NEW, ABSTRACT Saves a rectangle (parallel to the coordinate axes) of width r - l and of height b - t in a background buffer, from where it can be restored later using RestoreRect. SaveRect must be balanced by RestoreRect(l, t, r, b, disposeBuffer). All coordinates are in pixels. Calls to SaveRect may not be nested, and they may not occur during restoration of a view (-> Views.View.Restore). The purpose of SaveRect/RestoreRect is to act as temporary buffering mechanism during mouse tracking (->Views.View.HandleCtrlMsg). res = 0 means that the call was successful, otherwise RestoreRect must not be called. Pre (l <= r) & (t <= b) 20 PROCEDURE (rd: Rider) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN) NEW, ABSTRACT After a successful call to SaveRect, the same rectangle, i.e., its pixelmap contents as it was upon saving, can be restored with RestoreRect. All coordinates are in pixels. RestoreRect can be called several times in succession; the last time with dispose = disposeBuffer and all other times with dispose = keepBuffer. Pre (l <= r) & (t <= b) 20 PROCEDURE (rd: Rider) DrawRect (l, t, r, b, s: INTEGER; col: Color) NEW, ABSTRACT Draws a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. All coordinates are in pixels. If s < 0, the rectangle is filled with color col. Otherwise, the rectangle is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used. Pre (l <= r) & (t <= b) 20 (s >= 0) OR (s = fill) 21 PROCEDURE (rd: Rider) DrawOval (l, t, r, b, s: INTEGER; col: Color) NEW, ABSTRACT Draws an ellipse (parallel to the coordinate axes) of width r - l and of height b - t. All coordinates are in pixels. If s < 0, the ellipse is filled with color col. Otherwise, the ellipse is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used. Pre (l <= r) & (t <= b) 20 (s >= 0) OR (s = fill) 21 PROCEDURE (rd: Rider) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color) NEW, ABSTRACT Draws a line from the point (x0, y0) to the point (x1, y1) of thickness s in color col: All coordinates are in pixels. Note that if you need to draw strictly horizontal or vertical lines, you could use DrawRect with fill instead of DrawLine. The advantage of DrawRect is that it is clearer which pixels are really drawn, it's the pixels that are strictly inside the bounding rectangle. Figure 3: Line If s = 0, a very thin outline (hairline) is used. Pre s >= 0 20 PROCEDURE (rd: Rider) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color; path: INTEGER) NEW, ABSTRACT Draws the path consisting of points p[0] .. p[n - 1] in color col. The nature of the path is given by parameter path. It can either be a polyline, a polygon, an open Bezier curve, or a closed Bezier curve. The polyline is the same that a sequence of DrawLine operations would generate. For a polygon, the n points define the mathematical region which will be outlined or filled. An open path with n points results in n - 1 path pieces, a closed path with n points results in n path pieces. All coordinates in the point array are in pixels. Pre n >= 0 20 n <= LEN(p) 21 (s = fill) => (path = closedPoly) OR (path = closedBezier) 22 (s >= 0) OR (s = fill) 23 path IN {closedPoly, openPoly, closedBezier, openBezier} 25 path = openPoly n >= 2 20 path = closedPoly n >= 2 20 path = openBezier n >= 4 20 n MOD 3 = 1 24 path = closedBezier n >= 3 20 n MOD 3 = 0 24 PROCEDURE (rd: Rider) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN) NEW, ABSTRACT Marks a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. All coordinates are in pixels. If s < 0, the rectangle is filled in some way dependent on mode. Otherwise, the rectangle is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used. The meaning of mode is implementation-dependent, but it must change the marked area in a visible way. show indicates whether the mark should be drawn or removed. Calling MarkRect with show and then directly afterwards with hide (otherwise with the same parameters) should re-establish exactly the state before the first call. Pre (l <= r) & (l <= t) 20 s >= 0 21 mode IN {invert, hilite, dim25, dim50, dim75} 22 PROCEDURE (rd: Rider) Scroll (dx, dy: INTEGER) NEW, ABSTRACT Shifts the rider's contents by vector (dx, dy). The translation vector is given in pixels. Shifting occurs completely within the rider's rectangle, ie., pixels outside of it are neither written nor read. The part of the rectangle that becomes newly exposed is undefined. The purpose of Scroll is to speed up scrolling operations by reusing existing pixel data instead of making the application redraw everything. However, under special circumstances, this procedure may not actually copy pixel data, but cause the application to restore part of the rectangle instead anyway. Warning: this operation may only be used on interactive ports, in order to update the screen display after a user manipulation. Figure 4. Effect of Scroll Operation PROCEDURE (rd: Rider) SetCursor (cursor: INTEGER) NEW, ABSTRACT Sets the cursor to the given value. Pre cursor IN {arrowCursor..refCursor} 20 PROCEDURE (rd: Rider) Input (OUT x, y: INTEGER; OUT modifiers: SET; OUT isDown: BOOLEAN) NEW, ABSTRACT Polls the current mouse location and tells whether the mouse button is currently pressed. All coordinates are in pixels. In modifiers, the currently pressed modifier keys are returned, like Controllers.doubleClick, Controllers.extend, Controllers.modify, and possibly additional platform-specific modifiers. PROCEDURE (rd: Rider) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR; font: Fonts.Font) NEW, ABSTRACT Draws string s in color col and font font with the base line at y. All coordinates are in pixels. Pre font # NIL 20 PROCEDURE (rd: Rider) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font) NEW, ABSTRACT Draws short string s in color col and font font with the base line at y. All coordinates are in pixels. Pre font # NIL 20 PROCEDURE (rd: Rider) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER NEW, ABSTRACT Given string s at position x, CharIndex determines the index of the character which lies at position pos. All coordinates are in pixels. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s. Pre font # NIL 20 PROCEDURE (rd: Rider) LCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER NEW, ABSTRACT Given string s at position x, CharIndex determines the index of the character which lies at position pos. All coordinates are in pixels. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s. Pre font # NIL 20 PROCEDURE (rd: Rider) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER NEW, ABSTRACT Given string s at position x, CharPos determines the position of character index in s. All coordinates are in pixels. The position of the left margin of the character is returned. Pre font # NIL 20 PROCEDURE (rd: Rider) LCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER NEW, ABSTRACT Given string s at position x, CharPos determines the position of character index in s. All coordinates are in pixels. The position of the left margin of the character is returned. Pre font # NIL 20 TYPE Frame ABSTRACT A Frame is a mapper for a port. Every frame has its own coordinate system. All coordinates used for a frame are measured in universal units. Most frame operations forward to the frame's rider, i.e., they call the frame rider's corresponding procedure, and perform the necessary coordinate transformations (scaling between universal units and pixels, and a translation by the frame's origin). A frame f translates from local universal coordinates to global pixel coordinates using the following transformation: x := (f.gx + x) DIV f.unit; y := (f.gy + y) DIV f.unit; (* frame -> rider coordinates *) The opposit transformation is: x := x * f.unit - f.gx; y := y * f.unit - f.gy; (* rider -> frame coordinates *) The rider's clipping rectangle is always set up such that drawing cannot occur outside of the frame, i.e., outside of the drawing view. Be careful if you change the rider's clipping rectangle (using the rider's SetRect method), since this introduces mutable state that you have to manage. Frames are allocated by views. Frames are used by views, for drawing and for mouse polling. Frames are extended internally (Views.Frame). unit-: INTEGER unit > 0 The size of a pixel in universal units. dot-: INTEGER dot = point - point MOD unit This value can be used as an approximation of point, rounded to a pixel. By using dot instead of point, ugly rounding errors can be avoided. For example, if you used point as the thickness of a line, and a pixel were slightly larger than point, the line might disappear altogether. Moreover, you may want to use a very thin line on the screen (about one pixel) as a hairline, but not have it become too small on a laser printer (where the frame's unit is much smaller than on screen). In these cases, dot comes handy. rider-: Ports.Rider Rider which links the frame to a port. gx-, gy-: INTEGER [units] The frame's origin in global coordinates (i.e., relative to the port's upper-left corner), but in units instead of pixels. This is an exception from the rule that riders use pixels, while frames use units. PROCEDURE (f: Frame) ConnectTo (p: Port) NEW, EXTENSIBLE Connects the frame to a port. All other frame procedures require a connected frame, i.e., rider # NIL. This precondition is not checked explicitly. ConnectTo is used internally. Post p = NIL f.unit = 0 f.rider = NIL p # NIL f.unit = p.unit f.rider # NIL & f.rider.Base() = p f.dot = point - point MOD p.unit PROCEDURE (f: Frame) SetOffset (gx, gy: INTEGER) NEW, EXTENSIBLE Sets the frame's origin, in global coordinates (i.e., relative to the port's upper-left corner), but in units instead of pixels. All local coordinates are relative to this origin. This method is only for internal use in the framework. SetOffset is used internally. Pre f.rider # NIL 20 Post f.gx = gx & f.gy = gy PROCEDURE (f: Frame) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER) NEW Saves a rectangle (parallel to the coordinate axes) of width r - l and of height b - t in a background buffer, from where it can be restored later using RestoreRect. SaveRect must be balanced by RestoreRect(l, t, r, b, disposeBuffer). Calls to SaveRect may not be nested, and they may not occur during restoration of a view (-> Views.View.Restore). The purpose of SaveRect/RestoreRect is to act as temporary buffering mechanism during mouse tracking (->Views.View.HandleCtrlMsg). res = 0 means that the call was successful, otherwise RestoreRect must not be called. Pre (l <= r) & (t <= b) 20 PROCEDURE (f: Frame) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN) NEW After a successful call to SaveRect, the same rectangle, i.e., its pixelmap contents as it was upon saving, can be restored with RestoreRect. RestoreRect can be called several times in succession; the last time with dispose = disposeBuffer and all other times with dispose = keepBuffer. Pre (l <= r) & (t <= b) 20 PROCEDURE (f: Frame) DrawRect (l, t, r, b, s: INTEGER; col: Color) NEW Draws a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. If s < 0, the rectangle is filled with color col. Otherwise, the rectangle is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used. Pre (l <= r) & (t <= b) 20 (s >= 0) OR (s = fill) 21 PROCEDURE (f: Frame) DrawOval (l, t, r, b, s: INTEGER; col: Color) NEW Draws an ellipse (parallel to the coordinate axes) of width r - l and of height b - t. If s < 0, the ellipse is filled with color col. Otherwise, the ellipse is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used. Pre (l <= r) & (t <= b) 20 (s >= 0) OR (s = fill) 21 PROCEDURE (f: Frame) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color) NEW Draws a line from the point (x0, y0) to the point (x1, y1) of thickness s in color col: Figure 5. Line If s = 0, a very thin outline (hairline) is used. Pre s >= 0 20 PROCEDURE (f: Frame) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color; path: INTEGER) NEW Draws the path consisting of points p[0] .. p[n - 1] in color col. The nature of the path is given by parameter path. It can either be a polyline, a polygon, an open Bezier curve, or a closed Bezier curve. The polyline is the same that a sequence of DrawLine operations would generate. For a polygon, the n points define the mathematical region which will be outlined or filled. An open path with n points results in n - 1 path pieces, a closed path with n points results in n path pieces. Pre n >= 0 20 n <= LEN(p) 21 (s = fill) => (path = closedPoly) OR (path = closedBezier) 22 (s >= 0) OR (s = fill) 23 path IN {closedPoly, openPoly, closedBezier, openBezier} 25 path = openPoly n >= 2 20 path = closedPoly n >= 2 20 path = openBezier n >= 4 20 n MOD 3 = 1 24 path = closedBezier n >= 3 20 n MOD 3 = 0 24 PROCEDURE (f: Frame) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN) NEW Marks a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. If s < 0, the rectangle is filled in some way, dependent on mode. Otherwise, the rectangle is drawn as an outline of thickness s. If s = 0, a very thin outline (hairline) is used. The outline is drawn inside of the rectangle. The meaning of mode is implementation-dependent, but it must change the marked area in a visible way. show indicates whether the mark should be drawn or removed. Calling MarkRect with show and then directly afterwards with hide (otherwise with the same parameters) should re-establish exactly the state before the first call. Pre (l <= r) & (t <= b) 20 s >= 0 21 mode IN {invert, hilite, dim25, dim50, dim75} 22 PROCEDURE (f: Frame) Scroll (dx, dy: INTEGER) NEW Shifts the frame's area by vector (dx, dy). Shifting occurs completely within the frame's rectangle, i.e., pixels outside of it are neither written nor read. The part of the rectangle which becomes newly exposed should be considered as undefined. The purpose of Scroll is to speed up scrolling and editing operations by reusing existing pixel data instead of making the application redraw everything. However, under special circumstances, this procedure may not actually copy pixel data, but cause the application to restore part of the rectangle instead anyway. Warning: this operation may only be used on interactive ports, in order to update the screen display after a user manipulation. Figure 6. Effect of Scroll Operation PROCEDURE (f: Frame) SetCursor (cursor: INTEGER) NEW Sets the cursor to the given value. SetCursor is used in polling loops during mouse tracking. Pre cursor IN {arrowCursor..refCursor} 20 PROCEDURE (f: Frame) Input (OUT x, y: INTEGER; OUT modifiers: SET; OUT isDown: BOOLEAN) NEW Polls the current mouse location and tells whether the mouse button is currently pressed. Input is used in polling loops during mouse tracking. In modifiers, the currently pressed modifier keys are returned, like Controllers.doubleClick, Controllers.extend, Controllers.modify, and possibly additional platform-specific modifiers. PROCEDURE (f: Frame) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR; font: Fonts.Font) NEW Draws string s in color col and font font with the base line at y. Pre font # NIL 20 PROCEDURE (f: Frame) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font) NEW Draws short string s in color col and font font with the base line at y. Pre font # NIL 20 PROCEDURE (f: Frame) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER NEW Given string s at position x, CharIndex determines the index of the character which lies at position pos. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s. Pre font # NIL 20 PROCEDURE (f: Frame) SCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER Given short string s at position x, CharIndex determines the index of the character which lies at position pos. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s. Pre font # NIL 20 PROCEDURE (f: Frame) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR; font: Fonts.Font): INTEGER Given string s at position x, CharPos determines the position of character index in s. The position of the left margin of the character is returned. Pre font # NIL 20 PROCEDURE (f: Frame) SCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR; font: Fonts.Font): INTEGER Given short string s at position x, CharPos determines the position of character index in s. The position of the left margin of the character is returned. Pre font # NIL 20 VAR background: Color background >= 0 This variable denotes the color which is used for the background of a window. VAR dialogBackground: Color dialogBackground >= 0 This variable denotes the color which is used for the background of a dialog. PROCEDURE IsPrinterPort (p: Port): BOOLEAN Determines whether a port represents a printer. PROCEDURE RGBColor (red, green, blue: INTEGER): Color Constructs a Color out of the red, green, and blue components. Pre 0 <= red < 256 20 0 <= green < 256 21 0 <= blue < 256 22 Post result = blue * 65536 + green * 256 + red
System/Docu/Ports.odc
Printers This module has a private interface, it is only used internally.
System/Docu/Printers.odc
Printing DEFINITION Printing; IMPORT Fonts, Views, Dates; TYPE Par = POINTER TO LIMITED RECORD page: PageInfo; header, footer: Banner; copies-: INTEGER END; Banner = RECORD font: Fonts.Font; gap: INTEGER; left, right: ARRAY 128 OF CHAR END; PageInfo = RECORD first, from, to: INTEGER; alternate: BOOLEAN; title: Views.Title END; VAR par: Par; PROCEDURE NewPar (IN page: PageInfo; IN header, footer: Banner; copies: INTEGER): Par; PROCEDURE NewDefaultPar (title: Views.Title): Par; PROCEDURE PrintView (view: Views.View; p: Par); PROCEDURE Current (): INTEGER; PROCEDURE PrintBanner (f: Views.Frame; IN p: PageInfo; IN b: Banner; IN date: Dates.Date; IN time: Dates.Time; x0, x1, y: INTEGER); END Printing. This module allows to print a document, including headers and footers. TYPE Par Specification of the print job. Is passed as parameter to the function PrintView. During printing, it can be accessed via the global variable par. During printing, its state can be changed. page: PageInfo Information about the area of the pages to be printed; about page numbers; and whether printing of left and right pages is treated differently. header, footer: Banner Header/footer line to be printed on every page. copies-: INTEGER copies >= 1 Number of copies to be printed. TYPE Banner Describes a header or a footer line. font: Fonts.Font Font of the header/footer line. Only one font is possible. gap: INTEGER Distance to next base line. Currently ignored for footers. left, right: ARRAY 128 OF CHAR Text of the header/footer line. In this string the following abbreviations may occur: &p - replaced by current page number as arabic numeral &r - replaced by current page number as roman numeral &R - replaced by current page number as capital roman numeral &a - replaced by current page number as alphanumeric character &A - replaced by current page number as capital alphanumeric character &d - replaced by printing date &t - replaced by printing time &&- replaced by & character &; - specifies split point &f - title The text is centered, except if a split point occurs. A split point acts like a spring: it "presses" the items to the left and right apart. For example, "&;&p" presses an arabic page number to the right page border. TYPE PageInfo Information about the pages to be printed. first: INTEGER Page number of the first page to be printed. Page number of the currently printed page is Current() + first. May be changed during printing. from, to: INTEGER (from >= 0) & (to >= from) Range of pages to be printed. Specification is not in page numbers, but in absolute number. The first page of the document is number 0. There will be to - from + 1 pages printed. alternate: BOOLEAN Determines whether left and right pages are treated differntly. If ~alternate, then every page will be printed with the banners specified for right pages. Otherwise, pages with odd page number use the right banners, while pages with even page numbers use the left banners. The page number of the current page is first + Current(). title: Views.Title Title of the document. VAR par: Par This variable is set during printing of the document and may be changed by a printed view. However, this variable should not be used to determine whether the document is printed or displayed (-> Views.IsPrinterFrame). PROCEDURE NewPar (IN page: PageInfo; IN header, footer: Banner; copies: INTEGER): Par Allocates and initializes a new printing parameters object. Post result.page = page result.header = header result.footer = footer result.copies = copies header.font # NIL => result.header.font = header.font header.font = NIL => result.header.font = Fonts.dir.Default() footer.font # NIL => result.footer.font = footer.font footer.font = NIL => result.footer.font = Fonts.dir.Default() PROCEDURE NewDefaultPar (title: Views.Title): Par Allocates and initializes a new printing parameters object. Post result.page.first = 1 result.page.from = 0 result.page.to = 9999 result.page.alternate = FALSE result.copies = 1 result.header.gap = 0 result.header.left = "" result.header.right = "" result.header.font = Fonts.dir.Default() result.footer.gap = 0 result.footer.left = "" result.footer.right = "" result.footer.font = Fonts.dir.Default() PROCEDURE Current (): INTEGER Returns the page number of the page currently being printed. Post result >= 0 PROCEDURE PrintView (view: Views.View; par: Par) Prints view on the (current) printer, provided that a printer is available. For the parameter par, NIL can be passed. In this case, a default par parameter is generated. It is initialized with copies := 1; page.first := 1, page.from := 0, page.to := 9999, page.alternate := FALSE; page.title := title; header.gap := 0; header.left := ""; header.right := ""; header.font := Fonts.dir.Default(); footer.gap := 0; footer.left := ""; footer.right := ""; footer.font := Fonts.dir.Default(); otherwise par.title is overwritten by title. Actually, not the view view is printed, but a copy of it. PrintView makes a shallow copy of the view that is being printed, in order to avoid the original view to be changed by pagination, scrolling, or similar modifications that may be performed during printing. Pre view # NIL 20 par # NIL => par.page.first >= 0 23 par.page.from >= 0 24 par.page.to >= par.page.from 25 par.copies > 0 25 PROCEDURE PrintBanner (f: Views.Frame; IN p: PageInfo; IN b: Banner; IN date: Dates.Date; IN time: Dates.Time; x0, x1, y: INTEGER) Used internally.
System/Docu/Printing.odc
Properties DEFINITION Properties; IMPORT Fonts, Ports, Views, Controllers, Dialog; CONST color = 0; typeface = 1; size = 2; style = 3; weight = 4; width = 0; height = 1; maxVerbs = 16; noMark = FALSE; mark = TRUE; hide = FALSE; show = TRUE; TYPE Property = POINTER TO ABSTRACT RECORD next-: Property; known: SET; readOnly: SET; valid: SET; (p: Property) IntersectWith (q: Property; OUT equal: BOOLEAN) END; StdProp = POINTER TO RECORD (Property) color: Dialog.Color; typeface: Fonts.Typeface; size: INTEGER; style: RECORD val, mask: SET END; weight: INTEGER END; SizeProp = POINTER TO RECORD (Property) width, height: INTEGER END; Message = Views.PropMessage; PollMsg = RECORD (Message) prop: Property END; SetMsg = RECORD (Message) old, prop: Property END; Preference = ABSTRACT RECORD (Message) END; ResizePref = RECORD (Preference) fixed: BOOLEAN; horFitToPage: BOOLEAN; verFitToPage: BOOLEAN; horFitToWin: BOOLEAN; verFitToWin: BOOLEAN; END; SizePref = RECORD (Preference) w, h: INTEGER; fixedH, fixedW: BOOLEAN END; BoundsPref = RECORD (Preference) w, h: INTEGER END; FocusPref = RECORD (Preference) atLocation: BOOLEAN; x, y: INTEGER; hotFocus: BOOLEAN; setFocus: BOOLEAN END; ControlPref = RECORD (Preference) char: CHAR; focus: Views.View; getFocus: BOOLEAN; accepts: BOOLEAN END; PollVerbMsg = RECORD (Message) verb: INTEGER; label: ARRAY 64 OF CHAR; disabled, checked: BOOLEAN END; DoVerbMsg = RECORD (Message) verb: INTEGER; frame: Views.Frame END; CollectMsg = RECORD (Controllers.Message) poll: PollMsg END; EmitMsg = RECORD (Controllers.RequestMessage) set: SetMsg END; PollPickMsg = RECORD (Controllers.TransferMessage) mark: BOOLEAN; show: BOOLEAN; dest: Views.Frame END; PickMsg = RECORD (Controllers.TransferMessage) prop: Property END; VAR era-: INTEGER; PROCEDURE IncEra; PROCEDURE CollectProp (OUT prop: Property); PROCEDURE CollectStdProp (OUT prop: StdProp); PROCEDURE EmitProp (old, prop: Property); PROCEDURE PollPick (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; mark, show: BOOLEAN; OUT dest: Views.Frame; OUT destX, destY: INTEGER); PROCEDURE Pick (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; OUT prop: Property); PROCEDURE Insert (VAR list: Property; x: Property); PROCEDURE CopyOf (p: Property): Property; PROCEDURE CopyOfList (p: Property): Property; PROCEDURE Merge (VAR base, override: Property); PROCEDURE Intersect (VAR list: Property; x: Property; OUT equal: BOOLEAN); PROCEDURE IntersectSelections (a, aMask, b, bMask: SET; OUT c, cMask: SET; OUT equal: BOOLEAN); PROCEDURE PreferredSize (v: Views.View; minW, maxW, minH, maxH, defW, defH: INTEGER; VAR w, h: INTEGER); PROCEDURE ProportionalConstraint (scaleW, scaleH: INTEGER; fixedW, fixedH: BOOLEAN; VAR w, h: INTEGER); PROCEDURE GridConstraint (gridX, gridY: INTEGER; VAR x, y: INTEGER); PROCEDURE ThisType (view: Views.View; type: Stores.TypeName): Views.View; END Properties. Practically every view has some state, and for much of that state it is desirable that the user can change it interactively. However, in an extensible system this means that for every new view at least one, or more likely several, new dialog boxes would have to be created, and would have to be learned by the user. It is more economical for both programmer and user to have a generic and extensible way to deal with such state. Properties are provided for exactly this purpose, to communicate internal state to the user, and to communicate back any desired changes. They are the hooks for a general property editor. Of course, some interactions are optimized for convenience, thus the most important editing operations are also accessible in a more direct way: via typing or direct manipulation with the mouse. Furthermore, combinations of often-used properties can still be handled by a custom-tailored dialog, instead of a less specific general property editor. However, except where there are standard messages already defined by lower levels of the BlackBox framework, properties are the preferred way to implement such interactions. Properties are communicated via property messages. A particularly light-weight version of a property message is called a Preference: preferences inquire about a view's current preference, e.g., what its preferred size is. Preferences are normally used for the internal communication of an embedded view with its container, rather than with the user. Preferences are static message records, and a receiver should never change its state upon reception of such a message. These restrictions make preferences efficient and side-effect free, and thus easy to use. As with all message records in BlackBox, property messages may, but need not, be handled. CONST color, typeface, size, style, weight When the focus view returns a StdProp property in the CollectMsg, the StdProp.known, the StdProp.readOnly, and the StdProp.valid sets may contain one or more of the above elements. If one of these elements is set in StdProp.known, the focus view knows about the corresponding property. If one of these elements is set in both StdProp.valid and StdProp.known, the focus view currently has an opinion about what the current value of this property is. These current values are returned in the other fields of StdProp. If one of these elements is set in both StdProp.valid and StdProp.readOnly, the focus view currently doesn't allow this property to be changed. CONST width, height When the focus view returns a SizeProp property in the CollectMsg, the SizeProp.known and the SizeProp.valid sets may contain one or more of these elements. If one of these elements is set in both SizeProp.valid and SizeProp.known, the SizeProp property contains the focus view's current width and height in the width and height fields. CONST noMark, mark These values may be passed to the mark parameter of procedure PollPick. They denote whether the target feedback during drag & pick should be drawn or not. CONST maxVerbs Maximum number of verbs in a context menu. CONST hide, show These values may be passed to the show parameter of procedure PollPick. They denote whether the target feedback during drag & pick should be shown or hidden. This parameter is only relevant if mark holds. TYPE Property ABSTRACT Properties are a general mechanism to get and set attributes of a view from its environment. A view may know about attributes such as font, color, size, and arbitrary other attributes. Properties may be extended only once. next-: Property Properties are connected in a list, implemented by the next field. known: SET Each property record may describe up to 32 different attributes. These attributes are numbered from 0..31. The known field tells which of these attributes are known to the view which responds to the CollectMsg. readOnly: SET readOnly - known = {} Each known attribute may currently be read-only, i.e., not modifiable. The readOnly field tells which of the attributes are currently read-only. The readOnly set must be a subset of the known set, i.e., no attribute can be read-only and unknown simultaneously. valid: SET valid - known = {} Each known attribute may currently be undefined. This happens particularly when properties of multiple objects are collected together and some attributes differ from object to object (property with mixed values). The valid field tells which of the attributes are currently defined. Their current values should be represented by further fields of the specific property record, e.g., field color in StdProp corresponds to element 0 in the valid set, field typeface to the element 1, etc. The valid set must be a subset of the known set; i.e., no attribute can be valid and unknown simultaneously. Additionally valid is used to specify which attributes should change if a property record is sent to an object. PROCEDURE (p: Property) IntersectWith (q: Property; OUT equal: BOOLEAN) A property record p must be able to compare itself with another property record q. If all attributes in p have the same values as in q, equal should be set to TRUE. Otherwise p should be set to the intersection of p and q and equal should be set to FALSE. The intersection is built by excluding all differing attributes from the valid set. It can be assumed that the type of p is exactly the same as the type of q. IntersectWith must maintain the Property invariant that valid is a subset of known; otherwise it is not interested in known. As an example, see the implementation of StdProp.IntersectWith below. TYPE StdProp (Property) These are the standard attributes known to any BlackBox implementation. They encompass font attributes as well as color. color: Dialog.Color valid iff constant color IN StdProp.valid Current color. typeface: Fonts.Typeface valid iff constant typeface IN StdProp.valid Current typeface. size: INTEGER valid iff constant size IN StdProp.valid Current size. It usually, but not necessarily, refers to a font's size. style: RECORD valid iff constant style IN StdProp.valid style IN StdProp.valid => StdProp.style.mask # {} StdProp.style.val - StdProp.style.mask = {} (* val is subset of mask *) Current style. Field style.mask denotes which style flags are valid, style.val denotes which of the valid flags are currently set. weight: INTEGER valid iff constant weight IN StdProp.valid Current font weight. PROCEDURE (p: StdProp) IntersectWith* (q: Property; OUT equal: BOOLEAN); VAR valid: SET; c, m: SET; eq: BOOLEAN; BEGIN WITH q: StdProp DO equal := TRUE; valid := p.valid * q.valid; IF p.color.val # q.color.val THEN EXCL(valid, color) END; IF p.typeface # q.typeface THEN EXCL(valid, typeface) END; IF p.size # q.size THEN EXCL(valid, size) END; IntersectSelections(p.style.val, p.style.mask, q.style.val, q.style.mask, c, m, eq); IF m = {} THEN EXCL(valid, style) ELSIF (style IN valid) & ~eq THEN p.style.mask := m; equal := FALSE END; IF p.weight # q.weight THEN EXCL(valid, weight) END; IF p.valid # valid THEN p.valid := valid; equal := FALSE END END END IntersectWith; TYPE SizeProp (Property) This property record represents the size of a rectangular area, e.g., of a view. width: INTEGER valid iff constant width IN SizeProp.valid The current width in universal units. height: INTEGER valid iff constant height IN SizeProp.valid The current height in universal units. TYPE Message ABSTRACT Base type of all property messages. TYPE PollMsg (Message) This message is sent to get the receiving view's properties. The receiver should return the properties of all its contents, not only the selection. prop: Property The list of returned properties which may be modified. No property exists twice in such a list. TYPE SetMsg (Message) This message is sent to set the receiving view's properties. The properties' known and readOnly fields are not used and thus not defined in this case. The receiver should set the properties of all its contents, not only the selection. old: Property This list is provided for modifications of the kind "replace old by new", e.g., "replace typeface Helvetica by Times". Can be NIL. prop: Property The list of properties to be changed. No property may exist twice in the list. TYPE Preference (Message) ABSTRACT Preferences are special property messages. They are normally used for the communication between an embedded view and its container. They should operate as functions, i.e. the receiver should return values, but never change its state. TYPE ResizePref (Preference) The receiver of this message can indicate that it doesn't wish to be resized, by setting fixed to TRUE. A fixed size view doesn't show resize handled when it is selected as a singleton. For the root view in a document or window the fields horFitToPage, verFitToPage, horFitToWin, and verFitToWin can be used to enforce automatic adaptation of the view size to the actual window or page size. For embedded views, these four flags have no effect, in contrast to fixed. fixed: BOOLEAN fixed => ~horFitToPage & ~verFitToPage & ~horFitToWin & ~verFitToWin (view => caller, preset to FALSE) Can be set to indicate that the receiver's size should remain the same. horFitToPage: BOOLEAN horFitToPage => ~horFitToWin (view => caller, preset to FALSE) Can be set to indicate that the receiver's width should be adapted to the actual page width. verFitToPage: BOOLEAN verFitToPage => ~verFitToWin (view => caller, preset to FALSE) Can be set to indicate that the receiver's height should be adapted to the actual page height. horFitToWin: BOOLEAN horFitToWin => ~horFitToPage (view => caller, preset to FALSE) Can be set to indicate that the receiver's width should be adapted to the actual window width. verFitToWin: BOOLEAN verFitToWin => ~verFitToPage (view => caller, preset to FALSE) Can be set to indicate that the receiver's height should be adapted to the actual window height. TYPE SizePref (Preference) The sender of this message proposes a size for the receiving view; the size may be Views.undefined. The receiving view may override the proposal, e.g., in order to establish constraints between its width and height. The procedures ProportionalConstraint and GridConstraint are useful standard implementations of constraints. Procedure PreferredSize implements the caller's side of the protocol, i.e., fills out, sends, and interprets a SizeMsg. w, h: INTEGER (w = Views.undefined) = (h = Views.undefined) (view => caller, preset to Views.undefined if view is new or to caller's preference otherwise) Desired width and height. Either both values are preset to Views.undefined, or none of them. fixedH, fixedW: BOOLEAN (caller => view) These values are set up when the message is sent, to indicate whether height or width of the view should remain fixed. This can be used e.g. to keep a view's proportions, by adapting the width if the height is fixed, and vice versa. (See procedure ProportionalConstraint) TYPE BoundsPref (Preference) The receiving view should compute its bounding box, or, if this is too expensive to do, it should return an approximation of or a suggested substitute for the true bounding box. Views that can display part of their contents, e.g., by supporting scrolling in one or both directions, will handle BoundsPref very differently from SizePref. While SizePref relates to constraints and preferences of the size of the current view onto the model, BoundsPref should compute the size the view would need to take to just fully display all of the model. For very large or complex models (such as uncast text running over many pages) this can be a very costly operation and therefore it is anticipated that views may return an approximation of a bounding size, or an alternate suggestion, such as a size that is "quite big" but no bigger than the model. w, h: INTEGER (view => caller, preset to Views.undefined) Preferred width and height. TYPE FocusPref (Preference) A view can indicate if it doesn't want to become focus permanently, e.g., a button. It may even decide so depending on where the mouse has been clicked. atLocation: BOOLEAN (caller => view) This flag is set if the receiver would become focus through a mouse click. x, y: INTEGER [units] (caller => view, valid iff atLocation) Position of mouse click relative to the receiving view's top-left corner. hotFocus: BOOLEAN (view => caller, preset to FALSE) The receiver can set this flag to indicate that the view should release its focus immediately after the mouse is released. Command buttons are typical hot foci. setFocus: BOOLEAN (view => caller, preset to FALSE) The receiver can set this flag to indicate that the view should become focus when the mouse is clicked inside (otherwise the view may become selected immediately, e.g., to be dragged & dropped). setFocus should be set for all true editors, such that context-sensitive menu commands can be attached to the view. TYPE ControlPref (Preference) A view can indicate its preferred behavior if it is embedded in a dialog (i.e., a container in mask mode, -> Containers) and a key is pressed. The ControlPref message is sent first to the actual focus view and then to all other views in the container until one of the views sets either the getFocus or the accepts bit or both. If none of the views respond to the message, the character is forwarded to the focus view. char: CHAR (caller => view) The key which was pressed. focus: Views.View (caller => view) The actual focus view. getFocus: BOOLEAN (view => caller, valid if (view # focus), preset to (char = tab) ) Indicates that the view wants to become the focus view. accepts: BOOLEAN (view => caller, preset to ((view = focus) & (char # tab)) ) This flag should be set if the receiver would accept and interpret char to invoke some action. The character is sent to the view in a separate Edit message. TYPE PollVerbMsg (Message) Message used to ask a view whether it supports custom verbs. A verb is some kind of action that the user can apply to a view and that is shown in a popup-menu. verb: INTEGER verb >= 0 (IN) (caller => view) The index of the verb to be polled. label: ARRAY 64 OF CHAR (view => caller, preset to "") Displayed label of the verb. disabled: BOOLEAN (view => caller, preset to FALSE) Indicates whether verb is enabled or disabled. checked: BOOLEAN (view => caller, preset to FALSE) Indicates whether verb is unchecked or checked. TYPE DoVerbMsg (Message) Execute a particular custom verb. verb: INTEGER (caller => view) The verb to be executed. frame: Views.Frame (caller => verb) The frame of the view where the verb was invoked by the user. TYPE CollectMsg (Controllers.Message) This controller message is sent along the focus path, to poll the properties of the innermost focus view's selection or caret, i.e., unlike PollMsg it does not return the properties of the whole contents. poll: PollMsg TYPE EmitMsg (Controllers.RequestMessage) This controller message is sent along the focus path, to set the properties of the innermost focus view's selection or caret, i.e., unlike SetMsg it does not set the properties of the whole contents. set: SetMsg TYPE PollPickMsg (Controllers.TransferMessage) While an item is being dragged around for the purpose of picking properties (BlackBox's Drag & Pick mechanism), PollPickMsgs are sent to enable feedback about the pick target. Note that this is similar to the role of Controllers.PollDropMsg for Drag & Drop. mark: BOOLEAN A container which supports pick feedback should show (hide) its feedback mark when mark is set (cleared). You don't need to deal with the view's border mark (the rectangular outline of the view which is drawn while you are dragging over a view), this is handled completely by BlackBox itself through its container abstraction. show: BOOLEAN Indicates whether the mark should be drawn or removed. dest: Views.Frame The receiver should set dest to its own frame, if it would accept a pick. TYPE PickMsg (Controllers.TransferMessage) Extension This message is used if properties are to be picked from the cursor's location. Note that this is similar to the Controllers.DropMsg for Drag & Drop. prop: Property The receiver should set prop to the properties at the cursor's location. VAR era-: INTEGER propEra >= 0 This variable is used by BlackBox to determine whether the focus view's properties may have changed. PROCEDURE IncEra Increments era. This procedure should be called whenever one or several properties of a view have changed. As a response, the system will eventually send a PollMsg to get the new properties, e.g., to reflect them in the menus or in a property editor. Post era = era' + 1 PROCEDURE CollectProp (OUT prop: Property) Poll focus view's properties. PROCEDURE CollectStdProp (OUT prop: StdProp) Poll focus view's standard properties. PROCEDURE EmitProp (old, prop: Property) Set focus view's properties to prop. If old is not NIL, only the properties corresponding to old are replaced by their prop counterparts. PROCEDURE PollPick (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; mark, show: BOOLEAN; OUT dest: Views.Frame; OUT destX, destY: INTEGER) Control pick feedback at location (x, y) relative to the coordinates of source, by sending a PollPickMsg msg. Presets msg.dest to NIL, msg.mark to mark, msg.show to show, and calls Controllers.Transfer(x, y, source, sourceX, sourceY, msg). Returns msg.dest, msg.destX, and msg.destY in dest, destX, and destY, respectively. Pre source # NIL 20 PROCEDURE Pick (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; OUT prop: Property) Pick properties at location (x, y) relative to the coordinates of source, by sending a PickMsg msg. Presets msg.prop to NIL and calls Controllers.Transfer(x, y, source, sourceX, sourceY, msg). Returns msg.prop in prop. PROCEDURE Insert (VAR list: Property; x: Property) Insert new property record x in list list. A property whose type is already in the list replaces the property in the list. The dynamic type of x must be a direct extension of type Property. Pre x # NIL 20 x.next = NIL 21 x # list 22 x.valid - x.known = {} 23 list # NIL list.valid - list.known = {} 24 extension-level(list) = 1 25 extension-level(x) = 1 26 PROCEDURE CopyOf (p: Property): Property Returns a copy of the property p (not of the entire list!). The dynamic types of every property inp must be a direct extension of type Property. Pre extension-level(p) = 1 20 PROCEDURE CopyOfList (p: Property): Property Returns a copy of the property list p. The dynamic types of every property inp must be a direct extension of type Property. Pre all x in {p, p.next, p.next.next, ...}: extension-level(x) = 1 20 PROCEDURE Merge (VAR base, override: Property) Merge two property lists base and override. If the type of a property is in both lists, the attributes of the property in override will be selected for the merged list. The merged list is returned in base. PROCEDURE Intersect (VAR list: Property; x: Property; OUT same: BOOLEAN) It reduces the properties in list by all these properties which are not in x, or which have different values in x. Furthermore, it determines whether both lists are the same. PROCEDURE IntersectSelections (a, aMask, b, bMask: SET; OUT c, cMask: SET; OUT equal: BOOLEAN) Support procedure to implement the IntersectWith procedure of properties containing a set. This procedure is equivalent to the following code: cMask := aMask * bMask - (a / b); c := a * cMask; equal := (aMask = bMask) & (bMask = cMask) PROCEDURE PreferredSize (v: Views.View; minW, maxW, minH, maxH, defW, defH: INTEGER; VAR w, h: INTEGER) Sets up a SizePref and uses it to ask view v for its sizing preferences. [minW, maxW] and [minH, maxH] are the legal ranges of width and height, respectively, that are acceptable to the caller. (defW, defH) is the caller-specified default size, i.e., the size that the caller prefers in the absence of any preferences of v; specifying (Views.undefined, Views.undefined) means "no default". (w, h) can be preset by the caller and will be used to preset the SizePref; normally the caller uses this to pass the current size of a view that is to be resized. However, if (w < Views.undefined) or (w > maxW), then defW will be used instead of w. Likewise, if (h < Views.undefined) or (h > maxH), then defH will be used instead of h. If v does not interpret a SizePref or returns w = Views.undefined, then defW overrides the preference of v. Likewise, if the SizePref returns h = Views.undefined, then defH overrides the preference of v. Finally, (w, h) will be clipped to ([minW, maxW], [minH, maxH]) before returning to the caller. Therefore, if v has no (or no valid) preferences and the caller-specified default (or preset) value is Views.undefined, then the minimum values will be returned. Pre Views.undefined < minW 20 minW < maxW 21 Views.undefined < minH 23 minH < maxH 24 Views.undefined <= defW 26 Views.undefiend <= defH 28 PROCEDURE ProportionalConstraint (scaleW, scaleH: INTEGER; fixedW, fixedH: BOOLEAN; VAR w, h: INTEGER) Supports proportional resizing of rectangular shapes such as views. (scaleW, scaleH) is the size of a rectangle of the required proportions, e.g., (2,3) represents all rectangles having a ratio width to height of 2:3. (w, h) is the proposed size and ProportionalConstraint modifies this pair to satisfy the proportionality constraint. Normally, ProportionalConstraint performs its function by changing both, w and h, such that the resulting rectangle satisfies the constraint and that the new rectangle's area is as close to the old rectangle's area as possible. By setting fixedW, the constraint is satisfied by only changing h. Likewise, setting fixedH asks for at most changing w. When both, fixedW and fixedH, are set, then this is ignored and again the area-preserving heuristics is used. Pre w > Views.undefined 20 h > Views.undefined 21 scaleW > Views.undefined 22 scaleH > Views.undefined 23 ~fixedW OR ~fixedH 24 PROCEDURE GridConstraint (gridX, gridY: INTEGER; VAR x, y: INTEGER) Supports forcing the coordinates of a point, such as one of the corners of a view, to the nearest point of a grid. (gridX, gridY) specifies the resolution of the grid in x and y direction, e.g., (5,3) specifies a grid with valid coordinates being multiples of 5 in the x and multiples of 3 in the y direction. Pre gridX > Views.undefined 20 gridY > Views.undefined 21
System/Docu/Properties.odc
Sequencers This module has a private interface, it is only used internally.
System/Docu/Sequencers.odc
Services DEFINITION Services; CONST immediately = -1; now = 0; resolution = 1000; TYPE Action = POINTER TO ABSTRACT RECORD (a: Action) Do-, NEW, ABSTRACT END; PROCEDURE DoLater (a: Action; notBefore: LONGINT); PROCEDURE RemoveAction (a: Action); PROCEDURE Ticks (): LONGINT; PROCEDURE GetTypeName (IN rec: ANYREC; OUT type: ARRAY OF CHAR); PROCEDURE SameType (IN ra, rb: ANYREC): BOOLEAN; PROCEDURE IsExtensionOf (IN ra, rb: ANYREC): BOOLEAN; PROCEDURE Is (IN rec: ANYREC; IN type: ARRAY OF CHAR): BOOLEAN; PROCEDURE Extends (IN type, base: ARRAY OF CHAR): BOOLEAN; PROCEDURE Level (IN type: ARRAY OF CHAR): INTEGER; PROCEDURE TypeLevel (IN rec: ANYREC): INTEGER; PROCEDURE AdrOf (IN rec: ANYREC): INTEGER; PROCEDURE Collect; END Services. This module provides a variety of low-level services. Currently, only a timing service, a background processing service, and a reflection service is provided. Actions are objects whose Do procedures are executed in a delayed fashion, when the system is idle. An action which re-installs itself whenever it is invoked operates as a non-preemptive background task. The reflection service, unlike module Meta, only works on records, and it is also applicable to temporary variables on the stack (while Meta items typically denote long-lived variables). Examples: ObxActionsdocu ObxCubesdocu CONST immediately This value can be passed to DoLater as notBefore parameter, if the action must be executed as part of the currently executing command. CONST now This value can be passed to DoLater as notBefore parameter, if the action should be executed as quickly as possible, after the currently executing command. CONST resolution Time resolution in ticks per second. The current time can be inquired by procedure Ticks. TYPE Action ABSTRACT Actions are objects whose Do procedures are called in a deferred way, when the system is idle again. PROCEDURE (a: Action) Do- NEW, ABSTRACT For a registered action a, a.Do is called eventually, depending how it has been registered (see DoLater). PROCEDURE DoLater (a: Action; notBefore: LONGINT) Register an action. Its Do procedure will be executed once, later when time permits. a.Do is called eventually after Ticks() has reached notBefore, or if notBefore = now. If the action's Do procedure should be executed more than once, it may call DoLater to re-install itself. A particular action can only be registered once; additional attempts have no effect. Pre a # NIL 20 PROCEDURE RemoveAction (a: Action) Remove a registered action. If action a is not registered or NIL, nothing happens. PROCEDURE Ticks (): LONGINT Returns the current time in clock ticks. These ticks have a resolution of resolution., i.e., resolution ticks per second. PROCEDURE GetTypeName (IN rec: ANYREC; OUT type: ARRAY OF CHAR) Returns the name of a record type, in the form "module.type". If a pointer is passed, its record type is returned. If the record is anonymous, the pointer's type name is returned, e.g., "FormViews.StdView". PROCEDURE SameType (IN ra, rb: ANYREC): BOOLEAN Determines whether two record variables have (exactly!) the same type. PROCEDURE IsExtensionOf (IN ra, rb: ANYREC): BOOLEAN Determines whether the record type of ra is the same or an extension of the type of rb. PROCEDURE Is (IN rec: ANYREC; IN type: ARRAY OF CHAR): BOOLEAN Determines whether the record type of rec is the same or an extension of the type given in type (e.g., as "FormViews.View"). If type type was not found, FALSE is returned. Pre type # "" 20 type has form "module.type" 21 PROCEDURE Extends (IN type, base: ARRAY OF CHAR): BOOLEAN Determines whether the record type type is the same or an extension of the type base. If type type or base was not found, FALSE is returned. Pre type # "" & base # "" 20 type and base have form "module.type" 21 PROCEDURE Level (IN type: ARRAY OF CHAR): INTEGER Determines the extension level of a record type type. A newly introduced type has level 0. If type type was not found, -1 is returned. Pre type # "" 20 type has form "module.type" 21 PROCEDURE TypeLevel (IN rec: ANYREC): INTEGER Determines the extension level of a record variable rec's type. A newly introduced type has level 0. PROCEDURE AdrOf (IN rec: ANYREC): INTEGER Returns the address of a record variable. PROCEDURE Collect Forces a garbage collection.
System/Docu/Services.odc
SHELL32 This module is obsolete; use the Win subsystem instead.
System/Docu/SHELL32.odc
SMath Module SMath is identical to Math except that it uses the 32-bit SHORTREAL type instead of the normal 64-bit REAL type.
System/Docu/SMath.odc
Stores DEFINITION Stores; IMPORT Files; CONST alienVersion = 1; alienComponent = 2; inconsistentVersion = -1; inconsistentType = -2; moduleFileNotFound = -3; invalidModuleFile = -4; inconsModuleVersion = -5; typeNotFound = -6; TYPE TypeName = ARRAY 64 OF CHAR; TypePath = ARRAY 16 OF TypeName; OpName = ARRAY 32 OF CHAR; Domain = POINTER TO LIMITED RECORD PROCEDURE (d: Domain) GetSequencer (): ANYPTR, NEW; PROCEDURE (d: Domain) SetSequencer (sequencer: ANYPTR), NEW END; Operation = POINTER TO ABSTRACT RECORD PROCEDURE (op: Operation) Do, NEW, ABSTRACT END; Store = POINTER TO ABSTRACT RECORD PROCEDURE (s: Store) Domain (): Domain, NEW; PROCEDURE (s: Store) CopyFrom- (source: Store), NEW, EMPTY; PROCEDURE (s: Store) Internalize- (VAR rd: Reader), NEW, EMPTY; PROCEDURE (s: Store) Externalize- (VAR wr: Writer), NEW, EMPTY; PROCEDURE (s: Store) ExternalizeAs- (VAR s1: Store), NEW, EMPTY END; Reader = RECORD rider-: Files.Reader; cancelled-: BOOLEAN; readAlien-: BOOLEAN; (VAR rd: Reader) ConnectTo (f: Files.File), NEW; (VAR rd: Reader) Pos (): INTEGER, NEW; (VAR rd: Reader) SetPos (pos: INTEGER), NEW; (VAR rd: Reader) ReadBool (OUT x: BOOLEAN), NEW; (VAR rd: Reader) ReadSChar (OUT x: SHORTCHAR), NEW; (VAR rd: Reader) ReadXChar (OUT x: CHAR), NEW; (VAR rd: Reader) ReadChar (OUT x: CHAR), NEW; (VAR rd: Reader) ReadByte (OUT x: BYTE), NEW; (VAR rd: Reader) ReadSInt (OUT x: SHORTINT), NEW; (VAR rd: Reader) ReadXInt (OUT x: INTEGER), NEW; (VAR rd: Reader) ReadInt (OUT x: INTEGER), NEW; (VAR rd: Reader) ReadLong (OUT x: LONGINT), NEW; (VAR rd: Reader) ReadSReal (OUT x: SHORTREAL), NEW; (VAR rd: Reader) ReadXReal (OUT x: REAL), NEW; (VAR rd: Reader) ReadReal (OUT x: REAL), NEW; (VAR rd: Reader) ReadSet (OUT x: SET), NEW; (VAR rd: Reader) ReadSString (OUT x: ARRAY OF SHORTCHAR), NEW; (VAR rd: Reader) ReadXString (OUT x: ARRAY OF CHAR), NEW; (VAR rd: Reader) ReadString (OUT x: ARRAY OF CHAR), NEW; (VAR rd: Reader) ReadStore (OUT x: Store), NEW; (VAR rd: Reader) ReadVersion (min, max: INTEGER; OUT version: INTEGER), NEW; (VAR rd: Reader) TurnIntoAlien (cause: INTEGER), NEW END; Writer = RECORD rider-: Files.Writer; writtenStore-: Store; (VAR wr: Writer) ConnectTo (f: Files.File), NEW; (VAR wr: Writer) Pos (): INTEGER, NEW; (VAR wr: Writer) SetPos (pos: INTEGER), NEW; (VAR wr: Writer) WriteBool (x: BOOLEAN), NEW; (VAR wr: Writer) WriteSChar (x: SHORTCHAR), NEW; (VAR wr: Writer) WriteXChar (x: CHAR), NEW; (VAR wr: Writer) WriteChar (x: CHAR), NEW; (VAR wr: Writer) WriteByte (x: BYTE), NEW; (VAR wr: Writer) WriteSInt (x: SHORTINT), NEW; (VAR wr: Writer) WriteXInt (x: INTEGER), NEW; (VAR wr: Writer) WriteInt (x: INTEGER), NEW; (VAR wr: Writer) WriteLong (x: LONGINT), NEW; (VAR wr: Writer) WriteSReal (x: SHORTREAL), NEW; (VAR wr: Writer) WriteXReal (x: REAL), NEW; (VAR wr: Writer) WriteReal (x: REAL), NEW; (VAR wr: Writer) WriteSet (x: SET), NEW; (VAR wr: Writer) WriteSString (IN x: ARRAY OF SHORTCHAR), NEW; (VAR wr: Writer) WriteXString (IN x: ARRAY OF CHAR), NEW; (VAR wr: Writer) WriteString (IN x: ARRAY OF CHAR), NEW; (VAR wr: Writer) WriteStore (x: Store), NEW; (VAR wr: Writer) WriteVersion (version: INTEGER), NEW END; AlienComp = POINTER TO LIMITED RECORD next-: AlienComp END; AlienPiece = POINTER TO LIMITED RECORD (AlienComp) next-: AlienComp; pos-, len-: INTEGER END; AlienPart = POINTER TO LIMITED RECORD (AlienComp) next-: AlienComp; store-: Store END; Alien = POINTER TO LIMITED RECORD (Store) path-: TypePath; cause-: INTEGER; file-: Files.File; comps-: AlienComp END; PROCEDURE InitDomain (s: Store); PROCEDURE CopyOf (s: Store): Store; PROCEDURE Join (s0, s1: Store); PROCEDURE Joined (s0, s1: Store): BOOLEAN; PROCEDURE Unattached (s: Store): BOOLEAN; PROCEDURE ExternalizeProxy (s: Store): Store; PROCEDURE Report (IN msg, p0, p1, p2: ARRAY OF CHAR); END Stores. Introduction Module Stores defines a data type Store, which should be used as base type of all storable extensible objects. When storing an object of an extensible type, it is necessary to store not only its contents but also its particular type. The type is needed to create an object of the correct type when reading the data in again. A variable of (an extension of) type Store is stored in a file. A store must implement the Internalize procedure which takes a Reader as parameter, and the Externalize procedure which takes a Writer as parameter. These procedures read/write the store's persistent state. (A store may also have temporary state which is not internalized/externalized.) Readers and writers are mappers on files. The types Views.View and TextModels.Model are examples of Store extensions. Stores may form arbitrary graphs. The "boundary" of a graph is determined by its domain. This is an object that represents the whole collection of stores that can be externalized to a file, or be internalized from a file. The stores of a domain are externalized and internalized such that pointers among them are reconstructed correctly upon internalization. In particular, alias pointers are handled correctly: if several stores point to another element of the same domain, this element is read in only once, and all the pointers to it are rebuilt. Arbitrary graphs can be handled this way, e.g., cyclic data structures. Links to stores of other domains are prohibited. A document consists of a hierarchy of views and models, both of which are stores. Possibly there may occur further stores in a document, such as text attribute objects or controller objects. All stores of a document share the same domain. The stores of a domain may be manipulated indirectly via operation objects. An operation implements a method Do, which must be auto-inverse (i.e., executing it twice undoes its effect). This is the key to the undo/redo mechanism of the compound document architecture of BlackBox. However, in principle it could also be used by a transaction mechanism to implement transactions on persistent non-document data represented as stores. The contents of a store is stored in a file. When reading the same file by another BlackBox configuration, it may occur that not all necessary modules are available in this configuration, i.e., the module which defines the store's type cannot be loaded. Yet reading such an "alien" store does not fail completely. Instead of the correct store type, an "alien" object is generated. Obviously such an alien cannot interpret the data it represents, and therefore cannot provide any special behavior. However, it may be copied and stored into another file, such that its contents on the new file are intact and consistent. To define the set of stores that belong to a domain and to set up an actual domain, two procedures have to be provided by the framework. A first procedure is needed to collect stores in sets and to join store sets, and a second procedure is used to assign an actual domain object to a set of stores. In BlackBox these procedures are Join and InitDomain. They are discussed in more detail below. Join Procedure Join is used to join two store sets. This procedure has to be called whenever a link from a store in one set is established to a store in the other set. As arguments, representatives of the two store sets have to be passed. Join is symmetric. If the two stores which are passed as arguments already belong to the same set, Join has no effect. Figure 1 demonstrates the effect of a Join operation on two store sets X and Y. Figure 1: Effect of a Join operation on two disjoint store sets X and Y. Join calls have to be added at those places where newly created stores are connected, usually in a factory procedure. All those stores have to be joined with a store s which are written to disk in the Externalize method of store s. Join calls are not necessary in the Internalize and CopyOf methods where usually also links between stores are established. Module Stores has sufficient information to join these stores itself. The function Joined allows to test whether two given stores belong to the same store set, i.e., whether they have been joined or not. Joined is symmetric, reflexive and transitive. InitDomain In order to assign an actual domain object to a free store or a store set, the procedure InitDomain is called. As parameter a member of the set (or a single store) is passed. The actual domain object is created inside module Stores (Domain is limited) and then assigned to all stores in the set. After a domain has been assigned to a store graph this domain can be accessed with the Domain() method defined in the Store type. If InitDomain is called on a store which is already assigned to a domain object, then the procedure has no effect. The framework calls InitDomain in module Documents only whenever a new document is created. Usually, there is no need for BlackBox programmers to call InitDomain themselves, except when a deep copy of a document is created. The arguments of Join may or may not be bound to a domain. If only one argument store is bound to a domain, then the effect of Join is that all stores in the other set are bound to the same domain object. If both arguments are bound to a domain then they have to be bound to the same one and Join has no effect, otherwise a precondition trap is raised. The function Joined can be applied on stores independent of whether they are bound to a domain or not. If store s0 or s1 is bound to a domain, then Joined(s0, s1) is equivalent to s0.Domain() = s1.Domain(). The procedures Join and InitDomain specify the following pre and post conditions. PROCEDURE Join (s0, s1: Store) PRE 20 s0 # NIL PRE 21 s1 # NIL PRE 22 s0.Domain() = NIL OR s1.Domain() = NIL OR s0.Domain() = s1.Domain() POST Joined(s0, s1) PROCEDURE InitDomain (s: Store) PRE 20 s # NIL POST s.Domain() # NIL If two stores have to be joined and precondition 22 is not met, then a deep copy of one of the two stores has to be generated using CopyOf. Alias pointers and copying The stores of a domain are externalized and internalized such that pointers among them are reconstructed correctly upon internalization. In particular, alias pointers are handled correctly: if several stores point to a particular element of the same domain, this element is read in only once, and all the pointers to it are rebuilt. Arbitrary graphs can be handled this way, including cyclic data structures. Cloning of stores is provided by procedure CopyOf. This procedure creates a new object and then calls the CopyFrom method with the original object as parameter. This mechanism can conceptually be regarded as writing the store to a file and then reading it back as a clone. Alias pointers are handled correctly. Whenever CopyOf is called, all copied stores are stored in a table which is associated with the store's set of joined stores. All recursive calls of CopyOf can access this information. After the top-level call of CopyOf terminates, the table with the copies is discarded. However, there would be a problem with restoring alias pointers if during a call of CopyOf additional stores are added to the store set which contains the alias information. Therefore, Join(s0, s1) must not be called while a CopyOf operation is active either on s0 or on s1. If such a situation appears, then an implementation trap is raised. This can be avoided by joining the involved stores before copying the store graph. Additional Remarks Aliens Aliens are handled in a special way regarding domains. Since aliens are immutable, they are never copied and can be inserted into any store graph. As a store can only reference one domain, this would violate the rule that a store in a document may not refer to stores that belong to another domain. Therefore, all aliens are assigned a special domain for aliens. Module Stores knows this rule and does not trap if an alien is externalized. Operations and undo Calls of Join or InitDomain on stores are not operations, thus these calls cannot be undone! If stores are joined or assigned to a domain as a side effect of an operation and if the operation is undone, then the asignments which were performed on involved stores are not undone. This may require that a deep copy is generated before an operation is applied to a store graph. Shallow copies Module Views offers a procedure CopyOf which allows to make shallow copies of views. A shallow copy of a view means that the copy refers to the same model like the original. As models and views are always joined, this implies that a view and its shallow copy are also joined. Inspecting a store set A store set cannot be inspected programmatically beyond what is offered by procedure Joined. However, the debugger allows to iterate over all stores in a store set. The stores which belong to the same store set are linked in a circular list. As soon as a domain object is associated to the set, the links are set to NIL and each store in the set refers to the new domain object. To iterate over a store set the debugger has to be called before the store set is bound. Then, the stores can be iterated with the store's next field. Listing 2 shows a simple procedure which generates an empty text view and then opens the debugger. Following the next fields of the view v, you see that the following seven stores are joined in one set: TextModels.Model, TextModels.Attributes, TextRulers.Ruler, TextRulers.Style, TextRulers.Attributes, TextViews.View and TextControllers.Controller. MODULE Test; IMPORT TextViews, TextModels; PROCEDURE Do*; VAR v: TextViews.View; BEGIN v := TextViews.dir.New(TextModels.dir.New()); HALT(0); END Do; END Test. Listing 2: Inspecting the stores in a store set Unattached Function Unattached(s) tests whether a store s has been joined to other stores or was bound to a domain. If neither is the case Unattached returns TRUE. This function is only provided by the framework to decide whether a single store can be simply joined to another store graph or whether a deep copy must be generated; e.g., for a store that is kept in a cache and which may be joined to different store graphs. For this special purpose the following code pattern is used. In this example, store s1 is copied if it is attached. This way an unnecessary copy call in the case that the store is unattached is prevented. IF ~Stores.Joined(s0, s1) THEN IF ~Stores.Unattached(s1) THEN s1 := Stores.CopyOf(s1) END; Stores.Join(s0, s1) END; The pattern is not symmetric because it is often known statically that either s0 or s1 should never be copied. It is used for small stores which are generated once and which may be joined to different store sets. Data types Stores provides a pair of mapper types, which are used as parameters in a store's Internalize and Externalize procedures. These readers/writers use the following external (little endian) format: BOOLEAN 1 byte (0 = FALSE, 1 = TRUE) SHORTCHAR 1 byte in the Latin-1 character set (i.e., Unicode page 0; 00X..0FFX) CHAR 2 byte in the Unicode character set (0000X..0FFFFX) BYTE 1 byte (-128..127) SHORTINT 2 bytes (-32768..32767) INTEGER 4 bytes (-2147483648..2147483647) LONGINT 8 bytes (-9223372036854775808..9223372036854775807) SHORTREAL 4 bytes IEEE format REAL 8 bytes IEEE format SET 4 bytes (least significant bit = element 0) Short String string in the Latin-1 character set, followed by a 00X String string in the Unicode character set, followed by a 0000X CONST alienVersion This value is assigned to a Reader's cause field if Reader.ReadVersion read a version outside of the specified range. CONST alienComponent This value can be used as cause parameter to Reader.TurnIntoAlien to indicate that the store itself could be read, but that some store contained in it is an alien. As an example, a view may turn itself into an alien if its model is an alien. CONST inconsistentVersion This value is assigned to a Reader's cause field if Reader.ReadVersion read a data block which has an inconsistent length, i.e., not all of its data have been read, or it has been attempted to read beyond the end of the data. CONST inconsistentType This value is assigned to a Reader's cause field if Reader.ReadVersion detected a change in the type extension hierarchy of the internalized type. CONST moduleFileNotFound This value is assigned to a Reader's cause field if Reader.ReadVersion tried to load a module defining an internalized type, and the codefile for this module couldn't be found. CONST invalidModuleFile This value is assigned to a Reader's cause field if Reader.ReadVersion tried to load a module defining an internalized type, and the module couldn't be loaded because it imports another module which cannot be loaded for some reason. CONST inconsModuleVersion This value is assigned to a Reader's cause field if Reader.ReadVersion tried to load a module defining an internalized type, and the module couldn't be loaded because its version is inconsistent with some already loaded module. CONST typeNotFound This value is assigned to a Reader's cause field if Reader.ReadVersion tried to internalize a non-existing type (the module was found, however). TYPE TypeName String type for the type name of an object. TYPE TypePath Array of type names. TYPE OpName String type for the name of an operation. TYPE Domain LIMITED A domain represents a graph of stores which may be saved in a file as a whole. All stores of a domain refer to an object of type Domain. PROCEDURE (d: Domain) GetSequencer (): ANYPTR NEW Used internally. PROCEDURE (d: Domain) SetSequencer (sequencer: ANYPTR) NEW Used internally. TYPE Operation ABSTRACT An operation is an object that represents a command performed on some store(s) of a domain. An operation can be undone (i.e., aborted) and redone. PROCEDURE (op: Operation) Do NEW, ABSTRACT This method implements the actual behavior of the operation. It must be auto-inverse, i.e., if executed an even number of times, it must have no effect. If executed an odd number of times, it should have the same effect. TYPE Store ABSTRACT Storable extensible data types like Views.View or TextModels.Text are derived from Store. Stores are typically allocated by suitable directories, e.g., Views.Directory or TextModels.Directory. Stores are used as base types for all objects that must be both extensible and persistent. PROCEDURE (s: Store) Domain (): Domain NEW A store may be associated with a domain. This is done by the procedure InitDomain, which assigns a domain to the store. Domain may be called by arbitrary clients. PROCEDURE (s: Store) CopyFrom- (source: Store) NEW, EMPTY Copy the contents of source to s. Copying is a deep copy. Pre source # NIL guaranteed TYP(source) = TYP(s) guaranteed s.Domain() = NIL guaranteed s is not yet initialized guaranteed PROCEDURE (s: Store) Internalize- (VAR rd: Reader) NEW, EMPTY (For backward compatibility, this method is actually still EXTENSIBLE. This may change in the future.) Reads the contents of s from reader rd. Internalize must read the same (amount of) data as is written by the corresponding Externalize procedure. Internalize is called locally. Internalize is extended by various persistent object types, e.g., models, views, and controllers. Pre source.Domain() = NIL guaranteed source is not yet initialized guaranteed PROCEDURE (s: Store) Externalize- (VAR wr: Writer) NEW, EMPTY (For backward compatibility, this method is actually still EXTENSIBLE. This may change in the future.) Write the contents of s to writer wr. Externalize must write the same (amount of) data as is read by the corresponding Internalize procedure. Externalize ist called locally. Externalize is extended by various persistent object types, e.g., models, views, and controllers. PROCEDURE (s: Store) ExternalizeAs- (VAR s1: Store) NEW, EMPTY Before a store's Externalize procedure is called, its ExternalizeAs procedure is called, which gives the store the opportunity to denote another store that should be externalized in its place (a "proxy"). It is also possible to set s1 to NIL, which means that the store should not be externalized at all. This is used e.g. for compiler error markers, which are never stored. ExternalizeAs ist called locally. Pre s1 = s guaranteed TYPE Reader Reader for Component Pascal values like integers, reals, or sets. A reader contains a Files.Reader, to which it forwards most operations. Readers are used in the Store.Internalize procedure. Readers are not extensible. rider-: Files.Reader The file rider which links a Reader to a file. cancelled-: BOOLEAN valid during a Store.Internalize call Tells whether the currently executing Internalize has been called by ReadVersion or TurnIntoAlien. readAlien-: BOOLEAN Tells whether any alien has been read since the last ConnectTo. PROCEDURE (VAR rd: Reader) ConnectTo (f: Files.File) NEW Connect the reader to a file. All the following operations require connected readers, i.e., rd.rider # NIL. This precondition is not checked explicitly, however. After connecting, the reader's position is at the beginning of the file. If the same reader should be reused on another file, it must first be closed, by connecting it to NIL. ConnectTo is used internally. Pre 20 (f = NIL) OR (rd.rider = NIL) Post f = NIL rd.rider = NIL f # NIL (rd.rider # NIL) & (rd.rider.Base() = f) rd.Pos() = 0 PROCEDURE (VAR rd: Reader) Pos (): INTEGER NEW Returns the reader's current position. Post 0 <= result <= rd.rider.Base().Length() PROCEDURE (VAR rd: Reader) SetPos (pos: INTEGER) NEW Sets the reader's current position to pos. Pre 20 pos >= 0 21 pos <= rd.rider.Base().Length() Post rd.Pos() = pos ~rd.rider.eof PROCEDURE (VAR rd: Reader) ReadBool (OUT x: BOOLEAN) NEW Reads a Boolean value. PROCEDURE (VAR rd: Reader) ReadSChar (OUT x: SHORTCHAR) NEW Reads a short character (00X..0FFX). PROCEDURE (VAR rd: Reader) ReadXChar (OUT x: CHAR) NEW Same as ReadSChar, but has a CHAR-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR rd: Reader) ReadChar (OUT x: CHAR) NEW Reads a character (0000X..0FFFFX). PROCEDURE (VAR rd: Reader) ReadByte (OUT x: BYTE) NEW Reads a very short integer (-128..127). PROCEDURE (VAR rd: Reader) ReadSInt (OUT x: SHORTINT) NEW Reads a short integer (-32768..32767). PROCEDURE (VAR rd: Reader) ReadXInt (OUT x: INTEGER) NEW Same as ReadSInt, but has an INTEGER-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR rd: Reader) ReadInt (OUT x: INTEGER) NEW Reads an integer (-2147483648..2147483647). PROCEDURE (VAR rd: Reader) ReadLong (OUT x: LONGINT) NEW Reads a long integer (-9223372036854775808..9223372036854775807). PROCEDURE (VAR rd: Reader) ReadSReal (OUT x: SHORTREAL) NEW Reads a short real (32-bit IEEE number). PROCEDURE (VAR rd: Reader) ReadXReal (OUT x: REAL) NEW Same as ReadSReal, but has a REAL-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR rd: Reader) ReadReal (OUT x: REAL) NEW Reads a real (64-bit IEEE number). PROCEDURE (VAR rd: Reader) ReadSet (OUT x: SET) NEW Reads a set (32 elements). PROCEDURE (VAR rd: Reader) ReadSString (OUT x: ARRAY OF SHORTCHAR) NEW Reads a 0X-terminated short string. Pre invalid index LEN(x) > Length(string) PROCEDURE (VAR rd: Reader) ReadXString (OUT x: ARRAY OF CHAR) NEW Same as ReadSString, but has a string-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR rd: Reader) ReadString (OUT x: ARRAY OF CHAR) NEW Reads a 0X-terminated string. Pre invalid index LEN(x) > Length(string) PROCEDURE (VAR rd: Reader) ReadStore (OUT x: Store) NEW Reads a store's type, allocates it, and then reads its contents, by calling the store's Internalize procedure. x may also be NIL, or an alien if the store's module cannot be loaded, or if internalization has been cancelled by the Internalize procedure. If the store has already been read in, a pointer to the same store is returned instead of allocating a new one. This means that arbitrary graphs that have been written with WriteStore are reconstructed correctly, including alias pointers to the same store, cycles, etc. If the file on which the reader operates does not contain correct input, then an assertion trap will be caused (traps 101 to trap 106). Pre 20 the reader is at the start position of a new store Post empty store on file x = NIL non-empty store on file x # NIL x IS Alien x.cause # 0 x.type # "" x.file # NIL x.pos >= 0 beginning of store's data x.len >= 0 length of store's data alien store contents are on x.file in the range [x.pos .. x.pos + x.len[. These data include only the store's contents, not its prefix ~(x IS Alien) x was read successfully PROCEDURE (VAR rd: Reader) ReadVersion (min, max: INTEGER; OUT version: INTEGER) NEW Read a version byte and return it in version. If version is not in the specified range [min .. max], the store currently being read is turned into an alien, with cause = alienVersion. Pre 20 0 <= min <= max Post min <= version <= max legal version (version < min) OR (version > max) illegal version rd.cause = alienVersion rd.cancelled rd.readAlien PROCEDURE (VAR rd: Reader) TurnIntoAlien (cause: INTEGER) NEW A store which is currently being internalized can turn itself into an alien, e.g., if it has read a component store which is an alien. Pre 20 cause > 0 TYPE Writer Writer for Component Pascal values like integers, reals, or sets. A writer contains a Files.Writer, to which it forwards most operations. Writers are used in the Externalize procedure. Writers are not extensible. rider-: Files.Writer A file rider which links a Writer to a file. writtenStore-: Store Store which was most recently written as an effect of a call to WriteStore. PROCEDURE (VAR wr: Writer) ConnectTo (f: Files.File) NEW Connect the writer to a file. All the following operations require connected writers, i.e., wr.rider # NIL. This precondition is not checked explicitly, however. After connecting, the writer's position is at the end of the file. If the same writer should be reused on another file, it must first be closed, by connecting it to NIL. ConnectTo is used internally. Pre 20 (f = NIL) OR (wr.rider = NIL) Post f = NIL wr.rider = NIL f # NIL wr.rider # NIL & wr.rider.Base() = f wr.Pos() = wr.rider.Base().Length() PROCEDURE (VAR wr: Writer) Pos (): INTEGER NEW Returns the writer's current position. Post 0 <= result <= wr.rider.Base().Length() PROCEDURE (VAR wr: Writer) SetPos (pos: INTEGER) NEW Sets the writer's current position to pos. Pre 20 pos >= 0 21 pos <= wr.rider.Base().Length() Post wr.Pos() = pos PROCEDURE (VAR wr: Writer) WriteBool (x: BOOLEAN) NEW Writes a Boolean value. PROCEDURE (VAR wr: Writer) WriteSChar (x: SHORTCHAR) NEW Writes a character (00X..0FFX). PROCEDURE (VAR wr: Writer) WriteXChar (x: CHAR) NEW Same as WriteSChar, but has a CHAR-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR wr: Writer) WriteChar (x: CHAR) NEW Writes a character (0000X..0FFFFX). PROCEDURE (VAR wr: Writer) WriteByte (x: BYTE) NEW Writes a very short integer (-128..127). PROCEDURE (VAR wr: Writer) WriteSInt (x: SHORTINT) NEW Writes a short integer (-32768..32767). PROCEDURE (VAR wr: Writer) WriteXInt (x: INTEGER) NEW Same as WriteSInt, but has an INTEGER-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR wr: Writer) WriteInt (x: INTEGER) NEW Writes an integer (-2147483648..2147483647). PROCEDURE (VAR wr: Writer) WriteLong (x: LONGINT) NEW Writes a long integer (-9223372036854775808..9223372036854775807). PROCEDURE (VAR wr: Writer) WriteSReal (x: SHORTREAL) NEW Writes a real (32-bit IEEE number). PROCEDURE (VAR wr: Writer) WriteXReal (x: REAL) NEW Same as WriteSReal, but has a REAL-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR wr: Writer) WriteReal (x: REAL) NEW Writes a long real (64-bit IEEE number). PROCEDURE (VAR wr: Writer) WriteSet (x: SET) NEW Writes a set (32 elements). PROCEDURE (VAR wr: Writer) WriteSString (IN x: ARRAY OF SHORTCHAR) NEW Writes a 0X-terminated short string. PROCEDURE (VAR wr: Writer) WriteXString (IN x: ARRAY OF CHAR) NEW Same as WriteSString, but has a string-type parameter. This procedure is provided to simplify migration from Release 1.2 to 1.3. PROCEDURE (VAR wr: Writer) WriteString (IN x: ARRAY OF CHAR) NEW Writes a 0X-terminated string. PROCEDURE (VAR wr: Writer) WriteStore (x: Store) NEW Writes the store's type and then its contents, by calling the store's Externalize procedure. x may also be NIL, or an alien. Before Externalize, ExternalizeAs is called in order to give the store the opportunity to denote a proxy which should be stored in its stead. WriteStore writes x and (via Externalize) all the stores that it contains. Cycles are handled correctly, i.e., a store is only written once, even if referenced several times in a complex graph. All stores that are written using the same writer must have the identical domain. Pre 20 wr.rider # NIL 21 x # NIL => writer must have no domain, or the same one as x (and as all previously written stores) PROCEDURE WriteVersion (version: INTEGER) NEW Writes a version byte. Pre 20 0 <= version <= 127 TYPE AlienComp, AlienPiece, AlienPart, Alien LIMITED These auxiliary types are used internally, to handle alien stores. PROCEDURE Join (s0, s1: Store) Join two stores in the same store set. See the explanation at the beginning of this text. Pre 20 s0 # NIL 21 s1 # NIL 22 s0.Domain() = NIL OR s1.Domain() = NIL OR s0.Domain() = s1.Domain() Post Joined(s0, s1) PROCEDURE Joined (s0, s1: Store): BOOLEAN Test whether two stores are joined. Joined(x, x) always returns TRUE, i.e., it is reflexive. Pre 20 s0 # NIL 21 s1 # NIL PROCEDURE Unattached (s: Store): BOOLEAN Tests whether s is not attached to a domain and whether it has not been joined with another store. Rarely used. Pre 20 s # NIL PROCEDURE CopyOf (s: Store): Store Returns the clone of a store, with its contents copied. CopyOf allocates a new record with the same dynamic type as s, and initializes it by calling its CopyFrom procedure. The copy is a deep copy. Pre 20 s # NIL Post (result # NIL) & (result # s) TYP(result) = TYP(s) PROCEDURE InitDomain (s: Store) Initializes the domain of store s. See the explanation at the beginning of this text. Pre 20 s # NIL Post s.Domain() # NIL PROCEDURE ExternalizeProxy (s: Store): Store Causes s to call its ExternalizeAs method, basically doing the following: IF s # NIL THEN s.ExternalizeAs(s) END; RETURN s PROCEDURE Report (IN msg, p0, p1, p2: ARRAY OF CHAR) When a store encounters a problem during internalization, it can report the problem by calling this procedure. The parameters are similar to Dialog.ShowParamMsg.
System/Docu/Stores.odc
Strings DEFINITION Strings; CONST charCode = -1; decimal = 10; hexadecimal = -2; roman = -3; digitspace = 8FX; hideBase = FALSE; showBase = TRUE; PROCEDURE Valid (IN s: ARRAY OF CHAR): BOOLEAN; PROCEDURE Extract (s: ARRAY OF CHAR; pos, len: INTEGER; OUT res: ARRAY OF CHAR); PROCEDURE Find (IN s: ARRAY OF CHAR; IN pat: ARRAY OF CHAR; start: INTEGER; OUT pos: INTEGER); PROCEDURE Replace (VAR s: ARRAY OF CHAR; pos, len: INTEGER; IN rep: ARRAY OF CHAR); PROCEDURE Lower (ch: CHAR): CHAR; PROCEDURE Upper (ch: CHAR): CHAR; PROCEDURE ToLower (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR); PROCEDURE ToUpper (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR); PROCEDURE IntToString (x: LONGINT; OUT s: ARRAY OF CHAR); PROCEDURE IntToStringForm (x: LONGINT; form, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN; OUT s: ARRAY OF CHAR); PROCEDURE RealToString (x: REAL; OUT s: ARRAY OF CHAR); PROCEDURE RealToStringForm (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR; OUT s: ARRAY OF CHAR); PROCEDURE StringToInt (IN s: ARRAY OF CHAR; OUT x, res: INTEGER); PROCEDURE StringToLInt (IN s: ARRAY OF CHAR; OUT x: LONGINT; res: INTEGER); PROCEDURE StringToReal (IN s: ARRAY OF CHAR; OUT x: REAL; OUT res: INTEGER); END Strings. Module Strings is a simple and small string library. Its goal is to provide a few string operations that are both often needed and complicated to implement, in particular routines for conversions between numbers and strings. The library is optimized for convenience, not for efficiency. This tradeoff is apparent in that some operations, such as Extract, use value parameters instead of IN parameters. This allows to pass the same variable both for input and output purposes, which is often convenient (a variable should never be passed to several IN/OUT/VAR parameters simultaneously, since this may cause interference between them). It is not a goal to provide operations for all possible circumstances, since string processing in different applications simply varies to much to make this practical. Often it is useful to write a few string operations fully tailored to a particular application, which is usually easy to do. Moreover, such custom string operations can be optimized for speed, which is not possible for too general routines. Note that the language Component Pascal provides efficient built-in support for string assignment (implicitly or explicitly with the "$" operator), for string concatenation (with the "+" operator), and for counting the number of characters in a string (LEN(string$)). CONST charCode Possible value for parameter form of IntToStringForm, asking for formatting integers following the syntax of Component Pascal numerical character literals, e.g., 0DX or 37X. CONST decimal Possible value for parameter form of IntToStringForm, asking for formatting integers as decimal literals. CONST hexadecimal Possible value for parameter form of IntToStringForm, asking for formatting integers as hexadecimal literals. CONST roman Possible value for parameter form of IntToStringForm, asking for formatting integers as roman literals. CONST digitspace A digit space has the width of digit zero (0) which is equivalent to the width of all digits in most fonts, thus can be used for number formatting. CONST hideBase, showBase Possible values for parameter showBase of IntToStringForm, asking for showing / suppressing the base of the number format. PROCEDURE Valid (IN s: ARRAY OF CHAR): BOOLEAN Returns TRUE if and only if the array s contains at least one string terminator 0X. Post s contains a 0X character result = TRUE s does not contain a 0X character result = FALSE PROCEDURE Upper (ch: CHAR): CHAR Conversion to uppercase characters. Handles the entire ISO Latin-1 character set. Character values that have no uppercase equivalent (and Unicodes outside of Latin-1) are returned unchanged. PROCEDURE Lower (ch: CHAR): CHAR Conversion to lowercase characters. Handles the entire ISO Latin-1 character set. Character values that have no lowercase equivalent (and Unicodes outside of Latin-1) are returned unchanged. PROCEDURE ToLower (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR) Converts string in to lowercase characters and returns the result in out. Handles the entire ISO Latin-1 character set. Character values that have no lowercase equivalent (and Unicodes outside of Latin-1) are unchanged. The same actual parameter may be passed for in and out. Pre Valid(in) index trap Post Valid(out) PROCEDURE ToUpper (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR) Converts string in to uppercase characters and returns the result in out. Handles the entire ISO Latin-1 character set. Character values that have no uppercase equivalent (and Unicodes outside of Latin-1) are unchanged. The same actual parameter may be passed for in and out. Pre Valid(in) index trap Post Valid(out) PROCEDURE Extract (s: ARRAY OF CHAR; pos, len: INTEGER; OUT res: ARRAY OF CHAR) Extracts the stretch [pos, MIN(pos+len, Len(s))) from s and returns it in res. The result is truncated if res is not large enough. The same actual parameter may be passed for s and res. Pre len >= 0 20 pos >= 0 21 Valid(s) (not checked) Post Valid(res) LEN(res$) = MAX(MIN(len, LEN(s'$)-pos, LEN(res)-1), 0) PROCEDURE Replace (VAR s: ARRAY OF CHAR; pos, len: INTEGER; IN rep: ARRAY OF CHAR) Replaces the stretch [pos, MIN(pos+len, Len(s))) in s with the string in rep. The characters after the replaced stretch are moved if necessary. The result is truncated if s is not large enough. Hint: if len = 0 then rep is inserted in s at position pos. If LEN(rep$) = 0 then the stretch [pos, MIN(pos+len, LEN(s$))) is deleted from s. Pre len >= 0 20 pos >= 0 21 Valid(s) & Valid(rep) (not checked) Post Valid(s) PROCEDURE Find (IN s: ARRAY OF CHAR; IN pat: ARRAY OF CHAR; start: INTEGER; OUT pos: INTEGER); Searches the first occurrence of the pattern pat in string s after position start. If the pattern is found, the position of the first character of the pattern in s is returned in pos. If the pattern is not found, pos is -1. Pre start >= 0 20 Valid(s) & Valid(pat) (not checked) Post pattern found pos is start position of pat in s pattern not found pos = -1 PROCEDURE IntToStringForm (x: LONGINT; form, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN; OUT s: ARRAY OF CHAR) Convert integer x into string s. If form is charCode or hexadecimal, x is converted to a base 16 representation. The total representation will at least have a width of minWidth characters, where padding (if required) takes place to the left using characters as specified by fillCh. If showBase is TRUE, a suffix character is appended to the number representation according to the number form. The value form = charCode renders the suffix "X", while form = hexadecimal renders the suffix "H". These values of form also represent negative integers using a base-complement form of width minWidth, i.e., for negative hexadecimal numbers, fillCh is ignored and "F" is used instead (both for form = charCode and form = hexadecimal). For form values in the range 2..16, base-complement representation is not supported. E.g. x = -3, form = 16, minWidth = 4, fillCh = " " and showBase = FALSE renders a result of -3 x = -3, form = hexadecimal, minWidth = 4, fillCh = " " and showBase = FALSE renders a result of FFFD If showBase is TRUE and form is in the range 2..16, then the base is appended to the number, preceded by a "%" sign (e.g., "10111001%2"). If form = roman (roman numbers), then showBase is ignored. The following conditions imply that s is large enough to hold the resulting string (Pre 23): form = roman: LEN(s) > MAX(minWidth, 15) (form = charCode) OR (form = hexadecimal) OR (form >= 2) & (form <= 16): LEN(s) > MAX(minWidth, 4 + <number of digits>) Where <number of digits> is 1 + Floor(Logbase(ABS(x))), if ABS(x) >= 1, and 1 otherwise. Note that these values are non-tight upper bounds of the required string length. In individual cases, actual requirements might be lower but the given bounds guarantee compliance with the precondition. Pre (form = charCode) OR (form = hexadecimal) OR (form = roman) OR ((form >= 2) & (form <= 16)) 20 (form # roman) OR (form = roman) & (x > 0) & (x < 3999) 21 minWidth >= 0 22 s is large enough to hold resulting string (see above) 23 Post Valid(s) PROCEDURE IntToString (x: LONGINT; OUT s: ARRAY OF CHAR) Write integer in default format. Except for performance, equivalent to: IntToStringForm(x, decimal, 0, digitspace, FALSE, s) PROCEDURE RealToStringForm (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR; OUT s: ARRAY OF CHAR) Convert real x into string s. The string created to represent the number is either in fixed point or in scientific format, according to expW. precision denotes the number of valid decimal places (usually 7 for short reals and 16 for reals). minW denotes the minimal length in characters. If necessary, preceding fillCh will be inserted. Numbers are always rounded to the last valid and visible digit. expW > 0: exponential format (scientific) with at least expW digits in the exponent. expW = 0: fixpoint or floatingpoint format, depending on x. expW < 0: fixpoint format with -expW digits after the decimal point. The following conditions imply that s is large enough to hold the resulting string (Pre 23): (x = inf) OR (x = -inf) OR (x = nan): LEN(s) > MAX(minW, 4) expW >= 0: LEN(s) > MAX(minW, precision + 7) expW < 0: LEN(s) > MAX(minW, 3 - expW + <number of digits before the decimal point>) Where the <number of digits before the decimal point> is 1 + Floor(Log10(ABS(x))), if ABS(x) >= 1, and 1 otherwise. Note that these values are non-tight upper bounds of the required string length. In individual cases, actual requirements might be lower but the given bounds guarantee compliance with the precondition. Pre precision > 0 20 0 <= minW < LEN(s) 21 -LEN(s) < expW <= 3 22 s is large enough to hold resulting string (see above) 23 Pos Valid(s) PROCEDURE RealToString (x: REAL; OUT s: ARRAY OF CHAR) Write real in default format. Except for performance, equivalent to: RealToStringForm(x, 16, 0, 0, digitspace, s) PROCEDURE StringToInt (IN s: ARRAY OF CHAR; OUT x, res: INTEGER) PROCEDURE StringToLInt (IN s: ARRAY OF CHAR; OUT x: LONGINT; res: INTEGER) Converts the number contained in string s into value x. Legal integer number representations follow the syntax given below. Possible result codes are res = 1 for overflow, res = 2 for syntax error. Syntax: number = ( [ "+" | "-" ] dec | hex ) 0X . dec = digit { digit } . hex = hexdigit { hexdigit } ("H" | "X") . hexdigit = digit | "A" | "B" | "C" | "D" | "E" | "F" . digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" . Post s is legal integer number representation x is converted integer number res = 0 s is not a legal integer number representation res # 0 PROCEDURE StringToReal (IN s: ARRAY OF CHAR; OUT x: REAL; OUT res: INTEGER) Converts string s given in fixed or scientific notation into value x. Possible result codes are res = 1 for overflow, res = 2 for syntax error. Post s is legal real number representation x is converted real number res = 0 s is not legal real number representation res # 0
System/Docu/Strings.odc
Map to the BlackBox Core Miscellaneous Config In Out XYplane BlackBox Component Framework Containers Controls Properties Controllers Printing Views Converters Models Ports Stores Fonts BlackBox Component Library Integers Files Dialog Math Strings Dates Services Meta
System/Docu/Sys-Map.odc
BlackBox Component Builder User Manual Contents 1Overview 2Conventions 3Installation(Windowsonly) 4Serverinstallation(Windowsonly) 5Deinstallation 6DocumentWindows,ToolWindows,AuxiliaryWindows 7DocumentSize 8MenuConfiguration 9StringResources 10StandardCommands 10.1FileMenu 10.2EditMenu 10.3FontMenu(MacOS) 10.4AttributesMenu 10.5WindowMenu(Windows)/WindowsMenu(MacOS) 11CustomCommands Further user manuals TextSubsystem FormSubsystem DevSubsystem 1 Overview This document serves as a user's guide for BlackBox programmers. It is not intended as a manual for the end user of software written with the BlackBox Component Builder. Knowledge of the underlying platform's user interface guidelines is assumed. With the BlackBox Component Builder, there are no separate environments for developing programs, for testing and debugging programs, or for the distribution of programs. Instead there is only one, truly integrated, environment for all these purposes. A distribution version of a BlackBox application can be created simply by stripping away all tools which are specific to the development process. Neither development tools (the Dev-subsystem) nor documentation may be distributed. However, all other parts of BlackBox may be freely distributed along with applications; there are no royalties or other fees. Such a customized BlackBox environment always has the basic capabilities of the BlackBox Component Framework's compound document architecture, and of the standard text and form subsystems. Furthermore, it constitutes a standard Windows or Mac OS application, where the (boot) application can be double-clicked, where documents can be dropped onto the application icon to open them, etc. "Native" applications which are only developed under, but not based on, the BlackBox Component Builder can be created as well. For this purpose, a linker tool is provided. Normally, Component Pascal modules are linked and loaded dynamically, such that a separate linker is not strictly necessary. However, it is possible even for pure BlackBox applications to link or pack all or some of their modules together, in order to reduce the number of files to distribute. For further information about this topic, refer to the document Platform-SpecificIssues. On-line documentation: Text stretches which are blue and underlined are hyperlinks, and can be followed by clicking on them. When working in the BlackBox Component Builder environment for the first time, the following may be helpful to remember: almost all modifications to BlackBox documents are undoable, making it quite safe to try out a feature. In general, multiђlevel undo/redo is available, i.e., not only one, but several commands can be undone; as many as memory permits. Mac OS: Whenever the system is working on the completion of some command for more than a fraction of a second, BlackBox changes the cursor to a special busy cursor sequence, i.e., a cursor which changes its shape as long as the command is running. However, this does not guarantee that the executing program does make any progress. For example, the busy cursor will keep advancing, even if the program entered an endless loop. Use command-option-. to terminate such a program. Note that it may take a few seconds before you see a reaction. Windows: On Windows NT and Windows 95, an endless loop can be terminated with ctrl-break. 2 Conventions The contents of this documentation mostly applies to both the Windows and Mac OS versions of the BlackBox Component Builder. Where there are differences, e.g., a feature only available on one platform, this is clearly indicated, e.g., as in the previous paragraph. In order to reduce the number of such platform-specific remarks, a few notational conventions are followed: Mac OS folders are called (sub)directories. Path names contain "/" as directory separators, as in Unix and in the World-Wide Web. File and directory names contain both capital and small letters. In chapters which are not Windows-specific, document file names are given without the ".odc" suffix used in Windows. Thus the file name Text/Rsrc/Find under Windows corresponds to Text\Rsrc\Find.odc, and to Text:Rsrc:Find under Mac OS. modifier key: on Windows this is the ctrl key, on Mac OS this is the option key. menu commands: M->I is a shorthand notation for menu item I in menu M, e.g. File->New. Differences between Windows and Mac OS may be denoted in three different ways: large differences are handled by giving two different sections, one for each platform. In this case, the section title ends in "(Windows only)" or "(Mac OS only)". If not indicated otherwise, the next section will apply to both platforms again. Smaller differences are described as short notes, typically there is a note on Windows-specific behavior, followed by a note on Mac OS-specific behavior. There is an example at the end of the previous section. For small differences, both versions are given in the same sentence, e.g. "To drag & pick, hold down the alt key (Windows) / command key (Mac OS) while dragging." 3 Installation (Windows only) The BlackBox Component Builder requires a PC with an i386 or better, with Windows 95, Windows 98 (SE / ME), Windows NT, Windows 2000, Windows XP, or Windows Server 2003. A two-button mouse is sufficient, but a three-button mouse is recommended (see the chapter Windows 95 user interface guidelines). The resulting BlackBox directory contains several files and directories: Files: BlackBox.exe The BlackBox Component Framework boot application. BlackBox.exe.manifest Manifest file for BlackBox.exe. Empty.odc Empty BlackBox Component Builder document. Tour.odc A quick tour through the BlackBox Component Builder. unins000.dat Data file for BlackBox Component Builder Uninstall. unins000.exe BlackBox Component Builder Uninstall. Directories: Com Direct-To-COM Compiler. Comm Communications subsystem. Ctl OLE Automation support. Dev Development subsystem. Docu On-line documentation not specific to a particular module or subsystem. Dtf dtF driver for the Sql subsystem. Form Form subsystem with the visual designer. Host Private code of BlackBox. Obx Obx subsystem, a collection of examples. Ole OLE compound document support. Sql Sql subsystem for accessing relational databases. Std A number of command packages available to the user. System Core of the BlackBox Component Framework. Text Text subsystem, with the standard document/program editor. Win Interface modules for direct Windows API access. Xhtml Exporter for text to HTML conversion. 4 Server installation (Windows only) If several developers use BlackBox on the same machine(s), it becomes cumbersome to save one's work and clean up after the end of each session, so that the next developer gets a "clean" system again. It is even more cumbersome to start working with a copy that hasn't been cleaned up correctly by the previous user. To solve this problem, server support is available for BlackBox. BlackBox can be installed and maintained on one central server, while developers use an arbitrary number of client workstations on a local-area network. Preferably, each developer has his or her own working directory on the server (account). Note that with the Classic Edition of BlackBox you need seperate licenses for each developer seat using the server installation. For the installation, follow these steps: 1) Install BlackBox in a directory on the server machine, using Setup.exe. The directory must be shared on the network but the access may be restricted to read only. 2) For each workstation / user, create a working directory (either on the server or on the client). The user should have read/write access to this directory. The directory may be empty. 3) For each workstation, create a shortcut with the following contents: Command Line (Target): "<BlackBoxFDir>\BlackBox.exe /Use <WorkDir>" Working Directory (Start in): "<WorkDir>" where <BlackBoxFDir> stands for the full path name of the directory where BlackBox is installed (on the server), and <WorkDir> is the path of the working directory of the actual machine (on the client or on the server). The latter must not end with a backslash ("\"). Example: Command Line (Target): "S:\BLACKBOX\BlackBox.exe /Use C:\BLACKBOX" Working Directory (Start in): "C:\BLACKBOX" These features, originally introduced for situations where multiple users want to develop with BlackBox, can also be useful in a single-user environment. The idea is to have one directory with the original installation of BlackBox, and a separate directory for all the developer-specific files. If the user opens a file, it is first searched in his or her working directory. If it isn't found there, the corresponding file in the "server directory" is opened. When a file is saved, it is always saved in the working directory. This makes it easy to set up entirely separate projects simply by creating separate working directories for them. When an upgrade of BlackBox comes out, only the central "server directory" needs to be upgraded. If you use the server features in this way, without having multiple developers using the same installation simultaneously, then no special license is required. 5 Deinstallation In the Windows Control Panel, choose Add/Remove Programs. In the displayed list, locate the entry called BlackBox and select the Change/Remove button. Follow the instructions on the screen. 6 Document Windows, Tool Windows, Auxiliary Windows There are three kinds of windows in BlackBox: document windows, tool windows, and auxiliary windows. A document window may contain e.g. a text or a form layout, or any other kind of visual object ("view"). When the contents of a document window have been modified (made "dirty") and the user tries to close the window (or quit the application), the system asks whether it should save the document. A tool window allows to invoke actions on some document window underneath it. Typically, tool windows are used for modeless dialog boxes. Windows: Tool windows look the same way as dialog boxes. Mac OS: Tool windows look the same way as modeless dialog boxes, i.e. the same way as document windows. In order to make it possible for the user to distinguish tool and document windows, titles of tool windows are put between "<<" and ">>" brackets. Auxiliary windows are used mainly to hold temporary data for information purposes, e.g., the output of a browser. The contents of an auxiliary window may be editable, but the system does not ask whether a modified auxiliary window should be stored, i.e., it is temporary in nature. The Log window is an example of an auxiliary window. Windows: A document window is decorated with the BlackBox document icon, while an auxiliary window is decorated with the BlackBox application icon. A tool window is not decorated with an icon. Mac OS: Auxiliary windows look the same way as document windows. In order to make it possible for the user to distinguish auxiliary and document windows, the titles of auxiliary windows are put between "[" and "]" brackets. 7 Document Size The size of a document, or more exactly of its outermost ("root") view, can be updated in several ways. Its width, or independently its height, can be bound either to a fixed size, to the paper as defined in the PageSetup dialog box, or to the window's current size. For example, text views by default have a width bound to the paper page size, and a height bound to the window size. Documentation texts are often bound to the current window size in both dimensions, so that they automatically resize with the window. Such bindings can be changed with the Tools->Document Size... dialog box. 8 Menu Configuration The configurable menus can be inspected using Info->Menus. The displayed text can be edited, and the current menu configuration updated accordingly (Info->UpdateMenus). To make changes to the menus permanent, the menu text must be saved to disk. The file System/Rsrc/Menus contains the startup menu configuration, i.e., the text which is opened when Info->Menus is executed. The menu text consists of a sequence of menu definitions, which themselves consist of sequences of menu items. An example is the following extract of a possible Dev menu definition: MENU "Dev" "Compile" "K" "DevCompiler.Compile" "TextCmds.FocusGuard" "Compile Selection" "" "DevCompiler.CompileSelection" "TextCmds.SelectionGuard" SEPARATOR "Unmark Errors" "" "DevMarkers.UnmarkErrors" "TextCmds.FocusGuard" "Next Error" "E" "DevMarkers.NextError" "TextCmds.FocusGuard" "Toggle Error Mark" "" "DevMarkers.ToggleCurrent" "TextCmds.FocusGuard" SEPARATOR "Insert Commander" "" "DevCommanders.Deposit; StdCmds.PasteView" "TextCmds.PasteViewGuard" "Execute" "" "DevDebug.Execute" "TextCmds.SelectionGuard" "Unload" "" "DevDebug.Unload" "TextCmds.SelectionGuard" END Every menu has a name, in this case it is Dev. Optionally, the menu name can be followed by a menu type, e.g., MENU "Text" ("TextViews.View") A typed menu is only installed in the menu bar as long as the current focus has a matching type, i.e., it is context-sensitive. The other menus are always available. A menu's type is usually simply the name of a view type. This is only a convention, however. It guarantees that menu types are globally unique, so that no clashes occur. Mac OS: Standard menus, i.e., File, Edit, Font, Attributes, and Windows are predefined and not part of a menu configuration text. There are two kinds of menu items: normal items and separators. A separator optically organizes a menu into different groups of items. Normal menu items consist of four strings: a label, a keyboard shortcut, an action command, and a guard command. The label is the string presented to the user in the menu. A "&" character indicates which character of the label should be underlined (this is a Windows feature, and not available on Mac OS). If you want a "&" to appear, you should write a "&&" (this also holds for the Mac OS, i.e., the syntax is the same for both platforms). The keyboard shortcut, which may be empty, allows to associate a keyboard key to the menu item. The action string contains the command sequence which is activated when the menu item is executed. The guard string, which may be empty, contains a command which is called to determine whether the item is currently enabled or disabled, checked or unchecked, or to set up a current item name which overrides the normal name (e.g., to toggle between ShowXYZ and HideXYZ). Note: the menu guard is executed for example when the user clicks in the menu bar. This causes the guard's module to become loaded, even if the user never invokes the corresponding command. Note: if the guard's module cannot be loaded, the menu item remains disabled and the guard is not executed again (for performance reasons). If the module's code becomes available later, e.g., because its module was later compiled, the menu item will remain disabled. To force a re-evaluation of the guard, use the Dev->FlushResources command. Note: the standard menu configuration uses all letters of the alphabet and the digit "0" as keyboard shortcuts. Digits "1" to "9" are not used. The assignment of keyboard shortcuts, like the whole menu configuration, can easily be adapted to specific needs by appropriately changing the menu text. Windows: The following keyboard shortcuts can be specified in the keyboard shortcut string (they are ignored under Mac OS): "A".."Z", "0".."9" modifier + key "*A".."*Z", "*0".."*9" shift + modifier + key "F1".."F12" function key "^F1".."^F12" modifier + function key "*F1".."*F12" shift + function key "*^F1".."*^F12" shift + modifier + function key Windows: Context menus (pop-up menus activated by the right mouse button) are specified by giving them the name "*" instead of a true name. At most one context menu may be untyped, all other context menus must be typed. For example, just add the line "Open &Module" "" "DevCmds.OpenModuleList" "TextCmds.SelectionGuard" to the menu MENU "*" ("TextViews.View") in the file Text/Rsrc/Menus. This adds a (text-)context menu item for opening the sources of the module(s) whose name(s) is (are) selected. It is possible to put all menu specifications in the menu text System/Rsrc/Menus. However, it is a better idea to keep the menu specifications that refer to a subsystem's commands in this subsystem's resource directory. For example, the Text menu could be specified in Text/Rsrc/Menus. In this case, System/Rsrc/Menus needs a so-called include statement that tells the menu configuration mechanism where to look for further menus: INCLUDE "Text" The explicit include statements allow to define the exact order in which menus appear in a menu bar. The command INCLUDE "*" includes all menus that have not been mentioned explicitly before (directly or via an include statement). It is a "catch all" for menus, and it is recommended to put it at the end of the System/Rsrc/Menus text. For example, a typical System/Rsrc/Menus text may look as follows: INCLUDE "Dev" INCLUDE "Form" INCLUDE "Sql" INCLUDE "Obx" INCLUDE "Text" INCLUDE "*" Note: when you have edited a menu text different from System/Rsrc/Menus, then don't execute the command Info->Update Menus, because this will cause the installation of the edited menu text as root menu text, meaning that you lose all other subsystems' menus. In particular, it is inconvenient if you lose the Info menu in this way, because you then have to leave and restart the application before you can edit and install menus again... So when you have edited some such other menu text, then save it and execute Info->Update Menus. This command will re-install all menus, starting with the System/Rsrc/Menus like it does when starting up the application. See also modules StdMenuTool and StdCmds. The command package modules of all subsystems export commands that may be used in a menu. Consult the various modules' on-line documentation, e.g., Text/Docu/Cmds for module TextCmds. 9 String Resources String resources are files which define a mapping between strings, e.g., the string "untitled" may be mapped to "sans titre". This is useful to prevent hard-wiring textual messages in the program code, in order to make later editing of these messages possible without requiring a recompilation. From a programmer's point of view, string translation is done in several procedures of module Dialog, e.g., Dialog.MapString. String resource files can be normal BlackBox text documents, which simply consist of the keyword STRINGS followed by a sequence of lines; each line contains a string (the key), a TAB, another string (to which the key is mapped), and a carriage return, e.g., STRINGS untitled sans titre open ouvre close ferme There can be one string resource file per subsystem (->7.2 Modules and Subsystems). For example, a call of Dialog.MapString("#Form:CntrlInstallFailed", resultString) in a program maps the string "CntrlInstallFailed" according to the table in the Form/Rsrc/Strings file. In the English version, the mapping is "form controller installation failed". In a German version, "CntrlInstallFailed" might be mapped to "Der Form Controller konnte nicht installiert werden". 10 Standard Commands In this section, the menu items of the standard menus File, Edit, Font (Mac OS), Attributes, and Window(s) are described. For a menu item which is not permanently enabled, the condition for enabling it is specified. Often, such a guard command is one of the commands exported by module StdCmds. Windows: Under Windows, the standard menu items can be configured in the same way as all other menu items, by editing the System/Rsrc/Menus document. Most standard menu items are calls to a command exported by module StdCmds. 10.1 File Menu New Command: StdCmds.New Guard: Opens a new document window containing an empty text view. Open... Command: HostCmds.Open Guard: Opens the standard file Open dialog box. Mac OS: Only BlackBox documents (i.e., Mac OS files with file type = "oODC"), directories, and volumes are shown. By clicking the Morefiles check box, all other files for which there are converters are shown as well. In the Format pop-up menu, a converter can be chosen in case there are several possible importers. Open Stationery... Command: StdCmds.OpenStationery Guard: Opens the standard file Open dialog box, through which a stationery (i.e., template) file can be opened. Mac OS: Only BlackBox documents (i.e., Mac OS files with file type = "oODC"), directories, and volumes are shown. By clicking the Morefiles check box, all other files for which there are converters are shown as well. In the Format pop-up menu, a converter can be chosen in case there are several possible importers. Close Command: HostCmds.Close Guard: StdCmds.WindowGuard Closes the front window. If the window is a primary document window and its contents has been modified ("dirty"), the user is asked whether to save the window's contents in a file. Save Command: HostCmds.Save Guard: HostCmds.SaveGuard Saves the front window's contents to a file. If the window's contents has not yet been saved to a file, the user is asked for a file name. Save As... Command: HostCmds.SaveAs Guard: StdCmds.WindowGuard Saves the front window's contents to a file. The user is always asked for a file name. After the command, you continue working with the new file. Save Copy As... Command: HostCmds.SaveCopyAs Guard: StdCmds.WindowGuard Saves the front window's contents to a file. The user is always asked for a file name. After the command, you continue working with the old file. Page Setup... Command: HostDialog.InitPageSetup; StdCmds.OpenToolDialog('Host/Rsrc/Cmds', 'Page Setup') Guard: StdCmds.WindowGuard Asks the user for the page information of the front window's document, for later printing. In addition to the data which is specific to the current printer driver, the margins can be set (the distances between the paper's edges and the printed area), and a standard header can be switched on or off. The standard header consists of a page number and a date. Mac OS: For some printer drivers, you should switch on greyscale printing (not black/white), otherwise printing may produce entirely black pages. Print... Command: HostCmds.Print Guard: HostCmds.PrintGuard Asks the user for printing information, and then creates a print-out accordingly. Send Document... (Windows) Command: HostMail.SendDocument Guard: HostMail.SendDocumentGuard Sends the front window's document as an electronic mail. Send Note... (Windows) Command: HostMail.SendNote Guard: HostMail.SendNoteGuard Sends a note as an electronic mail. The not is initialized with the text selection, if there is one. Exit (Windows) Quit (Mac OS) Command: HostCmds.Exit Guard: Terminates the application. If windows with modified contents are open, the user is asked whether to save them in files. 10.2 Edit Menu Undo [...] Command: StdCmds.Undo Guard: StdCmds.UndoGuard Reverses the effect of the most recent modifying operation. Usually, the kind of operation is given behind the word "Undo", e.g., UndoPaste. Undo can be activated several times, until the opening, creation, or most recent saving of the document. Under low-memory conditions, the number of undoable operations may become reduced. Redo [...] Command: StdCmds.Redo Guard: StdCmds.RedoGuard Restores the effect of the most recently undone operation. Usually, the kind of operation is given behind the word "Redo", e.g., RedoPaste. Cut Command: HostCmds.CutGuard Guard: HostCmds.Cut Deletes the selection and puts a copy into the clipboard. Copy Command: HostCmds.CopyGuard Guard: HostCmds.Copy Puts a copy of the selection into the clipboard. Paste Command: HostCmds.PasteGuard Guard: HostCmds.Paste Pastes a copy of the clipboard's contents at the caret position. If the focus view contains the same kind of data as the clipboard, the data is inserted directly into the focus view's data. Otherwise, and if the focus view is a container, a copy of the whole view containing the clipboard data is inserted into the focus view's data. Delete (Windows) Command: StdCmds.Clear Guard: StdCmds.CutGuard Deletes the selection, without putting it into the clipboard. Copy Properties Command: StdCommands.CopyProp Guard: StdCmds.SelectionGuard Copies the properties of the current selection. This command has no effect on the clipboard contents. Paste Properties Command: StdCommands.PasteProp Guard: StdCmds.SelectionGuard Pastes the properties that were copied most recently (see CopyProperties). Paste Object (Windows) Paste as Part (Mac OS) Command: HostCmds.PasteObject Guard: HostCmds.PasteObjectGuard Pastes a copy of the clipboard's contents at the caret position. If the focus view is a container, a copy of the whole view containing the clipboard data is inserted into the focus view's data. Paste Special... (Windows) Command: HostCmds.PasteSpecial Guard: HostCmds.PasteObjectGuard Opens a dialog box, which allows to choose the data type of the view in the clipboard, if the view supports several possible types. Paste to Window (Windows) Command: HostCmds.PasteToWindowGuard Guard: HostCmds.PasteToWindow Opens a copy of the clipboard's contents into a new document window. Insert Object... (Windows) Command: OleClient.PasteSpecial Guard: StdCmds.PasteViewGuard Opens a dialog box which shows all installed OLE servers. When one of them is chosen, an object of this type is allocated and inserted into the front window's contents. Object Properties... (Windows) Command: HostMenus.ObjProperties Guard: HostMenus.PropertiesGuard Opens an appropriate property sheet for the selected view. Object (Windows) Command: HostMenus.ObjectMenu Guard: HostMenus.ObjectMenuGuard Shows a submenu with commands for the selected view. These commands, which are determined by the selected view itself, are called "verbs". Usually, the first two verbs are Edit and Open: Edit Makes the selected view the current focus view. Open Opens a new window showing a second view to the selected view. + other verbs defined by the selected view. Clear (Mac OS) Command: StdCmds.Clear Guard: StdCmds.CutGuard Deletes the selection, without putting it into the clipboard. Select Document Command: StdCmds.SelectDocument Guard: StdCmds.WindowGuard Selects the root view of the front window's document as a singleton. Note the difference to SelectAll, which selects the latter's contents instead (or rather the contents of whatever view is currently the focus). Select All Command: StdCmds.SelectAll Guard: StdCmds.SelectAllGuard Selects the whole focus view's contents. Select Next Object (Windows) Command: StdCmds.SelectNextView Guard: StdCmds.ContainerGuard If a view in the container is selected: select the next view. If the last view is selected or there is no singleton selection: select the first view. Part Info (Mac OS) Command: HostCmds.PartInfo Guard: StdCmds.SingletonGuard Opens a modeless dialog box with some information about the selected view. View In Window (Mac OS) Command: HostCmds.ViewInWindow Guard: StdCmds.WindowGuard Opens a new window on the front window's focus view. The subwindow's title is put between "(" and ")" parentheses. This command is similar to "New Window" (see below), except that it opens a new window on the currently focused view, which may or may not be the root view (as in "New Window"). Preferences... (Windows) Command: HostDialog.InitPrefDialog; StdCmds.OpenToolDialog('HostDialog.prefs', 'Preferences') Guard: Allows to define several parameters: whether TrueType metrics are used (for best printing results), whether screen updates are performed during scrolling, the font used as default for texts, the font used as default for controls, and whether the status bar is visible or not. 10.3 Font Menu (Mac OS) Available: font-carrying selection or caret in focus view in front window Default Font Sets the selection or the caret to the default font. Sets the selection or caret to the chosen font (more exactly: its typeface). The default font corresponds to one of the concrete fonts shown below, but this correspondence may be changed dynamically. {typeface name} Then the list of all the fonts which are currently available is given. Sets the selection or caret to the chosen font (more exactly: its typeface). The menu item for the caret's font, or the font of the selection if it is homogeneous, is checked. Set Default Font Sets the selection or caret's font as the new default font. All visible text stretches which have the default font as their font are redrawn in the new default font. 10.4 Attributes Menu Available: style/size/color-carrying selection or caret in focus view in front window The following commands work on the selection; if there is no selection, the caret's current attributes are affected instead. These attributes are used as defaults when typing in new text. For colors, there is a system-wide color (default color) which can be modified by the user. Under Windows, the default color can be changes using an operating-system utility. Everything drawn in the default color will be updated accordingly. Regular (Windows) Plain (Mac OS) Command: StdCmds.Plain Guard: StdCmds.PlainGuard Checked: if text to the left and to the right of the caret is plain, or if selection is homogeneously plain (i.e., non-bold, non-italicized, non-underlined, and non-striked-out). Removes all style attributes (bold, italic, underline, strikeout) from the selection. Bold Command: StdCmds.Bold Guard: StdCmds.BoldGuard Checked: if text to the left and to the right of the caret is bold, or if selection is homogeneously bold. If the selection is homogeneously bold, it is made non-bold, otherwise it is made bold. Italic Command: StdCmds.Italic Guard: StdCmds.ItalicGuard Checked: if text to the left and to the right of the caret is italic, or if selection is homogeneously italic. If the selection is homogeneously italic, it is made non-italic, otherwise it is made italic. Underline Command: StdCmds.Underline Guard: StdCmds.UnderlineGuard Checked: if text to the left and to the right of the caret is underlined, or if selection is homogeneously underlined. If the selection is homogeneously underlined, it is made non-underlined, otherwise it is made underlined. Strikeout (Mac OS) Command: StdCmds.Strikeout Guard: StdCmds.StrikeoutGuard Checked: if text to the left and to the right of the caret is striked out, or if selection is homogeneously striked out. If the selection is homogeneously striked out, it is made non-striked-out, otherwise it is made striked out. (8 point (Windows),) 9 point, 10, 12, 16, 20, 24 Command: StdCmds.Size(size) Guard: StdCmds.SizeGuard(size) Checked: if text to the left and to the right of the caret has the given size, or if the selection is homogeneously of the given size. The selection is set to the given point size. Size... (Windows) Other Size... (Mac OS) Command: StdCmds.InitSizeDialog; StdCmds.OpenToolDialog('Std/Rsrc/Cmds', 'Size') Guard: StdCmds.SizeGuard(-1) Checked: if none of the other sizes apply A tool dialog box is opened, which allows to enter a particular font size in points, and then to set the selection to this size. Default Color Command: StdCmds.Color(1000000H) Guard: StdCmds.ColorGuard(1000000H) Checked: if text to the left and to the right of the caret has the default color, or if the selection is homogeneously of the default color Sets the selection's color to the default color. Black Command: StdCmds.Color(0000000H) Guard: StdCmds.ColorGuard(0000000H) Checked: if text to the left and to the right of the caret is black, or if the selection is homogeneously black Sets the selection's color to black. Red Command: StdCmds.Color(00000FFH) Guard: StdCmds.ColorGuard(00000FFH) Checked: if text to the left and to the right of the caret is red, or if the selection is homogeneously red Sets the selection's color to red. Green Command: StdCmds.Color(000FF00H) Guard: StdCmds.ColorGuard(000FF00H) Checked: if text to the left and to the right of the caret is green, or if the selection is homogeneously green Sets the selection's color to green. Blue Command: StdCmds.Color(0FF0000H) Guard: StdCmds.ColorGuard(0FF0000H) Checked: if text to the left and to the right of the caret is blue, or if the selection is homogeneously blue Sets the selection's color to blue. Color... (Windows) Other Color... (Mac OS) Command: HostDialog.ColorDialog Guard: StdCmds.ColorGuard(-1) Checked: if none of the other colors apply Asks the user for a color, to which it then sets the selection. Set Default Color... (Mac OS) Guard: color-carrying selection or caret in focus view in front window Asks the user for a color, to which it then sets the default color. Default Font (Windows) Command: StdCmds.DefaultFont Guard: StdCmds.DefaultFontGuard Sets the selection to the default font. Font... (Windows) Command: HostDialog.FontDialog Guard: StdCmds.TypefaceGuard Opens the standard font dialog box and applies the chosen font attributes to the selection. Typeface... (Windows) Command: HostDialog.TypefaceDialog Guard: StdCmds.TypefaceGuard Opens the standard font dialog box and applies the chosen font attributes to the selection. In contrast to the Font... command, only the typeface (the name of the font) is changed, but not the other attributes like size or weight (bold/normal). 10.5 Window Menu (Windows) / Windows Menu (Mac OS) New Window Command: StdCmds.NewWindow Guard: StdCmds.WindowGuard Opens a new window on the same document as the front window. The window is of the same kind as the front window. The window's title is put between "(" and ")" parentheses. Cascade (Windows) Stack (Mac OS) Command: HostMenus.Cascade Guard: StdCmds.WindowGuard Arrange document windows in an overlapping fashion. Tile Horizontal Command: HostMenus.TileHorizontal Guard: StdCmds.WindowGuard Arrange windows from left to right in a non-overlapping fashion. This command does not affect non-resizable windows, and it ignores some windows when there are too many open windows for a reasonable tiling. The front window becomes the left-most window. Tile Vertical Command: HostMenus.TileVertical Guard: StdCmds.WindowGuard Arrange windows from top to bottom in a non-overlapping fashion. This command does not affect non-resizable windows, and it ignores some windows when there are too many open windows for a reasonable tiling. The front window becomes the top-most window. Arrange Icons (Windows) Command: HostMenus.ArrangeIcons Guard: StdCmds.WindowGuard Arrange icons (minimized windows) at the bottom of the application window. Show Clipboard / Hide Clipboard (Mac OS) If the clipboard is open, it closes it and all its secondary windows. Otherwise it opens a clipboard window. {window} Command: HostMenus.WindowList Guard: Here the list of open windows is appended, the front window at the top (checked). Document window titles are in boldface if their contents has been modified. 11 Custom Commands Not all commands are visible in the default configuration of the menus. The following is a list of modules from the Std subsystem. These modules contain many useful commands but not all of them appear in the menus. For more information about the commands in the modules, please consult the corresponding module documentation. StdClocks analog clock views StdCmds cmds of std menus StdCoder ASCII coder StdDebug minimal debugger StdFolds fold views StdHeaders headers / footers StdLinks hyperlink views StdLog standard output StdMenuTool menu tool StdStamps date stamp views StdTables table controls StdTabViews tabbed folder views StdViewSizer set size of a view
System/Docu/User-Man.odc
USER32 This module is obsolete; use the Win subsystem instead.
System/Docu/USER32.odc
Views DEFINITION Views; IMPORT Files, Fonts, Stores, Ports, Converters, Models; CONST undefined = 0; transparent = 0FF000000H; deep = FALSE; shallow = TRUE; keepFrames = FALSE; rebuildFrames = TRUE; dontAsk = FALSE; ask = TRUE; clean = 0; notUndoable = 1; invisible = 2; TYPE View = POINTER TO ABSTRACT RECORD (Stores.Store) context-: Models.Context; (v: View) InitContext (context: Models.Context), NEW, EXTENSIBLE; (v: View) GetBackground (VAR color: Ports.Color), NEW, EMPTY; (v: View) Neutralize, NEW, EMPTY; (v: View) ConsiderFocusRequestBy- (view: View), NEW, EMPTY; (v: View) GetNewFrame (VAR frame: Frame), NEW, EMPTY; (v: View) Restore (f: Frame; l, t, r, b: INTEGER), NEW, ABSTRACT; (v: View) RestoreMarks (f: Frame; l, t, r, b: INTEGER), NEW, EMPTY; (v: View) HandleViewMsg- (f: Frame; VAR msg: Message), NEW, EMPTY; (v: View) HandleCtrlMsg (f: Frame; VAR msg: CtrlMessage; VAR focus: View), NEW, EMPTY; (v: View) HandlePropMsg- (VAR p: PropMessage), NEW, EMPTY; (v: View) HandleModelMsg- (VAR msg: Models.Message), NEW, EMPTY; (v: View) CopyFrom- (source: View); (v: View) CopyFromSimpleView- (source: View), NEW, EMPTY; (v: View) CopyFromModelView- (source: View; model: Models.Model), NEW, EMPTY; (v: View) ThisModel (): Models.Model, NEW, EXTENSIBLE END; Alien = POINTER TO LIMITED RECORD (View) store-: Stores.Alien END; Message = ABSTRACT RECORD view-: View END; NotifyMsg = EXTENSIBLE RECORD (Message) id0, id1: INTEGER; opts: SET END; Frame = POINTER TO ABSTRACT RECORD (Ports.Frame) l-, t-, r-, b-: INTEGER; view-: View; front-, mark-: BOOLEAN; (f: Frame) Close, NEW, EMPTY END; RootFrame = POINTER TO RECORD (Frame) flags-: SET END; PropMessage = ABSTRACT RECORD END; CtrlMessage = ABSTRACT RECORD END; CtrlMsgHandler = PROCEDURE (op: INTEGER; f, g: Frame; VAR msg: CtrlMessage; VAR mark, front, req: BOOLEAN); Title = ARRAY 64 OF CHAR; UpdateCachesMsg = EXTENSIBLE RECORD (Message) END; ScrollClassMsg = RECORD (Message) allowBitmapScrolling: BOOLEAN END; VAR HandleCtrlMsg-: CtrlMsgHandler; PROCEDURE Broadcast (v: View; VAR msg: Message); PROCEDURE Domaincast (domain: Stores.Domain; VAR msg: Message); PROCEDURE Omnicast (VAR msg: ANYREC); PROCEDURE HandlePropMsg (v: View; VAR msg: PropMessage); PROCEDURE Era (v: View): INTEGER; PROCEDURE BeginModification (type: INTEGER; v: View); PROCEDURE EndModification (type: INTEGER; v: View); PROCEDURE BeginScript (v: View; name: Stores.OpName; OUT script: Stores.Operation); PROCEDURE EndScript (v: View; script: Stores.Operation); PROCEDURE Do (v: View; name: Stores.OpName; op: Stores.Operation); PROCEDURE LastOp (v: View): Stores.Operation; PROCEDURE Bunch (v: View); PROCEDURE StopBunching (v: View); PROCEDURE ForwardCtrlMsg (f: Frame; VAR msg: CtrlMessage); PROCEDURE Update (v: View; rebuild: BOOLEAN); PROCEDURE UpdateIn (v: View; l, t, r, b: INTEGER; rebuild: BOOLEAN); PROCEDURE ReadView (VAR rd: Stores.Reader; OUT v: View); PROCEDURE WriteView (VAR wr: Stores.Writer; v: View); PROCEDURE CopyOf (v: View; shallow: BOOLEAN): View; PROCEDURE CopyWithNewModel (v: View; m: Models.Model): View; PROCEDURE ReadFont (VAR rd: Stores.Reader; OUT f: Fonts.Font); PROCEDURE WriteFont (VAR wr: Stores.Writer; f: Fonts.Font); PROCEDURE IsPrinterFrame (f: Frame): BOOLEAN; PROCEDURE InstallFrame (host: Frame; view: View; x, y, level: INTEGER; focus: BOOLEAN); PROCEDURE ThisFrame (host: Frame; view: View): Frame; PROCEDURE FrameAt (host: Frame, x, y: INTEGER): Frame; PROCEDURE Old (ask: BOOLEAN; VAR loc: Files.Locator; VAR name: Files.Name; VAR conv: Converters.Converter): View; PROCEDURE OldView (loc: Files.Locator; name: Files.Name): View; PROCEDURE Register (view: View; ask: BOOLEAN; VAR loc: Files.Locator; VAR name: Files.Name; VAR conv: Converters.Converter; OUT res: INTEGER); PROCEDURE RegisterView (view: View; loc: Files.Locator; name: Files.Name); PROCEDURE Open (view: View; loc: Files.Locator; name: Files.Name; conv: Converters.Converter); PROCEDURE OpenView (view: View); PROCEDURE OpenAux (view: View; title: Title); PROCEDURE Deposit (view: View); PROCEDURE RestoreDomain (domain: Stores.Domain); PROCEDURE Scroll (v: View; dx, dy: INTEGER); PROCEDURE SetDir (d: Directory); PROCEDURE MarkBorders (root: RootFrame); PROCEDURE MarkBorder (host: Frame; v: View; l, t, r, b: INTEGER); PROCEDURE Fetch (OUT view: View); PROCEDURE Available (): INTEGER; PROCEDURE ClearQueue; PROCEDURE RemoveFrame (host, f: Frame); PROCEDURE RemoveFrames (host: Frame; l, t, r, b: INTEGER); PROCEDURE BroadcastModelMsg (f: Frame; VAR msg: Models.Message); PROCEDURE BroadcastViewMsg (f: Frame; VAR msg: Message); PROCEDURE HandleCtrlMsg (op: INTEGER; f, g: Frame; VAR msg: CtrlMessage; VAR target, front: BOOLEAN); PROCEDURE SetRoot (root: RootFrame; view: View; front: BOOLEAN; flags: SET); PROCEDURE AdaptRoot (root: RootFrame); PROCEDURE RootOf (f: Frame): RootFrame; PROCEDURE HostOf (f: Frame): Frame; PROCEDURE UpdateRoot (root: RootFrame; l, t, r, b: INTEGER; rebuild: BOOLEAN); PROCEDURE RestoreRoot (root: RootFrame; l, t, r, b: INTEGER); PROCEDURE ValidateRoot (root: RootFrame); PROCEDURE InitCtrl (p: CtrlMsgHandler); PROCEDURE IsInvalid (v: View): BOOLEAN; PROCEDURE RevalidateView (v: View); END Views. Figure 1. Model-View-Controller Separation A view is a rectangular display object which provides visual presentation of data. Views are storable, and may be embedded recursively. A view often contains a Models.Model which represents some data, and sometimes a Controllers.Controller which provides interaction of the view with the user. There may be several views for each model simultaneously, but at most one controller per view. If several views share the same model, every change of the model must cause all its views to update their contents accordingly. Module Models provides a messaging mechanism through which visible views can be notified of model modifications, and thus re-establish the display's consistency. It is possible to implement views which do not contain a model. These views cannot use the messaging mechanism of module Models. Therefore, such views usually don't share data and are independent from each other. Typically, these views are simple controls which implement a very specific functionality that relies on cooperation with the control's container, e.g., a form view container. It is also possible to implement views which do not contain a controller. This is possible because all messages to a controller are sent to the controller's view, not directly to the controller itself. Thus a view can decide whether to handle these messages itself, or whether to forward them to a controller. Simple views don't contain a controller. Because a view is an extension of a Stores.Store, it can be embedded in a model, such that it is externalized and internalized as part of this model. This makes it possible to realize compound documents, which contain views containing views containing views... When a view needs to draw to the screen (or printer), it can do this through a frame. A frame is an access path (a mapper) to the port on which the view is presented. Since several windows may show the same document with its hierarchy of views, one and the same view may be visible several times simultaneously. This results in several frames for the same view simultaneously, and therefore in the need to update a view change in several frames. In general, the reaction to a model modification happens in two steps. In the first step, the nature of the model's change is broadcast to all visible views, using the model broadcast mechanism of module Models. This causes every visible view to update its own state, if necessary. In the second step, every view which has changed its state uses the view broadcast mechanism of module Views, to notify all frames for this view. In fact, since frames are usually not extended, the view itself performs the update for each of its frames. This second broadcast step is normally invisible to the programmer, because he merely needs to determine the view's region which needs updating. The actual update of this region in each of its frames is done by the framework. A view may behave differently depending on the model in which it is embedded, i.e., depending on its context. For this purpose, a variable of type Models.Context is carried by a view, as a link to its container. For every user interaction, e.g., the press of a key, a view must be defined which should handle this interaction, i.e., a so-called focus. BlackBox doesn't know which view is the current focus. BlackBox only provides a strategy which decides which window is focus. Since a window may contain a hierarchy of views, a view which has received an interaction message ђ a controller message ђ must decide on its own whether it is the focus itself, or whether it contains another view which might be focus instead. In the former case, it handles the messages itself, in the latter case, it forwards the message to this view. Every window contains a tree of frames. This tree corresponds to the visible views of the window. Every view may only draw inside its own borders, drawing outside of its borders must be prevented. Frames provide the necessary clipping facility. The management of the frame tree and of clipping is largely transparent to the view programmer. Examples: ObxPatternsdocu views without models ObxCalcdocu ObxOmosidocu ObxButtonsdocu ObxLinesdocu views with models ObxGraphsdocu ObxBlackBoxdocu ObxWrappersdocu wrapper ObxTwinsdocu special container Formsubsystemmap general container CONST undefined This value can be used to denote the width or height of a view as currently undefined. CONST transparent A view may be asked for its background color. In this case, the view may either return a Ports.Color value, or the value transparent. The latter value means that the view's container must find another source for a background color, i.e., for the color which is used to erase the background before the foreground is restored (use Update or UpdateIn to restore a view's area in all its frames). Transparency is useful if several views are superimposed on each other, which naturally occurs in a compound document. CONST deep, shallow There are two ways that a view can be copied: deep or shallow. This distinction arises from the fact that a view can carry two types of data: data that it owns completely, and data that it can share with other views. The most important example of the latter is the view's model, if it has one. When a view is copied, it must be decided whether shareable state should actually be shared with the copy (shallow copy), or whether an independent copy of this state should be created (deep copy). These constants can be passed to a parameter of the CopyModel or the CopyOf procedure. CONST keepFrames, rebuildFrames When part of a view's area must be restored (in every frame on it), there are two possible kinds of restoration: a frame may be kept as it is and only its contents be redrawn, or it may be rebuilt, i.e., newly allocated, set up, and redrawn. The latter is less efficient than the former, and only necessary if the following holds: the view must be a container, and the operation which changed the view might have modified a subview's bounding box (and thus invalidated its subframes). In the rare case where frames are extended, it could sometimes also become necessary to rebuild the frames on a view. CONST dontAsk, ask Theses constants may be passed to the Old and Register procedures. They determine whether these procedures allow the user to interactively change loc, name, or conv used for the operation. CONST clean Possible value for parameter type of BeginModification/EndModification. Indicates an operation that does not make its document "dirty". Example: modifying a text in a way that is considered as "unimportant", such as collapsing or expanding a text fold (-> StdFolds). CONST invisible Possible value for parameter type of BeginModification/EndModification. Indicates an operation that "folds together" with the previous operation, i.e., does not itself become visible in the Undo/Redo menu items. Invisible operations can be used for operations that by themselves may not be expected to appear in an Undo/Redo menu. Example: setting options in a controller. When executing a Redo operation, after a (visible) operation, all invisible operations are executed. When executing an Undo operation, first all invisible operations are undone and afterwards the visible operations. CONST notUndoable Possible value for parameter type of BeginModification/EndModification. Indicates an operation that cannot be reversed ("undone"). This is important for operations where the undo feature would be too expensive. TYPE View (Stores.Store) ABSTRACT A view is a storable object which may contain a model, possibly maintains a scroll position in this model, and generates frames for its display when needed. A view can be regarded as a special editor, and advanced views (containers) are able to contain arbitrary other views as part of their editable data (i.e., of their model). Views are allocated by specific view directories, e.g., TextViews.dir. Views are used by commands which manipulate the visual presentation of data. Views are extended for new kinds of data to be presented visually. Besides the implementation of new commands, the implementation of new view extensions is the central activity of BlackBox programming. Restore is the only procedure which necessarily must be implemented in an extension of View. It is called by the framework when the view must be redrawn on a screen or on a printer. Internalize, Externalize must be implemented in views which contain persistent mutable data. In this case, a view without model should also implement the CopyFromSimpleView procedure, while a view with a model should implement the CopyFromModelView procedure instead. Internalize / Externalize is called by the framework when the user opens / saves a document. CopyFromSimpleView / CopyFromModelView should also be implemented by views with mutable state that should be printable. The reason is that the framework makes a shallow copy of a view that is being printed, in order to avoid the original view to be changed by pagination, scrolling, or similar modifications that may be performed during printing. ThisModel must be implemented in views which contain models. It is called by the framework to find out whether this view should receive model messages for this model. ConsiderFocusRequestBy should be implemented in container views. It can be called by an embedded view that wants to become focus itself. GetBackground must be implemented in views which have non-transparent background colors. It is called by the framework as part of the restore mechanism. RestoreMarks and Neutralize must be implemented in views which may contain marks like selections or carets. RestoreMarks is called by the framework as part of the restore mechanism, after its corresponding Restore has been called. HandleModelMsg must be implemented in views which support partial view updates after a model change. It is called by the framework in order to deliver notifications about changes to the view's model. HandleViewMsg must be implemented in views which support marks, or which don't use the delayed update mechanism for some other reason. It is called by the framework to deliver view messages via all currently visible paths (i.e., via frames) to this view. HandleCtrlMsg must be implemented in editable views. It is called by the surrounding container if it considers the receiving view to be the current focus. HandlePropMsg must be implemented in views which support preferences and properties (-> Properties). It is called by the surrounding container to find out about the way that the embedded view would like to be treated. InitContext and GetNewFrame are usually not extended. A view's domain is the same as the domain of its container and of all embedded views and models. The domain identifies the document in which the view, its context, and its contents are embedded. The view's PropagateDomain procedure propagates the assigned domain to its model, if there is one. context-: Models.Context The view's context links the view to its container. Communication between view and container occurs via the context. A context belongs (and is managed by) the container, but carried by the view. PROCEDURE (v: View) InitContext (context: Models.Context) NEW, EXTENSIBLE Assigns context to v.context. InitContext is called by v's container, when v is being embedded in it (which means that the container creates a suitable context for v). InitContext is usually not extended, only view wrappers need to extend it in order to forward a context. Pre context # NIL 21 v.context = NIL OR v.context = context 22 Post v.context = context PROCEDURE (v: View) GetBackground (VAR color: Ports.Color) NEW, EMPTY This procedure may return a background color of the view. Upon input, color = transparent. GetBackground is called internally. GetBackground is implemented if a view needs a non-transparent background color. PROCEDURE (v: View) Neutralize NEW, EMPTY This procedure should remove all marks that a view carries. Neutralize is called by the framework. Neutralize is implemented by views which may contain marks. PROCEDURE (v: View) ConsiderFocusRequestBy- (view: View) NEW, EMPTY A subview of v may request to become focus. Its container may or may not grant this request. ConsiderFocusRequestBy is called by a subview. ConsiderFocusRequestBy is implemented in a container view. PROCEDURE (v: View) GetNewFrame (VAR f: Frame) NEW, EMPTY The procedure may generate a frame for the view. Upon entry, f = NIL. This procedure is rarely implemented (mainly in native controls). GetNewFrame is called internally. GetNewFrame is implemented in views which need specialized extended view frames. PROCEDURE (v: View) Restore (f: Frame; l, t, r, b: INTEGER) NEW, ABSTRACT A view implementation must implement this procedure, to draw all or part of its contents. For drawing, a frame is passed to the view, whose drawing procedures can be called in the Restore procedure. Only the rectangle (l, t, r, b), which is given in universal coordinates, needs to be restored. Since drawing is clipped to this rectangle automatically, it is sometimes the best solution to simply restore the whole view's contents. However, often it is significantly faster to restore only the contents of the rectangle. If necessary, the size of the view can be determined by calling v.context.GetSize. Consistent with the frame drawing operations (as described in the documentation of module Ports), the origin for drawing is the view's top-left corner, with positive x-values to the right, and positive y-values to the bottom. For drawing at screen pixel resolutions without rounding errors, the frame's f.dot field is useful. The value f.unit can be inspected to obtain the size of a pixel in universal coordinates (see the documentation of module Fonts). For example, this allows to adapt to the different resolutions during screen display and during printing. If drawing should be done in different ways depending on whether the view is being displayed on screen or whether it is being printed, then Views.IsPrinterFrame(f) can be used to determine whether it is being printed or displayed on screen. Restore is called internally by the framework, whenever some part of the view becomes newly visible, or after someone has called Views.Update or Views.UpdateIn for this view. Restore is rarely called directly by a view itself. No assumptions are allowed of when Restore is called, how often, in which order, etc. Restore should simply draw everything within the given rectangle, it must not assume that something is still on screen from the last time it was called. Since views may be nested, a container must be drawn before the views contained in it are draw. The framework calls Restore methods in the correct order, from the "back" to the "front". An embedded view thus lies always "above" its container. As an exception of the back-to-front drawing rule, BlackBox allows to draw marks (in particular: selections) of a container on top of the contained views. This can be achieved by moving the restoration of marks to the view's RestoreMarks method. This is only necessary for view containers, however. Restore must be implemented in every view extension. It is the only view procedure whose implementation is mandatory, not optional. Pre f # NIL 20 f.view = v 21 v.context # NIL 22 0 <= f.l <= l <= r <= f.r <= width of view 23 0 <= f.t <= t <= b <= f.b <= height of view 24 PROCEDURE (v: View) RestoreMarks (f: Frame; l, t, r, b: INTEGER) NEW, EMPTY Restore all marks (in particular any selection) of view v via frame f. Only the rectangle (l, t, r, b), which is given in universal coordinates, needs to be restored. A frame contains the method MarkRect which is provided particularly for the drawing of marks. RestoreMarks is called locally by the framework as part of the restore mechanism, after its corresponding Restore has been called. RestoreMarks is implemented in views which support any kind of marks, e.g., selection, caret, or focus marks. Pre f # NIL 20 f.view = v 21 v.context # NIL 22 PROCEDURE (v: View) HandleViewMsg- (f: Frame; VAR msg: Message) NEW, EMPTY Message handler for view messages. HandleViewMsg is called locally. HandleViewMsg is implemented in views which support marks (e.g., selection marks), and in views which support different frame contents for the same view (a rare case). Pre f # NIL guaranteed f.view = v guaranteed v.context # NIL guaranteed msg.view = v OR msg.view = NIL guaranteed PROCEDURE (v: View) HandleCtrlMsg (f: Frame; VAR msg: CtrlMessage; VAR focus: View) NEW, EMPTY Message handler for messages to the focus. HandleCtrlMsg is called by the view's container, indirectly via ForwardCtrlMsg. If a controller message needs to be forwarded to an embedded view, set focus to this view. The framework will perform forwarding after HandleCtrlMsg returns. In the rare cases where this is not an adequate solution, ForwardCtrlMsg must be used; the embedded view's HandleCtrlMsg must never be called directly. After ForwardCtrlMsg, focus must be set to NIL, so that the message is not forwarded twice. During mouse tracking (i.e., when handling a Controllers.TrackMsg), drawing should only occur in frame f. This also implies that during mouse tracking, no update messages should be sent. If necessary, an update model message should be sent after the mouse button was released. HandleCtrlMsg is extended in editable views. Pre f # NIL 20 f.view = v 21 v.context # NIL 22 focus = NIL 23 PROCEDURE (v: View) HandlePropMsg- (VAR p: PropMessage) NEW, EMPTY Property messages can be passed to a view via its HandlePropMsg procedure. HandlePropMsg is called by the view's container. The global procedure HandlePropMsg (see further below) is used to send a property message to a view. HandlePropMsg is called locally. HandlePropMsg is implemented in views which support properties (not described here). PROCEDURE (v: View) HandleModelMsg- (VAR msg: Models.Message) NEW, EMPTY Message handler for model messages. HandleModelMsg is called locally. HandleModelMsg is implemented in views with a model which support updates after a model modification. Pre msg.model # NIL 20 msg.model = v.ThisModel() 21 PROCEDURE (v: View) CopyFrom- (source: Stores.Store) This method has become final. It calls the CopyFromSimpleView or CopyFromModelView, respectively. It checks that these procedures don't change the view context. PROCEDURE (v: View) CopyFromSimpleView- (source: View) NEW, EMPTY The procedure should be implemented in views which have no model. It should copy view-specific data from source. CopyFromModelView is called as part of module Views' copy operations (CopyOf, CopyWithNewModel). Note: it is not permissible to implement both CopyFromModelView and CopyFromSimpleView simultaneously! Pre source # NIL guaranteed TYP(source) = TYP(v) guaranteed CopyFromModelView must not be implemented 20 PROCEDURE (v: View) CopyFromModelView- (source: View; model: Models.Model) NEW, EMPTY The procedure must be implemented in views which have a model, and only in them. The major exception where a view without model may still implement CopyFromModelView instead of CopyFromSimpleView are wrapper views: using CopyFromModelView they can be implemented flexibly enough to wrap arbitrary views, whether they have models or not. The procedure should initialize its model to model. If necessary, it can copy view-specific data from source. CopyFromModelView is called as part of module Views' copy operations (CopyOf, CopyWithNewModel). Note that if model = source.ThisModel(), then a shallow copy is being performed. Note: it is not permissible to implement both CopyFromModelView and CopyFromSimpleView simultaneously! Pre source # NIL guaranteed TYP(source) = TYP(v) guaranteed model # NIL => TYP(model) = TYP(source.ThisModel()) guaranteed CopyFromSimpleView must not be implemented 20 Post v.ThisModel() = model PROCEDURE (v: View) ThisModel (): Models.Model NEW, EXTENSIBLE Returns the view's model, if it has one. The default implementation returns NIL. ThisModel is called internally. ThisModel is replaced by views which contain models. A view with a model must always return the same model, i.e., the one which was assigned to it upon initialization. TYPE Alien (View) LIMITED If the internalization of a view fails, either because its implementing module(s) cannot be loaded, or because it cancelled internalization (e.g., because of a version conflict), an alien is produced instead (this happens in procedure ReadView). An alien is immutable and doesn't contain a model. It contains an alien store which can be inspected to determine the type of the alien, and the cause for it to be an alien. Every container must be able to operate even if one or several of its embedded views are aliens. If the view's model is an alien store, the view may turn itself into an alien. Aliens are allocated in ReadView. store-: Stores.Alien store # NIL The alien store which has been generated by a Stores.Reader during internalization of the view. TYPE Message ABSTRACT Base type of all view messages. Such messages are sent when a view's state has changed, in order to render the display consistent again. There may be several frames displaying the same view, such that every one of them needs to be updated. Messages are sent by views when their states have changed and if they cannot use BlackBox's delayed update mechanism. This is true mainly when drawing marks, e.g., selection marks. Messages are extended to indicate what kind of update should be performed on a frame. view-: View The view which has changed. If view = NIL, all frames with the same domain are notified of the view change. TYPE NotifyMsg (Message) EXTENSIBLE This message notifies all visible views about a change in an interactor's state (-> Dialog). NotifyMsg is sent by the interactor procedures Update and UpdateList in module Dialog. NotifyMsg is never extended. NotifyMsg is sent only internally. id0, id1: INTEGER Identification of the interactor or of one of its fields. opts: SET Determines whether controls (not described here) should check their guards, for example. TYPE Frame (Ports.Frame) ABSTRACT All input and output operations of a view pass through a frame. A frame manages the whole layout of views on a port, including clipping. Model and view messages are broadcast along frame trees. A frame tree's internal structure is hidden. Frames are volatile objects, they are allocated and released by BlackBox whenever necessary, e.g., when the frame's window is resized. Thus they cannot be used to carry application-specific state, except for caches. Frames are allocated by a view's GetNewFrame procedure. Frames are managed internally, and passed as parameters to view procedures whenever necessary. Standard frames are sufficient for most purposes, and thus rarely extended. l-, t-, r-, b-: INTEGER 0 <= l <= r & 0 <= t <= b The visible area of the view in this frame. The values are in universal coordinates, relative to the frame's view's top-left corner. For example, f.l + f.gx is the distance of the left frame border from the left port (display, printer) border in universal coordinates; (f.l + f.gx) DIV f.unit is the same distance in pixels. view-: View view # NIL The frame's view. front-: BOOLEAN Flag which tells whether the frame is part of the front window mark-: BOOLEAN Flag which tells whether the frame is on its window's focus path, i.e., whether marks (caret, selection) should be drawn. Typically, marking procedures work the following way: IF f.mark THEN IF f.front THEN DrawMark(f) ELSE DrawBackgroundMark(f) END END PROCEDURE (f: Frame) Close NEW, EMPTY Perform finalization before the frame is removed. After a call to Close, f.view and f.rider are set to NIL and f.ConnectTo(NIL) is called. Close is called internally. TYPE RootFrame This type is used internally. flags-: SET Window-specific flags. Reserved for future use. TYPE PropMessage ABSTRACT Use its alias Properties.Message instead (properties are not described here). TYPE CtrlMessage ABSTRACT Base type of all controller messages. Use its alias Controllers.Message instead. TYPE CtrlMsgHandler Used internally. TYPE Title Type for view titles, e.g., in windows. TYPE UpdateCachesMsg (Message) EXTENSIBLE Used internally. TYPE ScrollClassMsg (Message) EXTENSIBLE Used internally. PROCEDURE Broadcast (v: View; VAR msg: Message) Broadcast msg for view. Before broadcasting, parameter v is assigned to the message's view-Field. The actual broadcast only takes place if v.domain # NIL. Broadcast is called by a view whenever its state has changed and the delayed restore mechanism is not sufficient, e.g., to update frame-specific marks. v will receive msg once for every visible frame on itself. The handler of a view message may not recursively broadcast another view message, since this could cause the messages to be received in another order than they have been sent, which would result in errors very hard to find. Pre v # NIL 20 no recursion 21 Post msg.view = v PROCEDURE Domaincast (domain: Stores.Domain; VAR msg: Message) Broadcasts msg inside domain. For visual objects, the domain corresponds to the object's document. Domaincast is only necessary in exceptional cases; usually a view message is sent in places where the corresponding view, and not only its domain, is known. In these cases, Broadcast is the appropriate (and faster) procedure. PROCEDURE Omnicast (VAR msg: Message) Broadcast msg to all open views, independent of their domain (i.e., of their document). All views will receive this message with msg.view = NIL. Omnicast is slower than Broadcast, and only necessary in exceptional cases, e.g., for clock views which should be updated every second through a message omnicast. PROCEDURE HandlePropMsg (v: View; VAR msg: PropMessage) Use this procedure to send a property message to a view. It is equivalent to v.HandlePropMsg(msg) except that a much better error handling is performed. PROCEDURE Era (v: View): INTEGER For views with models, returns the era in which the view was last synchronized with the model. Pre v # NIL 20 Post v.ThisModel() # NIL in-synch(v) iff Era(v) = Models.Era(v.ThisModel()) PROCEDURE BeginModification (type: INTEGER; v: View) PROCEDURE EndModification (type: INTEGER; v: View) PROCEDURE BeginScript (v: View; name: Stores.OpName; OUT script: Stores.Operation) PROCEDURE EndScript (v: View; script: Stores.Operation) PROCEDURE Do (v: View; name: Stores.OpName; op: Stores.Operation) PROCEDURE LastOp (v: View): Stores.Operation PROCEDURE Bunch (v: View) PROCEDURE StopBunching (v: View) These procedures handle modifications of a view. They are used in the same way as their model counterparts in module Models (-> Models). Note that these view procedures are provided for convenience, they are mostly identical to the Models. The only noticeable difference is that a view operation only affects this view, and doesn't affect other views even if they show the same model. For example, a script that modifies a view's model should use the Models procedure, so that all views are updated correctly. A script that modifies only a view's private state should use the procedures above. PROCEDURE ForwardCtrlMsg (f: Frame; VAR msg: CtrlMessage) This procedure should be used to send a controller message along the focus path. Usually, it is called within an implementation of HandleCtrlMsg. This is only necessary if it is not sufficient to just set the focus parameter of HandleCtrlMsg to the embedded view to which forwarding should occur. This in turn is only necessary if HandleCtrlMsg needs to do some postprocessing after forwarding has occurred. In this case, it calls ForwardCtrlMsg and then makes sure that focus = NIL. Pre f # NIL 20 PROCEDURE Update (v: View; rebuild: BOOLEAN) Causes view v to be restored, in all frames displaying v. The update occurs delayed, after the currently executing command has terminated. rebuild should be set to keepFrames for non-containers or for operations which didn't modify the layout of a container (i.e., the places and sizes of embedded views). Otherwise, rebuildFrames should be passed. Pre v # NIL 20 PROCEDURE UpdateIn (v: View; l, t, r, b: INTEGER; rebuild: BOOLEAN) Causes rectangle (l, t, r, b) of view v to be restored, in all frames displaying v. The update occurs delayed, after the currently executing command has terminated. rebuild should be set to keepFrames for non-containers or for operations which didn't modify the layout of a container (i.e., the places and sizes of embedded views). Otherwise, rebuildFrames should be passed. Pre v # NIL 20 PROCEDURE ReadView (VAR rd: Stores.Reader; OUT v: View) Reads view v, using reader rd. If internalization is not possible, an alien view is returned. PROCEDURE WriteView (VAR wr: Stores.Writer; v: View) Writes view v, using writer wr. Alien views are handled correctly. PROCEDURE CopyOf (v: View; shallow: BOOLEAN): View Returns a shallow or deep copy of v. Pre v # NIL 20 Post result # NIL PROCEDURE CopyWithNewModel (v: View; m: Models.Model): View Copies a view and assigns a new model to the copy. Pre v # NIL 20 v.ThisModel() # NIL 21 m # NIL 22 TYP(m) = TYP(v.ThisModel()) 23 PROCEDURE ReadFont (VAR rd: Stores.Reader; OUT f: Fonts.Font) Reads a font from a reader. Post f # NIL PROCEDURE WriteFont (VAR wr: Stores.Writer; f: Fonts.Font) Writes a font to a writer. Pre f # NIL 20 PROCEDURE IsPrinterFrame (f: Frame): BOOLEAN This function can be used to determine whether f's view is currently being restored on a printer or preview port. Pre f # NIL 20 PROCEDURE InstallFrame (host: Frame; view: View; x, y, level: INTEGER; focus: BOOLEAN) If view has no corresponding embedded frame in host, Install allocates and installs a new one for it, otherwise the existing frame is kept. Parameters x and y give the position of the view's top-left corner relative to the container view's (i.e., host.view) top-left corner. The frame ordering can be influenced by passing a view level at which view lies logically. Levels need not be unique (pass 0 if you don't care, e.g., if you never have overlapping frames). A frame always lies "above" other frames with smaller levels. Parameter focus tells whether the frame is part of the focus path. Pre host # NIL 20 host is opened in window 21 view # NIL 22 view.context # NIL 23 view.Domain() # NIL 24 PROCEDURE ThisFrame (host: Frame; view: View): Frame Searches the embedded frame of host which contains view view. Pre host # NIL 20 Post result = NIL view = NIL OR not found result # NIL view # NIL & found result.view = view PROCEDURE FrameAt (host: Frame; x, y: INTEGER): Frame Searches the embedded frame of host which contains point (x, y). Pre host # NIL 20 Post result = NIL no embedded frame at (x, y) result # NIL result contains (x, y) PROCEDURE Old (ask: BOOLEAN; VAR loc: Files.Locator; VAR name: Files.Name; VAR conv: Converters.Converter): View This procedure looks up a file, reads in the document in this file, and then returns the root view of this document. If the file is already opened in a window, the root view of this window's document is returned instead of reading the file. Parameter ask determines whether or not the user is asked interactively for the triple (loc, name, conv), via a standard file dialog. With this dialog, the user can navigate in the host file system's directory structure. loc, name, conv are treated as in-out parameters. On input, their values are used as defaults. If ask then the user may cause them to change. loc, name determine the file from which the document was read. conv determines the converter which is used for reading the document. conv = NIL means that no conversion is necessary, i.e., the file format already has the standard BlackBox format. Pre ask OR loc # NIL 20 ask OR name # "" 21 Post result = NIL loc.res # 0 result # NIL loc.res = 0 result.context # NIL ~ask loc = loc' & name = name' & conv = conv' PROCEDURE OldView (loc: Files.Locator; name: Files.Name): View OldView is an abbreviation of Old(dontAsk, loc, name, NIL). PROCEDURE Register (view: View; ask: BOOLEAN; VAR loc: Files.Locator; VAR name: Files.Name; VAR conv: Converters.Converter; OUT res: INTEGER) Saves view's document in a file. Parameter ask determines whether or not the user is asked interactively for the triple (loc, name, conv), via a standard file dialog. With this dialog, the user can navigate in the host file system's directory structure. loc, name, conv are treated as in-out parameters. On input, their values are used as defaults. If ask then the user may cause them to change. loc, name determine the file to which the document is written. conv determines the converter which is used for writing the document. conv = NIL means that no conversion is necessary, i.e., the file format gets the standard BlackBox format. Pre view # NIL 20 ask OR loc # NIL 22 ask OR name # "" 23 Post operation was successful res = 0 operation was not successful res # 0 PROCEDURE RegisterView (view: View; loc: Files.Locator; name: Files.Name) RegisterView is an abbreviation of Register(view, dontAsk, loc, name, nil, res). PROCEDURE Open (view: View; loc: Files.Locator; name: Files.Name; conv: Converters.Converter) Open view in a new window. (loc, name) determines the file associated with view, if there is any. conv is the converter which will be used when the user saves the document. conv = NIL is passed when saving in the standard BlackBox file format is desired. Pre view # NIL 20 (loc = NIL) = (name = "") 21 PROCEDURE OpenView (view: View) OpenView is an abbreviation of Open(view, NIL, "", NIL). PROCEDURE OpenAux (view: View; title: Title) Opens view in an auxiliary window with title title. Pre view # NIL 20 title # "" 21 PROCEDURE Deposit (view: View) Deposit a view for later use, typically for opening it in a window, or for pasting it to the focus. Deposit is used only by allocation commands, i.e., commands which allocate and then deposit a concrete view type. Pre view # NIL 20 PROCEDURE RestoreDomain (domain: Stores.Domain) This procedure forces a restoration of all update regions on views of domain. Normally, the display is updated in a delayed fashion, i.e., an update region is built for all invalid view areas (using Update and UpdateIn), and the display update according to this region is performed when the framework is idle, i.e., between commands. However, sometimes it is necessary to enforce a display update during a command, for which this procedure can be used. The need for enforced update comes from scrolling: if a view should be scrolled, the effect of scrolling should become immediately visible. PROCEDURE Scroll (v: View; dx, dy: INTEGER) Scroll the contents of each frame on v by (dx, dy). Pre v # NIL 20 PROCEDURE SetDir (d: Directory) Assigns directory. Pre d # NIL 20 Post stdDir' = NIL stdDir = d stdDir' # NIL stdDir = stdDir' dir = d The following procedures are used internally: PROCEDURE MarkBorders (root: RootFrame) PROCEDURE MarkBorder (host: Frame; view: View; l, t, r, b: INTEGER) PROCEDURE Fetch (OUT view: View) PROCEDURE Available (): INTEGER PROCEDURE ClearQueue PROCEDURE RemoveFrame (host, f: Frame) PROCEDURE RemoveFrames (host: Frame; l, t, r, b: INTEGER) PROCEDURE BroadcastModelMsg (f: Frame; VAR msg: Models.Message) PROCEDURE BroadcastViewMsg (f: Frame; VAR msg: Message) PROCEDURE HandleCtrlMsg (op: INTEGER; f, g: Frame; VAR msg: CtrlMessage; VAR target, front, req: BOOLEAN) PROCEDURE SetRoot (root: RootFrame; view: View; front: BOOLEAN; flags: SET) PROCEDURE AdaptRoot (root: RootFrame) PROCEDURE RootOf (f: Frame): RootFrame PROCEDURE HostOf (f: Frame): Frame PROCEDURE UpdateRoot (root: RootFrame; l, t, r, b: INTEGER; rebuild: BOOLEAN) PROCEDURE RestoreRoot (root: RootFrame; l, t, r, b: INTEGER) PROCEDURE ValidateRoot (root: RootFrame) PROCEDURE InitCtrl (p: CtrlMsgHandler) PROCEDURE IsInvalid (v: View): BOOLEAN PROCEDURE RevalidateView (v: View)
System/Docu/Views.odc
Windows This module has a private interface, it is only used internally.
System/Docu/Windows.odc
Winsock This module is obsolete; use the Win subsystem instead.
System/Docu/Winsock.odc
XYplane DEFINITION XYplane; CONST erase = 0; draw = 1; VAR X, Y, W, H: INTEGER; PROCEDURE Open; PROCEDURE Dot (x, y, mode: INTEGER); PROCEDURE IsDot (x, y: INTEGER): BOOLEAN; PROCEDURE ReadKey (): CHAR; PROCEDURE Clear; END XYplane. This module is provided for compatibility with the book "Programming in Oberon" by Reiser/Wirth. It is useful when learning the language. It is not recommended for use in production programs. CONST erase This value can be passed to parameter mode in procedure Dot. It indicates that a white dot should be placed at the given coordinates. CONST draw This value can be passed to parameter mode in procedure Dot. It indicates that a black dot should be placed at the given coordinates. VAR X, Y, W, H These values define the rectangle in which drawing occurs. (X, Y) is the lower-left corner of the rectangle, (W, H) its size. In BlackBox, (X, Y) is always (0, 0). Unlike the port model of BlackBox, XYplane has its origin at the lower-left corner of the drawing area, and positive Y values above the origin. PROCEDURE Open Opens a new window for drawing. The window's contents is cleared to white. PROCEDURE Dot (x, y, mode: INTEGER) Draws a white dot (mode = erase) or a black dot (mode = draw). PROCEDURE IsDot (x, y: INTEGER): BOOLEAN Returns whether the dot at (x, y) is white (FALSE) or black (TRUE). PROCEDURE ReadKey (): CHAR If a key has been pressed, it is returned as result. Otherwise, 0X is returned. PROCEDURE Clear Erases the whole drawing area (setting it to white).
System/Docu/XYplane.odc
ADVAPI32 Модуль устарел; используйте вместо него подсистему Win.
System/Docu/ru/ADVAPI32.odc
COMDLG32 Модуль устарел; используйте вместо него подсистему Win.
System/Docu/ru/COMDLG32.odc
Config DEFINITION Config; PROCEDURE Setup; END Config. BlackBox пытается выполнить команду Config.Setup при запуске. Вызов позволяет настроить конфигурацию BlackBox. Модуль Config предоставляется в исходном тексте и может быть изменен программистом произвольным образом. Реализация по умолчанию выглядит так: MODULE Config; IMPORT Dialog; PROCEDURE Setup*; VAR res: INTEGER; BEGIN (* ... здесь устанавливаются различные конвертеры файлов и буфера обмена ... *) Dialog.Call("StdLog.Open", "", res) END Setup; END Config. Эта конфигурация при запуске открывает окно рабочего журнала. Команда вызывается после полной загрузки библиотек, среды и стандартных подсистем BlackBox. Config может импортировать любой модуль BlackBox. Если необходимо, модуль Config можно удалить. Текущаяконфигурация Заметим, что подобно модулю Config может присутствовать (а может и нет) модуль Startup с командой Setup. Он служит для похожих целей, но вызывается перед загрузкой верхних уровней (подсистемы текста, форм и т.д.). Следовательно, Startup не может импортировать модули верхнего уровня BlackBox. Обычно модуля Startup не существует. Он используется при особых обстоятельствах, например, для перезаписи переменной Dialog.appName. PROCEDURE Setup Процедура может быть реализована в целях настройки начальной конфигурации BlackBox после запуска. Она вызывается после установки стандартных служб и меню. Реализация Setup необязательна. Пример реализации Setup: PROCEDURE Setup*; VAR res: INTEGER; BEGIN Dialog.Call("StdCmds.OpenAuxDialog('System/Rsrc/About', 'Splash Screen')", "", res) END Setup; Если процедура Setup не реализована, модуль (конкретно, его кодовый файл) может быть полностью удален.
System/Docu/ru/Config.odc
Containers DEFINITION Containers; IMPORT Controllers, Stores, Views, Models, Properties; CONST noSelection = 0; noFocus = 1; noCaret = 2; mask = {noSelection, noCaret}; layout = {noFocus}; deselect = FALSE; select = TRUE; any = FALSE; selection = TRUE; hide = FALSE; show = TRUE; TYPE Model = POINTER TO ABSTRACT RECORD (Models.Model) (m: Model) GetEmbeddingLimits (OUT minW, maxW, minH, maxH: INTEGER), NEW, ABSTRACT; (m: Model) ReplaceView (old, new: Views.View), NEW, ABSTRACT; (m: Model) InitFrom- (source: Model), NEW, EMPTY END; View = POINTER TO ABSTRACT RECORD (Views.View) (v: View) CopyFromModelView2- (source: Views.View; model: Models.Model), NEW, EMPTY; (v: View) Externalize2- (VAR rd: Stores.Writer), NEW, EMPTY; (v: View) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View), NEW, EMPTY; (v: View) HandleModelMsg2- (VAR msg: Models.Message), NEW, EMPTY; (v: View) HandlePropMsg2- (VAR p: Views.PropMessage), NEW, EMPTY; (v: View) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY; (v: View) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY; (v: View) InitModel (m: Model), NEW; (v: View) InitModel2- (m: Model), NEW, EMPTY; (v: View) AcceptableModel- (m: Model): BOOLEAN, NEW, ABSTRACT; (v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER), NEW, ABSTRACT; (v: View) ThisModel (): Model, EXTENSIBLE; (v: View) SetController (c: Controller), NEW; (v: View) ThisController (): Controller, NEW, EXTENSIBLE; (v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER), NEW, ABSTRACT; (v: View) CatchModelMsg (VAR msg: Models.Message), NEW, EMPTY; (v: View) CatchViewMsg (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY; (v: View) CatchCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View), NEW, EMPTY; (v: View) CatchPropMsg (VAR msg: Views.PropMessage), NEW, EMPTY END; Controller = POINTER TO ABSTRACT RECORD (Controllers.Controller) opts-: SET; (c: Controller) ThisView (): View, EXTENSIBLE; (c: Controller) SetOpts (opts: SET), NEW, EXTENSIBLE; (c: Controller) GetContextType (OUT type: Stores.TypeName), NEW, ABSTRACT; (c: Controller) GetValidOps (OUT valid: SET), NEW, ABSTRACT; (c: Controller) NativeModel (m: Models.Model): BOOLEAN, NEW, ABSTRACT; (c: Controller) NativeView (v: Views.View): BOOLEAN, NEW, ABSTRACT; (c: Controller) NativeCursorAt (f: Views.Frame; x, y: INTEGER): INTEGER, NEW, ABSTRACT; (c: Controller) PickNativeProp (f: Views.Frame; x, y: INTEGER; VAR p: Properties.Property), NEW, EMPTY; (c: Controller) PollNativeProp (selection: BOOLEAN; VAR p: Properties.Property; VAR truncated: BOOLEAN), NEW, EMPTY; (c: Controller) SetNativeProp (selection: BOOLEAN; old, p: Properties.Property), NEW, EMPTY; (c: Controller) MakeViewVisible (v: Views.View), NEW, EMPTY; (c: Controller) GetFirstView (selection: BOOLEAN; OUT v: Views.View), NEW, ABSTRACT; (c: Controller) GetNextView (selection: BOOLEAN; VAR v: Views.View), NEW, ABSTRACT; (c: Controller) GetPrevView (selection: BOOLEAN; VAR v: Views.View), NEW, EXTENSIBLE; (c: Controller) CanDrop (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, EXTENSIBLE; (c: Controller) MarkDropTarget (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; type: Stores.TypeName; isSingle, show: BOOLEAN), NEW, EMPTY; (c: Controller) Drop (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; view: Views.View; isSingle: BOOLEAN), NEW, ABSTRACT; (c: Controller) MarkPickTarget (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER; show: BOOLEAN), NEW, EMPTY; (c: Controller) TrackMarks (f: Views.Frame; x, y: INTEGER; units, extend, add: BOOLEAN), NEW, ABSTRACT; (c: Controller) Resize (view: Views.View; l, t, r, b: INTEGER), NEW, ABSTRACT; (c: Controller) GetSelectionBounds (f: Views.Frame; OUT x, y, w, h: INTEGER), NEW, EXTENSIBLE; (c: Controller) DeleteSelection, NEW, ABSTRACT; (c: Controller) MoveLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER), NEW, ABSTRACT; (c: Controller) CopyLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER), NEW, ABSTRACT; (c: Controller) SelectionCopy (): Model, NEW, ABSTRACT; (c: Controller) NativePaste (m: Models.Model; f: Views.Frame), NEW, ABSTRACT; (c: Controller) ArrowChar (f: Views.Frame; ch: CHAR; units, select: BOOLEAN), NEW, ABSTRACT; (c: Controller) ControlChar (f: Views.Frame; ch: CHAR), NEW, ABSTRACT; (c: Controller) PasteChar (ch: CHAR), NEW, ABSTRACT; (c: Controller) PasteView (f: Views.Frame; v: Views.View; w, h: INTEGER), NEW, ABSTRACT; (c: Controller) HasSelection (): BOOLEAN, NEW, EXTENSIBLE; (c: Controller) Selectable (): BOOLEAN, NEW, ABSTRACT; (c: Controller) Singleton (): Views.View, NEW; (c: Controller) SetSingleton (s: Views.View), NEW, EXTENSIBLE; (c: Controller) SelectAll (select: BOOLEAN), NEW, ABSTRACT; (c: Controller) InSelection (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, ABSTRACT; (c: Controller) MarkSelection (f: Views.Frame; show: BOOLEAN), NEW, EXTENSIBLE; (c: Controller) SetFocus (focus: Views.View), NEW; (c: Controller) HasCaret (): BOOLEAN, NEW, ABSTRACT; (c: Controller) MarkCaret (f: Views.Frame; show: BOOLEAN), NEW, ABSTRACT; (c: Controller) Mark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN), NEW, EXTENSIBLE END; Directory = POINTER TO ABSTRACT RECORD (d: Directory) New (): Controller, NEW, EXTENSIBLE; (d: Directory) NewController (opts: SET): Controller, NEW, ABSTRACT END; DropPref = RECORD (Properties.Preference) mode-: SET; okToDrop: BOOLEAN END; GetOpts = RECORD (Views.PropMessage) valid, opts: SET END; SetOpts = RECORD (Views.PropMessage) valid, opts: SET END; PROCEDURE Focus (): Controller; PROCEDURE FocusSingleton (): Views.View; PROCEDURE MarkSingleton (c: Controller; f: Views.Frame; show: BOOLEAN); PROCEDURE FadeMarks (c: Controller; show: BOOLEAN); END Containers. Контейнеры - это отображения, которые могут содержать другие (внедренные) отображения. Обычно контейнеры разделяются на две категории. К первой относятся контейнеры с фиксированной структурой и фиксированными типами внедряемых отображений. Например, контейнер электронной почты может состоять лишь из двух отображений: панели инструментов вверху и текстового отображения внизу. Их размещение не может редактироваться. Такие отображения называются статические контейнеры. Вторая категория контейнеров может внедрять произвольное количество отображений, которые могут иметь произвольные типы. Текстовые отображения и формы могут служить примерами таких динамических отображений-контейнеров. Только эта вторая категория, называемая динамические контейнеры, поддерживается модулем Containers, и к ним относится этот текст. Динамические контейнеры состоят из переменного числа внедренных отображений, плюс некоторое собственное содержание. Например, текстовые отображения содержат текст в качестве собственного содержания, но также позволяют произвольным отображениям (то есть, не-собственному содержанию), плавать в тексте. Отображения-формы являются деградировавшими в том смысле, что они не имеют собственного содержания. Различные стандарты составных документов (OLE, OpenDoc) различаются тем, как трактуется выделение и фокус. Фокус - это редактируемое в настоящий момент отображение, отображение, получающее события от клавиатуры, отображение, которое определяет доступные в настоящий момент меню, отображение, которое содержит текущее выделение, каретку или иную метку. Модуль Containers предоставляет строительные блоки для отображений-контейнеров, включая специальные модели и диспетчеры. В отличие от большинства модулей BlackBox, Containers экспортирует несколько конкретно реализованных типов, не считая чистых типов-интерфейсов. Реализации предоставляются в форме, общей для используемых платформ, то есть, различия в пользовательском интерфейсе скрыты реализацией Containers. В частности, Containers полностью реализует монолитные выделения, то есть, выделения, которые захватывают точно одно отображение без собственного содержимого контейнера. Пример: КартаподсистемыForm CONST noSelection, noFocus, noCaret Возможные элементы Controller.opt. noSelection указывает, что выделение должно быть отключено, noFocus указывает, что никакое из внедренных отображений не имеет фокуса, и noCaret указывает, что каретка (метка вставки) и, следовательно, возможность набора или вставки должны быть отключены. CONST mask, layout Два особенно полезных подмножества Controller.opr. mask запрещает редактирование собственного содержания контейнера, но допускает фокусирование и тем самым редактирование внедренных объектов; например, это позволяет использовать форму без ее изменения. layout действует с точностью до наоборот: фокусирование и редактирование внедренных объектов приостанавливаются, но собственное содержимое контейнера может свободно редактироваться; например, это полезно для редактирования форм без реальной активации, скажем, кнопки, когда редактируется ее позиция на форме. CONST deselect, select Возможные значения параметра select метода Controller.SelectAll. CONST any, selection Возможные значения параметра selection методов Controller.GetFirstView, Controller.GetNextView, Controller.GetPrevView, Controller.PollNativeProp и Controller.SetNativeProp. Указывает, когда сферой действия операции является текущее выделение или содержимое контейнера целиком. CONST hide, show Возможные значения параметра show процедур FadeMarks, MarkSingleton, Controller.Mark, Controller.MarkCaret, Controller.MarkDropTarget, Controller.MarkPickTarget и Controller.MarkSelections. Указывает, когда соответствующая метка должна быть скрыта или показана. TYPE Model (Models.Model) ABSTRACT Модели для контейнеров. PROCEDURE (m: Model) GetEmbeddingLimits (OUT minW, maxW, minH, maxH: INTEGER) NEW, ABSTRACT Возвращает минимальные (minW, minH) и максимальные (maxW, maxH) границы размеров отображения, внедряемого в модель m. При попытке внедрить в m отображение с шириной < minW, шириной >= maxW, высотой < minH или высотой >= maxH модели m следует (но не обязательно требуется) изменить размер внедряемого отображения. Постусловие 0 <= minW <= maxW 0 <= minH <= maxH PROCEDURE (m: Model) ReplaceView (old, new: Views.View) NEW, ABSTRACT Подстановка вместо отображения old, которое должно быть внедренным в m, отображения new, которое не может быть ранее внедренным нигде. В результате new оказывается внедренным в m, но old сохраняет свой контекст, который затем рапространяется вместе с new. Замена отображения допускает обертывание отображений: Новое отображение занимает место старого, добавляет некоторые новые свойства, но также может сохранить ссылку на старое отображение и делегировать к нему запросы. Пока старое отображение сохраняет свой контекст, оно будет продолжать работать, как если бы оно было непосредственно внедрено в m. Предусловие old # NIL old.context.ThisModel() = m EmbeddedIn(old, m) new # NIL new.context = NIL Постусловие NotEmbedded(old) new.context.ThisModel() = m new.context = old.context PROCEDURE (m: Model) InitFrom- (source: Model) NEW, EMPTY Инициализирует модель m, которая была заново размещена как объект того же типа, что и source. В некоторых (редких) случаях это может быть полезно для разделения некоторых внутренних структур данных между m и source. Предусловие source # NIL Type(m) = Type(source) TYPE View (Views.View) ABSTRACT Отображение для контейнеров. PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader) Уточнение унаследованной процедуры Полностью реализованная загрузка для отображений без собственного перманентного состояния, обрабатывающая загрузку модели отображения-контейнера и диспетчера. Если загрузка модели терпит неудачу, отображение переключается в нелегальное состояние и загрузка v отменяется; в противном случае модель присоединяется к v. Если загрузка диспетчера терпит неудачу, дипспетчер хранится для последующей выгрузки, чтобы предотвратить потерю информации, но не подключается к отображению (v.ThisController() = NIL), и отображение загружается нормально (то есть, не становится нелегалом). PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer) Уточнение унаследованной процедуры Полностью реализованная выгрузка для отображений без собственного перманентного состояния, обрабатывающая загрузку модели отображения-контейнера и диспетчера. Если v было ранее загружено с диспетчером-нелегалом, и никакой другой диспетчер установлен не был, то нелегальный диспетчер будет выгружен, хотя v.ThisController() = NIL. Супервызов в начале обязателен Предусловие v.ThisModel() # NIL 20 PROCEDURE (v: View) CopyFrom (source: Stores.Store) Уточнение унаследованной процедуры Предполагая, что модель для v уже была установлена, копирует диспетчер и, возможно, состояние другого отображения из source. Если source cодержит скрытый нелегальный диспетчер (см. Internalize выше), ссылка на него также копируется. Супервызов в начале обязателен Предусловие v.ThisModel() # NIL 20 Постусловие source.ThisController() = NIL v.ThisController() = NIL source.ThisController() # NIL v.ThisController() = source.ThisController().Clone().CopyFrom(source.ThisController()) PROCEDURE (v: View) ThisModel (): Model EXTENSIBLE Возвращает модель для v. Ковариантное сужение результата функции. PROCEDURE (v: View) InitModel (m: Containers.Model) NEW Назначить модель для данного отображения. Предусловие (v.ThisModel() = NIL) OR (v.ThisModel() = m) 20 m # NIL 21 v.AcceptableModel(m) 22 PROCEDURE (v: View) InitModel2- (m: Containers.Model) NEW, EMPTY Перехватчик расширений, вызываемый из InitModel. PROCEDURE (v: View) SetController (c: Controller) NEW, EXTENSIBLE, Operation Устанавливает диспетчер для v. Если v имеет скрытый нелегальный диспетчер, он удаляется. Предусловие v.ThisModel() # NIL 20 Постусловие v.ThisController() = c PROCEDURE (v: View) ThisController (): Controller NEW, EXTENSIBLE Возвращает диспетчер для v. PROCEDURE (v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER) NEW, ABSTRACT Для показа в кадре f, задает прямоугольную границу отображения view, которое должно быть внедренным в v. Если вычисления для границы будут слишком объемными, дает приемлемое приближение. Постусловие l <= r t<= b PROCEDURE (v: View) CatchModelMsg (VAR msg: Models.Message) NEW, EMPTY Перехватчик расширений для HandleModelMsg, который стал финальным. PROCEDURE (v: View) CatchViewMsg (f: Views.Frame; VAR msg: Views.Message) NEW, EMPTY Перехватчик расширений для HandleViewMsg, который стал финальным. PROCEDURE (v: View) CatchCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View) NEW, EMPTY Перехватчик расширений для HandleCtrlMsg, который стал финальным. PROCEDURE (v: View) CatchPropMsg (VAR p: Properties.Message) NEW, EMPTY Перехватчик расширений для HandlePropMsg, который стал финальным. PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View) Уточнение унаследованной процедуры Если v имеет установленный диспетчер, вызывает v.ThisController().HandleCtrlMsg(f, msg, focus), затем вызывает v.CatchCtrlMsg(f, msg, focus). То есть, диспетчер видит сообщение msg раньше, чем отображение. Дополнительно применяется строгий фильтр, отсеивающий нежелательные сообщения: сообщения делегируются диспетчеру или отображению, только если они удовлетворяют одному из следующих трех критериев: Первое, что кадр f является целевым или передним кадром. Второе, что сообщение пришло от Controllers.PollOpsMsg, Controllers.PollCursorMsg, Controllers.TransferMessage или Controllers.PageMsg. Третье, что контекст v является нормализованным, то есть, вызывалось v.context.Normalize(), и сообщение пришло от Controllers.PollSectionMsg or Controllers.ScrollMsg. Это стандартные условия фильтрации сообщений, делающие компоненты более устойчивыми против случайных сообщений. Наконец, сообщения прокрутки (приходящие от Controllers.PollSectionMsg или Controllers.ScrollMsg) могут запросить поверхностную обработку (~msg.focus), то есть подавление возможной пересылки сообщения существующим подфокусам. В этих случаях возрат из процедуры сопровождается очисткой focus. Постусловие (msg IS Controllers.PollSectionMsg) OR (msg IS Controllers.ScrollMsg) ~msg.focus focus = NIL TYPE Controller (Controllers.Controller) ABSTRACT Диспетчеры для контейнеров. opts-: SET Множество свойств диспетчера; используется для усечения функциональности диспетчера до опредленных подмножеств. PROCEDURE (c: Controller) ThisView (): View EXTENSIBLE Возвращаемый тип сужен. PROCEDURE (c: Controller) SetOpts (opts: SET) NEW, EXTENSIBLE, Операция Устанавливает свойства c. Это является операцией только после установки отображения, то есть, когда c.ThisView() # NIL, иначе это всего лишь простое присваивание opts полю c.opts. Свойства 0..7 используются или зарезервированы для BlackBox, остальные могут использоваться в расширениях. Постусловие c.opts = opts PROCEDURE (c: Controller) GetContextType (OUT type: Stores.TypeName) NEW, ABSTRACT Вызывается из c.HandleCtrlMsg для заполнения Controllers.PollOpsMsg.type. PROCEDURE (c: Controller) GetValidOps (OUT valid: SET) NEW, ABSTRACT Вызывается из c.HandleCtrlMsg для заполнения Controllers.PollOpsMsg.ops. PROCEDURE (c: Controller) NativeModel (m: Models.Model): BOOLEAN NEW, ABSTRACT Проверяет, что m является исконной моделью c, то есть, моделью, которая может быть подключена к отображению, годному для подключения к c. PROCEDURE (c: Controller) NativeView (v: Views.View): BOOLEAN NEW, ABSTRACT Проверяет, что v является исконным отображением c, то есть, отображением, которое может быть подключено к c. PROCEDURE (c: Controller) NativeCursorAt (f: Views.Frame; x, y: INTEGER): INTEGER NEW, ABSTRACT Курсор, который c будет отображал бы точке (x, y) кадра f, безотносительно к отображениям, возможно, внедренным на этой позиции. PROCEDURE (c: Controller) PickNativeProp (f: Views.Frame; x, y: INTEGER; VAR p: Properties.Property) NEW, EMPTY Свойства исконного содержания c в точке (x, y) кадра f, безотносительно к отображениям, возможно, внедренным на этой позиции. PROCEDURE (c: Controller) PollNativeProp (selection: BOOLEAN; VAR p: Properties.Property; VAR truncated: BOOLEAN); NEW, EMPTY Свойства исконного выделенного или полного содержания c, безотносительно к отображениям, возможно, внедренным на этом пространстве. PROCEDURE (c: Controller) SetNativeProp (selection: BOOLEAN; old, p: Properties.Property) NEW, EMPTY Устанавливает свойства исконного выделенного или полного содержания c равными p, безотносительно к отображениям, возможно, внедренным на этом пространстве. Изменяются значения только тех свойств c, старые значения которых совпадают с теми, которые переданы в old. Это делает возможным выборочное изменение свойств. Например, в цветной модели все красные объекты могут быть сделаны зелеными. PROCEDURE (c: Controller) MakeViewVisible (v: Views.View) NEW, EMPTY Делает внедренное отображение v видимым в отображении контроллера. Предусловие v внедрено в отображение c 20 PROCEDURE (c: Controller) GetFirstView (selection: BOOLEAN; OUT v: Views.View) NEW, ABSTRACT Возвращает первое отображение, внедренное в модель c, относительно начала модели или текущего выделения. PROCEDURE (c: Controller) GetNextView (selection: BOOLEAN; VAR v: Views.View) NEW, ABSTRACT Возвращает следующее отображение в указанном промежутке, который может быть выделением или полным содержанием модели c. Отображение, следующее за последним в указанном промежутке, считается NIL. PROCEDURE (c: Controller) GetPrevView (selection: BOOLEAN; VAR v: Views.View) NEW, EXTENSIBLE Возвращает следующее отображение в указанном промежутке, который может быть выделением или полным содержанием модели c. Обычно использует GetFirstView и GetNextView для поиска предыдущего отображения v. Отображение, предыдущее к первому в указанном промежутке, считается NIL. Предусловие v # NIL 20 EmbeddedIn(v, c.ThisModel()) 21 PROCEDURE (c: Controller) CanDrop (f: Views.Frame; x, y: INTEGER): BOOLEAN NEW, EXTENSIBLE Возвращает, может ли перетаскиваемый материал быть брошен в кадр f в его локальных координатах (x, y). По умолчанию любой запрос на бросание разрешается, то есть, возвращается TRUE. PROCEDURE (c: Controller) MarkDropTarget (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; type: Stores.TypeName; isSingle, show: BOOLEAN) NEW, EMPTY Помечает цель перетаскивания в принимающем кадре dst в точке (dx, dy) для потенциального бросания материала с позиции (sx, sy) кадра-источника src. show указывает, должна ли метка быть поставлена или удалена. isSingle указывает, является ли бросаемое выделение монолитом. (rx, ry) - точка привязки внутри выделения, в которой началась операция перетаскивания. См. также Controllers.PollDropMsg. PROCEDURE (c: Controller) Drop (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER; view: Views.View; isSingle: BOOLEAN) NEW, ABSTRACT Бросает материал, перетаскиваемый с позиции (sx, sy) кадра-источника src и инкапсулированный в отображении view под контролем c, в точку (dx, dy) кадра-приемника dst. По умолчанию бросание игнорируется. isSingle указывает, является ли бросаемое выделение монолитом. (rx, ry) - точка привязки внутри выделения, в которой началась операция перетаскивания. См. также Controllers.DropMsg. PROCEDURE (c: Controller) MarkPickTarget (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER; show: BOOLEAN) NEW, EMPTY Помечает цель перетаскивания в принимающем кадре dst в точке (dx, dy) для потенциального бросания материала с позиции (sx, sy) кадра-источника src. show указывает, должна ли метка быть поставлена или удалена. По умолчанию метка не ставится вообще. PROCEDURE (c: Controller) TrackMarks (f: Views.Frame; x, y: INTEGER; units, extend, add: BOOLEAN) NEW, ABSTRACT Протягивает метки в кадре f, начиная с точке (x, y), как задано параметрами units, extend и add. Метки являются общими выделениями и точками вставки (каретками). Протяжка крупных логических единиц (например, слов вместо символов) запрашивается параметром units. Непрерывное расширение существующего выделения запрашивается параметром extend. Дискретное добавление к существующему выделению запрашивается параметром add. Некоторые диспетчеры могут игнорировать тот или иной запрос, то есть могут не различать единицы различной гранулярности, могут не поддерживать выделение нескольких объектов или дискретные выделения. PROCEDURE (c: Controller) Resize (view: Views.View; l, t, r, b: INTEGER) NEW, ABSTRACT Запрос на изменение размера view, которое должно быть внедрено в модель c, на размер, заданный прямоугольником (l, t, r, b). (Обычно диспетчер делегирует этот запрос к своей модели, которая обрабатывает запрос, используя Properties.PreferredSize для согласования нового размера с отображением view). PROCEDURE (c: Controller) GetSelectionBounds (f: Views.Frame; OUT x, y, w, h: INTEGER) NEW, ABSTRACT Возвращает прямоугольную границу выделения, заданную верхней левой точкой привязки, шириной и высотой. Граница используется для обеспечения обратной связи при перетаскивании. PROCEDURE (c: Controller) DeleteSelection NEW, ABSTRACT Удаляет все объекты в текущем выделении. PROCEDURE (c: Controller) MoveLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER) NEW, ABSTRACT Передвигает выделенные объекты в пределах модели c c начальной точки (sx, sy) кадра src в целевую точку (dx, dy) кадра dst. Так как перемещение происходит в рамках единственной модели, нет необходимости в преобразованиях, и может быть предоставлена наиболее естественная семантика перемещения. PROCEDURE (c: Controller) CopyLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER) NEW, ABSTRACT Копирует выделенные объекты в пределах модели c c начальной точки (sx, sy) кадра src в целевую точку (dx, dy) кадра dst. Так как копирование происходит в рамках единственной модели, нет необходимости в преобразованиях, и может быть предоставлена наиболее естественная семантика перемещения. PROCEDURE (c: Controller) SelectionCopy (): Model NEW, ABSTRACT Возвращает копию выделенных объектов, инкапсулированную в возвращаемой модели. PROCEDURE (c: Controller) NativePaste (m: Models.Model; f: Views.Frame) NEW, ABSTRACT Вставляет исконную модель в модель c как показано в кадре f. Поскольку модель является исконной, она сливается с моделью c вместо того, чтобы оборачиваться в отображение и внедряться. PROCEDURE (c: Controller) ArrowChar (f: Views.Frame; ch: CHAR; units, select: BOOLEAN) NEW, ABSTRACT Обрабатывает символ стрелки ch - один из списка нижа. Обработка изменяется в зависимости от параметров units и select. Стандартная обработка символов стрелки - это изменение текущего выделения или перемещение точки вставки. Параметр units запрашивает изменение или перемещение в крупных единицах (например, словах вместо символов). Начало выделения запрашивается параметром select. Некоторые диспетчеры могут игнорировать тот или иной запрос, например, могут не различать единицы различной гранулярности или не поддерживать выделения. Таблица символов стрелок: имя код значение aL 1CX стрелка влево aR 1DX стрелка вправо aU 1EX стрелка вверх aD 1FX стрелка вниз pL 10X страница влево pR 11X страница вправо pU 12X страница вверх pD 13X страница вниз dL 14X документ влево dR 15X документ вправо dU 16X документ вверх dD 17X документ вниз Намерением является изменение или перемещение в указанном направлении на наименьшую поддерживаемую гранулярность ("стрелку"), на основе "страниц", которые определяются размером кадра f, или на основе целого "документа", то есть, крайних точек модели c. Точная трактовка направлений и единиц оставлена конкретному диспетчеру. PROCEDURE (c: Controller) ControlChar (f: Views.Frame; ch: CHAR) NEW, ABSTRACT Вход обработчика управляющего символа ch относительно модели и отображения c в кадре f. Таблица управляющих символов: имя код значение enter 3X ввод rdel 7X правое удаление del 8X левое удаление tab 09X табуляция ltab 0AX обратная табуляция line 0DX строка para 0EX абзац esc 1BX escape PROCEDURE (c: Controller) PasteChar (ch: CHAR) NEW, ABSTRACT Вставить символ ch в модель c. PROCEDURE (c: Controller) PasteView (f: Views.Frame; v: Views.View; w, h: INTEGER) NEW, ABSTRACT Вставить отображение v с заданными размерами (w, h) в модель c. (Обычно диспетчер делегирует этот запрос к своей модели, которая обрабатывает его, используя Properties.PreferredSize для согласования нового размера с v.) PROCEDURE (c: Controller) HasSelection (): BOOLEAN NEW, EXTENSIBLE Возвращает, имеет ли диспетчер текущее выделение. По умолчанию поддерживаются только выделения-монолиты. Следует расширить для поддержки полных выделений. Предусловие c.ThisModel() # NIL 20 PROCEDURE (c: Controller) Selectable (): BOOLEAN NEW, ABSTRACT Возвращает, сможет ли диспетчер начать непустое выделение. Если что-либо уже выделено, выделение считается возможным. PROCEDURE (c: Controller) Singleton (): Views.View NEW Если диспетчер имеет текущее выделение-монолит, то возвращается выделенное отображение, иначе NIL. PROCEDURE (c: Controller) SetSingleton (s: Views.View) NEW, EXTENSIBLE Устанавливает выделение для диспетчера равным монолиту, покрывающему отображение s. Если s = NIL, текущее выделение снимается. Метод следует расширить для соответствующей поддержки полного выделения. Предусловие c.ThisModel() # NIL 20 ~(noSelection IN c.opts) 21 s # NIL s.context # NIL 22 s.context.ThisModel() = c.ThisModel() 23 Постусловие c.Singleton() = s PROCEDURE (c: Controller) SelectAll (select: BOOLEAN) NEW, ABSTRACT Устанавливает выделение максимально возможной протяженности, то есть, выделяет все собственное содержание модели контейнера плюс все внедренные отображения. Для пустой модели не будет видимого результата; для модели с только одним внедренным отображением и без собственного содержания будет выделен монолит. PROCEDURE (c: Controller) InSelection (f: Views.Frame; x, y: INTEGER): BOOLEAN NEW, ABSTRACT Проверяет, лежит ли точка (x, y) кадра f в пределах текущего выделения. PROCEDURE (c: Controller) MarkSelection (f: Views.Frame; show: BOOLEAN) NEW, EXTENSIBLE В зависимости от show, показывает или скрывает визуальный показ выделения. По умолчанию работает только для выделений-монолитов. Метод следует переопределить для поддержки полных выделений. PROCEDURE (c: Controller) SetFocus (focus: Views.View) NEW Устанавливает текущий подфокус равным focus; если focus = NIL, текущий подфокус снимается. Предусловие c.ThisModel() # NIL 20 focus # NIL focus.context # NIL 21 focus.context.ThisModel() = c.ThisModel() 22 Постусловие c.ThisFocus() = focus PROCEDURE (c: Controller) HasCaret (): BOOLEAN NEW, ABSTRACT Возвращает, имеет ли диспетчер правильную каретку (точку вставки). PROCEDURE (c: Controller) MarkCaret (f: Views.Frame; show: BOOLEAN) NEW, ABSTRACT В зависимости от show, показывает или скрывает визуальный показ текущей каретки. PROCEDURE (c: Controller) Mark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN) NEW, EXTENSIBLE За исключением быстродействия, эквивалентно: MarkFocus(c, f, show); c.MarkSelection(f, show); c.MarkCaret(f, show) Метод следует расширить для поддержки расширенной полной пометки. PROCEDURE (c: Controller) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER) Уточнение унаследованной процедуры Вызывает Mark для показа всех меток в прямоугольнике (l, t, r, b), затем, если нет подфокуса и c.opts задает режим маски, пытается включить подфокус: его получает первое внедренное отображение, которое претендует на фокус (Properties.FocusPref.setFocus). Если новый подфокус желает быть запущенным с выделенным содержанием (Properties.FocusPref.selectOnFocus), оно целиком выделяется. PROCEDURE (c: Controller) Neutralize Уточнение унаследованной процедуры Снимает все модальные пометки, включая фокус, выделение и каретку. По умолчанию обрабатываются фокус и выделение. Для обработки каретки и, возможно, позже введенных пометок, метод следует расширить. За исключением быстродействия, по умолчанию эквивалентно: c.SetFocus(NIL); c.SelectAll(deselect) PROCEDURE (c: Controller) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View) Уточнение унаследованной процедуры Обрабатывает Controllers.PollCursorMsg, Controllers.PollOpsMsg, Controllers.TrackMsg, Controllers.EditMsg, Controllers.TransferMessage, Controllers.SelectMsg, Controllers.MarkMsg, Controllers.ReplaceViewMsg, Properties.CollectMsg, и Properties.EmitMsg. PROCEDURE (c: Controller) HandlePropMsg (VAR p: Properties.Message) Уточнение унаследованной процедуры По умолчанию предназначено для обработки Properties.SetMsg и Properties.PollMsg, разделяя обработку собственных и внедренных свойств и устанавливая или возвращая совмещенный список свойств. Также, если в c.opts установлены noSelection, noFocus, и noCaret, то устанавливается поле Properties.FocusPref.setFocus. Предусловие c.ThisModel() # NIL 20 TYPE Directory ABSTRACT Директория для диспетчеров PROCEDURE (d: Directory) New (): Controller NEW, EXTENSIBLE За исключением быстродействия, эквивалентно: RETURN d.NewController({}) PROCEDURE (d: Directory) NewController (opts: SET): Controller NEW, ABSTRACT Возвращает новый диспетчер со свойствами opts. TYPE DropPref = RECORD (Properties.Preference) Это сообщение посылается внедренному отображению, когда контейнеру необходимо принять решение, бросать ли что-либо в отображение или в контейнер. Это сообщение может быть перехвачено также для поддержки перетаскивания, когда контейнер должен сам нормально ловить сообщения бросания, то есть, когда он находится в режиме разметки. mode-: SET Текущий режим контейнера. okToDrop: BOOLEAN Установлено в TRUE, если отображение может получать сообщения о бросании также в режиме, заданном в mode. TYPE GetOpts = RECORD (Views.PropMessage) Это сообщение посылается выделенному отображению для запроса режима контейнера этого отображения. Если отображение ответило на это сообщение, оно должно установить valid равным свойствам, примененным к отображению, и opts равным текущим значениям этих свойств. Всякий раз, когда возможен ответ на GetOpts, также должен быть возможен ответ на сообщение SetOpts. valid: SET Должно быть установлено равным свойствам, которые примененяются к отображению. opts: SET Текущие значения свойств. TYPE SetOpts = RECORD (Views.PropMessage) Посылается отображению для указания, что свойства должны быть изменены на значения, заданные valid и opts. valid: SET Маска, указывающая, какие значения должны быть установлены. opts: SET Значения свойств, указанных в valid. PROCEDURE Focus (): Controller Возвращает диспетчер текущего фокусированного отображения, если это возможно. PROCEDURE FocusSingleton (): Views.View Возвращает выделение-монолит текущего фокусированного отображения, если это возможно. PROCEDURE MarkSingleton (c: Controller; f: Views.Frame; show: BOOLEAN) Для внутреннего пользования. PROCEDURE FadeMarks (c: Controller; show: BOOLEAN) Для внутреннего пользования.
System/Docu/ru/Containers.odc