texts
stringlengths 0
715k
| names
stringlengths 8
91
|
---|---|
4. Пошаговая разработка: Уплотнение массива
Задача. Уплотнить литерную цепочку (литеры в массиве до первого вхождения литеры-ограничителя 0X), заменив каждую последовательность идущих подряд двух или более пробелов на один пробел, сдвигая остальные элементы влево
Решение
ЧастьА Постановка задачи. Проектирование интерфейса
ЧастьБ Проверка корректности входных данных
ЧастьВ Построение основной процедуры
ЧастьГ Демонстрация работы
ЧастьД Упражнения
Часть А. Постановка задачи. Проектирование интерфейсов
Эта часть выполняется в основном так же, как и в первомпримере. Только тип элементов массива-параметра будет CHAR вместо INTEGER, и еще нужно по-другому назвать модуль и процедуру. Пусть полное имя модуля будет i21примУплотнение (т.е. имя файла, в котором хранится модуль, будет Уплотнение). Процедуру назовем Уплотнить. Получим следующую заготовку:
MODULE i21примУплотнение;
PROCEDURE Уплотнить* ( VAR a: ARRAY OF CHAR );
VAR
BEGIN
END Уплотнить;
END i21примУплотнение.
Часть Б. Проверка корректности входных данных
В этой части изложение менее подробно и предполагает хорошее знакомство с предыдущими примерами.
Особенностью данной задачи является сравнительно сложная структура входных данных, так что возникает необходимость проверить, выполняются ли предположения задачи. Конкретно, нужно определить, действительно ли в массиве a есть элемент, в котором хранится специальное значение 0X, используемое в качестве ограничителя символьных цепочек в Компонентном Паскале.
Рассуждая подобно примеруспроверкойпростыхчисел, выберем такой способ проверки, чтобы программа аварийно останавливалась, если входные условия не удовлетворены. Поручим проверку отдельной процедуре назовем ее Проверить, которая вызывается в самом начале процедуры Уплотнить. Для надежности расположим ее вне процедуры Уплотнить в том же модуле (перед Уплотнить):
MODULE i21примУплотнение;
PROCEDURE Проверить ( VAR a: ARRAY OF CHAR );
VAR
BEGIN
END Проверить;
PROCEDURE Уплотнить* ( VAR a: ARRAY OF CHAR );
VAR
BEGIN
Проверить( a );
END Уплотнить;
END i21примУплотнение.
Поиск конкретного значения в заданном массиве осуществляется по стандартной схеме, уже использовавшейся в примере с проверкой простых чисел (там искалсянаименьшийделительчисла). Сразу напишем нужный цикл (его следует сравнить с окончательным вариантом модуля i21примПростые):
PROCEDURE Проверить ( VAR a: ARRAY OF CHAR );
VAR кандидат: INTEGER;
BEGIN
кандидат := 0;
WHILE (кандидат < LEN(a)) & (a[кандидат] # 0X) DO
кандидат := кандидат + 1
END;
ASSERT( кандидат < LEN(a) )
END Проверить;
Здесь кандидат индекс очередного проверяемого элемента массива, и вместо того, чтобы возвращать логическое значение, мы передали его в стандартную процедуру ASSERT. Кроме того, при определении простоты числа TRUE возвращалось, когда подходящий кандидат на роль делителя не был найден, а здесь нужно передавать TRUE в том случае, когда кандидат на 0X был успешно обнаружен. Так что условие в ASSERT соответствует отрицанию возвращаемого выражения в процедуре i21примПростые.Простое.
Часть В. Построение основной процедуры
Алгоритм построим на основе следующего наблюдения: после исключения лишних пробелов порядок литер будет такой же, как и до уплотнения.
Тогда если i начальная позиция какой-то литеры, а j ее позиция после уплотнения, то при постепенном увеличении i значение j будет либо тоже возрастать, либо оно будет оставаться неизменным в том случае, если i проходит по "лишним" пробелам.
i
до уплотнения: один два три
после уплотнения: один два три
j
Алгоритм построим в виде цикла. На каждом шаге цикла будем либо увеличивать только i, пропуская лишние пробелы, либо одновременно увеличивать i и j и пересылать значение из a[i] в a[j].
Цикл будем строить так, чтобы в начале каждого шага цикла индекс j указывал на последнюю позицию, в которую мы что-либо переслали на предыдущих шагах, а i на последний просмотренный элемент.
Тогда цикл можно записать следующим образом:
установить начальные значения для цикла;
ПОКА не вышли за конец цепочки ДЕЛАТЬ
увеличить i;
ЕСЛИ a[i] лишний пробел ТО
перейти к след. шагу цикла
ИНАЧЕ
увеличить j;
передвинуть значение a[i] в a[j]
КОНЕЦ
КОНЕЦ
Переводя ключевые слова на английский язык и сразу кодируя на Компонентном Паскале очевидные операции, получим:
установить начальные значения для цикла;
WHILE не вышли за конец цепочки DO
i := i + 1;
IF a[i] лишний пробел THEN
(* ничего не делать *)
ELSE
j := j + 1;
a[j] := a[i]
END
END
После THEN стоит только комментарий, т.к. после IF нет никаких инструкций, и поэтому для перехода к началу цикла ничего специально делать не нужно.
Чтобы закодировать охрану цикла ("не вышли за конец цепочки"), посмотрим, что происходит в самом конце цикла. Цепочка замыкается специальной литерой-ограничителем 0X. Ее нужно переслать, чтобы получившаяся цепочка оказалась правильно оформленной. Поэтому ее можно трактовать как и любую другую литеру, не являющуюся пробелом. Тогда 0X должен быть последней литерой, которую мы переслали. Но тогда и распознать, что мы на предыдущем шаге уже переслали 0X, легко: достаточно проверить равенство a[j] = 0X.
установить начальные значения для цикла;
WHILE a[j] # 0X DO
i := i + 1;
IF a[i] лишний пробел THEN
(* ничего не делать *)
ELSE
j := j + 1;
a[j] := a[i]
END
END
Как теперь узнать, является ли значение, хранящееся в a[i], лишним пробелом?
Тут два условия, которые должны выполниться одновременно.
Во-первых, a[i] должно быть пробелом, и если это так, то это должен быть лишний пробел. Первое условие записать легко, так что охрану условного оператора IF можно записать так:
IF (a[i] = ' ') & (этот пробел лишний) THEN
Чтобы понять, как определить, является ли пробел лишним, изобразим именно такую ситуацию. Для этого возьмем тот же пример и поставим i и j в позиции, соответствующие именно такой ситуации:
i
до уплотнения: один два три
после уплотнения: один два три
j
Видно, что достаточно посмотреть на значение, хранящееся в a[j]: ведь именно там хранится последняя литера, которую мы переместили. Если там пробел, то пробел в a[i] заведомо лишний. В противном случае это не так.
В итоге наш цикл приобретает такой вид:
установить начальные значения для цикла;
WHILE a[j] # 0X DO
i := i + 1;
IF (a[i] = ' ') & (a[j] = ' ') THEN
(* ничего не делать *)
ELSE
j := j + 1;
a[j] := a[i]
END
END
Позаботимся об установлении начальных значений.
Мы построили цикл исходя из предположения, что в начале каждого шага цикла i должно указывать на последний элемент, который мы уже просмотрели, а j последний элемент, в который что-то было записано.
Другими словами, мы как бы должны к моменту начала первого шага цикла сделать первый шаг уплотнения.
Исследуем первую литеру начальной цепочки. Это может быть пробел, или любая другая литера, в том числе и 0X. Если это пробел, то перед ним, разумеется, нет пробелов, и поэтому по условию задачи он не является "лишним", т.е. должен остаться в цепочке после уплотнения. Если это другая литера (в том числе и 0X), то она тем более должна остаться в цепочке.
Куда она должна попасть? Так как это первая литера, то и попасть она должна на первое место попросту остаться там, где она и так стоит.
Выходит, чтобы цикл начался правильно, достаточно установить i и j в нуль и тогда нулевой элемент цепочки будет автоматически правильно обработан, что и требуется для правильного начала цикла. Получаем окончательный модуль:
MODULE i21примУплотнение;
PROCEDURE Проверить ( VAR a: ARRAY OF CHAR );
VAR кандидат: INTEGER;
BEGIN
кандидат := 0;
WHILE (кандидат < LEN(a)) & (a[кандидат] # 0X) DO
кандидат := кандидат + 1
END;
ASSERT( кандидат < LEN(a) )
END Проверить;
PROCEDURE Уплотнить* ( VAR a: ARRAY OF CHAR );
VAR i, j: INTEGER;
BEGIN
Проверить( a );
i := 0; j := 0;
WHILE a[j] # 0X DO
i := i + 1;
IF (a[i] # ' ') OR (a[j] # ' ') THEN
j := j + 1;
a[j] := a[i]
END
END
END Уплотнить;
END i21примУплотнение.
Мы еще сделали маленькое сокращение кода, исключив пустую ветвь оператора IF; для этого пришлось заменить условное выражение на его отрицание по правилу де Моргана.
Часть Г. Проверка работы
Чтобы продемонстрировать работу процедуры, введем в модуль еще одну процедуру с именем Демо, которая будет получать цепочку литер в качестве параметра, обрабатывать ее с помощью процедуры Уплотнить, а также печатать цепочку до и после уплотнения.
Разумеется, чтобы использовать средства печати в рабочий журнал, нужно импортировать модуль StdLog.
Окончательный вариант модуля выглядит так:
MODULE i21примУплотнение;
IMPORT StdLog;
PROCEDURE Проверить ( VAR a: ARRAY OF CHAR );
VAR кандидат: INTEGER;
BEGIN
кандидат := 0;
WHILE (кандидат < LEN(a)) & (a[кандидат] # 0X) DO
кандидат := кандидат + 1
END;
ASSERT( кандидат < LEN(a) )
END Проверить;
PROCEDURE Уплотнить* ( VAR a: ARRAY OF CHAR );
VAR i, j: INTEGER;
BEGIN
Проверить( a );
i := 0; j := 0;
WHILE a[j] # 0X DO
i := i + 1;
IF (a[i] # ' ') OR (a[j] # ' ') THEN
j := j + 1;
a[j] := a[i]
END
END
END Уплотнить;
PROCEDURE Демо* ( цепочка: ARRAY OF CHAR );
VAR a: ARRAY 200 OF CHAR;
BEGIN
a := цепочка$;
StdLog.String('до сжатия:'); StdLog.Ln;
StdLog.String(a); StdLog.Ln;
Уплотнить( a );
StdLog.String('после сжатия:'); StdLog.Ln;
StdLog.String(a); StdLog.Ln;
END Демо;
END i21примУплотнение.
Чтобы выполнить процедуру, нужно кликнуть по коммандеру (черному кружку):
"i21примУплотнение.Демо('Вот пример для уплотнения .')"
При этом можно произвольным образом менять уплотняемую цепочку (между одинарными кавычками) и смотреть, что получается.
Ясно, что условие задачи было не совсем реалистичным.
Более реалистичные варианты задачи оставляются в качестве упражнений.
Часть Д. Упражнения
Упражнение 1. Усовершенствовать процедуру так, чтобы полностью исключались пробелы в начале цепочки.
Подсказка. Достаточно изменить фрагмент инициализации цикла.
Упражнение 2. Усовершенствовать процедуру так, чтобы исключались все пробелы перед знаками препинания.
Упражнение 3. (а) Изменить процедуру так, чтобы исключить повторяющиеся вычисления:
двукратное обращение к одному и тому же элементу массива a[i] на каждом шаге цикла (обращение к элементу массива подразумевает некоторые скрытые вычисления, в том числе проверку индексов на предмет выхода за границы массива),
двукратное обращение к элементу a[j].
Заметить, сколько на это потребовалось времени.
(б). По образцу исследования, проведенного в другомпримере, измерить реальное ускорение, достигнутое за счет оптимизации в шаге (а).
Сделать выводы.
MODULE i21примУплотнение;
IMPORT StdLog;
PROCEDURE Проверить ( VAR a: ARRAY OF CHAR );
VAR кандидат: INTEGER;
BEGIN кандидат := 0;
WHILE (кандидат < LEN(a)) & (a[кандидат] # 0X) DO INC( кандидат ) END;
ASSERT( кандидат < LEN(a) )
END Проверить;
PROCEDURE Уплотнить* ( VAR a: ARRAY OF CHAR );
VAR i, j: INTEGER;
BEGIN Проверить( a ); i := 0; j := 0;
WHILE a[j] # 0X DO
i := i + 1;
IF (a[i] # ' ') OR (a[j] # ' ') THEN j := j + 1; a[j] := a[i] END
END
END Уплотнить;
PROCEDURE Уплотнить2* ( VAR a: ARRAY OF CHAR );
VAR i, j: INTEGER; ai, aj: CHAR; x: BOOLEAN;
BEGIN Проверить( a ); i := 0; j := 0; aj := a[0];
WHILE aj # 0X DO
i := i + 1; ai := a[i];
IF (ai # ' ') OR (aj # ' ') THEN j := j + 1; a[j] := ai; aj := a[j] END
END
END Уплотнить2;
PROCEDURE Демо* ( цепочка: ARRAY OF CHAR );
VAR a: ARRAY 200 OF CHAR;
BEGIN
a := цепочка$;
StdLog.String('до сжатия:'); StdLog.Ln; StdLog.String(a); StdLog.Ln;
Уплотнить( a );
StdLog.String('после сжатия:'); StdLog.Ln; StdLog.String(a); StdLog.Ln;
a := цепочка$;
Уплотнить2( a );
StdLog.String('после сжатия 2:'); StdLog.Ln; StdLog.String(a); StdLog.Ln;
END Демо;
PROCEDURE Test*;
VAR a: ARRAY 200 OF CHAR; i: INTEGER;
BEGIN FOR i := 1 TO 1000000 DO a := 'Вот пример для сжатия .'; Уплотнить( a ) END;
END Test;
PROCEDURE Test2*;
VAR a: ARRAY 200 OF CHAR; i: INTEGER;
BEGIN FOR i := 1 TO 1000000 DO a := 'Вот пример для сжатия .'; Уплотнить( a ) END;
END Test2;
END i21примУплотнение.
"i21примУплотнение.Демо('Вот пример для уплотнения .')"
i21примУплотнение.Test
i21примУплотнение.Test2
| i21прим/Docu.Пошаговая разработка/4. Уплотнение.odc |
(** Пример использования модуля i21eduFiles **)
MODULE i21примFiles;
IMPORT StdLog, Files := i21eduFiles;
PROCEDURE Создаем* ( a: ARRAY OF CHAR; n: INTEGER );
BEGIN
Files.New( a$ );
Files.WriteString( a$ );
Files.WriteString( 'Информатика-21' );
Files.WriteInt( n );
Files.WriteReal( 3.141592 );
Files.WriteChar( 's' );
Files.Close (* это нельзя забывать! а то модуль i21eduFiles будет ругаться *)
END Создаем;
PROCEDURE Читаем* ( a: ARRAY OF CHAR );
VAR i: INTEGER; x: REAL; c: CHAR; s: ARRAY 1000 OF CHAR;
BEGIN
StdLog.Ln;
Files.Open( a$ );
(* читаем точно в том же порядке *)
Files.ReadString( s ); StdLog.String( s ); StdLog.Ln;
Files.ReadString( s ); StdLog.String( s ); StdLog.Ln;
Files.ReadInt( i ); StdLog.Int( i ); StdLog.Ln;
Files.ReadReal( x ); StdLog.Real( x ); StdLog.Ln;
Files.ReadChar( c ); StdLog.Char( c ); StdLog.Ln;
Files.Close; (* это нельзя забывать! а то модуль i21eduFiles будет ругаться *)
StdLog.Ln
END Читаем;
PROCEDURE Стираем* ( a: ARRAY OF CHAR );
VAR i: INTEGER; x: REAL; c: CHAR; s: ARRAY 1000 OF CHAR;
BEGIN
(* прежде чем создать новый файл с тем же именем, нужно старый стереть явной командой *)
Files.Delete( a )
END Стираем;
END i21примFiles.
Для выполнения процедур кликать по черным коммандерам:
"i21примFiles.Стираем('test5.DAT')"
"i21примFiles.Создаем('test5.DAT',106)"
"i21примFiles.Читаем('test5.dat')"
Выгрузка двух модулей в правильном порядке:
DevDebug.UnloadThis i21примFiles i21eduFiles
Компиляция двух модулей в правильном порядке:
DevCompiler.CompileThis i21eduFiles i21примFiles
| i21прим/Mod/Files.odc |
MODULE i21примIn;
(* Примеры передачи входных параметров в процедуру с помощью средств модуля i21sysIn. *)
IMPORT StdLog, In := i21sysIn; (* конструкция In := ... вводит сокращенное имя In для использования в данном модуле; длинные имена модулей встречаются нередко, для них удобно вводить короткие псевдонимы *)
PROCEDURE ПростоПечать ( x: REAL; i: INTEGER; a: ARRAY OF CHAR ); (* эту процедуру нельзя вызвать с помощью коммандера *)
BEGIN
StdLog.Real( x ); StdLog.Ln;
StdLog.Int( i ); StdLog.Ln;
StdLog.String( a ); StdLog.Ln;
END ПростоПечать;
PROCEDURE Пример1*; (* вспомогательная интерфейсная процедура для ввода данных для Процедура *)
VAR x: REAL; i: INTEGER; a: ARRAY 1000 OF CHAR;
BEGIN
In.Open; (* открываем входной поток *)
ASSERT( In.Done ); (* проверяем, что все нормально *)
In.Real( x ); ASSERT( In.Done ); (* читаем значение для x; проверяем *)
In.Int( i ); ASSERT( In.Done );
In.String( a ); ASSERT( In.Done );
ПростоПечать( x, i, a ) (* вызываем тестируемую процедуру с нужными параметрами *)
END Пример1;
END i21примIn.
При клике по черному коммандеру будут считаны данные, отмеченные синим:
i21примIn.Пример1 3.14 2002 "цепочка литер"
Черный треугольник закрывает поток ввода, он вставляется посредством Ctrl+Shift+Q
Результаты (копия считанных данных) можно видеть в рабочем журнале.
Можно данные менять и снова кликать по левому коммандеру.
Если цепочка литер не содержит пробелов и других специальных символов, то можно опустить кавычки., например: 2.718 2008 информатика -- выделить синий текст мышкой, кликнуть по коммандеру выше -- и посмотреть в Рабочем журнале, что вышло.
| i21прим/Mod/In with global done.odc |
MODULE i21примIn;
(* Примеры передачи входных параметров в процедуру с помощью средств модуля i21sysIn. *)
IMPORT StdLog, In := i21eduIn; (* конструкция In := ... вводит сокращенное имя In для использования в данном модуле; длинные имена модулей встречаются нередко, для них удобно вводить короткие псевдонимы *)
PROCEDURE ПростоПечать ( x: REAL; i: INTEGER; a: ARRAY OF CHAR ); (* эту процедуру нельзя вызвать с помощью коммандера *)
BEGIN
StdLog.Real( x ); StdLog.Ln;
StdLog.Int( i ); StdLog.Ln;
StdLog.String( a ); StdLog.Ln;
END ПростоПечать;
PROCEDURE Пример1*; (* вспомогательная интерфейсная процедура для ввода данных для Процедура *)
VAR done: BOOLEAN; x: REAL; i: INTEGER; a: ARRAY 1000 OF CHAR;
BEGIN
In.Open( done ); (* открываем входной поток *)
ASSERT( done ); (* проверяем, что все нормально *)
In.Real( x, done ); ASSERT( done ); (* читаем значение для x; проверяем *)
In.Int( i, done ); ASSERT( done );
In.String( a, done ); ASSERT( done );
ПростоПечать( x, i, a ) (* вызываем тестируемую процедуру с нужными параметрами *)
END Пример1;
END i21примIn.
При клике по черному коммандеру будут считаны данные, отмеченные синим:
i21примIn.Пример1 3.14 2014 "цепочка литер"
Черный треугольник закрывает поток ввода, он вставляется посредством Ctrl+Shift+Q
Результаты (копия считанных данных) можно видеть в рабочем журнале.
Можно данные менять и снова кликать по левому коммандеру.
Если цепочка литер не содержит пробелов и других специальных символов, то можно опустить кавычки., например: 2.718 2022 информатика -- выделить синий текст мышкой, кликнуть по коммандеру выше -- и посмотреть в Рабочем журнале, что вышло.
| i21прим/Mod/In.odc |
MODULE i21примRandom;
IMPORT Log := StdLog, Ran := i21eduRandom;
PROCEDURE Do*;
VAR i, N: INTEGER; s, x: REAL;
BEGIN
(* печатаем несколько случайных целых чисел из диапазона 0..9 *)
FOR i := 1 TO 10 DO
Log.Int( Ran.Int( 10 ) ); Log.Ln
END;
Log.Ln;
(* печатаем несколько случайных вещественных чисел из сегмента 0..1 *)
FOR i := 1 TO 10 DO
Log.Real( Ran.Real() ); Log.Ln
END;
Log.Ln;
(* вычисляем интеграл функции 3*x*x от 0 до 1 методом Монте Карло *)
N := 1000000;
s := 0;
FOR i := 1 TO N DO
x := Ran.Real();
s := s + 3*x*x
END;
s := s / N;
(* должно получиться примерно 1: *)
Log.Real( s ); Log.Ln;
Log.Ln;
(* чтобы последовательность чисел можно было воспроизвести, нужно вначале сделать специальный вызов *)
Ran.InitSeed( 99 ); (* аргумент любое целое значение, от его выбора зависит конкретная получающаяся последовательность *)
FOR i := 1 TO 10 DO
Log.Int( Ran.Int( 10 ) ); Log.Ln
END;
Log.Ln;
END Do;
END i21примRandom.
Для выполнения примера кликнуть по черному коммандеру:
i21примRandom.Do
| i21прим/Mod/Random.odc |
MODULE i21примStdLog;
IMPORT Math,
Log := StdLog; (* Можно вводить сокращенный псеводним для любого импортируемого модуля (у них нередко длинные имена). Тогда вместо полного имени нужно указывать псевдоним во всех обращениях к нему в данном модуле.
Чтобы открыть описание модуля StdLog, нужно дважды кликнуть по имени и вызвать команду меню Инфо, Документация *)
PROCEDURE Делать*; (* звездочка после имени нужна, чтобы сделать процедуру видимой извне данного модуля -- иначе ее не выполнить с помощью коммандера или меню *)
VAR i: INTEGER; x: REAL;
a, b, c: ARRAY 10 OF CHAR;
s: SET;
BEGIN
Log.Ln; (* переход на новую строчку *)
Log.Char("'"); (* печать одной литеры -- одиночной кавычки *)
Log.Real( Math.Pi() ); (* печать вещественного числа *)
Log.Char("'");
Log.Ln;
Log.String("Блэкбокс'"); (* печать цепочки литер *)
Log.Ln;
Log.Tab; (* символ табуляции *)
Log.Char( 201CX ); Log.Char( 201DX ); (* пара кавычек -- литеры можно задавать в 16-ричном виде *)
Log.Ln
END Делать;
END i21примStdLog.
Для выполнения примера кликнуть по черному коммандеру:
i21примStdLog.Делать | i21прим/Mod/StdLog.odc |
MODULE i21примStrings;
(* Сначала напоминание:
Целое значение например, 1 может храниться в переменной любого целого типа INTEGER, SHORTINT, BYTE, LONGINT. Но если целое слишком большое, то оно может храниться только в достаточно "больших" типах. Например, значение 200 не может храниться в BYTE; для этого значения нужен по меньшей мере SHORTINT.
Аналогично цепочки литер:
Для цепочки литер нужен ARRAY OF CHAR достаточной длины. Причем длина ARRAY должен быть на единицу больше, чем кол-во литер в цепочке.
Дело в том, что конец цепочки отмечается спецлитерой 0X (нулевая позиция в кодовой таблице; это значение можно изобразить в программе и как 00Х; именно так его печатает процедура StdLog.Char(...)).
Для ясности: 0X или 00X это специальное значение, которое может храниться в переменных типа CHAR; на уровне машинного представления это означает, что все биты, составляющие переменную CHAR, равны нулю.
Если a: ARRAY OF CHAR, то обращение к значению т.е. литерной цепочке обозначается суффиксом $: a$.
В качестве литер можно брать любые символы таблицы Уникод.
Аналогично можно работать с цепочками SHORTCHAR (расширенный ASCII).
*)
IMPORT Log := StdLog;
PROCEDURE Показать* ( comment: ARRAY OF CHAR; IN s: ARRAY OF CHAR );
VAR i: INTEGER;
BEGIN
Log.String( comment ); Log.Ln;
Log.String("длина массива: "); Log.Int( LEN( s ) ); Log.Ln;
Log.String("длина цепочки литер в массиве: "); Log.Int( LEN( s$ ) ); Log.Ln; (* кол-во литер до первой спецлитеры 0X *)
(* сначала напечатаем цепочку: *)
Log.String("цепочка литер: "); Log.String( s ); Log.Ln;
(* теперь все элементы массива по отдельности: *)
Log.String("все элементы массива: ");
FOR i := 0 TO LEN( s ) - 1 DO
Log.Char( s[i] ); Log.Char(' ')
END;
Log.Ln; Log.Ln
END Показать;
PROCEDURE Демо0*;
VAR a: ARRAY 20 OF CHAR; p: POINTER TO ARRAY OF CHAR; c: CHAR;
BEGIN
(* при входе в процедуру в массиве a хранится "мусор" какие-то случайные значения: *)
Показать( "до присваивания мусор:", a );
(* присвоим значение цепочку литер: *)
a := 'Школа "Лидер"'; Показать( "после присваивания:", a );
(* искусственно "оборвем" цепочку, вставив в ее середину спецлитеру, обозначающую конец; предварительно сохраним заменяемую литеру во вспомогательной переменной c: *)
c := a[5];
a[5] := 0X; Показать( "после обрыва:", a );
(* восстановим символ: *)
a[5] := c; Показать( "восстановили цепочку:", a );
(* разместим новый массив: *)
NEW( p, 15 );
(* Мы говорили, что при входе в процедуру массивы, объявленные как локальные переменные процедуры, могут хранить "мусор" случайные значения. Однако массив, размещенный с помощью NEW, сразу после размещения всегда содержит одни нули (числа 0 для массивов целых типов и значения 0X для массивов литер). Это правило Компонентного Паскаля, введенное из соображений безопасности при работе в многопрограммных системах (чтобы нельзя было прочесть данные, оставленные в памяти компьютера другими программами).
Убедимся, что в размещенном таким образом массиве хранятся одни нули: *)
Показать( "после размещения с помощью NEW в массиве одни нули:", p );
(* запишем во вновь размещенный массив цепочку литер: *)
p^ := a$; Показать( "после присваивания:", p );
(* после идентификатора нужна шапочка, т.к. мы хотим присвоить что-то не указателю, а той переменной (в данном случае массиву), на которую указатель указывает *)
p^ := "слишком длинная цепочка вызывает облом"
END Демо0;
END i21примStrings.
Для выполнения примера кликнуть по черному коммандеру:
i21примStrings.Демо0 | i21прим/Mod/Strings.odc |
MODULE i21примTPGraphics;
(* 2014 ФВТ обновление.
2003 ФВТ для проекта Информатика-21; предложение Л.Г.Куркиной и А.И.Попкова.
Коммандеры для вызова процедур в конце этого документа. *)
IMPORT Gr := i21eduTPGraphics, Ports, In := i21sysIn, Log := StdLog;
PROCEDURE Do*;
VAR i, j: INTEGER;
BEGIN
Gr.SetBkColor( 5 ); (* Цифровые коды для цветов сделаны только для облегчения переноса готовых примеров с ТП. Для новых программ можно использовать прямые присваивания вроде: *)
Gr.color := Gr.white; (* вместо Gr.SetColor( 15 ) *)
(* или *)
Gr.color := Ports.RGBColor( 255, 255, 255 ); (* смесь красного, зеленого и синего, от 0 до 255 каждый *)
Gr.Line( 25, 77, 100, 200 );
Gr.SetColor( 10 );
Gr.Rectangle( 250, 250, 400, 400 );
Gr.SetColor( 7 );
Gr.Bar( 200, 300, 600, 700 );
Gr.MoveTo( 600, 50 );
Gr.LineTo( 500, 5 );
Gr.SetColor( 12 );
Gr.LineTo( 0, 500 );
Gr.SetColor( 13 );
Gr.LineTo( 500, 300 );
Gr.SetColor( 9 );
Gr.Circle( 400, 400, 100 );
Gr.color := Gr.white;
FOR j := 0 TO 30 DO
FOR i := 0 TO 100 BY 3 DO
Gr.PutPixel( 200 + i + j, 10 + j )
END;
END;
Gr.SetFillColor( 4 );
Gr.FillEllipse( 200, 200, 50, 70 );
Gr.color := Ports.red;
Gr.Arc( 200, 210, -45, 90, 60 );
Gr.color := Ports.RGBColor( 255, 255, 0 ); (* желтый *)
Gr.Ellipse( 300, 310, -180, 150, 160, 260 );
Gr.color := Gr.white;
Gr.SetFont( "Verdana", 18, FALSE, TRUE );
Gr.String( 100, 100, "Привет любителям программирования!" );
Gr.color := Gr.yellow;
Gr.SetFont( "Arial", 30, TRUE, FALSE );
Gr.String( 100, 250, "Привет любителям программирования!" );
END Do;
PROCEDURE Добавить*;
VAR x, y, rad: INTEGER;
BEGIN
In.Open;
In.Int( x );
WHILE In.Done DO
In.Int( y ); ASSERT( In.Done );
In.Int( rad ); ASSERT( In.Done & ( rad > 0 ) );
Gr.Circle( x, y, rad );
In.Int( x )
END;
END Добавить;
(*
PROCEDURE Ещё*;
VAR x, y: INTEGER;
BEGIN
x := 300; y := 300;
Gr.SetColor(4);
Gr.Circle( x, y, 100 );
Gr.Circle( x, y, 101 );
Gr.Circle( x, y, 102 );
Gr.Circle( x, y, 105 );
Gr.Circle( x, y, 106 );
Gr.Circle( x, y, 107 );
END Ещё;
*)
END i21примTPGraphics.
Чтобы открыть окошко, где рисуется картинка, кликнуть здесь:
"i21eduTPGraphics.Open;i21sysWindows.AlignTopRight"
Можно в любой момент закрыть картинку, и через какое-то время снова ее открыть.
Все, что было добавлено в картинку, пока она была закрыта, будет правильно показано во вновь открытой картинке.
Эту команду можно вставить и в свою программу.
Следующая команда добавляет в картинку сразу много элементов, как прописано в процедуре Do:
i21примTPGraphics.Do
Можно создать сколько угодно новых процедур в этом модуле, которые будут дорисовывать что-нибудь в картинку, и вызывать их(картинкой "владеет" другой модуль, который помнит, что в ней было нарисовано, и ему всё равно, какие модули вызывают его процедуры для дорисовывания в картинку).
Например, можно убрать комментарии вокруг процедуры Ещё (она стоит в конце модуля и покрашена красным), скомпилировать (Ctrl+K) и, прижав Ctrl, кликнуть по коммандеру:
i21примTPGraphics.Ещё
Или просто менять Do в этом модуле (только для вызова обновленной процедуры не забывать нажимать Ctrl при клике по коммандеру).
Можно добавлять элементы в картинку и так:
"i21eduTPGraphics.SetColor(1);i21примTPGraphics.Добавить"
0 0 40
20 20 40
40 40 40
60 60 40
80 80 40
60 60 40
Можно порисовать и так:
"i21eduTPGraphics.LineTo(70,30)"
"i21eduTPGraphics.LineTo(70,300)"
"i21eduTPGraphics.LineTo(100,200)"
Однако с помощью коммандеров можно вызывать далеко не все команды рисования-- но их всегда можно упаковать в новые процедуры, которые и будут вызываться.
Очистить картинку:
i21eduTPGraphics.Clear
| i21прим/Mod/TPGraphics.odc |
MODULE i21примВставки;
IMPORT StdLog, In := i21sysIn;
PROCEDURE Вставить ( VAR a: ARRAY OF INTEGER; i: INTEGER );
VAR t: INTEGER;
BEGIN
IF a[i] < a[i-1] THEN
t := a[i]; a[i] := a[i-1]; a[i-1] := t;
IF i - 1 # 0 THEN
Вставить( a, i - 1 )
END;
END;
END Вставить;
PROCEDURE Сорт* ( VAR a: ARRAY OF INTEGER );
VAR i: INTEGER;
BEGIN
FOR i := 1 TO LEN(a) - 1 DO
Вставить( a, i )
END;
END Сорт;
PROCEDURE Демо*;
VAR x, n: INTEGER; a: POINTER TO ARRAY OF INTEGER;
BEGIN In.Open; n := 0; In.Int( x );
WHILE In.Done DO
INC( n ); In.Int( x )
END;
NEW( a, n );
In.Open; n := 0; In.Int( x );
WHILE In.Done DO
a[n] := x; INC( n ); In.Int( x )
END;
Сорт( a );
FOR n := 0 TO LEN(a) - 1 DO
StdLog.Int( a[n] )
END;
END Демо;
END i21примВставки.
Для выполнения процедуры кликнуть по черному круглому коммандеру:
i21примВставки.Демо 2 0 90 11 -4 8
| i21прим/Mod/Вставки.odc |
MODULE i21примПростые;
IMPORT Math;
PROCEDURE Простое* ( n: INTEGER ): BOOLEAN;
VAR кандидат: INTEGER; корень: REAL;
BEGIN
кандидат := 2;
корень := Math.Sqrt( n );
WHILE (кандидат <= корень) & ~( (n MOD кандидат) = 0 ) DO
кандидат := кандидат + 1
END;
RETURN ~(кандидат <= корень)
END Простое;
END i21примПростые. | i21прим/Mod/Простые.odc |
МОДУЛЬ i21примПростыеЧисла;
ПОДКЛЮЧИТЬ Вывод := i21eduВывод, Math;
ПРОЦЕДУРА НеДелит ( i, n: ЦЕЛАЯ ): ЛОГИЧЕСКОЕ;
НАЧАЛО
ВЕРНУТЬ ( n MOD i ) # 0
КОНЕЦ НеДелит;
ПРОЦЕДУРА Простое* ( n: ЦЕЛАЯ ): ЛОГИЧЕСКОЕ;
ПЕРЕМЕННЫЕ i, мин, макс: ЦЕЛАЯ;
НАЧАЛО
(* проверка разрешенного значения параметра на входе *)
УБЕДИТЬСЯ( n > 1, 20 );
(* диапазон потенциальных делителей *)
мин := 2;
макс := SHORT( ENTIER( Math.Sqrt( n ) ) );
(* цикл поиска наименьшего делителя *)
i := мин;
ПОКА ( i <= макс ) & НеДелит( i, n ) DO
INC( i )
КОНЕЦ;
ВЕРНУТЬ i > макс (* прошли все возможности -- делителя не нашли *)
КОНЕЦ Простое;
ПРОЦЕДУРА КоличПростыхДо* ( n: ЦЕЛАЯ ): ЦЕЛАЯ;
ПЕРЕМЕННЫЕ i, k: ЦЕЛЫЕ;
НАЧАЛО
k := 0;
ДЛЯ i := 2 TO n - 1 DO
ЕСЛИ Простое( i ) ТО
INC( k )
КОНЕЦ
КОНЕЦ;
ВЕРНУТЬ k
КОНЕЦ КоличПростыхДо;
ПРОЦЕДУРА Показать* ( n: ЦЕЛАЯ );
НАЧАЛО
Вывод.НовСтрока; Вывод.Цепочка("Число "); Вывод.Цел( n );
ЕСЛИ ~Простое( n ) ТО
Вывод.Цепочка(" не")
КОНЕЦ;
Вывод.Цепочка(" является простым."); Вывод.НовСтрока;
Вывод.Цел( КоличПростыхДо( n ) );
Вывод.Цепочка(" простых, меньших ");
Вывод.Цел( n );
Вывод.НовСтрока
КОНЕЦ Показать;
КОНЕЦ i21примПростыеЧисла.
Для выполнения процедуры кликнуть по черному коммандеру:
"i21примПростыеЧисла.Показать(1791)"
| i21прим/Mod/ПростыеЧисла(Ру).odc |
MODULE i21примПростыеЧисла;
IMPORT Log := StdLog, Math;
PROCEDURE НеДелит ( i, n: INTEGER ): BOOLEAN;
BEGIN
RETURN ( n MOD i ) # 0
END НеДелит;
PROCEDURE Простое* ( n: INTEGER ): BOOLEAN;
VAR i, мин, макс: INTEGER;
BEGIN
(* проверка разрешенного значения параметра на входе *)
ASSERT( n > 1, 20 );
(* диапазон потенциальных делителей *)
мин := 2;
макс := SHORT( ENTIER( Math.Sqrt( n ) ) );
(* цикл поиска наименьшего делителя *)
i := мин;
WHILE ( i <= макс ) & НеДелит( i, n ) DO
INC( i )
END;
RETURN i > макс (* прошли все возможности -- делителя не нашли *)
END Простое;
PROCEDURE КоличПростыхДо* ( n: INTEGER ): INTEGER;
VAR i, k: INTEGER;
BEGIN
k := 0;
FOR i := 2 TO n - 1 DO
IF Простое( i ) THEN
INC( k )
END
END;
RETURN k
END КоличПростыхДо;
PROCEDURE Показать* ( n: INTEGER );
BEGIN
Log.Ln; Log.String("Число "); Log.Int( n );
IF ~Простое( n ) THEN
Log.String(" не")
END;
Log.String(" является простым."); Log.Ln;
Log.Int( КоличПростыхДо( n ) ); Log.String(" простых, меньших "); Log.Int( n ); Log.Ln
END Показать;
END i21примПростыеЧисла.
Для выполнения процедуры кликнуть по чёрному коммандеру:
"i21примПростыеЧисла.Показать(1791)"
| i21прим/Mod/ПростыеЧисла.odc |
MODULE i21примСортДемо1;
IMPORT StdLog, Модуль := i21примВставки, Тест := i21примСортТест;
PROCEDURE Выполнить*;
CONST L = 5;
VAR n: INTEGER; a: ARRAY L OF INTEGER;
BEGIN
(* инициализация массива *)
a[0] := 9;
a[1] := -2;
a[2] := 19;
a[3] := -6;
a[4] := 1;
(* печать массива до сортировки *)
StdLog.Ln; StdLog.String("до сортировки: ");
FOR n := 0 TO L - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
Модуль.Сорт( a ); (* это сортировка *)
ASSERT( Тест.Отсортирован( a ) ); (* автоматическая проверка результата *)
(* печать массива после сортировки *)
StdLog.Ln; StdLog.String("после сортировки: ");
FOR n := 0 TO L - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
END Выполнить;
END i21примСортДемо1.
Чтобы выполнить тест, нужно кликнуть по коммандеру (черный кружок):
i21примСортДемо1.Выполнить
Если хочется поменять числа, то нужно их поменять прямо в тексте,
а потом кликнуть по коммандеру здесь:
"DevCompiler.Compile;DevDebug.Unload;i21примСортДемо1.Выполнить"
Точно так же можно поменять модуль, содержащий проверяемую программу сортировки: достаточно изменить i21примВставки в операторе IMPORT на i21примПузырь.
Внимание! Так как процедуры сортировки и проверяющие программы реализованы в разных модулях, могут возникнуть проблемы (вызывается старая версия сортировки, когда уже написана и успешно скомпилирована новая). О том, что делать в таких случаях, см. здесь. | i21прим/Mod/СортДемо1.odc |
MODULE i21примСортДемо1;
IMPORT StdLog, Модуль := i21примВставки, Тест := i21примСортТест;
PROCEDURE Выполнить*;
CONST L = 5;
VAR n: INTEGER; a: ARRAY L OF INTEGER;
BEGIN
(* инициализация массива *)
a[0] := 9;
a[1] := -2;
a[2] := 19;
a[3] := -6;
a[4] := 1;
(* печать массива до сортировки *)
StdLog.Ln; StdLog.String("до сортировки: ");
FOR n := 0 TO L - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
Модуль.Сорт( a ); (* это сортировка *)
ASSERT( Тест.Отсортирован( a ) ); (* автоматическая проверка результата *)
(* печать массива после сортировки *)
StdLog.Ln; StdLog.String("после сортировки: ");
FOR n := 0 TO L - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
END Выполнить;
END i21примСортДемо1.
Чтобы выполнить тест, нужно кликнуть по коммандеру (черный кружок):
i21примСортДемо1.Выполнить
Если хочется поменять числа, то нужно их поменять прямо в тексте,
а потом кликнуть по коммандеру здесь:
"DevCompiler.Compile;DevDebug.Unload;i21примСортДемо1.Выполнить"
Точно так же можно поменять модуль, содержащий проверяемую программу сортировки: достаточно изменить i21примВставки в операторе IMPORT на i21примПузырь.
Внимание! Так как процедуры сортировки и проверяющие программы реализованы в разных модулях, могут возникнуть проблемы (вызывается старая версия сортировки, когда уже написана и успешно скомпилирована новая). О том, что делать в таких случаях, см. здесь. | i21прим/Mod/СортДемо1original.odc |
MODULE i21примСортДемо2;
IMPORT StdLog, In := i21sysIn, Модуль := i21примВставки, Тест := i21примСортТест;
PROCEDURE Выполнить*;
VAR x, n: INTEGER; a: POINTER TO ARRAY OF INTEGER;
BEGIN
(* подсчет количества сортируемых чисел *)
In.Open; n := 0; In.Int( x );
WHILE In.Done DO INC( n ); In.Int( x ) END;
IF n > 0 THEN
(* инициализация массива *)
NEW( a, n );
In.Open; n := 0; In.Int( x );
WHILE In.Done DO a[n] := x; INC( n ); In.Int( x ) END;
(* печать до сортировки *)
StdLog.Ln; StdLog.String('до сортировки: ');
FOR n := 0 TO LEN(a) - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
Модуль.Сорт( a ); (* это сортировка *)
ASSERT( Тест.Отсортирован( a ) ); (* автоматическая проверка результата *)
(* печать после сортировки *)
StdLog.Ln; StdLog.String('после сортировки: ');
FOR n := 0 TO LEN(a) - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
END
END Выполнить;
END i21примСортДемо2.
Чтобы выполнить тест, нужно кликнуть по коммандеру (черному кружку с восклицат. знаком).
Программа прочтет все числа после Выполнить и до второго коммандера отсортирует их и распечатает в рабочем журнале.
i21примСортДемо2.Выполнить 2 0 90 -111 151 -4 8
Можно призвольно менять последовательность чисел стирать, добавлять новые (в любом количестве) и т.п.
Можно поменять модуль, содержащий проверяемую программу сортировки: достаточно изменить i21примВставки в операторе IMPORT на i21примПузырь. После этого нужно клюкнуть по следующему коммандеру:
"DevCompiler.Compile;DevDebug.Unload;i21примСортДемо1.Выполнить"
Внимание! Так как процедура сортировки и проверяющие программы реализованы в разных модулях, могут возникнуть проблемы (вызывается старая версия сортировки, когда уже написана и успешно скомпилирована новая). О том, что делать в таких случаях, см. здесь. | i21прим/Mod/СортДемо2.odc |
MODULE i21примСортДемо2;
IMPORT StdLog, In := i21sysIn, Модуль := i21примВставки, Тест := i21примСортТест;
PROCEDURE Выполнить*;
VAR x, n: INTEGER; a: POINTER TO ARRAY OF INTEGER;
BEGIN
(* подсчет количества сортируемых чисел *)
In.Open; n := 0; In.Int( x );
WHILE In.Done DO INC( n ); In.Int( x ) END;
IF n > 0 THEN
(* инициализация массива *)
NEW( a, n );
In.Open; n := 0; In.Int( x );
WHILE In.Done DO a[n] := x; INC( n ); In.Int( x ) END;
(* печать до сортировки *)
StdLog.Ln; StdLog.String('до сортировки: ');
FOR n := 0 TO LEN(a) - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
Модуль.Сорт( a ); (* это сортировка *)
ASSERT( Тест.Отсортирован( a ) ); (* автоматическая проверка результата *)
(* печать после сортировки *)
StdLog.Ln; StdLog.String('после сортировки: ');
FOR n := 0 TO LEN(a) - 1 DO StdLog.Int( a[n] ) END;
StdLog.Ln;
END
END Выполнить;
END i21примСортДемо2.
Чтобы выполнить тест, нужно мышкой отметить первое из сортируемых чисел (не обязательно 2 можно отметить, например, и 90),
а затем кликнуть по коммандеру (черному кружку с восклицат. знаком).
Программа прочтет все числа, начиная с отмеченного и до , отсортирует их и распечатает в рабочем журнале.
i21примСортДемо2.Выполнить 2 0 90 -111 11 -4 8
Можно призвольно менять последовательность чисел стирать, добавлять новые (в любом количестве) и т.п.
Если после клюка ничего не происходит, то возможно Вы забыли отметить числа.
Можно поменять модуль, содержащий проверяемую программу сортировки: достаточно изменить i21примВставки в операторе IMPORT на i21примПузырь. После этого нужно клюкнуть по следующему коммандеру:
"DevCompiler.Compile;DevDebug.Unload;i21примСортДемо1.Выполнить"
Внимание! Так как процедура сортировки и проверяющие программы реализованы в разных модулях, могут возникнуть проблемы (вызывается старая версия сортировки, когда уже написана и успешно скомпилирована новая). О том, что делать в таких случаях, см. здесь. | i21прим/Mod/СортДемо2original.odc |
MODULE i21примСортТест;
PROCEDURE Отсортирован* ( IN м: ARRAY OF INTEGER ): BOOLEAN;
VAR результат: BOOLEAN; i: INTEGER;
BEGIN
результат := TRUE;
FOR i := 1 TO LEN( м ) - 1 DO
результат := результат & ( м[i-1] <= м[i] )
END;
RETURN результат
END Отсортирован;
END i21примСортТест.
| i21прим/Mod/СортТест.odc |
(* кликнуть по круглому коммандеру, чтобы начать:
i21примТетрис.НоваяИгра
Esc -- начать/пауза/продолжить.
Стрелочки -- вертеть, двигать падающую фигуру.
Пробел -- сбросить падающую фигуру.
*)
(* From [email protected] Sat Aug 9 08:29:34 2003
Date: Sat, 9 Aug 2003 07:29:29 +0300
From: Ketmar <[email protected]>
To: info21 <[email protected]>
Subject: tetris
Hello, info21.
Here's the promised tetris. it seems to be ok. excuse me my ugly code %-)
*)
(**
National russian game "Tetris"
Original idea by Alexey Pajitnov
Programmed in JOB by S.Sverdlov, 8.03.98/23.04.98
Ported to BlackBox by Ketmar // Piranha, 22-Aug-XXXVIII A.S.
game can be saved & loaded later
todo:
[?] revrite using models? (а зачем? это делают, чтобы по-разному изображать одни и те же данные. --info21)
*)
(* Модификации info21 2008-06-03: переименования, форматирование. *)
(* Модификации info21 2003-09-22:
Изменено имя модуля.
В процедуре HandleCtrlMsg поставлен CASE вместо IF в обработке клавиш и добавлены другие варианты клавиш.
*)
MODULE i21примТетрис;
IMPORT Dates, Services, Ports, Models, Views, Properties, Controllers, Stores;
CONST
(** random number generator *)
(** taken from Project Pbox by J. Stanley Warford *)
multiplier = 48271;
modulus = 2147483647;
quotient = modulus DIV multiplier;
remainder = modulus MOD multiplier;
seedLimit = modulus;
(** конец взятия *)
speed = Services.resolution DIV 2; (* 1 second *)
n = 24; (* высота стакана *)
m = 12; (* ширина стакана *)
s = 6 * Ports.mm; (*размер одного кубика фигуры *)
TYPE
Field = ARRAY n, m OF Ports.Color;
Figure = ARRAY 4, 4 OF BOOLEAN;
Figures = ARRAY 7 OF Figure;
Colors = ARRAY 7 OF Ports.Color;
GameView = POINTER TO RECORD (Views.View)
field: Field; (* стакан *)
figs: Figures; (* всевозможные фигуры *)
bc: Ports.Color; (* цвет фона *)
cols: Colors; (* цвета фигур? *)
ncurr: INTEGER; (* текущая фигура? *)
curr: Figure; (* текущая фигура? *)
x, y: INTEGER; (* координаты текущей фигуры в стакане *)
(*rand : ut.PRandom;*)
seed: INTEGER; (* "зерно" для бре... для генератора случайных чисел *)
fly: BOOLEAN; (* фигура в полёте? *)
paused: BOOLEAN; (* ждём-с? *)
prevTick: LONGINT; (* время прошлого tick-сообщения *)
END;
(** taken from Project Pbox by J. Stanley Warford *)
PROCEDURE ComputeNextSeed (VAR seed: INTEGER);
VAR low, high: INTEGER;
BEGIN
low := seed MOD quotient;
high := seed DIV quotient;
seed := multiplier * low - remainder * high;
IF seed <= 0 THEN seed := seed + modulus; END;
END ComputeNextSeed;
PROCEDURE RndInt (VAR seed: INTEGER; n: INTEGER): INTEGER;
BEGIN
ASSERT(0 < n, 20);
ASSERT(n < seedLimit, 21);
ComputeNextSeed (seed);
RETURN SHORT(ENTIER(seed / modulus * n));
END RndInt;
PROCEDURE Randomize (VAR seed: INTEGER);
VAR date: Dates.Date; time: Dates.Time; i: INTEGER;
BEGIN
Dates.GetDate(date); Dates.GetTime(time);
seed := 86400 * Dates.Day(date) + 3600 * time.hour + 60 * time.minute + time.second; (* Elapsed time this year in seconds *)
FOR i := 0 TO 7 DO ComputeNextSeed(seed); END;
END Randomize;
(** конец взятия *)
PROCEDURE WriteFigure (VAR wr: Stores.Writer; IN fig: Figure);
VAR f, c: INTEGER;
BEGIN
FOR f := 0 TO 3 DO
FOR c := 0 TO 3 DO
wr.WriteBool(fig[f, c]);
END;
END;
END WriteFigure;
PROCEDURE ReadFigure (VAR rd: Stores.Reader; OUT fig: Figure);
VAR f, c: INTEGER;
BEGIN
FOR f := 0 TO 3 DO
FOR c := 0 TO 3 DO
rd.ReadBool(fig[f, c]);
END;
END;
END ReadFigure;
PROCEDURE (v: GameView) Internalize- (VAR rd: Stores.Reader);
VAR f, c, ver: INTEGER;
BEGIN
IF ~rd.cancelled THEN
rd.ReadVersion(0, 0, ver);
IF ~rd.cancelled THEN
rd.ReadInt(v.bc);
rd.ReadInt(v.ncurr);
rd.ReadInt(v.x);
rd.ReadInt(v.y);
rd.ReadInt(v.seed);
rd.ReadBool(v.fly);
FOR f := 0 TO 6 DO rd.ReadInt(v.cols[f]); END;
FOR f := 0 TO 6 DO ReadFigure(rd, v.figs[f]); END;
ReadFigure(rd, v.curr);
FOR f := 0 TO n-1 DO
FOR c := 0 TO m-1 DO
rd.ReadInt(v.field[f, c]);
END;
END;
v.paused := TRUE;
END;
END;
END Internalize;
PROCEDURE (v: GameView) Externalize- (VAR wr: Stores.Writer);
VAR f, c: INTEGER;
BEGIN
wr.WriteVersion(0);
wr.WriteInt(v.bc);
wr.WriteInt(v.ncurr);
wr.WriteInt(v.x);
wr.WriteInt(v.y);
wr.WriteInt(v.seed);
wr.WriteBool(v.fly);
FOR f := 0 TO 6 DO wr.WriteInt(v.cols[f]); END;
FOR f := 0 TO 6 DO WriteFigure(wr, v.figs[f]); END;
WriteFigure(wr, v.curr);
FOR f := 0 TO n-1 DO
FOR c := 0 TO m-1 DO
wr.WriteInt(v.field[f, c]);
END;
END;
END Externalize;
PROCEDURE (v: GameView) CopyFromSimpleView- (source: Views.View);
BEGIN
WITH source: GameView DO
v.field := source.field;
v.figs := source.figs;
v.bc := source.bc;
v.cols := source.cols;
v.ncurr := source.ncurr;
v.curr := source.curr;
v.x := source.x;
v.y := source.y;
v.seed := source.seed;
v.fly := source.fly;
v.paused := TRUE;
END;
END CopyFromSimpleView;
(*********************************************)
PROCEDURE DrawFigure (f: Views.Frame; x0, y: INTEGER; IN fig: Figure; col: Ports.Color);
VAR i, j: INTEGER; x: INTEGER;
BEGIN
FOR i := 0 TO 3 DO
x := x0;
FOR j := 0 TO 3 DO
IF fig[i, j] & (0 <= x) & (x < m) & (0 <= y) & (y < n) THEN
f.DrawRect(x*(s+1), y*(s+1), x*(s+1)+s, y*(s+1)+s, Ports.fill, col);
END;
INC(x);
END;
INC(y);
END;
END DrawFigure;
PROCEDURE (v: GameView) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
(*: намалевать стакан *)
VAR i, j: INTEGER; x, y: INTEGER;
BEGIN
y := 0;
FOR i := 0 TO n - 1 DO
x := 0;
FOR j := 0 TO m - 1 DO
f.DrawRect(x, y, x+s, y+s, Ports.fill, v.field[i, j]);
IF ~v.paused THEN f.DrawRect(x+s DIV 2-Ports.mm, y+s DIV 2-Ports.mm, x+s DIV 2, y+s DIV 2, Ports.fill, Ports.red); END;
INC(x, s+1);
END;
INC(y, s+1);
END;
IF v.fly THEN DrawFigure(f, v.x, v.y, v.curr, v.cols[v.ncurr]); END;
END Restore;
PROCEDURE (v: GameView) InitField (), NEW;
(*: очистить стакан *)
VAR i, j: INTEGER;
BEGIN
FOR i := 0 TO n - 1 DO
FOR j := 0 TO m - 1 DO
v.field[i, j] := v.bc;
END;
END;
END InitField;
PROCEDURE (v: GameView) Free (IN f: Figure; x0, y0: INTEGER): BOOLEAN, NEW;
(*: проверить, свободно ли место для фигуры *)
VAR i, j: INTEGER; x, y: INTEGER; F: BOOLEAN;
BEGIN
F := TRUE;
i := 0;
y := y0;
REPEAT
j := 0;
x := x0;
REPEAT
IF f[i, j] & ((x < 0) OR (x >= m) OR (y >= n) OR (y >= 0) & (v.field[y, x] # v.bc)) THEN F := FALSE; END;
INC(j);
INC(x);
UNTIL ~F OR (j = 4);
INC(i);
INC(y);
UNTIL ~F OR (i = 4);
RETURN F;
END Free;
PROCEDURE (v: GameView) Move (dx, dy: INTEGER), NEW;
(*: стереть фигуру на старом месте, сдвинуть на dx и dy, нарисовать на новом *)
BEGIN
INC(v.x, dx);
INC(v.y, dy);
END Move;
PROCEDURE (v: GameView) Fix (), NEW;
(*: "прописать" фигуру в стакане *)
VAR i, j: INTEGER; x, y: INTEGER;
BEGIN
y := v.y;
FOR i := 0 TO 3 DO
x := v.x;
FOR j := 0 TO 3 DO
IF v.curr[i, j] & (0 <= x) & (x < m) & (0 <= y) & (y < n) THEN
v.field[y, x] := v.cols[v.ncurr];
END;
INC(x);
END;
INC(y);
END;
END Fix;
PROCEDURE (v: GameView) RowEmpty (r: INTEGER): BOOLEAN, NEW;
(*: пуста ли строка? *)
VAR e: BOOLEAN; j: INTEGER;
BEGIN
j := m;
REPEAT
DEC(j);
e := (v.field[r, j] = v.bc);
UNTIL (j = 0) OR ~e;
RETURN e;
END RowEmpty;
PROCEDURE (v: GameView) ClearRow (r: INTEGER), NEW;
(*: убрать все пустые строки, перерисовать стакан *)
BEGIN
WHILE (r > 0) & ~v.RowEmpty(r) DO
v.field[r] := v.field[r - 1];
DEC(r);
END;
END ClearRow;
PROCEDURE (v: GameView) RowFull (r: INTEGER): BOOLEAN, NEW;
(*: полна ли строка? *)
VAR j: INTEGER; full: BOOLEAN;
BEGIN
j := m;
REPEAT
DEC(j);
full := (v.field[r, j] # v.bc);
UNTIL (j = 0) OR ~full;
RETURN full;
END RowFull;
PROCEDURE (v: GameView) TestRows (), NEW;
(*: убрать все заполненые строки *)
VAR i, j, r: INTEGER;
BEGIN
i := 3;
r := v.y + i;
REPEAT
IF (r < n) & (r >= 0) & v.RowFull(r) THEN
v.ClearRow(r);
ELSE
DEC(r);
END;
DEC(i);
UNTIL i < 0;
END TestRows;
PROCEDURE Rotate (f: Figure; OUT fr: Figure);
(*: создать "повернутую" фигуру *)
VAR i, j: INTEGER;
BEGIN
i := 0;
j := 3;
REPEAT
fr[i, 0] := f[0, j];
fr[3, i] := f[i, 0];
fr[j, 3] := f[3, i];
fr[0, i] := f[i, 3];
INC(i);
DEC(j);
UNTIL j < 0;
fr[1, 1] := f[1, 2];
fr[2, 1] := f[1, 1];
fr[2, 2] := f[2, 1];
fr[1, 2] := f[2, 2];
END Rotate;
PROCEDURE (v: GameView) FigRotate (), NEW;
(*: повернуть фигуру *)
VAR temp: Figure;
BEGIN
Rotate(v.curr, temp);
IF v.Free(temp, v.x, v.y) THEN
v.curr := temp;
Views.Update(v, Views.keepFrames);
END;
END FigRotate;
PROCEDURE (v: GameView) FigDown (), NEW;
(*: опустить фигуру вниз на строку *)
BEGIN
IF v.Free(v.curr, v.x, v.y+1) THEN v.Move(0, 1);
ELSE
v.fly := FALSE;
v.Fix();
v.TestRows();
END;
Views.Update(v, Views.keepFrames);
END FigDown;
PROCEDURE (v: GameView) FigRelease (), NEW;
(*: уронить фигуру *)
BEGIN
WHILE v.Free(v.curr, v.x, v.y+1) DO v.Move(0, 1); END;
(* v.fly := FALSE;
v.Fix();
v.TestRows();*)
Views.Update(v, Views.keepFrames);
END FigRelease;
PROCEDURE (v: GameView) FigRight (), NEW;
(*: фигуру вправо *)
BEGIN
IF v.Free(v.curr, v.x+1, v.y) THEN v.Move(1, 0); END;
Views.Update(v, Views.keepFrames);
END FigRight;
PROCEDURE (v: GameView) FigLeft (), NEW;
(*: фигуру влево *)
BEGIN
IF v.Free(v.curr, v.x-1, v.y) THEN v.Move(-1, 0); END;
Views.Update(v, Views.keepFrames);
END FigLeft;
PROCEDURE NewColor (r, g, b: INTEGER): Ports.Color;
(*: новый цвет из ргб *)
BEGIN
RETURN Ports.RGBColor(r, g, b);
END NewColor;
PROCEDURE (v: GameView) InitColors (), NEW;
(*: установить цвета для фигур по умолчанию *)
BEGIN
v.bc := NewColor(220, 220, 220);
v.cols[0] := NewColor(255, 0, 0);
v.cols[1] := NewColor(255, 128, 0);
v.cols[2] := NewColor(255, 255, 0);
v.cols[3] := NewColor(0, 255, 0);
v.cols[4] := NewColor(0, 255, 255);
v.cols[5] := NewColor(0, 0, 255);
v.cols[6] := NewColor(255, 0, 255);
END InitColors;
PROCEDURE (v: GameView) InitFigures (), NEW;
(*: проинициализировать массив фигур *)
VAR i, j, k: INTEGER;
BEGIN
FOR i := 0 TO 6 DO
FOR j := 0 TO 3 DO
FOR k := 0 TO 3 DO
v.figs[i, j, k] := FALSE;
END;
END;
END;
v.figs[0, 1, 0] := TRUE;
v.figs[0, 1, 1] := TRUE;
v.figs[0, 1, 2] := TRUE;
v.figs[0, 1, 3] := TRUE;
v.figs[1, 1, 2] := TRUE;
v.figs[1, 2, 0] := TRUE;
v.figs[1, 2, 1] := TRUE;
v.figs[1, 2, 2] := TRUE;
v.figs[2, 1, 0] := TRUE;
v.figs[2, 1, 1] := TRUE;
v.figs[2, 1, 2] := TRUE;
v.figs[2, 2, 2] := TRUE;
v.figs[3, 1, 1] := TRUE;
v.figs[3, 1, 2] := TRUE;
v.figs[3, 2, 1] := TRUE;
v.figs[3, 2, 2] := TRUE;
v.figs[4, 1, 0] := TRUE;
v.figs[4, 1, 1] := TRUE;
v.figs[4, 2, 1] := TRUE;
v.figs[4, 2, 2] := TRUE;
v.figs[5, 0, 1] := TRUE;
v.figs[5, 1, 1] := TRUE;
v.figs[5, 1, 2] := TRUE;
v.figs[5, 2, 2] := TRUE;
v.figs[6, 1, 0] := TRUE;
v.figs[6, 1, 1] := TRUE;
v.figs[6, 1, 2] := TRUE;
v.figs[6, 2, 1] := TRUE;
END InitFigures;
PROCEDURE (v: GameView) NewFigure (), NEW;
(*: новая фигурка *)
VAR rot: INTEGER;
BEGIN
v.x := m DIV 2 - 2;
v.y := - 2;
v.ncurr := RndInt(v.seed, 7);
v.curr := v.figs[v.ncurr];
rot := RndInt(v.seed, 4);
WHILE rot > 0 DO
Rotate(v.curr, v.curr);
DEC(rot);
END;
END NewFigure;
PROCEDURE (v: GameView) TimerStep (), NEW;
(*: тикалка *)
BEGIN
IF v.fly THEN v.FigDown();
ELSE
v.NewFigure();
IF v.Free(v.curr, v.x, v.y) THEN v.fly := TRUE;
ELSE v.paused := TRUE; v.InitField();
END;
Views.Update(v, Views.keepFrames);
END;
END TimerStep;
PROCEDURE (v: GameView) HandlePropMsg- (VAR msg: Properties.Message);
(*: установка начальных размеров окна *)
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := m*(s+1);
msg.h := n*(s+1);
END;
ELSE
END;
END HandlePropMsg;
(* PROCEDURE (v: GameView) HandleCtrlMsg- (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View);*)
PROCEDURE (v: GameView) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
(*: обработка клавиш и таймера *)
CONST
стрелкаВлево = 1CX;
стрелкаВправо = 1DX;
стрелкаВверх = 1EX;
стрелкаВниз = 1FX;
цифра4 = 34X;
цифра5 = 35X;
цифра6 = 36X;
пробел = 20X;
BEGIN
WITH
| msg: Controllers.EditMsg DO
IF ~v.paused THEN
IF msg.char = 1CX THEN v.FigLeft();
ELSIF msg.char = 1DX THEN v.FigRight();
ELSIF msg.char = 1EX THEN v.FigRotate();
ELSIF msg.char = 1FX THEN v.FigRelease();
END;
(* ketmar's code inside the fold *)
CASE msg.char OF
| стрелкаВлево, цифра4:
v.FigLeft()
| стрелкаВправо, цифра6:
v.FigRight()
| стрелкаВверх, цифра5:
v.FigRotate()
| стрелкаВниз, пробел:
v.FigRelease()
ELSE
END;
END;
IF msg.char = 1BX THEN
v.paused := ~v.paused;
Views.Update(v, Views.keepFrames);
v.prevTick := Services.Ticks();
END;
| msg: Controllers.TickMsg DO
IF ~v.paused & (msg.tick - v.prevTick >= speed) THEN
v.TimerStep();
v.prevTick := msg.tick;
END;
ELSE
END;
END HandleCtrlMsg;
PROCEDURE (v: GameView) Init (), NEW;
BEGIN
v.InitColors();
v.InitFigures();
v.InitField();
Randomize(v.seed);
v.NewFigure();
v.fly := TRUE;
v.paused := TRUE;
END Init;
PROCEDURE НоваяИгра*;
VAR t: GameView;
BEGIN
NEW(t);
t.Init();
t.NewFigure();
Views.OpenView(t);
END НоваяИгра;
END i21примТетрис.
| i21прим/Mod/Тетрис.odc |
MODULE i21примТрап;
IMPORT Log := StdLog;
VAR a: INTEGER; b: ARRAY 3 OF REAL; c: ARRAY 50 OF CHAR;
PROCEDURE ДругаяПроц;
VAR y: INTEGER;
BEGIN
y := 256;
(* следующая команда вызовет аварийную остановку и откроет окошко Трап, в котором видны значения локальных переменных всех процедур в цепочке вызовов на момент остановки: *)
HALT(0); (*в открывшемся окошке Трап можно покликать по синим ромбам*)
END ДругаяПроц;
PROCEDURE Вызов*;
VAR a, b: INTEGER;
PROCEDURE ВнутрПроц ( x: INTEGER );
VAR y: REAL;
BEGIN
y := 3.14592; ДругаяПроц
END ВнутрПроц;
BEGIN
a := 13; b := 14;
ВнутрПроц( 2002 )
END Вызов;
BEGIN
a := MIN(INTEGER);
b[0] := 0; b[1] := 1; b[2] := 2;
c := "аварийная остановка"
END i21примТрап.
i21примТрап.Вызов | i21прим/Mod/Трап.odc |
MODULE i21примУплотнение;
IMPORT StdLog;
PROCEDURE Проверить ( VAR a: ARRAY OF CHAR );
VAR кандидат: INTEGER;
BEGIN
кандидат := 0;
WHILE (кандидат < LEN(a)) & (a[кандидат] # 0X) DO
кандидат := кандидат + 1
END;
ASSERT( кандидат < LEN(a) )
END Проверить;
PROCEDURE Уплотнить* ( VAR a: ARRAY OF CHAR );
VAR i, j: INTEGER;
BEGIN Проверить( a );
i := 0; j := 0;
WHILE a[j] # 0X DO
i := i + 1;
IF (a[i] # ' ') OR (a[j] # ' ') THEN
j := j + 1;
a[j] := a[i]
END
END
END Уплотнить;
PROCEDURE Демо* ( цепочка: ARRAY OF CHAR );
VAR a: ARRAY 200 OF CHAR;
BEGIN
a := цепочка$;
StdLog.String('до сжатия:'); StdLog.Ln;
StdLog.String(a); StdLog.Ln;
Уплотнить( a );
StdLog.String('после сжатия:'); StdLog.Ln;
StdLog.String(a); StdLog.Ln;
END Демо;
END i21примУплотнение.
Чтобы выполнить процедуру, нужно кликнуть по коммандеру:
"i21примУплотнение.Демо('Вот пример для уплотнения .')"
При этом можно произвольным образом менять уплотняемую цепочку (между одинарными кавычками) и смотреть, что получается.
Чтобы выполнить процедуру после какого-то изменения модуля, следует после компиляции нового варианта модуля кликнуть по коммандеру с одновременным нажатием на Ctrl (чтобы выгрузить из памяти старый вариант модуля).
| i21прим/Mod/Уплотнение.odc |
MODULE Self;IMPORT L:=StdLog,I:=i21sysIn;VAR c:CHAR;BEGIN I.OpenFocus;I.Char(c);WHILE c#0DX DO L.Char(c);I.Char(c) END END Self.
Выше приведена самопечатающаяся программа.
Чтобы её выполнить, нужно нажать Ctrl+F9: текст программы скопируется в Рабочий журнал (Log).
Аналогичная программа, копирующая себя с сохранением табуляций и концов строк:
MODULE Self;
IMPORT L:=StdLog, I:=i21sysIn;
VAR c: CHAR;
BEGIN
I.OpenFocus; I.Char(c);
WHILE I.done DO
IF c=09X THEN L.Tab
ELSIF c = 0DX THEN L.Ln
ELSE L.Char(c)
END;
I.Char(c)
END
END Self.
Чтобы её выполнить, нужно скопировать её в новый пустой документ (Ctrl+N) и нажать там Ctrl+F9. | Mod/Self.odc |
MODULE Профи; (* простейшие программы в Блэкбоксе *) (* в таких скобках комменты (* и они могут быть вложенными *) *)
IMPORT StdLog, Math, In := i21sysIn; (* импорт модулей; для последнего из импортируемых модулей введен короткий псевдоним, который и должен теперь всюду в данном модуле использоваться *)
PROCEDURE Do1*; (* Hello World *)
BEGIN
StdLog.String("Привет, профи! "); (* печать в рабочий журнал (Log) цепочки литер *)
StdLog.Real( Math.Pi() ); (* печать в Log результата функции Math.Pi() *)
StdLog.Ln (* переход в Log на новую строку *)
END Do1;
PROCEDURE Do2*; (* пример ввод из "командной строки" *)
VAR l, m, n: INTEGER;
BEGIN
In.Open; ASSERT( In.Done ); (* открыть поток ввода; убедиться, что ок *)
In.Int( l ); ASSERT( In.Done ); (* прочесть целое; убедиться, что ок *)
In.Int( m ); ASSERT( In.Done ); (* типа можно считывать много *)
IF l > 0 THEN
n := l + m; (* вычислить что-то *)
StdLog.Int( n ); StdLog.Ln; (* напечатать результат в Log *)
ELSE
HALT( 127 ); (* форсировать аварийную остановку с "выбросом кишок" *)
END;
END Do2;
END Профи. <<< конец исходника; компилятор игнорирует всё, что находится после точки.
Компиляция этого модуля: Ctrl+K (K латинское). Можно нажать! Смотреть в окошко Log (если его не видно, выполнить команду меню Info, Open Log / Инфо, Открыть журнал).
Выполнение процедур: клик по соотв. черному коммандеру, хоть два раза :) при этом наблюдать Log:
Профи.Do1
Профи.Do2 3 2 <<< менять числа и кликать снова
Поменять 3 на -3 и кликнуть, чтобы посмотреть на символический дамп процедурного стека -- там можно смело покликать по синим ромбикам и черным стрелочкам.
Нагулявшись по ромбикам, закрыть окошко Trap и продолжать читать тут.
Можно поменять что-нибудь в тексте модуля (добавить инструкции печати).
После изменений текста модуля: скомпилировать его, но чтобы выполнилась новая версия, при первом клике по коммандеру нажимать Ctrl (чтобы выкинуть из памяти старую версию модуля; потом можно Ctrl не нажимать -- модуль сидит в памяти, пока его не выкинут).
Программа Hello world в Блэкбоксе
Никаких project, make и т.п. заводить в Блэкбоксе не нужно. Просто напишите (см. ниже про как?) модуль (вроде показанного выше) и компилируйте его (см. ниже про как?).
Модули линкуются невидимо, динамически при загрузке (причем безопасно, т.е. с проверкой интерфейсов и типов).
Загрузка по мере необходимости. Линковщик остается полностью за кулисами.
(Еще одна фантомная боль:) Скомпоновать EXE или DLL можно. См. DevLinker, а также пособие по работе с DLL.
Но реально чаще не нужно: распространять свое приложение проще всего, переименовав BlackBox.exe и настроив соотв. образом загрузку (см. Особенностиплатформы) и меню (см. Среда). Можно в нескольких вариантах (кассир, охрана, ... БД, ...).
Программы в Блэкбоксе состоят из модулей (модуль = единица компиляции, инкапсуляции, загрузки).
Каждый модуль обычно (но не обязательно) хранится в отдельном документе, в его начале (а после модуля, как тут, чулан для барахла).
Чтобы завести новый модуль, нажать Ctrl+N (или через меню: File, New / Файлы, Новый) и вперед.
Набирается модуль, в принципе, обычным манером. (Однако есть F5: подробней см. насайте и в разделе Полезныесведения.)
Большие и малые буквы в языке различаются.
Хранить исходник модуля с простым именем как Профи обычно следует в папке Mod/.
Вообще полезно придерживаться некой дисциплины. Тогда Блэкбокс сможет при случае сам найти и открыть для вас исходник.
Подробней см. Полезныесведения, сайт и документацию.
В каждом модуле может быть сколько угодно процедур, в том числе экспортированных (которые со звездочкой как у двух процедур в примере).
Нет главной (main) процедуры этого наследия темных веков пакетной обработки (хватит уж, сколько можно).
Любая экспортированная процедура может быть вызвана извне, правда, при вызове коммандером или из меню есть ограничения на параметры (см. StdInterpreter). При вызове из программ никаких таких ограничений, конечно, нет.
Документ Блэкбокса это не чистый текстовый файл. В нем можно менять размер, цвет и т.п. шрифта. (Установки по умолчанию: Edit, Preferences... / Правка, Настройки...) Кроме того, в текст здесь можно вставлять объекты изображения, они же вьюшки/views например, маркеры ошибок, которые вставляет компилятор, или невидимые вьюшки, которые оформляют гиперссылки (чтобы увидеть/спрятать их, нажимать Ctrl+H; кстати, все вьюшки построены примерно по одному принципу, см. 6Построениеобъектовизображения(вьюшек)).
Компиляция: Ctrl+K (K латинская) или Dev, Compile / Программирование, Компилировать (модуль должен быть в переднем окошке, в начале текста).
Есть и другие способы, например, целым списком (DevCompiler.CompileThis имя_модуля1 имя_модуля2 ...) или из программы, не открывая исходник в окошке, а сгенерив его на лету; см. интерфейс модуля DevCompiler (дважды кликнуть по DevCompiler, нажать Ctrl+D).
Если в тексте компилируемого модуля не появились маркеры ошибок (черные квадраты), а в журнале (Log) нет сообщения о количестве ошибок, значит, компиляция прошла успешно.
По маркеру ошибок можно дважды кликнуть, чтобы прочесть соотв. сообщение об ошибке.
Чтобы выполнить процедуру, нужно где-то иметь (например, напечатать) ее полное имя (т.е. имя модуля, точка, имя процедуры). Если полное имя выделить мышкой, то выполнить процедуру можно командой меню Dev, Execute / Программирование, Выполнить (Процедуру). Но обычно перед полным именем вставляют т.наз. коммандер (черный кружок, см. выше) посредством Ctrl+Q (Tools, Insert Commander / Инструменты, Вставить коммандер) и кликают по нему.
Упр: покликать по обоим коммандерам вверху, наблюдая Log.
В продукте вызов процедуры попадает в меню или в диалог, но и конечный пользователь может предпочесть документ с коммандерами и входными данными это может дать большую гибкость, чем жесткая диалоговая форма.
Модуль, раз загрузившись в память (например, при первом вызове одной из своих процедур), продолжает там сидеть и ждать команды (как объект-синглтон).
Чтобы вызвать новую версию, предварительно выкинув старую, при клике по коммандеру нажимать Ctrl.
Интерфейс для любого модуля можно посмотреть, выделив его имя (хоть где, хотя бы в Log) и нажав Ctrl+D (Info, Interface / Инфо, Интерфейс (клиентский)). Например, дважды щелкните вот по этому Strings и посмотрите.
Документацию к любому модулю (если она приготовлена и хранится по правилам) можно посмотреть, выделив его имя и выполнив Info / Инфо, Documentation (для русского перевода Документация). Подобные команды могут быть и в контекстном меню.
Чтобы настроить под себя меню (включая контекстные, а также горячие клавиши), вызвать Info, Меnus / Инфо, Меню, кликнуть нужную ссылку откроется текстовый документ, внести в него изменения, сохранить, выполнить Info, Update Menus / Инфо, Обновить меню меню обновятся без перезапуска (см. Среда).
Раскраска синтаксиса: при ключевых словах из больших букв это вещь избыточная. Доказано экспериментально: устроить ее нетрудно (можно начать хотя бы с i21sysEdit), и вновь приходящие люди по инерции ее делали (известны минимум две полноценные попытки, где-то лежат готовые к употреблению), но сами авторы в итоге публично отказывались от этих бирюлек за ненадобностью.
Цвет очень полезен для других целей (отметить исправления и т.п.), и жалко растрачивать такую ценность на ерунду (при ключевых словах в all-caps их еще и раскрашивать совершенно излишне).
Пошагового отладчика нет и, можно надеяться, не будет. Почему см. тут.
Зато есть символический дамп (см. работу процедуры Do2 для отрицательного первого вводимого числа).
Учитесь культурно программировать 8))), шпигуя программу ASSERT'ами (прежде всего для предусловий и инвариантов цикла) тогда символического дампа достаточно.
Обработки исключений тоже нет. По-настоящему это вещь (под названием прерывания) для реального времени. В обычном программировании это нелокальная передача управления, которая при неизбежных массовых злоупотреблениях обнуляет возможности верификации программ (классики вроде Дейкстры поняли это еще в 70-х гг.; а производители промышленных инструментов провоцируют и эксплуатируют разврат ничуть не хуже наркоторговцев).
Устроить для этого библиотеку (и обойтись без введения в язык) можно (Трапы же сделаны), но реальное время всё-таки отдельная песня.
В расчете на школы были написаны Полезныесведения и инструкции на сайте. Их имеет смысл просмотреть, прежде чем врубаться в документацию.
Ввод-вывод. За побайтовый ввод-вывод отвечает модуль Files. Там реализована схема (паттерн, шаблон) Carrier-Rider (кстати, изобретенный в рамках проекта Оберон к 1988).
За ввод-вывод элементарных типов отвечают типы (=классы) Reader и Writer в модуле Stores. Там же средства поддержки сохранения на диск динамических структур данных с множественными внутренними ссылками (см. там тип Stores.Store; см. также пример в исходнике модуля i21sysDesktop, отталкиваясь от инструкций, выделенных синим, в процедурах Save и Restore, ближе к концу модуля).
Полезно иметь в виду, что модуль Files является (почти) чисто интерфейсным, лишь хранящим ссылки на стандартную реализацию (HostFiles), и вместо последней тому же Stores можно подсунуть любую другую (основанную на файлах, смоделированных в памяти, или какой-нибудь фасад над сетевым соединением и т.п.). Stores будет работать с любой корректной реализацией интерфейсов из Files как ни в чем не бывало.
Вообще философия ввода-вывода в Блэкбоксе отличается от старых подходов, здесь принят более высокоуровневый взгляд: чаще работают с блэкбоксовскими текстами (TextModels.Model), используя средства модулей TextMappers (и, возможно, Strings). Превратить внешний обычный текст в TextModels.Model можно примерно так:
PROCEDURE ImportText ( f: Files.File; OUT t: TextModels.Model );
VAR r: Stores.Reader; w: TextModels.Writer;
byte: SHORTCHAR; ch: CHAR; len: INTEGER;
BEGIN
ASSERT( f # NIL, 20 ); ASSERT( t = NIL, 21 );
r.ConnectTo( f ); r.SetPos( 0 );
len := f.Length();
t := TextModels.dir.New(); w := t.NewWriter( NIL );
WHILE len # 0 DO
r.ReadSChar( byte ); (* use directly r.ReadChar( ch ) to read 2-byte characters *)
ch := byte; (* сould translate character set here *)
w.WriteChar( ch ); DEC( len )
END;
r.ConnectTo( NIL )
END ImportText;
Последний тут маленький, но полезный штрих: ходить по какому-нибудь набору литер в документе можно так: выделить его (набор), нажать F3 попадем на следующий экземпляр этого набора в текущем документе; Shift+F3 на предыдущий; F4 на первый; Shift+F4 на последний. (Поупражняйтесь на ImportText в процитированной процедуре.)
Дальше можно изучать Примерыпроизводителя(подсистемаObx)
Успехов!
info21
2009-04-24
PS Большая благодарность В.В.Лаптеву за совет.
2011-02-04 Добавление русскоязычных названий меню, А.С.Ильин. | Mod/Профи.odc |
Overview by Example: ObxActions
This example demonstrates how background tasks can be implemented using actions. An action is an object which performs some action later when the system is idle, i.e., between user interactions. An action can be scheduled to execute as soon as possible, or after some time has passed. Upon execution, an action may re-schedule itself for a later point in time. In this way, an action can operate as a background task, getting computation time whenever the system is idle. This strategy is called cooperative multitasking. For this to work, an action must not do massive computations, because this would reduce the responsiveness of the system. Longer calculations need to be broken down into less time consuming pieces. This is demonstrated by an algorithm which calculates prime numbers up to a given maximum, as a background task. An action is used to perform the stepwise calculation. Every newly found prime number is written into a text. This text remains invisible as long as the calculation goes on. The action checks whether it has reached a maximum set by the user. If this is not yet the case, it re-schedules itself for further execution. Otherwise, it opens a window with the list of prime numbers, i.e., a text view on the created text.
"StdCmds.OpenAuxDialog('Obx/Rsrc/Actions', 'Prime Calculation')"
ObxActionssources
| Obx/Docu/Actions.odc |
Overview by Example: ObxAddress0
One of the hallmarks of modern user interfaces are modeless dialog boxes and data entry forms. They feature text entry fields, push buttons, check boxes, and a variety of other so-called controls. The BlackBox Component Builder addresses this issue in a unique way:
new controls can be implemented in Component Pascal; they are nothing more than specialized views, there is no artifical distinction between control objects and document objects
every view which may contain other views (i.e., a container view) may thus contain controls, there is no artifical distinction between control containers and document containers
every general container view can be turned into an input mask when desired
some controls can be directly linked to variables of a program
linking is done automatically, taking into account type information about the variables in order to guarantee consistency
initial form layouts can be generated automatically out of a record declaration
forms can be edited interactively and stored as documents, no intermediate code generation is required
forms can be used "live" while they are being edited
form layouts may be created or manipulated by a Component Pascal program, if this is desired.
Some of these aspects can be demonstrated with the example below:
MODULE ObxAddress0;
VAR
adr*: RECORD
name*: ARRAY 64 OF CHAR;
city*: ARRAY 24 OF CHAR;
country*: ARRAY 16 OF CHAR;
customer*: INTEGER;
update*: BOOLEAN
END;
PROCEDURE OpenText*;
BEGIN
END OpenText;
END ObxAddress0.
Compile this module and then execute NewForm... in the Controls menu. A dialog will be opened. Now type "ObxAddress0" into its Link field, and then click on the default button. A new window with the form will be opened. This form layout can be edited, e.g., by moving the update checkbox somewhat to the right. (Note that you have modified the document by doing that, thus you will be asked whether to save it when you try to close it. Don't save this one.
Now execute the Open asAuxDialog command in the Controls menu. As a result, you get a fully functional dialog with the current layout. This mask can be used right away, i.e., when you click into the update check box, the variable ObxAddress0.adr.update will be toggled!
If you have several views on the same variable (e.g., both the layout and the mask window), all of them will reflect the changes that the user makes.
A form's controls are linked to a program variable in a similar way as a text view is linked to its text model. Both text views and controls are implementations of the interface type Views.View. The container of the above controls is a form view, itself also an implementation of Views.View. Form views, just as text views, are examples of container views: container views may contain some intrinsic contents (e.g., text pieces) as well as arbitrary other views. Form views are degenerated in that they have no intrinsic contents; they may only contain other views.
Instead of starting with a record declaration as in the above example, you may prefer to start with the interactive design of a dialog, and only later turn to the programming aspects. This is perfectly possible as well: click on the Empty command button to create a new empty form. It will be opened in a new window, and the Layout menu will appear. Using the commands in the Controls menu, new controls can be inserted into the form. The form can be saved in a file, and its controls may later be connected to program variables using a tool called the control property editor (see the description of the Edit menu in the User's Manual).
BlackBox Component Builder only supports modeless forms, whether used as data entry masks or as dialogs. Modal forms would force the user to complete a certain task before doing anything else, e.g., looking up additional information on his task. BlackBox follows the philosophy that the user should be in control, not the computer.
In this example we have seen how a form is used, from the perspective of a programmer as well as from the perspective of a user interface designer. Furthermore we have seen how an initial form layout can be generated automatically; how a form can be viewed (even simultaneously) both as a layout and as a dialog mask; and how a control, like any other view, may live in an arbitrary container view, not just in a form view.
| Obx/Docu/Address0.odc |
Overview by Example: ObxAddress1
This example combines some features of the previous examples: it takes the address record of ObxAddress1 and adds behavior to it. Such a record, whose fields are displayed by controls, is called an interactor.
The behavior for our example interactor is defined by the global OpenText procedure. It creates a new text, into which it writes all the fields of the address record. The fields are written as one line of text, separated by tabulators and terminated by a carriage return. A new text view on this text is then opened in a window.
MODULE ObxAddress1;
IMPORT Views, TextModels, TextMappers, TextViews;
VAR
adr*: RECORD
name*: ARRAY 64 OF CHAR;
city*: ARRAY 24 OF CHAR;
country*: ARRAY 16 OF CHAR;
customer*: INTEGER;
update*: BOOLEAN
END;
PROCEDURE OpenText*;
VAR t: TextModels.Model; f: TextMappers.Formatter; v: Views.View;
BEGIN
t := TextModels.dir.New();
f.ConnectTo(t);
f.WriteString(adr.name); f.WriteTab;
f.WriteString(adr.city); f.WriteTab;
f.WriteString(adr.country); f.WriteTab;
f.WriteInt(adr.customer); f.WriteTab;
f.WriteBool(adr.update); f.WriteLn;
v := TextViews.dir.New(t);
Views.OpenView(v)
END OpenText;
END ObxAddress1.
After the example has been compiled, and after a form has been created for it and turned into a dialog, you can enter something into the fields (note that customer only accepts numeric values). Then click on the OpenText button. A window will be opened with a contents similar to the following:
Oberon microsystems Technoparkstrasse 1 Zьrich ZH 8005 Switzerland 1 $TRUE
In this example, we have seen how behavior can be added to interactors, by assigning global procedures to their procedure-typed fields.
| Obx/Docu/Address1.odc |
Overview by Example: ObxAddress2
This example combines features of earlier examples: it allows to enter an address via a mask, and a push button causes the entered data to be appended to a text in a file. Afterwards, the entered data is cleared again. Controls must be notified when a program modifies an interactor. For this purpose, there is the Dialog.Update procedure which takes an interactor as parameter.
MODULE ObxAddress2;
IMPORT Files, Converters, Views, Dialog, TextModels, TextMappers, TextViews;
VAR
adr*: RECORD
name*: ARRAY 64 OF CHAR;
city*: ARRAY 24 OF CHAR;
country*: ARRAY 16 OF CHAR;
customer: INTEGER;
update*: BOOLEAN
END;
PROCEDURE OpenText*;
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
v: Views.View; t: TextModels.Model; f: TextMappers.Formatter;
BEGIN
loc := NIL; name := ""; conv := NIL;
v := Views.Old(Views.ask, loc, name, conv);
IF (v # NIL) & (v IS TextViews.View) THEN
t := v(TextViews.View).ThisModel();
f.ConnectTo(t);
f.SetPos(t.Length());
f.WriteString(adr.name); f.WriteTab;
f.WriteString(adr.city); f.WriteTab;
f.WriteString(adr.country); f.WriteTab;
f.WriteInt(adr.customer); f.WriteTab;
f.WriteBool(adr.update); f.WriteLn;
Views.OpenView(v);
adr.name := ""; adr.city := ""; adr.country := ""; adr.customer := 0; adr.update := FALSE;
Dialog.Update(adr) (* update all controls for adr *)
END
END OpenText;
END ObxAddress2.
| Obx/Docu/Address2.odc |
Overview by Example: ObxAscii
Many times the input data to a program is given as an ASCII text file, or a given program specification dictates that the output format be plain ASCII text. This example shows how to process ASCII text files with the BlackBox Component Builder and presents a sketch of a module that provides a simple interface to handle ASCII text files.
The BlackBox Component Builder departs from the traditional I/O model found in other libraries. Module Files provides classes that abstract files, file directories, and access paths to open files, rather than cramming everything into one abstraction. So-called readers and writers represent positions in an open file. Several readers and writers may be operating on the same file simultaneously. The file itself represents the data carrier proper and may contain arbitrary data.
Textual information is handled by the text subsystem. Similar to the file abstraction, module TextModels provides a data carrier class ђ the text proper ђ and classes for reading characters from, and inserting characters into a text. Module TextMappers provides formatting routines to write values of the basic types of the Component Pascal language to texts. It also provides a scanner class that reads texts and converts the characters into integers, reals, strings, etc.
Texts may be stored in different formats on files. An ASCII text is just a special case of a text that contains no style information. So-called converters are used to handle different file formats. A converter translates the byte stream in a file into a text object in memory, and vice-versa.
The file and text abstractions are simpler, yet more flexible and powerful than the traditional I/O model. As with everything, this flexibility has its price. The simple, linear processing of a (text-)file requires some more programming to initialize the converter, text and formatter objects before a text file can be read.
This example demonstrates how to process ASCII text files with BlackBox. Module ObxAscii implements a simple, traditional interface for formatted textual input and output. It is by no means complete. ObxAscii may however serve as a model for implementing a more complete interface.
The implementation of data type Text is hidden. This renders possible a different implementation than the one presented below, e.g. using a traditional I/O library.
The field done of type Text indicates the success of the last operation. Procedure Open opens an existing file for reading. Procedure NewText creates a new, empty text for writing. Mixed reading and writing on the same text is not very common and is therefore not supported in this simple model. For new texts to become permanent, procedure Register must be used to enter the file in the directory. Finally, a set of Write procedures produce formatted output and the corresponding Read procedures read formatted data from texts.
A scanner and a formatter are associated with each text. In order to read ASCII text files and convert them to text objects, the converter for importing text files is needed. The initialization code in the module body finds the appropriate converter in the list of registered file converters and keeps a reference to it in the global variable conv.
A locator and a string is used to specify a directory and a file name when calling Open or Register. If the locator is NIL, the string given in parameter name is interpreted as a path name. (We use the well-established cross-platform URL-syntax for path names, i.e., directory names are separated by / characters.) The procedure PathToFileSpec produces a locator and file name from a path name.
Procedure Open uses Converters.Import with the ASCII text file converter stored in the global variable conv to initialize a text object with the contents of the file. The scanner is initialized and set to the beginning of the text. Procedure NewText just creates a new, empty text and initializes the formatter. Procedure Register uses Converters.Export with the ASCII text file converter to externalize a text to a file.
The Read procedures first check whether the text has been opened for reading and then use the scanner to read the next token from the text. If the token read by the scanner matches the desired type, the field done is set to TRUE to indicate success. The Write procedures first check whether the text has been opened for writing, i.e., created with NewText, and then use the formatter to write values to the text.
ObxAsciisources
| Obx/Docu/Ascii.odc |
The rules for playing BlackBox
The objective of the game is to find the form of a hidden molecule. The molecule consists of several atoms which are placed on the grid. To find out more about the hidden molecule, rays must be fired into the grid. The rays may be deflected or even absorbed by the atoms. From the position where a fired ray leaves the grid, the positions of the atoms have to be deduced. Only the reaction of the atoms on the fired rays is available, thus the name black box for this game.
Below, the possible influences of the atoms on the rays are described and illustrated with examples.
1) If the ray hits an atom head-on then it is absorbed. This situation is marked with an A at the position where the ray went in.
2) If the ray comes towards an atom one square off head-on, it gets deflected 90 degrees away from the atom. The entry and exit positions are marked with a 1 in the example on the right. Absorbing takes priority over deflecting, thus the second ray from the right side becomes absorbed.
3) If the ray tries to pass between two atoms that are one square apart, it is reflected straight back. The ray will return to its entry position which will be marked with an R. This mark is also used if an atom is situated on the border and the ray goes in just one position beside the atom. In this case the ray is reflected even before it enters the board. This sitation is the most typical reason for a reflected ray. In the example to the right, four positions are marked from which fired rays have been reflected.
4) If the ray is neither absorbed nor reflected, the positions where the ray enters and leaves the black box are marked with the same number (the number of the actual guess). Note, that the path of the ray may be arbitrarily complicated.
How to play BlackBox
To start the game, open the BlackBoxdialogbox. You may install a command into your menu to open this dialog. In the dialog you can define the size of the board and the number of atoms the computer will hide for you. When you click onto the OK button, a new window will appear which contains a new BlackBox puzzle. At the bottom of the view the number of hidden atoms is indicated.
To fire a ray into the grid, click into one of the locations on the edge of the grid. The result will be displayed immediately. Obviously this operation cannot be undone.
To tell the program where you think an atom is, click on the grid location. This will tentatively place an atom at that location. If you later decide that the atom should not be there, click on the square again, and it will disappear. When you think you have placed all of the atoms correctly, select Show Solution from the BlackBox menu and the computer will check the atoms that you placed and reveal any that you missed or placed incorrectly. In addition, a score will be displayed. The smaller the score, the better the result. Every ray which has been fired is counted with two points, except for absorbed and reflected ones which are only counted with one point. Additionally, for every misplaced atom five points are added. For an eight by eight board with four hidden atoms the average score is between ten and fifteen. Once the solution has been shown, you can visualize the path a ray will follow by clicking into the edge of the grid while holding down the modifier key.
If you execute the menu entry New Atoms, then the computer will hide a new molecule for you which consists of the same number of atoms as the last one.
If you want to generate a new puzzle for someone else, then place the atoms on the grid and select the Set New Atoms command. The number of the hidden atoms will be updated accordingly. You may save and mail such a puzzle to your friends.
Some background information
BlackBox has been invented by the English mathematician Dr. Eric W. Solomon. All the games he invented are distinguished by the fact that they are easy and simple, but very interesting. In other words, his games are in the spirit of Oberon, namely as simple as possible, but not simpler.
BlackBox got published in Germany under the names Logo and Ordo in 1978 but was withdrawn already two years later. It is now again available from the franjos company under its original name BlackBox in a nice edition (wooden stones and atoms made out of glass). Other games invented by Solomon are Sigma File and Vice Versa. The latter has also been published under the name Hyle.
The objective of the game is not to deduce the hidden position of all atoms completely, but rather to score with as few points as possible. Thus, in some situation it may be better to apply some intuition than firing additional rays.
The worst score is always p*5 where p is the number of hidden atoms. This score can be achieved if no ray is fired at all and if the atoms are placed arbitrarely. Note also, that it is not always possible to find the hidden atoms from the information one gets through the rays. The simplest example for a molecule consisting of 5 atoms is given in the example to the right. The position of the fifth atom in the center can not be deduced. There exist also a few examples with 4 atoms. Can you construct one?
Some nice examples
The following examples are ready for you to play.
| Obx/Docu/BB-Rules.odc |
Overview by Example: ObxBitmap
This example shows how Windows specific programming can be used to create a Windows bitmap and display it in a BlackBox view. For more information see platform-specificissues and the Win32 API documentation.
"ObxBitmap.Deposit; StdCmds.Open"
ObxBitmapsources
| Obx/Docu/Bitmap.odc |
Overview by Example: ObxBlackBox
This example implements the deductive game BlackBox, using the BlackBox Component Framework. The aim of the game is to guess the positions of atoms within an n by n grid by firing rays into a black box. The rays may be deflected or even absorbed. From the position where the ray leaves the grid one must try to deduce the position of the atoms. For more information about BlackBox and on how to play the game read the rules.
A main point of this example is to demonstrate one advantage of compound documents: The ObxBlackBox views which are implemented can directly be used in the documentation for illustration purposes. Neither additional code nor the use of a drawing program is required. Moreover, these views in the documentation are living elements and can be inspected and modified as desired.
This example also shows how a view-specific menu can be used. If a BlackBox view is the focus view, a special menu appears which offers BlackBox-specific commands that operate on the focus view. For this purpose, the following menu is installed in your Obx menu file (-> Menus):
MENU "BlackBox" ("ObxBlackBox.View")
"Show Solution" "" "ObxBlackBox.ShowSolution" "ObxBlackBox.ShowSolutionGuard"
SEPARATOR
"New Atoms" "" "ObxBlackBox.New" ""
"Set New Atoms" "" "ObxBlackBox.Set" ""
SEPARATOR
"Rules" "" "StdCmds.OpenBrowser('Obx/Docu/BB-Rules', 'BlackBox Rules')" ""
END
The first menu entry is enabled or disabled depending on the state of the focus view. A user-defined guard is added for this purpose. For more information about the commands themselves see the section on how to play BlackBox in the rules.
"StdCmds.OpenAuxDialog('Obx/Rsrc/BlackBox', 'BlackBox')"
ObxBlackBoxsources
| Obx/Docu/BlackBox.odc |
Overview by Example: ObxButtons
This example demonstrates how new controls can be implemented. A control is a visual object that allows to control some behavior of another part of the program. Examples of controls are buttons, sliders, check boxes, etc. In contrast to full-fledged editors, a control only makes sense in concert with its container and other controls contained therein. With the BlackBox Component Builder, a control is a specialized view. A standard selection of important controls is provided by the BlackBox Component Builder, others can be implemented by third parties. This article shows an example of a simple button control implementation.
Our example control has four properties: its current font, color, link, and label. The link is used by most BlackBox controls to bind them to some program elements. In our case, this program element is a Component Pascal command, i.e. an exported procedure. The label is the string displayed in the button.
Control properties can be inspected and modified with the control property inspector (module DevInspector). To try this, select the control, and then use the Properties... command in submenu Object of menu Edit (Windows) / PartInfo in menu Edit (Mac OS).
What do we have to implement to make this control work? In the remainder of this text, we will go through various aspects of the control implementation as it is given in the corresponding listing. We will look at all the procedures which must be implemented for the control to work. As is typical for object- and component-oriented programming, these procedures are meant to be called by the environment, not by yourself. This is called the Hollywood Principle of Object-Oriented Programming: Don't call us, we call you.
Typically, a control is embedded in a form. When the form is saved in a file, it gives all embedded controls the opportunity to externalize themselves. When the form is read from a file, the form allocates the controls and lets them internalize themselves. A control programmer needs to implement two procedures for this purpose: Externalize and Internalize. In the listing you can see that the auxiliary procedures Views.WriteFont and Views.ReadFont are used. They relieve you from the cumbersome task of writing or reading a font's typeface, size, style, and weight separately.
To support copying operations (e.g., cut and paste), a view must be able to copy its contents to an empty clone of itself. For this purpose, the CopyFrom procedure copies the state of an existing control (source) to a newly allocated but not yet initialized control.
Our control must be able to redraw its outline and label, which is the purpose of the Restore procedure. It draws the label in the control's color and font. The label is horizontally centered. Note that the control doesn't need to draw the background, this is handled by the container. Only the foreground, i.e., the outline and the label are drawn.
Of course, the control should also be able to perform some action when the user clicks in it. Mouse clicks and other interaction events are handled by a view's HandleCtrlMsg procedure. In our example, this procedure only reacts upon mouse-down messages (events). Other interactions such as key presses are not handled, in order to make the example as simple as possible.
Basically, the procedure's implementation consist of a mouse tracking loop, which terminates when the user releases the (primary) mouse button. The loop is programmed such that the control's rectangle is inverted as long as the mouse is located over the control, and not inverted otherwise.
If the mouse is released over the control, the inversion is removed and the string in v.link passed to the Dialog.Call procedure. This procedure basically implements an interpreter for Component Pascal commands, i.e., strings such as "Dialog.Beep" can be executed at run-time.
BlackBox predefines some standard system and control properties. The system properties are the ones that can be changed via the Characters menus (Font, Attributes menus on Mac OS), i.e., font and color. The control properties are the ones defined in module Controls, and changeable via the control property inspector. There is a message that BlackBox uses to poll a view's properties (Properties.PollMsg), and a message to modify a view's properties (Properties.SetMsg). Returning a control's properties is easy: allocate the suitable property descriptors (Properties.StdProp and Controls.Prop), assign their appropriate fields, i.e., typeface, size, style weight, link, and label, and signal that those are the valid properties that the control knows about. For the standard system properties, this is done in the auxiliary procedure GetStdProp. The other corresponding procedure SetStdProp is slightly more complicated, because for each property it must be tested whether it needs to be changed or retained. After all, the user may just have changed the control's color without changing the font.
The whole property handling is held together by the view's HandlePropMsg procedure, where the PollMsg and SetMsg messages are recognized. For SetMsg, all elements of its property list are traversed and existing system and control properties are picked out. This is done since obviously a control cannot set properties that it doesn't know.
Changes of the control's properties are bracketed by calls to Views.BeginModification and Views.EndModification. These procedures tell the BlackBox Framework that some operation was performed that cannot be undone. Undo support would not be much more complicated, but still a bit overkill for this example here.
The calls to Views.Update signal that the control's visible area should be restored as soon as the current command has terminated.
In HandlePropMsg, the control also answers some preferences. Preferences are messages that a container view (e.g., a form) sends to its contained views (e.g., the controls). Their purpose is to customize the container's behavior according to its contents. A container is not obliged to ask embedded views for their preferences, but "socially responsible" containers (e.g., texts and forms) do so. For example, a control which doesn't yet have a defined width or height is asked for its preferred size (Properties.SizeMsg). With the Properties.FocusPref preference, a view can influence how it is treated when the mouse is clicked in it. Our control indicates that it is a hot focus, i.e. it releases its focus immediately after the mouse is released.
Finally, the New procedure creates a new control, and the Deposit procedure deposits such a new control in a system queue of the BlackBox Framework. For example, the following command sequence can be used to put a new control into this queue:
"ObxButtons.Deposit; StdCmds.PasteView"
And already we are through with the discussion of the whole control implementation! Even though we haven't addressed some more advanced issues such as keyboard shortcuts for controls, and how a control can be linked to program variables instead of commands, it still is a complete control implementation.
ObxButtonssources
| Obx/Docu/Buttons.odc |
Overview by Example: ObxCalc
This example implements a simple pocket calculator view for integer numbers. The calculator can be used either with the keyboard or with the mouse. It is implemented as a stack calculator. The topmost entry of the stack is displayed. With the ^ key (or ENTER key on the keyboard) this value is duplicated and pushed onto the stack. The p-key performs a pop operation, that is the topmost entry gets replaced by the second one. With the s-key the two topmost entries of the stack can be swapped. Expressions must be evaluated using the reverse polish notation. The arithmetic operations replace the two topmost entries by the result. / stands for the quotient and ч for the remainder. For example, to add 12 and 25, the keys 12^25+ must be pressed. At the beginning, the stack is filled with zeroes.
The implementation is rather simple. The ObxCalc views are views which do not contain a model. Every view keeps its own stack. When a calculator is copied, the state of the copy gets initialized.
The state of a view is not externalized. This implies that any calculator loaded from a file is always in a cleared state.
From a view-programming point of view the following type-bound procedures are of interest:
Restore draws the view's contents.
HandleCtrlMsg handles all controller messages which are sent to the view, in particular when the mouse button (Controllers.TrackMsg) or when a key (Controllers.EditMsg) is pressed within the view.
HandlePropMsg handles the property messages which are sent to the view by its container. The container asks the view about its (preferred) size (Properties.SizePref), whether it is resizable (Properties.ResizePref) and whether it wants to become focus or not (Properties.FocusPref).
Externalize externalizes a version byte
Internalize reads the version byte and initializes a new view
With only these five procedures we get a fully working interactive view. The view can be saved to a file (without its internal state) and copied using Drag & Drop or Copy & Paste, it can be printed, and under Windows, it can be exported as ActiveX object into any ActiveX container.
"ObxCalc.Deposit; StdCmds.Open"
ObxCalcsources
| Obx/Docu/Calc.odc |
Overview by Example: ObxCaps
This example shows how the built-in text subsystem of the BlackBox Component Builder can be extended by new commands. To demonstrate this possibility, a command is shown which fetches the selection in the focus view (assuming the focus view is a text view), creates a new empty text, copies the selection into this new text (but with all small letters turned into capital letters), and then replaces the selection by the newly created text. In short, this command turns the selected text stretch into all capital letters.
MODULE ObxCaps;
IMPORT Stores, Models, TextModels, TextControllers;
PROCEDURE Do*;
VAR c: TextControllers.Controller; beg, end: INTEGER;
r: TextModels.Reader; ch: CHAR;
buf: TextModels.Model; w: TextModels.Writer; script: Stores.Operation;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
(* upper case text will be copied into this buffer *)
buf := TextModels.CloneOf(c.text); w := buf.NewWriter(NIL);
r := c.text.NewReader(NIL); r.SetPos(beg);
r.ReadChar(ch);
WHILE (r.Pos() <= end) & ~r.eot DO
IF (ch >= "a") & (ch <= "z") THEN ch := CAP(ch) END;
w.WriteChar(ch);
r.ReadChar(ch)
END;
Models.BeginScript(c.text, "Caps", script);
c.text.Delete(beg, end); c.text.Insert(beg, buf, 0, end - beg);
Models.EndScript(c.text, script)
END
END Do;
END ObxCaps.
As an example, select the test string several lines below, and then click on the following commander:
ObxCaps.Do
teSTstring834 .-st
You'll note that the selection has turned into all caps.
But now comes the surprise: execute UndoCaps in the Edit menu. As a result, the effect of the uppercase operation is undone! In the BlackBox Component Builder, most operations are undoable; this also holds for the Delete and Insert text procedures in the above example. Thus, you need to do nothing special in order to render such a command undoable!
However, you may have noticed that there is something special in the sample program: there is a BeginScript / EndScript pair of procedure calls before resp. after the calls to Delete / Insert. They bundle the sequence of a Delete followed by a Insert into one single compoundcommand, meaning that the user need not undo both of these operations individually, but rather in one single step.
In this example we have seen how an existing displayed text and its selection are accessed, how a buffer text is created, and how the selected text stretch is replaced by the buffer's contents.
| Obx/Docu/Caps.odc |
Overview by Example: ObxContIter
This example shows how to iterate over the views embedded in a container, whether it be a text container, a form container, etc. The command searches for the first embedded view whose label is "magic name". At first, the command gets the focus container on which to operate:
c := Containers.Focus();
This statement obtains the innermost general container's controller in the focus path, even if the container is in mask or browser mode and some control in the container is currently the innermost (non-container) view.
Every general container defines some order for the embedded views. For texts, this is the order of the views in the text, for forms it is the z-ordering, etc. The controller methods GetFirstView and GetNextView allow to iterate over the embedded views in the defined order:
c.GetFirstView(Containers.any, v);
c.GetNextView(Containers.any, v);
The first parameters denote whether all embedded views should be traversed (Containers.any) or only the selected views (Containers.selection).
The loop that searches for the specific control has the typical form of a search loop:
get first element;
WHILE (element # NIL) & ~(element is the right one) DO
get next element
END;
In our example, the condition in the WHILE loop is the following:
(v # NIL) & ~((v IS Controls.Control) & (v(Controls.Control).label = "magic name"))
The right-side term contains an expression that denotes "element is the right one", in this case:
(v IS Controls.Control) & (v(Controls.Control).label = "magic name")
This means that the element is a control, and its label is "magic name". The not-operator "~" inverts this condition, so that the loop continues as long as the right element has not yet been found.
Note that you shouldn't modify the selection during iteration over the selection. Also, you shouldn't insert into or delete from the container model during iteration.
ObxContItersources
| Obx/Docu/ContIter.odc |
Overview by Example: ObxControls
A change of an interactor field (i.e., a field of a globally declared record variable) may affect not only controls which are linked to this field, but others as well. For example, a command button may be disabled as long as a text field is empty, and become enabled when something is typed into the text field.
Guard commands
Such state changes of controls, which are the results of state changes in an interactor, are handled by guard commands. A guard is a command which may disable a control, may denote it as undefined, or may make it read-only. It does not have other side effects; in particular, it doesn't invoke an arbitrary action or change the state of an interactor. For that purpose, notifiers are used.
Notifier commands
A notifier is an optional command that can be bound to a control, using the control property editor (-> DevInspector). For example, a notifier command may write something into the status bar of a window when the mouse button is pressed, and clear the status bar when the mouse button is released again.
It is more typical, however, that a notifier changes the state of the interactor to which its control is linked; i.e., to change one or more of the interactor fields to which its control is not linked.
In this way, the change of one interactor field's value may cause a change of another field's value, via the former's notifier.
Example
The example illustrates guards and notifiers, as well as command button, radio button, and list box controls.
Imagine something whose size should be controlled via a dialog, with more skilled users getting more degrees of freedom. For example, this may be a dialog for a game, which allows the user to choose a skill level. A novice user only gets a default amount of money to invest in an economics simulation game, a more experienced user additionally may choose among three predefined choices, while a guru may enter any value he or she wants to use. In order to keep our example simple and to concentrate on the control behaviors, nothing as complex as a simulation game is implemented. Instead, the initial size of a square view can be controlled by the user, in a more or less flexible way that depends on the chosen skill level.
In our example, the skill level is implement as the class field of the data interactor in module ObxControls. It is an integer variable, to which a text entry field may be linked, or more appropriately, a number of radio buttons. The radio buttons are labeled beginner, advanced, expert, and guru. Depending on the currently selected class, the interactor's list field is adapted: for a beginner, the list box should be disabled, because there is no choice (the default is taken). For an advanced player, a choice between "small", "medium", and "large" are presented in addition to the "default" size. Obviously, the list box must be enabled if such a choice exists. "expert" players get even more choices, namely "tiny" and "huge". Note that if these choices appear, the list box becomes too small to show all choices simultaneously. As a consequence, the scroll bar of the list box becomes enabled.
"guru" players have even more freedom, they can type in the desired size numerically, in a text entry field which is read-only for all other skill levels. The command button Cancel closes the dialog without doing anything, the Open button starts the game, and the OK button starts the game and immediately closes the dialog.
Since we are mainly interested in how to implement the described behavior, we don't actually implement a game. Instead, the "game" merely consists in opening a new view, whose size is determined by the size chosen in the dialog (default, large, small, etc.)
With the New Form... menu command, a new dialog box for the ObxControls.data interactor can be created automatically. The layout of this dialog can be edited interactively, and the properties of the various controls can be set using the control property editor. They should be set up as in the table below:
Control Link Label Guard Notifier Level
Radio Button ObxControls.data.class &Beginner ObxControls.ClassNotify 0
Radio Button ObxControls.data.class &Advanced ObxControls.ClassNotify 1
Radio Button ObxControls.data.class &Expert ObxControls.ClassNotify 2
Radio Button ObxControls.data.class &Guru ObxControls.ClassNotify 3
List Box ObxControls.data.list ObxControls.ListGuard ObxControls.ListNotify
Text Field ObxControls.data.width ObxControls.WidthGuard
Command Button StdCmds.CloseDialog;
ObxControls.Open OK
Command Button ObxControls.Open &Open
"StdCmds.OpenAuxDialog('Obx/Rsrc/Controls', 'ObxControls Demo')"
ObxControlssources
| Obx/Docu/Controls.odc |
Overview by Example: ObxControlShifter
This example is described in chapter4 of the BlackBox tutorial.
| Obx/Docu/ControlShifter.odc |
Overview by Example: ObxConv
While most data files are BlackBox document files, it is sometimes necessary to deal with other file types as well: ASCII files, picture files, or files created by legacy applications. Sometimes it is sufficient to import such data once and then keep it in BlackBox documents, sometimes it is necessary to export data into some foreign file format, and it may even be desirable to import data from such a file format when opening a file, and to export data back into the same file format upon saving the file. Of course, the latter only works in a satisfying way if the conversion is truly invertible, i.e., both import and export are loss-free.
The example ObxConv shows a simple ASCII converter, which converts to and from standard BlackBox text views. The module consists of two commands, one is an importer and the other an exporter. Both commands have the same structure: in a loop over all characters of a text, each character is read (from a file or text) and then written (into a text or file).
Converters are often platform-dependent. In our example this can be seen in the assertion which checks the correct file type. Under Windows, it should read
ASSERT(f.type = "TXT", 22) while under Mac OS it should read
ASSERT(f.type = "TEXT", 22)
Furthermore, the characters would have to be converted from the host platform's native character set to (or from) the portable character set used by the BlackBox Component Builder. This is not done here since it would not contribute to demonstrating the converter mechanism per se.
Each BlackBox Component Builder implementation provides its own set of standard converters which are registered and thus made available to the user when the system is started up. A programmer may install additional converters in procedure Config.Setup, by calling the Converters.Register procedure:
Windows:
Converters.Register("ObxConv.ImportText", "ObxConv.ExportText", "TextViews.View", "TXT", {})
Mac OS:
Converters.Register("ObxConv.ImportText", "ObxConv.ExportText", "TextViews.View", "TEXT", {})
Config.Setup is called at the end of the BlackBox Component Builder's bootstrap process, i.e., when the core has been loaded successfully.
For each registered converter, 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 "ObxConv.ImportText" could be mapped to the more telling name "Obx Text" (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 is the following line in the Obx/Rsrc/Strings text:
ObxConv.ImportText Obx Text File
It is conceivable to implement compound converters: an HTML (Hypertext Markup Language) converter for example could use the standard ASCII converter of the BlackBox Component Builder (i.e., module HostTextConv) to perform a conversion from the platform's ASCII format to an BlackBox text. The created text could then be parsed and converted into an equivalent text which included some kind of hypertext link view instead of the textually specified hyperlinks.
ObxConvsources
| Obx/Docu/Conv.odc |
Overview by Example: ObxCount0
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/Count0.odc |
Overview by Example: ObxCount1
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/Count1.odc |
Overview by Example: ObxCtrls
There is no separate documentation.
| Obx/Docu/Ctrls.odc |
Overview by Example: ObxCubes
This example implements a simple rotating cube view. The cube rotates around two axes. It performs 10 state transformations per second and after 25.6 seconds it is back in its starting position. The example below shows a large cube rotating in front of a smaller one. Both cubes are embedded in a form view, which is embedded in the text view that you are currently reading:
What this example shows is the use of actions. Services.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 as in this example operates as a non-preemptive background task.
This example also demonstrates a simple property editor through which the colors of the sides of a cube can be changed. To open the property editor click into the cube while holding down the modifier key (or execute the command below to open the dialog). The property editor always shows the colors of the selected cube. The synchronization between the color fields in the dialog and the selected cube is also performed through the installed action. The colors of the sides are actually changed by a notifier which is attached to each color control in the property dialog. The color white is interpreted as invisible.
"ObxCubes.Deposit; StdCmds.Open"
"StdCmds.OpenToolDialog('Obx/Rsrc/Cubes', 'Cube Colors')"
ObxCubessources
| Obx/Docu/Cubes.odc |
Overview by Example: ObxDb
This example provides two commands to the user. The first, EnterData, takes a text selection as input, and reads it line by line. Each line should consist of an integer number, followed by a string, trailed by a real number. Each such tuple is entered into a globally anchored linear list, sorted by the integer value. The second command, ListData, generates a text which displays the data currently in the list.
ObxDbsources
ObxDb.EnterData ObxDb.ListData ObxDb.Reset
To try out the example, select the following lines, and then click the left commander above:
1 Cray 14.8
3 NEC 16.6
2 IBM 8.3
Now click the middle commander, as a result a window opens with the sorted input. If you repeat both steps, you'll note that the input has been added to the list a second time, and that consequently every item appears twice in the output.
This example has shown how a text can be scanned symbol by symbol, instead of character by character.
| Obx/Docu/Db.odc |
Overview by Example: ObxDialog
This example demonstrates list, selection, and combo interactor fields and their appropriate controls. Furthermore, notifiers and guards are used.
"StdCmds.OpenAuxDialog('Obx/Rsrc/Dialog', 'ObxDialog Demo')"
ObxDialogsources
| Obx/Docu/Dialog.odc |
Overview by Example: ObxExcel
This example how the OLE Automation controller subsystem can be used to program Microsoft Excel. Use the following menu entries to run the examples:
"Show Excel" "" "ObxExcel.ShowExcel" ""
"Read Excel" "" "ObxExcel.ReadExcel" "StdCmds.SingletonGuard"
"Open Chart" "" "ObxExcel.OpenChart" "StdCmds.SingletonGuard"
ShowExcel adds different values to a new worksheet and opens the worksheet as an OLE object in a BlackBox text.
ReadExcel reads a selected worksheet object and writes the contents of the cells into the log.
OpenChart uses the values in a selected worksheet object and opens a corresponding chart in a separate Excel window.
See also the CtlDeveloperManual.
ObxExcelsources
| Obx/Docu/Excel.odc |
Oberon by Example: ObxFact
This example demonstrates the use of module Integers, which implements arbitrary precision integers. The example implements the command ObxFact.Compute, which computes the factorial of an integer selected as text in a text view, and replaces the selection with the result.
Example:
25 -> 15511210043330985984000000
Note: The time required to compute a factorial grows exponentially with the size of the input. For numbers greater than 500 a considerable time will be needed.
ObxFactsources
| Obx/Docu/Fact.odc |
Overview by Example: Fractal Fern
(Example from "Programming in Oberon", by Wirth/Reiser)
1) Compile module ObxRandom
2) Compile module ObxFern
3) Select the following numbers:
120 0 25
0.0 0.85 0.2 -0.15
0.0 0.04 -0.26 0.28
0.0 -0.04 0.23 0.26
0.16 0.85 0.22 0.24
0.0 0.0 0.0 0.0
0.0 1.6 1.6 0.44
0.01 0.85 0.07 0.07
4) Execute the following command: ObxFern.Init
5) Execute the following command: ObxFern.Draw
6) Stop the iteration by pressing the key "s"
| Obx/Docu/Fern.odc |
Overview by Example: ObxFileTree
This example illustrates the use of the TreeControl. The aim is to create a file browser similar to the Windows Explorer. To keep it simple, the user interface will consist of a text field, three buttons, and a TreeControl. When the user types a path to a directory in the text field and clicks on the Display button the files and folders in the given directory are shown in the tree. The user can browse the files and folders in the tree, and a double click on a file opens the file in BlackBox.
The Interactors
To achieve this user interface we need a Dialog.String variable to connect to the text field, we need two procedures to connect to the Display and Open buttons respectively, and we need a Dialog.Tree variable to connect to the TreeControl. We also need a notifier to connect to TreeControl. This notifier should detect a double click on a leaf in the tree and open the corresponding file.
The TreeControl has several properties which can be modified with the property inspector. For this example the default properties are sufficient. In particular the option "Folder icons" should be switched on. This option makes the TreeControl show icons in front of each node in the tree. The leaf nodes get a "file" icon and the nodes that have subnodes get a "folder" icon. This option gives our program the same look and feel as the Windows Explorer.
The only problem is that if a file directory does not contain any files it will be a leaf node and thus look like a file and not a folder. For this purpose the Dialog.TreeNode offers a method called ViewAsFolder, which makes a node in a tree display a folder icon even if it doesn't have any subnodes.
The Implemantation
To implement this, this example uses four procedures:
PROCEDURE BuildDirTree (loc: Files.Locator; parent: Dialog.TreeNode);
PROCEDURE Update*;
PROCEDURE Open*;
PROCEDURE OpenGuard* (VAR par: Dialog.Par);
BuildDirTree recursively adds files and folders to the tree, and also makes sure that the ViewAsFolder attribute is set for nodes that are folders. Update is the procedure that is connected to the Display command button in the user interface. This procedure clears the tree and then calls BuildDirTree. The procedure Open opens the selected folder or file. StdCmds.DefaultOnDoubleClick, which is set as the TreeControl's notifier procedure, executes the default command Open when the TreeControl is double-clicked.
"StdCmds.OpenToolDialog('Obx/Rsrc/FileTree', 'ObxFileTree Demo')"
ObxFileTreesources
| Obx/Docu/FileTree.odc |
Overview by Example: ObxFldCtrls
There is no separate documentation.
| Obx/Docu/FldCtrls.odc |
Overview by Example: ObxGraphs
This example is a view which implements simple bar charts. The implementation consists of a view and a model. The view contains the model, and the model contains a linear list of values. For each of these values, a bar is drawn when the view is restored in a frame. The current list of values can be inspected by clicking with the mouse into the view: as a result, an auxiliary window is opened containing a textual representation of the values. This list of numbers can be edited, selected, and then dropped into the graph view again, to change its current list of values. A model's data (the value list) is always replaced as a whole and never modified incrementally. For this reason, not only shallow but also deep copying of a model can be implemented by copying the model reference (the pointer value), rather than by cloning the model and its contents. The same immutability property has been used in example ObxLines already.
The most interesting part of this view implementation is the handling of drag & drop messages. In order to let the BlackBox Component Builder provide drop feedback (i.e., the temporary outline denoting a graph view as a possible target for dropping a piece of text) the Controllers.PollDropMsg must be handled. In order to actually execute a drop operation (i.e., to let the graph view consume the dropped piece of text), the Controllers.DropMsg must be handled. In our example, the dropped view isn't inserted into the drop target, but rather interpreted as a specification for its new contents.
The handling of the Properties.FocusPref preference is also noteworthy. By setting up this preference, a view can inform its container how it would like to be treated concerning focusing. If this message is not handled, a view is never permanently focused, except if it is the root view. This means that upon clicking into the view, the view gets selection handles, but not a focus border. The focus preference allows to modify this behavior.
Graph views are not meant to be targets of menu commands, i.e., it is not necessary to denote them as focusable. Since they should react on mouse clicks into their interior, they shouldn't be selected either. A view which normally is neither focused nor selected, but still should receive mouse clicks in it, is called a hot focus. A command button is a more typical example of a hot focus. A view can denote itself as a hot focus by setting the hotFocus field of the Properties.FocusPref preference to TRUE.
Truly editable views should set the setFocus field instead of the hotFocus field, so the focus is not lost when the user releases the mouse button.
ObxGraphssources
"ObxGraphs.Deposit; StdCmds.Open"
After having opened a graph view with the command above, select the list of numbers below
10 53 4 14 24 34 60 52 8
drag the selection over the graph view, and then drop it into the graph view. As a result, the graph view shows a number of grey bars, whose heights correspond to the above values (in millimeters). The bar's widths adapt such that all of them together occupy the whole view's width.
Now click into the graph view to get a list of its current values.
| Obx/Docu/Graphs.odc |
Overview by Example: ObxHello0
After you have started the BlackBox Component Builder, you can open the file Hello0 in the Docu directory of the Obx directory. It contains exactly the text you are now reading.
A first example of a Component Pascal module is given below, as an embedded text object:
MODULE ObxHello0;
IMPORT StdLog;
PROCEDURE Do*;
BEGIN
StdLog.String("Hello World"); StdLog.Ln (* write string and 0DX into log *)
END Do;
END ObxHello0.
To compile this module, its source code must first be focused (i.e., set the caret or selection in it). This is done by clicking somewhere in the above source code. Then execute the Compile command in the Dev menu. After the compilation, a message like
compiling "ObxHello0" 104 0
appears in the Log window. It means that module ObxHello0 has been compiled successfully, that a code file has been written to disk containing the compiled code, that this module has a code size of 104 bytes and global variables of 0 bytes size, and that information about the module's interface has been written to disk in a symbol file. New symbol files are created whenever a module is compiled for the first time, or when its interface has changed.
The interface of the above module consists of one exported procedure: ObxHello0.Do. In order to call this procedure, a commander can be used (the little button below):
ObxHello0.Do
Click on this button to cause the following actions to occur: the code for ObxHello0 is loaded into memory, and then its procedure Do is executed. You see the result in the log window:
Hello World
When you click on the button again, BlackBox executes the command immediately, without loading the module's code again: once loaded, modules remain loaded unless they are removed explicitly.
When clicked, a commander takes the string which follows it, and tries to interpret it as a Component Pascal command, i.e., as a module name followed by a dot, followed by the name of an exported, parameterless procedure.
Try out the following examples:
StdLog.Clear
Dialog.Beep
DevDebug.ShowLoadedModules
The list of loaded modules can be inspected by executing the LoadedModules command in the Info menu, or by simply clicking in the appropriate commander above. It will generate a text similar to the following:
module name bytes used clients compiled loaded Update
ObxHello0 ЏЏЏ106 ЏЏЏ0 25.10.1994 20:07:08 25.10.1994 20:08:42
Out ЏЏЏ532 ЏЏЏ1 24.10.1994 13:53:49 25.10.1994 20:08:42
Config ЏЏЏ159 ЏЏЏ0 24.10.1994 13:53:47 25.10.1994 18:31:52
A module can be unloaded if its client count is zero, i.e., if it is not imported by any other module. In order to unload ObxHello0, focus its source text again and then execute Unload in the Dev menu. The following message will appear in the log window:
ObxHello0 unloaded
When you generate the list of loaded modules again, it will look as follows:
module name bytes used clients compiled loaded Update
Out 532 0 24.10.1994 13:53:49 25.10.1994 20:08:42
Config 159 0 24.10.1994 13:53:47 25.10.1994 18:31:52
Note that a module list is just a text which shows a snapshot of the loader state at a given point in time, it won't be updated automatically when you load or unload modules. You can print the text, save it in a file, or edit it without danger that it may be changed by the system. You can force an update by clicking on the blue update link in the text.
In this first example, we have seen how a very simple module looks like, how it can be compiled, how its command can be executed, how commanders are used as convenient alternatives to menu entries during development, how the list of loaded modules can be inspected, and how a loaded module can be unloaded again.
| Obx/Docu/Hello0.odc |
Overview by Example: ObxHello1
Everything in the BlackBox Component Framework revolves around views. A view is a rectangular part of a document; a document consists of a hierarchy of nested views. What you are now looking at is a text view; below is another text view embedded in it:
MODULE ObxHello1;
IMPORT Views, TextModels, TextMappers, TextViews;
PROCEDURE Do*;
VAR t: TextModels.Model; f: TextMappers.Formatter; v: TextViews.View;
BEGIN
t := TextModels.dir.New(); (* create a new, empty text object *)
f.ConnectTo(t); (* connect a formatter to the text *)
f.WriteString("Hello World"); f.WriteLn; (* write a string and a 0DX into new text *)
v := TextViews.dir.New(t); (* create a new text view for t *)
Views.OpenView(v) (* open the view in a window *)
END Do;
END ObxHello1.
ObxHello1.Do
The embedded text view above contains a slightly more advanced hello world program than ObxHello0. It doesn't use module StdLog to write into the log window. Instead, it creates a new empty text, to which it connects a text formatter. A text formatter is an object which provides procedures to write variables of all basic Component Pascal types into a text. In the above example, a string and a carriage return are written to the text, which means that they are appended to the existing text. Since a newly created text is empty, t now contains exactly what the formatter has written into it.
A text is an object which carries text and text attributes; i.e., a sequence of characters and information about font, color, and vertical offset of each character. However, a text does not know how to draw itself; this is the purpose of a text view. (Yes, what you are currently looking at is the rendering of such a view.) When a text view is created, it receives the text to be displayed as a parameter. Several views can be open on the same text simultaneously. When you edit in one view, the changes are propagated to all other views on the same text.
When you create a text, you perform the steps outlined below:
1) create a text model
2) connect a text formatter to it
3) write the text's contents via the formatter
4) create a text view for the model
5) open the text view in a window
In this example, we have seen how to use the text subsystem in order to create a new text.
| Obx/Docu/Hello1.odc |
Overview by Example: ObxLabelLister
This example is described in chapter4 of the BlackBox tutorial.
| Obx/Docu/LabelLister.odc |
Overview by Example: ObxLines
This example implements a view which allows to draw lines with the mouse. Beyond line drawing, the only interaction with such a view is through the keyboard: some characters are interpreted as colors, e.g. typing in an "r" sets a view's foreground color (in which the lines are drawn) to red. These two operations certainly don't constitute a graphics editor yet, but can serve as a sketch for a more useful implementation. Full undo/redo of the two operations is supported, however.
The implementation of ObxLines is simple: there is a view, a model, and a line data structure. The model represents a view's graph, which consists of a linear list of lines. A line is described by its two end points (x0, y0) and (x1, y1). Each view has its own independent foreground color. There is an operation for the entry of a line (a model operation), and an operation for the change of a foreground color (a view operation).
When a line is entered (or the entry is undone), its bounding box is restored. For this purpose, a suitable update message is defined.
There are two interesting aspects of the ObxLines implementation:
The contents of a graph, i.e., the linear list of lines, is immutable. This means that a line which has been inserted in a graph is never modified again. The list may become longer by adding another line with the mouse, but the existing line list itself remains unchanged. For example, an undo operation merely changes the graph to show a shorter piece of its line list, redo shows a larger piece of it again.
An immutable data structure has the nice property that it can be freely shared: copying can be implemented merely by letting another pointer point to the same data structure. There is no danger that someone inadvertently changes data belonging to someone else (aliasing problem). This property is used in the example below when copying the model.
The second interesting feature of ObxLines is the way rubberbanding is implemented. Rubberbanding is the feedback given when drawing a new line, as long as the mouse button is being held down. Procedure HandleCtrlMsg shows a typical implementation of such a mechanism: it consists of a polling loop, which repeatedly polls the mouse button's state. When the mouse has moved, the old rubberband line must be erased, and a new one must be drawn.
Erasing the old rubberband line is done using a temporary buffer. Before entering the polling loop, the frame's visible area is saved in the frame's buffer (one buffer per frame is supported). In the polling loop, when the rubberband line must be erased, its bounding box is restored from the buffer. After the polling loop, the last rubberband line is erased the same way, except that the temporary buffer is disposed of simultaneously.
With the HandlePropMsg procedure, the view indicates that it may be focused, so it can be edited in-place.
This view has a separate model. Because of this, it implements the "model protocol" of a view, i.e., the methods CopyFromModelView, ThisModel, and HandleModelMsg. CopyFromModelView is a model-oriented refinement of CopyFrom; it must be implemented instead of CopyFrom. ThisModel simply returns the view's model. HandleModelMsg receives a model update message and translates it into an update of a view's region, which eventually leads to a restoration of this region on the screen.
ObxLinessources
"ObxLines.Deposit; StdCmds.Open"
| Obx/Docu/Lines.odc |
Overview by Example: ObxLinks
This example demonstrates how a text can be created which contains link views. The text represents the contents of a directory. There is a link for each subdirectory, and a link for each file that can be converted into a view. Thus this example also demonstrates how files and locators are enumerated and how file converters are used.
"ObxLinks.Directory('')"
ObxLinkssources
| Obx/Docu/Links.odc |
Overview by Example: ObxLookup0
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/Lookup0.odc |
Overview by Example: ObxLookup1
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/Lookup1.odc |
Overview by Example: ObxMailMerge
When a business wants to communicate something to all its customers, e.g. the announcement of a new product, it can send out form letters to all its existing customers. Each such letter has the same contents, except for a few differences like the name and address of the respective customer. Mail merge is the process of creating these form letters out of a letter template and a customer database.
This example shows how the BlackBox Component Builder's built-in text component can be used to implement a simple mail merge extension.
Figure 1. Mail Merge Process
The following menu command is installed in menu Obx, to simplify trying out this example:
...
"Merge..." "" "ObxMMerge.Merge" "TextCmds.FocusGuard"
...
Before you execute Obx->Merge..., you need to open a mail merge template. For example, the following templatedocument
(Obx/Samples/MMTmpl) and then execute the Obx->Merge... command. A dialog box will ask you for the address database: open the mail merge datadocument (Obx/Samples/MMData).
As a result, a new text is created which contains a sequence of form letters. When you execute the ShowMarks command in the Text menu, you'll note that the individual letters are separated by page-breaking rulers (the right-most icon in a ruler).
Now let's take a closer look at how the program is implemented. There is one command called Merge, which fetches the template text (the focus), searches for place holders in this text (the fields of the template), then lets the user open the database text, determines for each template field which column of the database text corresponds to the field, creates a new output text, adds an instance of the letter template for every row of the database text, and finally opens the text in a window.
MODULE ObxMailMerge;
PROCEDURE TmplFields (t: TextModels.Model): Field;
PROCEDURE ThisDatabase (): TextModels.Model;
PROCEDURE MergeFields (f: Field; t: TextModels.Model);
PROCEDURE ReadTuple (f: Field; r: TextModels.Reader);
PROCEDURE AppendInstance (f: Field; data, tmpl, out: TextModels.Model);
PROCEDURE Merge*;
END ObxMailMerge.
Listing 2. Outline of the ObxMMerge Program
There are five auxiliary procedures which are called by Merge:
TmplFields analyzes the template text, and returns a list of fields for this text. Each field describes a place holder with its name and its position in the text. Place holders are specified as names between "<" and ">" characters, e.g., <Name>.
ThisDatabase asks the user for a database document, and returns the text contained in this document.
MergeFields determines for every template field the corresponding database column. To make this possible, the first row of the database text must contain the so-called meta data of the database. For mail merge applications, this is simply the symbolic name of every column, e.g., Name or City. This name must be identical to the name used in the template.
Each row is terminated by a carriage return (0DX), and the fields of a row (i.e., the columns) are separated by tabs (09X).
ReadTuple reads one row of the database text, and assigns the string occupied by one database field to every corresponding template field.
AppendInstance appends a copy of the template text to the end of the output text, and then replaces all the place holders by the contents of their respective database fields. These replacements are done from the end of the appended text towards the beginning, so that from/to indices are not invalidated by replacements. This explains why the field list is built up in reverse order, last field first.
Note that each replacement gets the text attributes of the first replaced character, i.e., if the place holder "<Name>" in bold face is replaced by the string "Joe", the resulting replacement will be 'Joe".
ObxMMerge doesn't need to insert page-breaking rulers; instead, the template text contains such a ruler.
ObxMMergesources
| Obx/Docu/MMerge.odc |
Overview by Example: ObxOmosi
Further examples:
Omosi1 Omosi2 Omosi3 Omosi4 Omosi5 Omosi6
An Omosi view consists of an area filled with triangles. Each of these triangles may take on one of four colors. By clicking on a triangle, it changes it color. By shift-clicking, several triangles can be selected, which will change colors simultaneously. By clicking on a triangle with the modifier key held down, a color palette dialog pops up which allows to map this color state to another RGB color.
ObxOmosisources
"ObxOmosi.Deposit; StdCmds.Open"
| Obx/Docu/Omosi.odc |
Overview by Example: ObxOpen0
This example asks the user for a file, opens the document contained in the file, and appends a string to the text contained in the document. Finally, the text (in its text view) is opened in a window.
MODULE ObxOpen0;
IMPORT Files, Converters, Views, TextModels, TextMappers, TextViews;
PROCEDURE Do*;
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
v: Views.View; t: TextModels.Model; f: TextMappers.Formatter;
BEGIN
loc := NIL; name := ""; conv := NIL; (* no defaults for Views.Old *)
v := Views.Old(Views.ask, loc, name, conv); (* ask user for a file and open it as a view *)
IF (v # NIL) & (v IS TextViews.View) THEN (* make sure it is a text view *)
t := v(TextViews.View).ThisModel(); (* get the text view's model *)
f.ConnectTo(t);
f.SetPos(t.Length()); (* set the formatter to the end of the text *)
f.WriteString("appendix"); (* append a string *)
Views.OpenView(v) (* open the text view in a window *)
END
END Do;
END ObxOpen0.
After compilation, you can try out the above example:
ObxOpen0.Do
With this example, we have seen how the contents of a document's root view can be accessed, and how this view can be opened in a window after its contents have been modified. In contrast to ObxHello1, an existing text has been modified; by first setting the formatter to its end, and then appending some new text.
Note that similar to the previous examples, views play a central role.
In contrast to traditional development systems and frameworks, files, windows, and applications play only a minor role in the BlackBox Component Framework, or have completely disappeared as abstractions of their own. On the other hand, the view has become a pivotal abstraction. It is an essential property of views that they may be nested, to form hierarchical documents.
These aspects of the BlackBox Component Framework constitute a fundamental shift
from monolithic applications to software components
from interoperable programs to integrated components
from automation islands to open environments
from application-centered design to document-centered design
| Obx/Docu/Open0.odc |
Overview by Example: ObxOpen1
This example is a variation of the previous one; instead of opening a view it stores it back in some file.
MODULE ObxOpen1;
IMPORT Converters, Files, Views, TextModels, TextMappers, TextViews;
PROCEDURE Do*;
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
v: Views.View; t: TextModels.Model; f: TextMappers.Formatter;
res: LONGINT;
BEGIN
loc := NIL; name := ""; conv := NIL;
v := Views.Old(Views.ask, loc, name, conv);
IF (v # NIL) & (v IS TextViews.View) THEN
t := v(TextViews.View).ThisModel();
f.ConnectTo(t);
f.SetPos(t.Length());
f.WriteString("appendix");
Views.Register(v, Views.ask, loc, name, conv, res) (* ask the user where to save the document *)
END
END Do;
END ObxOpen1.
ObxOpen1.Do
In this example we have seen how a view can be stored into a file.
| Obx/Docu/Open1.odc |
Overview by Example: ObxOrders
ObxOrders is a more realistic example of a program which uses forms for data entry and data manipulation. It lets the user enter new orders, browse through existing orders, and save all orders into a file, or load them from a file. A dialog always shows the current order. For this order, an invoice text can be generated, ready to be printed.
The order data is stored in a very simple main memory database: each order is represented as a record, and the orders are connected in a doubly-linked ring with a dummy header element. One element of a ring thus contains a next and a prev pointer, as well as the data of one order. In this case, the data is directly represented as a variable of the interactor type which is used for data entry. Note that this approach is only possible in very simple cases; normally an interactor would only represent a subset of a tuple stored in the database, and the database representation would be independent of any specific interactor.
The other aspect of our example program which is simpler than in typical applications is that the database is global: the doubly-linked ring is anchored in a global variable, so there is at most one order database open at any given point in time.
This example has four noteworthy aspects: The procedure NewRuler shows how a new text ruler with specific properties can be created, and in procedure Invoice it can be seen how the text font style can be changed to bold and back to normal when creating a text.
Thirdly, the dialog uses guard commands to disable and enable controls in the dialog: Depending on whether there currently is an open database, the data entry, invoice generation, etc. controls are enabled, otherwise disabled. Depending on whether the current order is the last (first) one, the Next (First) button is disabled, otherwise enabled.
Fourth, the formatter procedure WriteView is used twice to insert a view into the text: first a ruler view is written, and a bit later a standard clock view is written to the text.
ObxOrderssources
Maindialog
"Delete"dialog
"StdCmds.OpenAuxDialog('Obx/Rsrc/Orders', 'Order Processing')"
In Obx/Samples/Odata there is some sample data.
| Obx/Docu/Orders.odc |
Overview by Example: ObxParCmd
This example shows how a command button's context can be accessed. For example, a button in a text may invoke a command, which reads the text immediately following the command. This text can be used as an input parameter to the command.
ObxParCmd implements two commands which scan the text behind a command button for a string. In the first command, the string is written to the log:
"this is a string following a command button"
In this way, tool texts similar to the tools of the original ETH Oberon can be constructed.
In the second example, the string following the button is executed as a command, thus operating in a similar way as a commander (-> DevCommanders):
"DevDebug.ShowLoadedModules"
ObxParCmdsources
| Obx/Docu/ParCmd.odc |
Overview by Example: ObxPatterns
This view displays a series of concentric rectangles. The view contains no special state; its display is completely determined by its current size alone.
The view implementation is very simple. However, there are three aspects of this program which are noteworthy:
First, although the view has no state, it still extends the Internalize and Externalize procedures bound to type View. This is done only in order to store a version number of the view. It is strongly recommended to store such a version number even in the simplest of views, in order to provide file format extensibility for future versions of the view implementation.
Second, the view contains no special state of its own. However, its display may differ, depending on its current size. A view does not manage its own size, since its size is completely determined by the context in which the view is embedded. A view can determine its current size by asking its context via the context's GetSize procedure.
Third, while a view's size is completely controlled by its context, the context still may (but need not!) cooperate when the size is determined. For example, when a view is newly inserted into a container, the container may ask the view for its preferred size; or when it wants to change the embedded view's current size, it may give the view the opportunity to define constraints on its size, e.g., by limiting width or height to some minimal or maximal values. The container can cooperate by sending a size preference (Properties.SizePrefs) to the embedded view, containing the proposed sizes (which may be undefined). The view thus gets the opportunity to modify these values to indicate its preferences.
ObxPatternssources
"ObxPatterns.Deposit; StdCmds.Open"
Note: in order to change the pattern view's size, first select it using command Edit->Select Document, then manipulate one of the resize handles.
| Obx/Docu/Patterns.odc |
Overview by Example: ObxPDBRep0
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/PDBRep0.odc |
Overview by Example: ObxPDBRep1
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/PDBRep1.odc |
Overview by Example: ObxPDBRep2
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/PDBRep2.odc |
Overview by Example: ObxPDBRep3
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/PDBRep3.odc |
Overview by Example: ObxPDBRep4
This example is described in chapter5 of the BlackBox tutorial.
| Obx/Docu/PDBRep4.odc |
Overview by Example: ObxPhoneDB
This example is described in chapter3 of the BlackBox tutorial.
DEFINITION ObxPhoneDB;
TYPE String = ARRAY 32 OF CHAR;
PROCEDURE LookupByIndex (index: INTEGER; OUT name, number: String);
PROCEDURE LookupByName (name: String; OUT number: String);
PROCEDURE LookupByNumber (number: String; OUT name: String);
END ObxPhoneDB.
Module ObxPhoneDB provides access to a phone database. Access may happen by index, by name, or by number. An entry consists of a name and a phone number string. Neither may be empty. The smallest index is 0, and all entries are contiguous.
PROCEDURE LookupByIndex (index: INTEGER; OUT name, number: ARRAY OF CHAR)
Return the <name, number> pair of entry index. If the index is too large, <"", ""> is returned.
The procedure operates in constant time.
Pre
index >= 0 20
Post
index is legal
name # "" & number # ""
index is not legal
name = "" & number = ""
PROCEDURE LookupByName (name: ARRAY OF CHAR; OUT number: ARRAY OF CHAR)
Returns a phone number associated with name, or "" if no entry for name is found.
The procedure operates in linear time, depending on the size of the database.
Post
name found
number # ""
name not found
number = ""
PROCEDURE LookupByNumber (number: ARRAY OF CHAR; OUT name: ARRAY OF CHAR)
Returns the name associated with number, or "" if no entry for number is found.
The procedure operates in linear time, depending on the size of the database.
Post
number found
name # ""
number not found
name = ""
| Obx/Docu/PhoneDB.odc |
Overview by Example: ObxPhoneUI
This example is described in chapter4 of the BlackBox tutorial.
| Obx/Docu/PhoneUI.odc |
Overview by Example: ObxPhoneUI1
This example is described in chapter4 of the BlackBox tutorial.
| Obx/Docu/PhoneUI1.odc |
Oberon by Example: ObxPi
This example demonstrates the use of module Integers for computing with arbitrary precision decimals. The example implements the command ObxPi.WritePi, which computes n decimal digits of the constant Pi and writes the result into the log. The command ObxPi.Pi only computes Pi, without printing the result. It can be used to measure the efficiency of the arbitrary precision integer package.
For computation, the rule
Pi = 16 * atan(1/5) - 4 * atan(1/239)
is used where atan is approximated with its Taylor series expansion at x = 0:
atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
The computation is performed with integers only. Each decimal x is represented as integer x * 10^d where d is the number of decimal digits to the right of the decimal point. Arithmetic operations on decimals are performed using integer arithmetic. This way, the results are chopped, not rounded. For each operation, an error of at most one ulp may be introduced. Therefore, the computation of Pi is performed with some guard digits. The final result is chopped to the desired number of decimal digits. If you want to compute more digits of Pi you have to increase the number of guard digits. Use Ceiling(Log10(1.43*n)) guard digits in order to compute n digits of Pi.
Example:
"ObxPi.WritePi(1000)"
31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989
ObxPisources
| Obx/Docu/Pi.odc |
Overview by Example: ObxRandom
This example is adapted from the book "Programming in Oberon", by Wirth/Reiser.
| Obx/Docu/Random.odc |
Oberon by Example: ObxRatCalc
This example implements a simplifier for rational numbers of arbitrary precision. Expressions to be simplified are built up from integer numbers, the operators "+", "-", "*", "/", "^", and parentheses. Exponents ("^") must be integer numbers and their absolute value must not exceed MAX(INTEGER).
The result is either an integer or a rational number (command ObxRatCalc.Simplify), or a floating point number (ObxRatCalc.Approximate).
The implementation of ObxRatCalc uses the Integersmodule, which provides a data type for arbitrary precision integers and operations on them. The calculator works on arithmetic expressions, such as the following:
Source Expression ObxRatCalc.Simplify ObxRatCalc.Approximate
((100 + 27 - 2) / (-5 * (2 + 3))) ^ (-3) = -1 / 125 = -8*10^-3
999999999 * 999999999 / 81 = 12345678987654321
1234567890 / 987654321 = 137174210 / 109739369 = 1.2499999886093750001423828...
30.2 + 60.5 = 907 / 10 = 90.7
Note that the undo/redo mechanism can be used after an evaluation.
Syntax of input:
expression := ["-"] {term addop} term.
term := {factor mulop} factor.
factor := ("(" expression ")" | integer) ["^" factor].
integer := digit {digit} [ "." digit {digit} ].
addop := "+".
mulop := "*" | "/".
Menu entries in "Obx" menu:
"Simplify" "" "ObxRatCalc.Simplify" "TextCmds.SelectionGuard"
"Approximate" "" "ObxRatCalc.Approximate" "TextCmds.SelectionGuard"
ObxRatCalcsources
| Obx/Docu/RatCalc.odc |
Overview by Example: ObxSample
This example is described in chapter3 of the BlackBox tutorial.
| Obx/Docu/Sample.odc |
Oberon by Example: ObxScroll
By default, a view is always displayed in full size where the preferred size can be specified through the Properties.SizePref message. However, sometimes the contents of a view is too large to be shown completely and therefore scrolling of the view's contents within its frame must be supported. An example of views that support scrolling are the text views.
There exists a generic mechanism to implement scrolling by simply changing the scrolled frame's origin. The standard document container uses this feature. Every view which is opened in its own window is contained in a document container, therefore the generic mechanism is available to every root view. The same mechanism could also be offered for embedded views, through a wrapper which scrolls the view's frame on a pixel basis. However, if you want to support a scrolling behavior beyond pixel scrolling, or if the efficient implementation of a view depends on keeping frames small, then explicit handling of scrolling is necessary.
In this example we describe the mechanism ("protocol") a view needs to implement in order to support scrolling. As an example we present the implementation of a 10 by 10 checkers board view (see Figure 1) which can be scrolled within its frame. If this view is scrolled line by line, then the view is displaced field by field. Additionally, this view can also be scrolled if it is embedded in any container that has scrollbars. To scroll an embedded view it must be focus and the modifier key must be hold down when the cursor is over a scrollbar.
Figure 1
If a view wants to support scrolling operations, it must store the current scroll position in its instance variables. In our example, the coordinates of the upper left field (e.g., (6,2)) describe the scroll position. Only the visible fields need to be drawn when the view is restored.
To poll the current scroll state, the framework sends a Controllers.PollSectionMsg to the view. According to the information the view returns, the appearance of the scrollbars is determined. In this message, wholeSize denotes the width or height of the focus view's contents in arbitrary coordinates, and partSize describes the focus view's width or height in the same coordinates (i.e., how large is the view compared to the whole thing). The latter value is used to determine the size of the thumb in the scroll bar (varying thumb sizes are not supported by all window systems). The position of the thumb within the scroll bar is determined according to the value of the field partPos, which specifies the view's origin. The value of partPos must be greater or equal to zero and smaller or equal to the difference between the whole size and the part size.
In our example, all these values are specified in terms of rows or columns. partSize is set to the view's width or height divided by the width or height of one field, and partPos is set to the coordinate of the upper left field. For the above example view the part size is four. The value of wholeSize depends on the scroll position. If the part size is smaller than the difference between the board size and the part position, then wholeSize is set to 10, i.e., to the board size. Otherwise, the part size is greater than the visible fields of the checkers board and this empty space has to be added to the whole size of the view. The latter situation may occur if the view is enlarged, as the scroll position does not change if the view is resized.
When the view is scrolled, a Properties.ScrollMsg is sent to the view. This message specifies whether a horizontal or a vertical scroll operation should be performed, and it also specifies whether the view should scroll by increments or decrements of one line or page, or whether it should scroll to a given absolute position. Here again we must assert that the view is not scrolled outside its frame. If absolute scrolling is performed, then the position to be scrolled to is specified in the same coordinates that the PollSectionMsg uses.
All other methods in the source code are straight-forward. The CopyFrom method is needed to initialize a copy of the view with the same scroll position, and the Externalize and Internalize methods allow to make the scroll position persistent. Note, that the scroll position is only persistent for embedded views. For root views, the scroll position is normalized upon externalization, i.e., it is set to (0,0). Whether or not a view should normalize its persistent state is tested with the function Normalize which is defined in the context of the view. Embedded views keep their current scroll position when stored, i.e., the scroll position is not normalized.
The HandlePropMsg method finally specifies the default size of a newly generated view (depending on its scroll position); it indicates that it wants to become focus (otherwise embedded checkers views could not be scrolled); and it indicates that the size of root views is automatically adapted to the window's size.
The Deposit and DepositAt commands create and deposit a new checker view. If the scroll position is (x,y), then the default width of the view is 10-x times the cell size and the default height is 10-y times the cell size.
Further improvements of this example are possible. For example, the scroll operations could be implemented as genuine operations that can be undone. Note however, that these operations should only be undoable for views which are not embedded in a root context. Use the Normalize method of the context to determine whether the operations need to be undoable or not.
"ObxScroll.Deposit; StdCmds.Open"
ObxScrollsources
| Obx/Docu/Scroll.odc |
Overview by Example: ObxStores
There is no separate documentation.
| Obx/Docu/Stores.odc |
Map to "Overview by Example"
Text Commands
ObxHello0docu/sources write "Hello World" to log
ObxHello1docu/sources write "Hello World" to new text
ObxOpen0docu/sources open text document from a file
ObxOpen1docu/sources modify a text document on a file
ObxCapsdocu/sources change string to uppercase
ObxDbdocu/sources manage sorted list of records
ObxTabsdocu ObxTabssources transform some tabs into blanks
ObxMMergedocu ObxMMergesources mail merge of template and database
ObxParCmddocu ObxParCmdsources interpret text which follows a command button
ObxLinksdocu ObxLinkssources create a directory text with hyperlinks
ObxAsciidocu ObxAsciisources traditional text file I/O
Form Commands
ObxAddress0docu/sources declare interactor for address dialog
ObxAddress1docu/sources write address to new text document
ObxAddress2docu/sources append address to existing text document
ObxOrdersdocu ObxOrderssources simple order processing example
ObxControlsdocu ObxControlssources guards and notifiers
ObxDialogdocu ObxDialogsources selection and combo boxes
ObxUnitConvdocu ObxUnitConvsources dialog box that converts between inches and points
ObxFileTreedocu ObxFileTreesources using a tree control to list files and directories
Other Commands
ObxTrapdocu ObxTrapsources trap demo
ObxFerndocu ObxFernsources fractal fern as in Wirth/Reiser book
ObxConvdocu ObxConvsources file converter
ObxActionsdocu ObxActionssources actions as background tasks
ObxFactdocu ObxFactsources factorials calculated with arbitrary precision integers
ObxPidocu ObxPisources pi calculated with arbitrary precision integers
ObxRatCalcdocu ObxRatCalcsources rational number calculator
Simple Views
ObxPatternsdocu ObxPatternssources view with rectangular pattern
ObxCalcdocu ObxCalcsources calculator
ObxOmosidocu ObxOmosisources editor for 3-D structures
ObxCubesdocu ObxCubessources actions as animation engines (rotating cube)
ObxTickersdocu ObxTickerssources actions as animation engines (stock ticker)
ObxScrolldocu ObxScrollsources demonstration of scrolling mechanism
Control Views
ObxButtonsdocu ObxButtonssources how to implement your own controls
not available ObxCtrls slider control
not available ObxFldCtrls text field control with special behavior
Editor Views
ObxLinesdocu ObxLinessources view which allows to draw lines
ObxGraphsdocu ObxGraphssources bar chart which interprets dropped text
ObxBlackBoxdocu ObxBlackBoxsources deduction game
Wrapper Views
ObxWrappersdocu ObxWrapperssources sample wrapper view
Special Container Views
ObxTwinsdocu ObxTwinssources two vertically arranged text views
ObxTabViewsdocu ObxTabViewssources tabbed views
General Container Views
Formsubsystemmap complete sources of form subsystem
ObxContIterdocu ObxContItersources set focus in a particular control in some container
Other Examples
not available ObxStores example of how to use Stores as graph nodes
Communication Examples (part of the Comm subsystem)
CommObxStreamsServer implements a simple server using CommStreams
docu sources
CommObxStreamsClient implements a simple client using CommStreams
docu sources
Examples used in the On-Line Tutorial
ObxSample, ObxPhoneDB, ObxPhoneUI, ObxPhoneUI1, ObxControlShifter, ObxLabelLister,
ObxPDBRep0, ObxPDBRep1, ObxPDBRep2, ObxPDBRep3, ObxPDBRep 4,
ObxCount0, ObxCount1, ObxLookup0, ObxLookup1,
ObxViews0, ObxViews1, ObxViews2, ObxViews3, ObxViews4, ObxViews5, ObxViews6,
ObxViews10, ObxViews11, ObxViews12, ObxViews13, ObxViews14.
Windows-specific Examples
ObxBitmapdocu ObxBitmapsources shows a Windows bitmap
ObxExceldocu ObxExcelsources reads and writes Excel spreadsheets
ObxWordEditdocu ObxWordEditsources uses the Word Automation Interface
| Obx/Docu/Sys-Map.odc |
Overview by Example: ObxTabs
This example demonstrates a simple text transformation: the first, second and seventh tab character in each text line, starting from the beginning of a text selection, is transformed into a blank. Actually, this command was used to prepare some of the addresses to which the first issue of The Oberon Tribune was sent.
ObxTabssources
To use the command, select the beginning of the address list (i.e., the "Mr. Alan..." string) and then click on the commander below:
ObxTabs.Convert
Mr. Alan Taylor Moon, Inc. EDP department Upping Street 10 23987 Surlington Lunaland
Ms. Dianna Gloor Future SW Corp. Marketing Manhatten Blvd. 93842 Powderdale Otherland
| Obx/Docu/Tabs.odc |
Overview by Example: ObxTabViews
The property inspector for StdTabViews supplies a graphical user interface for creating and editing StdTabViews. This user interface is sufficient for most applications. However, if tabs need to be added and removed dynamically during runtime, the programming interface of StdTabViews needs to be used.
This example creates a StdTabViews.View with three tabs to start with. Then new tabs can be added or the selected tab can be deleted in runtime. Any kind of views can be added to a StdTabViews.View. In this example one ObxCube-view is added and the same ObxCalc-view is added several times. This shows another charactaristic of StdTabViews; when a view is added it is copied. Eventhough the same view is used to create several tabs, they all have their own view internally. You can easily try this by typing a number into a calculator view, then changing tab to another calculator view and type in another number. When you switch back to the first calculator it still displays the first number.
The example also installs a simple notifier which simply displays the notify message in the log.
Here you can try the example:
"ObxTabViews.Deposit; StdCmds.Open"
To add a new calculator view, use this command:
ObxTabViews.AddNewCalc
To delete the selected tab, use this command:
ObxTabViews.DeleteTab
ObxTabViewssources
| Obx/Docu/TabViews.odc |
Overview by Example: ObxTickers
This example implements a simple stock ticker. The curve which is displayed shows a random walk. The black line is the origin, at which the walk started. If the curve reaches the upper or lower end of the view, then the origin is moved accordingly.
What this example shows is the use of actions. Services.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 as in this example operates as a non-preemptive background task.
"ObxTickers.Deposit; StdCmds.Open"
ObxTickerssources
| Obx/Docu/Tickers.odc |
Overview by Example: ObxTrap
This example contains a programming error which leads to a run-time trap. It can be used to gain experience with the trap mechanism and the information shown in the trap viewer.
ObxTrap.Do
ObxTrapsources
| Obx/Docu/Trap.odc |
Overview by Example: ObxTwins
ObxTwins is an example of a container view. Container views come in mainly two flavours: dynamic containers, which may contain an arbitrary and variable number of other views that may be of any type. On the other hand, static containers contain an exactly predetermined number of views, and often the types and layout of these views are predetermined and cannot be changed.
Our example shows the implementation of a static container; for an example of a dynamic container please see the formsubsystem.
ObxTwins implements a view which shows two subviews, a smaller one at the top, and a larger one at the bottom. Both of these views are editable text views; one of them is the current focus. The two views are not treated exactly in the same way: the vertical scroll bar of the twin view always shows the state of the bottom view, even if the top view is focused. There are various ways in which such a twin view can be used. For example, the top view might be used to hold a database query, whose result appears in the bottom view. Or a "chatter" application could be written, with one's own input in the top view, and the partner's messages in the bottom view.
The twin view anchors its embedded views in two context objects (extensions of Models.Context). Such a context contains a view, its bounding box, and a backpointer to the twin view. A context is the link between a container and a contained view; it allows the contained view to communicate with its container. For this purpose, the contained view has a pointer to its context. Via this pointer, the view can access its environment; e.g., to ask what its current size is, or to ask for a size change or another favour from its container.
A context buffers the bounding box of its view; the twin may change the layout of the contained views by calling procedure RecalcLayout, which updates the two context objects in some appropriate way. In a more typical example, the top view would have a constant height ђ for demonstration purposes, ObxTwins shows a more dynamic layout, where the widths remain constant, but the heights are 1/3 for the top view and 2/3 for the bottom view.
The most interesting part of this example is the view's HandleCtrlMsg procedure. It handles incoming messages in three different ways. Normally, it just forwards the message to the currently focused subview. Messages which are related to scrolling (Controllers.PollSectionMsg, Controllers.ScrollMsg, Controllers.PageMsg) are always forwarded to the bottom view, independent of the current focus. And finally, cursor messages (Controllers.CursorMessage) are always forwarded to the view under the cursor position.
The twin view can be implemented with or without its own model. In this example, an empty dummy model is used. It does not contain state, and it is not externalized/internalized. Its single purpose is to allow more flexible copy behavior. A view without model implements the CopyFromSimpleView method, which is always a deep copy. A view with a model implements the CopyFromModelView method instead, which may be used for a deep copy, a shallow copy, or the copying with a new model (Views.CopyWithNewModel). Note that if you have an application where it is not useful to have several windows open on the same twin view, then you can completely eliminate the twin view's model.
These twins are unorthodox in that their embedded views are not contained in their shared model, as is usual for a normal BlackBox container. Rather, the embedded views are managed (via context objects) directly by the twin views, using separate copies of the embedded views if there are several twin views for the same twin model. The reason for this strange situation is that this allows the embedded views to become visible in different sizes and layouts, depending on the size or other properties of the specific twin view. In this case here, the view sizes are different depending on the twin view size, in particular its height. In effect, the embedded views are shallow-copied and thus behave like they had been opened directly in two different windows of the same document. For example, one text view may have hidden rulers and another one may have visible rulers, and the scrolling positions may be different.
However, note that more orthodox containers would forego this flexibility and use a more standard way of treating the embedded views, by putting them into the twin model.
ObxTwinssources
"ObxTwins.Deposit; StdCmds.Open"
| Obx/Docu/Twins.odc |
Overview by Example: ObxUnitConv
This example demonstrates a simple dialog box that allows to convert between inches and desktop publishing points. The dialog box is a form in mask mode, and embedded below in the text:
ObxUnitConvsources
| Obx/Docu/UnitConv.odc |
Overview by Example: ObxViews0
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views0.odc |
Overview by Example: ObxViews1
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views1.odc |
Overview by Example: ObxViews10
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views10.odc |
Overview by Example: ObxViews11
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views11.odc |
Overview by Example: ObxViews12
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views12.odc |
Overview by Example: ObxViews13
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views13.odc |
Overview by Example: ObxViews14
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views14.odc |
Overview by Example: ObxViews2
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views2.odc |
Overview by Example: ObxViews3
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views3.odc |
Overview by Example: ObxViews4
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views4.odc |
Overview by Example: ObxViews5
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views5.odc |
Overview by Example: ObxViews6
This example is described in chapter6 of the BlackBox tutorial.
| Obx/Docu/Views6.odc |
ObxWordEdit
This example shows some possible usage of the Automation interface of Microsoft Word 9.0. See also under:
mk:@MSITStore:I:\MSDN\off2000.chm::/html/Off2000LangRef.htm
in the MSDN Library.
For more information about automation controllers in BlackBox see the CtlDocu and the CtlWord9Docu.
The module consists of a set of commands. Most of them require that the module is connected to a Word application. Before using them, ObxWordEdit.Connect or ObxWordEdit.Start must be called. The commands which act on a document also require that a document is open. Always the active document is used.
ObxWordEditsources
Connecting / Disconnecting
ObxWordEdit.Connect
Connects to a Word application. If Word is not running, it is started.
ObxWordEdit.Disconnect
Disconnects from Word. If nobody else is using the application, it is terminated.
Starting / Quitting
ObxWordEdit.Start
Starts a new Word application.
ObxWordEdit.Quit
Quits the Word.
ObxWordEdit.Restart
Restarts Word.
File
ObxWordEdit.NewDoc
Creates a new document using CtlWord.NewDocument() and makes it visible.
The document is created in the oldest running Word. If there is no Word running, it is started.
ObxWordEdit.CreateDoc
Creates a new, visible document using CtlWord.Application.Documents().Add.
It is only visible, if the application is visible.
ObxWordEdit.CreateInvisibleDoc
Creates a new, invisible document. It is also invisible, if the application is visible.
ObxWordEdit.OpenDocTest
Opens a test file.
ObxWordEdit.CloseDoc
Closes the active document without saving.
ObxWordEdit.SaveAndCloseDoc
Saves the active document and closes it.
ObxWordEdit.SaveDoc
Saves the active document.
ObxWordEdit.Print
Prints the active document.
Application
ObxWordEdit.DispDocs
Displays the full names of all the open documents.
ObxWordEdit.DispFontNames
Displays the names of the available fonts in Word.
ObxWordEdit.DispBBFontNames
Displays the names of the available fonts in BlackBox. There are more than in Word.
ObxWordEdit.DispLanguages
Displays the languages available in Word.
ObxWordEdit.DispLanguagesAndDictionaries
Displays the languages available in Word and whether they have a dictionary.
Attention: ActiveSpellingDictionary traps if there is no dictionary available...
ObxWordEdit.UseSmartCutPaste
Sets the option SmartCutPaste.
Visibility
ObxWordEdit.MakeWordVisible
Makes all documents visible, also the ones that were created invisible.
ObxWordEdit.MakeWordInvisible
Makes all documents invisible.
ObxWordEdit.MakeWinVisible
Makes the first window of the active document visible.
ObxWordEdit.MakeWinInvisible
Makes the first window of the active document invisible.
ObxWordEdit.IsVisible
Displays whether the first window of the active document is visible.
Document
ObxWordEdit.Undo
Undoes the last action. Actions, such a typing characters, can be merged to one action by Word.
ObxWordEdit.Redo
Redoes the last undone action.
ObxWordEdit.Protect
Protects the active document.
ObxWordEdit.Unprotect
Unprotects the active document.
Accessing the Content of a Document
ObxWordEdit.DispContent
Displays the content of the active document.
ObxWordEdit.DispParagraphs
Displays the paragraphs of the active document.
ObxWordEdit.DispListParagraphs
Displays the ListParagraphs of the active document.
ObxWordEdit.DispLists
Displays the Lists of the active document.
ObxWordEdit.DispWords
Displays the Words of the active document, using the CtlWord.Document.Words method.
ObxWordEdit.DispWords2
Displays the Words of the active document, using the CtlWord.Range.Next method.
ObxWordEdit.DispWords3
Displays the Words of the active document, using the CtlWord.Range.MoveEnd method.
ObxWordEdit.DispCharacters
Displays the Characters of the active document.
ObxWordEdit.DispSentences
Displays the Sentences of the active document.
ObxWordEdit.DispStoryRanges
Displays the StoryRanges of the active document.
ObxWordEdit.DispRuns
Should write the runs of the active document, but it does not work! How can we get the runs?
Editing Text
ObxWordEdit.AppendThisText
Appends "This Text" to the end of the active document. This means that it is insert in front of the last 0DX.
ObxWordEdit.OverwriteLastCharWithA
Overwrites the last character, which is always a 0DX, with "A". Word inserts a new 0DX at the end.
ObxWordEdit.CopyText
Copies and inserts the first 10 chars at the beginning of the active document.
ObxWordEdit.CopyFormattedText
Copies and inserts the first 10 chars at the beginning of the active document, formatted.
ObxWordEdit.DeleteText
Deletes the first 10 character of the active document.
Font
ObxWordEdit.Disp2ndParagraphFontName
Displays the name of the font of the second paragraph of the active document, if it is defined.
ObxWordEdit.Is1stParagraphBold
Displays whether the first paragraph of the active document is bold or not, if it is defined.
ObxWordEdit.Get1stParagraphFontSize
Displays the size of the font of the first paragraph of the active document, if it is defined.
ObxWordEdit.Disp1stParagraphFontSize
Displays the size of the font of the first paragraph of the active document, if it is defined.
Performance
ObxWordEdit.Performance
Shows how much slower it is to call a procedure in Word via the automation interface.
| Obx/Docu/WordEdit.odc |
Overview by Example: ObxWrappers
This example implements a wrapper. Wrappers are views which contain other views. In particular, a wrapper may have the same size as the view(s) that it wraps. In this way, it can combine its own functionality with that of the wrapped view(s).
For example
a debugging wrapper lists the messages received by the wrapped view into the log
a background wrapper adds a background color, over which its wrapped view is drawn (which typically has no background color, i.e., which has a transparent background)
a layer wrapper contains several layered views, e.g., a graph view overlaid by a caption view
a terminal wrapper contains a terminal session and wraps a standard text view displaying the log of the session
a bundling wrapper filters out controller messages, such that the wrapped view becomes read-only etc., the sky's the limit! Wrappers demonstrate the power of composition, i.e., how functionality of different objects can be combined in a very simple manner, without having to use complex language mechanisms such as inheritance.
Our example wrapper simply echoes every key typed into the log.
The wrapper implementation is noteworthy in three respects. First, a wrapper reuses the context of the view which it wraps, it has no context of its own. This is only possible because the wrapper is exactly as large as the wrapped view, because a shared context cannot return different sizes in its GetSize method.
Second, it uses the wrapped view's model (if it has one!) as its own, this means that its ThisModel method returns the wrapped view's model, and that CopyFromModelView propagates the new model to the wrapped view.
Third, the wrapper is implemented in a flexible way which allows it to wrap both views with or without models. This flexibility is concentrated in procedure CopyFromModelView (which admittedly is a bad name in those special cases where the wrapped views don't have models).
ObxWrappers.Wrap (* select view (singleton) before calling this command *)
ObxWrappers.Unwrap (* select view (singleton) before calling this command *)
(* <== for example, select this view *)
and then type in some characters, and see what happens in the log.
ObxWrapperssources
| Obx/Docu/Wrappers.odc |
Описание системы примерами: ObxActions
(C) Перевод на русский язык: Чернышов Л.Н., 2005.
Этот пример демонстрирует, как могут быть реализованы фоновые задачи с помощью действий (actions). Действие - объект, который исполняет некоторое действие позже, когда система не занята, то есть, между действиями пользователя. Действие может быть назначено к исполнению как можно скорее, или по прошествии некоторого времени. После выполнения действие может перепланировать само себя на более позднее время. Таким образом, действие может работать как фоновая задача, получая процессорное время всякий раз, когда система не занята. Такая стратегия называется совместной мультизадачностью (cooperative multitasking). Для того чтобы выполняться, действие не должно делать массивных вычислений, потому что это увеличило бы время отклика системы. Длительные вычисления должны быть разложены на части, занимающие малое время. Это демонстрируется алгоритмом, который вычисляет простые числа до данного максимума в виде фоновой задачи. Действие используется для выполнения пошагового вычисления. Каждое новое найденное простое число записывается в текст. Этот текст остается невидимым пока продолжаются вычисления. Действие проверяет, достигнут ли максимум, установленный пользователем. Если этого еще не произошло, то действие назначает себя для дальнейшего выполнения. В противном случае оно открывает окно со списком простых чисел, то есть, отображение созданного текста.
"StdCmds.OpenAuxDialog('Obx/Rsrc/Actions', 'Prime Calculation')"
ObxActionssources | Obx/Docu/ru/Actions.odc |
Описание системы примерами: ObxAddress0
Одним из отличительных признаков современных пользовательских интерфейсов является немодальность диалоговых окон и форм ввода данных. Они изображают поля ввода данных, кнопки нажатий, флажки (check boxes) и вариации так называемых элементов управления (controls). Блэкбокс трактует эту проблему по-своему:
новые элеметы управления могут реализовываться в Компонентном Паскале; они суть не что иное, как специализированные отображения (views), нет никаких существенных различий между элементами управления и объектами-документами;
каждое отображение, которое может содержать другие отображения (т.е. отображение-контейнер), может также содержать элементы управления, нет существенных различий между контейнерами элементов управления и контейнерами документов;
каждый общий контейнер отображений при желании может быть превращён в маску ввода;
некоторые элементы управления могут быть непосредственно связаны с переменными программы;
для гарантирования согласованности связывание производится автоматически с учетом информации о типах переменных;
начальное представление формы может быть сгенерировано автоматически без объявления записи (без объединения переменных в одну запись - прим. пер.);
формы могут быть отредактированы в интерактивном режиме и сохраненты как документы, никакой промежуточной генерации кода не требуется;
формы могут использоваться "вживую", во время их редактирования;
макет формы может быть создан или изменен программой на Компонентным Паскале, если это желательно.
Некоторые из этих аспектов продемонстрированы следующим примером:
MODULE ObxAddress0;
VAR
adr*: RECORD
name*: ARRAY 64 OF CHAR;
city*: ARRAY 24 OF CHAR;
country*: ARRAY 16 OF CHAR;
customer*: INTEGER;
update*: BOOLEAN
END;
PROCEDURE OpenText*;
BEGIN
END OpenText;
END ObxAddress0.
Скомпилируйте этот файл, затем выполните Новая форма... в меню Диалоги. Откроется диалог. Затем напишите "ObxAddress0" в поле Связать с после чего щелкните кнопку ОК. Будет открыто новое окно с формой. Эту форму можно редактировать, например, двигая поле update немного вправо. (Заметьте, что тем самым вы изменяете документ, следовательно, вас спросят о сохранении изменений, когда вы попробуете закрыть окно. Не сохраняйте изменений.)
Теперь запустите Диалоговое управление модулем в меню Диалоги. В результате вы получите полностью фнкционирующий диалог с текущей компоновкой формы. Эта маска может быть использована немедленно, т.е., когда вы отмечаете окно Update, переменная ObxAddress0.adr.update будет переключена/изменена!
Если у вас несколько отображений, связанных с одной и той же переменной (например, в шаблоне и действующем окне диалога), все они будут отображать изменения, которые производит пользователь.
Элементы управления формы связаны с программными переменными очень просто, так же как текстовое представление связано с его текстовой моделью. И текстовое отображение, и элемент управления являются реализациями интерфейса Views.View. Контейнер упомянутых выше средств управления - суть отображение формы, которое в свою очередь также является реализацией типа Views.View. Отображения-формы, как и текстовые отображения, являются примерами отображений-контейнеров: отображение-контейнер может содержать встроенные части (например, куски текста), впрочем, как и любые другие отображения. Отображение-формы вырождены в том смысле, что они не имеют встроенных данных; они могут содержать лишь другие отображения.
Вместо того, чтобы начать с объявления записи в вышеприведённом примере, вы можете предпочесть начать с интерактивного создания диалога, и только после этого вернуться к аспектам программирования. Это вполне возможно: кликните на кнопку Пустой (Диалоги->Новая форма) для создания новой пустой формы. Она откроется в новом окне, и появится меню Разметка. Используя команды меню Диалоги, можно добавлять новые элементы управления в форму. Форму можно сохранить в файле, а её элементы управления могут быть позже связаны с программными переменными при помощи инструмента под названием Редактор свойств элементов (смотрите описание меню Правка в Руководстве пользователя).
Блэкбокс поддерживает только немодальные формы, используемые как маски ввода данных либо как диалоги. Модальные формы вынудили бы пользователя завершить некоторое действие перед тем как сделать что-либо ещё, например, просмотреть дополнительную информацию об этом действии. Блэкбокс следует той философии, в которой управляет пользователь, а не компьютер.
В данном примере мы увидели, как использовать формы, как с точки зрения программиста, так и с точки зрения дизайнера пользовательского интерфейса. Более того, мы увидели, как может автоматически генерироваться начальная компоновка формы; как форма может быть отображена (даже одновременно) и как редактируемый прототип, и как действующее окно диалога; и как элемент управления, как и любое другое отображение, может жить в отображении-контейнере, а не только в отображении-форме.
Текст перевёл Адаменко Оскар. гр. 08-302
Возможно, начинающему программисту будет более понятен несколько измененный (А.И.Попков) вариант примера:
MODULE ObxАдрес0;
IMPORT StdLog;
VAR
адрес*: RECORD
фамилия*: ARRAY 64 OF CHAR;
город*: ARRAY 24 OF CHAR;
страна*: ARRAY 16 OF CHAR;
заказчик*: INTEGER;
обновить*: BOOLEAN
END;
PROCEDURE ОткрытьТекст*;
BEGIN
StdLog.String(адрес.фамилия); StdLog.Ln;
StdLog.String(адрес.город); StdLog.Ln;
StdLog.String(адрес.страна); StdLog.Ln;
StdLog.Int(адрес.заказчик); StdLog.Ln;
StdLog.Bool(адрес.обновить); StdLog.Ln;
END ОткрытьТекст;
END ObxАдрес0.
| Obx/Docu/ru/Address0.odc |